diff --git a/.bundle/config b/.bundle/config new file mode 100644 index 0000000..2369228 --- /dev/null +++ b/.bundle/config @@ -0,0 +1,2 @@ +--- +BUNDLE_PATH: "vendor/bundle" diff --git a/.gitignore b/.gitignore index 9dcfe1a..5e857c0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ src/db/ -src/vendor/ +vendor/ src/public/auctions/ +/.yardoc/ +/_yardoc/ +/doc/ +/rdoc/ diff --git a/.yardopts b/.yardopts new file mode 100644 index 0000000..3dbe9ec --- /dev/null +++ b/.yardopts @@ -0,0 +1 @@ +src/**/*.rb --plugin yard-sinatra diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..9945b16 --- /dev/null +++ b/Gemfile @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +git_source(:github) { |repo_name| "https://github.com/#{repo_name}" } + +# gem "rails" + +gem "sinatra" +gem "sinatra-reloader" +gem "sqlite3" +gem "slim" +gem "sassc" +gem "colorize" +gem "bcrypt" + +gem "rmagick", "~> 4.2" + +gem "sinatra-flash", "~> 0.3.0" + +gem "fileutils", "~> 1.6" + +gem "webrick", "~> 1.7" + +gem "yard-sinatra", github: "chrisb/yard-sinatra" + +gem "yard", "~> 0.9.27" + +gem "rdoc", "~> 6.4" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..26db89a --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,87 @@ +GIT + remote: https://github.com/chrisb/yard-sinatra + revision: 226e048f615bdf068e65010d47f8cb143fd08865 + specs: + yard-sinatra (2.0.0.beta) + activesupport + yard (~> 0.7) + +GEM + remote: https://rubygems.org/ + specs: + activesupport (7.0.2.3) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + bcrypt (3.1.17) + colorize (0.8.1) + concurrent-ruby (1.1.10) + ffi (1.15.5) + fileutils (1.6.0) + i18n (1.10.0) + concurrent-ruby (~> 1.0) + minitest (5.15.0) + multi_json (1.15.0) + mustermann (1.1.1) + ruby2_keywords (~> 0.0.1) + psych (4.0.3) + stringio + rack (2.2.3) + rack-protection (2.2.0) + rack + rdoc (6.4.0) + psych (>= 4.0.0) + rmagick (4.2.5) + ruby2_keywords (0.0.5) + sassc (2.4.0) + ffi (~> 1.9) + sinatra (2.2.0) + mustermann (~> 1.0) + rack (~> 2.2) + rack-protection (= 2.2.0) + tilt (~> 2.0) + sinatra-contrib (2.2.0) + multi_json + mustermann (~> 1.0) + rack-protection (= 2.2.0) + sinatra (= 2.2.0) + tilt (~> 2.0) + sinatra-flash (0.3.0) + sinatra (>= 1.0.0) + sinatra-reloader (1.0) + sinatra-contrib + slim (4.1.0) + temple (>= 0.7.6, < 0.9) + tilt (>= 2.0.6, < 2.1) + sqlite3 (1.4.2) + stringio (3.0.1) + temple (0.8.2) + tilt (2.0.10) + tzinfo (2.0.4) + concurrent-ruby (~> 1.0) + webrick (1.7.0) + yard (0.9.27) + webrick (~> 1.7.0) + +PLATFORMS + x86_64-linux + +DEPENDENCIES + bcrypt + colorize + fileutils (~> 1.6) + rdoc (~> 6.4) + rmagick (~> 4.2) + sassc + sinatra + sinatra-flash (~> 0.3.0) + sinatra-reloader + slim + sqlite3 + webrick (~> 1.7) + yard (~> 0.9.27) + yard-sinatra! + +BUNDLED WITH + 2.3.10 diff --git a/vendor/bundle/ruby/3.0.0/bin/rackup b/vendor/bundle/ruby/3.0.0/bin/rackup new file mode 100755 index 0000000..f415070 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/bin/rackup @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +# +# This file was generated by RubyGems. +# +# The application 'rack' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'rubygems' + +Gem.use_gemdeps + +version = ">= 0.a" + +str = ARGV.first +if str + str = str.b[/\A_(.*)_\z/, 1] + if str and Gem::Version.correct?(str) + version = str + ARGV.shift + end +end + +if Gem.respond_to?(:activate_bin_path) +load Gem.activate_bin_path('rack', 'rackup', version) +else +gem "rack", version +load Gem.bin_path("rack", "rackup", version) +end diff --git a/vendor/bundle/ruby/3.0.0/bin/rdoc b/vendor/bundle/ruby/3.0.0/bin/rdoc new file mode 100755 index 0000000..b8c66ad --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/bin/rdoc @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +# +# This file was generated by RubyGems. +# +# The application 'rdoc' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'rubygems' + +Gem.use_gemdeps + +version = ">= 0.a" + +str = ARGV.first +if str + str = str.b[/\A_(.*)_\z/, 1] + if str and Gem::Version.correct?(str) + version = str + ARGV.shift + end +end + +if Gem.respond_to?(:activate_bin_path) +load Gem.activate_bin_path('rdoc', 'rdoc', version) +else +gem "rdoc", version +load Gem.bin_path("rdoc", "rdoc", version) +end diff --git a/vendor/bundle/ruby/3.0.0/bin/ri b/vendor/bundle/ruby/3.0.0/bin/ri new file mode 100755 index 0000000..c771c66 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/bin/ri @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +# +# This file was generated by RubyGems. +# +# The application 'rdoc' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'rubygems' + +Gem.use_gemdeps + +version = ">= 0.a" + +str = ARGV.first +if str + str = str.b[/\A_(.*)_\z/, 1] + if str and Gem::Version.correct?(str) + version = str + ARGV.shift + end +end + +if Gem.respond_to?(:activate_bin_path) +load Gem.activate_bin_path('rdoc', 'ri', version) +else +gem "rdoc", version +load Gem.bin_path("rdoc", "ri", version) +end diff --git a/vendor/bundle/ruby/3.0.0/bin/slimrb b/vendor/bundle/ruby/3.0.0/bin/slimrb new file mode 100755 index 0000000..69ebf67 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/bin/slimrb @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +# +# This file was generated by RubyGems. +# +# The application 'slim' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'rubygems' + +Gem.use_gemdeps + +version = ">= 0.a" + +str = ARGV.first +if str + str = str.b[/\A_(.*)_\z/, 1] + if str and Gem::Version.correct?(str) + version = str + ARGV.shift + end +end + +if Gem.respond_to?(:activate_bin_path) +load Gem.activate_bin_path('slim', 'slimrb', version) +else +gem "slim", version +load Gem.bin_path("slim", "slimrb", version) +end diff --git a/vendor/bundle/ruby/3.0.0/bin/tilt b/vendor/bundle/ruby/3.0.0/bin/tilt new file mode 100755 index 0000000..a515d81 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/bin/tilt @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +# +# This file was generated by RubyGems. +# +# The application 'tilt' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'rubygems' + +Gem.use_gemdeps + +version = ">= 0.a" + +str = ARGV.first +if str + str = str.b[/\A_(.*)_\z/, 1] + if str and Gem::Version.correct?(str) + version = str + ARGV.shift + end +end + +if Gem.respond_to?(:activate_bin_path) +load Gem.activate_bin_path('tilt', 'tilt', version) +else +gem "tilt", version +load Gem.bin_path("tilt", "tilt", version) +end diff --git a/vendor/bundle/ruby/3.0.0/bin/yard b/vendor/bundle/ruby/3.0.0/bin/yard new file mode 100755 index 0000000..20f711e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/bin/yard @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +# +# This file was generated by RubyGems. +# +# The application 'yard' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'rubygems' + +Gem.use_gemdeps + +version = ">= 0.a" + +str = ARGV.first +if str + str = str.b[/\A_(.*)_\z/, 1] + if str and Gem::Version.correct?(str) + version = str + ARGV.shift + end +end + +if Gem.respond_to?(:activate_bin_path) +load Gem.activate_bin_path('yard', 'yard', version) +else +gem "yard", version +load Gem.bin_path("yard", "yard", version) +end diff --git a/vendor/bundle/ruby/3.0.0/bin/yardoc b/vendor/bundle/ruby/3.0.0/bin/yardoc new file mode 100755 index 0000000..2429373 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/bin/yardoc @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +# +# This file was generated by RubyGems. +# +# The application 'yard' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'rubygems' + +Gem.use_gemdeps + +version = ">= 0.a" + +str = ARGV.first +if str + str = str.b[/\A_(.*)_\z/, 1] + if str and Gem::Version.correct?(str) + version = str + ARGV.shift + end +end + +if Gem.respond_to?(:activate_bin_path) +load Gem.activate_bin_path('yard', 'yardoc', version) +else +gem "yard", version +load Gem.bin_path("yard", "yardoc", version) +end diff --git a/vendor/bundle/ruby/3.0.0/bin/yri b/vendor/bundle/ruby/3.0.0/bin/yri new file mode 100755 index 0000000..4c3d5ce --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/bin/yri @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +# +# This file was generated by RubyGems. +# +# The application 'yard' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'rubygems' + +Gem.use_gemdeps + +version = ">= 0.a" + +str = ARGV.first +if str + str = str.b[/\A_(.*)_\z/, 1] + if str and Gem::Version.correct?(str) + version = str + ARGV.shift + end +end + +if Gem.respond_to?(:activate_bin_path) +load Gem.activate_bin_path('yard', 'yri', version) +else +gem "yard", version +load Gem.bin_path("yard", "yri", version) +end diff --git a/vendor/bundle/ruby/3.0.0/bundler/gems/yard-sinatra-226e048f615b b/vendor/bundle/ruby/3.0.0/bundler/gems/yard-sinatra-226e048f615b new file mode 160000 index 0000000..226e048 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/bundler/gems/yard-sinatra-226e048f615b @@ -0,0 +1 @@ +Subproject commit 226e048f615bdf068e65010d47f8cb143fd08865 diff --git a/vendor/bundle/ruby/3.0.0/cache/activesupport-7.0.2.3.gem b/vendor/bundle/ruby/3.0.0/cache/activesupport-7.0.2.3.gem new file mode 100644 index 0000000..2e69755 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/activesupport-7.0.2.3.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/bcrypt-3.1.17.gem b/vendor/bundle/ruby/3.0.0/cache/bcrypt-3.1.17.gem new file mode 100644 index 0000000..6713f46 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/bcrypt-3.1.17.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/FETCH_HEAD b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/FETCH_HEAD new file mode 100644 index 0000000..8adaa4b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/FETCH_HEAD @@ -0,0 +1,8 @@ +226e048f615bdf068e65010d47f8cb143fd08865 branch 'master' of https://github.com/chrisb/yard-sinatra +226e048f615bdf068e65010d47f8cb143fd08865 branch 'swagger-2' of https://github.com/chrisb/yard-sinatra +2fae74f3302c8a6a0563f88bbc37a0e2da7a654e branch 'work' of https://github.com/chrisb/yard-sinatra +f5ca95436ba9db78f47e37c04dfca921285f911e not-for-merge tag 'v0.4.0' of https://github.com/chrisb/yard-sinatra +b81262e2cc9f051650c6f0fc9889a8f8e9a1ab21 not-for-merge tag 'v0.4.0.1' of https://github.com/chrisb/yard-sinatra +f9152938e4b85f4011420903bd986d516a8c5771 not-for-merge tag 'v0.5.0' of https://github.com/chrisb/yard-sinatra +8e7a96bced01378f5d5d47ebe7a5f5403a324d52 not-for-merge tag 'v0.5.1' of https://github.com/chrisb/yard-sinatra +a730ffa306d1709ba9b551c1056622e54e50d7e7 not-for-merge tag 'v1.0.0' of https://github.com/chrisb/yard-sinatra diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/HEAD b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/HEAD new file mode 100644 index 0000000..cb089cd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/HEAD @@ -0,0 +1 @@ +ref: refs/heads/master diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/config b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/config new file mode 100644 index 0000000..01b3b14 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/config @@ -0,0 +1,6 @@ +[core] + repositoryformatversion = 0 + filemode = true + bare = true +[remote "origin"] + url = https://github.com/chrisb/yard-sinatra diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/description b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/description new file mode 100644 index 0000000..498b267 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/description @@ -0,0 +1 @@ +Unnamed repository; edit this file 'description' to name the repository. diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/applypatch-msg.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/applypatch-msg.sample new file mode 100755 index 0000000..a5d7b84 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/applypatch-msg.sample @@ -0,0 +1,15 @@ +#!/bin/sh +# +# An example hook script to check the commit log message taken by +# applypatch from an e-mail message. +# +# The hook should exit with non-zero status after issuing an +# appropriate message if it wants to stop the commit. The hook is +# allowed to edit the commit message file. +# +# To enable this hook, rename this file to "applypatch-msg". + +. git-sh-setup +commitmsg="$(git rev-parse --git-path hooks/commit-msg)" +test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"} +: diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/commit-msg.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/commit-msg.sample new file mode 100755 index 0000000..b58d118 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/commit-msg.sample @@ -0,0 +1,24 @@ +#!/bin/sh +# +# An example hook script to check the commit log message. +# Called by "git commit" with one argument, the name of the file +# that has the commit message. The hook should exit with non-zero +# status after issuing an appropriate message if it wants to stop the +# commit. The hook is allowed to edit the commit message file. +# +# To enable this hook, rename this file to "commit-msg". + +# Uncomment the below to add a Signed-off-by line to the message. +# Doing this in a hook is a bad idea in general, but the prepare-commit-msg +# hook is more suited to it. +# +# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') +# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" + +# This example catches duplicate Signed-off-by lines. + +test "" = "$(grep '^Signed-off-by: ' "$1" | + sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { + echo >&2 Duplicate Signed-off-by lines. + exit 1 +} diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/fsmonitor-watchman.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/fsmonitor-watchman.sample new file mode 100755 index 0000000..14ed0aa --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/fsmonitor-watchman.sample @@ -0,0 +1,173 @@ +#!/usr/bin/perl + +use strict; +use warnings; +use IPC::Open2; + +# An example hook script to integrate Watchman +# (https://facebook.github.io/watchman/) with git to speed up detecting +# new and modified files. +# +# The hook is passed a version (currently 2) and last update token +# formatted as a string and outputs to stdout a new update token and +# all files that have been modified since the update token. Paths must +# be relative to the root of the working tree and separated by a single NUL. +# +# To enable this hook, rename this file to "query-watchman" and set +# 'git config core.fsmonitor .git/hooks/query-watchman' +# +my ($version, $last_update_token) = @ARGV; + +# Uncomment for debugging +# print STDERR "$0 $version $last_update_token\n"; + +# Check the hook interface version +if ($version ne 2) { + die "Unsupported query-fsmonitor hook version '$version'.\n" . + "Falling back to scanning...\n"; +} + +my $git_work_tree = get_working_dir(); + +my $retry = 1; + +my $json_pkg; +eval { + require JSON::XS; + $json_pkg = "JSON::XS"; + 1; +} or do { + require JSON::PP; + $json_pkg = "JSON::PP"; +}; + +launch_watchman(); + +sub launch_watchman { + my $o = watchman_query(); + if (is_work_tree_watched($o)) { + output_result($o->{clock}, @{$o->{files}}); + } +} + +sub output_result { + my ($clockid, @files) = @_; + + # Uncomment for debugging watchman output + # open (my $fh, ">", ".git/watchman-output.out"); + # binmode $fh, ":utf8"; + # print $fh "$clockid\n@files\n"; + # close $fh; + + binmode STDOUT, ":utf8"; + print $clockid; + print "\0"; + local $, = "\0"; + print @files; +} + +sub watchman_clock { + my $response = qx/watchman clock "$git_work_tree"/; + die "Failed to get clock id on '$git_work_tree'.\n" . + "Falling back to scanning...\n" if $? != 0; + + return $json_pkg->new->utf8->decode($response); +} + +sub watchman_query { + my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty') + or die "open2() failed: $!\n" . + "Falling back to scanning...\n"; + + # In the query expression below we're asking for names of files that + # changed since $last_update_token but not from the .git folder. + # + # To accomplish this, we're using the "since" generator to use the + # recency index to select candidate nodes and "fields" to limit the + # output to file names only. Then we're using the "expression" term to + # further constrain the results. + if (substr($last_update_token, 0, 1) eq "c") { + $last_update_token = "\"$last_update_token\""; + } + my $query = <<" END"; + ["query", "$git_work_tree", { + "since": $last_update_token, + "fields": ["name"], + "expression": ["not", ["dirname", ".git"]] + }] + END + + # Uncomment for debugging the watchman query + # open (my $fh, ">", ".git/watchman-query.json"); + # print $fh $query; + # close $fh; + + print CHLD_IN $query; + close CHLD_IN; + my $response = do {local $/; }; + + # Uncomment for debugging the watch response + # open ($fh, ">", ".git/watchman-response.json"); + # print $fh $response; + # close $fh; + + die "Watchman: command returned no output.\n" . + "Falling back to scanning...\n" if $response eq ""; + die "Watchman: command returned invalid output: $response\n" . + "Falling back to scanning...\n" unless $response =~ /^\{/; + + return $json_pkg->new->utf8->decode($response); +} + +sub is_work_tree_watched { + my ($output) = @_; + my $error = $output->{error}; + if ($retry > 0 and $error and $error =~ m/unable to resolve root .* directory (.*) is not watched/) { + $retry--; + my $response = qx/watchman watch "$git_work_tree"/; + die "Failed to make watchman watch '$git_work_tree'.\n" . + "Falling back to scanning...\n" if $? != 0; + $output = $json_pkg->new->utf8->decode($response); + $error = $output->{error}; + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + # Uncomment for debugging watchman output + # open (my $fh, ">", ".git/watchman-output.out"); + # close $fh; + + # Watchman will always return all files on the first query so + # return the fast "everything is dirty" flag to git and do the + # Watchman query just to get it over with now so we won't pay + # the cost in git to look up each individual file. + my $o = watchman_clock(); + $error = $output->{error}; + + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + output_result($o->{clock}, ("/")); + $last_update_token = $o->{clock}; + + eval { launch_watchman() }; + return 0; + } + + die "Watchman: $error.\n" . + "Falling back to scanning...\n" if $error; + + return 1; +} + +sub get_working_dir { + my $working_dir; + if ($^O =~ 'msys' || $^O =~ 'cygwin') { + $working_dir = Win32::GetCwd(); + $working_dir =~ tr/\\/\//; + } else { + require Cwd; + $working_dir = Cwd::cwd(); + } + + return $working_dir; +} diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/post-update.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/post-update.sample new file mode 100755 index 0000000..ec17ec1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/post-update.sample @@ -0,0 +1,8 @@ +#!/bin/sh +# +# An example hook script to prepare a packed repository for use over +# dumb transports. +# +# To enable this hook, rename this file to "post-update". + +exec git update-server-info diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-applypatch.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-applypatch.sample new file mode 100755 index 0000000..4142082 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-applypatch.sample @@ -0,0 +1,14 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed +# by applypatch from an e-mail message. +# +# The hook should exit with non-zero status after issuing an +# appropriate message if it wants to stop the commit. +# +# To enable this hook, rename this file to "pre-applypatch". + +. git-sh-setup +precommit="$(git rev-parse --git-path hooks/pre-commit)" +test -x "$precommit" && exec "$precommit" ${1+"$@"} +: diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-commit.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-commit.sample new file mode 100755 index 0000000..e144712 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-commit.sample @@ -0,0 +1,49 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed. +# Called by "git commit" with no arguments. The hook should +# exit with non-zero status after issuing an appropriate message if +# it wants to stop the commit. +# +# To enable this hook, rename this file to "pre-commit". + +if git rev-parse --verify HEAD >/dev/null 2>&1 +then + against=HEAD +else + # Initial commit: diff against an empty tree object + against=$(git hash-object -t tree /dev/null) +fi + +# If you want to allow non-ASCII filenames set this variable to true. +allownonascii=$(git config --type=bool hooks.allownonascii) + +# Redirect output to stderr. +exec 1>&2 + +# Cross platform projects tend to avoid non-ASCII filenames; prevent +# them from being added to the repository. We exploit the fact that the +# printable range starts at the space character and ends with tilde. +if [ "$allownonascii" != "true" ] && + # Note that the use of brackets around a tr range is ok here, (it's + # even required, for portability to Solaris 10's /usr/bin/tr), since + # the square bracket bytes happen to fall in the designated range. + test $(git diff --cached --name-only --diff-filter=A -z $against | + LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 +then + cat <<\EOF +Error: Attempt to add a non-ASCII file name. + +This can cause problems if you want to work with people on other platforms. + +To be portable it is advisable to rename the file. + +If you know what you are doing you can disable this check using: + + git config hooks.allownonascii true +EOF + exit 1 +fi + +# If there are whitespace errors, print the offending file names and fail. +exec git diff-index --check --cached $against -- diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-merge-commit.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-merge-commit.sample new file mode 100755 index 0000000..399eab1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-merge-commit.sample @@ -0,0 +1,13 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed. +# Called by "git merge" with no arguments. The hook should +# exit with non-zero status after issuing an appropriate message to +# stderr if it wants to stop the merge commit. +# +# To enable this hook, rename this file to "pre-merge-commit". + +. git-sh-setup +test -x "$GIT_DIR/hooks/pre-commit" && + exec "$GIT_DIR/hooks/pre-commit" +: diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-push.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-push.sample new file mode 100755 index 0000000..4ce688d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-push.sample @@ -0,0 +1,53 @@ +#!/bin/sh + +# An example hook script to verify what is about to be pushed. Called by "git +# push" after it has checked the remote status, but before anything has been +# pushed. If this script exits with a non-zero status nothing will be pushed. +# +# This hook is called with the following parameters: +# +# $1 -- Name of the remote to which the push is being done +# $2 -- URL to which the push is being done +# +# If pushing without using a named remote those arguments will be equal. +# +# Information about the commits which are being pushed is supplied as lines to +# the standard input in the form: +# +# +# +# This sample shows how to prevent push of commits where the log message starts +# with "WIP" (work in progress). + +remote="$1" +url="$2" + +zero=$(git hash-object --stdin &2 "Found WIP commit in $local_ref, not pushing" + exit 1 + fi + fi +done + +exit 0 diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-rebase.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-rebase.sample new file mode 100755 index 0000000..6cbef5c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-rebase.sample @@ -0,0 +1,169 @@ +#!/bin/sh +# +# Copyright (c) 2006, 2008 Junio C Hamano +# +# The "pre-rebase" hook is run just before "git rebase" starts doing +# its job, and can prevent the command from running by exiting with +# non-zero status. +# +# The hook is called with the following parameters: +# +# $1 -- the upstream the series was forked from. +# $2 -- the branch being rebased (or empty when rebasing the current branch). +# +# This sample shows how to prevent topic branches that are already +# merged to 'next' branch from getting rebased, because allowing it +# would result in rebasing already published history. + +publish=next +basebranch="$1" +if test "$#" = 2 +then + topic="refs/heads/$2" +else + topic=`git symbolic-ref HEAD` || + exit 0 ;# we do not interrupt rebasing detached HEAD +fi + +case "$topic" in +refs/heads/??/*) + ;; +*) + exit 0 ;# we do not interrupt others. + ;; +esac + +# Now we are dealing with a topic branch being rebased +# on top of master. Is it OK to rebase it? + +# Does the topic really exist? +git show-ref -q "$topic" || { + echo >&2 "No such branch $topic" + exit 1 +} + +# Is topic fully merged to master? +not_in_master=`git rev-list --pretty=oneline ^master "$topic"` +if test -z "$not_in_master" +then + echo >&2 "$topic is fully merged to master; better remove it." + exit 1 ;# we could allow it, but there is no point. +fi + +# Is topic ever merged to next? If so you should not be rebasing it. +only_next_1=`git rev-list ^master "^$topic" ${publish} | sort` +only_next_2=`git rev-list ^master ${publish} | sort` +if test "$only_next_1" = "$only_next_2" +then + not_in_topic=`git rev-list "^$topic" master` + if test -z "$not_in_topic" + then + echo >&2 "$topic is already up to date with master" + exit 1 ;# we could allow it, but there is no point. + else + exit 0 + fi +else + not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"` + /usr/bin/perl -e ' + my $topic = $ARGV[0]; + my $msg = "* $topic has commits already merged to public branch:\n"; + my (%not_in_next) = map { + /^([0-9a-f]+) /; + ($1 => 1); + } split(/\n/, $ARGV[1]); + for my $elem (map { + /^([0-9a-f]+) (.*)$/; + [$1 => $2]; + } split(/\n/, $ARGV[2])) { + if (!exists $not_in_next{$elem->[0]}) { + if ($msg) { + print STDERR $msg; + undef $msg; + } + print STDERR " $elem->[1]\n"; + } + } + ' "$topic" "$not_in_next" "$not_in_master" + exit 1 +fi + +<<\DOC_END + +This sample hook safeguards topic branches that have been +published from being rewound. + +The workflow assumed here is: + + * Once a topic branch forks from "master", "master" is never + merged into it again (either directly or indirectly). + + * Once a topic branch is fully cooked and merged into "master", + it is deleted. If you need to build on top of it to correct + earlier mistakes, a new topic branch is created by forking at + the tip of the "master". This is not strictly necessary, but + it makes it easier to keep your history simple. + + * Whenever you need to test or publish your changes to topic + branches, merge them into "next" branch. + +The script, being an example, hardcodes the publish branch name +to be "next", but it is trivial to make it configurable via +$GIT_DIR/config mechanism. + +With this workflow, you would want to know: + +(1) ... if a topic branch has ever been merged to "next". Young + topic branches can have stupid mistakes you would rather + clean up before publishing, and things that have not been + merged into other branches can be easily rebased without + affecting other people. But once it is published, you would + not want to rewind it. + +(2) ... if a topic branch has been fully merged to "master". + Then you can delete it. More importantly, you should not + build on top of it -- other people may already want to + change things related to the topic as patches against your + "master", so if you need further changes, it is better to + fork the topic (perhaps with the same name) afresh from the + tip of "master". + +Let's look at this example: + + o---o---o---o---o---o---o---o---o---o "next" + / / / / + / a---a---b A / / + / / / / + / / c---c---c---c B / + / / / \ / + / / / b---b C \ / + / / / / \ / + ---o---o---o---o---o---o---o---o---o---o---o "master" + + +A, B and C are topic branches. + + * A has one fix since it was merged up to "next". + + * B has finished. It has been fully merged up to "master" and "next", + and is ready to be deleted. + + * C has not merged to "next" at all. + +We would want to allow C to be rebased, refuse A, and encourage +B to be deleted. + +To compute (1): + + git rev-list ^master ^topic next + git rev-list ^master next + + if these match, topic has not merged in next at all. + +To compute (2): + + git rev-list master..topic + + if this is empty, it is fully merged to "master". + +DOC_END diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-receive.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-receive.sample new file mode 100755 index 0000000..a1fd29e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/pre-receive.sample @@ -0,0 +1,24 @@ +#!/bin/sh +# +# An example hook script to make use of push options. +# The example simply echoes all push options that start with 'echoback=' +# and rejects all pushes when the "reject" push option is used. +# +# To enable this hook, rename this file to "pre-receive". + +if test -n "$GIT_PUSH_OPTION_COUNT" +then + i=0 + while test "$i" -lt "$GIT_PUSH_OPTION_COUNT" + do + eval "value=\$GIT_PUSH_OPTION_$i" + case "$value" in + echoback=*) + echo "echo from the pre-receive-hook: ${value#*=}" >&2 + ;; + reject) + exit 1 + esac + i=$((i + 1)) + done +fi diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/prepare-commit-msg.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/prepare-commit-msg.sample new file mode 100755 index 0000000..10fa14c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/prepare-commit-msg.sample @@ -0,0 +1,42 @@ +#!/bin/sh +# +# An example hook script to prepare the commit log message. +# Called by "git commit" with the name of the file that has the +# commit message, followed by the description of the commit +# message's source. The hook's purpose is to edit the commit +# message file. If the hook fails with a non-zero status, +# the commit is aborted. +# +# To enable this hook, rename this file to "prepare-commit-msg". + +# This hook includes three examples. The first one removes the +# "# Please enter the commit message..." help message. +# +# The second includes the output of "git diff --name-status -r" +# into the message, just before the "git status" output. It is +# commented because it doesn't cope with --amend or with squashed +# commits. +# +# The third example adds a Signed-off-by line to the message, that can +# still be edited. This is rarely a good idea. + +COMMIT_MSG_FILE=$1 +COMMIT_SOURCE=$2 +SHA1=$3 + +/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE" + +# case "$COMMIT_SOURCE,$SHA1" in +# ,|template,) +# /usr/bin/perl -i.bak -pe ' +# print "\n" . `git diff --cached --name-status -r` +# if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;; +# *) ;; +# esac + +# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') +# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE" +# if test -z "$COMMIT_SOURCE" +# then +# /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE" +# fi diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/push-to-checkout.sample b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/push-to-checkout.sample new file mode 100755 index 0000000..af5a0c0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/hooks/push-to-checkout.sample @@ -0,0 +1,78 @@ +#!/bin/sh + +# An example hook script to update a checked-out tree on a git push. +# +# This hook is invoked by git-receive-pack(1) when it reacts to git +# push and updates reference(s) in its repository, and when the push +# tries to update the branch that is currently checked out and the +# receive.denyCurrentBranch configuration variable is set to +# updateInstead. +# +# By default, such a push is refused if the working tree and the index +# of the remote repository has any difference from the currently +# checked out commit; when both the working tree and the index match +# the current commit, they are updated to match the newly pushed tip +# of the branch. This hook is to be used to override the default +# behaviour; however the code below reimplements the default behaviour +# as a starting point for convenient modification. +# +# The hook receives the commit with which the tip of the current +# branch is going to be updated: +commit=$1 + +# It can exit with a non-zero status to refuse the push (when it does +# so, it must not modify the index or the working tree). +die () { + echo >&2 "$*" + exit 1 +} + +# Or it can make any necessary changes to the working tree and to the +# index to bring them to the desired state when the tip of the current +# branch is updated to the new commit, and exit with a zero status. +# +# For example, the hook can simply run git read-tree -u -m HEAD "$1" +# in order to emulate git fetch that is run in the reverse direction +# with git push, as the two-tree form of git read-tree -u -m is +# essentially the same as git switch or git checkout that switches +# branches while keeping the local changes in the working tree that do +# not interfere with the difference between the branches. + +# The below is a more-or-less exact translation to shell of the C code +# for the default behaviour for git's push-to-checkout hook defined in +# the push_to_deploy() function in builtin/receive-pack.c. +# +# Note that the hook will be executed from the repository directory, +# not from the working tree, so if you want to perform operations on +# the working tree, you will have to adapt your code accordingly, e.g. +# by adding "cd .." or using relative paths. + +if ! git update-index -q --ignore-submodules --refresh +then + die "Up-to-date check failed" +fi + +if ! git diff-files --quiet --ignore-submodules -- +then + die "Working directory has unstaged changes" +fi + +# This is a rough translation of: +# +# head_has_history() ? "HEAD" : EMPTY_TREE_SHA1_HEX +if git cat-file -e HEAD 2>/dev/null +then + head=HEAD +else + head=$(git hash-object -t tree --stdin &2 + echo " (if you want, you could supply GIT_DIR then run" >&2 + echo " $0 )" >&2 + exit 1 +fi + +if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then + echo "usage: $0 " >&2 + exit 1 +fi + +# --- Config +allowunannotated=$(git config --type=bool hooks.allowunannotated) +allowdeletebranch=$(git config --type=bool hooks.allowdeletebranch) +denycreatebranch=$(git config --type=bool hooks.denycreatebranch) +allowdeletetag=$(git config --type=bool hooks.allowdeletetag) +allowmodifytag=$(git config --type=bool hooks.allowmodifytag) + +# check for no description +projectdesc=$(sed -e '1q' "$GIT_DIR/description") +case "$projectdesc" in +"Unnamed repository"* | "") + echo "*** Project description file hasn't been set" >&2 + exit 1 + ;; +esac + +# --- Check types +# if $newrev is 0000...0000, it's a commit to delete a ref. +zero=$(git hash-object --stdin &2 + echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2 + exit 1 + fi + ;; + refs/tags/*,delete) + # delete tag + if [ "$allowdeletetag" != "true" ]; then + echo "*** Deleting a tag is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/tags/*,tag) + # annotated tag + if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1 + then + echo "*** Tag '$refname' already exists." >&2 + echo "*** Modifying a tag is not allowed in this repository." >&2 + exit 1 + fi + ;; + refs/heads/*,commit) + # branch + if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then + echo "*** Creating a branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/heads/*,delete) + # delete branch + if [ "$allowdeletebranch" != "true" ]; then + echo "*** Deleting a branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + refs/remotes/*,commit) + # tracking branch + ;; + refs/remotes/*,delete) + # delete tracking branch + if [ "$allowdeletebranch" != "true" ]; then + echo "*** Deleting a tracking branch is not allowed in this repository" >&2 + exit 1 + fi + ;; + *) + # Anything else (is there anything else?) + echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2 + exit 1 + ;; +esac + +# --- Finished +exit 0 diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/info/exclude b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/info/exclude new file mode 100644 index 0000000..a5196d1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/info/exclude @@ -0,0 +1,6 @@ +# git ls-files --others --exclude-from=.git/info/exclude +# Lines that start with '#' are comments. +# For a project mostly in C, the following would be a good set of +# exclude patterns (uncomment them if you want to use them): +# *.[oa] +# *~ diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/objects/pack/pack-6f7928ceb77b18303186b1019d01c30c436c8e99.idx b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/objects/pack/pack-6f7928ceb77b18303186b1019d01c30c436c8e99.idx new file mode 100644 index 0000000..37ed3ce Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/objects/pack/pack-6f7928ceb77b18303186b1019d01c30c436c8e99.idx differ diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/objects/pack/pack-6f7928ceb77b18303186b1019d01c30c436c8e99.pack b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/objects/pack/pack-6f7928ceb77b18303186b1019d01c30c436c8e99.pack new file mode 100644 index 0000000..6db6823 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/objects/pack/pack-6f7928ceb77b18303186b1019d01c30c436c8e99.pack differ diff --git a/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/packed-refs b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/packed-refs new file mode 100644 index 0000000..d4995ff --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/cache/bundler/git/yard-sinatra-049e4f05dae93323a04e43ed000c9c3dcb91f6b7/packed-refs @@ -0,0 +1,14 @@ +# pack-refs with: peeled fully-peeled sorted +226e048f615bdf068e65010d47f8cb143fd08865 refs/heads/master +226e048f615bdf068e65010d47f8cb143fd08865 refs/heads/swagger-2 +2fae74f3302c8a6a0563f88bbc37a0e2da7a654e refs/heads/work +f5ca95436ba9db78f47e37c04dfca921285f911e refs/tags/v0.4.0 +^fe5f8854a0d7318d04a103a16572b7e5b33d406d +b81262e2cc9f051650c6f0fc9889a8f8e9a1ab21 refs/tags/v0.4.0.1 +^87a0398bd8f903cdaf63d900d993fdb772c51291 +f9152938e4b85f4011420903bd986d516a8c5771 refs/tags/v0.5.0 +^b4f554c281601e483bf2cca28a232959fd2331c0 +8e7a96bced01378f5d5d47ebe7a5f5403a324d52 refs/tags/v0.5.1 +^8170a1052e29f24e2d811632f656c8e97dea69ae +a730ffa306d1709ba9b551c1056622e54e50d7e7 refs/tags/v1.0.0 +^45678cd123e829fdff6574067cd3e5852942b084 diff --git a/vendor/bundle/ruby/3.0.0/cache/colorize-0.8.1.gem b/vendor/bundle/ruby/3.0.0/cache/colorize-0.8.1.gem new file mode 100644 index 0000000..bf9849c Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/colorize-0.8.1.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/concurrent-ruby-1.1.10.gem b/vendor/bundle/ruby/3.0.0/cache/concurrent-ruby-1.1.10.gem new file mode 100644 index 0000000..c796701 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/concurrent-ruby-1.1.10.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/ffi-1.15.5.gem b/vendor/bundle/ruby/3.0.0/cache/ffi-1.15.5.gem new file mode 100644 index 0000000..a632047 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/ffi-1.15.5.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/fileutils-1.6.0.gem b/vendor/bundle/ruby/3.0.0/cache/fileutils-1.6.0.gem new file mode 100644 index 0000000..bd9f078 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/fileutils-1.6.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/i18n-1.10.0.gem b/vendor/bundle/ruby/3.0.0/cache/i18n-1.10.0.gem new file mode 100644 index 0000000..a64602b Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/i18n-1.10.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/minitest-5.15.0.gem b/vendor/bundle/ruby/3.0.0/cache/minitest-5.15.0.gem new file mode 100644 index 0000000..bb3c247 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/minitest-5.15.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/multi_json-1.15.0.gem b/vendor/bundle/ruby/3.0.0/cache/multi_json-1.15.0.gem new file mode 100644 index 0000000..8348d7b Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/multi_json-1.15.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/mustermann-1.1.1.gem b/vendor/bundle/ruby/3.0.0/cache/mustermann-1.1.1.gem new file mode 100644 index 0000000..5501866 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/mustermann-1.1.1.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/psych-4.0.3.gem b/vendor/bundle/ruby/3.0.0/cache/psych-4.0.3.gem new file mode 100644 index 0000000..1ef7edc Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/psych-4.0.3.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/rack-2.2.3.gem b/vendor/bundle/ruby/3.0.0/cache/rack-2.2.3.gem new file mode 100644 index 0000000..19fa2e9 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/rack-2.2.3.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/rack-protection-2.2.0.gem b/vendor/bundle/ruby/3.0.0/cache/rack-protection-2.2.0.gem new file mode 100644 index 0000000..1e2d08f Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/rack-protection-2.2.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/rdoc-6.4.0.gem b/vendor/bundle/ruby/3.0.0/cache/rdoc-6.4.0.gem new file mode 100644 index 0000000..ce0372c Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/rdoc-6.4.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/rmagick-4.2.5.gem b/vendor/bundle/ruby/3.0.0/cache/rmagick-4.2.5.gem new file mode 100644 index 0000000..5883088 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/rmagick-4.2.5.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/ruby2_keywords-0.0.5.gem b/vendor/bundle/ruby/3.0.0/cache/ruby2_keywords-0.0.5.gem new file mode 100644 index 0000000..d311c5d Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/ruby2_keywords-0.0.5.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/sassc-2.4.0.gem b/vendor/bundle/ruby/3.0.0/cache/sassc-2.4.0.gem new file mode 100644 index 0000000..a8e2e1f Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/sassc-2.4.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/sinatra-2.2.0.gem b/vendor/bundle/ruby/3.0.0/cache/sinatra-2.2.0.gem new file mode 100644 index 0000000..4114652 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/sinatra-2.2.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/sinatra-contrib-2.2.0.gem b/vendor/bundle/ruby/3.0.0/cache/sinatra-contrib-2.2.0.gem new file mode 100644 index 0000000..62044a4 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/sinatra-contrib-2.2.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/sinatra-flash-0.3.0.gem b/vendor/bundle/ruby/3.0.0/cache/sinatra-flash-0.3.0.gem new file mode 100644 index 0000000..e3f237a Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/sinatra-flash-0.3.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/sinatra-reloader-1.0.gem b/vendor/bundle/ruby/3.0.0/cache/sinatra-reloader-1.0.gem new file mode 100644 index 0000000..a8ff8a4 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/sinatra-reloader-1.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/slim-4.1.0.gem b/vendor/bundle/ruby/3.0.0/cache/slim-4.1.0.gem new file mode 100644 index 0000000..ca6e6c2 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/slim-4.1.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/sqlite3-1.4.2.gem b/vendor/bundle/ruby/3.0.0/cache/sqlite3-1.4.2.gem new file mode 100644 index 0000000..e5df998 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/sqlite3-1.4.2.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/temple-0.8.2.gem b/vendor/bundle/ruby/3.0.0/cache/temple-0.8.2.gem new file mode 100644 index 0000000..85f7205 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/temple-0.8.2.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/tilt-2.0.10.gem b/vendor/bundle/ruby/3.0.0/cache/tilt-2.0.10.gem new file mode 100644 index 0000000..b432e15 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/tilt-2.0.10.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/tzinfo-2.0.4.gem b/vendor/bundle/ruby/3.0.0/cache/tzinfo-2.0.4.gem new file mode 100644 index 0000000..a3f9820 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/tzinfo-2.0.4.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/webrick-1.7.0.gem b/vendor/bundle/ruby/3.0.0/cache/webrick-1.7.0.gem new file mode 100644 index 0000000..127b836 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/webrick-1.7.0.gem differ diff --git a/vendor/bundle/ruby/3.0.0/cache/yard-0.9.27.gem b/vendor/bundle/ruby/3.0.0/cache/yard-0.9.27.gem new file mode 100644 index 0000000..9e9bff1 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/cache/yard-0.9.27.gem differ diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/bcrypt-3.1.17/bcrypt_ext.so b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/bcrypt-3.1.17/bcrypt_ext.so new file mode 100755 index 0000000..a3bc64a Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/bcrypt-3.1.17/bcrypt_ext.so differ diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/bcrypt-3.1.17/gem.build_complete b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/bcrypt-3.1.17/gem.build_complete new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/bcrypt-3.1.17/gem_make.out b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/bcrypt-3.1.17/gem_make.out new file mode 100644 index 0000000..0b0ddcd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/bcrypt-3.1.17/gem_make.out @@ -0,0 +1,22 @@ +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri +/usr/bin/ruby -I /usr/lib/ruby/3.0.0 -r ./siteconf20220424-672384-r0s1w5.rb extconf.rb +creating Makefile + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri +make DESTDIR\= clean + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri +make DESTDIR\= +compiling bcrypt_ext.c +compiling crypt_blowfish.c +gcc -D__SKIP_GNU -c -o x86.o x86.S +compiling crypt_gensalt.c +compiling wrapper.c +wrapper.c:182:60: warning: ‘struct crypt_data’ declared inside parameter list will not be visible outside of this definition or declaration + 182 | char *crypt_r(const char *key, const char *setting, struct crypt_data *data) + | ^~~~~~~~~~ +linking shared-object bcrypt_ext.so + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri +make DESTDIR\= install +/usr/bin/install -c -m 0755 bcrypt_ext.so ./.gem.20220424-672384-aslyfc diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/ffi-1.15.5/ffi_c.so b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/ffi-1.15.5/ffi_c.so new file mode 100755 index 0000000..196f6ad Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/ffi-1.15.5/ffi_c.so differ diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/ffi-1.15.5/gem.build_complete b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/ffi-1.15.5/gem.build_complete new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/ffi-1.15.5/gem_make.out b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/ffi-1.15.5/gem_make.out new file mode 100644 index 0000000..ba6a7e0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/ffi-1.15.5/gem_make.out @@ -0,0 +1,43 @@ +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c +/usr/bin/ruby -I /usr/lib/ruby/3.0.0 -r ./siteconf20220424-672384-j636kg.rb extconf.rb +checking for ffi_prep_closure_loc() in -lffi... yes +checking for ffi_prep_cif_var()... yes +checking for ffi_raw_call()... yes +checking for ffi_prep_raw_closure()... yes +checking for whether -pthread is accepted as LDFLAGS... yes +creating extconf.h +creating Makefile + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c +make DESTDIR\= clean + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c +make DESTDIR\= +compiling AbstractMemory.c +compiling ArrayType.c +compiling Buffer.c +compiling Call.c +compiling ClosurePool.c +compiling DynamicLibrary.c +compiling Function.c +compiling FunctionInfo.c +compiling LastError.c +compiling LongDouble.c +compiling MappedType.c +compiling MemoryPointer.c +compiling MethodHandle.c +compiling Platform.c +compiling Pointer.c +compiling Struct.c +compiling StructByValue.c +compiling StructLayout.c +compiling Thread.c +compiling Type.c +compiling Types.c +compiling Variadic.c +compiling ffi.c +linking shared-object ffi_c.so + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c +make DESTDIR\= install +/usr/bin/install -c -m 0755 ffi_c.so ./.gem.20220424-672384-3l4xqm diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/ffi-1.15.5/mkmf.log b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/ffi-1.15.5/mkmf.log new file mode 100644 index 0000000..e9f67c3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/ffi-1.15.5/mkmf.log @@ -0,0 +1,232 @@ +"pkg-config --exists libffi" +| pkg-config --libs libffi +=> "-lffi \n" +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lruby -lm -lc" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: int main(int argc, char **argv) +4: { +5: return !!argv[argc]; +6: } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lruby -lffi -lm -lc" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: int main(int argc, char **argv) +4: { +5: return !!argv[argc]; +6: } +/* end */ + +| pkg-config --cflags-only-I libffi +=> "\n" +| pkg-config --cflags-only-other libffi +=> "\n" +| pkg-config --libs-only-l libffi +=> "-lffi \n" +package configuration for libffi +incflags: +cflags: +ldflags: +libs: -lffi + +have_library: checking for ffi_prep_closure_loc() in -lffi... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lffi -lruby -lffi -lffi -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: + 5: /*top*/ + 6: extern int t(void); + 7: int main(int argc, char **argv) + 8: { + 9: if (argc > 1000000) { +10: int (* volatile tp)(void)=(int (*)(void))&t; +11: printf("%d", (*tp)()); +12: } +13: +14: return !!argv[argc]; +15: } +16: int t(void) { void ((*volatile p)()); p = (void ((*)()))ffi_prep_closure_loc; return !p; } +/* end */ + +-------------------- + +have_func: checking for ffi_prep_cif_var()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lffi -lffi -lruby -lffi -lffi -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘ffi_prep_cif_var’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))ffi_prep_cif_var; return !p; } + | ^~~~~~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))ffi_prep_cif_var; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lffi -lffi -lruby -lffi -lffi -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void ffi_prep_cif_var(); +15: int t(void) { ffi_prep_cif_var(); return 0; } +/* end */ + +-------------------- + +have_func: checking for ffi_raw_call()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lffi -lffi -lruby -lffi -lffi -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘ffi_raw_call’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))ffi_raw_call; return !p; } + | ^~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))ffi_raw_call; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lffi -lffi -lruby -lffi -lffi -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void ffi_raw_call(); +15: int t(void) { ffi_raw_call(); return 0; } +/* end */ + +-------------------- + +have_func: checking for ffi_prep_raw_closure()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lffi -lffi -lruby -lffi -lffi -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘ffi_prep_raw_closure’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))ffi_prep_raw_closure; return !p; } + | ^~~~~~~~~~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))ffi_prep_raw_closure; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lffi -lffi -lruby -lffi -lffi -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void ffi_prep_raw_closure(); +15: int t(void) { ffi_prep_raw_closure(); return 0; } +/* end */ + +-------------------- + +block in append_ldflags: checking for whether -pthread is accepted as LDFLAGS... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lffi -lffi -lruby -pthread -lm -lc" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: int main(int argc, char **argv) +4: { +5: return !!argv[argc]; +6: } +/* end */ + +-------------------- + +extconf.h is: +/* begin */ +1: #ifndef EXTCONF_H +2: #define EXTCONF_H +3: #define HAVE_FFI_PREP_CIF_VAR 1 +4: #define HAVE_FFI_RAW_CALL 1 +5: #define HAVE_FFI_PREP_RAW_CLOSURE 1 +6: #define HAVE_RAW_API 1 +7: #endif +/* end */ + diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/psych-4.0.3/gem.build_complete b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/psych-4.0.3/gem.build_complete new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/psych-4.0.3/gem_make.out b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/psych-4.0.3/gem_make.out new file mode 100644 index 0000000..84c50f9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/psych-4.0.3/gem_make.out @@ -0,0 +1,21 @@ +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych +/usr/bin/ruby -I /usr/lib/ruby/3.0.0 -r ./siteconf20220424-672384-38ekq0.rb extconf.rb +checking for yaml.h... yes +checking for yaml_get_version() in -lyaml... yes +creating Makefile + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych +make DESTDIR\= clean + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych +make DESTDIR\= +compiling psych.c +compiling psych_emitter.c +compiling psych_parser.c +compiling psych_to_ruby.c +compiling psych_yaml_tree.c +linking shared-object psych.so + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych +make DESTDIR\= install +/usr/bin/install -c -m 0755 psych.so ./.gem.20220424-672384-uh7xmc diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/psych-4.0.3/mkmf.log b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/psych-4.0.3/mkmf.log new file mode 100644 index 0000000..11664ef --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/psych-4.0.3/mkmf.log @@ -0,0 +1,71 @@ +find_header: checking for yaml.h... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lruby -lm -lc" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: int main(int argc, char **argv) +4: { +5: return !!argv[argc]; +6: } +/* end */ + +"gcc -E -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -o conftest.i" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: #include +/* end */ + +-------------------- + +find_library: checking for yaml_get_version() in -lyaml... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lruby -lyaml -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘yaml_get_version’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))yaml_get_version; return !p; } + | ^~~~~~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))yaml_get_version; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lruby -lyaml -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void yaml_get_version(); +15: int t(void) { yaml_get_version(); return 0; } +/* end */ + +-------------------- + diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/psych-4.0.3/psych.so b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/psych-4.0.3/psych.so new file mode 100755 index 0000000..0db4fbd Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/psych-4.0.3/psych.so differ diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/rmagick-4.2.5/RMagick2.so b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/rmagick-4.2.5/RMagick2.so new file mode 100755 index 0000000..2842375 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/rmagick-4.2.5/RMagick2.so differ diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/rmagick-4.2.5/gem.build_complete b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/rmagick-4.2.5/gem.build_complete new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/rmagick-4.2.5/gem_make.out b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/rmagick-4.2.5/gem_make.out new file mode 100644 index 0000000..d7e236a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/rmagick-4.2.5/gem_make.out @@ -0,0 +1,60 @@ +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/rmagick-4.2.5/ext/RMagick +/usr/bin/ruby -I /usr/lib/ruby/3.0.0 -r ./siteconf20220424-672384-vq7axx.rb extconf.rb +checking for brew... no +checking for pacman... yes +checking for Ruby version >= 2.3.0... yes +checking for pkg-config... yes +checking for outdated ImageMagick version (<= 6.7.7)... no +checking for gcc... yes + +Warning: Found a partial ImageMagick installation. Your operating +system likely has some built-in ImageMagick libraries but not all of +ImageMagick. This will most likely cause problems at both compile and +runtime. +Found partial installation at: /usr + +checking for __GNUC__... yes +checking for MagickCore/MagickCore.h... yes +checking for rb_gc_adjust_memory_usage() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... yes +checking for posix_memalign() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... yes +checking for malloc_usable_size() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... yes +checking for malloc_size() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... no +checking for _aligned_msize() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... no +checking for GetImageChannelEntropy() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... no +checking for SetImageGray() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... yes +checking for SetMagickAlignedMemoryMethods() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... yes +checking for malloc.h... yes +creating extconf.h +creating Makefile +====================================================================== +Sun 24 Apr 22 22:39:04 +This installation of RMagick 4.2.5 is configured for +Ruby 3.0.4 (x86_64-linux) and ImageMagick 7.1.0 +====================================================================== + + +Configured compile options: {:magick_version=>"7.1.0", :local_libs=>" -lMagickCore-7.Q16HDRI ", :cppflags=>" -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99", :ldflags=>" -lMagickCore-7.Q16HDRI -Wl,-rpath,", :defs=>[], :config_h=>"Makefile"} + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/rmagick-4.2.5/ext/RMagick +make DESTDIR\= clean + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/rmagick-4.2.5/ext/RMagick +make DESTDIR\= +compiling rmagick.c +compiling rmdraw.c +compiling rmenum.c +compiling rmfill.c +compiling rmilist.c +compiling rmimage.c +compiling rminfo.c +compiling rmkinfo.c +compiling rmmain.c +compiling rmmontage.c +compiling rmpixel.c +compiling rmstruct.c +compiling rmutil.c +linking shared-object RMagick2.so + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/rmagick-4.2.5/ext/RMagick +make DESTDIR\= install +/usr/bin/install -c -m 0755 RMagick2.so ./.gem.20220424-672384-htztp3 diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/rmagick-4.2.5/mkmf.log b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/rmagick-4.2.5/mkmf.log new file mode 100644 index 0000000..9cb6374 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/rmagick-4.2.5/mkmf.log @@ -0,0 +1,523 @@ +find_executable: checking for brew... -------------------- no + +-------------------- + +find_executable: checking for pacman... -------------------- yes + +-------------------- + +assert_minimum_ruby_version!: checking for Ruby version >= 2.3.0... -------------------- yes + +-------------------- + +find_executable: checking for pkg-config... -------------------- yes + +-------------------- + +assert_has_dev_libs!: checking for outdated ImageMagick version (<= 6.7.7)... -------------------- no + +Detected ImageMagick version: 7.1.0 +-------------------- + +find_executable: checking for gcc... -------------------- yes + +-------------------- + + +Warning: Found a partial ImageMagick installation. Your operating +system likely has some built-in ImageMagick libraries but not all of +ImageMagick. This will most likely cause problems at both compile and +runtime. +Found partial installation at: /usr + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: int main(int argc, char **argv) +4: { +5: return !!argv[argc]; +6: } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: int main() { } +/* end */ + +have_macro: checking for __GNUC__... -------------------- yes + +"gcc -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC -c conftest.c" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: /*top*/ +4: #ifndef __GNUC__ +5: # error +6: |:/ === __GNUC__ undefined === /:| +7: #endif +/* end */ + +-------------------- + +have_header: checking for MagickCore/MagickCore.h... -------------------- yes + +"gcc -E -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -o conftest.i" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: #include +/* end */ + +-------------------- + +have_func: checking for rb_gc_adjust_memory_usage() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_gc_adjust_memory_usage; return !p; } +/* end */ + +-------------------- + +have_func: checking for posix_memalign() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: int t(void) { void ((*volatile p)()); p = (void ((*)()))posix_memalign; return !p; } +/* end */ + +-------------------- + +have_func: checking for malloc_usable_size() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +conftest.c: In function ‘t’: +conftest.c:23:57: error: ‘malloc_usable_size’ undeclared (first use in this function) + 23 | int t(void) { void ((*volatile p)()); p = (void ((*)()))malloc_usable_size; return !p; } + | ^~~~~~~~~~~~~~~~~~ +conftest.c:23:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: int t(void) { void ((*volatile p)()); p = (void ((*)()))malloc_usable_size; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: extern void malloc_usable_size(); +24: int t(void) { malloc_usable_size(); return 0; } +/* end */ + +-------------------- + +have_func: checking for malloc_size() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... -------------------- no + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +conftest.c: In function ‘t’: +conftest.c:23:57: error: ‘malloc_size’ undeclared (first use in this function) + 23 | int t(void) { void ((*volatile p)()); p = (void ((*)()))malloc_size; return !p; } + | ^~~~~~~~~~~ +conftest.c:23:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: int t(void) { void ((*volatile p)()); p = (void ((*)()))malloc_size; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +/usr/bin/ld: /tmp/ccUiujjd.o: in function `t': +conftest.c:(.text+0xc): undefined reference to `malloc_size' +collect2: error: ld returned 1 exit status +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: extern void malloc_size(); +24: int t(void) { malloc_size(); return 0; } +/* end */ + +-------------------- + +have_func: checking for _aligned_msize() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... -------------------- no + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +conftest.c: In function ‘t’: +conftest.c:23:57: error: ‘_aligned_msize’ undeclared (first use in this function) + 23 | int t(void) { void ((*volatile p)()); p = (void ((*)()))_aligned_msize; return !p; } + | ^~~~~~~~~~~~~~ +conftest.c:23:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: int t(void) { void ((*volatile p)()); p = (void ((*)()))_aligned_msize; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +/usr/bin/ld: /tmp/ccladuxD.o: in function `t': +conftest.c:(.text+0xc): undefined reference to `_aligned_msize' +collect2: error: ld returned 1 exit status +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: extern void _aligned_msize(); +24: int t(void) { _aligned_msize(); return 0; } +/* end */ + +-------------------- + +have_func: checking for GetImageChannelEntropy() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... -------------------- no + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +conftest.c: In function ‘t’: +conftest.c:23:57: error: ‘GetImageChannelEntropy’ undeclared (first use in this function); did you mean ‘GetImageEntropy’? + 23 | int t(void) { void ((*volatile p)()); p = (void ((*)()))GetImageChannelEntropy; return !p; } + | ^~~~~~~~~~~~~~~~~~~~~~ + | GetImageEntropy +conftest.c:23:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: int t(void) { void ((*volatile p)()); p = (void ((*)()))GetImageChannelEntropy; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +/usr/bin/ld: /tmp/ccIp9PZ3.o: in function `t': +conftest.c:(.text+0xc): undefined reference to `GetImageChannelEntropy' +collect2: error: ld returned 1 exit status +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: extern void GetImageChannelEntropy(); +24: int t(void) { GetImageChannelEntropy(); return 0; } +/* end */ + +-------------------- + +have_func: checking for SetImageGray() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: int t(void) { void ((*volatile p)()); p = (void ((*)()))SetImageGray; return !p; } +/* end */ + +-------------------- + +have_func: checking for SetMagickAlignedMemoryMethods() in assert.h,ctype.h,stdio.h,stdlib.h,math.h,time.h,sys/types.h,MagickCore/MagickCore.h... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -lMagickCore-7.Q16HDRI -Wl,-rpath, -lMagickCore-7.Q16HDRI -lruby -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: #include + 4: #include + 5: #include + 6: #include + 7: #include + 8: #include + 9: #include +10: #include +11: +12: /*top*/ +13: extern int t(void); +14: int main(int argc, char **argv) +15: { +16: if (argc > 1000000) { +17: int (* volatile tp)(void)=(int (*)(void))&t; +18: printf("%d", (*tp)()); +19: } +20: +21: return !!argv[argc]; +22: } +23: int t(void) { void ((*volatile p)()); p = (void ((*)()))SetMagickAlignedMemoryMethods; return !p; } +/* end */ + +-------------------- + +have_header: checking for malloc.h... -------------------- yes + +"gcc -E -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99 -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -o conftest.i" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: #include +/* end */ + +-------------------- + +extconf.h is: +/* begin */ + 1: #ifndef EXTCONF_H + 2: #define EXTCONF_H + 3: #define HAVE_MAGICKCORE_MAGICKCORE_H 1 + 4: #define HAVE_RB_GC_ADJUST_MEMORY_USAGE 1 + 5: #define HAVE_POSIX_MEMALIGN 1 + 6: #define HAVE_MALLOC_USABLE_SIZE 1 + 7: #define HAVE_SETIMAGEGRAY 1 + 8: #define HAVE_SETMAGICKALIGNEDMEMORYMETHODS 1 + 9: #define HAVE_MALLOC_H 1 +10: #define RUBY_VERSION_STRING ruby 3.0.4 +11: #define RMAGICK_VERSION_STRING RMagick 4.2.5 +12: #define IMAGEMAGICK_GREATER_THAN_EQUAL_6_8_9 1 +13: #define IMAGEMAGICK_GREATER_THAN_EQUAL_6_9_0 1 +14: #define IMAGEMAGICK_GREATER_THAN_EQUAL_6_9_10 1 +15: #define IMAGEMAGICK_7 1 +16: #define IMAGEMAGICK_GREATER_THAN_EQUAL_7_0_8 1 +17: #define IMAGEMAGICK_GREATER_THAN_EQUAL_7_0_10 1 +18: #endif +/* end */ + +====================================================================== +Sun 24 Apr 22 22:39:04 +This installation of RMagick 4.2.5 is configured for +Ruby 3.0.4 (x86_64-linux) and ImageMagick 7.1.0 +====================================================================== + + +Configured compile options: {:magick_version=>"7.1.0", :local_libs=>" -lMagickCore-7.Q16HDRI ", :cppflags=>" -I/usr/include/ImageMagick-7 -fopenmp -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -std=gnu99", :ldflags=>" -lMagickCore-7.Q16HDRI -Wl,-rpath,", :defs=>[], :config_h=>"Makefile"} \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sassc-2.4.0/gem.build_complete b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sassc-2.4.0/gem.build_complete new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sassc-2.4.0/gem_make.out b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sassc-2.4.0/gem_make.out new file mode 100644 index 0000000..4a81dcb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sassc-2.4.0/gem_make.out @@ -0,0 +1,80 @@ +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/sassc-2.4.0/ext +/usr/bin/ruby -I /usr/lib/ruby/3.0.0 -r ./siteconf20220424-673820-jbni8g.rb extconf.rb +creating Makefile + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/sassc-2.4.0/ext +make DESTDIR\= clean + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/sassc-2.4.0/ext +make DESTDIR\= +compiling ./libsass/src/ast.cpp +compiling ./libsass/src/ast2c.cpp +compiling ./libsass/src/ast_fwd_decl.cpp +compiling ./libsass/src/ast_sel_cmp.cpp +compiling ./libsass/src/ast_sel_super.cpp +compiling ./libsass/src/ast_sel_unify.cpp +compiling ./libsass/src/ast_sel_weave.cpp +compiling ./libsass/src/ast_selectors.cpp +compiling ./libsass/src/ast_supports.cpp +compiling ./libsass/src/ast_values.cpp +compiling ./libsass/src/backtrace.cpp +compiling ./libsass/src/base64vlq.cpp +compiling ./libsass/src/bind.cpp +compiling ./libsass/src/c2ast.cpp +compiling ./libsass/src/c99func.c +compiling ./libsass/src/cencode.c +compiling ./libsass/src/check_nesting.cpp +compiling ./libsass/src/color_maps.cpp +compiling ./libsass/src/constants.cpp +compiling ./libsass/src/context.cpp +compiling ./libsass/src/cssize.cpp +compiling ./libsass/src/emitter.cpp +compiling ./libsass/src/environment.cpp +compiling ./libsass/src/error_handling.cpp +compiling ./libsass/src/eval.cpp +compiling ./libsass/src/eval_selectors.cpp +compiling ./libsass/src/expand.cpp +compiling ./libsass/src/extender.cpp +compiling ./libsass/src/extension.cpp +compiling ./libsass/src/file.cpp +compiling ./libsass/src/fn_colors.cpp +compiling ./libsass/src/fn_lists.cpp +compiling ./libsass/src/fn_maps.cpp +compiling ./libsass/src/fn_miscs.cpp +compiling ./libsass/src/fn_numbers.cpp +compiling ./libsass/src/fn_selectors.cpp +compiling ./libsass/src/fn_strings.cpp +compiling ./libsass/src/fn_utils.cpp +compiling ./libsass/src/inspect.cpp +compiling ./libsass/src/json.cpp +compiling ./libsass/src/lexer.cpp +compiling ./libsass/src/listize.cpp +compiling ./libsass/src/memory/allocator.cpp +compiling ./libsass/src/memory/shared_ptr.cpp +compiling ./libsass/src/operators.cpp +compiling ./libsass/src/output.cpp +compiling ./libsass/src/parser.cpp +compiling ./libsass/src/parser_selectors.cpp +compiling ./libsass/src/plugins.cpp +compiling ./libsass/src/position.cpp +compiling ./libsass/src/prelexer.cpp +compiling ./libsass/src/remove_placeholders.cpp +compiling ./libsass/src/sass.cpp +compiling ./libsass/src/sass2scss.cpp +compiling ./libsass/src/sass_context.cpp +compiling ./libsass/src/sass_functions.cpp +compiling ./libsass/src/sass_values.cpp +compiling ./libsass/src/source.cpp +compiling ./libsass/src/source_map.cpp +compiling ./libsass/src/stylesheet.cpp +compiling ./libsass/src/to_value.cpp +compiling ./libsass/src/units.cpp +compiling ./libsass/src/utf8_string.cpp +compiling ./libsass/src/util.cpp +compiling ./libsass/src/util_string.cpp +compiling ./libsass/src/values.cpp +linking shared-object sassc/libsass.so + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/sassc-2.4.0/ext +make DESTDIR\= install +/usr/bin/install -c -m 0755 libsass.so ./.gem.20220424-673820-x27wv9/sassc diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sassc-2.4.0/sassc/libsass.so b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sassc-2.4.0/sassc/libsass.so new file mode 100755 index 0000000..7360484 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sassc-2.4.0/sassc/libsass.so differ diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sqlite3-1.4.2/gem.build_complete b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sqlite3-1.4.2/gem.build_complete new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sqlite3-1.4.2/gem_make.out b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sqlite3-1.4.2/gem_make.out new file mode 100644 index 0000000..52a08a2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sqlite3-1.4.2/gem_make.out @@ -0,0 +1,76 @@ +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3 +/usr/bin/ruby -I /usr/lib/ruby/3.0.0 -r ./siteconf20220424-672384-6f01zl.rb extconf.rb +checking for sqlite3.h... yes +checking for pthread_create() in -lpthread... yes +checking for -ldl... yes +checking for sqlite3_libversion_number() in -lsqlite3... yes +checking for rb_proc_arity()... yes +checking for rb_integer_pack()... yes +checking for sqlite3_initialize()... yes +checking for sqlite3_backup_init()... yes +checking for sqlite3_column_database_name()... yes +checking for sqlite3_enable_load_extension()... yes +checking for sqlite3_load_extension()... yes +checking for sqlite3_open_v2()... yes +checking for sqlite3_prepare_v2()... yes +checking for sqlite3_int64 in sqlite3.h... yes +checking for sqlite3_uint64 in sqlite3.h... yes +creating Makefile + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3 +make DESTDIR\= clean + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3 +make DESTDIR\= +compiling aggregator.c +compiling backup.c +compiling database.c +database.c: In function ‘exec_batch’: +database.c:726:57: warning: passing argument 3 of ‘sqlite3_exec’ from incompatible pointer type [-Wincompatible-pointer-types] + 726 | status = sqlite3_exec(ctx->db, StringValuePtr(sql), hash_callback_function, callback_ary, &errMsg); + | ^~~~~~~~~~~~~~~~~~~~~~ + | | + | int (*)(VALUE, int, char **, char **) {aka int (*)(long unsigned int, int, char **, char **)} +In file included from ./sqlite3_ruby.h:25, + from database.c:1: +/usr/include/sqlite3.h:428:9: note: expected ‘int (*)(void *, int, char **, char **)’ but argument is of type ‘int (*)(VALUE, int, char **, char **)’ {aka ‘int (*)(long unsigned int, int, char **, char **)’} + 428 | int (*callback)(void*,int,char**,char**), /* Callback function */ + | ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +database.c:726:81: warning: passing argument 4 of ‘sqlite3_exec’ makes pointer from integer without a cast [-Wint-conversion] + 726 | status = sqlite3_exec(ctx->db, StringValuePtr(sql), hash_callback_function, callback_ary, &errMsg); + | ^~~~~~~~~~~~ + | | + | VALUE {aka long unsigned int} +In file included from ./sqlite3_ruby.h:25, + from database.c:1: +/usr/include/sqlite3.h:429:3: note: expected ‘void *’ but argument is of type ‘VALUE’ {aka ‘long unsigned int’} + 429 | void *, /* 1st argument to callback */ + | ^~~~~~ +database.c:728:57: warning: passing argument 3 of ‘sqlite3_exec’ from incompatible pointer type [-Wincompatible-pointer-types] + 728 | status = sqlite3_exec(ctx->db, StringValuePtr(sql), regular_callback_function, callback_ary, &errMsg); + | ^~~~~~~~~~~~~~~~~~~~~~~~~ + | | + | int (*)(VALUE, int, char **, char **) {aka int (*)(long unsigned int, int, char **, char **)} +In file included from ./sqlite3_ruby.h:25, + from database.c:1: +/usr/include/sqlite3.h:428:9: note: expected ‘int (*)(void *, int, char **, char **)’ but argument is of type ‘int (*)(VALUE, int, char **, char **)’ {aka ‘int (*)(long unsigned int, int, char **, char **)’} + 428 | int (*callback)(void*,int,char**,char**), /* Callback function */ + | ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +database.c:728:84: warning: passing argument 4 of ‘sqlite3_exec’ makes pointer from integer without a cast [-Wint-conversion] + 728 | status = sqlite3_exec(ctx->db, StringValuePtr(sql), regular_callback_function, callback_ary, &errMsg); + | ^~~~~~~~~~~~ + | | + | VALUE {aka long unsigned int} +In file included from ./sqlite3_ruby.h:25, + from database.c:1: +/usr/include/sqlite3.h:429:3: note: expected ‘void *’ but argument is of type ‘VALUE’ {aka ‘long unsigned int’} + 429 | void *, /* 1st argument to callback */ + | ^~~~~~ +compiling exception.c +compiling sqlite3.c +compiling statement.c +linking shared-object sqlite3/sqlite3_native.so + +current directory: /home/elal/Projects/websites/the_auctionhouse/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3 +make DESTDIR\= install +/usr/bin/install -c -m 0755 sqlite3_native.so ./.gem.20220424-672384-xzlu6m/sqlite3 diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sqlite3-1.4.2/mkmf.log b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sqlite3-1.4.2/mkmf.log new file mode 100644 index 0000000..1098d83 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sqlite3-1.4.2/mkmf.log @@ -0,0 +1,584 @@ +"pkg-config --exists sqlite3" +| pkg-config --libs sqlite3 +=> "-lsqlite3 \n" +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lruby -lm -lc" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: int main(int argc, char **argv) +4: { +5: return !!argv[argc]; +6: } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lruby -lsqlite3 -lm -lc" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: int main(int argc, char **argv) +4: { +5: return !!argv[argc]; +6: } +/* end */ + +| pkg-config --cflags-only-I sqlite3 +=> "\n" +| pkg-config --cflags-only-other sqlite3 +=> "\n" +| pkg-config --libs-only-l sqlite3 +=> "-lsqlite3 \n" +package configuration for sqlite3 +incflags: +cflags: +ldflags: +libs: -lsqlite3 + +find_header: checking for sqlite3.h... -------------------- yes + +"gcc -E -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -o conftest.i" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: #include +/* end */ + +-------------------- + +find_library: checking for pthread_create() in -lpthread... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -lruby -lpthread -lsqlite3 -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘pthread_create’ undeclared (first use in this function); did you mean ‘rb_thread_create’? + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))pthread_create; return !p; } + | ^~~~~~~~~~~~~~ + | rb_thread_create +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))pthread_create; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -lruby -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void pthread_create(); +15: int t(void) { pthread_create(); return 0; } +/* end */ + +-------------------- + +have_library: checking for -ldl... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lpthread -lsqlite3 -lruby -ldl -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: +15: int t(void) { ; return 0; } +/* end */ + +-------------------- + +find_library: checking for sqlite3_libversion_number() in -lsqlite3... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘sqlite3_libversion_number’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_libversion_number; return !p; } + | ^~~~~~~~~~~~~~~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_libversion_number; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void sqlite3_libversion_number(); +15: int t(void) { sqlite3_libversion_number(); return 0; } +/* end */ + +-------------------- + +have_func: checking for rb_proc_arity()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_proc_arity; return !p; } +/* end */ + +-------------------- + +have_func: checking for rb_integer_pack()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_integer_pack; return !p; } +/* end */ + +-------------------- + +have_func: checking for sqlite3_initialize()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘sqlite3_initialize’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_initialize; return !p; } + | ^~~~~~~~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_initialize; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void sqlite3_initialize(); +15: int t(void) { sqlite3_initialize(); return 0; } +/* end */ + +-------------------- + +have_func: checking for sqlite3_backup_init()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘sqlite3_backup_init’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_backup_init; return !p; } + | ^~~~~~~~~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_backup_init; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void sqlite3_backup_init(); +15: int t(void) { sqlite3_backup_init(); return 0; } +/* end */ + +-------------------- + +have_func: checking for sqlite3_column_database_name()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘sqlite3_column_database_name’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_column_database_name; return !p; } + | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_column_database_name; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void sqlite3_column_database_name(); +15: int t(void) { sqlite3_column_database_name(); return 0; } +/* end */ + +-------------------- + +have_func: checking for sqlite3_enable_load_extension()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘sqlite3_enable_load_extension’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_enable_load_extension; return !p; } + | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_enable_load_extension; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void sqlite3_enable_load_extension(); +15: int t(void) { sqlite3_enable_load_extension(); return 0; } +/* end */ + +-------------------- + +have_func: checking for sqlite3_load_extension()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘sqlite3_load_extension’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_load_extension; return !p; } + | ^~~~~~~~~~~~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_load_extension; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void sqlite3_load_extension(); +15: int t(void) { sqlite3_load_extension(); return 0; } +/* end */ + +-------------------- + +have_func: checking for sqlite3_open_v2()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘sqlite3_open_v2’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_open_v2; return !p; } + | ^~~~~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_open_v2; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void sqlite3_open_v2(); +15: int t(void) { sqlite3_open_v2(); return 0; } +/* end */ + +-------------------- + +have_func: checking for sqlite3_prepare_v2()... -------------------- yes + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +conftest.c: In function ‘t’: +conftest.c:14:57: error: ‘sqlite3_prepare_v2’ undeclared (first use in this function) + 14 | int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_prepare_v2; return !p; } + | ^~~~~~~~~~~~~~~~~~ +conftest.c:14:57: note: each undeclared identifier is reported only once for each function it appears in +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: int t(void) { void ((*volatile p)()); p = (void ((*)()))sqlite3_prepare_v2; return !p; } +/* end */ + +"gcc -o conftest -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC conftest.c -L. -L/usr/lib -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -lsqlite3 -ldl -lpthread -lsqlite3 -lruby -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc" +checked program was: +/* begin */ + 1: #include "ruby.h" + 2: + 3: /*top*/ + 4: extern int t(void); + 5: int main(int argc, char **argv) + 6: { + 7: if (argc > 1000000) { + 8: int (* volatile tp)(void)=(int (*)(void))&t; + 9: printf("%d", (*tp)()); +10: } +11: +12: return !!argv[argc]; +13: } +14: extern void sqlite3_prepare_v2(); +15: int t(void) { sqlite3_prepare_v2(); return 0; } +/* end */ + +-------------------- + +have_type: checking for sqlite3_int64 in sqlite3.h... -------------------- yes + +"gcc -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC -c conftest.c" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: #include +4: +5: /*top*/ +6: typedef sqlite3_int64 conftest_type; +7: int conftestval[sizeof(conftest_type)?1:-1]; +/* end */ + +-------------------- + +have_type: checking for sqlite3_uint64 in sqlite3.h... -------------------- yes + +"gcc -I/usr/include/ruby-3.0.0/x86_64-linux -I/usr/include/ruby-3.0.0/ruby/backward -I/usr/include/ruby-3.0.0 -I. -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC -c conftest.c" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: #include +4: +5: /*top*/ +6: typedef sqlite3_uint64 conftest_type; +7: int conftestval[sizeof(conftest_type)?1:-1]; +/* end */ + +-------------------- + diff --git a/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sqlite3-1.4.2/sqlite3/sqlite3_native.so b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sqlite3-1.4.2/sqlite3/sqlite3_native.so new file mode 100755 index 0000000..a9e91f6 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/extensions/x86_64-linux/3.0.0/sqlite3-1.4.2/sqlite3/sqlite3_native.so differ diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/CHANGELOG.md b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/CHANGELOG.md new file mode 100644 index 0000000..9bb0b43 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/CHANGELOG.md @@ -0,0 +1,419 @@ +## Rails 7.0.2.3 (March 08, 2022) ## + +* No changes. + + +## Rails 7.0.2.2 (February 11, 2022) ## + +* Fix Reloader method signature to work with the new Executor signature + + +## Rails 7.0.2.1 (February 11, 2022) ## + +* No changes. + + +## Rails 7.0.2 (February 08, 2022) ## + +* Fix `ActiveSupport::EncryptedConfiguration` to be compatible with Psych 4 + + *Stephen Sugden* + +* Improve `File.atomic_write` error handling. + + *Daniel Pepper* + + +## Rails 7.0.1 (January 06, 2022) ## + +* Fix `Class#descendants` and `DescendantsTracker#descendants` compatibility with Ruby 3.1. + + [The native `Class#descendants` was reverted prior to Ruby 3.1 release](https://bugs.ruby-lang.org/issues/14394#note-33), + but `Class#subclasses` was kept, breaking the feature detection. + + *Jean Boussier* + + +## Rails 7.0.0 (December 15, 2021) ## + +* Fix `ActiveSupport::Duration.build` to support negative values. + + The algorithm to collect the `parts` of the `ActiveSupport::Duration` + ignored the sign of the `value` and accumulated incorrect part values. This + impacted `ActiveSupport::Duration#sum` (which is dependent on `parts`) but + not `ActiveSupport::Duration#eql?` (which is dependent on `value`). + + *Caleb Buxton*, *Braden Staudacher* + + +## Rails 7.0.0.rc3 (December 14, 2021) ## + +* No changes. + + +## Rails 7.0.0.rc2 (December 14, 2021) ## + +* No changes. + +## Rails 7.0.0.rc1 (December 06, 2021) ## + +* Deprecate passing a format to `#to_s` in favor of `#to_formatted_s` in `Array`, `Range`, `Date`, `DateTime`, `Time`, + `BigDecimal`, `Float` and, `Integer`. + + *Rafael Mendonça França* + +* Document `ActiveSupport::Testing::Deprecation`. + + *Sam Bostock & Sam Jordan* + +* Add `Pathname#existence`. + + ```ruby + Pathname.new("file").existence&.read + ``` + + *Timo Schilling* + +* Remove deprecate `ActiveSupport::Multibyte::Unicode.default_normalization_form`. + + *Rafael Mendonça França* + +* Remove deprecated support to use `Range#include?` to check the inclusion of a value in + a date time range is deprecated. + + *Rafael Mendonça França* + +* Remove deprecated `URI.parser`. + + *Rafael Mendonça França* + +* Remove deprecated `config.active_support.use_sha1_digests`. + + *Rafael Mendonça França* + +* Invoking `Object#with_options` without a `&block` argument returns the + `ActiveSupport::OptionMerger` instance. + + *Sean Doyle* + +* `Rails.application.executor` hooks can now be called around every test + + This helps to better simulate request or job local state being reset around tests and prevents state + leaking from one test to another. + + However it requires the executor hooks executed in the test environment to be re-entrant. + + To enable this, set `config.active_support.executor_around_test_case = true` (this is the default in Rails 7). + + *Jean Boussier* + +* `ActiveSupport::DescendantsTracker` now mostly delegate to `Class#descendants` on Ruby 3.1 + + Ruby now provides a fast `Class#descendants` making `ActiveSupport::DescendantsTracker` mostly useless. + + As a result the following methods are deprecated: + + - `ActiveSupport::DescendantsTracker.direct_descendants` + - `ActiveSupport::DescendantsTracker#direct_descendants` + + *Jean Boussier* + +* Fix the `Digest::UUID.uuid_from_hash` behavior for namespace IDs that are different from the ones defined on `Digest::UUID`. + + The new behavior will be enabled by setting the + `config.active_support.use_rfc4122_namespaced_uuids` option to `true` + and is the default for new apps. + + The old behavior is the default for upgraded apps and will output a + deprecation warning every time a value that is different than one of + the constants defined on the `Digest::UUID` extension is used as the + namespace ID. + + *Alex Robbin*, *Erich Soares Machado*, *Eugene Kenny* + +* `ActiveSupport::Inflector::Inflections#clear(:acronyms)` is now supported, + and `inflector.clear` / `inflector.clear(:all)` also clears acronyms. + + *Alex Ghiculescu*, *Oliver Peate* + + +## Rails 7.0.0.alpha2 (September 15, 2021) ## + +* No changes. + + +## Rails 7.0.0.alpha1 (September 15, 2021) ## + +* `ActiveSupport::Dependencies` no longer installs a `const_missing` hook. Before this, you could push to the autoload paths and have constants autoloaded. This feature, known as the `classic` autoloader, has been removed. + + *Xavier Noria* + +* Private internal classes of `ActiveSupport::Dependencies` have been deleted, like `ActiveSupport::Dependencies::Reference`, `ActiveSupport::Dependencies::Blamable`, and others. + + *Xavier Noria* + +* The private API of `ActiveSupport::Dependencies` has been deleted. That includes methods like `hook!`, `unhook!`, `depend_on`, `require_or_load`, `mechanism`, and many others. + + *Xavier Noria* + +* Improves the performance of `ActiveSupport::NumberHelper` formatters by avoiding the use of exceptions as flow control. + + *Mike Dalessio* + +* Removed rescue block from `ActiveSupport::Cache::RedisCacheStore#handle_exception` + + Previously, if you provided a `error_handler` to `redis_cache_store`, any errors thrown by + the error handler would be rescued and logged only. Removed the `rescue` clause from `handle_exception` + to allow these to be thrown. + + *Nicholas A. Stuart* + +* Allow entirely opting out of deprecation warnings. + + Previously if you did `app.config.active_support.deprecation = :silence`, some work would + still be done on each call to `ActiveSupport::Deprecation.warn`. In very hot paths, this could + cause performance issues. + + Now, you can make `ActiveSupport::Deprecation.warn` a no-op: + + ```ruby + config.active_support.report_deprecations = false + ``` + + This is the default in production for new apps. It is the equivalent to: + + ```ruby + config.active_support.deprecation = :silence + config.active_support.disallowed_deprecation = :silence + ``` + + but will take a more optimised code path. + + *Alex Ghiculescu* + +* Faster tests by parallelizing only when overhead is justified by the number + of them. + + Running tests in parallel adds overhead in terms of database + setup and fixture loading. Now, Rails will only parallelize test executions when + there are enough tests to make it worth it. + + This threshold is 50 by default, and is configurable via config setting in + your test.rb: + + ```ruby + config.active_support.test_parallelization_threshold = 100 + ``` + + It's also configurable at the test case level: + + ```ruby + class ActiveSupport::TestCase + parallelize threshold: 100 + end + ``` + + *Jorge Manrubia* + +* OpenSSL constants are now used for Digest computations. + + *Dirkjan Bussink* + +* `TimeZone.iso8601` now accepts valid ordinal values similar to Ruby's `Date._iso8601` method. + A valid ordinal value will be converted to an instance of `TimeWithZone` using the `:year` + and `:yday` fragments returned from `Date._iso8601`. + + ```ruby + twz = ActiveSupport::TimeZone["Eastern Time (US & Canada)"].iso8601("21087") + twz.to_a[0, 6] == [0, 0, 0, 28, 03, 2021] + ``` + + *Steve Laing* + +* `Time#change` and methods that call it (e.g. `Time#advance`) will now + return a `Time` with the timezone argument provided, if the caller was + initialized with a timezone argument. + + Fixes [#42467](https://github.com/rails/rails/issues/42467). + + *Alex Ghiculescu* + +* Allow serializing any module or class to JSON by name. + + *Tyler Rick*, *Zachary Scott* + +* Raise `ActiveSupport::EncryptedFile::MissingKeyError` when the + `RAILS_MASTER_KEY` environment variable is blank (e.g. `""`). + + *Sunny Ripert* + +* The `from:` option is added to `ActiveSupport::TestCase#assert_no_changes`. + + It permits asserting on the initial value that is expected not to change. + + ```ruby + assert_no_changes -> { Status.all_good? }, from: true do + post :create, params: { status: { ok: true } } + end + ``` + + *George Claghorn* + +* Deprecate `ActiveSupport::SafeBuffer`'s incorrect implicit conversion of objects into string. + + Except for a few methods like `String#%`, objects must implement `#to_str` + to be implicitly converted to a String in string operations. In some + circumstances `ActiveSupport::SafeBuffer` was incorrectly calling the + explicit conversion method (`#to_s`) on them. This behavior is now + deprecated. + + *Jean Boussier* + +* Allow nested access to keys on `Rails.application.credentials`. + + Previously only top level keys in `credentials.yml.enc` could be accessed with method calls. Now any key can. + + For example, given these secrets: + + ```yml + aws: + access_key_id: 123 + secret_access_key: 345 + ``` + + `Rails.application.credentials.aws.access_key_id` will now return the same thing as + `Rails.application.credentials.aws[:access_key_id]`. + + *Alex Ghiculescu* + +* Added a faster and more compact `ActiveSupport::Cache` serialization format. + + It can be enabled with `config.active_support.cache_format_version = 7.0` or + `config.load_defaults 7.0`. Regardless of the configuration Active Support + 7.0 can read cache entries serialized by Active Support 6.1 which allows to + upgrade without invalidating the cache. However Rails 6.1 can't read the + new format, so all readers must be upgraded before the new format is enabled. + + *Jean Boussier* + +* Add `Enumerable#sole`, per `ActiveRecord::FinderMethods#sole`. Returns the + sole item of the enumerable, raising if no items are found, or if more than + one is. + + *Asherah Connor* + +* Freeze `ActiveSupport::Duration#parts` and remove writer methods. + + Durations are meant to be value objects and should not be mutated. + + *Andrew White* + +* Fix `ActiveSupport::TimeZone#utc_to_local` with fractional seconds. + + When `utc_to_local_returns_utc_offset_times` is false and the time + instance had fractional seconds the new UTC time instance was out by + a factor of 1,000,000 as the `Time.utc` constructor takes a usec + value and not a fractional second value. + + *Andrew White* + +* Add `expires_at` argument to `ActiveSupport::Cache` `write` and `fetch` to set a cache entry TTL as an absolute time. + + ```ruby + Rails.cache.write(key, value, expires_at: Time.now.at_end_of_hour) + ``` + + *Jean Boussier* + +* Deprecate `ActiveSupport::TimeWithZone.name` so that from Rails 7.1 it will use the default implementation. + + *Andrew White* + +* Deprecates Rails custom `Enumerable#sum` and `Array#sum` in favor of Ruby's native implementation which + is considerably faster. + + Ruby requires an initializer for non-numeric type as per examples below: + + ```ruby + %w[foo bar].sum('') + # instead of %w[foo bar].sum + + [[1, 2], [3, 4, 5]].sum([]) + # instead of [[1, 2], [3, 4, 5]].sum + ``` + + *Alberto Mota* + +* Tests parallelization is now disabled when running individual files to prevent the setup overhead. + + It can still be enforced if the environment variable `PARALLEL_WORKERS` is present and set to a value greater than 1. + + *Ricardo Díaz* + +* Fix proxying keyword arguments in `ActiveSupport::CurrentAttributes`. + + *Marcin Kołodziej* + +* Add `Enumerable#maximum` and `Enumerable#minimum` to easily calculate the maximum or minimum from extracted + elements of an enumerable. + + ```ruby + payments = [Payment.new(5), Payment.new(15), Payment.new(10)] + + payments.minimum(:price) # => 5 + payments.maximum(:price) # => 15 + ``` + + This also allows passing enumerables to `fresh_when` and `stale?` in Action Controller. + See PR [#41404](https://github.com/rails/rails/pull/41404) for an example. + + *Ayrton De Craene* + +* `ActiveSupport::Cache::MemCacheStore` now accepts an explicit `nil` for its `addresses` argument. + + ```ruby + config.cache_store = :mem_cache_store, nil + + # is now equivalent to + + config.cache_store = :mem_cache_store + + # and is also equivalent to + + config.cache_store = :mem_cache_store, ENV["MEMCACHE_SERVERS"] || "localhost:11211" + + # which is the fallback behavior of Dalli + ``` + + This helps those migrating from `:dalli_store`, where an explicit `nil` was permitted. + + *Michael Overmeyer* + +* Add `Enumerable#in_order_of` to put an Enumerable in a certain order by a key. + + *DHH* + +* `ActiveSupport::Inflector.camelize` behaves expected when provided a symbol `:upper` or `:lower` argument. Matches + `String#camelize` behavior. + + *Alex Ghiculescu* + +* Raises an `ArgumentError` when the first argument of `ActiveSupport::Notification.subscribe` is + invalid. + + *Vipul A M* + +* `HashWithIndifferentAccess#deep_transform_keys` now returns a `HashWithIndifferentAccess` instead of a `Hash`. + + *Nathaniel Woodthorpe* + +* Consume dalli’s `cache_nils` configuration as `ActiveSupport::Cache`'s `skip_nil` when using `MemCacheStore`. + + *Ritikesh G* + +* Add `RedisCacheStore#stats` method similar to `MemCacheStore#stats`. Calls `redis#info` internally. + + *Ritikesh G* + + +Please check [6-1-stable](https://github.com/rails/rails/blob/6-1-stable/activesupport/CHANGELOG.md) for previous changes. diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/MIT-LICENSE b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/MIT-LICENSE new file mode 100644 index 0000000..0a0ce38 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2005-2022 David Heinemeier Hansson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/README.rdoc b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/README.rdoc new file mode 100644 index 0000000..c2df6d7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/README.rdoc @@ -0,0 +1,40 @@ += Active Support -- Utility classes and Ruby extensions from Rails + +Active Support is a collection of utility classes and standard library +extensions that were found useful for the Rails framework. These additions +reside in this package so they can be loaded as needed in Ruby projects +outside of Rails. + +You can read more about the extensions in the {Active Support Core Extensions}[https://edgeguides.rubyonrails.org/active_support_core_extensions.html] guide. + +== Download and installation + +The latest version of Active Support can be installed with RubyGems: + + $ gem install activesupport + +Source code can be downloaded as part of the Rails project on GitHub: + +* https://github.com/rails/rails/tree/main/activesupport + + +== License + +Active Support is released under the MIT license: + +* https://opensource.org/licenses/MIT + + +== Support + +API documentation is at: + +* https://api.rubyonrails.org + +Bug reports for the Ruby on Rails project can be filed here: + +* https://github.com/rails/rails/issues + +Feature requests should be discussed on the rails-core mailing list here: + +* https://discuss.rubyonrails.org/c/rubyonrails-core diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support.rb new file mode 100644 index 0000000..e04796b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support.rb @@ -0,0 +1,124 @@ +# frozen_string_literal: true + +#-- +# Copyright (c) 2005-2022 David Heinemeier Hansson +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +#++ + +require "securerandom" +require "active_support/dependencies/autoload" +require "active_support/version" +require "active_support/logger" +require "active_support/lazy_load_hooks" +require "active_support/core_ext/date_and_time/compatibility" + +module ActiveSupport + extend ActiveSupport::Autoload + + autoload :Concern + autoload :CodeGenerator + autoload :ActionableError + autoload :ConfigurationFile + autoload :CurrentAttributes + autoload :Dependencies + autoload :DescendantsTracker + autoload :ExecutionContext + autoload :ExecutionWrapper + autoload :Executor + autoload :ErrorReporter + autoload :FileUpdateChecker + autoload :EventedFileUpdateChecker + autoload :ForkTracker + autoload :LogSubscriber + autoload :IsolatedExecutionState + autoload :Notifications + autoload :Reloader + autoload :PerThreadRegistry + autoload :SecureCompareRotator + + eager_autoload do + autoload :BacktraceCleaner + autoload :ProxyObject + autoload :Benchmarkable + autoload :Cache + autoload :Callbacks + autoload :Configurable + autoload :Deprecation + autoload :Digest + autoload :Gzip + autoload :Inflector + autoload :JSON + autoload :KeyGenerator + autoload :MessageEncryptor + autoload :MessageVerifier + autoload :Multibyte + autoload :NumberHelper + autoload :OptionMerger + autoload :OrderedHash + autoload :OrderedOptions + autoload :StringInquirer + autoload :EnvironmentInquirer + autoload :TaggedLogging + autoload :XmlMini + autoload :ArrayInquirer + end + + autoload :Rescuable + autoload :SafeBuffer, "active_support/core_ext/string/output_safety" + autoload :TestCase + + def self.eager_load! + super + + NumberHelper.eager_load! + end + + cattr_accessor :test_order # :nodoc: + cattr_accessor :test_parallelization_threshold, default: 50 # :nodoc: + + singleton_class.attr_accessor :error_reporter # :nodoc: + + def self.cache_format_version + Cache.format_version + end + + def self.cache_format_version=(value) + Cache.format_version = value + end + + def self.to_time_preserves_timezone + DateAndTime::Compatibility.preserve_timezone + end + + def self.to_time_preserves_timezone=(value) + DateAndTime::Compatibility.preserve_timezone = value + end + + def self.utc_to_local_returns_utc_offset_times + DateAndTime::Compatibility.utc_to_local_returns_utc_offset_times + end + + def self.utc_to_local_returns_utc_offset_times=(value) + DateAndTime::Compatibility.utc_to_local_returns_utc_offset_times = value + end +end + +autoload :I18n, "active_support/i18n" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/actionable_error.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/actionable_error.rb new file mode 100644 index 0000000..2b8b2ff --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/actionable_error.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +module ActiveSupport + # Actionable errors lets you define actions to resolve an error. + # + # To make an error actionable, include the ActiveSupport::ActionableError + # module and invoke the +action+ class macro to define the action. An action + # needs a name and a block to execute. + module ActionableError + extend Concern + + class NonActionable < StandardError; end + + included do + class_attribute :_actions, default: {} + end + + def self.actions(error) # :nodoc: + case error + when ActionableError, -> it { Class === it && it < ActionableError } + error._actions + else + {} + end + end + + def self.dispatch(error, name) # :nodoc: + actions(error).fetch(name).call + rescue KeyError + raise NonActionable, "Cannot find action \"#{name}\"" + end + + module ClassMethods + # Defines an action that can resolve the error. + # + # class PendingMigrationError < MigrationError + # include ActiveSupport::ActionableError + # + # action "Run pending migrations" do + # ActiveRecord::Tasks::DatabaseTasks.migrate + # end + # end + def action(name, &block) + _actions[name] = block + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/all.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/all.rb new file mode 100644 index 0000000..4adf446 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/all.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +require "active_support" +require "active_support/time" +require "active_support/core_ext" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/array_inquirer.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/array_inquirer.rb new file mode 100644 index 0000000..ecd2389 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/array_inquirer.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +module ActiveSupport + # Wrapping an array in an +ArrayInquirer+ gives a friendlier way to check + # its string-like contents: + # + # variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet]) + # + # variants.phone? # => true + # variants.tablet? # => true + # variants.desktop? # => false + class ArrayInquirer < Array + # Passes each element of +candidates+ collection to ArrayInquirer collection. + # The method returns true if any element from the ArrayInquirer collection + # is equal to the stringified or symbolized form of any element in the +candidates+ collection. + # + # If +candidates+ collection is not given, method returns true. + # + # variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet]) + # + # variants.any? # => true + # variants.any?(:phone, :tablet) # => true + # variants.any?('phone', 'desktop') # => true + # variants.any?(:desktop, :watch) # => false + def any?(*candidates) + if candidates.none? + super + else + candidates.any? do |candidate| + include?(candidate.to_sym) || include?(candidate.to_s) + end + end + end + + private + def respond_to_missing?(name, include_private = false) + name.end_with?("?") || super + end + + def method_missing(name, *args) + if name.end_with?("?") + any?(name[0..-2]) + else + super + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/backtrace_cleaner.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/backtrace_cleaner.rb new file mode 100644 index 0000000..03c7dc7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/backtrace_cleaner.rb @@ -0,0 +1,131 @@ +# frozen_string_literal: true + +module ActiveSupport + # Backtraces often include many lines that are not relevant for the context + # under review. This makes it hard to find the signal amongst the backtrace + # noise, and adds debugging time. With a BacktraceCleaner, filters and + # silencers are used to remove the noisy lines, so that only the most relevant + # lines remain. + # + # Filters are used to modify lines of data, while silencers are used to remove + # lines entirely. The typical filter use case is to remove lengthy path + # information from the start of each line, and view file paths relevant to the + # app directory instead of the file system root. The typical silencer use case + # is to exclude the output of a noisy library from the backtrace, so that you + # can focus on the rest. + # + # bc = ActiveSupport::BacktraceCleaner.new + # bc.add_filter { |line| line.gsub(Rails.root.to_s, '') } # strip the Rails.root prefix + # bc.add_silencer { |line| /puma|rubygems/.match?(line) } # skip any lines from puma or rubygems + # bc.clean(exception.backtrace) # perform the cleanup + # + # To reconfigure an existing BacktraceCleaner (like the default one in Rails) + # and show as much data as possible, you can always call + # BacktraceCleaner#remove_silencers!, which will restore the + # backtrace to a pristine state. If you need to reconfigure an existing + # BacktraceCleaner so that it does not filter or modify the paths of any lines + # of the backtrace, you can call BacktraceCleaner#remove_filters! + # These two methods will give you a completely untouched backtrace. + # + # Inspired by the Quiet Backtrace gem by thoughtbot. + class BacktraceCleaner + def initialize + @filters, @silencers = [], [] + add_gem_filter + add_gem_silencer + add_stdlib_silencer + end + + # Returns the backtrace after all filters and silencers have been run + # against it. Filters run first, then silencers. + def clean(backtrace, kind = :silent) + filtered = filter_backtrace(backtrace) + + case kind + when :silent + silence(filtered) + when :noise + noise(filtered) + else + filtered + end + end + alias :filter :clean + + # Adds a filter from the block provided. Each line in the backtrace will be + # mapped against this filter. + # + # # Will turn "/my/rails/root/app/models/person.rb" into "/app/models/person.rb" + # backtrace_cleaner.add_filter { |line| line.gsub(Rails.root, '') } + def add_filter(&block) + @filters << block + end + + # Adds a silencer from the block provided. If the silencer returns +true+ + # for a given line, it will be excluded from the clean backtrace. + # + # # Will reject all lines that include the word "puma", like "/gems/puma/server.rb" or "/app/my_puma_server/rb" + # backtrace_cleaner.add_silencer { |line| /puma/.match?(line) } + def add_silencer(&block) + @silencers << block + end + + # Removes all silencers, but leaves in the filters. Useful if your + # context of debugging suddenly expands as you suspect a bug in one of + # the libraries you use. + def remove_silencers! + @silencers = [] + end + + # Removes all filters, but leaves in the silencers. Useful if you suddenly + # need to see entire filepaths in the backtrace that you had already + # filtered out. + def remove_filters! + @filters = [] + end + + private + FORMATTED_GEMS_PATTERN = /\A[^\/]+ \([\w.]+\) / + + def add_gem_filter + gems_paths = (Gem.path | [Gem.default_dir]).map { |p| Regexp.escape(p) } + return if gems_paths.empty? + + gems_regexp = %r{\A(#{gems_paths.join('|')})/(bundler/)?gems/([^/]+)-([\w.]+)/(.*)} + gems_result = '\3 (\4) \5' + add_filter { |line| line.sub(gems_regexp, gems_result) } + end + + def add_gem_silencer + add_silencer { |line| FORMATTED_GEMS_PATTERN.match?(line) } + end + + def add_stdlib_silencer + add_silencer { |line| line.start_with?(RbConfig::CONFIG["rubylibdir"]) } + end + + def filter_backtrace(backtrace) + @filters.each do |f| + backtrace = backtrace.map { |line| f.call(line) } + end + + backtrace + end + + def silence(backtrace) + @silencers.each do |s| + backtrace = backtrace.reject { |line| s.call(line) } + end + + backtrace + end + + def noise(backtrace) + backtrace.select do |line| + @silencers.any? do |s| + s.call(line) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/benchmarkable.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/benchmarkable.rb new file mode 100644 index 0000000..4060784 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/benchmarkable.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require "active_support/core_ext/benchmark" +require "active_support/core_ext/hash/keys" + +module ActiveSupport + module Benchmarkable + # Allows you to measure the execution time of a block in a template and + # records the result to the log. Wrap this block around expensive operations + # or possible bottlenecks to get a time reading for the operation. For + # example, let's say you thought your file processing method was taking too + # long; you could wrap it in a benchmark block. + # + # <% benchmark 'Process data files' do %> + # <%= expensive_files_operation %> + # <% end %> + # + # That would add something like "Process data files (345.2ms)" to the log, + # which you can then use to compare timings when optimizing your code. + # + # You may give an optional logger level (:debug, :info, + # :warn, :error) as the :level option. The + # default logger level value is :info. + # + # <% benchmark 'Low-level files', level: :debug do %> + # <%= lowlevel_files_operation %> + # <% end %> + # + # Finally, you can pass true as the third argument to silence all log + # activity (other than the timing information) from inside the block. This + # is great for boiling down a noisy block to just a single statement that + # produces one log line: + # + # <% benchmark 'Process data files', level: :info, silence: true do %> + # <%= expensive_and_chatty_files_operation %> + # <% end %> + def benchmark(message = "Benchmarking", options = {}, &block) + if logger + options.assert_valid_keys(:level, :silence) + options[:level] ||= :info + + result = nil + ms = Benchmark.ms { result = options[:silence] ? logger.silence(&block) : yield } + logger.public_send(options[:level], "%s (%.1fms)" % [ message, ms ]) + result + else + yield + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/builder.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/builder.rb new file mode 100644 index 0000000..3fa7e6b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/builder.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +begin + require "builder" +rescue LoadError => e + $stderr.puts "You don't have builder installed in your application. Please add it to your Gemfile and run bundle install" + raise e +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache.rb new file mode 100644 index 0000000..0ec98fd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache.rb @@ -0,0 +1,1022 @@ +# frozen_string_literal: true + +require "zlib" +require "active_support/core_ext/array/extract_options" +require "active_support/core_ext/array/wrap" +require "active_support/core_ext/enumerable" +require "active_support/core_ext/module/attribute_accessors" +require "active_support/core_ext/numeric/bytes" +require "active_support/core_ext/numeric/time" +require "active_support/core_ext/object/to_param" +require "active_support/core_ext/object/try" +require "active_support/core_ext/string/inflections" + +module ActiveSupport + # See ActiveSupport::Cache::Store for documentation. + module Cache + autoload :FileStore, "active_support/cache/file_store" + autoload :MemoryStore, "active_support/cache/memory_store" + autoload :MemCacheStore, "active_support/cache/mem_cache_store" + autoload :NullStore, "active_support/cache/null_store" + autoload :RedisCacheStore, "active_support/cache/redis_cache_store" + + # These options mean something to all cache implementations. Individual cache + # implementations may support additional options. + UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :expire_in, :expired_in, :race_condition_ttl, :coder, :skip_nil] + + DEFAULT_COMPRESS_LIMIT = 1.kilobyte + + # Mapping of canonical option names to aliases that a store will recognize. + OPTION_ALIASES = { + expires_in: [:expire_in, :expired_in] + }.freeze + + module Strategy + autoload :LocalCache, "active_support/cache/strategy/local_cache" + end + + @format_version = 6.1 + + class << self + attr_accessor :format_version + + # Creates a new Store object according to the given options. + # + # If no arguments are passed to this method, then a new + # ActiveSupport::Cache::MemoryStore object will be returned. + # + # If you pass a Symbol as the first argument, then a corresponding cache + # store class under the ActiveSupport::Cache namespace will be created. + # For example: + # + # ActiveSupport::Cache.lookup_store(:memory_store) + # # => returns a new ActiveSupport::Cache::MemoryStore object + # + # ActiveSupport::Cache.lookup_store(:mem_cache_store) + # # => returns a new ActiveSupport::Cache::MemCacheStore object + # + # Any additional arguments will be passed to the corresponding cache store + # class's constructor: + # + # ActiveSupport::Cache.lookup_store(:file_store, '/tmp/cache') + # # => same as: ActiveSupport::Cache::FileStore.new('/tmp/cache') + # + # If the first argument is not a Symbol, then it will simply be returned: + # + # ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new) + # # => returns MyOwnCacheStore.new + def lookup_store(store = nil, *parameters) + case store + when Symbol + options = parameters.extract_options! + # clean this up once Ruby 2.7 support is dropped + # see https://github.com/rails/rails/pull/41522#discussion_r581186602 + if options.empty? + retrieve_store_class(store).new(*parameters) + else + retrieve_store_class(store).new(*parameters, **options) + end + when Array + lookup_store(*store) + when nil + ActiveSupport::Cache::MemoryStore.new + else + store + end + end + + # Expands out the +key+ argument into a key that can be used for the + # cache store. Optionally accepts a namespace, and all keys will be + # scoped within that namespace. + # + # If the +key+ argument provided is an array, or responds to +to_a+, then + # each of elements in the array will be turned into parameters/keys and + # concatenated into a single key. For example: + # + # ActiveSupport::Cache.expand_cache_key([:foo, :bar]) # => "foo/bar" + # ActiveSupport::Cache.expand_cache_key([:foo, :bar], "namespace") # => "namespace/foo/bar" + # + # The +key+ argument can also respond to +cache_key+ or +to_param+. + def expand_cache_key(key, namespace = nil) + expanded_cache_key = namespace ? +"#{namespace}/" : +"" + + if prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"] + expanded_cache_key << "#{prefix}/" + end + + expanded_cache_key << retrieve_cache_key(key) + expanded_cache_key + end + + private + def retrieve_cache_key(key) + case + when key.respond_to?(:cache_key_with_version) then key.cache_key_with_version + when key.respond_to?(:cache_key) then key.cache_key + when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param + when key.respond_to?(:to_a) then retrieve_cache_key(key.to_a) + else key.to_param + end.to_s + end + + # Obtains the specified cache store class, given the name of the +store+. + # Raises an error when the store class cannot be found. + def retrieve_store_class(store) + # require_relative cannot be used here because the class might be + # provided by another gem, like redis-activesupport for example. + require "active_support/cache/#{store}" + rescue LoadError => e + raise "Could not find cache store adapter for #{store} (#{e})" + else + ActiveSupport::Cache.const_get(store.to_s.camelize) + end + end + + # An abstract cache store class. There are multiple cache store + # implementations, each having its own additional features. See the classes + # under the ActiveSupport::Cache module, e.g. + # ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most + # popular cache store for large production websites. + # + # Some implementations may not support all methods beyond the basic cache + # methods of +fetch+, +write+, +read+, +exist?+, and +delete+. + # + # ActiveSupport::Cache::Store can store any serializable Ruby object. + # + # cache = ActiveSupport::Cache::MemoryStore.new + # + # cache.read('city') # => nil + # cache.write('city', "Duckburgh") + # cache.read('city') # => "Duckburgh" + # + # Keys are always translated into Strings and are case sensitive. When an + # object is specified as a key and has a +cache_key+ method defined, this + # method will be called to define the key. Otherwise, the +to_param+ + # method will be called. Hashes and Arrays can also be used as keys. The + # elements will be delimited by slashes, and the elements within a Hash + # will be sorted by key so they are consistent. + # + # cache.read('city') == cache.read(:city) # => true + # + # Nil values can be cached. + # + # If your cache is on a shared infrastructure, you can define a namespace + # for your cache entries. If a namespace is defined, it will be prefixed on + # to every key. The namespace can be either a static value or a Proc. If it + # is a Proc, it will be invoked when each key is evaluated so that you can + # use application logic to invalidate keys. + # + # cache.namespace = -> { @last_mod_time } # Set the namespace to a variable + # @last_mod_time = Time.now # Invalidate the entire cache by changing namespace + # + # Cached data larger than 1kB are compressed by default. To turn off + # compression, pass compress: false to the initializer or to + # individual +fetch+ or +write+ method calls. The 1kB compression + # threshold is configurable with the :compress_threshold option, + # specified in bytes. + class Store + cattr_accessor :logger, instance_writer: true + + attr_reader :silence, :options + alias :silence? :silence + + class << self + private + def retrieve_pool_options(options) + {}.tap do |pool_options| + pool_options[:size] = options.delete(:pool_size) if options[:pool_size] + pool_options[:timeout] = options.delete(:pool_timeout) if options[:pool_timeout] + end + end + + def ensure_connection_pool_added! + require "connection_pool" + rescue LoadError => e + $stderr.puts "You don't have connection_pool installed in your application. Please add it to your Gemfile and run bundle install" + raise e + end + end + + # Creates a new cache. The options will be passed to any write method calls + # except for :namespace which can be used to set the global + # namespace for the cache. + def initialize(options = nil) + @options = options ? normalize_options(options) : {} + @options[:compress] = true unless @options.key?(:compress) + @options[:compress_threshold] = DEFAULT_COMPRESS_LIMIT unless @options.key?(:compress_threshold) + + @coder = @options.delete(:coder) { default_coder } || NullCoder + @coder_supports_compression = @coder.respond_to?(:dump_compressed) + end + + # Silences the logger. + def silence! + @silence = true + self + end + + # Silences the logger within a block. + def mute + previous_silence, @silence = defined?(@silence) && @silence, true + yield + ensure + @silence = previous_silence + end + + # Fetches data from the cache, using the given key. If there is data in + # the cache with the given key, then that data is returned. + # + # If there is no such data in the cache (a cache miss), then +nil+ will be + # returned. However, if a block has been passed, that block will be passed + # the key and executed in the event of a cache miss. The return value of the + # block will be written to the cache under the given cache key, and that + # return value will be returned. + # + # cache.write('today', 'Monday') + # cache.fetch('today') # => "Monday" + # + # cache.fetch('city') # => nil + # cache.fetch('city') do + # 'Duckburgh' + # end + # cache.fetch('city') # => "Duckburgh" + # + # You may also specify additional options via the +options+ argument. + # Setting force: true forces a cache "miss," meaning we treat + # the cache value as missing even if it's present. Passing a block is + # required when +force+ is true so this always results in a cache write. + # + # cache.write('today', 'Monday') + # cache.fetch('today', force: true) { 'Tuesday' } # => 'Tuesday' + # cache.fetch('today', force: true) # => ArgumentError + # + # The +:force+ option is useful when you're calling some other method to + # ask whether you should force a cache write. Otherwise, it's clearer to + # just call Cache#write. + # + # Setting skip_nil: true will not cache nil result: + # + # cache.fetch('foo') { nil } + # cache.fetch('bar', skip_nil: true) { nil } + # cache.exist?('foo') # => true + # cache.exist?('bar') # => false + # + # + # Setting compress: false disables compression of the cache entry. + # + # Setting :expires_in will set an expiration time on the cache. + # All caches support auto-expiring content after a specified number of + # seconds. This value can be specified as an option to the constructor + # (in which case all entries will be affected), or it can be supplied to + # the +fetch+ or +write+ method to affect just one entry. + # :expire_in and :expired_in are aliases for + # :expires_in. + # + # cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes) + # cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry + # + # Setting :expires_at will set an absolute expiration time on the cache. + # All caches support auto-expiring content after a specified number of + # seconds. This value can only be supplied to the +fetch+ or +write+ method to + # affect just one entry. + # + # cache = ActiveSupport::Cache::MemoryStore.new + # cache.write(key, value, expires_at: Time.now.at_end_of_hour) + # + # Setting :version verifies the cache stored under name + # is of the same version. nil is returned on mismatches despite contents. + # This feature is used to support recyclable cache keys. + # + # Setting :race_condition_ttl is very useful in situations where + # a cache entry is used very frequently and is under heavy load. If a + # cache expires and due to heavy load several different processes will try + # to read data natively and then they all will try to write to cache. To + # avoid that case the first process to find an expired cache entry will + # bump the cache expiration time by the value set in :race_condition_ttl. + # Yes, this process is extending the time for a stale value by another few + # seconds. Because of extended life of the previous cache, other processes + # will continue to use slightly stale data for a just a bit longer. In the + # meantime that first process will go ahead and will write into cache the + # new value. After that all the processes will start getting the new value. + # The key is to keep :race_condition_ttl small. + # + # If the process regenerating the entry errors out, the entry will be + # regenerated after the specified number of seconds. Also note that the + # life of stale cache is extended only if it expired recently. Otherwise + # a new value is generated and :race_condition_ttl does not play + # any role. + # + # # Set all values to expire after one minute. + # cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute) + # + # cache.write('foo', 'original value') + # val_1 = nil + # val_2 = nil + # sleep 60 + # + # Thread.new do + # val_1 = cache.fetch('foo', race_condition_ttl: 10.seconds) do + # sleep 1 + # 'new value 1' + # end + # end + # + # Thread.new do + # val_2 = cache.fetch('foo', race_condition_ttl: 10.seconds) do + # 'new value 2' + # end + # end + # + # cache.fetch('foo') # => "original value" + # sleep 10 # First thread extended the life of cache by another 10 seconds + # cache.fetch('foo') # => "new value 1" + # val_1 # => "new value 1" + # val_2 # => "original value" + # + # Other options will be handled by the specific cache store implementation. + # Internally, #fetch calls #read_entry, and calls #write_entry on a cache + # miss. +options+ will be passed to the #read and #write calls. + # + # For example, MemCacheStore's #write method supports the +:raw+ + # option, which tells the memcached server to store all values as strings. + # We can use this option with #fetch too: + # + # cache = ActiveSupport::Cache::MemCacheStore.new + # cache.fetch("foo", force: true, raw: true) do + # :bar + # end + # cache.fetch('foo') # => "bar" + def fetch(name, options = nil, &block) + if block_given? + options = merged_options(options) + key = normalize_key(name, options) + + entry = nil + instrument(:read, name, options) do |payload| + cached_entry = read_entry(key, **options, event: payload) unless options[:force] + entry = handle_expired_entry(cached_entry, key, options) + entry = nil if entry && entry.mismatched?(normalize_version(name, options)) + payload[:super_operation] = :fetch if payload + payload[:hit] = !!entry if payload + end + + if entry + get_entry_value(entry, name, options) + else + save_block_result_to_cache(name, options, &block) + end + elsif options && options[:force] + raise ArgumentError, "Missing block: Calling `Cache#fetch` with `force: true` requires a block." + else + read(name, options) + end + end + + # Reads data from the cache, using the given key. If there is data in + # the cache with the given key, then that data is returned. Otherwise, + # +nil+ is returned. + # + # Note, if data was written with the :expires_in or + # :version options, both of these conditions are applied before + # the data is returned. + # + # Options are passed to the underlying cache implementation. + def read(name, options = nil) + options = merged_options(options) + key = normalize_key(name, options) + version = normalize_version(name, options) + + instrument(:read, name, options) do |payload| + entry = read_entry(key, **options, event: payload) + + if entry + if entry.expired? + delete_entry(key, **options) + payload[:hit] = false if payload + nil + elsif entry.mismatched?(version) + payload[:hit] = false if payload + nil + else + payload[:hit] = true if payload + entry.value + end + else + payload[:hit] = false if payload + nil + end + end + end + + # Reads multiple values at once from the cache. Options can be passed + # in the last argument. + # + # Some cache implementation may optimize this method. + # + # Returns a hash mapping the names provided to the values found. + def read_multi(*names) + options = names.extract_options! + options = merged_options(options) + + instrument :read_multi, names, options do |payload| + read_multi_entries(names, **options, event: payload).tap do |results| + payload[:hits] = results.keys + end + end + end + + # Cache Storage API to write multiple values at once. + def write_multi(hash, options = nil) + options = merged_options(options) + + instrument :write_multi, hash, options do |payload| + entries = hash.each_with_object({}) do |(name, value), memo| + memo[normalize_key(name, options)] = Entry.new(value, **options.merge(version: normalize_version(name, options))) + end + + write_multi_entries entries, **options + end + end + + # Fetches data from the cache, using the given keys. If there is data in + # the cache with the given keys, then that data is returned. Otherwise, + # the supplied block is called for each key for which there was no data, + # and the result will be written to the cache and returned. + # Therefore, you need to pass a block that returns the data to be written + # to the cache. If you do not want to write the cache when the cache is + # not found, use #read_multi. + # + # Returns a hash with the data for each of the names. For example: + # + # cache.write("bim", "bam") + # cache.fetch_multi("bim", "unknown_key") do |key| + # "Fallback value for key: #{key}" + # end + # # => { "bim" => "bam", + # # "unknown_key" => "Fallback value for key: unknown_key" } + # + # Options are passed to the underlying cache implementation. For example: + # + # cache.fetch_multi("fizz", expires_in: 5.seconds) do |key| + # "buzz" + # end + # # => {"fizz"=>"buzz"} + # cache.read("fizz") + # # => "buzz" + # sleep(6) + # cache.read("fizz") + # # => nil + def fetch_multi(*names) + raise ArgumentError, "Missing block: `Cache#fetch_multi` requires a block." unless block_given? + + options = names.extract_options! + options = merged_options(options) + + instrument :read_multi, names, options do |payload| + reads = read_multi_entries(names, **options) + writes = {} + ordered = names.index_with do |name| + reads.fetch(name) { writes[name] = yield(name) } + end + + payload[:hits] = reads.keys + payload[:super_operation] = :fetch_multi + + write_multi(writes, options) + + ordered + end + end + + # Writes the value to the cache, with the key. + # + # Options are passed to the underlying cache implementation. + def write(name, value, options = nil) + options = merged_options(options) + + instrument(:write, name, options) do + entry = Entry.new(value, **options.merge(version: normalize_version(name, options))) + write_entry(normalize_key(name, options), entry, **options) + end + end + + # Deletes an entry in the cache. Returns +true+ if an entry is deleted. + # + # Options are passed to the underlying cache implementation. + def delete(name, options = nil) + options = merged_options(options) + + instrument(:delete, name) do + delete_entry(normalize_key(name, options), **options) + end + end + + # Deletes multiple entries in the cache. + # + # Options are passed to the underlying cache implementation. + def delete_multi(names, options = nil) + options = merged_options(options) + names.map! { |key| normalize_key(key, options) } + + instrument :delete_multi, names do + delete_multi_entries(names, **options) + end + end + + # Returns +true+ if the cache contains an entry for the given key. + # + # Options are passed to the underlying cache implementation. + def exist?(name, options = nil) + options = merged_options(options) + + instrument(:exist?, name) do |payload| + entry = read_entry(normalize_key(name, options), **options, event: payload) + (entry && !entry.expired? && !entry.mismatched?(normalize_version(name, options))) || false + end + end + + def new_entry(value, options = nil) # :nodoc: + Entry.new(value, **merged_options(options)) + end + + # Deletes all entries with keys matching the pattern. + # + # Options are passed to the underlying cache implementation. + # + # Some implementations may not support this method. + def delete_matched(matcher, options = nil) + raise NotImplementedError.new("#{self.class.name} does not support delete_matched") + end + + # Increments an integer value in the cache. + # + # Options are passed to the underlying cache implementation. + # + # Some implementations may not support this method. + def increment(name, amount = 1, options = nil) + raise NotImplementedError.new("#{self.class.name} does not support increment") + end + + # Decrements an integer value in the cache. + # + # Options are passed to the underlying cache implementation. + # + # Some implementations may not support this method. + def decrement(name, amount = 1, options = nil) + raise NotImplementedError.new("#{self.class.name} does not support decrement") + end + + # Cleanups the cache by removing expired entries. + # + # Options are passed to the underlying cache implementation. + # + # Some implementations may not support this method. + def cleanup(options = nil) + raise NotImplementedError.new("#{self.class.name} does not support cleanup") + end + + # Clears the entire cache. Be careful with this method since it could + # affect other processes if shared cache is being used. + # + # The options hash is passed to the underlying cache implementation. + # + # Some implementations may not support this method. + def clear(options = nil) + raise NotImplementedError.new("#{self.class.name} does not support clear") + end + + private + def default_coder + Coders[Cache.format_version] + end + + # Adds the namespace defined in the options to a pattern designed to + # match keys. Implementations that support delete_matched should call + # this method to translate a pattern that matches names into one that + # matches namespaced keys. + def key_matcher(pattern, options) # :doc: + prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace] + if prefix + source = pattern.source + if source.start_with?("^") + source = source[1, source.length] + else + source = ".*#{source[0, source.length]}" + end + Regexp.new("^#{Regexp.escape(prefix)}:#{source}", pattern.options) + else + pattern + end + end + + # Reads an entry from the cache implementation. Subclasses must implement + # this method. + def read_entry(key, **options) + raise NotImplementedError.new + end + + # Writes an entry to the cache implementation. Subclasses must implement + # this method. + def write_entry(key, entry, **options) + raise NotImplementedError.new + end + + def serialize_entry(entry, **options) + options = merged_options(options) + if @coder_supports_compression && options[:compress] + @coder.dump_compressed(entry, options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT) + else + @coder.dump(entry) + end + end + + def deserialize_entry(payload) + payload.nil? ? nil : @coder.load(payload) + end + + # Reads multiple entries from the cache implementation. Subclasses MAY + # implement this method. + def read_multi_entries(names, **options) + names.each_with_object({}) do |name, results| + key = normalize_key(name, options) + entry = read_entry(key, **options) + + next unless entry + + version = normalize_version(name, options) + + if entry.expired? + delete_entry(key, **options) + elsif !entry.mismatched?(version) + results[name] = entry.value + end + end + end + + # Writes multiple entries to the cache implementation. Subclasses MAY + # implement this method. + def write_multi_entries(hash, **options) + hash.each do |key, entry| + write_entry key, entry, **options + end + end + + # Deletes an entry from the cache implementation. Subclasses must + # implement this method. + def delete_entry(key, **options) + raise NotImplementedError.new + end + + # Deletes multiples entries in the cache implementation. Subclasses MAY + # implement this method. + def delete_multi_entries(entries, **options) + entries.count { |key| delete_entry(key, **options) } + end + + # Merges the default options with ones specific to a method call. + def merged_options(call_options) + if call_options + call_options = normalize_options(call_options) + if options.empty? + call_options + else + options.merge(call_options) + end + else + options + end + end + + # Normalize aliased options to their canonical form + def normalize_options(options) + options = options.dup + OPTION_ALIASES.each do |canonical_name, aliases| + alias_key = aliases.detect { |key| options.key?(key) } + options[canonical_name] ||= options[alias_key] if alias_key + options.except!(*aliases) + end + + options + end + + # Expands and namespaces the cache key. May be overridden by + # cache stores to do additional normalization. + def normalize_key(key, options = nil) + namespace_key expanded_key(key), options + end + + # Prefix the key with a namespace string: + # + # namespace_key 'foo', namespace: 'cache' + # # => 'cache:foo' + # + # With a namespace block: + # + # namespace_key 'foo', namespace: -> { 'cache' } + # # => 'cache:foo' + def namespace_key(key, options = nil) + options = merged_options(options) + namespace = options[:namespace] + + if namespace.respond_to?(:call) + namespace = namespace.call + end + + if key && key.encoding != Encoding::UTF_8 + key = key.dup.force_encoding(Encoding::UTF_8) + end + + if namespace + "#{namespace}:#{key}" + else + key + end + end + + # Expands key to be a consistent string value. Invokes +cache_key+ if + # object responds to +cache_key+. Otherwise, +to_param+ method will be + # called. If the key is a Hash, then keys will be sorted alphabetically. + def expanded_key(key) + return key.cache_key.to_s if key.respond_to?(:cache_key) + + case key + when Array + if key.size > 1 + key.collect { |element| expanded_key(element) } + else + expanded_key(key.first) + end + when Hash + key.collect { |k, v| "#{k}=#{v}" }.sort! + else + key + end.to_param + end + + def normalize_version(key, options = nil) + (options && options[:version].try(:to_param)) || expanded_version(key) + end + + def expanded_version(key) + case + when key.respond_to?(:cache_version) then key.cache_version.to_param + when key.is_a?(Array) then key.map { |element| expanded_version(element) }.tap(&:compact!).to_param + when key.respond_to?(:to_a) then expanded_version(key.to_a) + end + end + + def instrument(operation, key, options = nil) + if logger && logger.debug? && !silence? + logger.debug "Cache #{operation}: #{normalize_key(key, options)}#{options.blank? ? "" : " (#{options.inspect})"}" + end + + payload = { key: key, store: self.class.name } + payload.merge!(options) if options.is_a?(Hash) + ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload) { yield(payload) } + end + + def handle_expired_entry(entry, key, options) + if entry && entry.expired? + race_ttl = options[:race_condition_ttl].to_i + if (race_ttl > 0) && (Time.now.to_f - entry.expires_at <= race_ttl) + # When an entry has a positive :race_condition_ttl defined, put the stale entry back into the cache + # for a brief period while the entry is being recalculated. + entry.expires_at = Time.now.to_f + race_ttl + write_entry(key, entry, expires_in: race_ttl * 2) + else + delete_entry(key, **options) + end + entry = nil + end + entry + end + + def get_entry_value(entry, name, options) + instrument(:fetch_hit, name, options) { } + entry.value + end + + def save_block_result_to_cache(name, options) + result = instrument(:generate, name, options) do + yield(name) + end + + write(name, result, options) unless result.nil? && options[:skip_nil] + result + end + end + + module NullCoder # :nodoc: + extend self + + def dump(entry) + entry + end + + def dump_compressed(entry, threshold) + entry.compressed(threshold) + end + + def load(payload) + payload + end + end + + module Coders # :nodoc: + MARK_61 = "\x04\b".b.freeze # The one set by Marshal. + MARK_70_UNCOMPRESSED = "\x00".b.freeze + MARK_70_COMPRESSED = "\x01".b.freeze + + class << self + def [](version) + case version + when 6.1 + Rails61Coder + when 7.0 + Rails70Coder + else + raise ArgumentError, "Unknown ActiveSupport::Cache.format_version #{Cache.format_version.inspect}" + end + end + end + + module Loader + extend self + + def load(payload) + if !payload.is_a?(String) + ActiveSupport::Cache::Store.logger&.warn %{Payload wasn't a string, was #{payload.class.name} - couldn't unmarshal, so returning nil."} + + return nil + elsif payload.start_with?(MARK_70_UNCOMPRESSED) + members = Marshal.load(payload.byteslice(1..-1)) + elsif payload.start_with?(MARK_70_COMPRESSED) + members = Marshal.load(Zlib::Inflate.inflate(payload.byteslice(1..-1))) + elsif payload.start_with?(MARK_61) + return Marshal.load(payload) + else + ActiveSupport::Cache::Store.logger&.warn %{Invalid cache prefix: #{payload.byteslice(0).inspect}, expected "\\x00" or "\\x01"} + + return nil + end + Entry.unpack(members) + end + end + + module Rails61Coder + include Loader + extend self + + def dump(entry) + Marshal.dump(entry) + end + + def dump_compressed(entry, threshold) + Marshal.dump(entry.compressed(threshold)) + end + end + + module Rails70Coder + include Loader + extend self + + def dump(entry) + MARK_70_UNCOMPRESSED + Marshal.dump(entry.pack) + end + + def dump_compressed(entry, threshold) + payload = Marshal.dump(entry.pack) + if payload.bytesize >= threshold + compressed_payload = Zlib::Deflate.deflate(payload) + if compressed_payload.bytesize < payload.bytesize + return MARK_70_COMPRESSED + compressed_payload + end + end + + MARK_70_UNCOMPRESSED + payload + end + end + end + + # This class is used to represent cache entries. Cache entries have a value, an optional + # expiration time, and an optional version. The expiration time is used to support the :race_condition_ttl option + # on the cache. The version is used to support the :version option on the cache for rejecting + # mismatches. + # + # Since cache entries in most instances will be serialized, the internals of this class are highly optimized + # using short instance variable names that are lazily defined. + class Entry # :nodoc: + class << self + def unpack(members) + new(members[0], expires_at: members[1], version: members[2]) + end + end + + attr_reader :version + + # Creates a new cache entry for the specified value. Options supported are + # +:compressed+, +:version+, +:expires_at+ and +:expires_in+. + def initialize(value, compressed: false, version: nil, expires_in: nil, expires_at: nil, **) + @value = value + @version = version + @created_at = 0.0 + @expires_in = expires_at&.to_f || expires_in && (expires_in.to_f + Time.now.to_f) + @compressed = true if compressed + end + + def value + compressed? ? uncompress(@value) : @value + end + + def mismatched?(version) + @version && version && @version != version + end + + # Checks if the entry is expired. The +expires_in+ parameter can override + # the value set when the entry was created. + def expired? + @expires_in && @created_at + @expires_in <= Time.now.to_f + end + + def expires_at + @expires_in ? @created_at + @expires_in : nil + end + + def expires_at=(value) + if value + @expires_in = value.to_f - @created_at + else + @expires_in = nil + end + end + + # Returns the size of the cached value. This could be less than + # value.bytesize if the data is compressed. + def bytesize + case value + when NilClass + 0 + when String + @value.bytesize + else + @s ||= Marshal.dump(@value).bytesize + end + end + + def compressed? # :nodoc: + defined?(@compressed) + end + + def compressed(compress_threshold) + return self if compressed? + + case @value + when nil, true, false, Numeric + uncompressed_size = 0 + when String + uncompressed_size = @value.bytesize + else + serialized = Marshal.dump(@value) + uncompressed_size = serialized.bytesize + end + + if uncompressed_size >= compress_threshold + serialized ||= Marshal.dump(@value) + compressed = Zlib::Deflate.deflate(serialized) + + if compressed.bytesize < uncompressed_size + return Entry.new(compressed, compressed: true, expires_at: expires_at, version: version) + end + end + self + end + + def local? + false + end + + # Duplicates the value in a class. This is used by cache implementations that don't natively + # serialize entries to protect against accidental cache modifications. + def dup_value! + if @value && !compressed? && !(@value.is_a?(Numeric) || @value == true || @value == false) + if @value.is_a?(String) + @value = @value.dup + else + @value = Marshal.load(Marshal.dump(@value)) + end + end + end + + def pack + members = [value, expires_at, version] + members.pop while !members.empty? && members.last.nil? + members + end + + private + def uncompress(value) + Marshal.load(Zlib::Inflate.inflate(value)) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/file_store.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/file_store.rb new file mode 100644 index 0000000..604ed82 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/file_store.rb @@ -0,0 +1,202 @@ +# frozen_string_literal: true + +require "active_support/core_ext/file/atomic" +require "active_support/core_ext/string/conversions" +require "uri/common" + +module ActiveSupport + module Cache + # A cache store implementation which stores everything on the filesystem. + # + # FileStore implements the Strategy::LocalCache strategy which implements + # an in-memory cache inside of a block. + class FileStore < Store + attr_reader :cache_path + + DIR_FORMATTER = "%03X" + FILENAME_MAX_SIZE = 226 # max filename size on file system is 255, minus room for timestamp, pid, and random characters appended by Tempfile (used by atomic write) + FILEPATH_MAX_SIZE = 900 # max is 1024, plus some room + GITKEEP_FILES = [".gitkeep", ".keep"].freeze + + def initialize(cache_path, **options) + super(options) + @cache_path = cache_path.to_s + end + + # Advertise cache versioning support. + def self.supports_cache_versioning? + true + end + + # Deletes all items from the cache. In this case it deletes all the entries in the specified + # file store directory except for .keep or .gitkeep. Be careful which directory is specified in your + # config file when using +FileStore+ because everything in that directory will be deleted. + def clear(options = nil) + root_dirs = (Dir.children(cache_path) - GITKEEP_FILES) + FileUtils.rm_r(root_dirs.collect { |f| File.join(cache_path, f) }) + rescue Errno::ENOENT, Errno::ENOTEMPTY + end + + # Preemptively iterates through all stored keys and removes the ones which have expired. + def cleanup(options = nil) + options = merged_options(options) + search_dir(cache_path) do |fname| + entry = read_entry(fname, **options) + delete_entry(fname, **options) if entry && entry.expired? + end + end + + # Increments an already existing integer value that is stored in the cache. + # If the key is not found nothing is done. + def increment(name, amount = 1, options = nil) + modify_value(name, amount, options) + end + + # Decrements an already existing integer value that is stored in the cache. + # If the key is not found nothing is done. + def decrement(name, amount = 1, options = nil) + modify_value(name, -amount, options) + end + + def delete_matched(matcher, options = nil) + options = merged_options(options) + instrument(:delete_matched, matcher.inspect) do + matcher = key_matcher(matcher, options) + search_dir(cache_path) do |path| + key = file_path_key(path) + delete_entry(path, **options) if key.match(matcher) + end + end + end + + private + def read_entry(key, **options) + if payload = read_serialized_entry(key, **options) + entry = deserialize_entry(payload) + entry if entry.is_a?(Cache::Entry) + end + end + + def read_serialized_entry(key, **) + File.binread(key) if File.exist?(key) + rescue => error + logger.error("FileStoreError (#{error}): #{error.message}") if logger + nil + end + + def write_entry(key, entry, **options) + write_serialized_entry(key, serialize_entry(entry, **options), **options) + end + + def write_serialized_entry(key, payload, **options) + return false if options[:unless_exist] && File.exist?(key) + ensure_cache_path(File.dirname(key)) + File.atomic_write(key, cache_path) { |f| f.write(payload) } + true + end + + def delete_entry(key, **options) + if File.exist?(key) + begin + File.delete(key) + delete_empty_directories(File.dirname(key)) + true + rescue + # Just in case the error was caused by another process deleting the file first. + raise if File.exist?(key) + false + end + end + end + + # Lock a file for a block so only one process can modify it at a time. + def lock_file(file_name, &block) + if File.exist?(file_name) + File.open(file_name, "r+") do |f| + f.flock File::LOCK_EX + yield + ensure + f.flock File::LOCK_UN + end + else + yield + end + end + + # Translate a key into a file path. + def normalize_key(key, options) + key = super + fname = URI.encode_www_form_component(key) + + if fname.size > FILEPATH_MAX_SIZE + fname = ActiveSupport::Digest.hexdigest(key) + end + + hash = Zlib.adler32(fname) + hash, dir_1 = hash.divmod(0x1000) + dir_2 = hash.modulo(0x1000) + + # Make sure file name doesn't exceed file system limits. + if fname.length < FILENAME_MAX_SIZE + fname_paths = fname + else + fname_paths = [] + begin + fname_paths << fname[0, FILENAME_MAX_SIZE] + fname = fname[FILENAME_MAX_SIZE..-1] + end until fname.blank? + end + + File.join(cache_path, DIR_FORMATTER % dir_1, DIR_FORMATTER % dir_2, fname_paths) + end + + # Translate a file path into a key. + def file_path_key(path) + fname = path[cache_path.to_s.size..-1].split(File::SEPARATOR, 4).last + URI.decode_www_form_component(fname, Encoding::UTF_8) + end + + # Delete empty directories in the cache. + def delete_empty_directories(dir) + return if File.realpath(dir) == File.realpath(cache_path) + if Dir.children(dir).empty? + Dir.delete(dir) rescue nil + delete_empty_directories(File.dirname(dir)) + end + end + + # Make sure a file path's directories exist. + def ensure_cache_path(path) + FileUtils.makedirs(path) unless File.exist?(path) + end + + def search_dir(dir, &callback) + return if !File.exist?(dir) + Dir.each_child(dir) do |d| + name = File.join(dir, d) + if File.directory?(name) + search_dir(name, &callback) + else + callback.call name + end + end + end + + # Modifies the amount of an already existing integer value that is stored in the cache. + # If the key is not found nothing is done. + def modify_value(name, amount, options) + file_name = normalize_key(name, options) + + lock_file(file_name) do + options = merged_options(options) + + if num = read(name, options) + num = num.to_i + amount + write(name, num, options) + num + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/mem_cache_store.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/mem_cache_store.rb new file mode 100644 index 0000000..6f3a8ec --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/mem_cache_store.rb @@ -0,0 +1,308 @@ +# frozen_string_literal: true + +begin + require "dalli" +rescue LoadError => e + $stderr.puts "You don't have dalli installed in your application. Please add it to your Gemfile and run bundle install" + raise e +end + +require "delegate" +require "active_support/core_ext/enumerable" +require "active_support/core_ext/array/extract_options" + +module ActiveSupport + module Cache + # A cache store implementation which stores data in Memcached: + # https://memcached.org + # + # This is currently the most popular cache store for production websites. + # + # Special features: + # - Clustering and load balancing. One can specify multiple memcached servers, + # and MemCacheStore will load balance between all available servers. If a + # server goes down, then MemCacheStore will ignore it until it comes back up. + # + # MemCacheStore implements the Strategy::LocalCache strategy which implements + # an in-memory cache inside of a block. + class MemCacheStore < Store + # Advertise cache versioning support. + def self.supports_cache_versioning? + true + end + + prepend Strategy::LocalCache + + module DupLocalCache + class DupLocalStore < DelegateClass(Strategy::LocalCache::LocalStore) + def write_entry(_key, entry) + if entry.is_a?(Entry) + entry.dup_value! + end + super + end + + def fetch_entry(key) + entry = super do + new_entry = yield + if entry.is_a?(Entry) + new_entry.dup_value! + end + new_entry + end + entry = entry.dup + + if entry.is_a?(Entry) + entry.dup_value! + end + + entry + end + end + + private + def local_cache + if ActiveSupport::Cache.format_version == 6.1 + if local_cache = super + DupLocalStore.new(local_cache) + end + else + super + end + end + end + prepend DupLocalCache + + ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/n + + # Creates a new Dalli::Client instance with specified addresses and options. + # If no addresses are provided, we give nil to Dalli::Client, so it uses its fallbacks: + # - ENV["MEMCACHE_SERVERS"] (if defined) + # - "127.0.0.1:11211" (otherwise) + # + # ActiveSupport::Cache::MemCacheStore.build_mem_cache + # # => # + # ActiveSupport::Cache::MemCacheStore.build_mem_cache('localhost:10290') + # # => # + def self.build_mem_cache(*addresses) # :nodoc: + addresses = addresses.flatten + options = addresses.extract_options! + addresses = nil if addresses.compact.empty? + pool_options = retrieve_pool_options(options) + + if pool_options.empty? + Dalli::Client.new(addresses, options) + else + ensure_connection_pool_added! + ConnectionPool.new(pool_options) { Dalli::Client.new(addresses, options.merge(threadsafe: false)) } + end + end + + # Creates a new MemCacheStore object, with the given memcached server + # addresses. Each address is either a host name, or a host-with-port string + # in the form of "host_name:port". For example: + # + # ActiveSupport::Cache::MemCacheStore.new("localhost", "server-downstairs.localnetwork:8229") + # + # If no addresses are provided, but ENV['MEMCACHE_SERVERS'] is defined, it will be used instead. Otherwise, + # MemCacheStore will connect to localhost:11211 (the default memcached port). + def initialize(*addresses) + addresses = addresses.flatten + options = addresses.extract_options! + if options.key?(:cache_nils) + options[:skip_nil] = !options.delete(:cache_nils) + end + super(options) + + unless [String, Dalli::Client, NilClass].include?(addresses.first.class) + raise ArgumentError, "First argument must be an empty array, an array of hosts or a Dalli::Client instance." + end + if addresses.first.is_a?(Dalli::Client) + @data = addresses.first + else + mem_cache_options = options.dup + # The value "compress: false" prevents duplicate compression within Dalli. + mem_cache_options[:compress] = false + (UNIVERSAL_OPTIONS - %i(compress)).each { |name| mem_cache_options.delete(name) } + @data = self.class.build_mem_cache(*(addresses + [mem_cache_options])) + end + end + + # Increment a cached value. This method uses the memcached incr atomic + # operator and can only be used on values written with the :raw option. + # Calling it on a value not stored with :raw will initialize that value + # to zero. + def increment(name, amount = 1, options = nil) + options = merged_options(options) + instrument(:increment, name, amount: amount) do + rescue_error_with nil do + @data.with { |c| c.incr(normalize_key(name, options), amount, options[:expires_in]) } + end + end + end + + # Decrement a cached value. This method uses the memcached decr atomic + # operator and can only be used on values written with the :raw option. + # Calling it on a value not stored with :raw will initialize that value + # to zero. + def decrement(name, amount = 1, options = nil) + options = merged_options(options) + instrument(:decrement, name, amount: amount) do + rescue_error_with nil do + @data.with { |c| c.decr(normalize_key(name, options), amount, options[:expires_in]) } + end + end + end + + # Clear the entire cache on all memcached servers. This method should + # be used with care when shared cache is being used. + def clear(options = nil) + rescue_error_with(nil) { @data.with { |c| c.flush_all } } + end + + # Get the statistics from the memcached servers. + def stats + @data.with { |c| c.stats } + end + + private + module Coders # :nodoc: + class << self + def [](version) + case version + when 6.1 + Rails61Coder + when 7.0 + Rails70Coder + else + raise ArgumentError, "Unknown ActiveSupport::Cache.format_version #{Cache.format_version.inspect}" + end + end + end + + module Loader + def load(payload) + if payload.is_a?(Entry) + payload + else + Cache::Coders::Loader.load(payload) + end + end + end + + module Rails61Coder + include Loader + extend self + + def dump(entry) + entry + end + + def dump_compressed(entry, threshold) + entry.compressed(threshold) + end + end + + module Rails70Coder + include Cache::Coders::Rails70Coder + include Loader + extend self + end + end + + def default_coder + Coders[Cache.format_version] + end + + # Read an entry from the cache. + def read_entry(key, **options) + deserialize_entry(read_serialized_entry(key, **options), **options) + end + + def read_serialized_entry(key, **options) + rescue_error_with(nil) do + @data.with { |c| c.get(key, options) } + end + end + + # Write an entry to the cache. + def write_entry(key, entry, **options) + write_serialized_entry(key, serialize_entry(entry, **options), **options) + end + + def write_serialized_entry(key, payload, **options) + method = options[:unless_exist] ? :add : :set + expires_in = options[:expires_in].to_i + if options[:race_condition_ttl] && expires_in > 0 && !options[:raw] + # Set the memcache expire a few minutes in the future to support race condition ttls on read + expires_in += 5.minutes + end + rescue_error_with false do + # Don't pass compress option to Dalli since we are already dealing with compression. + options.delete(:compress) + @data.with { |c| c.send(method, key, payload, expires_in, **options) } + end + end + + # Reads multiple entries from the cache implementation. + def read_multi_entries(names, **options) + keys_to_names = names.index_by { |name| normalize_key(name, options) } + + raw_values = @data.with { |c| c.get_multi(keys_to_names.keys) } + values = {} + + raw_values.each do |key, value| + entry = deserialize_entry(value, raw: options[:raw]) + + unless entry.expired? || entry.mismatched?(normalize_version(keys_to_names[key], options)) + values[keys_to_names[key]] = entry.value + end + end + + values + end + + # Delete an entry from the cache. + def delete_entry(key, **options) + rescue_error_with(false) { @data.with { |c| c.delete(key) } } + end + + def serialize_entry(entry, raw: false, **options) + if raw + entry.value.to_s + else + super(entry, raw: raw, **options) + end + end + + # Memcache keys are binaries. So we need to force their encoding to binary + # before applying the regular expression to ensure we are escaping all + # characters properly. + def normalize_key(key, options) + key = super + if key + key = key.dup.force_encoding(Encoding::ASCII_8BIT) + key = key.gsub(ESCAPE_KEY_CHARS) { |match| "%#{match.getbyte(0).to_s(16).upcase}" } + key = "#{key[0, 212]}:hash:#{ActiveSupport::Digest.hexdigest(key)}" if key.size > 250 + end + key + end + + def deserialize_entry(payload, raw: false, **) + if payload && raw + Entry.new(payload) + else + super(payload) + end + end + + def rescue_error_with(fallback) + yield + rescue Dalli::DalliError => error + ActiveSupport.error_reporter&.report(error, handled: true, severity: :warning) + logger.error("DalliError (#{error}): #{error.message}") if logger + fallback + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/memory_store.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/memory_store.rb new file mode 100644 index 0000000..04ce257 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/memory_store.rb @@ -0,0 +1,203 @@ +# frozen_string_literal: true + +require "monitor" + +module ActiveSupport + module Cache + # A cache store implementation which stores everything into memory in the + # same process. If you're running multiple Ruby on Rails server processes + # (which is the case if you're using Phusion Passenger or puma clustered mode), + # then this means that Rails server process instances won't be able + # to share cache data with each other and this may not be the most + # appropriate cache in that scenario. + # + # This cache has a bounded size specified by the :size options to the + # initializer (default is 32Mb). When the cache exceeds the allotted size, + # a cleanup will occur which tries to prune the cache down to three quarters + # of the maximum size by removing the least recently used entries. + # + # Unlike other Cache store implementations, MemoryStore does not compress + # values by default. MemoryStore does not benefit from compression as much + # as other Store implementations, as it does not send data over a network. + # However, when compression is enabled, it still pays the full cost of + # compression in terms of cpu use. + # + # MemoryStore is thread-safe. + class MemoryStore < Store + module DupCoder # :nodoc: + extend self + + def dump(entry) + entry.dup_value! unless entry.compressed? + entry + end + + def dump_compressed(entry, threshold) + entry = entry.compressed(threshold) + entry.dup_value! unless entry.compressed? + entry + end + + def load(entry) + entry = entry.dup + entry.dup_value! + entry + end + end + + def initialize(options = nil) + options ||= {} + # Disable compression by default. + options[:compress] ||= false + super(options) + @data = {} + @max_size = options[:size] || 32.megabytes + @max_prune_time = options[:max_prune_time] || 2 + @cache_size = 0 + @monitor = Monitor.new + @pruning = false + end + + # Advertise cache versioning support. + def self.supports_cache_versioning? + true + end + + # Delete all data stored in a given cache store. + def clear(options = nil) + synchronize do + @data.clear + @cache_size = 0 + end + end + + # Preemptively iterates through all stored keys and removes the ones which have expired. + def cleanup(options = nil) + options = merged_options(options) + instrument(:cleanup, size: @data.size) do + keys = synchronize { @data.keys } + keys.each do |key| + entry = @data[key] + delete_entry(key, **options) if entry && entry.expired? + end + end + end + + # To ensure entries fit within the specified memory prune the cache by removing the least + # recently accessed entries. + def prune(target_size, max_time = nil) + return if pruning? + @pruning = true + begin + start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) + cleanup + instrument(:prune, target_size, from: @cache_size) do + keys = synchronize { @data.keys } + keys.each do |key| + delete_entry(key, **options) + return if @cache_size <= target_size || (max_time && Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time > max_time) + end + end + ensure + @pruning = false + end + end + + # Returns true if the cache is currently being pruned. + def pruning? + @pruning + end + + # Increment an integer value in the cache. + def increment(name, amount = 1, options = nil) + modify_value(name, amount, options) + end + + # Decrement an integer value in the cache. + def decrement(name, amount = 1, options = nil) + modify_value(name, -amount, options) + end + + # Deletes cache entries if the cache key matches a given pattern. + def delete_matched(matcher, options = nil) + options = merged_options(options) + instrument(:delete_matched, matcher.inspect) do + matcher = key_matcher(matcher, options) + keys = synchronize { @data.keys } + keys.each do |key| + delete_entry(key, **options) if key.match(matcher) + end + end + end + + def inspect # :nodoc: + "#<#{self.class.name} entries=#{@data.size}, size=#{@cache_size}, options=#{@options.inspect}>" + end + + # Synchronize calls to the cache. This should be called wherever the underlying cache implementation + # is not thread safe. + def synchronize(&block) # :nodoc: + @monitor.synchronize(&block) + end + + private + PER_ENTRY_OVERHEAD = 240 + + def default_coder + DupCoder + end + + def cached_size(key, payload) + key.to_s.bytesize + payload.bytesize + PER_ENTRY_OVERHEAD + end + + def read_entry(key, **options) + entry = nil + synchronize do + payload = @data.delete(key) + if payload + @data[key] = payload + entry = deserialize_entry(payload) + end + end + entry + end + + def write_entry(key, entry, **options) + payload = serialize_entry(entry, **options) + synchronize do + return false if options[:unless_exist] && @data.key?(key) + + old_payload = @data[key] + if old_payload + @cache_size -= (old_payload.bytesize - payload.bytesize) + else + @cache_size += cached_size(key, payload) + end + @data[key] = payload + prune(@max_size * 0.75, @max_prune_time) if @cache_size > @max_size + true + end + end + + def delete_entry(key, **options) + synchronize do + payload = @data.delete(key) + @cache_size -= cached_size(key, payload) if payload + !!payload + end + end + + def modify_value(name, amount, options) + options = merged_options(options) + synchronize do + if num = read(name, options) + num = num.to_i + amount + write(name, num, options) + num + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/null_store.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/null_store.rb new file mode 100644 index 0000000..e840b26 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/null_store.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +module ActiveSupport + module Cache + # A cache store implementation which doesn't actually store anything. Useful in + # development and test environments where you don't want caching turned on but + # need to go through the caching interface. + # + # This cache does implement the local cache strategy, so values will actually + # be cached inside blocks that utilize this strategy. See + # ActiveSupport::Cache::Strategy::LocalCache for more details. + class NullStore < Store + prepend Strategy::LocalCache + + # Advertise cache versioning support. + def self.supports_cache_versioning? + true + end + + def clear(options = nil) + end + + def cleanup(options = nil) + end + + def increment(name, amount = 1, options = nil) + end + + def decrement(name, amount = 1, options = nil) + end + + def delete_matched(matcher, options = nil) + end + + private + def read_entry(key, **s) + deserialize_entry(read_serialized_entry(key)) + end + + def read_serialized_entry(_key, **) + end + + def write_entry(key, entry, **) + write_serialized_entry(key, serialize_entry(entry)) + end + + def write_serialized_entry(_key, _payload, **) + true + end + + def delete_entry(key, **options) + false + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/redis_cache_store.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/redis_cache_store.rb new file mode 100644 index 0000000..4809cd7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/redis_cache_store.rb @@ -0,0 +1,468 @@ +# frozen_string_literal: true + +begin + gem "redis", ">= 4.0.1" + require "redis" + require "redis/distributed" +rescue LoadError + warn "The Redis cache store requires the redis gem, version 4.0.1 or later. Please add it to your Gemfile: `gem \"redis\", \"~> 4.0\"`" + raise +end + +# Prefer the hiredis driver but don't require it. +begin + require "redis/connection/hiredis" +rescue LoadError +end + +require "active_support/digest" + +module ActiveSupport + module Cache + module ConnectionPoolLike + def with + yield self + end + end + + ::Redis.include(ConnectionPoolLike) + ::Redis::Distributed.include(ConnectionPoolLike) + + # Redis cache store. + # + # Deployment note: Take care to use a *dedicated Redis cache* rather + # than pointing this at your existing Redis server. It won't cope well + # with mixed usage patterns and it won't expire cache entries by default. + # + # Redis cache server setup guide: https://redis.io/topics/lru-cache + # + # * Supports vanilla Redis, hiredis, and Redis::Distributed. + # * Supports Memcached-like sharding across Redises with Redis::Distributed. + # * Fault tolerant. If the Redis server is unavailable, no exceptions are + # raised. Cache fetches are all misses and writes are dropped. + # * Local cache. Hot in-memory primary cache within block/middleware scope. + # * +read_multi+ and +write_multi+ support for Redis mget/mset. Use Redis::Distributed + # 4.0.1+ for distributed mget support. + # * +delete_matched+ support for Redis KEYS globs. + class RedisCacheStore < Store + # Keys are truncated with the ActiveSupport digest if they exceed 1kB + MAX_KEY_BYTESIZE = 1024 + + DEFAULT_REDIS_OPTIONS = { + connect_timeout: 20, + read_timeout: 1, + write_timeout: 1, + reconnect_attempts: 0, + } + + DEFAULT_ERROR_HANDLER = -> (method:, returning:, exception:) do + if logger + logger.error { "RedisCacheStore: #{method} failed, returned #{returning.inspect}: #{exception.class}: #{exception.message}" } + end + end + + # The maximum number of entries to receive per SCAN call. + SCAN_BATCH_SIZE = 1000 + private_constant :SCAN_BATCH_SIZE + + # Advertise cache versioning support. + def self.supports_cache_versioning? + true + end + + prepend Strategy::LocalCache + + class << self + # Factory method to create a new Redis instance. + # + # Handles four options: :redis block, :redis instance, single :url + # string, and multiple :url strings. + # + # Option Class Result + # :redis Proc -> options[:redis].call + # :redis Object -> options[:redis] + # :url String -> Redis.new(url: …) + # :url Array -> Redis::Distributed.new([{ url: … }, { url: … }, …]) + # + def build_redis(redis: nil, url: nil, **redis_options) # :nodoc: + urls = Array(url) + + if redis.is_a?(Proc) + redis.call + elsif redis + redis + elsif urls.size > 1 + build_redis_distributed_client urls: urls, **redis_options + else + build_redis_client url: urls.first, **redis_options + end + end + + private + def build_redis_distributed_client(urls:, **redis_options) + ::Redis::Distributed.new([], DEFAULT_REDIS_OPTIONS.merge(redis_options)).tap do |dist| + urls.each { |u| dist.add_node url: u } + end + end + + def build_redis_client(url:, **redis_options) + ::Redis.new DEFAULT_REDIS_OPTIONS.merge(redis_options.merge(url: url)) + end + end + + attr_reader :redis_options + attr_reader :max_key_bytesize + + # Creates a new Redis cache store. + # + # Handles four options: :redis block, :redis instance, single :url + # string, and multiple :url strings. + # + # Option Class Result + # :redis Proc -> options[:redis].call + # :redis Object -> options[:redis] + # :url String -> Redis.new(url: …) + # :url Array -> Redis::Distributed.new([{ url: … }, { url: … }, …]) + # + # No namespace is set by default. Provide one if the Redis cache + # server is shared with other apps: namespace: 'myapp-cache'. + # + # Compression is enabled by default with a 1kB threshold, so cached + # values larger than 1kB are automatically compressed. Disable by + # passing compress: false or change the threshold by passing + # compress_threshold: 4.kilobytes. + # + # No expiry is set on cache entries by default. Redis is expected to + # be configured with an eviction policy that automatically deletes + # least-recently or -frequently used keys when it reaches max memory. + # See https://redis.io/topics/lru-cache for cache server setup. + # + # Race condition TTL is not set by default. This can be used to avoid + # "thundering herd" cache writes when hot cache entries are expired. + # See ActiveSupport::Cache::Store#fetch for more. + def initialize(namespace: nil, compress: true, compress_threshold: 1.kilobyte, coder: default_coder, expires_in: nil, race_condition_ttl: nil, error_handler: DEFAULT_ERROR_HANDLER, **redis_options) + @redis_options = redis_options + + @max_key_bytesize = MAX_KEY_BYTESIZE + @error_handler = error_handler + + super namespace: namespace, + compress: compress, compress_threshold: compress_threshold, + expires_in: expires_in, race_condition_ttl: race_condition_ttl, + coder: coder + end + + def redis + @redis ||= begin + pool_options = self.class.send(:retrieve_pool_options, redis_options) + + if pool_options.any? + self.class.send(:ensure_connection_pool_added!) + ::ConnectionPool.new(pool_options) { self.class.build_redis(**redis_options) } + else + self.class.build_redis(**redis_options) + end + end + end + + def inspect + instance = @redis || @redis_options + "#<#{self.class} options=#{options.inspect} redis=#{instance.inspect}>" + end + + # Cache Store API implementation. + # + # Read multiple values at once. Returns a hash of requested keys -> + # fetched values. + def read_multi(*names) + if mget_capable? + instrument(:read_multi, names, options) do |payload| + read_multi_mget(*names).tap do |results| + payload[:hits] = results.keys + end + end + else + super + end + end + + # Cache Store API implementation. + # + # Supports Redis KEYS glob patterns: + # + # h?llo matches hello, hallo and hxllo + # h*llo matches hllo and heeeello + # h[ae]llo matches hello and hallo, but not hillo + # h[^e]llo matches hallo, hbllo, ... but not hello + # h[a-b]llo matches hallo and hbllo + # + # Use \ to escape special characters if you want to match them verbatim. + # + # See https://redis.io/commands/KEYS for more. + # + # Failsafe: Raises errors. + def delete_matched(matcher, options = nil) + instrument :delete_matched, matcher do + unless String === matcher + raise ArgumentError, "Only Redis glob strings are supported: #{matcher.inspect}" + end + redis.with do |c| + pattern = namespace_key(matcher, options) + cursor = "0" + # Fetch keys in batches using SCAN to avoid blocking the Redis server. + nodes = c.respond_to?(:nodes) ? c.nodes : [c] + + nodes.each do |node| + begin + cursor, keys = node.scan(cursor, match: pattern, count: SCAN_BATCH_SIZE) + node.del(*keys) unless keys.empty? + end until cursor == "0" + end + end + end + end + + # Cache Store API implementation. + # + # Increment a cached value. This method uses the Redis incr atomic + # operator and can only be used on values written with the :raw option. + # Calling it on a value not stored with :raw will initialize that value + # to zero. + # + # Failsafe: Raises errors. + def increment(name, amount = 1, options = nil) + instrument :increment, name, amount: amount do + failsafe :increment do + options = merged_options(options) + key = normalize_key(name, options) + + redis.with do |c| + c.incrby(key, amount).tap do + write_key_expiry(c, key, options) + end + end + end + end + end + + # Cache Store API implementation. + # + # Decrement a cached value. This method uses the Redis decr atomic + # operator and can only be used on values written with the :raw option. + # Calling it on a value not stored with :raw will initialize that value + # to zero. + # + # Failsafe: Raises errors. + def decrement(name, amount = 1, options = nil) + instrument :decrement, name, amount: amount do + failsafe :decrement do + options = merged_options(options) + key = normalize_key(name, options) + + redis.with do |c| + c.decrby(key, amount).tap do + write_key_expiry(c, key, options) + end + end + end + end + end + + # Cache Store API implementation. + # + # Removes expired entries. Handled natively by Redis least-recently-/ + # least-frequently-used expiry, so manual cleanup is not supported. + def cleanup(options = nil) + super + end + + # Clear the entire cache on all Redis servers. Safe to use on + # shared servers if the cache is namespaced. + # + # Failsafe: Raises errors. + def clear(options = nil) + failsafe :clear do + if namespace = merged_options(options)[:namespace] + delete_matched "*", namespace: namespace + else + redis.with { |c| c.flushdb } + end + end + end + + # Get info from redis servers. + def stats + redis.with { |c| c.info } + end + + def mget_capable? # :nodoc: + set_redis_capabilities unless defined? @mget_capable + @mget_capable + end + + def mset_capable? # :nodoc: + set_redis_capabilities unless defined? @mset_capable + @mset_capable + end + + private + def set_redis_capabilities + case redis + when Redis::Distributed + @mget_capable = true + @mset_capable = false + else + @mget_capable = true + @mset_capable = true + end + end + + # Store provider interface: + # Read an entry from the cache. + def read_entry(key, **options) + deserialize_entry(read_serialized_entry(key, **options), **options) + end + + def read_serialized_entry(key, raw: false, **options) + failsafe :read_entry do + redis.with { |c| c.get(key) } + end + end + + def read_multi_entries(names, **options) + if mget_capable? + read_multi_mget(*names, **options) + else + super + end + end + + def read_multi_mget(*names) + options = names.extract_options! + options = merged_options(options) + return {} if names == [] + raw = options&.fetch(:raw, false) + + keys = names.map { |name| normalize_key(name, options) } + + values = failsafe(:read_multi_mget, returning: {}) do + redis.with { |c| c.mget(*keys) } + end + + names.zip(values).each_with_object({}) do |(name, value), results| + if value + entry = deserialize_entry(value, raw: raw) + unless entry.nil? || entry.expired? || entry.mismatched?(normalize_version(name, options)) + results[name] = entry.value + end + end + end + end + + # Write an entry to the cache. + # + # Requires Redis 2.6.12+ for extended SET options. + def write_entry(key, entry, raw: false, **options) + write_serialized_entry(key, serialize_entry(entry, raw: raw, **options), raw: raw, **options) + end + + def write_serialized_entry(key, payload, raw: false, unless_exist: false, expires_in: nil, race_condition_ttl: nil, **options) + # If race condition TTL is in use, ensure that cache entries + # stick around a bit longer after they would have expired + # so we can purposefully serve stale entries. + if race_condition_ttl && expires_in && expires_in > 0 && !raw + expires_in += 5.minutes + end + + modifiers = {} + if unless_exist || expires_in + modifiers[:nx] = unless_exist + modifiers[:px] = (1000 * expires_in.to_f).ceil if expires_in + end + + failsafe :write_entry, returning: false do + redis.with { |c| c.set key, payload, **modifiers } + end + end + + def write_key_expiry(client, key, options) + if options[:expires_in] && client.ttl(key).negative? + client.expire key, options[:expires_in].to_i + end + end + + # Delete an entry from the cache. + def delete_entry(key, options) + failsafe :delete_entry, returning: false do + redis.with { |c| c.del key } + end + end + + # Deletes multiple entries in the cache. Returns the number of entries deleted. + def delete_multi_entries(entries, **_options) + redis.with { |c| c.del(entries) } + end + + # Nonstandard store provider API to write multiple values at once. + def write_multi_entries(entries, expires_in: nil, **options) + if entries.any? + if mset_capable? && expires_in.nil? + failsafe :write_multi_entries do + payload = serialize_entries(entries, **options) + redis.with do |c| + c.mapped_mset(payload) + end + end + else + super + end + end + end + + # Truncate keys that exceed 1kB. + def normalize_key(key, options) + truncate_key super&.b + end + + def truncate_key(key) + if key && key.bytesize > max_key_bytesize + suffix = ":hash:#{ActiveSupport::Digest.hexdigest(key)}" + truncate_at = max_key_bytesize - suffix.bytesize + "#{key.byteslice(0, truncate_at)}#{suffix}" + else + key + end + end + + def deserialize_entry(payload, raw: false, **) + if raw && !payload.nil? + Entry.new(payload) + else + super(payload) + end + end + + def serialize_entry(entry, raw: false, **options) + if raw + entry.value.to_s + else + super(entry, raw: raw, **options) + end + end + + def serialize_entries(entries, **options) + entries.transform_values do |entry| + serialize_entry(entry, **options) + end + end + + def failsafe(method, returning: nil) + yield + rescue ::Redis::BaseError => error + ActiveSupport.error_reporter&.report(error, handled: true, severity: :warning) + @error_handler&.call(method: method, exception: error, returning: returning) + returning + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/strategy/local_cache.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/strategy/local_cache.rb new file mode 100644 index 0000000..0b2e0d7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/strategy/local_cache.rb @@ -0,0 +1,183 @@ +# frozen_string_literal: true + +require "active_support/core_ext/string/inflections" + +module ActiveSupport + module Cache + module Strategy + # Caches that implement LocalCache will be backed by an in-memory cache for the + # duration of a block. Repeated calls to the cache for the same key will hit the + # in-memory cache for faster access. + module LocalCache + autoload :Middleware, "active_support/cache/strategy/local_cache_middleware" + + # Class for storing and registering the local caches. + module LocalCacheRegistry # :nodoc: + extend self + + def cache_for(local_cache_key) + registry = ActiveSupport::IsolatedExecutionState[:active_support_local_cache_registry] ||= {} + registry[local_cache_key] + end + + def set_cache_for(local_cache_key, value) + registry = ActiveSupport::IsolatedExecutionState[:active_support_local_cache_registry] ||= {} + registry[local_cache_key] = value + end + end + + # Simple memory backed cache. This cache is not thread safe and is intended only + # for serving as a temporary memory cache for a single thread. + class LocalStore + def initialize + @data = {} + end + + def clear(options = nil) + @data.clear + end + + def read_entry(key) + @data[key] + end + + def read_multi_entries(keys) + @data.slice(*keys) + end + + def write_entry(key, entry) + @data[key] = entry + true + end + + def delete_entry(key) + !!@data.delete(key) + end + + def fetch_entry(key) # :nodoc: + @data.fetch(key) { @data[key] = yield } + end + end + + # Use a local cache for the duration of block. + def with_local_cache(&block) + use_temporary_local_cache(LocalStore.new, &block) + end + + # Middleware class can be inserted as a Rack handler to be local cache for the + # duration of request. + def middleware + @middleware ||= Middleware.new( + "ActiveSupport::Cache::Strategy::LocalCache", + local_cache_key) + end + + def clear(**options) # :nodoc: + return super unless cache = local_cache + cache.clear(options) + super + end + + def cleanup(**options) # :nodoc: + return super unless cache = local_cache + cache.clear + super + end + + def delete_matched(matcher, options = nil) # :nodoc: + return super unless cache = local_cache + cache.clear + super + end + + def increment(name, amount = 1, **options) # :nodoc: + return super unless local_cache + value = bypass_local_cache { super } + write_cache_value(name, value, raw: true, **options) + value + end + + def decrement(name, amount = 1, **options) # :nodoc: + return super unless local_cache + value = bypass_local_cache { super } + write_cache_value(name, value, raw: true, **options) + value + end + + private + def read_serialized_entry(key, raw: false, **options) + if cache = local_cache + hit = true + entry = cache.fetch_entry(key) do + hit = false + super + end + options[:event][:store] = cache.class.name if hit && options[:event] + entry + else + super + end + end + + def read_multi_entries(keys, **options) + return super unless local_cache + + local_entries = local_cache.read_multi_entries(keys) + missed_keys = keys - local_entries.keys + + if missed_keys.any? + local_entries.merge!(super(missed_keys, **options)) + else + local_entries + end + end + + def write_serialized_entry(key, payload, **) + if return_value = super + local_cache.write_entry(key, payload) if local_cache + else + local_cache.delete_entry(key) if local_cache + end + return_value + end + + def delete_entry(key, **) + local_cache.delete_entry(key) if local_cache + super + end + + def write_cache_value(name, value, **options) + name = normalize_key(name, options) + cache = local_cache + if value + cache.write_entry(name, serialize_entry(new_entry(value, **options), **options)) + else + cache.delete_entry(name) + end + end + + def local_cache_key + @local_cache_key ||= "#{self.class.name.underscore}_local_cache_#{object_id}".gsub(/[\/-]/, "_").to_sym + end + + def local_cache + LocalCacheRegistry.cache_for(local_cache_key) + end + + def bypass_local_cache(&block) + use_temporary_local_cache(nil, &block) + end + + def use_temporary_local_cache(temporary_cache) + save_cache = LocalCacheRegistry.cache_for(local_cache_key) + begin + LocalCacheRegistry.set_cache_for(local_cache_key, temporary_cache) + yield + ensure + LocalCacheRegistry.set_cache_for(local_cache_key, save_cache) + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/strategy/local_cache_middleware.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/strategy/local_cache_middleware.rb new file mode 100644 index 0000000..62542bd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/cache/strategy/local_cache_middleware.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +require "rack/body_proxy" +require "rack/utils" + +module ActiveSupport + module Cache + module Strategy + module LocalCache + #-- + # This class wraps up local storage for middlewares. Only the middleware method should + # construct them. + class Middleware # :nodoc: + attr_reader :name, :local_cache_key + + def initialize(name, local_cache_key) + @name = name + @local_cache_key = local_cache_key + @app = nil + end + + def new(app) + @app = app + self + end + + def call(env) + LocalCacheRegistry.set_cache_for(local_cache_key, LocalStore.new) + response = @app.call(env) + response[2] = ::Rack::BodyProxy.new(response[2]) do + LocalCacheRegistry.set_cache_for(local_cache_key, nil) + end + cleanup_on_body_close = true + response + rescue Rack::Utils::InvalidParameterError + [400, {}, []] + ensure + LocalCacheRegistry.set_cache_for(local_cache_key, nil) unless + cleanup_on_body_close + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/callbacks.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/callbacks.rb new file mode 100644 index 0000000..c644d86 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/callbacks.rb @@ -0,0 +1,961 @@ +# frozen_string_literal: true + +require "active_support/concern" +require "active_support/descendants_tracker" +require "active_support/core_ext/array/extract_options" +require "active_support/core_ext/class/attribute" +require "active_support/core_ext/string/filters" +require "active_support/core_ext/object/blank" +require "thread" + +module ActiveSupport + # Callbacks are code hooks that are run at key points in an object's life cycle. + # The typical use case is to have a base class define a set of callbacks + # relevant to the other functionality it supplies, so that subclasses can + # install callbacks that enhance or modify the base functionality without + # needing to override or redefine methods of the base class. + # + # Mixing in this module allows you to define the events in the object's + # life cycle that will support callbacks (via +ClassMethods.define_callbacks+), + # set the instance methods, procs, or callback objects to be called (via + # +ClassMethods.set_callback+), and run the installed callbacks at the + # appropriate times (via +run_callbacks+). + # + # By default callbacks are halted by throwing +:abort+. + # See +ClassMethods.define_callbacks+ for details. + # + # Three kinds of callbacks are supported: before callbacks, run before a + # certain event; after callbacks, run after the event; and around callbacks, + # blocks that surround the event, triggering it when they yield. Callback code + # can be contained in instance methods, procs or lambdas, or callback objects + # that respond to certain predetermined methods. See +ClassMethods.set_callback+ + # for details. + # + # class Record + # include ActiveSupport::Callbacks + # define_callbacks :save + # + # def save + # run_callbacks :save do + # puts "- save" + # end + # end + # end + # + # class PersonRecord < Record + # set_callback :save, :before, :saving_message + # def saving_message + # puts "saving..." + # end + # + # set_callback :save, :after do |object| + # puts "saved" + # end + # end + # + # person = PersonRecord.new + # person.save + # + # Output: + # saving... + # - save + # saved + module Callbacks + extend Concern + + included do + extend ActiveSupport::DescendantsTracker + class_attribute :__callbacks, instance_writer: false, default: {} + end + + CALLBACK_FILTER_TYPES = [:before, :after, :around] + + # Runs the callbacks for the given event. + # + # Calls the before and around callbacks in the order they were set, yields + # the block (if given one), and then runs the after callbacks in reverse + # order. + # + # If the callback chain was halted, returns +false+. Otherwise returns the + # result of the block, +nil+ if no callbacks have been set, or +true+ + # if callbacks have been set but no block is given. + # + # run_callbacks :save do + # save + # end + # + #-- + # + # As this method is used in many places, and often wraps large portions of + # user code, it has an additional design goal of minimizing its impact on + # the visible call stack. An exception from inside a :before or :after + # callback can be as noisy as it likes -- but when control has passed + # smoothly through and into the supplied block, we want as little evidence + # as possible that we were here. + def run_callbacks(kind) + callbacks = __callbacks[kind.to_sym] + + if callbacks.empty? + yield if block_given? + else + env = Filters::Environment.new(self, false, nil) + next_sequence = callbacks.compile + + # Common case: no 'around' callbacks defined + if next_sequence.final? + next_sequence.invoke_before(env) + env.value = !env.halted && (!block_given? || yield) + next_sequence.invoke_after(env) + env.value + else + invoke_sequence = Proc.new do + skipped = nil + + while true + current = next_sequence + current.invoke_before(env) + if current.final? + env.value = !env.halted && (!block_given? || yield) + elsif current.skip?(env) + (skipped ||= []) << current + next_sequence = next_sequence.nested + next + else + next_sequence = next_sequence.nested + begin + target, block, method, *arguments = current.expand_call_template(env, invoke_sequence) + target.send(method, *arguments, &block) + ensure + next_sequence = current + end + end + current.invoke_after(env) + skipped.pop.invoke_after(env) while skipped&.first + break env.value + end + end + + invoke_sequence.call + end + end + end + + private + # A hook invoked every time a before callback is halted. + # This can be overridden in ActiveSupport::Callbacks implementors in order + # to provide better debugging/logging. + def halted_callback_hook(filter, name) + end + + module Conditionals # :nodoc: + class Value + def initialize(&block) + @block = block + end + def call(target, value); @block.call(value); end + end + end + + module Filters + Environment = Struct.new(:target, :halted, :value) + + class Before + def self.build(callback_sequence, user_callback, user_conditions, chain_config, filter, name) + halted_lambda = chain_config[:terminator] + + if user_conditions.any? + halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter, name) + else + halting(callback_sequence, user_callback, halted_lambda, filter, name) + end + end + + def self.halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter, name) + callback_sequence.before do |env| + target = env.target + value = env.value + halted = env.halted + + if !halted && user_conditions.all? { |c| c.call(target, value) } + result_lambda = -> { user_callback.call target, value } + env.halted = halted_lambda.call(target, result_lambda) + if env.halted + target.send :halted_callback_hook, filter, name + end + end + + env + end + end + private_class_method :halting_and_conditional + + def self.halting(callback_sequence, user_callback, halted_lambda, filter, name) + callback_sequence.before do |env| + target = env.target + value = env.value + halted = env.halted + + unless halted + result_lambda = -> { user_callback.call target, value } + env.halted = halted_lambda.call(target, result_lambda) + if env.halted + target.send :halted_callback_hook, filter, name + end + end + + env + end + end + private_class_method :halting + end + + class After + def self.build(callback_sequence, user_callback, user_conditions, chain_config) + if chain_config[:skip_after_callbacks_if_terminated] + if user_conditions.any? + halting_and_conditional(callback_sequence, user_callback, user_conditions) + else + halting(callback_sequence, user_callback) + end + else + if user_conditions.any? + conditional callback_sequence, user_callback, user_conditions + else + simple callback_sequence, user_callback + end + end + end + + def self.halting_and_conditional(callback_sequence, user_callback, user_conditions) + callback_sequence.after do |env| + target = env.target + value = env.value + halted = env.halted + + if !halted && user_conditions.all? { |c| c.call(target, value) } + user_callback.call target, value + end + + env + end + end + private_class_method :halting_and_conditional + + def self.halting(callback_sequence, user_callback) + callback_sequence.after do |env| + unless env.halted + user_callback.call env.target, env.value + end + + env + end + end + private_class_method :halting + + def self.conditional(callback_sequence, user_callback, user_conditions) + callback_sequence.after do |env| + target = env.target + value = env.value + + if user_conditions.all? { |c| c.call(target, value) } + user_callback.call target, value + end + + env + end + end + private_class_method :conditional + + def self.simple(callback_sequence, user_callback) + callback_sequence.after do |env| + user_callback.call env.target, env.value + + env + end + end + private_class_method :simple + end + end + + class Callback # :nodoc:# + def self.build(chain, filter, kind, options) + if filter.is_a?(String) + raise ArgumentError, <<-MSG.squish + Passing string to define a callback is not supported. See the `.set_callback` + documentation to see supported values. + MSG + end + + new chain.name, filter, kind, options, chain.config + end + + attr_accessor :kind, :name + attr_reader :chain_config, :filter + + def initialize(name, filter, kind, options, chain_config) + @chain_config = chain_config + @name = name + @kind = kind + @filter = filter + @if = check_conditionals(options[:if]) + @unless = check_conditionals(options[:unless]) + end + + def merge_conditional_options(chain, if_option:, unless_option:) + options = { + if: @if.dup, + unless: @unless.dup + } + + options[:if].concat Array(unless_option) + options[:unless].concat Array(if_option) + + self.class.build chain, @filter, @kind, options + end + + def matches?(_kind, _filter) + @kind == _kind && filter == _filter + end + + def duplicates?(other) + case @filter + when Symbol + matches?(other.kind, other.filter) + else + false + end + end + + # Wraps code with filter + def apply(callback_sequence) + user_conditions = conditions_lambdas + user_callback = CallTemplate.build(@filter, self) + + case kind + when :before + Filters::Before.build(callback_sequence, user_callback.make_lambda, user_conditions, chain_config, @filter, name) + when :after + Filters::After.build(callback_sequence, user_callback.make_lambda, user_conditions, chain_config) + when :around + callback_sequence.around(user_callback, user_conditions) + end + end + + def current_scopes + Array(chain_config[:scope]).map { |s| public_send(s) } + end + + private + EMPTY_ARRAY = [].freeze + private_constant :EMPTY_ARRAY + + def check_conditionals(conditionals) + return EMPTY_ARRAY if conditionals.blank? + + conditionals = Array(conditionals) + if conditionals.any?(String) + raise ArgumentError, <<-MSG.squish + Passing string to be evaluated in :if and :unless conditional + options is not supported. Pass a symbol for an instance method, + or a lambda, proc or block, instead. + MSG + end + + conditionals.freeze + end + + def conditions_lambdas + @if.map { |c| CallTemplate.build(c, self).make_lambda } + + @unless.map { |c| CallTemplate.build(c, self).inverted_lambda } + end + end + + # A future invocation of user-supplied code (either as a callback, + # or a condition filter). + module CallTemplate # :nodoc: + class MethodCall + def initialize(method) + @method_name = method + end + + # Return the parts needed to make this call, with the given + # input values. + # + # Returns an array of the form: + # + # [target, block, method, *arguments] + # + # This array can be used as such: + # + # target.send(method, *arguments, &block) + # + # The actual invocation is left up to the caller to minimize + # call stack pollution. + def expand(target, value, block) + [target, block, @method_name] + end + + def make_lambda + lambda do |target, value, &block| + target.send(@method_name, &block) + end + end + + def inverted_lambda + lambda do |target, value, &block| + !target.send(@method_name, &block) + end + end + end + + class ObjectCall + def initialize(target, method) + @override_target = target + @method_name = method + end + + def expand(target, value, block) + [@override_target || target, block, @method_name, target] + end + + def make_lambda + lambda do |target, value, &block| + (@override_target || target).send(@method_name, target, &block) + end + end + + def inverted_lambda + lambda do |target, value, &block| + !(@override_target || target).send(@method_name, target, &block) + end + end + end + + class InstanceExec0 + def initialize(block) + @override_block = block + end + + def expand(target, value, block) + [target, @override_block, :instance_exec] + end + + def make_lambda + lambda do |target, value, &block| + target.instance_exec(&@override_block) + end + end + + def inverted_lambda + lambda do |target, value, &block| + !target.instance_exec(&@override_block) + end + end + end + + class InstanceExec1 + def initialize(block) + @override_block = block + end + + def expand(target, value, block) + [target, @override_block, :instance_exec, target] + end + + def make_lambda + lambda do |target, value, &block| + target.instance_exec(target, &@override_block) + end + end + + def inverted_lambda + lambda do |target, value, &block| + !target.instance_exec(target, &@override_block) + end + end + end + + class InstanceExec2 + def initialize(block) + @override_block = block + end + + def expand(target, value, block) + raise ArgumentError unless block + [target, @override_block || block, :instance_exec, target, block] + end + + def make_lambda + lambda do |target, value, &block| + raise ArgumentError unless block + target.instance_exec(target, block, &@override_block) + end + end + + def inverted_lambda + lambda do |target, value, &block| + raise ArgumentError unless block + !target.instance_exec(target, block, &@override_block) + end + end + end + + class ProcCall + def initialize(target) + @override_target = target + end + + def expand(target, value, block) + [@override_target || target, block, :call, target, value] + end + + def make_lambda + lambda do |target, value, &block| + (@override_target || target).call(target, value, &block) + end + end + + def inverted_lambda + lambda do |target, value, &block| + !(@override_target || target).call(target, value, &block) + end + end + end + + # Filters support: + # + # Symbols:: A method to call. + # Procs:: A proc to call with the object. + # Objects:: An object with a before_foo method on it to call. + # + # All of these objects are converted into a CallTemplate and handled + # the same after this point. + def self.build(filter, callback) + case filter + when Symbol + MethodCall.new(filter) + when Conditionals::Value + ProcCall.new(filter) + when ::Proc + if filter.arity > 1 + InstanceExec2.new(filter) + elsif filter.arity > 0 + InstanceExec1.new(filter) + else + InstanceExec0.new(filter) + end + else + ObjectCall.new(filter, callback.current_scopes.join("_").to_sym) + end + end + end + + # Execute before and after filters in a sequence instead of + # chaining them with nested lambda calls, see: + # https://github.com/rails/rails/issues/18011 + class CallbackSequence # :nodoc: + def initialize(nested = nil, call_template = nil, user_conditions = nil) + @nested = nested + @call_template = call_template + @user_conditions = user_conditions + + @before = [] + @after = [] + end + + def before(&before) + @before.unshift(before) + self + end + + def after(&after) + @after.push(after) + self + end + + def around(call_template, user_conditions) + CallbackSequence.new(self, call_template, user_conditions) + end + + def skip?(arg) + arg.halted || !@user_conditions.all? { |c| c.call(arg.target, arg.value) } + end + + attr_reader :nested + + def final? + !@call_template + end + + def expand_call_template(arg, block) + @call_template.expand(arg.target, arg.value, block) + end + + def invoke_before(arg) + @before.each { |b| b.call(arg) } + end + + def invoke_after(arg) + @after.each { |a| a.call(arg) } + end + end + + class CallbackChain # :nodoc:# + include Enumerable + + attr_reader :name, :config + + def initialize(name, config) + @name = name + @config = { + scope: [:kind], + terminator: default_terminator + }.merge!(config) + @chain = [] + @callbacks = nil + @mutex = Mutex.new + end + + def each(&block); @chain.each(&block); end + def index(o); @chain.index(o); end + def empty?; @chain.empty?; end + + def insert(index, o) + @callbacks = nil + @chain.insert(index, o) + end + + def delete(o) + @callbacks = nil + @chain.delete(o) + end + + def clear + @callbacks = nil + @chain.clear + self + end + + def initialize_copy(other) + @callbacks = nil + @chain = other.chain.dup + @mutex = Mutex.new + end + + def compile + @callbacks || @mutex.synchronize do + final_sequence = CallbackSequence.new + @callbacks ||= @chain.reverse.inject(final_sequence) do |callback_sequence, callback| + callback.apply callback_sequence + end + end + end + + def append(*callbacks) + callbacks.each { |c| append_one(c) } + end + + def prepend(*callbacks) + callbacks.each { |c| prepend_one(c) } + end + + protected + attr_reader :chain + + private + def append_one(callback) + @callbacks = nil + remove_duplicates(callback) + @chain.push(callback) + end + + def prepend_one(callback) + @callbacks = nil + remove_duplicates(callback) + @chain.unshift(callback) + end + + def remove_duplicates(callback) + @callbacks = nil + @chain.delete_if { |c| callback.duplicates?(c) } + end + + def default_terminator + Proc.new do |target, result_lambda| + terminate = true + catch(:abort) do + result_lambda.call + terminate = false + end + terminate + end + end + end + + module ClassMethods + def normalize_callback_params(filters, block) # :nodoc: + type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before + options = filters.extract_options! + filters.unshift(block) if block + [type, filters, options.dup] + end + + # This is used internally to append, prepend and skip callbacks to the + # CallbackChain. + def __update_callbacks(name) # :nodoc: + ([self] + self.descendants).reverse_each do |target| + chain = target.get_callbacks name + yield target, chain.dup + end + end + + # Install a callback for the given event. + # + # set_callback :save, :before, :before_method + # set_callback :save, :after, :after_method, if: :condition + # set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff } + # + # The second argument indicates whether the callback is to be run +:before+, + # +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This + # means the first example above can also be written as: + # + # set_callback :save, :before_method + # + # The callback can be specified as a symbol naming an instance method; as a + # proc, lambda, or block; or as an object that responds to a certain method + # determined by the :scope argument to +define_callbacks+. + # + # If a proc, lambda, or block is given, its body is evaluated in the context + # of the current object. It can also optionally accept the current object as + # an argument. + # + # Before and around callbacks are called in the order that they are set; + # after callbacks are called in the reverse order. + # + # Around callbacks can access the return value from the event, if it + # wasn't halted, from the +yield+ call. + # + # ===== Options + # + # * :if - A symbol or an array of symbols, each naming an instance + # method or a proc; the callback will be called only when they all return + # a true value. + # + # If a proc is given, its body is evaluated in the context of the + # current object. It can also optionally accept the current object as + # an argument. + # * :unless - A symbol or an array of symbols, each naming an + # instance method or a proc; the callback will be called only when they + # all return a false value. + # + # If a proc is given, its body is evaluated in the context of the + # current object. It can also optionally accept the current object as + # an argument. + # * :prepend - If +true+, the callback will be prepended to the + # existing chain rather than appended. + def set_callback(name, *filter_list, &block) + type, filters, options = normalize_callback_params(filter_list, block) + + self_chain = get_callbacks name + mapped = filters.map do |filter| + Callback.build(self_chain, filter, type, options) + end + + __update_callbacks(name) do |target, chain| + options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped) + target.set_callbacks name, chain + end + end + + # Skip a previously set callback. Like +set_callback+, :if or + # :unless options may be passed in order to control when the + # callback is skipped. + # + # class Writer < PersonRecord + # attr_accessor :age + # skip_callback :save, :before, :saving_message, if: -> { age > 18 } + # end + # + # When if option returns true, callback is skipped. + # + # writer = Writer.new + # writer.age = 20 + # writer.save + # + # Output: + # - save + # saved + # + # When if option returns false, callback is NOT skipped. + # + # young_writer = Writer.new + # young_writer.age = 17 + # young_writer.save + # + # Output: + # saving... + # - save + # saved + # + # An ArgumentError will be raised if the callback has not + # already been set (unless the :raise option is set to false). + def skip_callback(name, *filter_list, &block) + type, filters, options = normalize_callback_params(filter_list, block) + + options[:raise] = true unless options.key?(:raise) + + __update_callbacks(name) do |target, chain| + filters.each do |filter| + callback = chain.find { |c| c.matches?(type, filter) } + + if !callback && options[:raise] + raise ArgumentError, "#{type.to_s.capitalize} #{name} callback #{filter.inspect} has not been defined" + end + + if callback && (options.key?(:if) || options.key?(:unless)) + new_callback = callback.merge_conditional_options(chain, if_option: options[:if], unless_option: options[:unless]) + chain.insert(chain.index(callback), new_callback) + end + + chain.delete(callback) + end + target.set_callbacks name, chain + end + end + + # Remove all set callbacks for the given event. + def reset_callbacks(name) + callbacks = get_callbacks name + + self.descendants.each do |target| + chain = target.get_callbacks(name).dup + callbacks.each { |c| chain.delete(c) } + target.set_callbacks name, chain + end + + set_callbacks(name, callbacks.dup.clear) + end + + # Define sets of events in the object life cycle that support callbacks. + # + # define_callbacks :validate + # define_callbacks :initialize, :save, :destroy + # + # ===== Options + # + # * :terminator - Determines when a before filter will halt the + # callback chain, preventing following before and around callbacks from + # being called and the event from being triggered. + # This should be a lambda to be executed. + # The current object and the result lambda of the callback will be provided + # to the terminator lambda. + # + # define_callbacks :validate, terminator: ->(target, result_lambda) { result_lambda.call == false } + # + # In this example, if any before validate callbacks returns +false+, + # any successive before and around callback is not executed. + # + # The default terminator halts the chain when a callback throws +:abort+. + # + # * :skip_after_callbacks_if_terminated - Determines if after + # callbacks should be terminated by the :terminator option. By + # default after callbacks are executed no matter if callback chain was + # terminated or not. This option has no effect if :terminator + # option is set to +nil+. + # + # * :scope - Indicates which methods should be executed when an + # object is used as a callback. + # + # class Audit + # def before(caller) + # puts 'Audit: before is called' + # end + # + # def before_save(caller) + # puts 'Audit: before_save is called' + # end + # end + # + # class Account + # include ActiveSupport::Callbacks + # + # define_callbacks :save + # set_callback :save, :before, Audit.new + # + # def save + # run_callbacks :save do + # puts 'save in main' + # end + # end + # end + # + # In the above case whenever you save an account the method + # Audit#before will be called. On the other hand + # + # define_callbacks :save, scope: [:kind, :name] + # + # would trigger Audit#before_save instead. That's constructed + # by calling #{kind}_#{name} on the given instance. In this + # case "kind" is "before" and "name" is "save". In this context +:kind+ + # and +:name+ have special meanings: +:kind+ refers to the kind of + # callback (before/after/around) and +:name+ refers to the method on + # which callbacks are being defined. + # + # A declaration like + # + # define_callbacks :save, scope: [:name] + # + # would call Audit#save. + # + # ===== Notes + # + # +names+ passed to +define_callbacks+ must not end with + # !, ? or =. + # + # Calling +define_callbacks+ multiple times with the same +names+ will + # overwrite previous callbacks registered with +set_callback+. + def define_callbacks(*names) + options = names.extract_options! + + names.each do |name| + name = name.to_sym + + ([self] + self.descendants).each do |target| + target.set_callbacks name, CallbackChain.new(name, options) + end + + module_eval <<-RUBY, __FILE__, __LINE__ + 1 + def _run_#{name}_callbacks(&block) + run_callbacks #{name.inspect}, &block + end + + def self._#{name}_callbacks + get_callbacks(#{name.inspect}) + end + + def self._#{name}_callbacks=(value) + set_callbacks(#{name.inspect}, value) + end + + def _#{name}_callbacks + __callbacks[#{name.inspect}] + end + RUBY + end + end + + protected + def get_callbacks(name) # :nodoc: + __callbacks[name.to_sym] + end + + def set_callbacks(name, callbacks) # :nodoc: + unless singleton_class.method_defined?(:__callbacks, false) + self.__callbacks = __callbacks.dup + end + self.__callbacks[name.to_sym] = callbacks + self.__callbacks + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/code_generator.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/code_generator.rb new file mode 100644 index 0000000..46f612d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/code_generator.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +module ActiveSupport + class CodeGenerator # :nodoc: + class MethodSet + METHOD_CACHES = Hash.new { |h, k| h[k] = Module.new } + + def initialize(namespace) + @cache = METHOD_CACHES[namespace] + @sources = [] + @methods = {} + end + + def define_cached_method(name, as: name) + name = name.to_sym + as = as.to_sym + @methods.fetch(name) do + unless @cache.method_defined?(as) + yield @sources + end + @methods[name] = as + end + end + + def apply(owner, path, line) + unless @sources.empty? + @cache.module_eval("# frozen_string_literal: true\n" + @sources.join(";"), path, line) + end + @methods.each do |name, as| + owner.define_method(name, @cache.instance_method(as)) + end + end + end + + class << self + def batch(owner, path, line) + if owner.is_a?(CodeGenerator) + yield owner + else + instance = new(owner, path, line) + result = yield instance + instance.execute + result + end + end + end + + def initialize(owner, path, line) + @owner = owner + @path = path + @line = line + @namespaces = Hash.new { |h, k| h[k] = MethodSet.new(k) } + end + + def define_cached_method(name, namespace:, as: name, &block) + @namespaces[namespace].define_cached_method(name, as: as, &block) + end + + def execute + @namespaces.each_value do |method_set| + method_set.apply(@owner, @path, @line - 1) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/concern.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/concern.rb new file mode 100644 index 0000000..9511338 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/concern.rb @@ -0,0 +1,215 @@ +# frozen_string_literal: true + +module ActiveSupport + # A typical module looks like this: + # + # module M + # def self.included(base) + # base.extend ClassMethods + # base.class_eval do + # scope :disabled, -> { where(disabled: true) } + # end + # end + # + # module ClassMethods + # ... + # end + # end + # + # By using ActiveSupport::Concern the above module could instead be + # written as: + # + # require "active_support/concern" + # + # module M + # extend ActiveSupport::Concern + # + # included do + # scope :disabled, -> { where(disabled: true) } + # end + # + # class_methods do + # ... + # end + # end + # + # Moreover, it gracefully handles module dependencies. Given a +Foo+ module + # and a +Bar+ module which depends on the former, we would typically write the + # following: + # + # module Foo + # def self.included(base) + # base.class_eval do + # def self.method_injected_by_foo + # ... + # end + # end + # end + # end + # + # module Bar + # def self.included(base) + # base.method_injected_by_foo + # end + # end + # + # class Host + # include Foo # We need to include this dependency for Bar + # include Bar # Bar is the module that Host really needs + # end + # + # But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We + # could try to hide these from +Host+ directly including +Foo+ in +Bar+: + # + # module Bar + # include Foo + # def self.included(base) + # base.method_injected_by_foo + # end + # end + # + # class Host + # include Bar + # end + # + # Unfortunately this won't work, since when +Foo+ is included, its base + # is the +Bar+ module, not the +Host+ class. With ActiveSupport::Concern, + # module dependencies are properly resolved: + # + # require "active_support/concern" + # + # module Foo + # extend ActiveSupport::Concern + # included do + # def self.method_injected_by_foo + # ... + # end + # end + # end + # + # module Bar + # extend ActiveSupport::Concern + # include Foo + # + # included do + # self.method_injected_by_foo + # end + # end + # + # class Host + # include Bar # It works, now Bar takes care of its dependencies + # end + # + # === Prepending concerns + # + # Just like include, concerns also support prepend with a corresponding + # prepended do callback. module ClassMethods or class_methods do are + # prepended as well. + # + # prepend is also used for any dependencies. + module Concern + class MultipleIncludedBlocks < StandardError # :nodoc: + def initialize + super "Cannot define multiple 'included' blocks for a Concern" + end + end + + class MultiplePrependBlocks < StandardError # :nodoc: + def initialize + super "Cannot define multiple 'prepended' blocks for a Concern" + end + end + + def self.extended(base) # :nodoc: + base.instance_variable_set(:@_dependencies, []) + end + + def append_features(base) # :nodoc: + if base.instance_variable_defined?(:@_dependencies) + base.instance_variable_get(:@_dependencies) << self + false + else + return false if base < self + @_dependencies.each { |dep| base.include(dep) } + super + base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods) + base.class_eval(&@_included_block) if instance_variable_defined?(:@_included_block) + end + end + + def prepend_features(base) # :nodoc: + if base.instance_variable_defined?(:@_dependencies) + base.instance_variable_get(:@_dependencies).unshift self + false + else + return false if base < self + @_dependencies.each { |dep| base.prepend(dep) } + super + base.singleton_class.prepend const_get(:ClassMethods) if const_defined?(:ClassMethods) + base.class_eval(&@_prepended_block) if instance_variable_defined?(:@_prepended_block) + end + end + + # Evaluate given block in context of base class, + # so that you can write class macros here. + # When you define more than one +included+ block, it raises an exception. + def included(base = nil, &block) + if base.nil? + if instance_variable_defined?(:@_included_block) + if @_included_block.source_location != block.source_location + raise MultipleIncludedBlocks + end + else + @_included_block = block + end + else + super + end + end + + # Evaluate given block in context of base class, + # so that you can write class macros here. + # When you define more than one +prepended+ block, it raises an exception. + def prepended(base = nil, &block) + if base.nil? + if instance_variable_defined?(:@_prepended_block) + if @_prepended_block.source_location != block.source_location + raise MultiplePrependBlocks + end + else + @_prepended_block = block + end + else + super + end + end + + # Define class methods from given block. + # You can define private class methods as well. + # + # module Example + # extend ActiveSupport::Concern + # + # class_methods do + # def foo; puts 'foo'; end + # + # private + # def bar; puts 'bar'; end + # end + # end + # + # class Buzz + # include Example + # end + # + # Buzz.foo # => "foo" + # Buzz.bar # => private method 'bar' called for Buzz:Class(NoMethodError) + def class_methods(&class_methods_module_definition) + mod = const_defined?(:ClassMethods, false) ? + const_get(:ClassMethods) : + const_set(:ClassMethods, Module.new) + + mod.module_eval(&class_methods_module_definition) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/concurrency/load_interlock_aware_monitor.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/concurrency/load_interlock_aware_monitor.rb new file mode 100644 index 0000000..9af2bd9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/concurrency/load_interlock_aware_monitor.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +require "monitor" + +module ActiveSupport + module Concurrency + # A monitor that will permit dependency loading while blocked waiting for + # the lock. + class LoadInterlockAwareMonitor < Monitor + EXCEPTION_NEVER = { Exception => :never }.freeze + EXCEPTION_IMMEDIATE = { Exception => :immediate }.freeze + private_constant :EXCEPTION_NEVER, :EXCEPTION_IMMEDIATE + + # Enters an exclusive section, but allows dependency loading while blocked + def mon_enter + mon_try_enter || + ActiveSupport::Dependencies.interlock.permit_concurrent_loads { super } + end + + def synchronize(&block) + Thread.handle_interrupt(EXCEPTION_NEVER) do + mon_enter + + begin + Thread.handle_interrupt(EXCEPTION_IMMEDIATE, &block) + ensure + mon_exit + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/concurrency/share_lock.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/concurrency/share_lock.rb new file mode 100644 index 0000000..fef87c7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/concurrency/share_lock.rb @@ -0,0 +1,226 @@ +# frozen_string_literal: true + +require "thread" +require "monitor" + +module ActiveSupport + module Concurrency + # A share/exclusive lock, otherwise known as a read/write lock. + # + # https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock + class ShareLock + include MonitorMixin + + # We track Thread objects, instead of just using counters, because + # we need exclusive locks to be reentrant, and we need to be able + # to upgrade share locks to exclusive. + + def raw_state # :nodoc: + synchronize do + threads = @sleeping.keys | @sharing.keys | @waiting.keys + threads |= [@exclusive_thread] if @exclusive_thread + + data = {} + + threads.each do |thread| + purpose, compatible = @waiting[thread] + + data[thread] = { + thread: thread, + sharing: @sharing[thread], + exclusive: @exclusive_thread == thread, + purpose: purpose, + compatible: compatible, + waiting: !!@waiting[thread], + sleeper: @sleeping[thread], + } + end + + # NB: Yields while holding our *internal* synchronize lock, + # which is supposed to be used only for a few instructions at + # a time. This allows the caller to inspect additional state + # without things changing out from underneath, but would have + # disastrous effects upon normal operation. Fortunately, this + # method is only intended to be called when things have + # already gone wrong. + yield data + end + end + + def initialize + super() + + @cv = new_cond + + @sharing = Hash.new(0) + @waiting = {} + @sleeping = {} + @exclusive_thread = nil + @exclusive_depth = 0 + end + + # Returns false if +no_wait+ is set and the lock is not + # immediately available. Otherwise, returns true after the lock + # has been acquired. + # + # +purpose+ and +compatible+ work together; while this thread is + # waiting for the exclusive lock, it will yield its share (if any) + # to any other attempt whose +purpose+ appears in this attempt's + # +compatible+ list. This allows a "loose" upgrade, which, being + # less strict, prevents some classes of deadlocks. + # + # For many resources, loose upgrades are sufficient: if a thread + # is awaiting a lock, it is not running any other code. With + # +purpose+ matching, it is possible to yield only to other + # threads whose activity will not interfere. + def start_exclusive(purpose: nil, compatible: [], no_wait: false) + synchronize do + unless @exclusive_thread == Thread.current + if busy_for_exclusive?(purpose) + return false if no_wait + + yield_shares(purpose: purpose, compatible: compatible, block_share: true) do + wait_for(:start_exclusive) { busy_for_exclusive?(purpose) } + end + end + @exclusive_thread = Thread.current + end + @exclusive_depth += 1 + + true + end + end + + # Relinquish the exclusive lock. Must only be called by the thread + # that called start_exclusive (and currently holds the lock). + def stop_exclusive(compatible: []) + synchronize do + raise "invalid unlock" if @exclusive_thread != Thread.current + + @exclusive_depth -= 1 + if @exclusive_depth == 0 + @exclusive_thread = nil + + if eligible_waiters?(compatible) + yield_shares(compatible: compatible, block_share: true) do + wait_for(:stop_exclusive) { @exclusive_thread || eligible_waiters?(compatible) } + end + end + @cv.broadcast + end + end + end + + def start_sharing + synchronize do + if @sharing[Thread.current] > 0 || @exclusive_thread == Thread.current + # We already hold a lock; nothing to wait for + elsif @waiting[Thread.current] + # We're nested inside a +yield_shares+ call: we'll resume as + # soon as there isn't an exclusive lock in our way + wait_for(:start_sharing) { @exclusive_thread } + else + # This is an initial / outermost share call: any outstanding + # requests for an exclusive lock get to go first + wait_for(:start_sharing) { busy_for_sharing?(false) } + end + @sharing[Thread.current] += 1 + end + end + + def stop_sharing + synchronize do + if @sharing[Thread.current] > 1 + @sharing[Thread.current] -= 1 + else + @sharing.delete Thread.current + @cv.broadcast + end + end + end + + # Execute the supplied block while holding the Exclusive lock. If + # +no_wait+ is set and the lock is not immediately available, + # returns +nil+ without yielding. Otherwise, returns the result of + # the block. + # + # See +start_exclusive+ for other options. + def exclusive(purpose: nil, compatible: [], after_compatible: [], no_wait: false) + if start_exclusive(purpose: purpose, compatible: compatible, no_wait: no_wait) + begin + yield + ensure + stop_exclusive(compatible: after_compatible) + end + end + end + + # Execute the supplied block while holding the Share lock. + def sharing + start_sharing + begin + yield + ensure + stop_sharing + end + end + + # Temporarily give up all held Share locks while executing the + # supplied block, allowing any +compatible+ exclusive lock request + # to proceed. + def yield_shares(purpose: nil, compatible: [], block_share: false) + loose_shares = previous_wait = nil + synchronize do + if loose_shares = @sharing.delete(Thread.current) + if previous_wait = @waiting[Thread.current] + purpose = nil unless purpose == previous_wait[0] + compatible &= previous_wait[1] + end + compatible |= [false] unless block_share + @waiting[Thread.current] = [purpose, compatible] + end + + @cv.broadcast + end + + begin + yield + ensure + synchronize do + wait_for(:yield_shares) { @exclusive_thread && @exclusive_thread != Thread.current } + + if previous_wait + @waiting[Thread.current] = previous_wait + else + @waiting.delete Thread.current + end + @sharing[Thread.current] = loose_shares if loose_shares + end + end + end + + private + # Must be called within synchronize + def busy_for_exclusive?(purpose) + busy_for_sharing?(purpose) || + @sharing.size > (@sharing[Thread.current] > 0 ? 1 : 0) + end + + def busy_for_sharing?(purpose) + (@exclusive_thread && @exclusive_thread != Thread.current) || + @waiting.any? { |t, (_, c)| t != Thread.current && !c.include?(purpose) } + end + + def eligible_waiters?(compatible) + @waiting.any? { |t, (p, _)| compatible.include?(p) && @waiting.all? { |t2, (_, c2)| t == t2 || c2.include?(p) } } + end + + def wait_for(method, &block) + @sleeping[Thread.current] = method + @cv.wait_while(&block) + ensure + @sleeping.delete Thread.current + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/configurable.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/configurable.rb new file mode 100644 index 0000000..a6ae8b3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/configurable.rb @@ -0,0 +1,149 @@ +# frozen_string_literal: true + +require "active_support/concern" +require "active_support/ordered_options" + +module ActiveSupport + # Configurable provides a config method to store and retrieve + # configuration options as an OrderedOptions. + module Configurable + extend ActiveSupport::Concern + + class Configuration < ActiveSupport::InheritableOptions + def compile_methods! + self.class.compile_methods!(keys) + end + + # Compiles reader methods so we don't have to go through method_missing. + def self.compile_methods!(keys) + keys.reject { |m| method_defined?(m) }.each do |key| + class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{key}; _get(#{key.inspect}); end + RUBY + end + end + end + + module ClassMethods + def config + @_config ||= if respond_to?(:superclass) && superclass.respond_to?(:config) + superclass.config.inheritable_copy + else + # create a new "anonymous" class that will host the compiled reader methods + Class.new(Configuration).new + end + end + + def configure + yield config + end + + # Allows you to add shortcut so that you don't have to refer to attribute + # through config. Also look at the example for config to contrast. + # + # Defines both class and instance config accessors. + # + # class User + # include ActiveSupport::Configurable + # config_accessor :allowed_access + # end + # + # User.allowed_access # => nil + # User.allowed_access = false + # User.allowed_access # => false + # + # user = User.new + # user.allowed_access # => false + # user.allowed_access = true + # user.allowed_access # => true + # + # User.allowed_access # => false + # + # The attribute name must be a valid method name in Ruby. + # + # class User + # include ActiveSupport::Configurable + # config_accessor :"1_Badname" + # end + # # => NameError: invalid config attribute name + # + # To omit the instance writer method, pass instance_writer: false. + # To omit the instance reader method, pass instance_reader: false. + # + # class User + # include ActiveSupport::Configurable + # config_accessor :allowed_access, instance_reader: false, instance_writer: false + # end + # + # User.allowed_access = false + # User.allowed_access # => false + # + # User.new.allowed_access = true # => NoMethodError + # User.new.allowed_access # => NoMethodError + # + # Or pass instance_accessor: false, to omit both instance methods. + # + # class User + # include ActiveSupport::Configurable + # config_accessor :allowed_access, instance_accessor: false + # end + # + # User.allowed_access = false + # User.allowed_access # => false + # + # User.new.allowed_access = true # => NoMethodError + # User.new.allowed_access # => NoMethodError + # + # Also you can pass default or a block to set up the attribute with a default value. + # + # class User + # include ActiveSupport::Configurable + # config_accessor :allowed_access, default: false + # config_accessor :hair_colors do + # [:brown, :black, :blonde, :red] + # end + # end + # + # User.allowed_access # => false + # User.hair_colors # => [:brown, :black, :blonde, :red] + def config_accessor(*names, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil) # :doc: + names.each do |name| + raise NameError.new("invalid config attribute name") unless /\A[_A-Za-z]\w*\z/.match?(name) + + reader, reader_line = "def #{name}; config.#{name}; end", __LINE__ + writer, writer_line = "def #{name}=(value); config.#{name} = value; end", __LINE__ + + singleton_class.class_eval reader, __FILE__, reader_line + singleton_class.class_eval writer, __FILE__, writer_line + + if instance_accessor + class_eval reader, __FILE__, reader_line if instance_reader + class_eval writer, __FILE__, writer_line if instance_writer + end + + send("#{name}=", block_given? ? yield : default) + end + end + private :config_accessor + end + + # Reads and writes attributes from a configuration OrderedOptions. + # + # require "active_support/configurable" + # + # class User + # include ActiveSupport::Configurable + # end + # + # user = User.new + # + # user.config.allowed_access = true + # user.config.level = 1 + # + # user.config.allowed_access # => true + # user.config.level # => 1 + def config + @_config ||= self.class.config.inheritable_copy + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/configuration_file.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/configuration_file.rb new file mode 100644 index 0000000..d025501 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/configuration_file.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +module ActiveSupport + # Reads a YAML configuration file, evaluating any ERB, then + # parsing the resulting YAML. + # + # Warns in case of YAML confusing characters, like invisible + # non-breaking spaces. + class ConfigurationFile # :nodoc: + class FormatError < StandardError; end + + def initialize(content_path) + @content_path = content_path.to_s + @content = read content_path + end + + def self.parse(content_path, **options) + new(content_path).parse(**options) + end + + def parse(context: nil, **options) + source = render(context) + if YAML.respond_to?(:unsafe_load) + YAML.unsafe_load(source, **options) || {} + else + YAML.load(source, **options) || {} + end + rescue Psych::SyntaxError => error + raise "YAML syntax error occurred while parsing #{@content_path}. " \ + "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \ + "Error: #{error.message}" + end + + private + def read(content_path) + require "yaml" + require "erb" + + File.read(content_path).tap do |content| + if content.include?("\u00A0") + warn "#{content_path} contains invisible non-breaking spaces, you may want to remove those" + end + end + end + + def render(context) + erb = ERB.new(@content).tap { |e| e.filename = @content_path } + context ? erb.result(context) : erb.result + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext.rb new file mode 100644 index 0000000..db2be98 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +Dir.glob(File.expand_path("core_ext/*.rb", __dir__)).sort.each do |path| + next if path.end_with?("core_ext/uri.rb") + require path +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array.rb new file mode 100644 index 0000000..81c9f69 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require "active_support/core_ext/array/wrap" +require "active_support/core_ext/array/access" +require "active_support/core_ext/array/conversions" +require "active_support/core_ext/array/deprecated_conversions" unless ENV["RAILS_DISABLE_DEPRECATED_TO_S_CONVERSION"] +require "active_support/core_ext/array/extract" +require "active_support/core_ext/array/extract_options" +require "active_support/core_ext/array/grouping" +require "active_support/core_ext/array/inquiry" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/access.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/access.rb new file mode 100644 index 0000000..8f36669 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/access.rb @@ -0,0 +1,100 @@ +# frozen_string_literal: true + +class Array + # Returns the tail of the array from +position+. + # + # %w( a b c d ).from(0) # => ["a", "b", "c", "d"] + # %w( a b c d ).from(2) # => ["c", "d"] + # %w( a b c d ).from(10) # => [] + # %w().from(0) # => [] + # %w( a b c d ).from(-2) # => ["c", "d"] + # %w( a b c ).from(-10) # => [] + def from(position) + self[position, length] || [] + end + + # Returns the beginning of the array up to +position+. + # + # %w( a b c d ).to(0) # => ["a"] + # %w( a b c d ).to(2) # => ["a", "b", "c"] + # %w( a b c d ).to(10) # => ["a", "b", "c", "d"] + # %w().to(0) # => [] + # %w( a b c d ).to(-2) # => ["a", "b", "c"] + # %w( a b c ).to(-10) # => [] + def to(position) + if position >= 0 + take position + 1 + else + self[0..position] + end + end + + # Returns a new array that includes the passed elements. + # + # [ 1, 2, 3 ].including(4, 5) # => [ 1, 2, 3, 4, 5 ] + # [ [ 0, 1 ] ].including([ [ 1, 0 ] ]) # => [ [ 0, 1 ], [ 1, 0 ] ] + def including(*elements) + self + elements.flatten(1) + end + + # Returns a copy of the Array excluding the specified elements. + # + # ["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"] + # [ [ 0, 1 ], [ 1, 0 ] ].excluding([ [ 1, 0 ] ]) # => [ [ 0, 1 ] ] + # + # Note: This is an optimization of Enumerable#excluding that uses Array#- + # instead of Array#reject for performance reasons. + def excluding(*elements) + self - elements.flatten(1) + end + alias :without :excluding + + # Equal to self[1]. + # + # %w( a b c d e ).second # => "b" + def second + self[1] + end + + # Equal to self[2]. + # + # %w( a b c d e ).third # => "c" + def third + self[2] + end + + # Equal to self[3]. + # + # %w( a b c d e ).fourth # => "d" + def fourth + self[3] + end + + # Equal to self[4]. + # + # %w( a b c d e ).fifth # => "e" + def fifth + self[4] + end + + # Equal to self[41]. Also known as accessing "the reddit". + # + # (1..42).to_a.forty_two # => 42 + def forty_two + self[41] + end + + # Equal to self[-3]. + # + # %w( a b c d e ).third_to_last # => "c" + def third_to_last + self[-3] + end + + # Equal to self[-2]. + # + # %w( a b c d e ).second_to_last # => "d" + def second_to_last + self[-2] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/conversions.rb new file mode 100644 index 0000000..77e5c60 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/conversions.rb @@ -0,0 +1,215 @@ +# frozen_string_literal: true + +require "active_support/xml_mini" +require "active_support/core_ext/hash/keys" +require "active_support/core_ext/string/inflections" +require "active_support/core_ext/object/to_param" +require "active_support/core_ext/object/to_query" + +class Array + # Converts the array to a comma-separated sentence where the last element is + # joined by the connector word. + # + # You can pass the following options to change the default behavior. If you + # pass an option key that doesn't exist in the list below, it will raise an + # ArgumentError. + # + # ==== Options + # + # * :words_connector - The sign or word used to join all but the last + # element in arrays with three or more elements (default: ", "). + # * :last_word_connector - The sign or word used to join the last element + # in arrays with three or more elements (default: ", and "). + # * :two_words_connector - The sign or word used to join the elements + # in arrays with two elements (default: " and "). + # * :locale - If +i18n+ is available, you can set a locale and use + # the connector options defined on the 'support.array' namespace in the + # corresponding dictionary file. + # + # ==== Examples + # + # [].to_sentence # => "" + # ['one'].to_sentence # => "one" + # ['one', 'two'].to_sentence # => "one and two" + # ['one', 'two', 'three'].to_sentence # => "one, two, and three" + # + # ['one', 'two'].to_sentence(passing: 'invalid option') + # # => ArgumentError: Unknown key: :passing. Valid keys are: :words_connector, :two_words_connector, :last_word_connector, :locale + # + # ['one', 'two'].to_sentence(two_words_connector: '-') + # # => "one-two" + # + # ['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ') + # # => "one or two or at least three" + # + # Using :locale option: + # + # # Given this locale dictionary: + # # + # # es: + # # support: + # # array: + # # words_connector: " o " + # # two_words_connector: " y " + # # last_word_connector: " o al menos " + # + # ['uno', 'dos'].to_sentence(locale: :es) + # # => "uno y dos" + # + # ['uno', 'dos', 'tres'].to_sentence(locale: :es) + # # => "uno o dos o al menos tres" + def to_sentence(options = {}) + options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale) + + default_connectors = { + words_connector: ", ", + two_words_connector: " and ", + last_word_connector: ", and " + } + if options[:locale] != false && defined?(I18n) + i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {}) + default_connectors.merge!(i18n_connectors) + end + options = default_connectors.merge!(options) + + case length + when 0 + +"" + when 1 + +"#{self[0]}" + when 2 + +"#{self[0]}#{options[:two_words_connector]}#{self[1]}" + else + +"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}" + end + end + + # Extends Array#to_s to convert a collection of elements into a + # comma separated id list if :db argument is given as the format. + # + # This method is aliased to to_formatted_s. + # + # Blog.all.to_fs(:db) # => "1,2,3" + # Blog.none.to_fs(:db) # => "null" + # [1,2].to_fs # => "[1, 2]" + def to_fs(format = :default) + case format + when :db + if empty? + "null" + else + collect(&:id).join(",") + end + else + to_default_s + end + end + alias_method :to_formatted_s, :to_fs + alias_method :to_default_s, :to_s + + # Returns a string that represents the array in XML by invoking +to_xml+ + # on each element. Active Record collections delegate their representation + # in XML to this method. + # + # All elements are expected to respond to +to_xml+, if any of them does + # not then an exception is raised. + # + # The root node reflects the class name of the first element in plural + # if all elements belong to the same type and that's not Hash: + # + # customer.projects.to_xml + # + # + # + # + # 20000.0 + # 1567 + # 2008-04-09 + # ... + # + # + # 57230.0 + # 1567 + # 2008-04-15 + # ... + # + # + # + # Otherwise the root element is "objects": + # + # [{ foo: 1, bar: 2}, { baz: 3}].to_xml + # + # + # + # + # 2 + # 1 + # + # + # 3 + # + # + # + # If the collection is empty the root element is "nil-classes" by default: + # + # [].to_xml + # + # + # + # + # To ensure a meaningful root element use the :root option: + # + # customer_with_no_projects.projects.to_xml(root: 'projects') + # + # + # + # + # By default name of the node for the children of root is root.singularize. + # You can change it with the :children option. + # + # The +options+ hash is passed downwards: + # + # Message.all.to_xml(skip_types: true) + # + # + # + # + # 2008-03-07T09:58:18+01:00 + # 1 + # 1 + # 2008-03-07T09:58:18+01:00 + # 1 + # + # + # + def to_xml(options = {}) + require "active_support/builder" unless defined?(Builder::XmlMarkup) + + options = options.dup + options[:indent] ||= 2 + options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent]) + options[:root] ||= \ + if first.class != Hash && all?(first.class) + underscored = ActiveSupport::Inflector.underscore(first.class.name) + ActiveSupport::Inflector.pluralize(underscored).tr("/", "_") + else + "objects" + end + + builder = options[:builder] + builder.instruct! unless options.delete(:skip_instruct) + + root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options) + children = options.delete(:children) || root.singularize + attributes = options[:skip_types] ? {} : { type: "array" } + + if empty? + builder.tag!(root, attributes) + else + builder.tag!(root, attributes) do + each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) } + yield builder if block_given? + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/deprecated_conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/deprecated_conversions.rb new file mode 100644 index 0000000..b2eabdf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/deprecated_conversions.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +class Array + NOT_SET = Object.new # :nodoc: + def to_s(format = NOT_SET) # :nodoc: + case format + when :db + ActiveSupport::Deprecation.warn( + "Array#to_s(#{format.inspect}) is deprecated. Please use Array#to_fs(#{format.inspect}) instead." + ) + if empty? + "null" + else + collect(&:id).join(",") + end + when NOT_SET + to_default_s + else + ActiveSupport::Deprecation.warn( + "Array#to_s(#{format.inspect}) is deprecated. Please use Array#to_fs(#{format.inspect}) instead." + ) + to_default_s + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/extract.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/extract.rb new file mode 100644 index 0000000..cc5a8a3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/extract.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +class Array + # Removes and returns the elements for which the block returns a true value. + # If no block is given, an Enumerator is returned instead. + # + # numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + # odd_numbers = numbers.extract! { |number| number.odd? } # => [1, 3, 5, 7, 9] + # numbers # => [0, 2, 4, 6, 8] + def extract! + return to_enum(:extract!) { size } unless block_given? + + extracted_elements = [] + + reject! do |element| + extracted_elements << element if yield(element) + end + + extracted_elements + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/extract_options.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/extract_options.rb new file mode 100644 index 0000000..8c7cb2e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/extract_options.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +class Hash + # By default, only instances of Hash itself are extractable. + # Subclasses of Hash may implement this method and return + # true to declare themselves as extractable. If a Hash + # is extractable, Array#extract_options! pops it from + # the Array when it is the last element of the Array. + def extractable_options? + instance_of?(Hash) + end +end + +class Array + # Extracts options from a set of arguments. Removes and returns the last + # element in the array if it's a hash, otherwise returns a blank hash. + # + # def options(*args) + # args.extract_options! + # end + # + # options(1, 2) # => {} + # options(1, 2, a: :b) # => {:a=>:b} + def extract_options! + if last.is_a?(Hash) && last.extractable_options? + pop + else + {} + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/grouping.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/grouping.rb new file mode 100644 index 0000000..36993e0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/grouping.rb @@ -0,0 +1,109 @@ +# frozen_string_literal: true + +class Array + # Splits or iterates over the array in groups of size +number+, + # padding any remaining slots with +fill_with+ unless it is +false+. + # + # %w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group} + # ["1", "2", "3"] + # ["4", "5", "6"] + # ["7", "8", "9"] + # ["10", nil, nil] + # + # %w(1 2 3 4 5).in_groups_of(2, ' ') {|group| p group} + # ["1", "2"] + # ["3", "4"] + # ["5", " "] + # + # %w(1 2 3 4 5).in_groups_of(2, false) {|group| p group} + # ["1", "2"] + # ["3", "4"] + # ["5"] + def in_groups_of(number, fill_with = nil, &block) + if number.to_i <= 0 + raise ArgumentError, + "Group size must be a positive integer, was #{number.inspect}" + end + + if fill_with == false + collection = self + else + # size % number gives how many extra we have; + # subtracting from number gives how many to add; + # modulo number ensures we don't add group of just fill. + padding = (number - size % number) % number + collection = dup.concat(Array.new(padding, fill_with)) + end + + if block_given? + collection.each_slice(number, &block) + else + collection.each_slice(number).to_a + end + end + + # Splits or iterates over the array in +number+ of groups, padding any + # remaining slots with +fill_with+ unless it is +false+. + # + # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group} + # ["1", "2", "3", "4"] + # ["5", "6", "7", nil] + # ["8", "9", "10", nil] + # + # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3, ' ') {|group| p group} + # ["1", "2", "3", "4"] + # ["5", "6", "7", " "] + # ["8", "9", "10", " "] + # + # %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group} + # ["1", "2", "3"] + # ["4", "5"] + # ["6", "7"] + def in_groups(number, fill_with = nil, &block) + # size.div number gives minor group size; + # size % number gives how many objects need extra accommodation; + # each group hold either division or division + 1 items. + division = size.div number + modulo = size % number + + # create a new array avoiding dup + groups = [] + start = 0 + + number.times do |index| + length = division + (modulo > 0 && modulo > index ? 1 : 0) + groups << last_group = slice(start, length) + last_group << fill_with if fill_with != false && + modulo > 0 && length == division + start += length + end + + if block_given? + groups.each(&block) + else + groups + end + end + + # Divides the array into one or more subarrays based on a delimiting +value+ + # or the result of an optional block. + # + # [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]] + # (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]] + def split(value = nil, &block) + arr = dup + result = [] + if block_given? + while (idx = arr.index(&block)) + result << arr.shift(idx) + arr.shift + end + else + while (idx = arr.index(value)) + result << arr.shift(idx) + arr.shift + end + end + result << arr + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/inquiry.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/inquiry.rb new file mode 100644 index 0000000..92c61bf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/inquiry.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +require "active_support/array_inquirer" + +class Array + # Wraps the array in an +ArrayInquirer+ object, which gives a friendlier way + # to check its string-like contents. + # + # pets = [:cat, :dog].inquiry + # + # pets.cat? # => true + # pets.ferret? # => false + # + # pets.any?(:cat, :ferret) # => true + # pets.any?(:ferret, :alligator) # => false + def inquiry + ActiveSupport::ArrayInquirer.new(self) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/wrap.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/wrap.rb new file mode 100644 index 0000000..d62f97e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/array/wrap.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +class Array + # Wraps its argument in an array unless it is already an array (or array-like). + # + # Specifically: + # + # * If the argument is +nil+ an empty array is returned. + # * Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned. + # * Otherwise, returns an array with the argument as its single element. + # + # Array.wrap(nil) # => [] + # Array.wrap([1, 2, 3]) # => [1, 2, 3] + # Array.wrap(0) # => [0] + # + # This method is similar in purpose to Kernel#Array, but there are some differences: + # + # * If the argument responds to +to_ary+ the method is invoked. Kernel#Array + # moves on to try +to_a+ if the returned value is +nil+, but Array.wrap returns + # an array with the argument as its single element right away. + # * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, Kernel#Array + # raises an exception, while Array.wrap does not, it just returns the value. + # * It does not call +to_a+ on the argument, if the argument does not respond to +to_ary+ + # it returns an array with the argument as its single element. + # + # The last point is easily explained with some enumerables: + # + # Array(foo: :bar) # => [[:foo, :bar]] + # Array.wrap(foo: :bar) # => [{:foo=>:bar}] + # + # There's also a related idiom that uses the splat operator: + # + # [*object] + # + # which returns [] for +nil+, but calls to Array(object) otherwise. + # + # The differences with Kernel#Array explained above + # apply to the rest of objects. + def self.wrap(object) + if object.nil? + [] + elsif object.respond_to?(:to_ary) + object.to_ary || [object] + else + [object] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/benchmark.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/benchmark.rb new file mode 100644 index 0000000..f6e1b72 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/benchmark.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require "benchmark" + +class << Benchmark + # Benchmark realtime in milliseconds. + # + # Benchmark.realtime { User.all } + # # => 8.0e-05 + # + # Benchmark.ms { User.all } + # # => 0.074 + def ms(&block) + 1000 * realtime(&block) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/big_decimal.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/big_decimal.rb new file mode 100644 index 0000000..9e6a9d6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/big_decimal.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +require "active_support/core_ext/big_decimal/conversions" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/big_decimal/conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/big_decimal/conversions.rb new file mode 100644 index 0000000..76ad584 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/big_decimal/conversions.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +require "bigdecimal" +require "bigdecimal/util" + +module ActiveSupport + module BigDecimalWithDefaultFormat # :nodoc: + def to_s(format = "F") + super(format) + end + end +end + +BigDecimal.prepend(ActiveSupport::BigDecimalWithDefaultFormat) diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class.rb new file mode 100644 index 0000000..1c110fd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +require "active_support/core_ext/class/attribute" +require "active_support/core_ext/class/subclasses" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class/attribute.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class/attribute.rb new file mode 100644 index 0000000..ec78845 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class/attribute.rb @@ -0,0 +1,131 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/redefine_method" + +class Class + # Declare a class-level attribute whose value is inheritable by subclasses. + # Subclasses can change their own value and it will not impact parent class. + # + # ==== Options + # + # * :instance_reader - Sets the instance reader method (defaults to true). + # * :instance_writer - Sets the instance writer method (defaults to true). + # * :instance_accessor - Sets both instance methods (defaults to true). + # * :instance_predicate - Sets a predicate method (defaults to true). + # * :default - Sets a default value for the attribute (defaults to nil). + # + # ==== Examples + # + # class Base + # class_attribute :setting + # end + # + # class Subclass < Base + # end + # + # Base.setting = true + # Subclass.setting # => true + # Subclass.setting = false + # Subclass.setting # => false + # Base.setting # => true + # + # In the above case as long as Subclass does not assign a value to setting + # by performing Subclass.setting = _something_, Subclass.setting + # would read value assigned to parent class. Once Subclass assigns a value then + # the value assigned by Subclass would be returned. + # + # This matches normal Ruby method inheritance: think of writing an attribute + # on a subclass as overriding the reader method. However, you need to be aware + # when using +class_attribute+ with mutable structures as +Array+ or +Hash+. + # In such cases, you don't want to do changes in place. Instead use setters: + # + # Base.setting = [] + # Base.setting # => [] + # Subclass.setting # => [] + # + # # Appending in child changes both parent and child because it is the same object: + # Subclass.setting << :foo + # Base.setting # => [:foo] + # Subclass.setting # => [:foo] + # + # # Use setters to not propagate changes: + # Base.setting = [] + # Subclass.setting += [:foo] + # Base.setting # => [] + # Subclass.setting # => [:foo] + # + # For convenience, an instance predicate method is defined as well. + # To skip it, pass instance_predicate: false. + # + # Subclass.setting? # => false + # + # Instances may overwrite the class value in the same way: + # + # Base.setting = true + # object = Base.new + # object.setting # => true + # object.setting = false + # object.setting # => false + # Base.setting # => true + # + # To opt out of the instance reader method, pass instance_reader: false. + # + # object.setting # => NoMethodError + # object.setting? # => NoMethodError + # + # To opt out of the instance writer method, pass instance_writer: false. + # + # object.setting = false # => NoMethodError + # + # To opt out of both instance methods, pass instance_accessor: false. + # + # To set a default value for the attribute, pass default:, like so: + # + # class_attribute :settings, default: {} + def class_attribute(*attrs, instance_accessor: true, + instance_reader: instance_accessor, instance_writer: instance_accessor, instance_predicate: true, default: nil) + + class_methods, methods = [], [] + attrs.each do |name| + unless name.is_a?(Symbol) || name.is_a?(String) + raise TypeError, "#{name.inspect} is not a symbol nor a string" + end + + class_methods << <<~RUBY # In case the method exists and is not public + silence_redefinition_of_method def #{name} + end + RUBY + + methods << <<~RUBY if instance_reader + silence_redefinition_of_method def #{name} + defined?(@#{name}) ? @#{name} : self.class.#{name} + end + RUBY + + class_methods << <<~RUBY + silence_redefinition_of_method def #{name}=(value) + redefine_method(:#{name}) { value } if singleton_class? + redefine_singleton_method(:#{name}) { value } + value + end + RUBY + + methods << <<~RUBY if instance_writer + silence_redefinition_of_method(:#{name}=) + attr_writer :#{name} + RUBY + + if instance_predicate + class_methods << "silence_redefinition_of_method def #{name}?; !!self.#{name}; end" + if instance_reader + methods << "silence_redefinition_of_method def #{name}?; !!self.#{name}; end" + end + end + end + + location = caller_locations(1, 1).first + class_eval(["class << self", *class_methods, "end", *methods].join(";").tr("\n", ";"), location.path, location.lineno) + + attrs.each { |name| public_send("#{name}=", default) } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class/attribute_accessors.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class/attribute_accessors.rb new file mode 100644 index 0000000..a77354e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class/attribute_accessors.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +# cattr_* became mattr_* aliases in 7dfbd91b0780fbd6a1dd9bfbc176e10894871d2d, +# but we keep this around for libraries that directly require it knowing they +# want cattr_*. No need to deprecate. +require "active_support/core_ext/module/attribute_accessors" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class/subclasses.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class/subclasses.rb new file mode 100644 index 0000000..3f4c24d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/class/subclasses.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +require "active_support/ruby_features" + +class Class + if ActiveSupport::RubyFeatures::CLASS_SUBCLASSES + # Returns an array with all classes that are < than its receiver. + # + # class C; end + # C.descendants # => [] + # + # class B < C; end + # C.descendants # => [B] + # + # class A < B; end + # C.descendants # => [B, A] + # + # class D < C; end + # C.descendants # => [B, A, D] + def descendants + subclasses.concat(subclasses.flat_map(&:descendants)) + end + else + def descendants + ObjectSpace.each_object(singleton_class).reject do |k| + k.singleton_class? || k == self + end + end + end + + # Returns an array with the direct children of +self+. + # + # class Foo; end + # class Bar < Foo; end + # class Baz < Bar; end + # + # Foo.subclasses # => [Bar] + def subclasses + descendants.select { |descendant| descendant.superclass == self } + end unless ActiveSupport::RubyFeatures::CLASS_SUBCLASSES +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date.rb new file mode 100644 index 0000000..b683597 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +require "active_support/core_ext/date/acts_like" +require "active_support/core_ext/date/blank" +require "active_support/core_ext/date/calculations" +require "active_support/core_ext/date/conversions" +require "active_support/core_ext/date/deprecated_conversions" unless ENV["RAILS_DISABLE_DEPRECATED_TO_S_CONVERSION"] +require "active_support/core_ext/date/zones" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/acts_like.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/acts_like.rb new file mode 100644 index 0000000..c8077f3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/acts_like.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/acts_like" + +class Date + # Duck-types as a Date-like class. See Object#acts_like?. + def acts_like_date? + true + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/blank.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/blank.rb new file mode 100644 index 0000000..2c59029 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/blank.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +require "date" + +class Date # :nodoc: + # No Date is blank: + # + # Date.today.blank? # => false + # + # @return [false] + def blank? + false + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/calculations.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/calculations.rb new file mode 100644 index 0000000..34961f2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/calculations.rb @@ -0,0 +1,146 @@ +# frozen_string_literal: true + +require "date" +require "active_support/duration" +require "active_support/core_ext/object/acts_like" +require "active_support/core_ext/date/zones" +require "active_support/core_ext/time/zones" +require "active_support/core_ext/date_and_time/calculations" + +class Date + include DateAndTime::Calculations + + class << self + attr_accessor :beginning_of_week_default + + # Returns the week start (e.g. :monday) for the current request, if this has been set (via Date.beginning_of_week=). + # If Date.beginning_of_week has not been set for the current request, returns the week start specified in config.beginning_of_week. + # If no config.beginning_of_week was specified, returns :monday. + def beginning_of_week + ::ActiveSupport::IsolatedExecutionState[:beginning_of_week] || beginning_of_week_default || :monday + end + + # Sets Date.beginning_of_week to a week start (e.g. :monday) for current request/thread. + # + # This method accepts any of the following day symbols: + # :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday + def beginning_of_week=(week_start) + ::ActiveSupport::IsolatedExecutionState[:beginning_of_week] = find_beginning_of_week!(week_start) + end + + # Returns week start day symbol (e.g. :monday), or raises an +ArgumentError+ for invalid day symbol. + def find_beginning_of_week!(week_start) + raise ArgumentError, "Invalid beginning of week: #{week_start}" unless ::Date::DAYS_INTO_WEEK.key?(week_start) + week_start + end + + # Returns a new Date representing the date 1 day ago (i.e. yesterday's date). + def yesterday + ::Date.current.yesterday + end + + # Returns a new Date representing the date 1 day after today (i.e. tomorrow's date). + def tomorrow + ::Date.current.tomorrow + end + + # Returns Time.zone.today when Time.zone or config.time_zone are set, otherwise just returns Date.today. + def current + ::Time.zone ? ::Time.zone.today : ::Date.today + end + end + + # Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00) + # and then subtracts the specified number of seconds. + def ago(seconds) + in_time_zone.since(-seconds) + end + + # Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00) + # and then adds the specified number of seconds + def since(seconds) + in_time_zone.since(seconds) + end + alias :in :since + + # Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00) + def beginning_of_day + in_time_zone + end + alias :midnight :beginning_of_day + alias :at_midnight :beginning_of_day + alias :at_beginning_of_day :beginning_of_day + + # Converts Date to a Time (or DateTime if necessary) with the time portion set to the middle of the day (12:00) + def middle_of_day + in_time_zone.middle_of_day + end + alias :midday :middle_of_day + alias :noon :middle_of_day + alias :at_midday :middle_of_day + alias :at_noon :middle_of_day + alias :at_middle_of_day :middle_of_day + + # Converts Date to a Time (or DateTime if necessary) with the time portion set to the end of the day (23:59:59) + def end_of_day + in_time_zone.end_of_day + end + alias :at_end_of_day :end_of_day + + def plus_with_duration(other) # :nodoc: + if ActiveSupport::Duration === other + other.since(self) + else + plus_without_duration(other) + end + end + alias_method :plus_without_duration, :+ + alias_method :+, :plus_with_duration + + def minus_with_duration(other) # :nodoc: + if ActiveSupport::Duration === other + plus_with_duration(-other) + else + minus_without_duration(other) + end + end + alias_method :minus_without_duration, :- + alias_method :-, :minus_with_duration + + # Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with + # any of these keys: :years, :months, :weeks, :days. + def advance(options) + d = self + + d = d >> options[:years] * 12 if options[:years] + d = d >> options[:months] if options[:months] + d = d + options[:weeks] * 7 if options[:weeks] + d = d + options[:days] if options[:days] + + d + end + + # Returns a new Date where one or more of the elements have been changed according to the +options+ parameter. + # The +options+ parameter is a hash with a combination of these keys: :year, :month, :day. + # + # Date.new(2007, 5, 12).change(day: 1) # => Date.new(2007, 5, 1) + # Date.new(2007, 5, 12).change(year: 2005, month: 1) # => Date.new(2005, 1, 12) + def change(options) + ::Date.new( + options.fetch(:year, year), + options.fetch(:month, month), + options.fetch(:day, day) + ) + end + + # Allow Date to be compared with Time by converting to DateTime and relying on the <=> from there. + def compare_with_coercion(other) + if other.is_a?(Time) + to_datetime <=> other + else + compare_without_coercion(other) + end + end + alias_method :compare_without_coercion, :<=> + alias_method :<=>, :compare_with_coercion +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/conversions.rb new file mode 100644 index 0000000..b75badd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/conversions.rb @@ -0,0 +1,97 @@ +# frozen_string_literal: true + +require "date" +require "active_support/inflector/methods" +require "active_support/core_ext/date/zones" +require "active_support/core_ext/module/redefine_method" + +class Date + DATE_FORMATS = { + short: "%d %b", + long: "%B %d, %Y", + db: "%Y-%m-%d", + inspect: "%Y-%m-%d", + number: "%Y%m%d", + long_ordinal: lambda { |date| + day_format = ActiveSupport::Inflector.ordinalize(date.day) + date.strftime("%B #{day_format}, %Y") # => "April 25th, 2007" + }, + rfc822: "%d %b %Y", + iso8601: lambda { |date| date.iso8601 } + } + + # Convert to a formatted string. See DATE_FORMATS for predefined formats. + # + # This method is aliased to to_formatted_s. + # + # date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007 + # + # date.to_fs(:db) # => "2007-11-10" + # date.to_formatted_s(:db) # => "2007-11-10" + # + # date.to_fs(:short) # => "10 Nov" + # date.to_fs(:number) # => "20071110" + # date.to_fs(:long) # => "November 10, 2007" + # date.to_fs(:long_ordinal) # => "November 10th, 2007" + # date.to_fs(:rfc822) # => "10 Nov 2007" + # date.to_fs(:iso8601) # => "2007-11-10" + # + # == Adding your own date formats to to_fs + # You can add your own formats to the Date::DATE_FORMATS hash. + # Use the format name as the hash key and either a strftime string + # or Proc instance that takes a date argument as the value. + # + # # config/initializers/date_formats.rb + # Date::DATE_FORMATS[:month_and_year] = '%B %Y' + # Date::DATE_FORMATS[:short_ordinal] = ->(date) { date.strftime("%B #{date.day.ordinalize}") } + def to_fs(format = :default) + if formatter = DATE_FORMATS[format] + if formatter.respond_to?(:call) + formatter.call(self).to_s + else + strftime(formatter) + end + else + to_default_s + end + end + alias_method :to_formatted_s, :to_fs + alias_method :to_default_s, :to_s + + # Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005" + def readable_inspect + strftime("%a, %d %b %Y") + end + alias_method :default_inspect, :inspect + alias_method :inspect, :readable_inspect + + silence_redefinition_of_method :to_time + + # Converts a Date instance to a Time, where the time is set to the beginning of the day. + # The timezone can be either :local or :utc (default :local). + # + # date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007 + # + # date.to_time # => 2007-11-10 00:00:00 0800 + # date.to_time(:local) # => 2007-11-10 00:00:00 0800 + # + # date.to_time(:utc) # => 2007-11-10 00:00:00 UTC + # + # NOTE: The :local timezone is Ruby's *process* timezone, i.e. ENV['TZ']. + # If the *application's* timezone is needed, then use +in_time_zone+ instead. + def to_time(form = :local) + raise ArgumentError, "Expected :local or :utc, got #{form.inspect}." unless [:local, :utc].include?(form) + ::Time.public_send(form, year, month, day) + end + + silence_redefinition_of_method :xmlschema + + # Returns a string which represents the time in used time zone as DateTime + # defined by XML Schema: + # + # date = Date.new(2015, 05, 23) # => Sat, 23 May 2015 + # date.xmlschema # => "2015-05-23T00:00:00+04:00" + def xmlschema + in_time_zone.xmlschema + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/deprecated_conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/deprecated_conversions.rb new file mode 100644 index 0000000..f983235 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/deprecated_conversions.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +require "date" + +class Date + NOT_SET = Object.new # :nodoc: + def to_s(format = NOT_SET) # :nodoc: + if formatter = DATE_FORMATS[format] + ActiveSupport::Deprecation.warn( + "Date#to_s(#{format.inspect}) is deprecated. Please use Date#to_fs(#{format.inspect}) instead." + ) + if formatter.respond_to?(:call) + formatter.call(self).to_s + else + strftime(formatter) + end + elsif format == NOT_SET + to_default_s + else + ActiveSupport::Deprecation.warn( + "Date#to_s(#{format.inspect}) is deprecated. Please use Date#to_fs(#{format.inspect}) instead." + ) + to_default_s + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/zones.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/zones.rb new file mode 100644 index 0000000..2dcf97c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date/zones.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +require "date" +require "active_support/core_ext/date_and_time/zones" + +class Date + include DateAndTime::Zones +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_and_time/calculations.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_and_time/calculations.rb new file mode 100644 index 0000000..21cfeed --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_and_time/calculations.rb @@ -0,0 +1,364 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/try" +require "active_support/core_ext/date_time/conversions" + +module DateAndTime + module Calculations + DAYS_INTO_WEEK = { + sunday: 0, + monday: 1, + tuesday: 2, + wednesday: 3, + thursday: 4, + friday: 5, + saturday: 6 + } + WEEKEND_DAYS = [ 6, 0 ] + + # Returns a new date/time representing yesterday. + def yesterday + advance(days: -1) + end + + # Returns a new date/time representing tomorrow. + def tomorrow + advance(days: 1) + end + + # Returns true if the date/time is today. + def today? + to_date == ::Date.current + end + + # Returns true if the date/time is tomorrow. + def tomorrow? + to_date == ::Date.current.tomorrow + end + alias :next_day? :tomorrow? + + # Returns true if the date/time is yesterday. + def yesterday? + to_date == ::Date.current.yesterday + end + alias :prev_day? :yesterday? + + # Returns true if the date/time is in the past. + def past? + self < self.class.current + end + + # Returns true if the date/time is in the future. + def future? + self > self.class.current + end + + # Returns true if the date/time falls on a Saturday or Sunday. + def on_weekend? + WEEKEND_DAYS.include?(wday) + end + + # Returns true if the date/time does not fall on a Saturday or Sunday. + def on_weekday? + !WEEKEND_DAYS.include?(wday) + end + + # Returns true if the date/time falls before date_or_time. + def before?(date_or_time) + self < date_or_time + end + + # Returns true if the date/time falls after date_or_time. + def after?(date_or_time) + self > date_or_time + end + + # Returns a new date/time the specified number of days ago. + def days_ago(days) + advance(days: -days) + end + + # Returns a new date/time the specified number of days in the future. + def days_since(days) + advance(days: days) + end + + # Returns a new date/time the specified number of weeks ago. + def weeks_ago(weeks) + advance(weeks: -weeks) + end + + # Returns a new date/time the specified number of weeks in the future. + def weeks_since(weeks) + advance(weeks: weeks) + end + + # Returns a new date/time the specified number of months ago. + def months_ago(months) + advance(months: -months) + end + + # Returns a new date/time the specified number of months in the future. + def months_since(months) + advance(months: months) + end + + # Returns a new date/time the specified number of years ago. + def years_ago(years) + advance(years: -years) + end + + # Returns a new date/time the specified number of years in the future. + def years_since(years) + advance(years: years) + end + + # Returns a new date/time at the start of the month. + # + # today = Date.today # => Thu, 18 Jun 2015 + # today.beginning_of_month # => Mon, 01 Jun 2015 + # + # +DateTime+ objects will have a time set to 0:00. + # + # now = DateTime.current # => Thu, 18 Jun 2015 15:23:13 +0000 + # now.beginning_of_month # => Mon, 01 Jun 2015 00:00:00 +0000 + def beginning_of_month + first_hour(change(day: 1)) + end + alias :at_beginning_of_month :beginning_of_month + + # Returns a new date/time at the start of the quarter. + # + # today = Date.today # => Fri, 10 Jul 2015 + # today.beginning_of_quarter # => Wed, 01 Jul 2015 + # + # +DateTime+ objects will have a time set to 0:00. + # + # now = DateTime.current # => Fri, 10 Jul 2015 18:41:29 +0000 + # now.beginning_of_quarter # => Wed, 01 Jul 2015 00:00:00 +0000 + def beginning_of_quarter + first_quarter_month = month - (2 + month) % 3 + beginning_of_month.change(month: first_quarter_month) + end + alias :at_beginning_of_quarter :beginning_of_quarter + + # Returns a new date/time at the end of the quarter. + # + # today = Date.today # => Fri, 10 Jul 2015 + # today.end_of_quarter # => Wed, 30 Sep 2015 + # + # +DateTime+ objects will have a time set to 23:59:59. + # + # now = DateTime.current # => Fri, 10 Jul 2015 18:41:29 +0000 + # now.end_of_quarter # => Wed, 30 Sep 2015 23:59:59 +0000 + def end_of_quarter + last_quarter_month = month + (12 - month) % 3 + beginning_of_month.change(month: last_quarter_month).end_of_month + end + alias :at_end_of_quarter :end_of_quarter + + # Returns a new date/time at the beginning of the year. + # + # today = Date.today # => Fri, 10 Jul 2015 + # today.beginning_of_year # => Thu, 01 Jan 2015 + # + # +DateTime+ objects will have a time set to 0:00. + # + # now = DateTime.current # => Fri, 10 Jul 2015 18:41:29 +0000 + # now.beginning_of_year # => Thu, 01 Jan 2015 00:00:00 +0000 + def beginning_of_year + change(month: 1).beginning_of_month + end + alias :at_beginning_of_year :beginning_of_year + + # Returns a new date/time representing the given day in the next week. + # + # today = Date.today # => Thu, 07 May 2015 + # today.next_week # => Mon, 11 May 2015 + # + # The +given_day_in_next_week+ defaults to the beginning of the week + # which is determined by +Date.beginning_of_week+ or +config.beginning_of_week+ + # when set. + # + # today = Date.today # => Thu, 07 May 2015 + # today.next_week(:friday) # => Fri, 15 May 2015 + # + # +DateTime+ objects have their time set to 0:00 unless +same_time+ is true. + # + # now = DateTime.current # => Thu, 07 May 2015 13:31:16 +0000 + # now.next_week # => Mon, 11 May 2015 00:00:00 +0000 + def next_week(given_day_in_next_week = Date.beginning_of_week, same_time: false) + result = first_hour(weeks_since(1).beginning_of_week.days_since(days_span(given_day_in_next_week))) + same_time ? copy_time_to(result) : result + end + + # Returns a new date/time representing the next weekday. + def next_weekday + if next_day.on_weekend? + next_week(:monday, same_time: true) + else + next_day + end + end + + # Short-hand for months_since(3) + def next_quarter + months_since(3) + end + + # Returns a new date/time representing the given day in the previous week. + # Week is assumed to start on +start_day+, default is + # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. + # DateTime objects have their time set to 0:00 unless +same_time+ is true. + def prev_week(start_day = Date.beginning_of_week, same_time: false) + result = first_hour(weeks_ago(1).beginning_of_week.days_since(days_span(start_day))) + same_time ? copy_time_to(result) : result + end + alias_method :last_week, :prev_week + + # Returns a new date/time representing the previous weekday. + def prev_weekday + if prev_day.on_weekend? + copy_time_to(beginning_of_week(:friday)) + else + prev_day + end + end + alias_method :last_weekday, :prev_weekday + + # Short-hand for months_ago(1). + def last_month + months_ago(1) + end + + # Short-hand for months_ago(3). + def prev_quarter + months_ago(3) + end + alias_method :last_quarter, :prev_quarter + + # Short-hand for years_ago(1). + def last_year + years_ago(1) + end + + # Returns the number of days to the start of the week on the given day. + # Week is assumed to start on +start_day+, default is + # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. + def days_to_week_start(start_day = Date.beginning_of_week) + start_day_number = DAYS_INTO_WEEK.fetch(start_day) + (wday - start_day_number) % 7 + end + + # Returns a new date/time representing the start of this week on the given day. + # Week is assumed to start on +start_day+, default is + # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. + # +DateTime+ objects have their time set to 0:00. + def beginning_of_week(start_day = Date.beginning_of_week) + result = days_ago(days_to_week_start(start_day)) + acts_like?(:time) ? result.midnight : result + end + alias :at_beginning_of_week :beginning_of_week + + # Returns Monday of this week assuming that week starts on Monday. + # +DateTime+ objects have their time set to 0:00. + def monday + beginning_of_week(:monday) + end + + # Returns a new date/time representing the end of this week on the given day. + # Week is assumed to start on +start_day+, default is + # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. + # DateTime objects have their time set to 23:59:59. + def end_of_week(start_day = Date.beginning_of_week) + last_hour(days_since(6 - days_to_week_start(start_day))) + end + alias :at_end_of_week :end_of_week + + # Returns Sunday of this week assuming that week starts on Monday. + # +DateTime+ objects have their time set to 23:59:59. + def sunday + end_of_week(:monday) + end + + # Returns a new date/time representing the end of the month. + # DateTime objects will have a time set to 23:59:59. + def end_of_month + last_day = ::Time.days_in_month(month, year) + last_hour(days_since(last_day - day)) + end + alias :at_end_of_month :end_of_month + + # Returns a new date/time representing the end of the year. + # DateTime objects will have a time set to 23:59:59. + def end_of_year + change(month: 12).end_of_month + end + alias :at_end_of_year :end_of_year + + # Returns a Range representing the whole day of the current date/time. + def all_day + beginning_of_day..end_of_day + end + + # Returns a Range representing the whole week of the current date/time. + # Week starts on start_day, default is Date.beginning_of_week or config.beginning_of_week when set. + def all_week(start_day = Date.beginning_of_week) + beginning_of_week(start_day)..end_of_week(start_day) + end + + # Returns a Range representing the whole month of the current date/time. + def all_month + beginning_of_month..end_of_month + end + + # Returns a Range representing the whole quarter of the current date/time. + def all_quarter + beginning_of_quarter..end_of_quarter + end + + # Returns a Range representing the whole year of the current date/time. + def all_year + beginning_of_year..end_of_year + end + + # Returns a new date/time representing the next occurrence of the specified day of week. + # + # today = Date.today # => Thu, 14 Dec 2017 + # today.next_occurring(:monday) # => Mon, 18 Dec 2017 + # today.next_occurring(:thursday) # => Thu, 21 Dec 2017 + def next_occurring(day_of_week) + from_now = DAYS_INTO_WEEK.fetch(day_of_week) - wday + from_now += 7 unless from_now > 0 + advance(days: from_now) + end + + # Returns a new date/time representing the previous occurrence of the specified day of week. + # + # today = Date.today # => Thu, 14 Dec 2017 + # today.prev_occurring(:monday) # => Mon, 11 Dec 2017 + # today.prev_occurring(:thursday) # => Thu, 07 Dec 2017 + def prev_occurring(day_of_week) + ago = wday - DAYS_INTO_WEEK.fetch(day_of_week) + ago += 7 unless ago > 0 + advance(days: -ago) + end + + private + def first_hour(date_or_time) + date_or_time.acts_like?(:time) ? date_or_time.beginning_of_day : date_or_time + end + + def last_hour(date_or_time) + date_or_time.acts_like?(:time) ? date_or_time.end_of_day : date_or_time + end + + def days_span(day) + (DAYS_INTO_WEEK.fetch(day) - DAYS_INTO_WEEK.fetch(Date.beginning_of_week)) % 7 + end + + def copy_time_to(other) + other.change(hour: hour, min: min, sec: sec, nsec: try(:nsec)) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_and_time/compatibility.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_and_time/compatibility.rb new file mode 100644 index 0000000..3a3dbc3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_and_time/compatibility.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/attribute_accessors" + +module DateAndTime + module Compatibility + # If true, +to_time+ preserves the timezone offset of receiver. + # + # NOTE: With Ruby 2.4+ the default for +to_time+ changed from + # converting to the local system time, to preserving the offset + # of the receiver. For backwards compatibility we're overriding + # this behavior, but new apps will have an initializer that sets + # this to true, because the new behavior is preferred. + mattr_accessor :preserve_timezone, instance_writer: false, default: false + + # Change the output of ActiveSupport::TimeZone.utc_to_local. + # + # When `true`, it returns local times with a UTC offset, with `false` local + # times are returned as UTC. + # + # # Given this zone: + # zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"] + # + # # With `utc_to_local_returns_utc_offset_times = false`, local time is converted to UTC: + # zone.utc_to_local(Time.utc(2000, 1)) # => 1999-12-31 19:00:00 UTC + # + # # With `utc_to_local_returns_utc_offset_times = true`, local time is returned with UTC offset: + # zone.utc_to_local(Time.utc(2000, 1)) # => 1999-12-31 19:00:00 -0500 + mattr_accessor :utc_to_local_returns_utc_offset_times, instance_writer: false, default: false + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_and_time/zones.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_and_time/zones.rb new file mode 100644 index 0000000..fb6a27c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_and_time/zones.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +module DateAndTime + module Zones + # Returns the simultaneous time in Time.zone if a zone is given or + # if Time.zone_default is set. Otherwise, it returns the current time. + # + # Time.zone = 'Hawaii' # => 'Hawaii' + # Time.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00 + # Date.new(2000).in_time_zone # => Sat, 01 Jan 2000 00:00:00 HST -10:00 + # + # This method is similar to Time#localtime, except that it uses Time.zone as the local zone + # instead of the operating system's time zone. + # + # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument, + # and the conversion will be based on that zone instead of Time.zone. + # + # Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00 + # Date.new(2000).in_time_zone('Alaska') # => Sat, 01 Jan 2000 00:00:00 AKST -09:00 + def in_time_zone(zone = ::Time.zone) + time_zone = ::Time.find_zone! zone + time = acts_like?(:time) ? self : nil + + if time_zone + time_with_zone(time, time_zone) + else + time || to_time + end + end + + private + def time_with_zone(time, zone) + if time + ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone) + else + ActiveSupport::TimeWithZone.new(nil, zone, to_time(:utc)) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time.rb new file mode 100644 index 0000000..e23a8be --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +require "active_support/core_ext/date_time/acts_like" +require "active_support/core_ext/date_time/blank" +require "active_support/core_ext/date_time/calculations" +require "active_support/core_ext/date_time/compatibility" +require "active_support/core_ext/date_time/conversions" +require "active_support/core_ext/date_time/deprecated_conversions" unless ENV["RAILS_DISABLE_DEPRECATED_TO_S_CONVERSION"] diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/acts_like.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/acts_like.rb new file mode 100644 index 0000000..5dccdfe --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/acts_like.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require "date" +require "active_support/core_ext/object/acts_like" + +class DateTime + # Duck-types as a Date-like class. See Object#acts_like?. + def acts_like_date? + true + end + + # Duck-types as a Time-like class. See Object#acts_like?. + def acts_like_time? + true + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/blank.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/blank.rb new file mode 100644 index 0000000..d1c418c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/blank.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +require "date" + +class DateTime # :nodoc: + # No DateTime is ever blank: + # + # DateTime.now.blank? # => false + # + # @return [false] + def blank? + false + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/calculations.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/calculations.rb new file mode 100644 index 0000000..bc670c3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/calculations.rb @@ -0,0 +1,211 @@ +# frozen_string_literal: true + +require "date" + +class DateTime + class << self + # Returns Time.zone.now.to_datetime when Time.zone or + # config.time_zone are set, otherwise returns + # Time.now.to_datetime. + def current + ::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime + end + end + + # Returns the number of seconds since 00:00:00. + # + # DateTime.new(2012, 8, 29, 0, 0, 0).seconds_since_midnight # => 0 + # DateTime.new(2012, 8, 29, 12, 34, 56).seconds_since_midnight # => 45296 + # DateTime.new(2012, 8, 29, 23, 59, 59).seconds_since_midnight # => 86399 + def seconds_since_midnight + sec + (min * 60) + (hour * 3600) + end + + # Returns the number of seconds until 23:59:59. + # + # DateTime.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399 + # DateTime.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103 + # DateTime.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0 + def seconds_until_end_of_day + end_of_day.to_i - to_i + end + + # Returns the fraction of a second as a +Rational+ + # + # DateTime.new(2012, 8, 29, 0, 0, 0.5).subsec # => (1/2) + def subsec + sec_fraction + end + + # Returns a new DateTime where one or more of the elements have been changed + # according to the +options+ parameter. The time options (:hour, + # :min, :sec) reset cascadingly, so if only the hour is + # passed, then minute and sec is set to 0. If the hour and minute is passed, + # then sec is set to 0. The +options+ parameter takes a hash with any of these + # keys: :year, :month, :day, :hour, + # :min, :sec, :offset, :start. + # + # DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => DateTime.new(2012, 8, 1, 22, 35, 0) + # DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => DateTime.new(1981, 8, 1, 22, 35, 0) + # DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => DateTime.new(1981, 8, 29, 0, 0, 0) + def change(options) + if new_nsec = options[:nsec] + raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec] + new_fraction = Rational(new_nsec, 1000000000) + else + new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000)) + new_fraction = Rational(new_usec, 1000000) + end + + raise ArgumentError, "argument out of range" if new_fraction >= 1 + + ::DateTime.civil( + options.fetch(:year, year), + options.fetch(:month, month), + options.fetch(:day, day), + options.fetch(:hour, hour), + options.fetch(:min, options[:hour] ? 0 : min), + options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec) + new_fraction, + options.fetch(:offset, offset), + options.fetch(:start, start) + ) + end + + # Uses Date to provide precise Time calculations for years, months, and days. + # The +options+ parameter takes a hash with any of these keys: :years, + # :months, :weeks, :days, :hours, + # :minutes, :seconds. + def advance(options) + unless options[:weeks].nil? + options[:weeks], partial_weeks = options[:weeks].divmod(1) + options[:days] = options.fetch(:days, 0) + 7 * partial_weeks + end + + unless options[:days].nil? + options[:days], partial_days = options[:days].divmod(1) + options[:hours] = options.fetch(:hours, 0) + 24 * partial_days + end + + d = to_date.advance(options) + datetime_advanced_by_date = change(year: d.year, month: d.month, day: d.day) + seconds_to_advance = \ + options.fetch(:seconds, 0) + + options.fetch(:minutes, 0) * 60 + + options.fetch(:hours, 0) * 3600 + + if seconds_to_advance.zero? + datetime_advanced_by_date + else + datetime_advanced_by_date.since(seconds_to_advance) + end + end + + # Returns a new DateTime representing the time a number of seconds ago. + # Do not use this method in combination with x.months, use months_ago instead! + def ago(seconds) + since(-seconds) + end + + # Returns a new DateTime representing the time a number of seconds since the + # instance time. Do not use this method in combination with x.months, use + # months_since instead! + def since(seconds) + self + Rational(seconds, 86400) + end + alias :in :since + + # Returns a new DateTime representing the start of the day (0:00). + def beginning_of_day + change(hour: 0) + end + alias :midnight :beginning_of_day + alias :at_midnight :beginning_of_day + alias :at_beginning_of_day :beginning_of_day + + # Returns a new DateTime representing the middle of the day (12:00) + def middle_of_day + change(hour: 12) + end + alias :midday :middle_of_day + alias :noon :middle_of_day + alias :at_midday :middle_of_day + alias :at_noon :middle_of_day + alias :at_middle_of_day :middle_of_day + + # Returns a new DateTime representing the end of the day (23:59:59). + def end_of_day + change(hour: 23, min: 59, sec: 59, usec: Rational(999999999, 1000)) + end + alias :at_end_of_day :end_of_day + + # Returns a new DateTime representing the start of the hour (hh:00:00). + def beginning_of_hour + change(min: 0) + end + alias :at_beginning_of_hour :beginning_of_hour + + # Returns a new DateTime representing the end of the hour (hh:59:59). + def end_of_hour + change(min: 59, sec: 59, usec: Rational(999999999, 1000)) + end + alias :at_end_of_hour :end_of_hour + + # Returns a new DateTime representing the start of the minute (hh:mm:00). + def beginning_of_minute + change(sec: 0) + end + alias :at_beginning_of_minute :beginning_of_minute + + # Returns a new DateTime representing the end of the minute (hh:mm:59). + def end_of_minute + change(sec: 59, usec: Rational(999999999, 1000)) + end + alias :at_end_of_minute :end_of_minute + + # Returns a Time instance of the simultaneous time in the system timezone. + def localtime(utc_offset = nil) + utc = new_offset(0) + + Time.utc( + utc.year, utc.month, utc.day, + utc.hour, utc.min, utc.sec + utc.sec_fraction + ).getlocal(utc_offset) + end + alias_method :getlocal, :localtime + + # Returns a Time instance of the simultaneous time in the UTC timezone. + # + # DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)) # => Mon, 21 Feb 2005 10:11:12 -0600 + # DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc # => Mon, 21 Feb 2005 16:11:12 UTC + def utc + utc = new_offset(0) + + Time.utc( + utc.year, utc.month, utc.day, + utc.hour, utc.min, utc.sec + utc.sec_fraction + ) + end + alias_method :getgm, :utc + alias_method :getutc, :utc + alias_method :gmtime, :utc + + # Returns +true+ if offset == 0. + def utc? + offset == 0 + end + + # Returns the offset value in seconds. + def utc_offset + (offset * 86400).to_i + end + + # Layers additional behavior on DateTime#<=> so that Time and + # ActiveSupport::TimeWithZone instances can be compared with a DateTime. + def <=>(other) + if other.respond_to? :to_datetime + super other.to_datetime rescue nil + else + super + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/compatibility.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/compatibility.rb new file mode 100644 index 0000000..7600a06 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/compatibility.rb @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +require "active_support/core_ext/date_and_time/compatibility" +require "active_support/core_ext/module/redefine_method" + +class DateTime + include DateAndTime::Compatibility + + silence_redefinition_of_method :to_time + + # Either return an instance of +Time+ with the same UTC offset + # as +self+ or an instance of +Time+ representing the same time + # in the local system timezone depending on the setting of + # on the setting of +ActiveSupport.to_time_preserves_timezone+. + def to_time + preserve_timezone ? getlocal(utc_offset) : getlocal + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/conversions.rb new file mode 100644 index 0000000..be1c472 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/conversions.rb @@ -0,0 +1,106 @@ +# frozen_string_literal: true + +require "date" +require "active_support/inflector/methods" +require "active_support/core_ext/time/conversions" +require "active_support/core_ext/date_time/calculations" +require "active_support/values/time_zone" + +class DateTime + # Convert to a formatted string. See Time::DATE_FORMATS for predefined formats. + # + # This method is aliased to to_formatted_s. + # + # === Examples + # datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000 + # + # datetime.to_fs(:db) # => "2007-12-04 00:00:00" + # datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00" + # datetime.to_fs(:number) # => "20071204000000" + # datetime.to_fs(:short) # => "04 Dec 00:00" + # datetime.to_fs(:long) # => "December 04, 2007 00:00" + # datetime.to_fs(:long_ordinal) # => "December 4th, 2007 00:00" + # datetime.to_fs(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000" + # datetime.to_fs(:iso8601) # => "2007-12-04T00:00:00+00:00" + # + # == Adding your own datetime formats to to_fs + # DateTime formats are shared with Time. You can add your own to the + # Time::DATE_FORMATS hash. Use the format name as the hash key and + # either a strftime string or Proc instance that takes a time or + # datetime argument as the value. + # + # # config/initializers/time_formats.rb + # Time::DATE_FORMATS[:month_and_year] = '%B %Y' + # Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") } + def to_fs(format = :default) + if formatter = ::Time::DATE_FORMATS[format] + formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) + else + to_default_s + end + end + alias_method :to_formatted_s, :to_fs + alias_method :to_default_s, :to_s if instance_methods(false).include?(:to_s) + + # Returns a formatted string of the offset from UTC, or an alternative + # string if the time zone is already UTC. + # + # datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24)) + # datetime.formatted_offset # => "-06:00" + # datetime.formatted_offset(false) # => "-0600" + def formatted_offset(colon = true, alternate_utc_string = nil) + utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon) + end + + # Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000". + def readable_inspect + to_fs(:rfc822) + end + alias_method :default_inspect, :inspect + alias_method :inspect, :readable_inspect + + # Returns DateTime with local offset for given year if format is local else + # offset is zero. + # + # DateTime.civil_from_format :local, 2012 + # # => Sun, 01 Jan 2012 00:00:00 +0300 + # DateTime.civil_from_format :local, 2012, 12, 17 + # # => Mon, 17 Dec 2012 00:00:00 +0000 + def self.civil_from_format(utc_or_local, year, month = 1, day = 1, hour = 0, min = 0, sec = 0) + if utc_or_local.to_sym == :local + offset = ::Time.local(year, month, day).utc_offset.to_r / 86400 + else + offset = 0 + end + civil(year, month, day, hour, min, sec, offset) + end + + # Converts +self+ to a floating-point number of seconds, including fractional microseconds, since the Unix epoch. + def to_f + seconds_since_unix_epoch.to_f + sec_fraction + end + + # Converts +self+ to an integer number of seconds since the Unix epoch. + def to_i + seconds_since_unix_epoch.to_i + end + + # Returns the fraction of a second as microseconds + def usec + (sec_fraction * 1_000_000).to_i + end + + # Returns the fraction of a second as nanoseconds + def nsec + (sec_fraction * 1_000_000_000).to_i + end + + private + def offset_in_seconds + (offset * 86400).to_i + end + + def seconds_since_unix_epoch + (jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/deprecated_conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/deprecated_conversions.rb new file mode 100644 index 0000000..7380839 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/date_time/deprecated_conversions.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +require "date" + +class DateTime + NOT_SET = Object.new # :nodoc: + def to_s(format = NOT_SET) # :nodoc: + if formatter = ::Time::DATE_FORMATS[format] + ActiveSupport::Deprecation.warn( + "DateTime#to_s(#{format.inspect}) is deprecated. Please use DateTime#to_fs(#{format.inspect}) instead." + ) + formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) + elsif format == NOT_SET + to_default_s + else + ActiveSupport::Deprecation.warn( + "DateTime#to_s(#{format.inspect}) is deprecated. Please use DateTime#to_fs(#{format.inspect}) instead." + ) + to_default_s + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/digest.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/digest.rb new file mode 100644 index 0000000..ce1427e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/digest.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +require "active_support/core_ext/digest/uuid" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/digest/uuid.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/digest/uuid.rb new file mode 100644 index 0000000..3546932 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/digest/uuid.rb @@ -0,0 +1,79 @@ +# frozen_string_literal: true + +require "securerandom" +require "openssl" + +module Digest + module UUID + DNS_NAMESPACE = "k\xA7\xB8\x10\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" # :nodoc: + URL_NAMESPACE = "k\xA7\xB8\x11\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" # :nodoc: + OID_NAMESPACE = "k\xA7\xB8\x12\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" # :nodoc: + X500_NAMESPACE = "k\xA7\xB8\x14\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" # :nodoc: + + mattr_accessor :use_rfc4122_namespaced_uuids, instance_accessor: false, default: false + + # Generates a v5 non-random UUID (Universally Unique IDentifier). + # + # Using OpenSSL::Digest::MD5 generates version 3 UUIDs; OpenSSL::Digest::SHA1 generates version 5 UUIDs. + # uuid_from_hash always generates the same UUID for a given name and namespace combination. + # + # See RFC 4122 for details of UUID at: https://www.ietf.org/rfc/rfc4122.txt + def self.uuid_from_hash(hash_class, namespace, name) + if hash_class == Digest::MD5 || hash_class == OpenSSL::Digest::MD5 + version = 3 + elsif hash_class == Digest::SHA1 || hash_class == OpenSSL::Digest::SHA1 + version = 5 + else + raise ArgumentError, "Expected OpenSSL::Digest::SHA1 or OpenSSL::Digest::MD5, got #{hash_class.name}." + end + + uuid_namespace = pack_uuid_namespace(namespace) + + hash = hash_class.new + hash.update(uuid_namespace) + hash.update(name) + + ary = hash.digest.unpack("NnnnnN") + ary[2] = (ary[2] & 0x0FFF) | (version << 12) + ary[3] = (ary[3] & 0x3FFF) | 0x8000 + + "%08x-%04x-%04x-%04x-%04x%08x" % ary + end + + # Convenience method for uuid_from_hash using OpenSSL::Digest::MD5. + def self.uuid_v3(uuid_namespace, name) + uuid_from_hash(OpenSSL::Digest::MD5, uuid_namespace, name) + end + + # Convenience method for uuid_from_hash using OpenSSL::Digest::SHA1. + def self.uuid_v5(uuid_namespace, name) + uuid_from_hash(OpenSSL::Digest::SHA1, uuid_namespace, name) + end + + # Convenience method for SecureRandom.uuid. + def self.uuid_v4 + SecureRandom.uuid + end + + def self.pack_uuid_namespace(namespace) + if [DNS_NAMESPACE, OID_NAMESPACE, URL_NAMESPACE, X500_NAMESPACE].include?(namespace) + namespace + elsif use_rfc4122_namespaced_uuids == true + match_data = namespace.match(/\A(\h{8})-(\h{4})-(\h{4})-(\h{4})-(\h{4})(\h{8})\z/) + + raise ArgumentError, "Only UUIDs are valid namespace identifiers" unless match_data.present? + + match_data.captures.map { |s| s.to_i(16) }.pack("NnnnnN") + else + ActiveSupport::Deprecation.warn <<~WARNING.squish + Providing a namespace ID that is not one of the constants defined on Digest::UUID generates an incorrect UUID value according to RFC 4122. + To enable the correct behavior, set the Rails.application.config.active_support.use_rfc4122_namespaced_uuids configuration option to true. + WARNING + + namespace + end + end + + private_class_method :pack_uuid_namespace + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/enumerable.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/enumerable.rb new file mode 100644 index 0000000..28be5be --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/enumerable.rb @@ -0,0 +1,312 @@ +# frozen_string_literal: true + +module Enumerable + INDEX_WITH_DEFAULT = Object.new + private_constant :INDEX_WITH_DEFAULT + + # Error generated by +sole+ when called on an enumerable that doesn't have + # exactly one item. + class SoleItemExpectedError < StandardError; end + + # Enumerable#sum was added in Ruby 2.4, but it only works with Numeric elements + # when we omit an identity. + + # :stopdoc: + + # We can't use Refinements here because Refinements with Module which will be prepended + # doesn't work well https://bugs.ruby-lang.org/issues/13446 + alias :_original_sum_with_required_identity :sum + private :_original_sum_with_required_identity + + # :startdoc: + + # Calculates the minimum from the extracted elements. + # + # payments = [Payment.new(5), Payment.new(15), Payment.new(10)] + # payments.minimum(:price) # => 5 + def minimum(key) + map(&key).min + end + + # Calculates the maximum from the extracted elements. + # + # payments = [Payment.new(5), Payment.new(15), Payment.new(10)] + # payments.maximum(:price) # => 15 + def maximum(key) + map(&key).max + end + + # Calculates a sum from the elements. + # + # payments.sum { |p| p.price * p.tax_rate } + # payments.sum(&:price) + # + # The latter is a shortcut for: + # + # payments.inject(0) { |sum, p| sum + p.price } + # + # It can also calculate the sum without the use of a block. + # + # [5, 15, 10].sum # => 30 + # ['foo', 'bar'].sum('') # => "foobar" + # [[1, 2], [3, 1, 5]].sum([]) # => [1, 2, 3, 1, 5] + # + # The default sum of an empty list is zero. You can override this default: + # + # [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0) + def sum(identity = nil, &block) + if identity + _original_sum_with_required_identity(identity, &block) + elsif block_given? + map(&block).sum + # we check `first(1) == []` to check if we have an + # empty Enumerable; checking `empty?` would return + # true for `[nil]`, which we want to deprecate to + # keep consistent with Ruby + elsif first.is_a?(Numeric) || first(1) == [] + identity ||= 0 + _original_sum_with_required_identity(identity, &block) + else + ActiveSupport::Deprecation.warn(<<-MSG.squish) + Rails 7.0 has deprecated Enumerable.sum in favor of Ruby's native implementation available since 2.4. + Sum of non-numeric elements requires an initial argument. + MSG + inject(:+) || 0 + end + end + + # Convert an enumerable to a hash, using the block result as the key and the + # element as the value. + # + # people.index_by(&:login) + # # => { "nextangle" => , "chade-" => , ...} + # + # people.index_by { |person| "#{person.first_name} #{person.last_name}" } + # # => { "Chade- Fowlersburg-e" => , "David Heinemeier Hansson" => , ...} + def index_by + if block_given? + result = {} + each { |elem| result[yield(elem)] = elem } + result + else + to_enum(:index_by) { size if respond_to?(:size) } + end + end + + # Convert an enumerable to a hash, using the element as the key and the block + # result as the value. + # + # post = Post.new(title: "hey there", body: "what's up?") + # + # %i( title body ).index_with { |attr_name| post.public_send(attr_name) } + # # => { title: "hey there", body: "what's up?" } + # + # If an argument is passed instead of a block, it will be used as the value + # for all elements: + # + # %i( created_at updated_at ).index_with(Time.now) + # # => { created_at: 2020-03-09 22:31:47, updated_at: 2020-03-09 22:31:47 } + def index_with(default = INDEX_WITH_DEFAULT) + if block_given? + result = {} + each { |elem| result[elem] = yield(elem) } + result + elsif default != INDEX_WITH_DEFAULT + result = {} + each { |elem| result[elem] = default } + result + else + to_enum(:index_with) { size if respond_to?(:size) } + end + end + + # Returns +true+ if the enumerable has more than 1 element. Functionally + # equivalent to enum.to_a.size > 1. Can be called with a block too, + # much like any?, so people.many? { |p| p.age > 26 } returns +true+ + # if more than one person is over 26. + def many? + cnt = 0 + if block_given? + any? do |element| + cnt += 1 if yield element + cnt > 1 + end + else + any? { (cnt += 1) > 1 } + end + end + + # Returns a new array that includes the passed elements. + # + # [ 1, 2, 3 ].including(4, 5) + # # => [ 1, 2, 3, 4, 5 ] + # + # ["David", "Rafael"].including %w[ Aaron Todd ] + # # => ["David", "Rafael", "Aaron", "Todd"] + def including(*elements) + to_a.including(*elements) + end + + # The negative of the Enumerable#include?. Returns +true+ if the + # collection does not include the object. + def exclude?(object) + !include?(object) + end + + # Returns a copy of the enumerable excluding the specified elements. + # + # ["David", "Rafael", "Aaron", "Todd"].excluding "Aaron", "Todd" + # # => ["David", "Rafael"] + # + # ["David", "Rafael", "Aaron", "Todd"].excluding %w[ Aaron Todd ] + # # => ["David", "Rafael"] + # + # {foo: 1, bar: 2, baz: 3}.excluding :bar + # # => {foo: 1, baz: 3} + def excluding(*elements) + elements.flatten!(1) + reject { |element| elements.include?(element) } + end + alias :without :excluding + + # Extract the given key from each element in the enumerable. + # + # [{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name) + # # => ["David", "Rafael", "Aaron"] + # + # [{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :name) + # # => [[1, "David"], [2, "Rafael"]] + def pluck(*keys) + if keys.many? + map { |element| keys.map { |key| element[key] } } + else + key = keys.first + map { |element| element[key] } + end + end + + # Extract the given key from the first element in the enumerable. + # + # [{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pick(:name) + # # => "David" + # + # [{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pick(:id, :name) + # # => [1, "David"] + def pick(*keys) + return if none? + + if keys.many? + keys.map { |key| first[key] } + else + first[keys.first] + end + end + + # Returns a new +Array+ without the blank items. + # Uses Object#blank? for determining if an item is blank. + # + # [1, "", nil, 2, " ", [], {}, false, true].compact_blank + # # => [1, 2, true] + # + # Set.new([nil, "", 1, 2]) + # # => [2, 1] (or [1, 2]) + # + # When called on a +Hash+, returns a new +Hash+ without the blank values. + # + # { a: "", b: 1, c: nil, d: [], e: false, f: true }.compact_blank + # # => { b: 1, f: true } + def compact_blank + reject(&:blank?) + end + + # Returns a new +Array+ where the order has been set to that provided in the +series+, based on the +key+ of the + # objects in the original enumerable. + # + # [ Person.find(5), Person.find(3), Person.find(1) ].in_order_of(:id, [ 1, 5, 3 ]) + # # => [ Person.find(1), Person.find(5), Person.find(3) ] + # + # If the +series+ include keys that have no corresponding element in the Enumerable, these are ignored. + # If the Enumerable has additional elements that aren't named in the +series+, these are not included in the result. + def in_order_of(key, series) + index_by(&key).values_at(*series).compact + end + + # Returns the sole item in the enumerable. If there are no items, or more + # than one item, raises +Enumerable::SoleItemExpectedError+. + # + # ["x"].sole # => "x" + # Set.new.sole # => Enumerable::SoleItemExpectedError: no item found + # { a: 1, b: 2 }.sole # => Enumerable::SoleItemExpectedError: multiple items found + def sole + case count + when 1 then return first # rubocop:disable Style/RedundantReturn + when 0 then raise SoleItemExpectedError, "no item found" + when 2.. then raise SoleItemExpectedError, "multiple items found" + end + end +end + +class Hash + # Hash#reject has its own definition, so this needs one too. + def compact_blank # :nodoc: + reject { |_k, v| v.blank? } + end + + # Removes all blank values from the +Hash+ in place and returns self. + # Uses Object#blank? for determining if a value is blank. + # + # h = { a: "", b: 1, c: nil, d: [], e: false, f: true } + # h.compact_blank! + # # => { b: 1, f: true } + def compact_blank! + # use delete_if rather than reject! because it always returns self even if nothing changed + delete_if { |_k, v| v.blank? } + end +end + +class Range # :nodoc: + # Optimize range sum to use arithmetic progression if a block is not given and + # we have a range of numeric values. + def sum(identity = nil) + if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer)) + super + else + actual_last = exclude_end? ? (last - 1) : last + if actual_last >= first + sum = identity || 0 + sum + (actual_last - first + 1) * (actual_last + first) / 2 + else + identity || 0 + end + end + end +end + +# Using Refinements here in order not to expose our internal method +using Module.new { + refine Array do + alias :orig_sum :sum + end +} + +class Array # :nodoc: + def sum(init = nil, &block) + if init.is_a?(Numeric) || first.is_a?(Numeric) + init ||= 0 + orig_sum(init, &block) + else + super + end + end + + # Removes all blank elements from the +Array+ in place and returns self. + # Uses Object#blank? for determining if an item is blank. + # + # a = [1, "", nil, 2, " ", [], {}, false, true] + # a.compact_blank! + # # => [1, 2, true] + def compact_blank! + # use delete_if rather than reject! because it always returns self even if nothing changed + delete_if(&:blank?) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/file.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/file.rb new file mode 100644 index 0000000..64553bf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/file.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +require "active_support/core_ext/file/atomic" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/file/atomic.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/file/atomic.rb new file mode 100644 index 0000000..b442ea3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/file/atomic.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +require "fileutils" + +class File + # Write to a file atomically. Useful for situations where you don't + # want other processes or threads to see half-written files. + # + # File.atomic_write('important.file') do |file| + # file.write('hello') + # end + # + # This method needs to create a temporary file. By default it will create it + # in the same directory as the destination file. If you don't like this + # behavior you can provide a different directory but it must be on the + # same physical filesystem as the file you're trying to write. + # + # File.atomic_write('/data/something.important', '/data/tmp') do |file| + # file.write('hello') + # end + def self.atomic_write(file_name, temp_dir = dirname(file_name)) + require "tempfile" unless defined?(Tempfile) + + Tempfile.open(".#{basename(file_name)}", temp_dir) do |temp_file| + temp_file.binmode + return_val = yield temp_file + temp_file.close + + old_stat = if exist?(file_name) + # Get original file permissions + stat(file_name) + else + # If not possible, probe which are the default permissions in the + # destination directory. + probe_stat_in(dirname(file_name)) + end + + if old_stat + # Set correct permissions on new file + begin + chown(old_stat.uid, old_stat.gid, temp_file.path) + # This operation will affect filesystem ACL's + chmod(old_stat.mode, temp_file.path) + rescue Errno::EPERM, Errno::EACCES + # Changing file ownership failed, moving on. + end + end + + # Overwrite original file with temp file + rename(temp_file.path, file_name) + return_val + end + end + + # Private utility method. + def self.probe_stat_in(dir) # :nodoc: + basename = [ + ".permissions_check", + Thread.current.object_id, + Process.pid, + rand(1000000) + ].join(".") + + file_name = join(dir, basename) + FileUtils.touch(file_name) + stat(file_name) + rescue Errno::ENOENT + file_name = nil + ensure + FileUtils.rm_f(file_name) if file_name + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash.rb new file mode 100644 index 0000000..2f0901d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require "active_support/core_ext/hash/conversions" +require "active_support/core_ext/hash/deep_merge" +require "active_support/core_ext/hash/deep_transform_values" +require "active_support/core_ext/hash/except" +require "active_support/core_ext/hash/indifferent_access" +require "active_support/core_ext/hash/keys" +require "active_support/core_ext/hash/reverse_merge" +require "active_support/core_ext/hash/slice" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/conversions.rb new file mode 100644 index 0000000..2b5e484 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/conversions.rb @@ -0,0 +1,263 @@ +# frozen_string_literal: true + +require "active_support/xml_mini" +require "active_support/core_ext/object/blank" +require "active_support/core_ext/object/to_param" +require "active_support/core_ext/object/to_query" +require "active_support/core_ext/object/try" +require "active_support/core_ext/array/wrap" +require "active_support/core_ext/hash/reverse_merge" +require "active_support/core_ext/string/inflections" + +class Hash + # Returns a string containing an XML representation of its receiver: + # + # { foo: 1, bar: 2 }.to_xml + # # => + # # + # # + # # 1 + # # 2 + # # + # + # To do so, the method loops over the pairs and builds nodes that depend on + # the _values_. Given a pair +key+, +value+: + # + # * If +value+ is a hash there's a recursive call with +key+ as :root. + # + # * If +value+ is an array there's a recursive call with +key+ as :root, + # and +key+ singularized as :children. + # + # * If +value+ is a callable object it must expect one or two arguments. Depending + # on the arity, the callable is invoked with the +options+ hash as first argument + # with +key+ as :root, and +key+ singularized as second argument. The + # callable can add nodes by using options[:builder]. + # + # {foo: lambda { |options, key| options[:builder].b(key) }}.to_xml + # # => "foo" + # + # * If +value+ responds to +to_xml+ the method is invoked with +key+ as :root. + # + # class Foo + # def to_xml(options) + # options[:builder].bar 'fooing!' + # end + # end + # + # { foo: Foo.new }.to_xml(skip_instruct: true) + # # => + # # + # # fooing! + # # + # + # * Otherwise, a node with +key+ as tag is created with a string representation of + # +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added. + # Unless the option :skip_types exists and is true, an attribute "type" is + # added as well according to the following mapping: + # + # XML_TYPE_NAMES = { + # "Symbol" => "symbol", + # "Integer" => "integer", + # "BigDecimal" => "decimal", + # "Float" => "float", + # "TrueClass" => "boolean", + # "FalseClass" => "boolean", + # "Date" => "date", + # "DateTime" => "dateTime", + # "Time" => "dateTime" + # } + # + # By default the root node is "hash", but that's configurable via the :root option. + # + # The default XML builder is a fresh instance of Builder::XmlMarkup. You can + # configure your own builder with the :builder option. The method also accepts + # options like :dasherize and friends, they are forwarded to the builder. + def to_xml(options = {}) + require "active_support/builder" unless defined?(Builder::XmlMarkup) + + options = options.dup + options[:indent] ||= 2 + options[:root] ||= "hash" + options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent]) + + builder = options[:builder] + builder.instruct! unless options.delete(:skip_instruct) + + root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options) + + builder.tag!(root) do + each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) } + yield builder if block_given? + end + end + + class << self + # Returns a Hash containing a collection of pairs when the key is the node name and the value is + # its content + # + # xml = <<-XML + # + # + # 1 + # 2 + # + # XML + # + # hash = Hash.from_xml(xml) + # # => {"hash"=>{"foo"=>1, "bar"=>2}} + # + # +DisallowedType+ is raised if the XML contains attributes with type="yaml" or + # type="symbol". Use Hash.from_trusted_xml to + # parse this XML. + # + # Custom +disallowed_types+ can also be passed in the form of an + # array. + # + # xml = <<-XML + # + # + # 1 + # "David" + # + # XML + # + # hash = Hash.from_xml(xml, ['integer']) + # # => ActiveSupport::XMLConverter::DisallowedType: Disallowed type attribute: "integer" + # + # Note that passing custom disallowed types will override the default types, + # which are Symbol and YAML. + def from_xml(xml, disallowed_types = nil) + ActiveSupport::XMLConverter.new(xml, disallowed_types).to_h + end + + # Builds a Hash from XML just like Hash.from_xml, but also allows Symbol and YAML. + def from_trusted_xml(xml) + from_xml xml, [] + end + end +end + +module ActiveSupport + class XMLConverter # :nodoc: + # Raised if the XML contains attributes with type="yaml" or + # type="symbol". Read Hash#from_xml for more details. + class DisallowedType < StandardError + def initialize(type) + super "Disallowed type attribute: #{type.inspect}" + end + end + + DISALLOWED_TYPES = %w(symbol yaml) + + def initialize(xml, disallowed_types = nil) + @xml = normalize_keys(XmlMini.parse(xml)) + @disallowed_types = disallowed_types || DISALLOWED_TYPES + end + + def to_h + deep_to_h(@xml) + end + + private + def normalize_keys(params) + case params + when Hash + Hash[params.map { |k, v| [k.to_s.tr("-", "_"), normalize_keys(v)] } ] + when Array + params.map { |v| normalize_keys(v) } + else + params + end + end + + def deep_to_h(value) + case value + when Hash + process_hash(value) + when Array + process_array(value) + when String + value + else + raise "can't typecast #{value.class.name} - #{value.inspect}" + end + end + + def process_hash(value) + if value.include?("type") && !value["type"].is_a?(Hash) && @disallowed_types.include?(value["type"]) + raise DisallowedType, value["type"] + end + + if become_array?(value) + _, entries = Array.wrap(value.detect { |k, v| not v.is_a?(String) }) + if entries.nil? || value["__content__"].try(:empty?) + [] + else + case entries + when Array + entries.collect { |v| deep_to_h(v) } + when Hash + [deep_to_h(entries)] + else + raise "can't typecast #{entries.inspect}" + end + end + elsif become_content?(value) + process_content(value) + + elsif become_empty_string?(value) + "" + elsif become_hash?(value) + xml_value = value.transform_values { |v| deep_to_h(v) } + + # Turn { files: { file: # } } into { files: # } so it is compatible with + # how multipart uploaded files from HTML appear + xml_value["file"].is_a?(StringIO) ? xml_value["file"] : xml_value + end + end + + def become_content?(value) + value["type"] == "file" || (value["__content__"] && (value.keys.size == 1 || value["__content__"].present?)) + end + + def become_array?(value) + value["type"] == "array" + end + + def become_empty_string?(value) + # { "string" => true } + # No tests fail when the second term is removed. + value["type"] == "string" && value["nil"] != "true" + end + + def become_hash?(value) + !nothing?(value) && !garbage?(value) + end + + def nothing?(value) + # blank or nil parsed values are represented by nil + value.blank? || value["nil"] == "true" + end + + def garbage?(value) + # If the type is the only element which makes it then + # this still makes the value nil, except if type is + # an XML node(where type['value'] is a Hash) + value["type"] && !value["type"].is_a?(::Hash) && value.size == 1 + end + + def process_content(value) + content = value["__content__"] + if parser = ActiveSupport::XmlMini::PARSING[value["type"]] + parser.arity == 1 ? parser.call(content) : parser.call(content, value) + else + content + end + end + + def process_array(value) + value.map! { |i| deep_to_h(i) } + value.length > 1 ? value : value.first + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/deep_merge.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/deep_merge.rb new file mode 100644 index 0000000..9bc50b7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/deep_merge.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +class Hash + # Returns a new hash with +self+ and +other_hash+ merged recursively. + # + # h1 = { a: true, b: { c: [1, 2, 3] } } + # h2 = { a: false, b: { x: [3, 4, 5] } } + # + # h1.deep_merge(h2) # => { a: false, b: { c: [1, 2, 3], x: [3, 4, 5] } } + # + # Like with Hash#merge in the standard library, a block can be provided + # to merge values: + # + # h1 = { a: 100, b: 200, c: { c1: 100 } } + # h2 = { b: 250, c: { c1: 200 } } + # h1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val } + # # => { a: 100, b: 450, c: { c1: 300 } } + def deep_merge(other_hash, &block) + dup.deep_merge!(other_hash, &block) + end + + # Same as +deep_merge+, but modifies +self+. + def deep_merge!(other_hash, &block) + merge!(other_hash) do |key, this_val, other_val| + if this_val.is_a?(Hash) && other_val.is_a?(Hash) + this_val.deep_merge(other_val, &block) + elsif block_given? + block.call(key, this_val, other_val) + else + other_val + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/deep_transform_values.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/deep_transform_values.rb new file mode 100644 index 0000000..8ad85c0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/deep_transform_values.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +class Hash + # Returns a new hash with all values converted by the block operation. + # This includes the values from the root hash and from all + # nested hashes and arrays. + # + # hash = { person: { name: 'Rob', age: '28' } } + # + # hash.deep_transform_values{ |value| value.to_s.upcase } + # # => {person: {name: "ROB", age: "28"}} + def deep_transform_values(&block) + _deep_transform_values_in_object(self, &block) + end + + # Destructively converts all values by using the block operation. + # This includes the values from the root hash and from all + # nested hashes and arrays. + def deep_transform_values!(&block) + _deep_transform_values_in_object!(self, &block) + end + + private + # Support methods for deep transforming nested hashes and arrays. + def _deep_transform_values_in_object(object, &block) + case object + when Hash + object.transform_values { |value| _deep_transform_values_in_object(value, &block) } + when Array + object.map { |e| _deep_transform_values_in_object(e, &block) } + else + yield(object) + end + end + + def _deep_transform_values_in_object!(object, &block) + case object + when Hash + object.transform_values! { |value| _deep_transform_values_in_object!(value, &block) } + when Array + object.map! { |e| _deep_transform_values_in_object!(e, &block) } + else + yield(object) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/except.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/except.rb new file mode 100644 index 0000000..ec96929 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/except.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +class Hash + # Returns a hash that includes everything except given keys. + # hash = { a: true, b: false, c: nil } + # hash.except(:c) # => { a: true, b: false } + # hash.except(:a, :b) # => { c: nil } + # hash # => { a: true, b: false, c: nil } + # + # This is useful for limiting a set of parameters to everything but a few known toggles: + # @person.update(params[:person].except(:admin)) + def except(*keys) + slice(*self.keys - keys) + end unless method_defined?(:except) + + # Removes the given keys from hash and returns it. + # hash = { a: true, b: false, c: nil } + # hash.except!(:c) # => { a: true, b: false } + # hash # => { a: true, b: false } + def except!(*keys) + keys.each { |key| delete(key) } + self + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/indifferent_access.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/indifferent_access.rb new file mode 100644 index 0000000..a38f33f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/indifferent_access.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +require "active_support/hash_with_indifferent_access" + +class Hash + # Returns an ActiveSupport::HashWithIndifferentAccess out of its receiver: + # + # { a: 1 }.with_indifferent_access['a'] # => 1 + def with_indifferent_access + ActiveSupport::HashWithIndifferentAccess.new(self) + end + + # Called when object is nested under an object that receives + # #with_indifferent_access. This method will be called on the current object + # by the enclosing object and is aliased to #with_indifferent_access by + # default. Subclasses of Hash may overwrite this method to return +self+ if + # converting to an ActiveSupport::HashWithIndifferentAccess would not be + # desirable. + # + # b = { b: 1 } + # { a: b }.with_indifferent_access['a'] # calls b.nested_under_indifferent_access + # # => {"b"=>1} + alias nested_under_indifferent_access with_indifferent_access +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/keys.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/keys.rb new file mode 100644 index 0000000..73487e0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/keys.rb @@ -0,0 +1,143 @@ +# frozen_string_literal: true + +class Hash + # Returns a new hash with all keys converted to strings. + # + # hash = { name: 'Rob', age: '28' } + # + # hash.stringify_keys + # # => {"name"=>"Rob", "age"=>"28"} + def stringify_keys + transform_keys(&:to_s) + end + + # Destructively converts all keys to strings. Same as + # +stringify_keys+, but modifies +self+. + def stringify_keys! + transform_keys!(&:to_s) + end + + # Returns a new hash with all keys converted to symbols, as long as + # they respond to +to_sym+. + # + # hash = { 'name' => 'Rob', 'age' => '28' } + # + # hash.symbolize_keys + # # => {:name=>"Rob", :age=>"28"} + def symbolize_keys + transform_keys { |key| key.to_sym rescue key } + end + alias_method :to_options, :symbolize_keys + + # Destructively converts all keys to symbols, as long as they respond + # to +to_sym+. Same as +symbolize_keys+, but modifies +self+. + def symbolize_keys! + transform_keys! { |key| key.to_sym rescue key } + end + alias_method :to_options!, :symbolize_keys! + + # Validates all keys in a hash match *valid_keys, raising + # +ArgumentError+ on a mismatch. + # + # Note that keys are treated differently than HashWithIndifferentAccess, + # meaning that string and symbol keys will not match. + # + # { name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age" + # { name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'" + # { name: 'Rob', age: '28' }.assert_valid_keys(:name, :age) # => passes, raises nothing + def assert_valid_keys(*valid_keys) + valid_keys.flatten! + each_key do |k| + unless valid_keys.include?(k) + raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}") + end + end + end + + # Returns a new hash with all keys converted by the block operation. + # This includes the keys from the root hash and from all + # nested hashes and arrays. + # + # hash = { person: { name: 'Rob', age: '28' } } + # + # hash.deep_transform_keys{ |key| key.to_s.upcase } + # # => {"PERSON"=>{"NAME"=>"Rob", "AGE"=>"28"}} + def deep_transform_keys(&block) + _deep_transform_keys_in_object(self, &block) + end + + # Destructively converts all keys by using the block operation. + # This includes the keys from the root hash and from all + # nested hashes and arrays. + def deep_transform_keys!(&block) + _deep_transform_keys_in_object!(self, &block) + end + + # Returns a new hash with all keys converted to strings. + # This includes the keys from the root hash and from all + # nested hashes and arrays. + # + # hash = { person: { name: 'Rob', age: '28' } } + # + # hash.deep_stringify_keys + # # => {"person"=>{"name"=>"Rob", "age"=>"28"}} + def deep_stringify_keys + deep_transform_keys(&:to_s) + end + + # Destructively converts all keys to strings. + # This includes the keys from the root hash and from all + # nested hashes and arrays. + def deep_stringify_keys! + deep_transform_keys!(&:to_s) + end + + # Returns a new hash with all keys converted to symbols, as long as + # they respond to +to_sym+. This includes the keys from the root hash + # and from all nested hashes and arrays. + # + # hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } } + # + # hash.deep_symbolize_keys + # # => {:person=>{:name=>"Rob", :age=>"28"}} + def deep_symbolize_keys + deep_transform_keys { |key| key.to_sym rescue key } + end + + # Destructively converts all keys to symbols, as long as they respond + # to +to_sym+. This includes the keys from the root hash and from all + # nested hashes and arrays. + def deep_symbolize_keys! + deep_transform_keys! { |key| key.to_sym rescue key } + end + + private + # Support methods for deep transforming nested hashes and arrays. + def _deep_transform_keys_in_object(object, &block) + case object + when Hash + object.each_with_object(self.class.new) do |(key, value), result| + result[yield(key)] = _deep_transform_keys_in_object(value, &block) + end + when Array + object.map { |e| _deep_transform_keys_in_object(e, &block) } + else + object + end + end + + def _deep_transform_keys_in_object!(object, &block) + case object + when Hash + object.keys.each do |key| + value = object.delete(key) + object[yield(key)] = _deep_transform_keys_in_object!(value, &block) + end + object + when Array + object.map! { |e| _deep_transform_keys_in_object!(e, &block) } + else + object + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/reverse_merge.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/reverse_merge.rb new file mode 100644 index 0000000..ef8d592 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/reverse_merge.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +class Hash + # Merges the caller into +other_hash+. For example, + # + # options = options.reverse_merge(size: 25, velocity: 10) + # + # is equivalent to + # + # options = { size: 25, velocity: 10 }.merge(options) + # + # This is particularly useful for initializing an options hash + # with default values. + def reverse_merge(other_hash) + other_hash.merge(self) + end + alias_method :with_defaults, :reverse_merge + + # Destructive +reverse_merge+. + def reverse_merge!(other_hash) + replace(reverse_merge(other_hash)) + end + alias_method :reverse_update, :reverse_merge! + alias_method :with_defaults!, :reverse_merge! +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/slice.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/slice.rb new file mode 100644 index 0000000..56bc5de --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/hash/slice.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +class Hash + # Replaces the hash with only the given keys. + # Returns a hash containing the removed key/value pairs. + # + # hash = { a: 1, b: 2, c: 3, d: 4 } + # hash.slice!(:a, :b) # => {:c=>3, :d=>4} + # hash # => {:a=>1, :b=>2} + def slice!(*keys) + omit = slice(*self.keys - keys) + hash = slice(*keys) + hash.default = default + hash.default_proc = default_proc if default_proc + replace(hash) + omit + end + + # Removes and returns the key/value pairs matching the given keys. + # + # hash = { a: 1, b: 2, c: 3, d: 4 } + # hash.extract!(:a, :b) # => {:a=>1, :b=>2} + # hash # => {:c=>3, :d=>4} + def extract!(*keys) + keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer.rb new file mode 100644 index 0000000..d227013 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +require "active_support/core_ext/integer/multiple" +require "active_support/core_ext/integer/inflections" +require "active_support/core_ext/integer/time" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer/inflections.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer/inflections.rb new file mode 100644 index 0000000..aef3266 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer/inflections.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require "active_support/inflector" + +class Integer + # Ordinalize turns a number into an ordinal string used to denote the + # position in an ordered sequence such as 1st, 2nd, 3rd, 4th. + # + # 1.ordinalize # => "1st" + # 2.ordinalize # => "2nd" + # 1002.ordinalize # => "1002nd" + # 1003.ordinalize # => "1003rd" + # -11.ordinalize # => "-11th" + # -1001.ordinalize # => "-1001st" + def ordinalize + ActiveSupport::Inflector.ordinalize(self) + end + + # Ordinal returns the suffix used to denote the position + # in an ordered sequence such as 1st, 2nd, 3rd, 4th. + # + # 1.ordinal # => "st" + # 2.ordinal # => "nd" + # 1002.ordinal # => "nd" + # 1003.ordinal # => "rd" + # -11.ordinal # => "th" + # -1001.ordinal # => "st" + def ordinal + ActiveSupport::Inflector.ordinal(self) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer/multiple.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer/multiple.rb new file mode 100644 index 0000000..bd57a90 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer/multiple.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +class Integer + # Check whether the integer is evenly divisible by the argument. + # + # 0.multiple_of?(0) # => true + # 6.multiple_of?(5) # => false + # 10.multiple_of?(2) # => true + def multiple_of?(number) + number == 0 ? self == 0 : self % number == 0 + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer/time.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer/time.rb new file mode 100644 index 0000000..5efb89c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/integer/time.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +require "active_support/duration" +require "active_support/core_ext/numeric/time" + +class Integer + # Returns a Duration instance matching the number of months provided. + # + # 2.months # => 2 months + def months + ActiveSupport::Duration.months(self) + end + alias :month :months + + # Returns a Duration instance matching the number of years provided. + # + # 2.years # => 2 years + def years + ActiveSupport::Duration.years(self) + end + alias :year :years +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel.rb new file mode 100644 index 0000000..7708069 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +require "active_support/core_ext/kernel/concern" +require "active_support/core_ext/kernel/reporting" +require "active_support/core_ext/kernel/singleton_class" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel/concern.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel/concern.rb new file mode 100644 index 0000000..0b2baed --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel/concern.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/concerning" + +module Kernel + module_function + + # A shortcut to define a toplevel concern, not within a module. + # + # See Module::Concerning for more. + def concern(topic, &module_definition) + Object.concern topic, &module_definition + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel/reporting.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel/reporting.rb new file mode 100644 index 0000000..1ae1ae8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel/reporting.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +module Kernel + module_function + + # Sets $VERBOSE to +nil+ for the duration of the block and back to its original + # value afterwards. + # + # silence_warnings do + # value = noisy_call # no warning voiced + # end + # + # noisy_call # warning voiced + def silence_warnings(&block) + with_warnings(nil, &block) + end + + # Sets $VERBOSE to +true+ for the duration of the block and back to its + # original value afterwards. + def enable_warnings(&block) + with_warnings(true, &block) + end + + # Sets $VERBOSE for the duration of the block and back to its original + # value afterwards. + def with_warnings(flag) + old_verbose, $VERBOSE = $VERBOSE, flag + yield + ensure + $VERBOSE = old_verbose + end + + # Blocks and ignores any exception passed as argument if raised within the block. + # + # suppress(ZeroDivisionError) do + # 1/0 + # puts 'This code is NOT reached' + # end + # + # puts 'This code gets executed and nothing related to ZeroDivisionError was seen' + def suppress(*exception_classes) + yield + rescue *exception_classes + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel/singleton_class.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel/singleton_class.rb new file mode 100644 index 0000000..6715eba --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/kernel/singleton_class.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +module Kernel + # class_eval on an object acts like singleton_class.class_eval. + def class_eval(*args, &block) + singleton_class.class_eval(*args, &block) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/load_error.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/load_error.rb new file mode 100644 index 0000000..03df2dd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/load_error.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +class LoadError + # Returns true if the given path name (except perhaps for the ".rb" + # extension) is the missing file which caused the exception to be raised. + def is_missing?(location) + location.delete_suffix(".rb") == path.to_s.delete_suffix(".rb") + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module.rb new file mode 100644 index 0000000..542af98 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/aliasing" +require "active_support/core_ext/module/introspection" +require "active_support/core_ext/module/anonymous" +require "active_support/core_ext/module/attribute_accessors" +require "active_support/core_ext/module/attribute_accessors_per_thread" +require "active_support/core_ext/module/attr_internal" +require "active_support/core_ext/module/concerning" +require "active_support/core_ext/module/delegation" +require "active_support/core_ext/module/deprecation" +require "active_support/core_ext/module/redefine_method" +require "active_support/core_ext/module/remove_method" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/aliasing.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/aliasing.rb new file mode 100644 index 0000000..6f64d11 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/aliasing.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +class Module + # Allows you to make aliases for attributes, which includes + # getter, setter, and a predicate. + # + # class Content < ActiveRecord::Base + # # has a title attribute + # end + # + # class Email < Content + # alias_attribute :subject, :title + # end + # + # e = Email.find(1) + # e.title # => "Superstars" + # e.subject # => "Superstars" + # e.subject? # => true + # e.subject = "Megastars" + # e.title # => "Megastars" + def alias_attribute(new_name, old_name) + # The following reader methods use an explicit `self` receiver in order to + # support aliases that start with an uppercase letter. Otherwise, they would + # be resolved as constants instead. + module_eval <<-STR, __FILE__, __LINE__ + 1 + def #{new_name}; self.#{old_name}; end # def subject; self.title; end + def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end + def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end + STR + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/anonymous.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/anonymous.rb new file mode 100644 index 0000000..d1c86b8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/anonymous.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +class Module + # A module may or may not have a name. + # + # module M; end + # M.name # => "M" + # + # m = Module.new + # m.name # => nil + # + # +anonymous?+ method returns true if module does not have a name, false otherwise: + # + # Module.new.anonymous? # => true + # + # module M; end + # M.anonymous? # => false + # + # A module gets a name when it is first assigned to a constant. Either + # via the +module+ or +class+ keyword or by an explicit assignment: + # + # m = Module.new # creates an anonymous module + # m.anonymous? # => true + # M = m # m gets a name here as a side-effect + # m.name # => "M" + # m.anonymous? # => false + def anonymous? + name.nil? + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/attr_internal.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/attr_internal.rb new file mode 100644 index 0000000..3bd66ff --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/attr_internal.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +class Module + # Declares an attribute reader backed by an internally-named instance variable. + def attr_internal_reader(*attrs) + attrs.each { |attr_name| attr_internal_define(attr_name, :reader) } + end + + # Declares an attribute writer backed by an internally-named instance variable. + def attr_internal_writer(*attrs) + attrs.each { |attr_name| attr_internal_define(attr_name, :writer) } + end + + # Declares an attribute reader and writer backed by an internally-named instance + # variable. + def attr_internal_accessor(*attrs) + attr_internal_reader(*attrs) + attr_internal_writer(*attrs) + end + alias_method :attr_internal, :attr_internal_accessor + + class << self; attr_accessor :attr_internal_naming_format end + self.attr_internal_naming_format = "@_%s" + + private + def attr_internal_ivar_name(attr) + Module.attr_internal_naming_format % attr + end + + def attr_internal_define(attr_name, type) + internal_name = attr_internal_ivar_name(attr_name).delete_prefix("@") + # use native attr_* methods as they are faster on some Ruby implementations + public_send("attr_#{type}", internal_name) + attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer + alias_method attr_name, internal_name + remove_method internal_name + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/attribute_accessors.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/attribute_accessors.rb new file mode 100644 index 0000000..f7903af --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/attribute_accessors.rb @@ -0,0 +1,208 @@ +# frozen_string_literal: true + +# == Attribute Accessors +# +# Extends the module object with class/module and instance accessors for +# class/module attributes, just like the native attr* accessors for instance +# attributes. +class Module + # Defines a class attribute and creates a class and instance reader methods. + # The underlying class variable is set to +nil+, if it is not previously + # defined. All class and instance methods created will be public, even if + # this method is called with a private or protected access modifier. + # + # module HairColors + # mattr_reader :hair_colors + # end + # + # HairColors.hair_colors # => nil + # HairColors.class_variable_set("@@hair_colors", [:brown, :black]) + # HairColors.hair_colors # => [:brown, :black] + # + # The attribute name must be a valid method name in Ruby. + # + # module Foo + # mattr_reader :"1_Badname" + # end + # # => NameError: invalid attribute name: 1_Badname + # + # To omit the instance reader method, pass + # instance_reader: false or instance_accessor: false. + # + # module HairColors + # mattr_reader :hair_colors, instance_reader: false + # end + # + # class Person + # include HairColors + # end + # + # Person.new.hair_colors # => NoMethodError + # + # You can set a default value for the attribute. + # + # module HairColors + # mattr_reader :hair_colors, default: [:brown, :black, :blonde, :red] + # end + # + # class Person + # include HairColors + # end + # + # Person.new.hair_colors # => [:brown, :black, :blonde, :red] + def mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil, location: nil) + raise TypeError, "module attributes should be defined directly on class, not singleton" if singleton_class? + location ||= caller_locations(1, 1).first + + definition = [] + syms.each do |sym| + raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym) + + definition << "def self.#{sym}; @@#{sym}; end" + + if instance_reader && instance_accessor + definition << "def #{sym}; @@#{sym}; end" + end + + sym_default_value = (block_given? && default.nil?) ? yield : default + class_variable_set("@@#{sym}", sym_default_value) unless sym_default_value.nil? && class_variable_defined?("@@#{sym}") + end + + module_eval(definition.join(";"), location.path, location.lineno) + end + alias :cattr_reader :mattr_reader + + # Defines a class attribute and creates a class and instance writer methods to + # allow assignment to the attribute. All class and instance methods created + # will be public, even if this method is called with a private or protected + # access modifier. + # + # module HairColors + # mattr_writer :hair_colors + # end + # + # class Person + # include HairColors + # end + # + # HairColors.hair_colors = [:brown, :black] + # Person.class_variable_get("@@hair_colors") # => [:brown, :black] + # Person.new.hair_colors = [:blonde, :red] + # HairColors.class_variable_get("@@hair_colors") # => [:blonde, :red] + # + # To omit the instance writer method, pass + # instance_writer: false or instance_accessor: false. + # + # module HairColors + # mattr_writer :hair_colors, instance_writer: false + # end + # + # class Person + # include HairColors + # end + # + # Person.new.hair_colors = [:blonde, :red] # => NoMethodError + # + # You can set a default value for the attribute. + # + # module HairColors + # mattr_writer :hair_colors, default: [:brown, :black, :blonde, :red] + # end + # + # class Person + # include HairColors + # end + # + # Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red] + def mattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil, location: nil) + raise TypeError, "module attributes should be defined directly on class, not singleton" if singleton_class? + location ||= caller_locations(1, 1).first + + definition = [] + syms.each do |sym| + raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym) + definition << "def self.#{sym}=(val); @@#{sym} = val; end" + + if instance_writer && instance_accessor + definition << "def #{sym}=(val); @@#{sym} = val; end" + end + + sym_default_value = (block_given? && default.nil?) ? yield : default + class_variable_set("@@#{sym}", sym_default_value) unless sym_default_value.nil? && class_variable_defined?("@@#{sym}") + end + + module_eval(definition.join(";"), location.path, location.lineno) + end + alias :cattr_writer :mattr_writer + + # Defines both class and instance accessors for class attributes. + # All class and instance methods created will be public, even if + # this method is called with a private or protected access modifier. + # + # module HairColors + # mattr_accessor :hair_colors + # end + # + # class Person + # include HairColors + # end + # + # HairColors.hair_colors = [:brown, :black, :blonde, :red] + # HairColors.hair_colors # => [:brown, :black, :blonde, :red] + # Person.new.hair_colors # => [:brown, :black, :blonde, :red] + # + # If a subclass changes the value then that would also change the value for + # parent class. Similarly if parent class changes the value then that would + # change the value of subclasses too. + # + # class Citizen < Person + # end + # + # Citizen.new.hair_colors << :blue + # Person.new.hair_colors # => [:brown, :black, :blonde, :red, :blue] + # + # To omit the instance writer method, pass instance_writer: false. + # To omit the instance reader method, pass instance_reader: false. + # + # module HairColors + # mattr_accessor :hair_colors, instance_writer: false, instance_reader: false + # end + # + # class Person + # include HairColors + # end + # + # Person.new.hair_colors = [:brown] # => NoMethodError + # Person.new.hair_colors # => NoMethodError + # + # Or pass instance_accessor: false, to omit both instance methods. + # + # module HairColors + # mattr_accessor :hair_colors, instance_accessor: false + # end + # + # class Person + # include HairColors + # end + # + # Person.new.hair_colors = [:brown] # => NoMethodError + # Person.new.hair_colors # => NoMethodError + # + # You can set a default value for the attribute. + # + # module HairColors + # mattr_accessor :hair_colors, default: [:brown, :black, :blonde, :red] + # end + # + # class Person + # include HairColors + # end + # + # Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red] + def mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil, &blk) + location = caller_locations(1, 1).first + mattr_reader(*syms, instance_reader: instance_reader, instance_accessor: instance_accessor, default: default, location: location, &blk) + mattr_writer(*syms, instance_writer: instance_writer, instance_accessor: instance_accessor, default: default, location: location) + end + alias :cattr_accessor :mattr_accessor +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb new file mode 100644 index 0000000..850affa --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb @@ -0,0 +1,157 @@ +# frozen_string_literal: true + +# == Attribute Accessors per Thread +# +# Extends the module object with class/module and instance accessors for +# class/module attributes, just like the native attr* accessors for instance +# attributes, but does so on a per-thread basis. +# +# So the values are scoped within the Thread.current space under the class name +# of the module. +# +# Note that it can also be scoped per-fiber if Rails.application.config.active_support.isolation_level +# is set to `:fiber` +class Module + # Defines a per-thread class attribute and creates class and instance reader methods. + # The underlying per-thread class variable is set to +nil+, if it is not previously defined. + # + # module Current + # thread_mattr_reader :user + # end + # + # Current.user = "DHH" + # Current.user # => "DHH" + # Thread.new { Current.user }.values # => nil + # + # The attribute name must be a valid method name in Ruby. + # + # module Foo + # thread_mattr_reader :"1_Badname" + # end + # # => NameError: invalid attribute name: 1_Badname + # + # To omit the instance reader method, pass + # instance_reader: false or instance_accessor: false. + # + # class Current + # thread_mattr_reader :user, instance_reader: false + # end + # + # Current.new.user # => NoMethodError + def thread_mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil) # :nodoc: + syms.each do |sym| + raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym) + + # The following generated method concatenates `name` because we want it + # to work with inheritance via polymorphism. + class_eval(<<-EOS, __FILE__, __LINE__ + 1) + def self.#{sym} + @__thread_mattr_#{sym} ||= "attr_\#{name}_#{sym}" + ::ActiveSupport::IsolatedExecutionState[@__thread_mattr_#{sym}] + end + EOS + + if instance_reader && instance_accessor + class_eval(<<-EOS, __FILE__, __LINE__ + 1) + def #{sym} + self.class.#{sym} + end + EOS + end + + ::ActiveSupport::IsolatedExecutionState["attr_#{name}_#{sym}"] = default unless default.nil? + end + end + alias :thread_cattr_reader :thread_mattr_reader + + # Defines a per-thread class attribute and creates a class and instance writer methods to + # allow assignment to the attribute. + # + # module Current + # thread_mattr_writer :user + # end + # + # Current.user = "DHH" + # Thread.current[:attr_Current_user] # => "DHH" + # + # To omit the instance writer method, pass + # instance_writer: false or instance_accessor: false. + # + # class Current + # thread_mattr_writer :user, instance_writer: false + # end + # + # Current.new.user = "DHH" # => NoMethodError + def thread_mattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil) # :nodoc: + syms.each do |sym| + raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym) + + # The following generated method concatenates `name` because we want it + # to work with inheritance via polymorphism. + class_eval(<<-EOS, __FILE__, __LINE__ + 1) + def self.#{sym}=(obj) + @__thread_mattr_#{sym} ||= "attr_\#{name}_#{sym}" + ::ActiveSupport::IsolatedExecutionState[@__thread_mattr_#{sym}] = obj + end + EOS + + if instance_writer && instance_accessor + class_eval(<<-EOS, __FILE__, __LINE__ + 1) + def #{sym}=(obj) + self.class.#{sym} = obj + end + EOS + end + + public_send("#{sym}=", default) unless default.nil? + end + end + alias :thread_cattr_writer :thread_mattr_writer + + # Defines both class and instance accessors for class attributes. + # + # class Account + # thread_mattr_accessor :user + # end + # + # Account.user = "DHH" + # Account.user # => "DHH" + # Account.new.user # => "DHH" + # + # Unlike `mattr_accessor`, values are *not* shared with subclasses or parent classes. + # If a subclass changes the value, the parent class' value is not changed. + # If the parent class changes the value, the value of subclasses is not changed. + # + # class Customer < Account + # end + # + # Account.user # => "DHH" + # Customer.user # => nil + # Customer.user = "Rafael" + # Customer.user # => "Rafael" + # Account.user # => "DHH" + # + # To omit the instance writer method, pass instance_writer: false. + # To omit the instance reader method, pass instance_reader: false. + # + # class Current + # thread_mattr_accessor :user, instance_writer: false, instance_reader: false + # end + # + # Current.new.user = "DHH" # => NoMethodError + # Current.new.user # => NoMethodError + # + # Or pass instance_accessor: false, to omit both instance methods. + # + # class Current + # thread_mattr_accessor :user, instance_accessor: false + # end + # + # Current.new.user = "DHH" # => NoMethodError + # Current.new.user # => NoMethodError + def thread_mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil) + thread_mattr_reader(*syms, instance_reader: instance_reader, instance_accessor: instance_accessor, default: default) + thread_mattr_writer(*syms, instance_writer: instance_writer, instance_accessor: instance_accessor) + end + alias :thread_cattr_accessor :thread_mattr_accessor +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/concerning.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/concerning.rb new file mode 100644 index 0000000..36f5f85 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/concerning.rb @@ -0,0 +1,140 @@ +# frozen_string_literal: true + +require "active_support/concern" + +class Module + # = Bite-sized separation of concerns + # + # We often find ourselves with a medium-sized chunk of behavior that we'd + # like to extract, but only mix in to a single class. + # + # Extracting a plain old Ruby object to encapsulate it and collaborate or + # delegate to the original object is often a good choice, but when there's + # no additional state to encapsulate or we're making DSL-style declarations + # about the parent class, introducing new collaborators can obfuscate rather + # than simplify. + # + # The typical route is to just dump everything in a monolithic class, perhaps + # with a comment, as a least-bad alternative. Using modules in separate files + # means tedious sifting to get a big-picture view. + # + # = Dissatisfying ways to separate small concerns + # + # == Using comments: + # + # class Todo < ApplicationRecord + # # Other todo implementation + # # ... + # + # ## Event tracking + # has_many :events + # + # before_create :track_creation + # + # private + # def track_creation + # # ... + # end + # end + # + # == With an inline module: + # + # Noisy syntax. + # + # class Todo < ApplicationRecord + # # Other todo implementation + # # ... + # + # module EventTracking + # extend ActiveSupport::Concern + # + # included do + # has_many :events + # before_create :track_creation + # end + # + # private + # def track_creation + # # ... + # end + # end + # include EventTracking + # end + # + # == Mix-in noise exiled to its own file: + # + # Once our chunk of behavior starts pushing the scroll-to-understand-it + # boundary, we give in and move it to a separate file. At this size, the + # increased overhead can be a reasonable tradeoff even if it reduces our + # at-a-glance perception of how things work. + # + # class Todo < ApplicationRecord + # # Other todo implementation + # # ... + # + # include TodoEventTracking + # end + # + # = Introducing Module#concerning + # + # By quieting the mix-in noise, we arrive at a natural, low-ceremony way to + # separate bite-sized concerns. + # + # class Todo < ApplicationRecord + # # Other todo implementation + # # ... + # + # concerning :EventTracking do + # included do + # has_many :events + # before_create :track_creation + # end + # + # private + # def track_creation + # # ... + # end + # end + # end + # + # Todo.ancestors + # # => [Todo, Todo::EventTracking, ApplicationRecord, Object] + # + # This small step has some wonderful ripple effects. We can + # * grok the behavior of our class in one glance, + # * clean up monolithic junk-drawer classes by separating their concerns, and + # * stop leaning on protected/private for crude "this is internal stuff" modularity. + # + # === Prepending concerning + # + # concerning supports a prepend: true argument which will prepend the + # concern instead of using include for it. + module Concerning + # Define a new concern and mix it in. + def concerning(topic, prepend: false, &block) + method = prepend ? :prepend : :include + __send__(method, concern(topic, &block)) + end + + # A low-cruft shortcut to define a concern. + # + # concern :EventTracking do + # ... + # end + # + # is equivalent to + # + # module EventTracking + # extend ActiveSupport::Concern + # + # ... + # end + def concern(topic, &module_definition) + const_set topic, Module.new { + extend ::ActiveSupport::Concern + module_eval(&module_definition) + } + end + end + include Concerning +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/delegation.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/delegation.rb new file mode 100644 index 0000000..dcec1b1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/delegation.rb @@ -0,0 +1,324 @@ +# frozen_string_literal: true + +require "set" + +class Module + # Error generated by +delegate+ when a method is called on +nil+ and +allow_nil+ + # option is not used. + class DelegationError < NoMethodError; end + + RUBY_RESERVED_KEYWORDS = %w(alias and BEGIN begin break case class def defined? do + else elsif END end ensure false for if in module next nil not or redo rescue retry + return self super then true undef unless until when while yield) + DELEGATION_RESERVED_KEYWORDS = %w(_ arg args block) + DELEGATION_RESERVED_METHOD_NAMES = Set.new( + RUBY_RESERVED_KEYWORDS + DELEGATION_RESERVED_KEYWORDS + ).freeze + + # Provides a +delegate+ class method to easily expose contained objects' + # public methods as your own. + # + # ==== Options + # * :to - Specifies the target object name as a symbol or string + # * :prefix - Prefixes the new method with the target name or a custom prefix + # * :allow_nil - If set to true, prevents a +Module::DelegationError+ + # from being raised + # * :private - If set to true, changes method visibility to private + # + # The macro receives one or more method names (specified as symbols or + # strings) and the name of the target object via the :to option + # (also a symbol or string). + # + # Delegation is particularly useful with Active Record associations: + # + # class Greeter < ActiveRecord::Base + # def hello + # 'hello' + # end + # + # def goodbye + # 'goodbye' + # end + # end + # + # class Foo < ActiveRecord::Base + # belongs_to :greeter + # delegate :hello, to: :greeter + # end + # + # Foo.new.hello # => "hello" + # Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for # + # + # Multiple delegates to the same target are allowed: + # + # class Foo < ActiveRecord::Base + # belongs_to :greeter + # delegate :hello, :goodbye, to: :greeter + # end + # + # Foo.new.goodbye # => "goodbye" + # + # Methods can be delegated to instance variables, class variables, or constants + # by providing them as a symbols: + # + # class Foo + # CONSTANT_ARRAY = [0,1,2,3] + # @@class_array = [4,5,6,7] + # + # def initialize + # @instance_array = [8,9,10,11] + # end + # delegate :sum, to: :CONSTANT_ARRAY + # delegate :min, to: :@@class_array + # delegate :max, to: :@instance_array + # end + # + # Foo.new.sum # => 6 + # Foo.new.min # => 4 + # Foo.new.max # => 11 + # + # It's also possible to delegate a method to the class by using +:class+: + # + # class Foo + # def self.hello + # "world" + # end + # + # delegate :hello, to: :class + # end + # + # Foo.new.hello # => "world" + # + # Delegates can optionally be prefixed using the :prefix option. If the value + # is true, the delegate methods are prefixed with the name of the object being + # delegated to. + # + # Person = Struct.new(:name, :address) + # + # class Invoice < Struct.new(:client) + # delegate :name, :address, to: :client, prefix: true + # end + # + # john_doe = Person.new('John Doe', 'Vimmersvej 13') + # invoice = Invoice.new(john_doe) + # invoice.client_name # => "John Doe" + # invoice.client_address # => "Vimmersvej 13" + # + # It is also possible to supply a custom prefix. + # + # class Invoice < Struct.new(:client) + # delegate :name, :address, to: :client, prefix: :customer + # end + # + # invoice = Invoice.new(john_doe) + # invoice.customer_name # => 'John Doe' + # invoice.customer_address # => 'Vimmersvej 13' + # + # The delegated methods are public by default. + # Pass private: true to change that. + # + # class User < ActiveRecord::Base + # has_one :profile + # delegate :first_name, to: :profile + # delegate :date_of_birth, to: :profile, private: true + # + # def age + # Date.today.year - date_of_birth.year + # end + # end + # + # User.new.first_name # => "Tomas" + # User.new.date_of_birth # => NoMethodError: private method `date_of_birth' called for # + # User.new.age # => 2 + # + # If the target is +nil+ and does not respond to the delegated method a + # +Module::DelegationError+ is raised. If you wish to instead return +nil+, + # use the :allow_nil option. + # + # class User < ActiveRecord::Base + # has_one :profile + # delegate :age, to: :profile + # end + # + # User.new.age + # # => Module::DelegationError: User#age delegated to profile.age, but profile is nil + # + # But if not having a profile yet is fine and should not be an error + # condition: + # + # class User < ActiveRecord::Base + # has_one :profile + # delegate :age, to: :profile, allow_nil: true + # end + # + # User.new.age # nil + # + # Note that if the target is not +nil+ then the call is attempted regardless of the + # :allow_nil option, and thus an exception is still raised if said object + # does not respond to the method: + # + # class Foo + # def initialize(bar) + # @bar = bar + # end + # + # delegate :name, to: :@bar, allow_nil: true + # end + # + # Foo.new("Bar").name # raises NoMethodError: undefined method `name' + # + # The target method must be public, otherwise it will raise +NoMethodError+. + def delegate(*methods, to: nil, prefix: nil, allow_nil: nil, private: nil) + unless to + raise ArgumentError, "Delegation needs a target. Supply a keyword argument 'to' (e.g. delegate :hello, to: :greeter)." + end + + if prefix == true && /^[^a-z_]/.match?(to) + raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method." + end + + method_prefix = \ + if prefix + "#{prefix == true ? to : prefix}_" + else + "" + end + + location = caller_locations(1, 1).first + file, line = location.path, location.lineno + + to = to.to_s + to = "self.#{to}" if DELEGATION_RESERVED_METHOD_NAMES.include?(to) + + method_def = [] + method_names = [] + + methods.map do |method| + method_name = prefix ? "#{method_prefix}#{method}" : method + method_names << method_name.to_sym + + # Attribute writer methods only accept one argument. Makes sure []= + # methods still accept two arguments. + definition = /[^\]]=\z/.match?(method) ? "arg" : "..." + + # The following generated method calls the target exactly once, storing + # the returned value in a dummy variable. + # + # Reason is twofold: On one hand doing less calls is in general better. + # On the other hand it could be that the target has side-effects, + # whereas conceptually, from the user point of view, the delegator should + # be doing one call. + if allow_nil + method = method.to_s + + method_def << + "def #{method_name}(#{definition})" << + " _ = #{to}" << + " if !_.nil? || nil.respond_to?(:#{method})" << + " _.#{method}(#{definition})" << + " end" << + "end" + else + method = method.to_s + method_name = method_name.to_s + + method_def << + "def #{method_name}(#{definition})" << + " _ = #{to}" << + " _.#{method}(#{definition})" << + "rescue NoMethodError => e" << + " if _.nil? && e.name == :#{method}" << + %( raise DelegationError, "#{self}##{method_name} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}") << + " else" << + " raise" << + " end" << + "end" + end + end + module_eval(method_def.join(";"), file, line) + private(*method_names) if private + method_names + end + + # When building decorators, a common pattern may emerge: + # + # class Partition + # def initialize(event) + # @event = event + # end + # + # def person + # detail.person || creator + # end + # + # private + # def respond_to_missing?(name, include_private = false) + # @event.respond_to?(name, include_private) + # end + # + # def method_missing(method, *args, &block) + # @event.send(method, *args, &block) + # end + # end + # + # With Module#delegate_missing_to, the above is condensed to: + # + # class Partition + # delegate_missing_to :@event + # + # def initialize(event) + # @event = event + # end + # + # def person + # detail.person || creator + # end + # end + # + # The target can be anything callable within the object, e.g. instance + # variables, methods, constants, etc. + # + # The delegated method must be public on the target, otherwise it will + # raise +DelegationError+. If you wish to instead return +nil+, + # use the :allow_nil option. + # + # The marshal_dump and _dump methods are exempt from + # delegation due to possible interference when calling + # Marshal.dump(object), should the delegation target method + # of object add or remove instance variables. + def delegate_missing_to(target, allow_nil: nil) + target = target.to_s + target = "self.#{target}" if DELEGATION_RESERVED_METHOD_NAMES.include?(target) + + module_eval <<-RUBY, __FILE__, __LINE__ + 1 + def respond_to_missing?(name, include_private = false) + # It may look like an oversight, but we deliberately do not pass + # +include_private+, because they do not get delegated. + + return false if name == :marshal_dump || name == :_dump + #{target}.respond_to?(name) || super + end + + def method_missing(method, *args, &block) + if #{target}.respond_to?(method) + #{target}.public_send(method, *args, &block) + else + begin + super + rescue NoMethodError + if #{target}.nil? + if #{allow_nil == true} + nil + else + raise DelegationError, "\#{method} delegated to #{target}, but #{target} is nil" + end + else + raise + end + end + end + end + ruby2_keywords(:method_missing) + RUBY + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/deprecation.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/deprecation.rb new file mode 100644 index 0000000..71c42eb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/deprecation.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +class Module + # deprecate :foo + # deprecate bar: 'message' + # deprecate :foo, :bar, baz: 'warning!', qux: 'gone!' + # + # You can also use custom deprecator instance: + # + # deprecate :foo, deprecator: MyLib::Deprecator.new + # deprecate :foo, bar: "warning!", deprecator: MyLib::Deprecator.new + # + # \Custom deprecators must respond to deprecation_warning(deprecated_method_name, message, caller_backtrace) + # method where you can implement your custom warning behavior. + # + # class MyLib::Deprecator + # def deprecation_warning(deprecated_method_name, message, caller_backtrace = nil) + # message = "#{deprecated_method_name} is deprecated and will be removed from MyLibrary | #{message}" + # Kernel.warn message + # end + # end + def deprecate(*method_names) + ActiveSupport::Deprecation.deprecate_methods(self, *method_names) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/introspection.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/introspection.rb new file mode 100644 index 0000000..7cdcab5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/introspection.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +require "active_support/core_ext/string/filters" +require "active_support/inflector" + +class Module + # Returns the name of the module containing this one. + # + # M::N.module_parent_name # => "M" + def module_parent_name + if defined?(@parent_name) + @parent_name + else + parent_name = name =~ /::[^:]+\z/ ? -$` : nil + @parent_name = parent_name unless frozen? + parent_name + end + end + + # Returns the module which contains this one according to its name. + # + # module M + # module N + # end + # end + # X = M::N + # + # M::N.module_parent # => M + # X.module_parent # => M + # + # The parent of top-level and anonymous modules is Object. + # + # M.module_parent # => Object + # Module.new.module_parent # => Object + def module_parent + module_parent_name ? ActiveSupport::Inflector.constantize(module_parent_name) : Object + end + + # Returns all the parents of this module according to its name, ordered from + # nested outwards. The receiver is not contained within the result. + # + # module M + # module N + # end + # end + # X = M::N + # + # M.module_parents # => [Object] + # M::N.module_parents # => [M, Object] + # X.module_parents # => [M, Object] + def module_parents + parents = [] + if module_parent_name + parts = module_parent_name.split("::") + until parts.empty? + parents << ActiveSupport::Inflector.constantize(parts * "::") + parts.pop + end + end + parents << Object unless parents.include? Object + parents + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/redefine_method.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/redefine_method.rb new file mode 100644 index 0000000..5bd8e6e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/redefine_method.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +class Module + # Marks the named method as intended to be redefined, if it exists. + # Suppresses the Ruby method redefinition warning. Prefer + # #redefine_method where possible. + def silence_redefinition_of_method(method) + if method_defined?(method) || private_method_defined?(method) + # This suppresses the "method redefined" warning; the self-alias + # looks odd, but means we don't need to generate a unique name + alias_method method, method + end + end + + # Replaces the existing method definition, if there is one, with the passed + # block as its body. + def redefine_method(method, &block) + visibility = method_visibility(method) + silence_redefinition_of_method(method) + define_method(method, &block) + send(visibility, method) + end + + # Replaces the existing singleton method definition, if there is one, with + # the passed block as its body. + def redefine_singleton_method(method, &block) + singleton_class.redefine_method(method, &block) + end + + def method_visibility(method) # :nodoc: + case + when private_method_defined?(method) + :private + when protected_method_defined?(method) + :protected + else + :public + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/remove_method.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/remove_method.rb new file mode 100644 index 0000000..97eb5f9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/module/remove_method.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/redefine_method" + +class Module + # Removes the named method, if it exists. + def remove_possible_method(method) + if method_defined?(method) || private_method_defined?(method) + undef_method(method) + end + end + + # Removes the named singleton method, if it exists. + def remove_possible_singleton_method(method) + singleton_class.remove_possible_method(method) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/name_error.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/name_error.rb new file mode 100644 index 0000000..18ea275 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/name_error.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +class NameError + # Extract the name of the missing constant from the exception message. + # + # begin + # HelloWorld + # rescue NameError => e + # e.missing_name + # end + # # => "HelloWorld" + def missing_name + # Since ruby v2.3.0 `did_you_mean` gem is loaded by default. + # It extends NameError#message with spell corrections which are SLOW. + # We should use original_message message instead. + message = respond_to?(:original_message) ? original_message : self.message + return unless message.start_with?("uninitialized constant ") + + receiver = begin + self.receiver + rescue ArgumentError + nil + end + + if receiver == Object + name.to_s + elsif receiver + "#{real_mod_name(receiver)}::#{self.name}" + else + if match = message.match(/((::)?([A-Z]\w*)(::[A-Z]\w*)*)$/) + match[1] + end + end + end + + # Was this exception raised because the given name was missing? + # + # begin + # HelloWorld + # rescue NameError => e + # e.missing_name?("HelloWorld") + # end + # # => true + def missing_name?(name) + if name.is_a? Symbol + self.name == name + else + missing_name == name.to_s + end + end + + private + UNBOUND_METHOD_MODULE_NAME = Module.instance_method(:name) + private_constant :UNBOUND_METHOD_MODULE_NAME + + def real_mod_name(mod) + UNBOUND_METHOD_MODULE_NAME.bind_call(mod) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric.rb new file mode 100644 index 0000000..9368cb3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +require "active_support/core_ext/numeric/bytes" +require "active_support/core_ext/numeric/time" +require "active_support/core_ext/numeric/conversions" +require "active_support/core_ext/numeric/deprecated_conversions" unless ENV["RAILS_DISABLE_DEPRECATED_TO_S_CONVERSION"] diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/bytes.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/bytes.rb new file mode 100644 index 0000000..b002eba --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/bytes.rb @@ -0,0 +1,66 @@ +# frozen_string_literal: true + +class Numeric + KILOBYTE = 1024 + MEGABYTE = KILOBYTE * 1024 + GIGABYTE = MEGABYTE * 1024 + TERABYTE = GIGABYTE * 1024 + PETABYTE = TERABYTE * 1024 + EXABYTE = PETABYTE * 1024 + + # Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes + # + # 2.bytes # => 2 + def bytes + self + end + alias :byte :bytes + + # Returns the number of bytes equivalent to the kilobytes provided. + # + # 2.kilobytes # => 2048 + def kilobytes + self * KILOBYTE + end + alias :kilobyte :kilobytes + + # Returns the number of bytes equivalent to the megabytes provided. + # + # 2.megabytes # => 2_097_152 + def megabytes + self * MEGABYTE + end + alias :megabyte :megabytes + + # Returns the number of bytes equivalent to the gigabytes provided. + # + # 2.gigabytes # => 2_147_483_648 + def gigabytes + self * GIGABYTE + end + alias :gigabyte :gigabytes + + # Returns the number of bytes equivalent to the terabytes provided. + # + # 2.terabytes # => 2_199_023_255_552 + def terabytes + self * TERABYTE + end + alias :terabyte :terabytes + + # Returns the number of bytes equivalent to the petabytes provided. + # + # 2.petabytes # => 2_251_799_813_685_248 + def petabytes + self * PETABYTE + end + alias :petabyte :petabytes + + # Returns the number of bytes equivalent to the exabytes provided. + # + # 2.exabytes # => 2_305_843_009_213_693_952 + def exabytes + self * EXABYTE + end + alias :exabyte :exabytes +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/conversions.rb new file mode 100644 index 0000000..d8196bd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/conversions.rb @@ -0,0 +1,143 @@ +# frozen_string_literal: true + +require "active_support/core_ext/big_decimal/conversions" +require "active_support/number_helper" + +module ActiveSupport + module NumericWithFormat + # Provides options for converting numbers into formatted strings. + # Options are provided for phone numbers, currency, percentage, + # precision, positional notation, file size and pretty printing. + # + # This method is aliased to to_formatted_s. + # + # ==== Options + # + # For details on which formats use which options, see ActiveSupport::NumberHelper + # + # ==== Examples + # + # Phone Numbers: + # 5551234.to_fs(:phone) # => "555-1234" + # 1235551234.to_fs(:phone) # => "123-555-1234" + # 1235551234.to_fs(:phone, area_code: true) # => "(123) 555-1234" + # 1235551234.to_fs(:phone, delimiter: ' ') # => "123 555 1234" + # 1235551234.to_fs(:phone, area_code: true, extension: 555) # => "(123) 555-1234 x 555" + # 1235551234.to_fs(:phone, country_code: 1) # => "+1-123-555-1234" + # 1235551234.to_fs(:phone, country_code: 1, extension: 1343, delimiter: '.') + # # => "+1.123.555.1234 x 1343" + # + # Currency: + # 1234567890.50.to_fs(:currency) # => "$1,234,567,890.50" + # 1234567890.506.to_fs(:currency) # => "$1,234,567,890.51" + # 1234567890.506.to_fs(:currency, precision: 3) # => "$1,234,567,890.506" + # 1234567890.506.to_fs(:currency, round_mode: :down) # => "$1,234,567,890.50" + # 1234567890.506.to_fs(:currency, locale: :fr) # => "1 234 567 890,51 €" + # -1234567890.50.to_fs(:currency, negative_format: '(%u%n)') + # # => "($1,234,567,890.50)" + # 1234567890.50.to_fs(:currency, unit: '£', separator: ',', delimiter: '') + # # => "£1234567890,50" + # 1234567890.50.to_fs(:currency, unit: '£', separator: ',', delimiter: '', format: '%n %u') + # # => "1234567890,50 £" + # + # Percentage: + # 100.to_fs(:percentage) # => "100.000%" + # 100.to_fs(:percentage, precision: 0) # => "100%" + # 1000.to_fs(:percentage, delimiter: '.', separator: ',') # => "1.000,000%" + # 302.24398923423.to_fs(:percentage, precision: 5) # => "302.24399%" + # 302.24398923423.to_fs(:percentage, round_mode: :down) # => "302.243%" + # 1000.to_fs(:percentage, locale: :fr) # => "1 000,000%" + # 100.to_fs(:percentage, format: '%n %') # => "100.000 %" + # + # Delimited: + # 12345678.to_fs(:delimited) # => "12,345,678" + # 12345678.05.to_fs(:delimited) # => "12,345,678.05" + # 12345678.to_fs(:delimited, delimiter: '.') # => "12.345.678" + # 12345678.to_fs(:delimited, delimiter: ',') # => "12,345,678" + # 12345678.05.to_fs(:delimited, separator: ' ') # => "12,345,678 05" + # 12345678.05.to_fs(:delimited, locale: :fr) # => "12 345 678,05" + # 98765432.98.to_fs(:delimited, delimiter: ' ', separator: ',') + # # => "98 765 432,98" + # + # Rounded: + # 111.2345.to_fs(:rounded) # => "111.235" + # 111.2345.to_fs(:rounded, precision: 2) # => "111.23" + # 111.2345.to_fs(:rounded, precision: 2, round_mode: :up) # => "111.24" + # 13.to_fs(:rounded, precision: 5) # => "13.00000" + # 389.32314.to_fs(:rounded, precision: 0) # => "389" + # 111.2345.to_fs(:rounded, significant: true) # => "111" + # 111.2345.to_fs(:rounded, precision: 1, significant: true) # => "100" + # 13.to_fs(:rounded, precision: 5, significant: true) # => "13.000" + # 111.234.to_fs(:rounded, locale: :fr) # => "111,234" + # 13.to_fs(:rounded, precision: 5, significant: true, strip_insignificant_zeros: true) + # # => "13" + # 389.32314.to_fs(:rounded, precision: 4, significant: true) # => "389.3" + # 1111.2345.to_fs(:rounded, precision: 2, separator: ',', delimiter: '.') + # # => "1.111,23" + # + # Human-friendly size in Bytes: + # 123.to_fs(:human_size) # => "123 Bytes" + # 1234.to_fs(:human_size) # => "1.21 KB" + # 12345.to_fs(:human_size) # => "12.1 KB" + # 1234567.to_fs(:human_size) # => "1.18 MB" + # 1234567890.to_fs(:human_size) # => "1.15 GB" + # 1234567890123.to_fs(:human_size) # => "1.12 TB" + # 1234567890123456.to_fs(:human_size) # => "1.1 PB" + # 1234567890123456789.to_fs(:human_size) # => "1.07 EB" + # 1234567.to_fs(:human_size, precision: 2) # => "1.2 MB" + # 1234567.to_fs(:human_size, precision: 2, round_mode: :up) # => "1.3 MB" + # 483989.to_fs(:human_size, precision: 2) # => "470 KB" + # 1234567.to_fs(:human_size, precision: 2, separator: ',') # => "1,2 MB" + # 1234567890123.to_fs(:human_size, precision: 5) # => "1.1228 TB" + # 524288000.to_fs(:human_size, precision: 5) # => "500 MB" + # + # Human-friendly format: + # 123.to_fs(:human) # => "123" + # 1234.to_fs(:human) # => "1.23 Thousand" + # 12345.to_fs(:human) # => "12.3 Thousand" + # 1234567.to_fs(:human) # => "1.23 Million" + # 1234567890.to_fs(:human) # => "1.23 Billion" + # 1234567890123.to_fs(:human) # => "1.23 Trillion" + # 1234567890123456.to_fs(:human) # => "1.23 Quadrillion" + # 1234567890123456789.to_fs(:human) # => "1230 Quadrillion" + # 489939.to_fs(:human, precision: 2) # => "490 Thousand" + # 489939.to_fs(:human, precision: 2, round_mode: :down) # => "480 Thousand" + # 489939.to_fs(:human, precision: 4) # => "489.9 Thousand" + # 1234567.to_fs(:human, precision: 4, + # significant: false) # => "1.2346 Million" + # 1234567.to_fs(:human, precision: 1, + # separator: ',', + # significant: false) # => "1,2 Million" + def to_fs(format = nil, options = nil) + return to_s if format.nil? + + case format + when Integer, String + to_s(format) + when :phone + ActiveSupport::NumberHelper.number_to_phone(self, options || {}) + when :currency + ActiveSupport::NumberHelper.number_to_currency(self, options || {}) + when :percentage + ActiveSupport::NumberHelper.number_to_percentage(self, options || {}) + when :delimited + ActiveSupport::NumberHelper.number_to_delimited(self, options || {}) + when :rounded + ActiveSupport::NumberHelper.number_to_rounded(self, options || {}) + when :human + ActiveSupport::NumberHelper.number_to_human(self, options || {}) + when :human_size + ActiveSupport::NumberHelper.number_to_human_size(self, options || {}) + when Symbol + to_s + else + to_s(format) + end + end + alias_method :to_formatted_s, :to_fs + end +end + +Integer.prepend ActiveSupport::NumericWithFormat +Float.prepend ActiveSupport::NumericWithFormat +BigDecimal.prepend ActiveSupport::NumericWithFormat diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/deprecated_conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/deprecated_conversions.rb new file mode 100644 index 0000000..5f81dc6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/deprecated_conversions.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +module ActiveSupport + module DeprecatedNumericWithFormat # :nodoc: + def to_s(format = nil, options = nil) + return super() if format.nil? + + case format + when Integer, String + super(format) + when :phone + ActiveSupport::Deprecation.warn( + "#{self.class}#to_s(#{format.inspect}) is deprecated. Please use #{self.class}#to_fs(#{format.inspect}) instead." + ) + ActiveSupport::NumberHelper.number_to_phone(self, options || {}) + when :currency + ActiveSupport::Deprecation.warn( + "#{self.class}#to_s(#{format.inspect}) is deprecated. Please use #{self.class}#to_fs(#{format.inspect}) instead." + ) + ActiveSupport::NumberHelper.number_to_currency(self, options || {}) + when :percentage + ActiveSupport::Deprecation.warn( + "#{self.class}#to_s(#{format.inspect}) is deprecated. Please use #{self.class}#to_fs(#{format.inspect}) instead." + ) + ActiveSupport::NumberHelper.number_to_percentage(self, options || {}) + when :delimited + ActiveSupport::Deprecation.warn( + "#{self.class}#to_s(#{format.inspect}) is deprecated. Please use #{self.class}#to_fs(#{format.inspect}) instead." + ) + ActiveSupport::NumberHelper.number_to_delimited(self, options || {}) + when :rounded + ActiveSupport::Deprecation.warn( + "#{self.class}#to_s(#{format.inspect}) is deprecated. Please use #{self.class}#to_fs(#{format.inspect}) instead." + ) + ActiveSupport::NumberHelper.number_to_rounded(self, options || {}) + when :human + ActiveSupport::Deprecation.warn( + "#{self.class}#to_s(#{format.inspect}) is deprecated. Please use #{self.class}#to_fs(#{format.inspect}) instead." + ) + ActiveSupport::NumberHelper.number_to_human(self, options || {}) + when :human_size + ActiveSupport::Deprecation.warn( + "#{self.class}#to_s(#{format.inspect}) is deprecated. Please use #{self.class}#to_fs(#{format.inspect}) instead." + ) + ActiveSupport::NumberHelper.number_to_human_size(self, options || {}) + when Symbol + ActiveSupport::Deprecation.warn( + "#{self.class}#to_s(#{format.inspect}) is deprecated. Please use #{self.class}#to_fs(#{format.inspect}) instead." + ) + super() + else + super(format) + end + end + end +end + +Integer.prepend ActiveSupport::DeprecatedNumericWithFormat +Float.prepend ActiveSupport::DeprecatedNumericWithFormat +BigDecimal.prepend ActiveSupport::DeprecatedNumericWithFormat diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/time.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/time.rb new file mode 100644 index 0000000..bc4627f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/numeric/time.rb @@ -0,0 +1,66 @@ +# frozen_string_literal: true + +require "active_support/duration" +require "active_support/core_ext/time/calculations" +require "active_support/core_ext/time/acts_like" +require "active_support/core_ext/date/calculations" +require "active_support/core_ext/date/acts_like" + +class Numeric + # Returns a Duration instance matching the number of seconds provided. + # + # 2.seconds # => 2 seconds + def seconds + ActiveSupport::Duration.seconds(self) + end + alias :second :seconds + + # Returns a Duration instance matching the number of minutes provided. + # + # 2.minutes # => 2 minutes + def minutes + ActiveSupport::Duration.minutes(self) + end + alias :minute :minutes + + # Returns a Duration instance matching the number of hours provided. + # + # 2.hours # => 2 hours + def hours + ActiveSupport::Duration.hours(self) + end + alias :hour :hours + + # Returns a Duration instance matching the number of days provided. + # + # 2.days # => 2 days + def days + ActiveSupport::Duration.days(self) + end + alias :day :days + + # Returns a Duration instance matching the number of weeks provided. + # + # 2.weeks # => 2 weeks + def weeks + ActiveSupport::Duration.weeks(self) + end + alias :week :weeks + + # Returns a Duration instance matching the number of fortnights provided. + # + # 2.fortnights # => 4 weeks + def fortnights + ActiveSupport::Duration.weeks(self * 2) + end + alias :fortnight :fortnights + + # Returns the number of milliseconds equivalent to the seconds provided. + # Used with the standard time durations. + # + # 2.in_milliseconds # => 2000 + # 1.hour.in_milliseconds # => 3600000 + def in_milliseconds + self * 1000 + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object.rb new file mode 100644 index 0000000..efd34cc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/acts_like" +require "active_support/core_ext/object/blank" +require "active_support/core_ext/object/duplicable" +require "active_support/core_ext/object/deep_dup" +require "active_support/core_ext/object/try" +require "active_support/core_ext/object/inclusion" + +require "active_support/core_ext/object/conversions" +require "active_support/core_ext/object/instance_variables" + +require "active_support/core_ext/object/json" +require "active_support/core_ext/object/to_param" +require "active_support/core_ext/object/to_query" +require "active_support/core_ext/object/with_options" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/acts_like.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/acts_like.rb new file mode 100644 index 0000000..292826c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/acts_like.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +class Object + # Provides a way to check whether some class acts like some other class based on the existence of + # an appropriately-named marker method. + # + # A class that provides the same interface as SomeClass may define a marker method named + # acts_like_some_class? to signal its compatibility to callers of + # acts_like?(:some_class). + # + # For example, Active Support extends Date to define an acts_like_date? method, + # and extends Time to define acts_like_time?. As a result, developers can call + # x.acts_like?(:time) and x.acts_like?(:date) to test duck-type compatibility, + # and classes that are able to act like Time can also define an acts_like_time? + # method to interoperate. + # + # Note that the marker method is only expected to exist. It isn't called, so its body or return + # value are irrelevant. + # + # ==== Example: A class that provides the same interface as String + # + # This class may define: + # + # class Stringish + # def acts_like_string? + # end + # end + # + # Then client code can query for duck-type-safeness this way: + # + # Stringish.new.acts_like?(:string) # => true + # + def acts_like?(duck) + case duck + when :time + respond_to? :acts_like_time? + when :date + respond_to? :acts_like_date? + when :string + respond_to? :acts_like_string? + else + respond_to? :"acts_like_#{duck}?" + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/blank.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/blank.rb new file mode 100644 index 0000000..372f725 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/blank.rb @@ -0,0 +1,155 @@ +# frozen_string_literal: true + +require "concurrent/map" + +class Object + # An object is blank if it's false, empty, or a whitespace string. + # For example, +nil+, '', ' ', [], {}, and +false+ are all blank. + # + # This simplifies + # + # !address || address.empty? + # + # to + # + # address.blank? + # + # @return [true, false] + def blank? + respond_to?(:empty?) ? !!empty? : !self + end + + # An object is present if it's not blank. + # + # @return [true, false] + def present? + !blank? + end + + # Returns the receiver if it's present otherwise returns +nil+. + # object.presence is equivalent to + # + # object.present? ? object : nil + # + # For example, something like + # + # state = params[:state] if params[:state].present? + # country = params[:country] if params[:country].present? + # region = state || country || 'US' + # + # becomes + # + # region = params[:state].presence || params[:country].presence || 'US' + # + # @return [Object] + def presence + self if present? + end +end + +class NilClass + # +nil+ is blank: + # + # nil.blank? # => true + # + # @return [true] + def blank? + true + end +end + +class FalseClass + # +false+ is blank: + # + # false.blank? # => true + # + # @return [true] + def blank? + true + end +end + +class TrueClass + # +true+ is not blank: + # + # true.blank? # => false + # + # @return [false] + def blank? + false + end +end + +class Array + # An array is blank if it's empty: + # + # [].blank? # => true + # [1,2,3].blank? # => false + # + # @return [true, false] + alias_method :blank?, :empty? +end + +class Hash + # A hash is blank if it's empty: + # + # {}.blank? # => true + # { key: 'value' }.blank? # => false + # + # @return [true, false] + alias_method :blank?, :empty? +end + +class String + BLANK_RE = /\A[[:space:]]*\z/ + ENCODED_BLANKS = Concurrent::Map.new do |h, enc| + h[enc] = Regexp.new(BLANK_RE.source.encode(enc), BLANK_RE.options | Regexp::FIXEDENCODING) + end + + # A string is blank if it's empty or contains whitespaces only: + # + # ''.blank? # => true + # ' '.blank? # => true + # "\t\n\r".blank? # => true + # ' blah '.blank? # => false + # + # Unicode whitespace is supported: + # + # "\u00a0".blank? # => true + # + # @return [true, false] + def blank? + # The regexp that matches blank strings is expensive. For the case of empty + # strings we can speed up this method (~3.5x) with an empty? call. The + # penalty for the rest of strings is marginal. + empty? || + begin + BLANK_RE.match?(self) + rescue Encoding::CompatibilityError + ENCODED_BLANKS[self.encoding].match?(self) + end + end +end + +class Numeric # :nodoc: + # No number is blank: + # + # 1.blank? # => false + # 0.blank? # => false + # + # @return [false] + def blank? + false + end +end + +class Time # :nodoc: + # No Time is blank: + # + # Time.now.blank? # => false + # + # @return [false] + def blank? + false + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/conversions.rb new file mode 100644 index 0000000..624fb8d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/conversions.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/to_param" +require "active_support/core_ext/object/to_query" +require "active_support/core_ext/array/conversions" +require "active_support/core_ext/hash/conversions" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/deep_dup.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/deep_dup.rb new file mode 100644 index 0000000..4aca04a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/deep_dup.rb @@ -0,0 +1,55 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/duplicable" + +class Object + # Returns a deep copy of object if it's duplicable. If it's + # not duplicable, returns +self+. + # + # object = Object.new + # dup = object.deep_dup + # dup.instance_variable_set(:@a, 1) + # + # object.instance_variable_defined?(:@a) # => false + # dup.instance_variable_defined?(:@a) # => true + def deep_dup + duplicable? ? dup : self + end +end + +class Array + # Returns a deep copy of array. + # + # array = [1, [2, 3]] + # dup = array.deep_dup + # dup[1][2] = 4 + # + # array[1][2] # => nil + # dup[1][2] # => 4 + def deep_dup + map(&:deep_dup) + end +end + +class Hash + # Returns a deep copy of hash. + # + # hash = { a: { b: 'b' } } + # dup = hash.deep_dup + # dup[:a][:c] = 'c' + # + # hash[:a][:c] # => nil + # dup[:a][:c] # => "c" + def deep_dup + hash = dup + each_pair do |key, value| + if ::String === key || ::Symbol === key + hash[key] = value.deep_dup + else + hash.delete(key) + hash[key.deep_dup] = value.deep_dup + end + end + hash + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/duplicable.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/duplicable.rb new file mode 100644 index 0000000..c09e893 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/duplicable.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +#-- +# Most objects are cloneable, but not all. For example you can't dup methods: +# +# method(:puts).dup # => TypeError: allocator undefined for Method +# +# Classes may signal their instances are not duplicable removing +dup+/+clone+ +# or raising exceptions from them. So, to dup an arbitrary object you normally +# use an optimistic approach and are ready to catch an exception, say: +# +# arbitrary_object.dup rescue object +# +# Rails dups objects in a few critical spots where they are not that arbitrary. +# That rescue is very expensive (like 40 times slower than a predicate), and it +# is often triggered. +# +# That's why we hardcode the following cases and check duplicable? instead of +# using that rescue idiom. +#++ +class Object + # Can you safely dup this object? + # + # False for method objects; + # true otherwise. + def duplicable? + true + end +end + +class Method + # Methods are not duplicable: + # + # method(:puts).duplicable? # => false + # method(:puts).dup # => TypeError: allocator undefined for Method + def duplicable? + false + end +end + +class UnboundMethod + # Unbound methods are not duplicable: + # + # method(:puts).unbind.duplicable? # => false + # method(:puts).unbind.dup # => TypeError: allocator undefined for UnboundMethod + def duplicable? + false + end +end + +require "singleton" + +module Singleton + # Singleton instances are not duplicable: + # + # Class.new.include(Singleton).instance.dup # TypeError (can't dup instance of singleton + def duplicable? + false + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/inclusion.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/inclusion.rb new file mode 100644 index 0000000..6064e92 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/inclusion.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +class Object + # Returns true if this object is included in the argument. Argument must be + # any object which responds to +#include?+. Usage: + # + # characters = ["Konata", "Kagami", "Tsukasa"] + # "Konata".in?(characters) # => true + # + # This will throw an +ArgumentError+ if the argument doesn't respond + # to +#include?+. + def in?(another_object) + another_object.include?(self) + rescue NoMethodError + raise ArgumentError.new("The parameter passed to #in? must respond to #include?") + end + + # Returns the receiver if it's included in the argument otherwise returns +nil+. + # Argument must be any object which responds to +#include?+. Usage: + # + # params[:bucket_type].presence_in %w( project calendar ) + # + # This will throw an +ArgumentError+ if the argument doesn't respond to +#include?+. + # + # @return [Object] + def presence_in(another_object) + in?(another_object) ? self : nil + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/instance_variables.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/instance_variables.rb new file mode 100644 index 0000000..12fdf84 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/instance_variables.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +class Object + # Returns a hash with string keys that maps instance variable names without "@" to their + # corresponding values. + # + # class C + # def initialize(x, y) + # @x, @y = x, y + # end + # end + # + # C.new(0, 1).instance_values # => {"x" => 0, "y" => 1} + def instance_values + Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }] + end + + # Returns an array of instance variable names as strings including "@". + # + # class C + # def initialize(x, y) + # @x, @y = x, y + # end + # end + # + # C.new(0, 1).instance_variable_names # => ["@y", "@x"] + def instance_variable_names + instance_variables.map(&:to_s) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/json.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/json.rb new file mode 100644 index 0000000..f46441c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/json.rb @@ -0,0 +1,244 @@ +# frozen_string_literal: true + +# Hack to load json gem first so we can overwrite its to_json. +require "json" +require "bigdecimal" +require "ipaddr" +require "uri/generic" +require "pathname" +require "active_support/core_ext/big_decimal/conversions" # for #to_s +require "active_support/core_ext/hash/except" +require "active_support/core_ext/hash/slice" +require "active_support/core_ext/object/instance_variables" +require "time" +require "active_support/core_ext/time/conversions" +require "active_support/core_ext/date_time/conversions" +require "active_support/core_ext/date/conversions" + +#-- +# The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting +# their default behavior. That said, we need to define the basic to_json method in all of them, +# otherwise they will always use to_json gem implementation, which is backwards incompatible in +# several cases (for instance, the JSON implementation for Hash does not work) with inheritance. +# +# On the other hand, we should avoid conflict with ::JSON.{generate,dump}(obj). Unfortunately, the +# JSON gem's encoder relies on its own to_json implementation to encode objects. Since it always +# passes a ::JSON::State object as the only argument to to_json, we can detect that and forward the +# calls to the original to_json method. +# +# It should be noted that when using ::JSON.{generate,dump} directly, ActiveSupport's encoder is +# bypassed completely. This means that as_json won't be invoked and the JSON gem will simply +# ignore any options it does not natively understand. This also means that ::JSON.{generate,dump} +# should give exactly the same results with or without active support. + +module ActiveSupport + module ToJsonWithActiveSupportEncoder # :nodoc: + def to_json(options = nil) + if options.is_a?(::JSON::State) + # Called from JSON.{generate,dump}, forward it to JSON gem's to_json + super(options) + else + # to_json is being invoked directly, use ActiveSupport's encoder + ActiveSupport::JSON.encode(self, options) + end + end + end +end + +[Enumerable, Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].reverse_each do |klass| + klass.prepend(ActiveSupport::ToJsonWithActiveSupportEncoder) +end + +class Module + def as_json(options = nil) # :nodoc: + name + end +end + +class Object + def as_json(options = nil) # :nodoc: + if respond_to?(:to_hash) + to_hash.as_json(options) + else + instance_values.as_json(options) + end + end +end + +class Struct # :nodoc: + def as_json(options = nil) + Hash[members.zip(values)].as_json(options) + end +end + +class TrueClass + def as_json(options = nil) # :nodoc: + self + end +end + +class FalseClass + def as_json(options = nil) # :nodoc: + self + end +end + +class NilClass + def as_json(options = nil) # :nodoc: + self + end +end + +class String + def as_json(options = nil) # :nodoc: + self + end +end + +class Symbol + def as_json(options = nil) # :nodoc: + to_s + end +end + +class Numeric + def as_json(options = nil) # :nodoc: + self + end +end + +class Float + # Encoding Infinity or NaN to JSON should return "null". The default returns + # "Infinity" or "NaN" which are not valid JSON. + def as_json(options = nil) # :nodoc: + finite? ? self : nil + end +end + +class BigDecimal + # A BigDecimal would be naturally represented as a JSON number. Most libraries, + # however, parse non-integer JSON numbers directly as floats. Clients using + # those libraries would get in general a wrong number and no way to recover + # other than manually inspecting the string with the JSON code itself. + # + # That's why a JSON string is returned. The JSON literal is not numeric, but + # if the other end knows by contract that the data is supposed to be a + # BigDecimal, it still has the chance to post-process the string and get the + # real value. + def as_json(options = nil) # :nodoc: + finite? ? to_s : nil + end +end + +class Regexp + def as_json(options = nil) # :nodoc: + to_s + end +end + +module Enumerable + def as_json(options = nil) # :nodoc: + to_a.as_json(options) + end +end + +class IO + def as_json(options = nil) # :nodoc: + to_s + end +end + +class Range + def as_json(options = nil) # :nodoc: + to_s + end +end + +class Array + def as_json(options = nil) # :nodoc: + map { |v| options ? v.as_json(options.dup) : v.as_json } + end +end + +class Hash + def as_json(options = nil) # :nodoc: + # create a subset of the hash by applying :only or :except + subset = if options + if attrs = options[:only] + slice(*Array(attrs)) + elsif attrs = options[:except] + except(*Array(attrs)) + else + self + end + else + self + end + + result = {} + subset.each do |k, v| + result[k.to_s] = options ? v.as_json(options.dup) : v.as_json + end + result + end +end + +class Time + def as_json(options = nil) # :nodoc: + if ActiveSupport::JSON::Encoding.use_standard_json_time_format + xmlschema(ActiveSupport::JSON::Encoding.time_precision) + else + %(#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) + end + end +end + +class Date + def as_json(options = nil) # :nodoc: + if ActiveSupport::JSON::Encoding.use_standard_json_time_format + strftime("%Y-%m-%d") + else + strftime("%Y/%m/%d") + end + end +end + +class DateTime + def as_json(options = nil) # :nodoc: + if ActiveSupport::JSON::Encoding.use_standard_json_time_format + xmlschema(ActiveSupport::JSON::Encoding.time_precision) + else + strftime("%Y/%m/%d %H:%M:%S %z") + end + end +end + +class URI::Generic # :nodoc: + def as_json(options = nil) + to_s + end +end + +class Pathname # :nodoc: + def as_json(options = nil) + to_s + end +end + +class IPAddr # :nodoc: + def as_json(options = nil) + to_s + end +end + +class Process::Status # :nodoc: + def as_json(options = nil) + { exitstatus: exitstatus, pid: pid } + end +end + +class Exception + def as_json(options = nil) + to_s + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/to_param.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/to_param.rb new file mode 100644 index 0000000..6d2bdd7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/to_param.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/to_query" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/to_query.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/to_query.rb new file mode 100644 index 0000000..736643b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/to_query.rb @@ -0,0 +1,89 @@ +# frozen_string_literal: true + +require "cgi" + +class Object + # Alias of to_s. + def to_param + to_s + end + + # Converts an object into a string suitable for use as a URL query string, + # using the given key as the param name. + def to_query(key) + "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}" + end +end + +class NilClass + # Returns +self+. + def to_param + self + end +end + +class TrueClass + # Returns +self+. + def to_param + self + end +end + +class FalseClass + # Returns +self+. + def to_param + self + end +end + +class Array + # Calls to_param on all its elements and joins the result with + # slashes. This is used by url_for in Action Pack. + def to_param + collect(&:to_param).join "/" + end + + # Converts an array into a string suitable for use as a URL query string, + # using the given +key+ as the param name. + # + # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding" + def to_query(key) + prefix = "#{key}[]" + + if empty? + nil.to_query(prefix) + else + collect { |value| value.to_query(prefix) }.join "&" + end + end +end + +class Hash + # Returns a string representation of the receiver suitable for use as a URL + # query string: + # + # {name: 'David', nationality: 'Danish'}.to_query + # # => "name=David&nationality=Danish" + # + # An optional namespace can be passed to enclose key names: + # + # {name: 'David', nationality: 'Danish'}.to_query('user') + # # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish" + # + # The string pairs "key=value" that conform the query string + # are sorted lexicographically in ascending order. + # + # This method is also aliased as +to_param+. + def to_query(namespace = nil) + query = filter_map do |key, value| + unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty? + value.to_query(namespace ? "#{namespace}[#{key}]" : key) + end + end + + query.sort! unless namespace.to_s.include?("[]") + query.join("&") + end + + alias_method :to_param, :to_query +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/try.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/try.rb new file mode 100644 index 0000000..c2c7625 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/try.rb @@ -0,0 +1,158 @@ +# frozen_string_literal: true + +require "delegate" + +module ActiveSupport + module Tryable # :nodoc: + def try(*args, &block) + if args.empty? && block_given? + if block.arity == 0 + instance_eval(&block) + else + yield self + end + elsif respond_to?(args.first) + public_send(*args, &block) + end + end + ruby2_keywords(:try) + + def try!(*args, &block) + if args.empty? && block_given? + if block.arity == 0 + instance_eval(&block) + else + yield self + end + else + public_send(*args, &block) + end + end + ruby2_keywords(:try!) + end +end + +class Object + include ActiveSupport::Tryable + + ## + # :method: try + # + # :call-seq: + # try(*args, &block) + # + # Invokes the public method whose name goes as first argument just like + # +public_send+ does, except that if the receiver does not respond to it the + # call returns +nil+ rather than raising an exception. + # + # This method is defined to be able to write + # + # @person.try(:name) + # + # instead of + # + # @person.name if @person + # + # +try+ calls can be chained: + # + # @person.try(:spouse).try(:name) + # + # instead of + # + # @person.spouse.name if @person && @person.spouse + # + # +try+ will also return +nil+ if the receiver does not respond to the method: + # + # @person.try(:non_existing_method) # => nil + # + # instead of + # + # @person.non_existing_method if @person.respond_to?(:non_existing_method) # => nil + # + # +try+ returns +nil+ when called on +nil+ regardless of whether it responds + # to the method: + # + # nil.try(:to_i) # => nil, rather than 0 + # + # Arguments and blocks are forwarded to the method if invoked: + # + # @posts.try(:each_slice, 2) do |a, b| + # ... + # end + # + # The number of arguments in the signature must match. If the object responds + # to the method the call is attempted and +ArgumentError+ is still raised + # in case of argument mismatch. + # + # If +try+ is called without arguments it yields the receiver to a given + # block unless it is +nil+: + # + # @person.try do |p| + # ... + # end + # + # You can also call try with a block without accepting an argument, and the block + # will be instance_eval'ed instead: + # + # @person.try { upcase.truncate(50) } + # + # Please also note that +try+ is defined on +Object+. Therefore, it won't work + # with instances of classes that do not have +Object+ among their ancestors, + # like direct subclasses of +BasicObject+. + + ## + # :method: try! + # + # :call-seq: + # try!(*args, &block) + # + # Same as #try, but raises a +NoMethodError+ exception if the receiver is + # not +nil+ and does not implement the tried method. + # + # "a".try!(:upcase) # => "A" + # nil.try!(:upcase) # => nil + # 123.try!(:upcase) # => NoMethodError: undefined method `upcase' for 123:Integer +end + +class Delegator + include ActiveSupport::Tryable + + ## + # :method: try + # + # :call-seq: + # try(*args, &block) + # + # See Object#try + + ## + # :method: try! + # + # :call-seq: + # try!(*args, &block) + # + # See Object#try! +end + +class NilClass + # Calling +try+ on +nil+ always returns +nil+. + # It becomes especially helpful when navigating through associations that may return +nil+. + # + # nil.try(:name) # => nil + # + # Without +try+ + # @person && @person.children.any? && @person.children.first.name + # + # With +try+ + # @person.try(:children).try(:first).try(:name) + def try(*) + nil + end + + # Calling +try!+ on +nil+ always returns +nil+. + # + # nil.try!(:name) # => nil + def try!(*) + nil + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/with_options.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/with_options.rb new file mode 100644 index 0000000..0f40448 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/object/with_options.rb @@ -0,0 +1,101 @@ +# frozen_string_literal: true + +require "active_support/option_merger" + +class Object + # An elegant way to factor duplication out of options passed to a series of + # method calls. Each method called in the block, with the block variable as + # the receiver, will have its options merged with the default +options+ hash + # provided. Each method called on the block variable must take an options + # hash as its final argument. + # + # Without with_options, this code contains duplication: + # + # class Account < ActiveRecord::Base + # has_many :customers, dependent: :destroy + # has_many :products, dependent: :destroy + # has_many :invoices, dependent: :destroy + # has_many :expenses, dependent: :destroy + # end + # + # Using with_options, we can remove the duplication: + # + # class Account < ActiveRecord::Base + # with_options dependent: :destroy do |assoc| + # assoc.has_many :customers + # assoc.has_many :products + # assoc.has_many :invoices + # assoc.has_many :expenses + # end + # end + # + # It can also be used with an explicit receiver: + # + # I18n.with_options locale: user.locale, scope: 'newsletter' do |i18n| + # subject i18n.t :subject + # body i18n.t :body, user_name: user.name + # end + # + # When you don't pass an explicit receiver, it executes the whole block + # in merging options context: + # + # class Account < ActiveRecord::Base + # with_options dependent: :destroy do + # has_many :customers + # has_many :products + # has_many :invoices + # has_many :expenses + # end + # end + # + # with_options can also be nested since the call is forwarded to its receiver. + # + # NOTE: Each nesting level will merge inherited defaults in addition to their own. + # + # class Post < ActiveRecord::Base + # with_options if: :persisted?, length: { minimum: 50 } do + # validates :content, if: -> { content.present? } + # end + # end + # + # The code is equivalent to: + # + # validates :content, length: { minimum: 50 }, if: -> { content.present? } + # + # Hence the inherited default for +if+ key is ignored. + # + # NOTE: You cannot call class methods implicitly inside of with_options. + # You can access these methods using the class name instead: + # + # class Phone < ActiveRecord::Base + # enum phone_number_type: { home: 0, office: 1, mobile: 2 } + # + # with_options presence: true do + # validates :phone_number_type, inclusion: { in: Phone.phone_number_types.keys } + # end + # end + # + # When the block argument is omitted, the decorated Object instance is returned: + # + # module MyStyledHelpers + # def styled + # with_options style: "color: red;" + # end + # end + # + # # styled.link_to "I'm red", "/" + # # #=> I'm red + # + # # styled.button_tag "I'm red too!" + # # #=> + # + def with_options(options, &block) + option_merger = ActiveSupport::OptionMerger.new(self, options) + + if block + block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger) + else + option_merger + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/pathname.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/pathname.rb new file mode 100644 index 0000000..611a43e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/pathname.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +require "active_support/core_ext/pathname/existence" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/pathname/existence.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/pathname/existence.rb new file mode 100644 index 0000000..9bb9b17 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/pathname/existence.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +class Pathname + # Returns the receiver if the named file exists otherwise returns +nil+. + # pathname.existence is equivalent to + # + # pathname.exist? ? pathname : nil + # + # For example, something like + # + # content = pathname.read if pathname.exist? + # + # becomes + # + # content = pathname.existence&.read + # + # @return [Pathname] + def existence + self if exist? + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range.rb new file mode 100644 index 0000000..ba6bc9b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +require "active_support/core_ext/range/conversions" +require "active_support/core_ext/range/deprecated_conversions" unless ENV["RAILS_DISABLE_DEPRECATED_TO_S_CONVERSION"] +require "active_support/core_ext/range/compare_range" +require "active_support/core_ext/range/overlaps" +require "active_support/core_ext/range/each" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/compare_range.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/compare_range.rb new file mode 100644 index 0000000..affbbeb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/compare_range.rb @@ -0,0 +1,57 @@ +# frozen_string_literal: true + +module ActiveSupport + module CompareWithRange + # Extends the default Range#=== to support range comparisons. + # (1..5) === (1..5) # => true + # (1..5) === (2..3) # => true + # (1..5) === (1...6) # => true + # (1..5) === (2..6) # => false + # + # The native Range#=== behavior is untouched. + # ('a'..'f') === ('c') # => true + # (5..9) === (11) # => false + # + # The given range must be fully bounded, with both start and end. + def ===(value) + if value.is_a?(::Range) + is_backwards_op = value.exclude_end? ? :>= : :> + return false if value.begin && value.end && value.begin.public_send(is_backwards_op, value.end) + # 1...10 includes 1..9 but it does not include 1..10. + # 1..10 includes 1...11 but it does not include 1...12. + operator = exclude_end? && !value.exclude_end? ? :< : :<= + value_max = !exclude_end? && value.exclude_end? ? value.max : value.last + super(value.first) && (self.end.nil? || value_max.public_send(operator, last)) + else + super + end + end + + # Extends the default Range#include? to support range comparisons. + # (1..5).include?(1..5) # => true + # (1..5).include?(2..3) # => true + # (1..5).include?(1...6) # => true + # (1..5).include?(2..6) # => false + # + # The native Range#include? behavior is untouched. + # ('a'..'f').include?('c') # => true + # (5..9).include?(11) # => false + # + # The given range must be fully bounded, with both start and end. + def include?(value) + if value.is_a?(::Range) + is_backwards_op = value.exclude_end? ? :>= : :> + return false if value.begin && value.end && value.begin.public_send(is_backwards_op, value.end) + # 1...10 includes 1..9 but it does not include 1..10. + # 1..10 includes 1...11 but it does not include 1...12. + operator = exclude_end? && !value.exclude_end? ? :< : :<= + value_max = !exclude_end? && value.exclude_end? ? value.max : value.last + super(value.first) && (self.end.nil? || value_max.public_send(operator, last)) + else + super + end + end + end +end + +Range.prepend(ActiveSupport::CompareWithRange) diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/conversions.rb new file mode 100644 index 0000000..1c80ea3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/conversions.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +module ActiveSupport + module RangeWithFormat + RANGE_FORMATS = { + db: -> (start, stop) do + case start + when String then "BETWEEN '#{start}' AND '#{stop}'" + else + "BETWEEN '#{start.to_fs(:db)}' AND '#{stop.to_fs(:db)}'" + end + end + } + + # Convert range to a formatted string. See RANGE_FORMATS for predefined formats. + # + # This method is aliased to to_formatted_s. + # + # range = (1..100) # => 1..100 + # + # range.to_s # => "1..100" + # range.to_fs(:db) # => "BETWEEN '1' AND '100'" + # + # == Adding your own range formats to to_s + # You can add your own formats to the Range::RANGE_FORMATS hash. + # Use the format name as the hash key and a Proc instance. + # + # # config/initializers/range_formats.rb + # Range::RANGE_FORMATS[:short] = ->(start, stop) { "Between #{start.to_fs(:db)} and #{stop.to_fs(:db)}" } + def to_fs(format = :default) + if formatter = RANGE_FORMATS[format] + formatter.call(first, last) + else + to_s + end + end + alias_method :to_formatted_s, :to_fs + end +end + +Range.prepend(ActiveSupport::RangeWithFormat) diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/deprecated_conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/deprecated_conversions.rb new file mode 100644 index 0000000..86b377f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/deprecated_conversions.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +module ActiveSupport + module DeprecatedRangeWithFormat # :nodoc: + NOT_SET = Object.new # :nodoc: + def to_s(format = NOT_SET) + if formatter = RangeWithFormat::RANGE_FORMATS[format] + ActiveSupport::Deprecation.warn( + "Range#to_s(#{format.inspect}) is deprecated. Please use Range#to_fs(#{format.inspect}) instead." + ) + formatter.call(first, last) + elsif format == NOT_SET + super() + else + ActiveSupport::Deprecation.warn( + "Range#to_s(#{format.inspect}) is deprecated. Please use Range#to_fs(#{format.inspect}) instead." + ) + super() + end + end + alias_method :to_default_s, :to_s + deprecate :to_default_s + end +end + +Range.prepend(ActiveSupport::DeprecatedRangeWithFormat) diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/each.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/each.rb new file mode 100644 index 0000000..1c44cc8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/each.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +require "active_support/time_with_zone" + +module ActiveSupport + module EachTimeWithZone # :nodoc: + def each(&block) + ensure_iteration_allowed + super + end + + def step(n = 1, &block) + ensure_iteration_allowed + super + end + + private + def ensure_iteration_allowed + raise TypeError, "can't iterate from #{first.class}" if first.is_a?(TimeWithZone) + end + end +end + +Range.prepend(ActiveSupport::EachTimeWithZone) diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/include_time_with_zone.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/include_time_with_zone.rb new file mode 100644 index 0000000..f2378d4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/include_time_with_zone.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +# frozen_string_literal: true + +ActiveSupport::Deprecation.warn(<<-MSG.squish) + `active_support/core_ext/range/include_time_with_zone` is deprecated and will be removed in Rails 7.1. +MSG diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/overlaps.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/overlaps.rb new file mode 100644 index 0000000..f753607 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/range/overlaps.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +class Range + # Compare two ranges and see if they overlap each other + # (1..5).overlaps?(4..6) # => true + # (1..5).overlaps?(7..9) # => false + def overlaps?(other) + cover?(other.first) || other.cover?(first) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/regexp.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/regexp.rb new file mode 100644 index 0000000..15534ff --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/regexp.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +class Regexp + # Returns +true+ if the regexp has the multiline flag set. + # + # (/./).multiline? # => false + # (/./m).multiline? # => true + # + # Regexp.new(".").multiline? # => false + # Regexp.new(".", Regexp::MULTILINE).multiline? # => true + def multiline? + options & MULTILINE == MULTILINE + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/securerandom.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/securerandom.rb new file mode 100644 index 0000000..ef812f7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/securerandom.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +require "securerandom" + +module SecureRandom + BASE58_ALPHABET = ("0".."9").to_a + ("A".."Z").to_a + ("a".."z").to_a - ["0", "O", "I", "l"] + BASE36_ALPHABET = ("0".."9").to_a + ("a".."z").to_a + + # SecureRandom.base58 generates a random base58 string. + # + # The argument _n_ specifies the length of the random string to be generated. + # + # If _n_ is not specified or is +nil+, 16 is assumed. It may be larger in the future. + # + # The result may contain alphanumeric characters except 0, O, I and l. + # + # p SecureRandom.base58 # => "4kUgL2pdQMSCQtjE" + # p SecureRandom.base58(24) # => "77TMHrHJFvFDwodq8w7Ev2m7" + def self.base58(n = 16) + SecureRandom.random_bytes(n).unpack("C*").map do |byte| + idx = byte % 64 + idx = SecureRandom.random_number(58) if idx >= 58 + BASE58_ALPHABET[idx] + end.join + end + + # SecureRandom.base36 generates a random base36 string in lowercase. + # + # The argument _n_ specifies the length of the random string to be generated. + # + # If _n_ is not specified or is +nil+, 16 is assumed. It may be larger in the future. + # This method can be used over +base58+ if a deterministic case key is necessary. + # + # The result will contain alphanumeric characters in lowercase. + # + # p SecureRandom.base36 # => "4kugl2pdqmscqtje" + # p SecureRandom.base36(24) # => "77tmhrhjfvfdwodq8w7ev2m7" + def self.base36(n = 16) + SecureRandom.random_bytes(n).unpack("C*").map do |byte| + idx = byte % 64 + idx = SecureRandom.random_number(36) if idx >= 36 + BASE36_ALPHABET[idx] + end.join + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string.rb new file mode 100644 index 0000000..757d15c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +require "active_support/core_ext/string/conversions" +require "active_support/core_ext/string/filters" +require "active_support/core_ext/string/multibyte" +require "active_support/core_ext/string/starts_ends_with" +require "active_support/core_ext/string/inflections" +require "active_support/core_ext/string/access" +require "active_support/core_ext/string/behavior" +require "active_support/core_ext/string/output_safety" +require "active_support/core_ext/string/exclude" +require "active_support/core_ext/string/strip" +require "active_support/core_ext/string/inquiry" +require "active_support/core_ext/string/indent" +require "active_support/core_ext/string/zones" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/access.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/access.rb new file mode 100644 index 0000000..f6a14c0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/access.rb @@ -0,0 +1,95 @@ +# frozen_string_literal: true + +class String + # If you pass a single integer, returns a substring of one character at that + # position. The first character of the string is at position 0, the next at + # position 1, and so on. If a range is supplied, a substring containing + # characters at offsets given by the range is returned. In both cases, if an + # offset is negative, it is counted from the end of the string. Returns +nil+ + # if the initial offset falls outside the string. Returns an empty string if + # the beginning of the range is greater than the end of the string. + # + # str = "hello" + # str.at(0) # => "h" + # str.at(1..3) # => "ell" + # str.at(-2) # => "l" + # str.at(-2..-1) # => "lo" + # str.at(5) # => nil + # str.at(5..-1) # => "" + # + # If a Regexp is given, the matching portion of the string is returned. + # If a String is given, that given string is returned if it occurs in + # the string. In both cases, +nil+ is returned if there is no match. + # + # str = "hello" + # str.at(/lo/) # => "lo" + # str.at(/ol/) # => nil + # str.at("lo") # => "lo" + # str.at("ol") # => nil + def at(position) + self[position] + end + + # Returns a substring from the given position to the end of the string. + # If the position is negative, it is counted from the end of the string. + # + # str = "hello" + # str.from(0) # => "hello" + # str.from(3) # => "lo" + # str.from(-2) # => "lo" + # + # You can mix it with +to+ method and do fun things like: + # + # str = "hello" + # str.from(0).to(-1) # => "hello" + # str.from(1).to(-2) # => "ell" + def from(position) + self[position, length] + end + + # Returns a substring from the beginning of the string to the given position. + # If the position is negative, it is counted from the end of the string. + # + # str = "hello" + # str.to(0) # => "h" + # str.to(3) # => "hell" + # str.to(-2) # => "hell" + # + # You can mix it with +from+ method and do fun things like: + # + # str = "hello" + # str.from(0).to(-1) # => "hello" + # str.from(1).to(-2) # => "ell" + def to(position) + position += size if position < 0 + self[0, position + 1] || +"" + end + + # Returns the first character. If a limit is supplied, returns a substring + # from the beginning of the string until it reaches the limit value. If the + # given limit is greater than or equal to the string length, returns a copy of self. + # + # str = "hello" + # str.first # => "h" + # str.first(1) # => "h" + # str.first(2) # => "he" + # str.first(0) # => "" + # str.first(6) # => "hello" + def first(limit = 1) + self[0, limit] || raise(ArgumentError, "negative limit") + end + + # Returns the last character of the string. If a limit is supplied, returns a substring + # from the end of the string until it reaches the limit value (counting backwards). If + # the given limit is greater than or equal to the string length, returns a copy of self. + # + # str = "hello" + # str.last # => "o" + # str.last(1) # => "o" + # str.last(2) # => "lo" + # str.last(0) # => "" + # str.last(6) # => "hello" + def last(limit = 1) + self[[length - limit, 0].max, limit] || raise(ArgumentError, "negative limit") + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/behavior.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/behavior.rb new file mode 100644 index 0000000..35a5aa7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/behavior.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +class String + # Enables more predictable duck-typing on String-like classes. See Object#acts_like?. + def acts_like_string? + true + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/conversions.rb new file mode 100644 index 0000000..e84a390 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/conversions.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +require "date" +require "active_support/core_ext/time/calculations" + +class String + # Converts a string to a Time value. + # The +form+ can be either :utc or :local (default :local). + # + # The time is parsed using Time.parse method. + # If +form+ is :local, then the time is in the system timezone. + # If the date part is missing then the current date is used and if + # the time part is missing then it is assumed to be 00:00:00. + # + # "13-12-2012".to_time # => 2012-12-13 00:00:00 +0100 + # "06:12".to_time # => 2012-12-13 06:12:00 +0100 + # "2012-12-13 06:12".to_time # => 2012-12-13 06:12:00 +0100 + # "2012-12-13T06:12".to_time # => 2012-12-13 06:12:00 +0100 + # "2012-12-13T06:12".to_time(:utc) # => 2012-12-13 06:12:00 UTC + # "12/13/2012".to_time # => ArgumentError: argument out of range + # "1604326192".to_time # => ArgumentError: argument out of range + def to_time(form = :local) + parts = Date._parse(self, false) + used_keys = %i(year mon mday hour min sec sec_fraction offset) + return if (parts.keys & used_keys).empty? + + now = Time.now + time = Time.new( + parts.fetch(:year, now.year), + parts.fetch(:mon, now.month), + parts.fetch(:mday, now.day), + parts.fetch(:hour, 0), + parts.fetch(:min, 0), + parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0), + parts.fetch(:offset, form == :utc ? 0 : nil) + ) + + form == :utc ? time.utc : time.to_time + end + + # Converts a string to a Date value. + # + # "1-1-2012".to_date # => Sun, 01 Jan 2012 + # "01/01/2012".to_date # => Sun, 01 Jan 2012 + # "2012-12-13".to_date # => Thu, 13 Dec 2012 + # "12/13/2012".to_date # => ArgumentError: invalid date + def to_date + ::Date.parse(self, false) unless blank? + end + + # Converts a string to a DateTime value. + # + # "1-1-2012".to_datetime # => Sun, 01 Jan 2012 00:00:00 +0000 + # "01/01/2012 23:59:59".to_datetime # => Sun, 01 Jan 2012 23:59:59 +0000 + # "2012-12-13 12:50".to_datetime # => Thu, 13 Dec 2012 12:50:00 +0000 + # "12/13/2012".to_datetime # => ArgumentError: invalid date + def to_datetime + ::DateTime.parse(self, false) unless blank? + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/exclude.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/exclude.rb new file mode 100644 index 0000000..8e46268 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/exclude.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +class String + # The inverse of String#include?. Returns true if the string + # does not include the other string. + # + # "hello".exclude? "lo" # => false + # "hello".exclude? "ol" # => true + # "hello".exclude? ?h # => false + def exclude?(string) + !include?(string) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/filters.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/filters.rb new file mode 100644 index 0000000..dc163c5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/filters.rb @@ -0,0 +1,145 @@ +# frozen_string_literal: true + +class String + # Returns the string, first removing all whitespace on both ends of + # the string, and then changing remaining consecutive whitespace + # groups into one space each. + # + # Note that it handles both ASCII and Unicode whitespace. + # + # %{ Multi-line + # string }.squish # => "Multi-line string" + # " foo bar \n \t boo".squish # => "foo bar boo" + def squish + dup.squish! + end + + # Performs a destructive squish. See String#squish. + # str = " foo bar \n \t boo" + # str.squish! # => "foo bar boo" + # str # => "foo bar boo" + def squish! + gsub!(/[[:space:]]+/, " ") + strip! + self + end + + # Returns a new string with all occurrences of the patterns removed. + # str = "foo bar test" + # str.remove(" test") # => "foo bar" + # str.remove(" test", /bar/) # => "foo " + # str # => "foo bar test" + def remove(*patterns) + dup.remove!(*patterns) + end + + # Alters the string by removing all occurrences of the patterns. + # str = "foo bar test" + # str.remove!(" test", /bar/) # => "foo " + # str # => "foo " + def remove!(*patterns) + patterns.each do |pattern| + gsub! pattern, "" + end + + self + end + + # Truncates a given +text+ after a given length if +text+ is longer than length: + # + # 'Once upon a time in a world far far away'.truncate(27) + # # => "Once upon a time in a wo..." + # + # Pass a string or regexp :separator to truncate +text+ at a natural break: + # + # 'Once upon a time in a world far far away'.truncate(27, separator: ' ') + # # => "Once upon a time in a..." + # + # 'Once upon a time in a world far far away'.truncate(27, separator: /\s/) + # # => "Once upon a time in a..." + # + # The last characters will be replaced with the :omission string (defaults to "...") + # for a total length not exceeding length: + # + # 'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)') + # # => "And they f... (continued)" + def truncate(truncate_at, options = {}) + return dup unless length > truncate_at + + omission = options[:omission] || "..." + length_with_room_for_omission = truncate_at - omission.length + stop = \ + if options[:separator] + rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission + else + length_with_room_for_omission + end + + +"#{self[0, stop]}#{omission}" + end + + # Truncates +text+ to at most bytesize bytes in length without + # breaking string encoding by splitting multibyte characters or breaking + # grapheme clusters ("perceptual characters") by truncating at combining + # characters. + # + # >> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".size + # => 20 + # >> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".bytesize + # => 80 + # >> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".truncate_bytes(20) + # => "🔪🔪🔪🔪…" + # + # The truncated text ends with the :omission string, defaulting + # to "…", for a total length not exceeding bytesize. + def truncate_bytes(truncate_at, omission: "…") + omission ||= "" + + case + when bytesize <= truncate_at + dup + when omission.bytesize > truncate_at + raise ArgumentError, "Omission #{omission.inspect} is #{omission.bytesize}, larger than the truncation length of #{truncate_at} bytes" + when omission.bytesize == truncate_at + omission.dup + else + self.class.new.tap do |cut| + cut_at = truncate_at - omission.bytesize + + each_grapheme_cluster do |grapheme| + if cut.bytesize + grapheme.bytesize <= cut_at + cut << grapheme + else + break + end + end + + cut << omission + end + end + end + + # Truncates a given +text+ after a given number of words (words_count): + # + # 'Once upon a time in a world far far away'.truncate_words(4) + # # => "Once upon a time..." + # + # Pass a string or regexp :separator to specify a different separator of words: + # + # 'Once
upon
a
time
in
a
world'.truncate_words(5, separator: '
') + # # => "Once
upon
a
time
in..." + # + # The last characters will be replaced with the :omission string (defaults to "..."): + # + # 'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)') + # # => "And they found that many... (continued)" + def truncate_words(words_count, options = {}) + sep = options[:separator] || /\s+/ + sep = Regexp.escape(sep.to_s) unless Regexp === sep + if self =~ /\A((?>.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/m + $1 + (options[:omission] || "...") + else + dup + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/indent.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/indent.rb new file mode 100644 index 0000000..af9d181 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/indent.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +class String + # Same as +indent+, except it indents the receiver in-place. + # + # Returns the indented string, or +nil+ if there was nothing to indent. + def indent!(amount, indent_string = nil, indent_empty_lines = false) + indent_string = indent_string || self[/^[ \t]/] || " " + re = indent_empty_lines ? /^/ : /^(?!$)/ + gsub!(re, indent_string * amount) + end + + # Indents the lines in the receiver: + # + # < + # def some_method + # some_code + # end + # + # The second argument, +indent_string+, specifies which indent string to + # use. The default is +nil+, which tells the method to make a guess by + # peeking at the first indented line, and fallback to a space if there is + # none. + # + # " foo".indent(2) # => " foo" + # "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar" + # "foo".indent(2, "\t") # => "\t\tfoo" + # + # While +indent_string+ is typically one space or tab, it may be any string. + # + # The third argument, +indent_empty_lines+, is a flag that says whether + # empty lines should be indented. Default is false. + # + # "foo\n\nbar".indent(2) # => " foo\n\n bar" + # "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar" + # + def indent(amount, indent_string = nil, indent_empty_lines = false) + dup.tap { |_| _.indent!(amount, indent_string, indent_empty_lines) } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/inflections.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/inflections.rb new file mode 100644 index 0000000..e0749f9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/inflections.rb @@ -0,0 +1,293 @@ +# frozen_string_literal: true + +require "active_support/inflector/methods" +require "active_support/inflector/transliterate" + +# String inflections define new methods on the String class to transform names for different purposes. +# For instance, you can figure out the name of a table from the name of a class. +# +# 'ScaleScore'.tableize # => "scale_scores" +# +class String + # Returns the plural form of the word in the string. + # + # If the optional parameter +count+ is specified, + # the singular form will be returned if count == 1. + # For any other value of +count+ the plural will be returned. + # + # If the optional parameter +locale+ is specified, + # the word will be pluralized as a word of that language. + # By default, this parameter is set to :en. + # You must define your own inflection rules for languages other than English. + # + # 'post'.pluralize # => "posts" + # 'octopus'.pluralize # => "octopi" + # 'sheep'.pluralize # => "sheep" + # 'words'.pluralize # => "words" + # 'the blue mailman'.pluralize # => "the blue mailmen" + # 'CamelOctopus'.pluralize # => "CamelOctopi" + # 'apple'.pluralize(1) # => "apple" + # 'apple'.pluralize(2) # => "apples" + # 'ley'.pluralize(:es) # => "leyes" + # 'ley'.pluralize(1, :es) # => "ley" + # + # See ActiveSupport::Inflector.pluralize. + def pluralize(count = nil, locale = :en) + locale = count if count.is_a?(Symbol) + if count == 1 + dup + else + ActiveSupport::Inflector.pluralize(self, locale) + end + end + + # The reverse of +pluralize+, returns the singular form of a word in a string. + # + # If the optional parameter +locale+ is specified, + # the word will be singularized as a word of that language. + # By default, this parameter is set to :en. + # You must define your own inflection rules for languages other than English. + # + # 'posts'.singularize # => "post" + # 'octopi'.singularize # => "octopus" + # 'sheep'.singularize # => "sheep" + # 'word'.singularize # => "word" + # 'the blue mailmen'.singularize # => "the blue mailman" + # 'CamelOctopi'.singularize # => "CamelOctopus" + # 'leyes'.singularize(:es) # => "ley" + # + # See ActiveSupport::Inflector.singularize. + def singularize(locale = :en) + ActiveSupport::Inflector.singularize(self, locale) + end + + # +constantize+ tries to find a declared constant with the name specified + # in the string. It raises a NameError when the name is not in CamelCase + # or is not initialized. + # + # 'Module'.constantize # => Module + # 'Class'.constantize # => Class + # 'blargle'.constantize # => NameError: wrong constant name blargle + # + # See ActiveSupport::Inflector.constantize. + def constantize + ActiveSupport::Inflector.constantize(self) + end + + # +safe_constantize+ tries to find a declared constant with the name specified + # in the string. It returns +nil+ when the name is not in CamelCase + # or is not initialized. + # + # 'Module'.safe_constantize # => Module + # 'Class'.safe_constantize # => Class + # 'blargle'.safe_constantize # => nil + # + # See ActiveSupport::Inflector.safe_constantize. + def safe_constantize + ActiveSupport::Inflector.safe_constantize(self) + end + + # By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize + # is set to :lower then camelize produces lowerCamelCase. + # + # +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces. + # + # 'active_record'.camelize # => "ActiveRecord" + # 'active_record'.camelize(:lower) # => "activeRecord" + # 'active_record/errors'.camelize # => "ActiveRecord::Errors" + # 'active_record/errors'.camelize(:lower) # => "activeRecord::Errors" + # + # +camelize+ is also aliased as +camelcase+. + # + # See ActiveSupport::Inflector.camelize. + def camelize(first_letter = :upper) + case first_letter + when :upper + ActiveSupport::Inflector.camelize(self, true) + when :lower + ActiveSupport::Inflector.camelize(self, false) + else + raise ArgumentError, "Invalid option, use either :upper or :lower." + end + end + alias_method :camelcase, :camelize + + # Capitalizes all the words and replaces some characters in the string to create + # a nicer looking title. +titleize+ is meant for creating pretty output. It is not + # used in the Rails internals. + # + # The trailing '_id','Id'.. can be kept and capitalized by setting the + # optional parameter +keep_id_suffix+ to true. + # By default, this parameter is false. + # + # 'man from the boondocks'.titleize # => "Man From The Boondocks" + # 'x-men: the last stand'.titleize # => "X Men: The Last Stand" + # 'string_ending_with_id'.titleize(keep_id_suffix: true) # => "String Ending With Id" + # + # +titleize+ is also aliased as +titlecase+. + # + # See ActiveSupport::Inflector.titleize. + def titleize(keep_id_suffix: false) + ActiveSupport::Inflector.titleize(self, keep_id_suffix: keep_id_suffix) + end + alias_method :titlecase, :titleize + + # The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string. + # + # +underscore+ will also change '::' to '/' to convert namespaces to paths. + # + # 'ActiveModel'.underscore # => "active_model" + # 'ActiveModel::Errors'.underscore # => "active_model/errors" + # + # See ActiveSupport::Inflector.underscore. + def underscore + ActiveSupport::Inflector.underscore(self) + end + + # Replaces underscores with dashes in the string. + # + # 'puni_puni'.dasherize # => "puni-puni" + # + # See ActiveSupport::Inflector.dasherize. + def dasherize + ActiveSupport::Inflector.dasherize(self) + end + + # Removes the module part from the constant expression in the string. + # + # 'ActiveSupport::Inflector::Inflections'.demodulize # => "Inflections" + # 'Inflections'.demodulize # => "Inflections" + # '::Inflections'.demodulize # => "Inflections" + # ''.demodulize # => '' + # + # See ActiveSupport::Inflector.demodulize. + # + # See also +deconstantize+. + def demodulize + ActiveSupport::Inflector.demodulize(self) + end + + # Removes the rightmost segment from the constant expression in the string. + # + # 'Net::HTTP'.deconstantize # => "Net" + # '::Net::HTTP'.deconstantize # => "::Net" + # 'String'.deconstantize # => "" + # '::String'.deconstantize # => "" + # ''.deconstantize # => "" + # + # See ActiveSupport::Inflector.deconstantize. + # + # See also +demodulize+. + def deconstantize + ActiveSupport::Inflector.deconstantize(self) + end + + # Replaces special characters in a string so that it may be used as part of a 'pretty' URL. + # + # If the optional parameter +locale+ is specified, + # the word will be parameterized as a word of that language. + # By default, this parameter is set to nil and it will use + # the configured I18n.locale. + # + # class Person + # def to_param + # "#{id}-#{name.parameterize}" + # end + # end + # + # @person = Person.find(1) + # # => # + # + # <%= link_to(@person.name, person_path) %> + # # => Donald E. Knuth + # + # To preserve the case of the characters in a string, use the +preserve_case+ argument. + # + # class Person + # def to_param + # "#{id}-#{name.parameterize(preserve_case: true)}" + # end + # end + # + # @person = Person.find(1) + # # => # + # + # <%= link_to(@person.name, person_path) %> + # # => Donald E. Knuth + # + # See ActiveSupport::Inflector.parameterize. + def parameterize(separator: "-", preserve_case: false, locale: nil) + ActiveSupport::Inflector.parameterize(self, separator: separator, preserve_case: preserve_case, locale: locale) + end + + # Creates the name of a table like Rails does for models to table names. This method + # uses the +pluralize+ method on the last word in the string. + # + # 'RawScaledScorer'.tableize # => "raw_scaled_scorers" + # 'ham_and_egg'.tableize # => "ham_and_eggs" + # 'fancyCategory'.tableize # => "fancy_categories" + # + # See ActiveSupport::Inflector.tableize. + def tableize + ActiveSupport::Inflector.tableize(self) + end + + # Creates a class name from a plural table name like Rails does for table names to models. + # Note that this returns a string and not a class. (To convert to an actual class + # follow +classify+ with +constantize+.) + # + # 'ham_and_eggs'.classify # => "HamAndEgg" + # 'posts'.classify # => "Post" + # + # See ActiveSupport::Inflector.classify. + def classify + ActiveSupport::Inflector.classify(self) + end + + # Capitalizes the first word, turns underscores into spaces, and (by default)strips a + # trailing '_id' if present. + # Like +titleize+, this is meant for creating pretty output. + # + # The capitalization of the first word can be turned off by setting the + # optional parameter +capitalize+ to false. + # By default, this parameter is true. + # + # The trailing '_id' can be kept and capitalized by setting the + # optional parameter +keep_id_suffix+ to true. + # By default, this parameter is false. + # + # 'employee_salary'.humanize # => "Employee salary" + # 'author_id'.humanize # => "Author" + # 'author_id'.humanize(capitalize: false) # => "author" + # '_id'.humanize # => "Id" + # 'author_id'.humanize(keep_id_suffix: true) # => "Author id" + # + # See ActiveSupport::Inflector.humanize. + def humanize(capitalize: true, keep_id_suffix: false) + ActiveSupport::Inflector.humanize(self, capitalize: capitalize, keep_id_suffix: keep_id_suffix) + end + + # Converts just the first character to uppercase. + # + # 'what a Lovely Day'.upcase_first # => "What a Lovely Day" + # 'w'.upcase_first # => "W" + # ''.upcase_first # => "" + # + # See ActiveSupport::Inflector.upcase_first. + def upcase_first + ActiveSupport::Inflector.upcase_first(self) + end + + # Creates a foreign key name from a class name. + # +separate_class_name_and_id_with_underscore+ sets whether + # the method should put '_' between the name and 'id'. + # + # 'Message'.foreign_key # => "message_id" + # 'Message'.foreign_key(false) # => "messageid" + # 'Admin::Post'.foreign_key # => "post_id" + # + # See ActiveSupport::Inflector.foreign_key. + def foreign_key(separate_class_name_and_id_with_underscore = true) + ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/inquiry.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/inquiry.rb new file mode 100644 index 0000000..d78ad9b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/inquiry.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require "active_support/string_inquirer" +require "active_support/environment_inquirer" + +class String + # Wraps the current string in the ActiveSupport::StringInquirer class, + # which gives you a prettier way to test for equality. + # + # env = 'production'.inquiry + # env.production? # => true + # env.development? # => false + def inquiry + ActiveSupport::StringInquirer.new(self) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/multibyte.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/multibyte.rb new file mode 100644 index 0000000..0542121 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/multibyte.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true + +require "active_support/multibyte" + +class String + # == Multibyte proxy + # + # +mb_chars+ is a multibyte safe proxy for string methods. + # + # It creates and returns an instance of the ActiveSupport::Multibyte::Chars class which + # encapsulates the original string. A Unicode safe version of all the String methods are defined on this proxy + # class. If the proxy class doesn't respond to a certain method, it's forwarded to the encapsulated string. + # + # >> "lj".mb_chars.upcase.to_s + # => "LJ" + # + # NOTE: Ruby 2.4 and later support native Unicode case mappings: + # + # >> "lj".upcase + # => "LJ" + # + # == Method chaining + # + # All the methods on the Chars proxy which normally return a string will return a Chars object. This allows + # method chaining on the result of any of these methods. + # + # name.mb_chars.reverse.length # => 12 + # + # == Interoperability and configuration + # + # The Chars object tries to be as interchangeable with String objects as possible: sorting and comparing between + # String and Char work like expected. The bang! methods change the internal string representation in the Chars + # object. Interoperability problems can be resolved easily with a +to_s+ call. + # + # For more information about the methods defined on the Chars proxy see ActiveSupport::Multibyte::Chars. For + # information about how to change the default Multibyte behavior see ActiveSupport::Multibyte. + def mb_chars + ActiveSupport::Multibyte.proxy_class.new(self) + end + + # Returns +true+ if string has utf_8 encoding. + # + # utf_8_str = "some string".encode "UTF-8" + # iso_str = "some string".encode "ISO-8859-1" + # + # utf_8_str.is_utf8? # => true + # iso_str.is_utf8? # => false + def is_utf8? + case encoding + when Encoding::UTF_8, Encoding::US_ASCII + valid_encoding? + when Encoding::ASCII_8BIT + dup.force_encoding(Encoding::UTF_8).valid_encoding? + else + false + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/output_safety.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/output_safety.rb new file mode 100644 index 0000000..6110b09 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/output_safety.rb @@ -0,0 +1,339 @@ +# frozen_string_literal: true + +require "erb" +require "active_support/core_ext/module/redefine_method" +require "active_support/multibyte/unicode" + +class ERB + module Util + HTML_ESCAPE = { "&" => "&", ">" => ">", "<" => "<", '"' => """, "'" => "'" } + JSON_ESCAPE = { "&" => '\u0026', ">" => '\u003e', "<" => '\u003c', "\u2028" => '\u2028', "\u2029" => '\u2029' } + HTML_ESCAPE_ONCE_REGEXP = /["><']|&(?!([a-zA-Z]+|(#\d+)|(#[xX][\dA-Fa-f]+));)/ + JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/u + + # A utility method for escaping HTML tag characters. + # This method is also aliased as h. + # + # puts html_escape('is a > 0 & a < 10?') + # # => is a > 0 & a < 10? + def html_escape(s) + unwrapped_html_escape(s).html_safe + end + + silence_redefinition_of_method :h + alias h html_escape + + module_function :h + + singleton_class.silence_redefinition_of_method :html_escape + module_function :html_escape + + # HTML escapes strings but doesn't wrap them with an ActiveSupport::SafeBuffer. + # This method is not for public consumption! Seriously! + def unwrapped_html_escape(s) # :nodoc: + s = s.to_s + if s.html_safe? + s + else + CGI.escapeHTML(ActiveSupport::Multibyte::Unicode.tidy_bytes(s)) + end + end + module_function :unwrapped_html_escape + + # A utility method for escaping HTML without affecting existing escaped entities. + # + # html_escape_once('1 < 2 & 3') + # # => "1 < 2 & 3" + # + # html_escape_once('<< Accept & Checkout') + # # => "<< Accept & Checkout" + def html_escape_once(s) + result = ActiveSupport::Multibyte::Unicode.tidy_bytes(s.to_s).gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE) + s.html_safe? ? result.html_safe : result + end + + module_function :html_escape_once + + # A utility method for escaping HTML entities in JSON strings. Specifically, the + # &, > and < characters are replaced with their equivalent unicode escaped form - + # \u0026, \u003e, and \u003c. The Unicode sequences \u2028 and \u2029 are also + # escaped as they are treated as newline characters in some JavaScript engines. + # These sequences have identical meaning as the original characters inside the + # context of a JSON string, so assuming the input is a valid and well-formed + # JSON value, the output will have equivalent meaning when parsed: + # + # json = JSON.generate({ name: ""}) + # # => "{\"name\":\"\"}" + # + # json_escape(json) + # # => "{\"name\":\"\\u003C/script\\u003E\\u003Cscript\\u003Ealert('PWNED!!!')\\u003C/script\\u003E\"}" + # + # JSON.parse(json) == JSON.parse(json_escape(json)) + # # => true + # + # The intended use case for this method is to escape JSON strings before including + # them inside a script tag to avoid XSS vulnerability: + # + # + # + # It is necessary to +raw+ the result of +json_escape+, so that quotation marks + # don't get converted to " entities. +json_escape+ doesn't + # automatically flag the result as HTML safe, since the raw value is unsafe to + # use inside HTML attributes. + # + # If your JSON is being used downstream for insertion into the DOM, be aware of + # whether or not it is being inserted via html(). Most jQuery plugins do this. + # If that is the case, be sure to +html_escape+ or +sanitize+ any user-generated + # content returned by your JSON. + # + # If you need to output JSON elsewhere in your HTML, you can just do something + # like this, as any unsafe characters (including quotation marks) will be + # automatically escaped for you: + # + #
...
+ # + # WARNING: this helper only works with valid JSON. Using this on non-JSON values + # will open up serious XSS vulnerabilities. For example, if you replace the + # +current_user.to_json+ in the example above with user input instead, the browser + # will happily eval() that string as JavaScript. + # + # The escaping performed in this method is identical to those performed in the + # Active Support JSON encoder when +ActiveSupport.escape_html_entities_in_json+ is + # set to true. Because this transformation is idempotent, this helper can be + # applied even if +ActiveSupport.escape_html_entities_in_json+ is already true. + # + # Therefore, when you are unsure if +ActiveSupport.escape_html_entities_in_json+ + # is enabled, or if you are unsure where your JSON string originated from, it + # is recommended that you always apply this helper (other libraries, such as the + # JSON gem, do not provide this kind of protection by default; also some gems + # might override +to_json+ to bypass Active Support's encoder). + def json_escape(s) + result = s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE) + s.html_safe? ? result.html_safe : result + end + + module_function :json_escape + end +end + +class Object + def html_safe? + false + end +end + +class Numeric + def html_safe? + true + end +end + +module ActiveSupport # :nodoc: + class SafeBuffer < String + UNSAFE_STRING_METHODS = %w( + capitalize chomp chop delete delete_prefix delete_suffix + downcase lstrip next reverse rstrip scrub slice squeeze strip + succ swapcase tr tr_s unicode_normalize upcase + ) + + UNSAFE_STRING_METHODS_WITH_BACKREF = %w(gsub sub) + + alias_method :original_concat, :concat + private :original_concat + + # Raised when ActiveSupport::SafeBuffer#safe_concat is called on unsafe buffers. + class SafeConcatError < StandardError + def initialize + super "Could not concatenate to the buffer because it is not html safe." + end + end + + def [](*args) + if html_safe? + new_string = super + + return unless new_string + + new_safe_buffer = new_string.is_a?(SafeBuffer) ? new_string : SafeBuffer.new(new_string) + new_safe_buffer.instance_variable_set :@html_safe, true + new_safe_buffer + else + to_str[*args] + end + end + + def safe_concat(value) + raise SafeConcatError unless html_safe? + original_concat(value) + end + + def initialize(str = "") + @html_safe = true + super + end + + def initialize_copy(other) + super + @html_safe = other.html_safe? + end + + def clone_empty + self[0, 0] + end + + def concat(value) + unless value.nil? + super(implicit_html_escape_interpolated_argument(value)) + end + self + end + alias << concat + + def insert(index, value) + super(index, implicit_html_escape_interpolated_argument(value)) + end + + def prepend(value) + super(implicit_html_escape_interpolated_argument(value)) + end + + def replace(value) + super(implicit_html_escape_interpolated_argument(value)) + end + + def []=(*args) + if args.length == 3 + super(args[0], args[1], implicit_html_escape_interpolated_argument(args[2])) + else + super(args[0], implicit_html_escape_interpolated_argument(args[1])) + end + end + + def +(other) + dup.concat(other) + end + + def *(*) + new_string = super + new_safe_buffer = new_string.is_a?(SafeBuffer) ? new_string : SafeBuffer.new(new_string) + new_safe_buffer.instance_variable_set(:@html_safe, @html_safe) + new_safe_buffer + end + + def %(args) + case args + when Hash + escaped_args = args.transform_values { |arg| explicit_html_escape_interpolated_argument(arg) } + else + escaped_args = Array(args).map { |arg| explicit_html_escape_interpolated_argument(arg) } + end + + self.class.new(super(escaped_args)) + end + + def html_safe? + defined?(@html_safe) && @html_safe + end + + def to_s + self + end + + def to_param + to_str + end + + def encode_with(coder) + coder.represent_object nil, to_str + end + + UNSAFE_STRING_METHODS.each do |unsafe_method| + if unsafe_method.respond_to?(unsafe_method) + class_eval <<-EOT, __FILE__, __LINE__ + 1 + def #{unsafe_method}(*args, &block) # def capitalize(*args, &block) + to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block) + end # end + + def #{unsafe_method}!(*args) # def capitalize!(*args) + @html_safe = false # @html_safe = false + super # super + end # end + EOT + end + end + + UNSAFE_STRING_METHODS_WITH_BACKREF.each do |unsafe_method| + class_eval <<-EOT, __FILE__, __LINE__ + 1 + def #{unsafe_method}(*args, &block) # def gsub(*args, &block) + if block # if block + to_str.#{unsafe_method}(*args) { |*params| # to_str.gsub(*args) { |*params| + set_block_back_references(block, $~) # set_block_back_references(block, $~) + block.call(*params) # block.call(*params) + } # } + else # else + to_str.#{unsafe_method}(*args) # to_str.gsub(*args) + end # end + end # end + + def #{unsafe_method}!(*args, &block) # def gsub!(*args, &block) + @html_safe = false # @html_safe = false + if block # if block + super(*args) { |*params| # super(*args) { |*params| + set_block_back_references(block, $~) # set_block_back_references(block, $~) + block.call(*params) # block.call(*params) + } # } + else # else + super # super + end # end + end # end + EOT + end + + private + def explicit_html_escape_interpolated_argument(arg) + (!html_safe? || arg.html_safe?) ? arg : CGI.escapeHTML(arg.to_s) + end + + def implicit_html_escape_interpolated_argument(arg) + if !html_safe? || arg.html_safe? + arg + else + arg_string = begin + arg.to_str + rescue NoMethodError => error + if error.name == :to_str + str = arg.to_s + ActiveSupport::Deprecation.warn <<~MSG.squish + Implicit conversion of #{arg.class} into String by ActiveSupport::SafeBuffer + is deprecated and will be removed in Rails 7.1. + You must explicitly cast it to a String. + MSG + str + else + raise + end + end + CGI.escapeHTML(arg_string) + end + end + + def set_block_back_references(block, match_data) + block.binding.eval("proc { |m| $~ = m }").call(match_data) + rescue ArgumentError + # Can't create binding from C level Proc + end + end +end + +class String + # Marks a string as trusted safe. It will be inserted into HTML with no + # additional escaping performed. It is your responsibility to ensure that the + # string contains no malicious content. This method is equivalent to the + # +raw+ helper in views. It is recommended that you use +sanitize+ instead of + # this method. It should never be called on user input. + def html_safe + ActiveSupport::SafeBuffer.new(self) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/starts_ends_with.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/starts_ends_with.rb new file mode 100644 index 0000000..1e21637 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/starts_ends_with.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +class String + alias :starts_with? :start_with? + alias :ends_with? :end_with? +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/strip.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/strip.rb new file mode 100644 index 0000000..60e9952 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/strip.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +class String + # Strips indentation in heredocs. + # + # For example in + # + # if options[:usage] + # puts <<-USAGE.strip_heredoc + # This command does such and such. + # + # Supported options are: + # -h This message + # ... + # USAGE + # end + # + # the user would see the usage message aligned against the left margin. + # + # Technically, it looks for the least indented non-empty line + # in the whole string, and removes that amount of leading whitespace. + def strip_heredoc + gsub(/^#{scan(/^[ \t]*(?=\S)/).min}/, "").tap do |stripped| + stripped.freeze if frozen? + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/zones.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/zones.rb new file mode 100644 index 0000000..55dc231 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/string/zones.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require "active_support/core_ext/string/conversions" +require "active_support/core_ext/time/zones" + +class String + # Converts String to a TimeWithZone in the current zone if Time.zone or Time.zone_default + # is set, otherwise converts String to a Time via String#to_time + def in_time_zone(zone = ::Time.zone) + if zone + ::Time.find_zone!(zone).parse(self) + else + to_time + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/symbol.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/symbol.rb new file mode 100644 index 0000000..709fed2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/symbol.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +require "active_support/core_ext/symbol/starts_ends_with" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/symbol/starts_ends_with.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/symbol/starts_ends_with.rb new file mode 100644 index 0000000..4f85217 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/symbol/starts_ends_with.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +class Symbol + alias :starts_with? :start_with? + alias :ends_with? :end_with? +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time.rb new file mode 100644 index 0000000..9716257 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +require "active_support/core_ext/time/acts_like" +require "active_support/core_ext/time/calculations" +require "active_support/core_ext/time/compatibility" +require "active_support/core_ext/time/conversions" +require "active_support/core_ext/time/deprecated_conversions" unless ENV["RAILS_DISABLE_DEPRECATED_TO_S_CONVERSION"] +require "active_support/core_ext/time/zones" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/acts_like.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/acts_like.rb new file mode 100644 index 0000000..8572b49 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/acts_like.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/acts_like" + +class Time + # Duck-types as a Time-like class. See Object#acts_like?. + def acts_like_time? + true + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/calculations.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/calculations.rb new file mode 100644 index 0000000..09553d3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/calculations.rb @@ -0,0 +1,364 @@ +# frozen_string_literal: true + +require "active_support/duration" +require "active_support/core_ext/time/conversions" +require "active_support/time_with_zone" +require "active_support/core_ext/time/zones" +require "active_support/core_ext/date_and_time/calculations" +require "active_support/core_ext/date/calculations" +require "active_support/core_ext/module/remove_method" + +class Time + include DateAndTime::Calculations + + COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + + class << self + # Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances + def ===(other) + super || (self == Time && other.is_a?(ActiveSupport::TimeWithZone)) + end + + # Returns the number of days in the given month. + # If no year is specified, it will use the current year. + def days_in_month(month, year = current.year) + if month == 2 && ::Date.gregorian_leap?(year) + 29 + else + COMMON_YEAR_DAYS_IN_MONTH[month] + end + end + + # Returns the number of days in the given year. + # If no year is specified, it will use the current year. + def days_in_year(year = current.year) + days_in_month(2, year) + 337 + end + + # Returns Time.zone.now when Time.zone or config.time_zone are set, otherwise just returns Time.now. + def current + ::Time.zone ? ::Time.zone.now : ::Time.now + end + + # Layers additional behavior on Time.at so that ActiveSupport::TimeWithZone and DateTime + # instances can be used when called with a single argument + def at_with_coercion(*args, **kwargs) + return at_without_coercion(*args, **kwargs) if args.size != 1 || !kwargs.empty? + + # Time.at can be called with a time or numerical value + time_or_number = args.first + + if time_or_number.is_a?(ActiveSupport::TimeWithZone) + at_without_coercion(time_or_number.to_r).getlocal + elsif time_or_number.is_a?(DateTime) + at_without_coercion(time_or_number.to_f).getlocal + else + at_without_coercion(time_or_number) + end + end + alias_method :at_without_coercion, :at + alias_method :at, :at_with_coercion + + # Creates a +Time+ instance from an RFC 3339 string. + # + # Time.rfc3339('1999-12-31T14:00:00-10:00') # => 2000-01-01 00:00:00 -1000 + # + # If the time or offset components are missing then an +ArgumentError+ will be raised. + # + # Time.rfc3339('1999-12-31') # => ArgumentError: invalid date + def rfc3339(str) + parts = Date._rfc3339(str) + + raise ArgumentError, "invalid date" if parts.empty? + + Time.new( + parts.fetch(:year), + parts.fetch(:mon), + parts.fetch(:mday), + parts.fetch(:hour), + parts.fetch(:min), + parts.fetch(:sec) + parts.fetch(:sec_fraction, 0), + parts.fetch(:offset) + ) + end + end + + # Returns the number of seconds since 00:00:00. + # + # Time.new(2012, 8, 29, 0, 0, 0).seconds_since_midnight # => 0.0 + # Time.new(2012, 8, 29, 12, 34, 56).seconds_since_midnight # => 45296.0 + # Time.new(2012, 8, 29, 23, 59, 59).seconds_since_midnight # => 86399.0 + def seconds_since_midnight + to_i - change(hour: 0).to_i + (usec / 1.0e+6) + end + + # Returns the number of seconds until 23:59:59. + # + # Time.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399 + # Time.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103 + # Time.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0 + def seconds_until_end_of_day + end_of_day.to_i - to_i + end + + # Returns the fraction of a second as a +Rational+ + # + # Time.new(2012, 8, 29, 0, 0, 0.5).sec_fraction # => (1/2) + def sec_fraction + subsec + end + + unless Time.method_defined?(:floor) + def floor(precision = 0) + change(nsec: 0) + subsec.floor(precision) + end + end + + # Restricted Ruby version due to a bug in `Time#ceil` + # See https://bugs.ruby-lang.org/issues/17025 for more details + if RUBY_VERSION <= "2.8" + remove_possible_method :ceil + def ceil(precision = 0) + change(nsec: 0) + subsec.ceil(precision) + end + end + + # Returns a new Time where one or more of the elements have been changed according + # to the +options+ parameter. The time options (:hour, :min, + # :sec, :usec, :nsec) reset cascadingly, so if only + # the hour is passed, then minute, sec, usec and nsec is set to 0. If the hour + # and minute is passed, then sec, usec and nsec is set to 0. The +options+ parameter + # takes a hash with any of these keys: :year, :month, :day, + # :hour, :min, :sec, :usec, :nsec, + # :offset. Pass either :usec or :nsec, not both. + # + # Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0) + # Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0) + # Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => Time.new(1981, 8, 29, 0, 0, 0) + def change(options) + new_year = options.fetch(:year, year) + new_month = options.fetch(:month, month) + new_day = options.fetch(:day, day) + new_hour = options.fetch(:hour, hour) + new_min = options.fetch(:min, options[:hour] ? 0 : min) + new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec) + new_offset = options.fetch(:offset, nil) + + if new_nsec = options[:nsec] + raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec] + new_usec = Rational(new_nsec, 1000) + else + new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000)) + end + + raise ArgumentError, "argument out of range" if new_usec >= 1000000 + + new_sec += Rational(new_usec, 1000000) + + if new_offset + ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec, new_offset) + elsif utc? + ::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec) + elsif zone&.respond_to?(:utc_to_local) + ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec, zone) + elsif zone + ::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec) + else + ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec, utc_offset) + end + end + + # Uses Date to provide precise Time calculations for years, months, and days + # according to the proleptic Gregorian calendar. The +options+ parameter + # takes a hash with any of these keys: :years, :months, + # :weeks, :days, :hours, :minutes, + # :seconds. + # + # Time.new(2015, 8, 1, 14, 35, 0).advance(seconds: 1) # => 2015-08-01 14:35:01 -0700 + # Time.new(2015, 8, 1, 14, 35, 0).advance(minutes: 1) # => 2015-08-01 14:36:00 -0700 + # Time.new(2015, 8, 1, 14, 35, 0).advance(hours: 1) # => 2015-08-01 15:35:00 -0700 + # Time.new(2015, 8, 1, 14, 35, 0).advance(days: 1) # => 2015-08-02 14:35:00 -0700 + # Time.new(2015, 8, 1, 14, 35, 0).advance(weeks: 1) # => 2015-08-08 14:35:00 -0700 + def advance(options) + unless options[:weeks].nil? + options[:weeks], partial_weeks = options[:weeks].divmod(1) + options[:days] = options.fetch(:days, 0) + 7 * partial_weeks + end + + unless options[:days].nil? + options[:days], partial_days = options[:days].divmod(1) + options[:hours] = options.fetch(:hours, 0) + 24 * partial_days + end + + d = to_date.gregorian.advance(options) + time_advanced_by_date = change(year: d.year, month: d.month, day: d.day) + seconds_to_advance = \ + options.fetch(:seconds, 0) + + options.fetch(:minutes, 0) * 60 + + options.fetch(:hours, 0) * 3600 + + if seconds_to_advance.zero? + time_advanced_by_date + else + time_advanced_by_date.since(seconds_to_advance) + end + end + + # Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension + def ago(seconds) + since(-seconds) + end + + # Returns a new Time representing the time a number of seconds since the instance time + def since(seconds) + self + seconds + rescue + to_datetime.since(seconds) + end + alias :in :since + + # Returns a new Time representing the start of the day (0:00) + def beginning_of_day + change(hour: 0) + end + alias :midnight :beginning_of_day + alias :at_midnight :beginning_of_day + alias :at_beginning_of_day :beginning_of_day + + # Returns a new Time representing the middle of the day (12:00) + def middle_of_day + change(hour: 12) + end + alias :midday :middle_of_day + alias :noon :middle_of_day + alias :at_midday :middle_of_day + alias :at_noon :middle_of_day + alias :at_middle_of_day :middle_of_day + + # Returns a new Time representing the end of the day, 23:59:59.999999 + def end_of_day + change( + hour: 23, + min: 59, + sec: 59, + usec: Rational(999999999, 1000) + ) + end + alias :at_end_of_day :end_of_day + + # Returns a new Time representing the start of the hour (x:00) + def beginning_of_hour + change(min: 0) + end + alias :at_beginning_of_hour :beginning_of_hour + + # Returns a new Time representing the end of the hour, x:59:59.999999 + def end_of_hour + change( + min: 59, + sec: 59, + usec: Rational(999999999, 1000) + ) + end + alias :at_end_of_hour :end_of_hour + + # Returns a new Time representing the start of the minute (x:xx:00) + def beginning_of_minute + change(sec: 0) + end + alias :at_beginning_of_minute :beginning_of_minute + + # Returns a new Time representing the end of the minute, x:xx:59.999999 + def end_of_minute + change( + sec: 59, + usec: Rational(999999999, 1000) + ) + end + alias :at_end_of_minute :end_of_minute + + def plus_with_duration(other) # :nodoc: + if ActiveSupport::Duration === other + other.since(self) + else + plus_without_duration(other) + end + end + alias_method :plus_without_duration, :+ + alias_method :+, :plus_with_duration + + def minus_with_duration(other) # :nodoc: + if ActiveSupport::Duration === other + other.until(self) + else + minus_without_duration(other) + end + end + alias_method :minus_without_duration, :- + alias_method :-, :minus_with_duration + + # Time#- can also be used to determine the number of seconds between two Time instances. + # We're layering on additional behavior so that ActiveSupport::TimeWithZone instances + # are coerced into values that Time#- will recognize + def minus_with_coercion(other) + other = other.comparable_time if other.respond_to?(:comparable_time) + other.is_a?(DateTime) ? to_f - other.to_f : minus_without_coercion(other) + end + alias_method :minus_without_coercion, :- + alias_method :-, :minus_with_coercion # rubocop:disable Lint/DuplicateMethods + + # Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances + # can be chronologically compared with a Time + def compare_with_coercion(other) + # we're avoiding Time#to_datetime and Time#to_time because they're expensive + if other.class == Time + compare_without_coercion(other) + elsif other.is_a?(Time) + compare_without_coercion(other.to_time) + else + to_datetime <=> other + end + end + alias_method :compare_without_coercion, :<=> + alias_method :<=>, :compare_with_coercion + + # Layers additional behavior on Time#eql? so that ActiveSupport::TimeWithZone instances + # can be eql? to an equivalent Time + def eql_with_coercion(other) + # if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do eql? comparison + other = other.comparable_time if other.respond_to?(:comparable_time) + eql_without_coercion(other) + end + alias_method :eql_without_coercion, :eql? + alias_method :eql?, :eql_with_coercion + + # Returns a new time the specified number of days ago. + def prev_day(days = 1) + advance(days: -days) + end + + # Returns a new time the specified number of days in the future. + def next_day(days = 1) + advance(days: days) + end + + # Returns a new time the specified number of months ago. + def prev_month(months = 1) + advance(months: -months) + end + + # Returns a new time the specified number of months in the future. + def next_month(months = 1) + advance(months: months) + end + + # Returns a new time the specified number of years ago. + def prev_year(years = 1) + advance(years: -years) + end + + # Returns a new time the specified number of years in the future. + def next_year(years = 1) + advance(years: years) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/compatibility.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/compatibility.rb new file mode 100644 index 0000000..495e4f3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/compatibility.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require "active_support/core_ext/date_and_time/compatibility" +require "active_support/core_ext/module/redefine_method" + +class Time + include DateAndTime::Compatibility + + silence_redefinition_of_method :to_time + + # Either return +self+ or the time in the local system timezone depending + # on the setting of +ActiveSupport.to_time_preserves_timezone+. + def to_time + preserve_timezone ? self : getlocal + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/conversions.rb new file mode 100644 index 0000000..aeb8e14 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/conversions.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true + +require "time" +require "active_support/inflector/methods" +require "active_support/values/time_zone" + +class Time + DATE_FORMATS = { + db: "%Y-%m-%d %H:%M:%S", + inspect: "%Y-%m-%d %H:%M:%S.%9N %z", + number: "%Y%m%d%H%M%S", + nsec: "%Y%m%d%H%M%S%9N", + usec: "%Y%m%d%H%M%S%6N", + time: "%H:%M", + short: "%d %b %H:%M", + long: "%B %d, %Y %H:%M", + long_ordinal: lambda { |time| + day_format = ActiveSupport::Inflector.ordinalize(time.day) + time.strftime("%B #{day_format}, %Y %H:%M") + }, + rfc822: lambda { |time| + offset_format = time.formatted_offset(false) + time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}") + }, + iso8601: lambda { |time| time.iso8601 } + } + + # Converts to a formatted string. See DATE_FORMATS for built-in formats. + # + # This method is aliased to to_formatted_s. + # + # time = Time.now # => 2007-01-18 06:10:17 -06:00 + # + # time.to_fs(:time) # => "06:10" + # time.to_formatted_s(:time) # => "06:10" + # + # time.to_fs(:db) # => "2007-01-18 06:10:17" + # time.to_fs(:number) # => "20070118061017" + # time.to_fs(:short) # => "18 Jan 06:10" + # time.to_fs(:long) # => "January 18, 2007 06:10" + # time.to_fs(:long_ordinal) # => "January 18th, 2007 06:10" + # time.to_fs(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600" + # time.to_fs(:iso8601) # => "2007-01-18T06:10:17-06:00" + # + # == Adding your own time formats to +to_fs+ + # You can add your own formats to the Time::DATE_FORMATS hash. + # Use the format name as the hash key and either a strftime string + # or Proc instance that takes a time argument as the value. + # + # # config/initializers/time_formats.rb + # Time::DATE_FORMATS[:month_and_year] = '%B %Y' + # Time::DATE_FORMATS[:short_ordinal] = ->(time) { time.strftime("%B #{time.day.ordinalize}") } + def to_fs(format = :default) + if formatter = DATE_FORMATS[format] + formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) + else + # Change to `to_s` when deprecation is gone. Also deprecate `to_default_s`. + to_default_s + end + end + alias_method :to_formatted_s, :to_fs + alias_method :to_default_s, :to_s + + # Returns a formatted string of the offset from UTC, or an alternative + # string if the time zone is already UTC. + # + # Time.local(2000).formatted_offset # => "-06:00" + # Time.local(2000).formatted_offset(false) # => "-0600" + def formatted_offset(colon = true, alternate_utc_string = nil) + utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon) + end + + # Aliased to +xmlschema+ for compatibility with +DateTime+ + alias_method :rfc3339, :xmlschema +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/deprecated_conversions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/deprecated_conversions.rb new file mode 100644 index 0000000..2fe730b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/deprecated_conversions.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +require "time" + +class Time + NOT_SET = Object.new # :nodoc: + def to_s(format = NOT_SET) # :nodoc: + if formatter = DATE_FORMATS[format] + ActiveSupport::Deprecation.warn( + "Time#to_s(#{format.inspect}) is deprecated. Please use Time#to_fs(#{format.inspect}) instead." + ) + formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) + elsif format == NOT_SET + to_default_s + else + ActiveSupport::Deprecation.warn( + "Time#to_s(#{format.inspect}) is deprecated. Please use Time#to_fs(#{format.inspect}) instead." + ) + to_default_s + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/zones.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/zones.rb new file mode 100644 index 0000000..76d8639 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/time/zones.rb @@ -0,0 +1,98 @@ +# frozen_string_literal: true + +require "active_support/time_with_zone" +require "active_support/core_ext/time/acts_like" +require "active_support/core_ext/date_and_time/zones" + +class Time + include DateAndTime::Zones + class << self + attr_accessor :zone_default + + # Returns the TimeZone for the current request, if this has been set (via Time.zone=). + # If Time.zone has not been set for the current request, returns the TimeZone specified in config.time_zone. + def zone + ::ActiveSupport::IsolatedExecutionState[:time_zone] || zone_default + end + + # Sets Time.zone to a TimeZone object for the current request/thread. + # + # This method accepts any of the following: + # + # * A Rails TimeZone object. + # * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", -5.hours). + # * A TZInfo::Timezone object. + # * An identifier for a TZInfo::Timezone object (e.g., "America/New_York"). + # + # Here's an example of how you might set Time.zone on a per request basis and reset it when the request is done. + # current_user.time_zone just needs to return a string identifying the user's preferred time zone: + # + # class ApplicationController < ActionController::Base + # around_action :set_time_zone + # + # def set_time_zone + # if logged_in? + # Time.use_zone(current_user.time_zone) { yield } + # else + # yield + # end + # end + # end + def zone=(time_zone) + ::ActiveSupport::IsolatedExecutionState[:time_zone] = find_zone!(time_zone) + end + + # Allows override of Time.zone locally inside supplied block; + # resets Time.zone to existing value when done. + # + # class ApplicationController < ActionController::Base + # around_action :set_time_zone + # + # private + # + # def set_time_zone + # Time.use_zone(current_user.timezone) { yield } + # end + # end + # + # NOTE: This won't affect any ActiveSupport::TimeWithZone + # objects that have already been created, e.g. any model timestamp + # attributes that have been read before the block will remain in + # the application's default timezone. + def use_zone(time_zone) + new_zone = find_zone!(time_zone) + begin + old_zone, ::Time.zone = ::Time.zone, new_zone + yield + ensure + ::Time.zone = old_zone + end + end + + # Returns a TimeZone instance matching the time zone provided. + # Accepts the time zone in any format supported by Time.zone=. + # Raises an +ArgumentError+ for invalid time zones. + # + # Time.find_zone! "America/New_York" # => # + # Time.find_zone! "EST" # => # + # Time.find_zone! -5.hours # => # + # Time.find_zone! nil # => nil + # Time.find_zone! false # => false + # Time.find_zone! "NOT-A-TIMEZONE" # => ArgumentError: Invalid Timezone: NOT-A-TIMEZONE + def find_zone!(time_zone) + return time_zone unless time_zone + + ActiveSupport::TimeZone[time_zone] || raise(ArgumentError, "Invalid Timezone: #{time_zone}") + end + + # Returns a TimeZone instance matching the time zone provided. + # Accepts the time zone in any format supported by Time.zone=. + # Returns +nil+ for invalid time zones. + # + # Time.find_zone "America/New_York" # => # + # Time.find_zone "NOT-A-TIMEZONE" # => nil + def find_zone(time_zone) + find_zone!(time_zone) rescue nil + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/uri.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/uri.rb new file mode 100644 index 0000000..9811477 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/core_ext/uri.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +ActiveSupport::Deprecation.warn(<<-MSG.squish) + `active_support/core_ext/uri` is deprecated and will be removed in Rails 7.1. +MSG diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/current_attributes.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/current_attributes.rb new file mode 100644 index 0000000..b4c6a5d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/current_attributes.rb @@ -0,0 +1,226 @@ +# frozen_string_literal: true + +require "active_support/callbacks" +require "active_support/core_ext/enumerable" +require "active_support/core_ext/module/delegation" + +module ActiveSupport + # Abstract super class that provides a thread-isolated attributes singleton, which resets automatically + # before and after each request. This allows you to keep all the per-request attributes easily + # available to the whole system. + # + # The following full app-like example demonstrates how to use a Current class to + # facilitate easy access to the global, per-request attributes without passing them deeply + # around everywhere: + # + # # app/models/current.rb + # class Current < ActiveSupport::CurrentAttributes + # attribute :account, :user + # attribute :request_id, :user_agent, :ip_address + # + # resets { Time.zone = nil } + # + # def user=(user) + # super + # self.account = user.account + # Time.zone = user.time_zone + # end + # end + # + # # app/controllers/concerns/authentication.rb + # module Authentication + # extend ActiveSupport::Concern + # + # included do + # before_action :authenticate + # end + # + # private + # def authenticate + # if authenticated_user = User.find_by(id: cookies.encrypted[:user_id]) + # Current.user = authenticated_user + # else + # redirect_to new_session_url + # end + # end + # end + # + # # app/controllers/concerns/set_current_request_details.rb + # module SetCurrentRequestDetails + # extend ActiveSupport::Concern + # + # included do + # before_action do + # Current.request_id = request.uuid + # Current.user_agent = request.user_agent + # Current.ip_address = request.ip + # end + # end + # end + # + # class ApplicationController < ActionController::Base + # include Authentication + # include SetCurrentRequestDetails + # end + # + # class MessagesController < ApplicationController + # def create + # Current.account.messages.create(message_params) + # end + # end + # + # class Message < ApplicationRecord + # belongs_to :creator, default: -> { Current.user } + # after_create { |message| Event.create(record: message) } + # end + # + # class Event < ApplicationRecord + # before_create do + # self.request_id = Current.request_id + # self.user_agent = Current.user_agent + # self.ip_address = Current.ip_address + # end + # end + # + # A word of caution: It's easy to overdo a global singleton like Current and tangle your model as a result. + # Current should only be used for a few, top-level globals, like account, user, and request details. + # The attributes stuck in Current should be used by more or less all actions on all requests. If you start + # sticking controller-specific attributes in there, you're going to create a mess. + class CurrentAttributes + include ActiveSupport::Callbacks + define_callbacks :reset + + class << self + # Returns singleton instance for this class in this thread. If none exists, one is created. + def instance + current_instances[current_instances_key] ||= new + end + + # Declares one or more attributes that will be given both class and instance accessor methods. + def attribute(*names) + ActiveSupport::CodeGenerator.batch(generated_attribute_methods, __FILE__, __LINE__) do |owner| + names.each do |name| + owner.define_cached_method(name, namespace: :current_attributes) do |batch| + batch << + "def #{name}" << + "attributes[:#{name}]" << + "end" + end + owner.define_cached_method("#{name}=", namespace: :current_attributes) do |batch| + batch << + "def #{name}=(value)" << + "attributes[:#{name}] = value" << + "end" + end + end + end + + ActiveSupport::CodeGenerator.batch(singleton_class, __FILE__, __LINE__) do |owner| + names.each do |name| + owner.define_cached_method(name, namespace: :current_attributes_delegation) do |batch| + batch << + "def #{name}" << + "instance.#{name}" << + "end" + end + owner.define_cached_method("#{name}=", namespace: :current_attributes_delegation) do |batch| + batch << + "def #{name}=(value)" << + "instance.#{name} = value" << + "end" + end + end + end + end + + # Calls this block before #reset is called on the instance. Used for resetting external collaborators that depend on current values. + def before_reset(&block) + set_callback :reset, :before, &block + end + + # Calls this block after #reset is called on the instance. Used for resetting external collaborators, like Time.zone. + def resets(&block) + set_callback :reset, :after, &block + end + alias_method :after_reset, :resets + + delegate :set, :reset, to: :instance + + def reset_all # :nodoc: + current_instances.each_value(&:reset) + end + + def clear_all # :nodoc: + reset_all + current_instances.clear + end + + private + def generated_attribute_methods + @generated_attribute_methods ||= Module.new.tap { |mod| include mod } + end + + def current_instances + IsolatedExecutionState[:current_attributes_instances] ||= {} + end + + def current_instances_key + @current_instances_key ||= name.to_sym + end + + def method_missing(name, *args, &block) + # Caches the method definition as a singleton method of the receiver. + # + # By letting #delegate handle it, we avoid an enclosure that'll capture args. + singleton_class.delegate name, to: :instance + + send(name, *args, &block) + end + ruby2_keywords(:method_missing) + + def respond_to_missing?(name, _) + super || instance.respond_to?(name) + end + end + + attr_accessor :attributes + + def initialize + @attributes = {} + end + + # Expose one or more attributes within a block. Old values are returned after the block concludes. + # Example demonstrating the common use of needing to set Current attributes outside the request-cycle: + # + # class Chat::PublicationJob < ApplicationJob + # def perform(attributes, room_number, creator) + # Current.set(person: creator) do + # Chat::Publisher.publish(attributes: attributes, room_number: room_number) + # end + # end + # end + def set(set_attributes) + old_attributes = compute_attributes(set_attributes.keys) + assign_attributes(set_attributes) + yield + ensure + assign_attributes(old_attributes) + end + + # Reset all attributes. Should be called before and after actions, when used as a per-request singleton. + def reset + run_callbacks :reset do + self.attributes = {} + end + end + + private + def assign_attributes(new_attributes) + new_attributes.each { |key, value| public_send("#{key}=", value) } + end + + def compute_attributes(keys) + keys.index_with { |key| public_send(key) } + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/current_attributes/test_helper.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/current_attributes/test_helper.rb new file mode 100644 index 0000000..2016384 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/current_attributes/test_helper.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +module ActiveSupport::CurrentAttributes::TestHelper # :nodoc: + def before_setup + ActiveSupport::CurrentAttributes.reset_all + super + end + + def after_teardown + super + ActiveSupport::CurrentAttributes.reset_all + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies.rb new file mode 100644 index 0000000..bb1fc46 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies.rb @@ -0,0 +1,98 @@ +# frozen_string_literal: true + +require "set" +require "active_support/dependencies/interlock" + +module ActiveSupport # :nodoc: + module Dependencies # :nodoc: + require_relative "dependencies/require_dependency" + + singleton_class.attr_accessor :interlock + @interlock = Interlock.new + + # :doc: + + # Execute the supplied block without interference from any + # concurrent loads. + def self.run_interlock(&block) + interlock.running(&block) + end + + # Execute the supplied block while holding an exclusive lock, + # preventing any other thread from being inside a #run_interlock + # block at the same time. + def self.load_interlock(&block) + interlock.loading(&block) + end + + # Execute the supplied block while holding an exclusive lock, + # preventing any other thread from being inside a #run_interlock + # block at the same time. + def self.unload_interlock(&block) + interlock.unloading(&block) + end + + # :nodoc: + + # The array of directories from which we autoload and reload, if reloading + # is enabled. The public interface to push directories to this collection + # from applications or engines is config.autoload_paths. + # + # This collection is allowed to have intersection with autoload_once_paths. + # Common directories are not reloaded. + singleton_class.attr_accessor :autoload_paths + self.autoload_paths = [] + + # The array of directories from which we autoload and never reload, even if + # reloading is enabled. The public interface to push directories to this + # collection from applications or engines is config.autoload_once_paths. + singleton_class.attr_accessor :autoload_once_paths + self.autoload_once_paths = [] + + # This is a private set that collects all eager load paths during bootstrap. + # Useful for Zeitwerk integration. The public interface to push custom + # directories to this collection from applications or engines is + # config.eager_load_paths. + singleton_class.attr_accessor :_eager_load_paths + self._eager_load_paths = Set.new + + # If reloading is enabled, this private set holds autoloaded classes tracked + # by the descendants tracker. It is populated by an on_load callback in the + # main autoloader. Used to clear state. + singleton_class.attr_accessor :_autoloaded_tracked_classes + self._autoloaded_tracked_classes = Set.new + + # If reloading is enabled, this private attribute stores the main autoloader + # of a Rails application. It is `nil` otherwise. + # + # The public interface for this autoloader is `Rails.autoloaders.main`. + singleton_class.attr_accessor :autoloader + + # Private method that reloads constants autoloaded by the main autoloader. + # + # Rails.application.reloader.reload! is the public interface for application + # reload. That involves more things, like deleting unloaded classes from the + # internal state of the descendants tracker, or reloading routes. + def self.clear + unload_interlock do + _autoloaded_tracked_classes.clear + autoloader.reload + end + end + + # Private method used by require_dependency. + def self.search_for_file(relpath) + relpath += ".rb" unless relpath.end_with?(".rb") + autoload_paths.each do |autoload_path| + abspath = File.join(autoload_path, relpath) + return abspath if File.file?(abspath) + end + nil + end + + # Private method that helps configuring the autoloaders. + def self.eager_load?(path) + _eager_load_paths.member?(path) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies/autoload.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies/autoload.rb new file mode 100644 index 0000000..1cee85d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies/autoload.rb @@ -0,0 +1,79 @@ +# frozen_string_literal: true + +require "active_support/inflector/methods" + +module ActiveSupport + # Autoload and eager load conveniences for your library. + # + # This module allows you to define autoloads based on + # Rails conventions (i.e. no need to define the path + # it is automatically guessed based on the filename) + # and also define a set of constants that needs to be + # eager loaded: + # + # module MyLib + # extend ActiveSupport::Autoload + # + # autoload :Model + # + # eager_autoload do + # autoload :Cache + # end + # end + # + # Then your library can be eager loaded by simply calling: + # + # MyLib.eager_load! + module Autoload + def self.extended(base) # :nodoc: + base.class_eval do + @_autoloads = {} + @_under_path = nil + @_at_path = nil + @_eager_autoload = false + end + end + + def autoload(const_name, path = @_at_path) + unless path + full = [name, @_under_path, const_name.to_s].compact.join("::") + path = Inflector.underscore(full) + end + + if @_eager_autoload + @_autoloads[const_name] = path + end + + super const_name, path + end + + def autoload_under(path) + @_under_path, old_path = path, @_under_path + yield + ensure + @_under_path = old_path + end + + def autoload_at(path) + @_at_path, old_path = path, @_at_path + yield + ensure + @_at_path = old_path + end + + def eager_autoload + old_eager, @_eager_autoload = @_eager_autoload, true + yield + ensure + @_eager_autoload = old_eager + end + + def eager_load! + @_autoloads.each_value { |file| require file } + end + + def autoloads + @_autoloads + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies/interlock.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies/interlock.rb new file mode 100644 index 0000000..e0e32e8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies/interlock.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require "active_support/concurrency/share_lock" + +module ActiveSupport # :nodoc: + module Dependencies # :nodoc: + class Interlock + def initialize # :nodoc: + @lock = ActiveSupport::Concurrency::ShareLock.new + end + + def loading(&block) + @lock.exclusive(purpose: :load, compatible: [:load], after_compatible: [:load], &block) + end + + def unloading(&block) + @lock.exclusive(purpose: :unload, compatible: [:load, :unload], after_compatible: [:load, :unload], &block) + end + + def start_unloading + @lock.start_exclusive(purpose: :unload, compatible: [:load, :unload]) + end + + def done_unloading + @lock.stop_exclusive(compatible: [:load, :unload]) + end + + def start_running + @lock.start_sharing + end + + def done_running + @lock.stop_sharing + end + + def running(&block) + @lock.sharing(&block) + end + + def permit_concurrent_loads(&block) + @lock.yield_shares(compatible: [:load], &block) + end + + def raw_state(&block) # :nodoc: + @lock.raw_state(&block) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies/require_dependency.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies/require_dependency.rb new file mode 100644 index 0000000..403f5fa --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/dependencies/require_dependency.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +module ActiveSupport::Dependencies::RequireDependency + # Warning: This method is obsolete. The semantics of the autoloader + # match Ruby's and you do not need to be defensive with load order anymore. + # Just refer to classes and modules normally. + # + # Engines that do not control the mode in which their parent application runs + # should call +require_dependency+ where needed in case the runtime mode is + # +:classic+. + def require_dependency(filename) + filename = filename.to_path if filename.respond_to?(:to_path) + + unless filename.is_a?(String) + raise ArgumentError, "the file name must be either a String or implement #to_path -- you passed #{filename.inspect}" + end + + if abspath = ActiveSupport::Dependencies.search_for_file(filename) + require abspath + else + require filename + end + end + + # We could define require_dependency in Object directly, but a module makes + # the extension apparent if you list ancestors. + Object.prepend(self) +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation.rb new file mode 100644 index 0000000..a9bc3a0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require "singleton" + +module ActiveSupport + # \Deprecation specifies the API used by Rails to deprecate methods, instance + # variables, objects and constants. + class Deprecation + # active_support.rb sets an autoload for ActiveSupport::Deprecation. + # + # If these requires were at the top of the file the constant would not be + # defined by the time their files were loaded. Since some of them reopen + # ActiveSupport::Deprecation its autoload would be triggered, resulting in + # a circular require warning for active_support/deprecation.rb. + # + # So, we define the constant first, and load dependencies later. + require "active_support/deprecation/instance_delegator" + require "active_support/deprecation/behaviors" + require "active_support/deprecation/reporting" + require "active_support/deprecation/disallowed" + require "active_support/deprecation/constant_accessor" + require "active_support/deprecation/method_wrappers" + require "active_support/deprecation/proxy_wrappers" + require "active_support/core_ext/module/deprecation" + require "concurrent/atomic/thread_local_var" + + include Singleton + include InstanceDelegator + include Behavior + include Reporting + include Disallowed + include MethodWrapper + + # The version number in which the deprecated behavior will be removed, by default. + attr_accessor :deprecation_horizon + + # It accepts two parameters on initialization. The first is a version of library + # and the second is a library name. + # + # ActiveSupport::Deprecation.new('2.0', 'MyLibrary') + def initialize(deprecation_horizon = "7.1", gem_name = "Rails") + self.gem_name = gem_name + self.deprecation_horizon = deprecation_horizon + # By default, warnings are not silenced and debugging is off. + self.silenced = false + self.debug = false + @silenced_thread = Concurrent::ThreadLocalVar.new(false) + @explicitly_allowed_warnings = Concurrent::ThreadLocalVar.new(nil) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/behaviors.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/behaviors.rb new file mode 100644 index 0000000..80a6970 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/behaviors.rb @@ -0,0 +1,125 @@ +# frozen_string_literal: true + +require "active_support/notifications" + +module ActiveSupport + # Raised when ActiveSupport::Deprecation::Behavior#behavior is set with :raise. + # You would set :raise, as a behavior to raise errors and proactively report exceptions from deprecations. + class DeprecationException < StandardError + end + + class Deprecation + # Default warning behaviors per Rails.env. + DEFAULT_BEHAVIORS = { + raise: ->(message, callstack, deprecation_horizon, gem_name) { + e = DeprecationException.new(message) + e.set_backtrace(callstack.map(&:to_s)) + raise e + }, + + stderr: ->(message, callstack, deprecation_horizon, gem_name) { + $stderr.puts(message) + $stderr.puts callstack.join("\n ") if debug + }, + + log: ->(message, callstack, deprecation_horizon, gem_name) { + logger = + if defined?(Rails.logger) && Rails.logger + Rails.logger + else + require "active_support/logger" + ActiveSupport::Logger.new($stderr) + end + logger.warn message + logger.debug callstack.join("\n ") if debug + }, + + notify: ->(message, callstack, deprecation_horizon, gem_name) { + notification_name = "deprecation.#{gem_name.underscore.tr('/', '_')}" + ActiveSupport::Notifications.instrument(notification_name, + message: message, + callstack: callstack, + gem_name: gem_name, + deprecation_horizon: deprecation_horizon) + }, + + silence: ->(message, callstack, deprecation_horizon, gem_name) { }, + } + + # Behavior module allows to determine how to display deprecation messages. + # You can create a custom behavior or set any from the +DEFAULT_BEHAVIORS+ + # constant. Available behaviors are: + # + # [+raise+] Raise ActiveSupport::DeprecationException. + # [+stderr+] Log all deprecation warnings to $stderr. + # [+log+] Log all deprecation warnings to +Rails.logger+. + # [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+. + # [+silence+] Do nothing. On Rails, set config.active_support.report_deprecations = false to disable all behaviors. + # + # Setting behaviors only affects deprecations that happen after boot time. + # For more information you can read the documentation of the +behavior=+ method. + module Behavior + # Whether to print a backtrace along with the warning. + attr_accessor :debug + + # Returns the current behavior or if one isn't set, defaults to +:stderr+. + def behavior + @behavior ||= [DEFAULT_BEHAVIORS[:stderr]] + end + + # Returns the current behavior for disallowed deprecations or if one isn't set, defaults to +:raise+. + def disallowed_behavior + @disallowed_behavior ||= [DEFAULT_BEHAVIORS[:raise]] + end + + # Sets the behavior to the specified value. Can be a single value, array, + # or an object that responds to +call+. + # + # Available behaviors: + # + # [+raise+] Raise ActiveSupport::DeprecationException. + # [+stderr+] Log all deprecation warnings to $stderr. + # [+log+] Log all deprecation warnings to +Rails.logger+. + # [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+. + # [+silence+] Do nothing. + # + # Setting behaviors only affects deprecations that happen after boot time. + # Deprecation warnings raised by gems are not affected by this setting + # because they happen before Rails boots up. + # + # ActiveSupport::Deprecation.behavior = :stderr + # ActiveSupport::Deprecation.behavior = [:stderr, :log] + # ActiveSupport::Deprecation.behavior = MyCustomHandler + # ActiveSupport::Deprecation.behavior = ->(message, callstack, deprecation_horizon, gem_name) { + # # custom stuff + # } + # + # If you are using Rails, you can set config.active_support.report_deprecations = false to disable + # all deprecation behaviors. This is similar to the +silence+ option but more performant. + def behavior=(behavior) + @behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || arity_coerce(b) } + end + + # Sets the behavior for disallowed deprecations (those configured by + # ActiveSupport::Deprecation.disallowed_warnings=) to the specified + # value. As with +behavior=+, this can be a single value, array, or an + # object that responds to +call+. + def disallowed_behavior=(behavior) + @disallowed_behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || arity_coerce(b) } + end + + private + def arity_coerce(behavior) + unless behavior.respond_to?(:call) + raise ArgumentError, "#{behavior.inspect} is not a valid deprecation behavior." + end + + if behavior.arity == 4 || behavior.arity == -1 + behavior + else + -> message, callstack, _, _ { behavior.call(message, callstack) } + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/constant_accessor.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/constant_accessor.rb new file mode 100644 index 0000000..1ed0015 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/constant_accessor.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true + +module ActiveSupport + class Deprecation + # DeprecatedConstantAccessor transforms a constant into a deprecated one by + # hooking +const_missing+. + # + # It takes the names of an old (deprecated) constant and of a new constant + # (both in string form) and optionally a deprecator. The deprecator defaults + # to +ActiveSupport::Deprecator+ if none is specified. + # + # The deprecated constant now returns the same object as the new one rather + # than a proxy object, so it can be used transparently in +rescue+ blocks + # etc. + # + # PLANETS = %w(mercury venus earth mars jupiter saturn uranus neptune pluto) + # + # # (In a later update, the original implementation of `PLANETS` has been removed.) + # + # PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune) + # include ActiveSupport::Deprecation::DeprecatedConstantAccessor + # deprecate_constant 'PLANETS', 'PLANETS_POST_2006' + # + # PLANETS.map { |planet| planet.capitalize } + # # => DEPRECATION WARNING: PLANETS is deprecated! Use PLANETS_POST_2006 instead. + # (Backtrace information…) + # ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"] + module DeprecatedConstantAccessor + def self.included(base) + require "active_support/inflector/methods" + + extension = Module.new do + def const_missing(missing_const_name) + if class_variable_defined?(:@@_deprecated_constants) + if (replacement = class_variable_get(:@@_deprecated_constants)[missing_const_name.to_s]) + replacement[:deprecator].warn(replacement[:message] || "#{name}::#{missing_const_name} is deprecated! Use #{replacement[:new]} instead.", caller_locations) + return ActiveSupport::Inflector.constantize(replacement[:new].to_s) + end + end + super + end + + def deprecate_constant(const_name, new_constant, message: nil, deprecator: ActiveSupport::Deprecation.instance) + class_variable_set(:@@_deprecated_constants, {}) unless class_variable_defined?(:@@_deprecated_constants) + class_variable_get(:@@_deprecated_constants)[const_name.to_s] = { new: new_constant, message: message, deprecator: deprecator } + end + end + base.singleton_class.prepend extension + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/disallowed.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/disallowed.rb new file mode 100644 index 0000000..096ecaa --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/disallowed.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +module ActiveSupport + class Deprecation + module Disallowed + # Sets the criteria used to identify deprecation messages which should be + # disallowed. Can be an array containing strings, symbols, or regular + # expressions. (Symbols are treated as strings). These are compared against + # the text of the generated deprecation warning. + # + # Additionally the scalar symbol +:all+ may be used to treat all + # deprecations as disallowed. + # + # Deprecations matching a substring or regular expression will be handled + # using the configured +ActiveSupport::Deprecation.disallowed_behavior+ + # rather than +ActiveSupport::Deprecation.behavior+ + attr_writer :disallowed_warnings + + # Returns the configured criteria used to identify deprecation messages + # which should be treated as disallowed. + def disallowed_warnings + @disallowed_warnings ||= [] + end + + private + def deprecation_disallowed?(message) + disallowed = ActiveSupport::Deprecation.disallowed_warnings + return false if explicitly_allowed?(message) + return true if disallowed == :all + disallowed.any? do |rule| + case rule + when String, Symbol + message.include?(rule.to_s) + when Regexp + rule.match?(message) + end + end + end + + def explicitly_allowed?(message) + allowances = @explicitly_allowed_warnings.value + return false unless allowances + return true if allowances == :all + allowances = [allowances] unless allowances.kind_of?(Array) + allowances.any? do |rule| + case rule + when String, Symbol + message.include?(rule.to_s) + when Regexp + rule.match?(message) + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/instance_delegator.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/instance_delegator.rb new file mode 100644 index 0000000..59dd30a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/instance_delegator.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/delegation" + +module ActiveSupport + class Deprecation + module InstanceDelegator # :nodoc: + def self.included(base) + base.extend(ClassMethods) + base.singleton_class.prepend(OverrideDelegators) + base.public_class_method :new + end + + module ClassMethods # :nodoc: + def include(included_module) + included_module.instance_methods.each { |m| method_added(m) } + super + end + + def method_added(method_name) + singleton_class.delegate(method_name, to: :instance) + end + end + + module OverrideDelegators # :nodoc: + def warn(message = nil, callstack = nil) + callstack ||= caller_locations(2) + super + end + + def deprecation_warning(deprecated_method_name, message = nil, caller_backtrace = nil) + caller_backtrace ||= caller_locations(2) + super + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/method_wrappers.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/method_wrappers.rb new file mode 100644 index 0000000..5437598 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/method_wrappers.rb @@ -0,0 +1,85 @@ +# frozen_string_literal: true + +require "active_support/core_ext/array/extract_options" +require "active_support/core_ext/module/redefine_method" + +module ActiveSupport + class Deprecation + module MethodWrapper + # Declare that a method has been deprecated. + # + # class Fred + # def aaa; end + # def bbb; end + # def ccc; end + # def ddd; end + # def eee; end + # end + # + # Using the default deprecator: + # ActiveSupport::Deprecation.deprecate_methods(Fred, :aaa, bbb: :zzz, ccc: 'use Bar#ccc instead') + # # => Fred + # + # Fred.new.aaa + # # DEPRECATION WARNING: aaa is deprecated and will be removed from Rails 5.1. (called from irb_binding at (irb):10) + # # => nil + # + # Fred.new.bbb + # # DEPRECATION WARNING: bbb is deprecated and will be removed from Rails 5.1 (use zzz instead). (called from irb_binding at (irb):11) + # # => nil + # + # Fred.new.ccc + # # DEPRECATION WARNING: ccc is deprecated and will be removed from Rails 5.1 (use Bar#ccc instead). (called from irb_binding at (irb):12) + # # => nil + # + # Passing in a custom deprecator: + # custom_deprecator = ActiveSupport::Deprecation.new('next-release', 'MyGem') + # ActiveSupport::Deprecation.deprecate_methods(Fred, ddd: :zzz, deprecator: custom_deprecator) + # # => [:ddd] + # + # Fred.new.ddd + # DEPRECATION WARNING: ddd is deprecated and will be removed from MyGem next-release (use zzz instead). (called from irb_binding at (irb):15) + # # => nil + # + # Using a custom deprecator directly: + # custom_deprecator = ActiveSupport::Deprecation.new('next-release', 'MyGem') + # custom_deprecator.deprecate_methods(Fred, eee: :zzz) + # # => [:eee] + # + # Fred.new.eee + # DEPRECATION WARNING: eee is deprecated and will be removed from MyGem next-release (use zzz instead). (called from irb_binding at (irb):18) + # # => nil + def deprecate_methods(target_module, *method_names) + options = method_names.extract_options! + deprecator = options.delete(:deprecator) || self + method_names += options.keys + mod = nil + + method_names.each do |method_name| + message = options[method_name] + if target_module.method_defined?(method_name) || target_module.private_method_defined?(method_name) + method = target_module.instance_method(method_name) + target_module.module_eval do + redefine_method(method_name) do |*args, &block| + deprecator.deprecation_warning(method_name, message) + method.bind_call(self, *args, &block) + end + ruby2_keywords(method_name) + end + else + mod ||= Module.new + mod.module_eval do + define_method(method_name) do |*args, &block| + deprecator.deprecation_warning(method_name, message) + super(*args, &block) + end + ruby2_keywords(method_name) + end + end + end + + target_module.prepend(mod) if mod + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/proxy_wrappers.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/proxy_wrappers.rb new file mode 100644 index 0000000..615376d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/proxy_wrappers.rb @@ -0,0 +1,177 @@ +# frozen_string_literal: true + +module ActiveSupport + class Deprecation + class DeprecationProxy # :nodoc: + def self.new(*args, &block) + object = args.first + + return object unless object + super + end + + instance_methods.each { |m| undef_method m unless /^__|^object_id$/.match?(m) } + + # Don't give a deprecation warning on inspect since test/unit and error + # logs rely on it for diagnostics. + def inspect + target.inspect + end + + private + def method_missing(called, *args, &block) + warn caller_locations, called, args + target.__send__(called, *args, &block) + end + end + + # DeprecatedObjectProxy transforms an object into a deprecated one. It + # takes an object, a deprecation message and optionally a deprecator. The + # deprecator defaults to +ActiveSupport::Deprecator+ if none is specified. + # + # deprecated_object = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(Object.new, "This object is now deprecated") + # # => # + # + # deprecated_object.to_s + # DEPRECATION WARNING: This object is now deprecated. + # (Backtrace) + # # => "#" + class DeprecatedObjectProxy < DeprecationProxy + def initialize(object, message, deprecator = ActiveSupport::Deprecation.instance) + @object = object + @message = message + @deprecator = deprecator + end + + private + def target + @object + end + + def warn(callstack, called, args) + @deprecator.warn(@message, callstack) + end + end + + # DeprecatedInstanceVariableProxy transforms an instance variable into a + # deprecated one. It takes an instance of a class, a method on that class + # and an instance variable. It optionally takes a deprecator as the last + # argument. The deprecator defaults to +ActiveSupport::Deprecator+ if none + # is specified. + # + # class Example + # def initialize + # @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request, :@request) + # @_request = :special_request + # end + # + # def request + # @_request + # end + # + # def old_request + # @request + # end + # end + # + # example = Example.new + # # => # + # + # example.old_request.to_s + # # => DEPRECATION WARNING: @request is deprecated! Call request.to_s instead of + # @request.to_s + # (Backtrace information…) + # "special_request" + # + # example.request.to_s + # # => "special_request" + class DeprecatedInstanceVariableProxy < DeprecationProxy + def initialize(instance, method, var = "@#{method}", deprecator = ActiveSupport::Deprecation.instance) + @instance = instance + @method = method + @var = var + @deprecator = deprecator + end + + private + def target + @instance.__send__(@method) + end + + def warn(callstack, called, args) + @deprecator.warn("#{@var} is deprecated! Call #{@method}.#{called} instead of #{@var}.#{called}. Args: #{args.inspect}", callstack) + end + end + + # DeprecatedConstantProxy transforms a constant into a deprecated one. It + # takes the names of an old (deprecated) constant and of a new constant + # (both in string form) and optionally a deprecator. The deprecator defaults + # to +ActiveSupport::Deprecator+ if none is specified. The deprecated constant + # now returns the value of the new one. + # + # PLANETS = %w(mercury venus earth mars jupiter saturn uranus neptune pluto) + # + # # (In a later update, the original implementation of `PLANETS` has been removed.) + # + # PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune) + # PLANETS = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('PLANETS', 'PLANETS_POST_2006') + # + # PLANETS.map { |planet| planet.capitalize } + # # => DEPRECATION WARNING: PLANETS is deprecated! Use PLANETS_POST_2006 instead. + # (Backtrace information…) + # ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"] + class DeprecatedConstantProxy < Module + def self.new(*args, **options, &block) + object = args.first + + return object unless object + super + end + + def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance, message: "#{old_const} is deprecated! Use #{new_const} instead.") + Kernel.require "active_support/inflector/methods" + + @old_const = old_const + @new_const = new_const + @deprecator = deprecator + @message = message + end + + instance_methods.each { |m| undef_method m unless /^__|^object_id$/.match?(m) } + + # Don't give a deprecation warning on inspect since test/unit and error + # logs rely on it for diagnostics. + def inspect + target.inspect + end + + # Don't give a deprecation warning on methods that IRB may invoke + # during tab-completion. + delegate :hash, :instance_methods, :name, :respond_to?, to: :target + + # Returns the class of the new constant. + # + # PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune) + # PLANETS = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('PLANETS', 'PLANETS_POST_2006') + # PLANETS.class # => Array + def class + target.class + end + + private + def target + ActiveSupport::Inflector.constantize(@new_const.to_s) + end + + def const_missing(name) + @deprecator.warn(@message, caller_locations) + target.const_get(name) + end + + def method_missing(called, *args, &block) + @deprecator.warn(@message, caller_locations) + target.__send__(called, *args, &block) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/reporting.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/reporting.rb new file mode 100644 index 0000000..51514eb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/deprecation/reporting.rb @@ -0,0 +1,157 @@ +# frozen_string_literal: true + +require "rbconfig" + +module ActiveSupport + class Deprecation + module Reporting + # Whether to print a message (silent mode) + attr_writer :silenced + # Name of gem where method is deprecated + attr_accessor :gem_name + + # Outputs a deprecation warning to the output configured by + # ActiveSupport::Deprecation.behavior. + # + # ActiveSupport::Deprecation.warn('something broke!') + # # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)" + def warn(message = nil, callstack = nil) + return if silenced + + callstack ||= caller_locations(2) + deprecation_message(callstack, message).tap do |m| + if deprecation_disallowed?(message) + disallowed_behavior.each { |b| b.call(m, callstack, deprecation_horizon, gem_name) } + else + behavior.each { |b| b.call(m, callstack, deprecation_horizon, gem_name) } + end + end + end + + # Silence deprecation warnings within the block. + # + # ActiveSupport::Deprecation.warn('something broke!') + # # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)" + # + # ActiveSupport::Deprecation.silence do + # ActiveSupport::Deprecation.warn('something broke!') + # end + # # => nil + def silence(&block) + @silenced_thread.bind(true, &block) + end + + # Allow previously disallowed deprecation warnings within the block. + # allowed_warnings can be an array containing strings, symbols, or regular + # expressions. (Symbols are treated as strings). These are compared against + # the text of deprecation warning messages generated within the block. + # Matching warnings will be exempt from the rules set by + # +ActiveSupport::Deprecation.disallowed_warnings+ + # + # The optional if: argument accepts a truthy/falsy value or an object that + # responds to .call. If truthy, then matching warnings will be allowed. + # If falsey then the method yields to the block without allowing the warning. + # + # ActiveSupport::Deprecation.disallowed_behavior = :raise + # ActiveSupport::Deprecation.disallowed_warnings = [ + # "something broke" + # ] + # + # ActiveSupport::Deprecation.warn('something broke!') + # # => ActiveSupport::DeprecationException + # + # ActiveSupport::Deprecation.allow ['something broke'] do + # ActiveSupport::Deprecation.warn('something broke!') + # end + # # => nil + # + # ActiveSupport::Deprecation.allow ['something broke'], if: Rails.env.production? do + # ActiveSupport::Deprecation.warn('something broke!') + # end + # # => ActiveSupport::DeprecationException for dev/test, nil for production + def allow(allowed_warnings = :all, if: true, &block) + conditional = binding.local_variable_get(:if) + conditional = conditional.call if conditional.respond_to?(:call) + if conditional + @explicitly_allowed_warnings.bind(allowed_warnings, &block) + else + yield + end + end + + def silenced + @silenced || @silenced_thread.value + end + + def deprecation_warning(deprecated_method_name, message = nil, caller_backtrace = nil) + caller_backtrace ||= caller_locations(2) + deprecated_method_warning(deprecated_method_name, message).tap do |msg| + warn(msg, caller_backtrace) + end + end + + private + # Outputs a deprecation warning message + # + # deprecated_method_warning(:method_name) + # # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon}" + # deprecated_method_warning(:method_name, :another_method) + # # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (use another_method instead)" + # deprecated_method_warning(:method_name, "Optional message") + # # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (Optional message)" + def deprecated_method_warning(method_name, message = nil) + warning = "#{method_name} is deprecated and will be removed from #{gem_name} #{deprecation_horizon}" + case message + when Symbol then "#{warning} (use #{message} instead)" + when String then "#{warning} (#{message})" + else warning + end + end + + def deprecation_message(callstack, message = nil) + message ||= "You are using deprecated behavior which will be removed from the next major or minor release." + "DEPRECATION WARNING: #{message} #{deprecation_caller_message(callstack)}" + end + + def deprecation_caller_message(callstack) + file, line, method = extract_callstack(callstack) + if file + if line && method + "(called from #{method} at #{file}:#{line})" + else + "(called from #{file}:#{line})" + end + end + end + + def extract_callstack(callstack) + return _extract_callstack(callstack) if callstack.first.is_a? String + + offending_line = callstack.find { |frame| + frame.absolute_path && !ignored_callstack(frame.absolute_path) + } || callstack.first + + [offending_line.path, offending_line.lineno, offending_line.label] + end + + def _extract_callstack(callstack) + warn "Please pass `caller_locations` to the deprecation API" if $VERBOSE + offending_line = callstack.find { |line| !ignored_callstack(line) } || callstack.first + + if offending_line + if md = offending_line.match(/^(.+?):(\d+)(?::in `(.*?)')?/) + md.captures + else + offending_line + end + end + end + + RAILS_GEM_ROOT = File.expand_path("../../../..", __dir__) + "/" + + def ignored_callstack(path) + path.start_with?(RAILS_GEM_ROOT) || path.start_with?(RbConfig::CONFIG["rubylibdir"]) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/descendants_tracker.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/descendants_tracker.rb new file mode 100644 index 0000000..ea3ed1f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/descendants_tracker.rb @@ -0,0 +1,218 @@ +# frozen_string_literal: true + +require "weakref" +require "active_support/ruby_features" + +module ActiveSupport + # This module provides an internal implementation to track descendants + # which is faster than iterating through ObjectSpace. + module DescendantsTracker + class << self + def direct_descendants(klass) + ActiveSupport::Deprecation.warn(<<~MSG) + ActiveSupport::DescendantsTracker.direct_descendants is deprecated and will be removed in Rails 7.1. + Use ActiveSupport::DescendantsTracker.subclasses instead. + MSG + subclasses(klass) + end + end + + @clear_disabled = false + + if RubyFeatures::CLASS_SUBCLASSES + @@excluded_descendants = if RUBY_ENGINE == "ruby" + # On MRI `ObjectSpace::WeakMap` keys are weak references. + # So we can simply use WeakMap as a `Set`. + ObjectSpace::WeakMap.new + else + # On TruffleRuby `ObjectSpace::WeakMap` keys are strong references. + # So we use `object_id` as a key and the actual object as a value. + # + # JRuby for now doesn't have Class#descendant, but when it will, it will likely + # have the same WeakMap semantic than Truffle so we future proof this as much as possible. + class WeakSet # :nodoc: + def initialize + @map = ObjectSpace::WeakMap.new + end + + def [](object) + @map.key?(object.object_id) + end + + def []=(object, _present) + @map[object.object_id] = object + end + end + WeakSet.new + end + + class << self + def disable_clear! # :nodoc: + unless @clear_disabled + @clear_disabled = true + remove_method(:subclasses) + @@excluded_descendants = nil + end + end + + def subclasses(klass) + klass.subclasses + end + + def descendants(klass) + klass.descendants + end + + def clear(classes) # :nodoc: + raise "DescendantsTracker.clear was disabled because config.cache_classes = true" if @clear_disabled + + classes.each do |klass| + @@excluded_descendants[klass] = true + klass.descendants.each do |descendant| + @@excluded_descendants[descendant] = true + end + end + end + + def native? # :nodoc: + true + end + end + + def subclasses + subclasses = super + subclasses.reject! { |d| @@excluded_descendants[d] } + subclasses + end + + def descendants + subclasses.concat(subclasses.flat_map(&:descendants)) + end + + def direct_descendants + ActiveSupport::Deprecation.warn(<<~MSG) + ActiveSupport::DescendantsTracker#direct_descendants is deprecated and will be removed in Rails 7.1. + Use #subclasses instead. + MSG + subclasses + end + else + @@direct_descendants = {} + + class << self + def disable_clear! # :nodoc: + @clear_disabled = true + end + + def subclasses(klass) + descendants = @@direct_descendants[klass] + descendants ? descendants.to_a : [] + end + + def descendants(klass) + arr = [] + accumulate_descendants(klass, arr) + arr + end + + def clear(classes) # :nodoc: + raise "DescendantsTracker.clear was disabled because config.cache_classes = true" if @clear_disabled + + @@direct_descendants.each do |klass, direct_descendants_of_klass| + if classes.member?(klass) + @@direct_descendants.delete(klass) + else + direct_descendants_of_klass.reject! do |direct_descendant_of_class| + classes.member?(direct_descendant_of_class) + end + end + end + end + + def native? # :nodoc: + false + end + + # This is the only method that is not thread safe, but is only ever called + # during the eager loading phase. + def store_inherited(klass, descendant) + (@@direct_descendants[klass] ||= DescendantsArray.new) << descendant + end + + private + def accumulate_descendants(klass, acc) + if direct_descendants = @@direct_descendants[klass] + direct_descendants.each do |direct_descendant| + acc << direct_descendant + accumulate_descendants(direct_descendant, acc) + end + end + end + end + + def inherited(base) + DescendantsTracker.store_inherited(self, base) + super + end + + def direct_descendants + ActiveSupport::Deprecation.warn(<<~MSG) + ActiveSupport::DescendantsTracker#direct_descendants is deprecated and will be removed in Rails 7.1. + Use #subclasses instead. + MSG + DescendantsTracker.subclasses(self) + end + + def subclasses + DescendantsTracker.subclasses(self) + end + + def descendants + DescendantsTracker.descendants(self) + end + + # DescendantsArray is an array that contains weak references to classes. + class DescendantsArray # :nodoc: + include Enumerable + + def initialize + @refs = [] + end + + def initialize_copy(orig) + @refs = @refs.dup + end + + def <<(klass) + @refs << WeakRef.new(klass) + end + + def each + @refs.reject! do |ref| + yield ref.__getobj__ + false + rescue WeakRef::RefError + true + end + self + end + + def refs_size + @refs.size + end + + def cleanup! + @refs.delete_if { |ref| !ref.weakref_alive? } + end + + def reject! + @refs.reject! do |ref| + yield ref.__getobj__ + rescue WeakRef::RefError + true + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/digest.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/digest.rb new file mode 100644 index 0000000..a3d27be --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/digest.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +require "openssl" + +module ActiveSupport + class Digest # :nodoc: + class << self + def hash_digest_class + @hash_digest_class ||= OpenSSL::Digest::MD5 + end + + def hash_digest_class=(klass) + raise ArgumentError, "#{klass} is expected to implement hexdigest class method" unless klass.respond_to?(:hexdigest) + @hash_digest_class = klass + end + + def hexdigest(arg) + hash_digest_class.hexdigest(arg)[0...32] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/duration.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/duration.rb new file mode 100644 index 0000000..19986d1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/duration.rb @@ -0,0 +1,514 @@ +# frozen_string_literal: true + +require "active_support/core_ext/array/conversions" +require "active_support/core_ext/module/delegation" +require "active_support/core_ext/object/acts_like" +require "active_support/core_ext/string/filters" + +module ActiveSupport + # Provides accurate date and time measurements using Date#advance and + # Time#advance, respectively. It mainly supports the methods on Numeric. + # + # 1.month.ago # equivalent to Time.now.advance(months: -1) + class Duration + class Scalar < Numeric # :nodoc: + attr_reader :value + delegate :to_i, :to_f, :to_s, to: :value + + def initialize(value) + @value = value + end + + def coerce(other) + [Scalar.new(other), self] + end + + def -@ + Scalar.new(-value) + end + + def <=>(other) + if Scalar === other || Duration === other + value <=> other.value + elsif Numeric === other + value <=> other + else + nil + end + end + + def +(other) + if Duration === other + seconds = value + other._parts.fetch(:seconds, 0) + new_parts = other._parts.merge(seconds: seconds) + new_value = value + other.value + + Duration.new(new_value, new_parts, other.variable?) + else + calculate(:+, other) + end + end + + def -(other) + if Duration === other + seconds = value - other._parts.fetch(:seconds, 0) + new_parts = other._parts.transform_values(&:-@) + new_parts = new_parts.merge(seconds: seconds) + new_value = value - other.value + + Duration.new(new_value, new_parts, other.variable?) + else + calculate(:-, other) + end + end + + def *(other) + if Duration === other + new_parts = other._parts.transform_values { |other_value| value * other_value } + new_value = value * other.value + + Duration.new(new_value, new_parts, other.variable?) + else + calculate(:*, other) + end + end + + def /(other) + if Duration === other + value / other.value + else + calculate(:/, other) + end + end + + def %(other) + if Duration === other + Duration.build(value % other.value) + else + calculate(:%, other) + end + end + + def variable? # :nodoc: + false + end + + private + def calculate(op, other) + if Scalar === other + Scalar.new(value.public_send(op, other.value)) + elsif Numeric === other + Scalar.new(value.public_send(op, other)) + else + raise_type_error(other) + end + end + + def raise_type_error(other) + raise TypeError, "no implicit conversion of #{other.class} into #{self.class}" + end + end + + SECONDS_PER_MINUTE = 60 + SECONDS_PER_HOUR = 3600 + SECONDS_PER_DAY = 86400 + SECONDS_PER_WEEK = 604800 + SECONDS_PER_MONTH = 2629746 # 1/12 of a gregorian year + SECONDS_PER_YEAR = 31556952 # length of a gregorian year (365.2425 days) + + PARTS_IN_SECONDS = { + seconds: 1, + minutes: SECONDS_PER_MINUTE, + hours: SECONDS_PER_HOUR, + days: SECONDS_PER_DAY, + weeks: SECONDS_PER_WEEK, + months: SECONDS_PER_MONTH, + years: SECONDS_PER_YEAR + }.freeze + + PARTS = [:years, :months, :weeks, :days, :hours, :minutes, :seconds].freeze + VARIABLE_PARTS = [:years, :months, :weeks, :days].freeze + + attr_reader :value + + autoload :ISO8601Parser, "active_support/duration/iso8601_parser" + autoload :ISO8601Serializer, "active_support/duration/iso8601_serializer" + + class << self + # Creates a new Duration from string formatted according to ISO 8601 Duration. + # + # See {ISO 8601}[https://en.wikipedia.org/wiki/ISO_8601#Durations] for more information. + # This method allows negative parts to be present in pattern. + # If invalid string is provided, it will raise +ActiveSupport::Duration::ISO8601Parser::ParsingError+. + def parse(iso8601duration) + parts = ISO8601Parser.new(iso8601duration).parse! + new(calculate_total_seconds(parts), parts) + end + + def ===(other) # :nodoc: + other.is_a?(Duration) + rescue ::NoMethodError + false + end + + def seconds(value) # :nodoc: + new(value, { seconds: value }, false) + end + + def minutes(value) # :nodoc: + new(value * SECONDS_PER_MINUTE, { minutes: value }, false) + end + + def hours(value) # :nodoc: + new(value * SECONDS_PER_HOUR, { hours: value }, false) + end + + def days(value) # :nodoc: + new(value * SECONDS_PER_DAY, { days: value }, true) + end + + def weeks(value) # :nodoc: + new(value * SECONDS_PER_WEEK, { weeks: value }, true) + end + + def months(value) # :nodoc: + new(value * SECONDS_PER_MONTH, { months: value }, true) + end + + def years(value) # :nodoc: + new(value * SECONDS_PER_YEAR, { years: value }, true) + end + + # Creates a new Duration from a seconds value that is converted + # to the individual parts: + # + # ActiveSupport::Duration.build(31556952).parts # => {:years=>1} + # ActiveSupport::Duration.build(2716146).parts # => {:months=>1, :days=>1} + # + def build(value) + unless value.is_a?(::Numeric) + raise TypeError, "can't build an #{self.name} from a #{value.class.name}" + end + + parts = {} + remainder_sign = value <=> 0 + remainder = value.round(9).abs + variable = false + + PARTS.each do |part| + unless part == :seconds + part_in_seconds = PARTS_IN_SECONDS[part] + parts[part] = remainder.div(part_in_seconds) * remainder_sign + remainder %= part_in_seconds + + unless parts[part].zero? + variable ||= VARIABLE_PARTS.include?(part) + end + end + end unless value == 0 + + parts[:seconds] = remainder * remainder_sign + + new(value, parts, variable) + end + + private + def calculate_total_seconds(parts) + parts.inject(0) do |total, (part, value)| + total + value * PARTS_IN_SECONDS[part] + end + end + end + + def initialize(value, parts, variable = nil) # :nodoc: + @value, @parts = value, parts + @parts.reject! { |k, v| v.zero? } unless value == 0 + @parts.freeze + @variable = variable + + if @variable.nil? + @variable = @parts.any? { |part, _| VARIABLE_PARTS.include?(part) } + end + end + + # Returns a copy of the parts hash that defines the duration + def parts + @parts.dup + end + + def coerce(other) # :nodoc: + case other + when Scalar + [other, self] + when Duration + [Scalar.new(other.value), self] + else + [Scalar.new(other), self] + end + end + + # Compares one Duration with another or a Numeric to this Duration. + # Numeric values are treated as seconds. + def <=>(other) + if Duration === other + value <=> other.value + elsif Numeric === other + value <=> other + end + end + + # Adds another Duration or a Numeric to this Duration. Numeric values + # are treated as seconds. + def +(other) + if Duration === other + parts = @parts.merge(other._parts) do |_key, value, other_value| + value + other_value + end + Duration.new(value + other.value, parts, @variable || other.variable?) + else + seconds = @parts.fetch(:seconds, 0) + other + Duration.new(value + other, @parts.merge(seconds: seconds), @variable) + end + end + + # Subtracts another Duration or a Numeric from this Duration. Numeric + # values are treated as seconds. + def -(other) + self + (-other) + end + + # Multiplies this Duration by a Numeric and returns a new Duration. + def *(other) + if Scalar === other || Duration === other + Duration.new(value * other.value, @parts.transform_values { |number| number * other.value }, @variable || other.variable?) + elsif Numeric === other + Duration.new(value * other, @parts.transform_values { |number| number * other }, @variable) + else + raise_type_error(other) + end + end + + # Divides this Duration by a Numeric and returns a new Duration. + def /(other) + if Scalar === other + Duration.new(value / other.value, @parts.transform_values { |number| number / other.value }, @variable) + elsif Duration === other + value / other.value + elsif Numeric === other + Duration.new(value / other, @parts.transform_values { |number| number / other }, @variable) + else + raise_type_error(other) + end + end + + # Returns the modulo of this Duration by another Duration or Numeric. + # Numeric values are treated as seconds. + def %(other) + if Duration === other || Scalar === other + Duration.build(value % other.value) + elsif Numeric === other + Duration.build(value % other) + else + raise_type_error(other) + end + end + + def -@ # :nodoc: + Duration.new(-value, @parts.transform_values(&:-@), @variable) + end + + def +@ # :nodoc: + self + end + + def is_a?(klass) # :nodoc: + Duration == klass || value.is_a?(klass) + end + alias :kind_of? :is_a? + + def instance_of?(klass) # :nodoc: + Duration == klass || value.instance_of?(klass) + end + + # Returns +true+ if +other+ is also a Duration instance with the + # same +value+, or if other == value. + def ==(other) + if Duration === other + other.value == value + else + other == value + end + end + + # Returns the amount of seconds a duration covers as a string. + # For more information check to_i method. + # + # 1.day.to_s # => "86400" + def to_s + @value.to_s + end + + # Returns the number of seconds that this Duration represents. + # + # 1.minute.to_i # => 60 + # 1.hour.to_i # => 3600 + # 1.day.to_i # => 86400 + # + # Note that this conversion makes some assumptions about the + # duration of some periods, e.g. months are always 1/12 of year + # and years are 365.2425 days: + # + # # equivalent to (1.year / 12).to_i + # 1.month.to_i # => 2629746 + # + # # equivalent to 365.2425.days.to_i + # 1.year.to_i # => 31556952 + # + # In such cases, Ruby's core + # Date[https://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and + # Time[https://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision + # date and time arithmetic. + def to_i + @value.to_i + end + alias :in_seconds :to_i + + # Returns the amount of minutes a duration covers as a float + # + # 1.day.in_minutes # => 1440.0 + def in_minutes + in_seconds / SECONDS_PER_MINUTE.to_f + end + + # Returns the amount of hours a duration covers as a float + # + # 1.day.in_hours # => 24.0 + def in_hours + in_seconds / SECONDS_PER_HOUR.to_f + end + + # Returns the amount of days a duration covers as a float + # + # 12.hours.in_days # => 0.5 + def in_days + in_seconds / SECONDS_PER_DAY.to_f + end + + # Returns the amount of weeks a duration covers as a float + # + # 2.months.in_weeks # => 8.696 + def in_weeks + in_seconds / SECONDS_PER_WEEK.to_f + end + + # Returns the amount of months a duration covers as a float + # + # 9.weeks.in_months # => 2.07 + def in_months + in_seconds / SECONDS_PER_MONTH.to_f + end + + # Returns the amount of years a duration covers as a float + # + # 30.days.in_years # => 0.082 + def in_years + in_seconds / SECONDS_PER_YEAR.to_f + end + + # Returns +true+ if +other+ is also a Duration instance, which has the + # same parts as this one. + def eql?(other) + Duration === other && other.value.eql?(value) + end + + def hash + @value.hash + end + + # Calculates a new Time or Date that is as far in the future + # as this Duration represents. + def since(time = ::Time.current) + sum(1, time) + end + alias :from_now :since + alias :after :since + + # Calculates a new Time or Date that is as far in the past + # as this Duration represents. + def ago(time = ::Time.current) + sum(-1, time) + end + alias :until :ago + alias :before :ago + + def inspect # :nodoc: + return "#{value} seconds" if @parts.empty? + + @parts. + sort_by { |unit, _ | PARTS.index(unit) }. + map { |unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}" }. + to_sentence(locale: false) + end + + def as_json(options = nil) # :nodoc: + to_i + end + + def init_with(coder) # :nodoc: + initialize(coder["value"], coder["parts"]) + end + + def encode_with(coder) # :nodoc: + coder.map = { "value" => @value, "parts" => @parts } + end + + # Build ISO 8601 Duration string for this duration. + # The +precision+ parameter can be used to limit seconds' precision of duration. + def iso8601(precision: nil) + ISO8601Serializer.new(self, precision: precision).serialize + end + + def variable? # :nodoc: + @variable + end + + def _parts # :nodoc: + @parts + end + + private + def sum(sign, time = ::Time.current) + unless time.acts_like?(:time) || time.acts_like?(:date) + raise ::ArgumentError, "expected a time or date, got #{time.inspect}" + end + + if @parts.empty? + time.since(sign * value) + else + @parts.inject(time) do |t, (type, number)| + if type == :seconds + t.since(sign * number) + elsif type == :minutes + t.since(sign * number * 60) + elsif type == :hours + t.since(sign * number * 3600) + else + t.advance(type => sign * number) + end + end + end + end + + def respond_to_missing?(method, _) + value.respond_to?(method) + end + + def method_missing(method, *args, &block) + value.public_send(method, *args, &block) + end + + def raise_type_error(other) + raise TypeError, "no implicit conversion of #{other.class} into #{self.class}" + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/duration/iso8601_parser.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/duration/iso8601_parser.rb new file mode 100644 index 0000000..839caab --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/duration/iso8601_parser.rb @@ -0,0 +1,123 @@ +# frozen_string_literal: true + +require "strscan" + +module ActiveSupport + class Duration + # Parses a string formatted according to ISO 8601 Duration into the hash. + # + # See {ISO 8601}[https://en.wikipedia.org/wiki/ISO_8601#Durations] for more information. + # + # This parser allows negative parts to be present in pattern. + class ISO8601Parser # :nodoc: + class ParsingError < ::ArgumentError; end + + PERIOD_OR_COMMA = /\.|,/ + PERIOD = "." + COMMA = "," + + SIGN_MARKER = /\A-|\+|/ + DATE_MARKER = /P/ + TIME_MARKER = /T/ + DATE_COMPONENT = /(-?\d+(?:[.,]\d+)?)(Y|M|D|W)/ + TIME_COMPONENT = /(-?\d+(?:[.,]\d+)?)(H|M|S)/ + + DATE_TO_PART = { "Y" => :years, "M" => :months, "W" => :weeks, "D" => :days } + TIME_TO_PART = { "H" => :hours, "M" => :minutes, "S" => :seconds } + + DATE_COMPONENTS = [:years, :months, :days] + TIME_COMPONENTS = [:hours, :minutes, :seconds] + + attr_reader :parts, :scanner + attr_accessor :mode, :sign + + def initialize(string) + @scanner = StringScanner.new(string) + @parts = {} + @mode = :start + @sign = 1 + end + + def parse! + while !finished? + case mode + when :start + if scan(SIGN_MARKER) + self.sign = (scanner.matched == "-") ? -1 : 1 + self.mode = :sign + else + raise_parsing_error + end + + when :sign + if scan(DATE_MARKER) + self.mode = :date + else + raise_parsing_error + end + + when :date + if scan(TIME_MARKER) + self.mode = :time + elsif scan(DATE_COMPONENT) + parts[DATE_TO_PART[scanner[2]]] = number * sign + else + raise_parsing_error + end + + when :time + if scan(TIME_COMPONENT) + parts[TIME_TO_PART[scanner[2]]] = number * sign + else + raise_parsing_error + end + + end + end + + validate! + parts + end + + private + def finished? + scanner.eos? + end + + # Parses number which can be a float with either comma or period. + def number + PERIOD_OR_COMMA.match?(scanner[1]) ? scanner[1].tr(COMMA, PERIOD).to_f : scanner[1].to_i + end + + def scan(pattern) + scanner.scan(pattern) + end + + def raise_parsing_error(reason = nil) + raise ParsingError, "Invalid ISO 8601 duration: #{scanner.string.inspect} #{reason}".strip + end + + # Checks for various semantic errors as stated in ISO 8601 standard. + def validate! + raise_parsing_error("is empty duration") if parts.empty? + + # Mixing any of Y, M, D with W is invalid. + if parts.key?(:weeks) && (parts.keys & DATE_COMPONENTS).any? + raise_parsing_error("mixing weeks with other date parts not allowed") + end + + # Specifying an empty T part is invalid. + if mode == :time && (parts.keys & TIME_COMPONENTS).empty? + raise_parsing_error("time part marker is present but time part is empty") + end + + fractions = parts.values.reject(&:zero?).select { |a| (a % 1) != 0 } + unless fractions.empty? || (fractions.size == 1 && fractions.last == @parts.values.reject(&:zero?).last) + raise_parsing_error "(only last part can be fractional)" + end + + true + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/duration/iso8601_serializer.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/duration/iso8601_serializer.rb new file mode 100644 index 0000000..9353c64 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/duration/iso8601_serializer.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/blank" + +module ActiveSupport + class Duration + # Serializes duration to string according to ISO 8601 Duration format. + class ISO8601Serializer # :nodoc: + DATE_COMPONENTS = %i(years months days) + + def initialize(duration, precision: nil) + @duration = duration + @precision = precision + end + + # Builds and returns output string. + def serialize + parts = normalize + return "PT0S" if parts.empty? + + output = +"P" + output << "#{parts[:years]}Y" if parts.key?(:years) + output << "#{parts[:months]}M" if parts.key?(:months) + output << "#{parts[:days]}D" if parts.key?(:days) + output << "#{parts[:weeks]}W" if parts.key?(:weeks) + time = +"" + time << "#{parts[:hours]}H" if parts.key?(:hours) + time << "#{parts[:minutes]}M" if parts.key?(:minutes) + if parts.key?(:seconds) + time << "#{format_seconds(parts[:seconds])}S" + end + output << "T#{time}" unless time.empty? + output + end + + private + # Return pair of duration's parts and whole duration sign. + # Parts are summarized (as they can become repetitive due to addition, etc). + # Zero parts are removed as not significant. + # If all parts are negative it will negate all of them and return minus as a sign. + def normalize + parts = @duration.parts.each_with_object(Hash.new(0)) do |(k, v), p| + p[k] += v unless v.zero? + end + + # Convert weeks to days and remove weeks if mixed with date parts + if week_mixed_with_date?(parts) + parts[:days] += parts.delete(:weeks) * SECONDS_PER_WEEK / SECONDS_PER_DAY + end + + parts + end + + def week_mixed_with_date?(parts) + parts.key?(:weeks) && (parts.keys & DATE_COMPONENTS).any? + end + + def format_seconds(seconds) + if @precision + sprintf("%0.0#{@precision}f", seconds) + else + seconds.to_s + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/encrypted_configuration.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/encrypted_configuration.rb new file mode 100644 index 0000000..3382fe7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/encrypted_configuration.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require "yaml" +require "active_support/encrypted_file" +require "active_support/ordered_options" +require "active_support/core_ext/object/inclusion" +require "active_support/core_ext/module/delegation" + +module ActiveSupport + class EncryptedConfiguration < EncryptedFile + delegate :[], :fetch, to: :config + delegate_missing_to :options + + def initialize(config_path:, key_path:, env_key:, raise_if_missing_key:) + super content_path: config_path, key_path: key_path, + env_key: env_key, raise_if_missing_key: raise_if_missing_key + end + + # Allow a config to be started without a file present + def read + super + rescue ActiveSupport::EncryptedFile::MissingContentError + "" + end + + def write(contents) + deserialize(contents) + + super + end + + def config + @config ||= deserialize(read).deep_symbolize_keys + end + + private + def deep_transform(hash) + return hash unless hash.is_a?(Hash) + + h = ActiveSupport::InheritableOptions.new + hash.each do |k, v| + h[k] = deep_transform(v) + end + h + end + + def options + @options ||= ActiveSupport::InheritableOptions.new(deep_transform(config)) + end + + def deserialize(config) + doc = YAML.respond_to?(:unsafe_load) ? YAML.unsafe_load(config) : YAML.load(config) + doc.presence || {} + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/encrypted_file.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/encrypted_file.rb new file mode 100644 index 0000000..6a6d6c0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/encrypted_file.rb @@ -0,0 +1,117 @@ +# frozen_string_literal: true + +require "pathname" +require "tmpdir" +require "active_support/message_encryptor" + +module ActiveSupport + class EncryptedFile + class MissingContentError < RuntimeError + def initialize(content_path) + super "Missing encrypted content file in #{content_path}." + end + end + + class MissingKeyError < RuntimeError + def initialize(key_path:, env_key:) + super \ + "Missing encryption key to decrypt file with. " + + "Ask your team for your master key and write it to #{key_path} or put it in the ENV['#{env_key}']." + end + end + + class InvalidKeyLengthError < RuntimeError + def initialize + super "Encryption key must be exactly #{EncryptedFile.expected_key_length} characters." + end + end + + CIPHER = "aes-128-gcm" + + def self.generate_key + SecureRandom.hex(ActiveSupport::MessageEncryptor.key_len(CIPHER)) + end + + def self.expected_key_length # :nodoc: + @expected_key_length ||= generate_key.length + end + + + attr_reader :content_path, :key_path, :env_key, :raise_if_missing_key + + def initialize(content_path:, key_path:, env_key:, raise_if_missing_key:) + @content_path = Pathname.new(content_path).yield_self { |path| path.symlink? ? path.realpath : path } + @key_path = Pathname.new(key_path) + @env_key, @raise_if_missing_key = env_key, raise_if_missing_key + end + + def key + read_env_key || read_key_file || handle_missing_key + end + + def read + if !key.nil? && content_path.exist? + decrypt content_path.binread + else + raise MissingContentError, content_path + end + end + + def write(contents) + IO.binwrite "#{content_path}.tmp", encrypt(contents) + FileUtils.mv "#{content_path}.tmp", content_path + end + + def change(&block) + writing read, &block + end + + + private + def writing(contents) + tmp_file = "#{Process.pid}.#{content_path.basename.to_s.chomp('.enc')}" + tmp_path = Pathname.new File.join(Dir.tmpdir, tmp_file) + tmp_path.binwrite contents + + yield tmp_path + + updated_contents = tmp_path.binread + + write(updated_contents) if updated_contents != contents + ensure + FileUtils.rm(tmp_path) if tmp_path&.exist? + end + + + def encrypt(contents) + check_key_length + encryptor.encrypt_and_sign contents + end + + def decrypt(contents) + encryptor.decrypt_and_verify contents + end + + def encryptor + @encryptor ||= ActiveSupport::MessageEncryptor.new([ key ].pack("H*"), cipher: CIPHER) + end + + + def read_env_key + ENV[env_key].presence + end + + def read_key_file + return @key_file_contents if defined?(@key_file_contents) + @key_file_contents = (key_path.binread.strip if key_path.exist?) + end + + def handle_missing_key + raise MissingKeyError.new(key_path: key_path, env_key: env_key) if raise_if_missing_key + end + + def check_key_length + raise InvalidKeyLengthError if key&.length != self.class.expected_key_length + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/environment_inquirer.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/environment_inquirer.rb new file mode 100644 index 0000000..770cddd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/environment_inquirer.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +require "active_support/string_inquirer" + +module ActiveSupport + class EnvironmentInquirer < StringInquirer # :nodoc: + DEFAULT_ENVIRONMENTS = ["development", "test", "production"] + def initialize(env) + super(env) + + DEFAULT_ENVIRONMENTS.each do |default| + instance_variable_set :"@#{default}", env == default + end + end + + DEFAULT_ENVIRONMENTS.each do |env| + class_eval "def #{env}?; @#{env}; end" + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/error_reporter.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/error_reporter.rb new file mode 100644 index 0000000..43683c1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/error_reporter.rb @@ -0,0 +1,117 @@ +# frozen_string_literal: true + +module ActiveSupport + # +ActiveSupport::ErrorReporter+ is a common interface for error reporting services. + # + # To rescue and report any unhandled error, you can use the +handle+ method: + # + # Rails.error.handle do + # do_something! + # end + # + # If an error is raised, it will be reported and swallowed. + # + # Alternatively if you want to report the error but not swallow it, you can use +record+ + # + # Rails.error.record do + # do_something! + # end + # + # Both methods can be restricted to only handle a specific exception class + # + # maybe_tags = Rails.error.handle(Redis::BaseError) { redis.get("tags") } + # + # You can also pass some extra context information that may be used by the error subscribers: + # + # Rails.error.handle(context: { section: "admin" }) do + # # ... + # end + # + # Additionally a +severity+ can be passed along to communicate how important the error report is. + # +severity+ can be one of +:error+, +:warning+ or +:info+. Handled errors default to the +:warning+ + # severity, and unhandled ones to +error+. + # + # Both +handle+ and +record+ pass through the return value from the block. In the case of +handle+ + # rescuing an error, a fallback can be provided. The fallback must be a callable whose result will + # be returned when the block raises and is handled: + # + # user = Rails.error.handle(fallback: -> { User.anonymous }) do + # User.find_by(params) + # end + class ErrorReporter + SEVERITIES = %i(error warning info) + + attr_accessor :logger + + def initialize(*subscribers, logger: nil) + @subscribers = subscribers.flatten + @logger = logger + end + + # Report any unhandled exception, and swallow it. + # + # Rails.error.handle do + # 1 + '1' + # end + # + def handle(error_class = StandardError, severity: :warning, context: {}, fallback: nil) + yield + rescue error_class => error + report(error, handled: true, severity: severity, context: context) + fallback.call if fallback + end + + def record(error_class = StandardError, severity: :error, context: {}) + yield + rescue error_class => error + report(error, handled: false, severity: severity, context: context) + raise + end + + # Register a new error subscriber. The subscriber must respond to + # + # report(Exception, handled: Boolean, context: Hash) + # + # The +report+ method +should+ never raise an error. + def subscribe(subscriber) + unless subscriber.respond_to?(:report) + raise ArgumentError, "Error subscribers must respond to #report" + end + @subscribers << subscriber + end + + # Update the execution context that is accessible to error subscribers + # + # Rails.error.set_context(section: "checkout", user_id: @user.id) + # + # See +ActiveSupport::ExecutionContext.set+ + def set_context(...) + ActiveSupport::ExecutionContext.set(...) + end + + # When the block based +handle+ and +record+ methods are not suitable, you can directly use +report+ + # + # Rails.error.report(error, handled: true) + def report(error, handled:, severity: handled ? :warning : :error, context: {}) + unless SEVERITIES.include?(severity) + raise ArgumentError, "severity must be one of #{SEVERITIES.map(&:inspect).join(", ")}, got: #{severity.inspect}" + end + + full_context = ActiveSupport::ExecutionContext.to_h.merge(context) + @subscribers.each do |subscriber| + subscriber.report(error, handled: handled, severity: severity, context: full_context) + rescue => subscriber_error + if logger + logger.fatal( + "Error subscriber raised an error: #{subscriber_error.message} (#{subscriber_error.class})\n" + + subscriber_error.backtrace.join("\n") + ) + else + raise + end + end + + nil + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/evented_file_update_checker.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/evented_file_update_checker.rb new file mode 100644 index 0000000..00e20cd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/evented_file_update_checker.rb @@ -0,0 +1,170 @@ +# frozen_string_literal: true + +require "set" +require "pathname" +require "concurrent/atomic/atomic_boolean" +require "listen" +require "active_support/fork_tracker" + +module ActiveSupport + # Allows you to "listen" to changes in a file system. + # The evented file updater does not hit disk when checking for updates + # instead it uses platform specific file system events to trigger a change + # in state. + # + # The file checker takes an array of files to watch or a hash specifying directories + # and file extensions to watch. It also takes a block that is called when + # EventedFileUpdateChecker#execute is run or when EventedFileUpdateChecker#execute_if_updated + # is run and there have been changes to the file system. + # + # Note: Forking will cause the first call to `updated?` to return `true`. + # + # Example: + # + # checker = ActiveSupport::EventedFileUpdateChecker.new(["/tmp/foo"]) { puts "changed" } + # checker.updated? + # # => false + # checker.execute_if_updated + # # => nil + # + # FileUtils.touch("/tmp/foo") + # + # checker.updated? + # # => true + # checker.execute_if_updated + # # => "changed" + # + class EventedFileUpdateChecker # :nodoc: all + def initialize(files, dirs = {}, &block) + unless block + raise ArgumentError, "A block is required to initialize an EventedFileUpdateChecker" + end + + @block = block + @core = Core.new(files, dirs) + ObjectSpace.define_finalizer(self, @core.finalizer) + end + + def updated? + if @core.restart? + @core.thread_safely(&:restart) + @core.updated.make_true + end + + @core.updated.true? + end + + def execute + @core.updated.make_false + @block.call + end + + def execute_if_updated + if updated? + yield if block_given? + execute + true + end + end + + class Core + attr_reader :updated + + def initialize(files, dirs) + @files = files.map { |file| Pathname(file).expand_path }.to_set + + @dirs = dirs.each_with_object({}) do |(dir, exts), hash| + hash[Pathname(dir).expand_path] = Array(exts).map { |ext| ext.to_s.sub(/\A\.?/, ".") }.to_set + end + + @common_path = common_path(@dirs.keys) + + @dtw = directories_to_watch + @missing = [] + + @updated = Concurrent::AtomicBoolean.new(false) + @mutex = Mutex.new + + start + @after_fork = ActiveSupport::ForkTracker.after_fork { start } + end + + def finalizer + proc do + stop + ActiveSupport::ForkTracker.unregister(@after_fork) + end + end + + def thread_safely + @mutex.synchronize do + yield self + end + end + + def start + normalize_dirs! + @dtw, @missing = [*@dtw, *@missing].partition(&:exist?) + @listener = @dtw.any? ? Listen.to(*@dtw, &method(:changed)) : nil + @listener&.start + end + + def stop + @listener&.stop + end + + def restart + stop + start + end + + def restart? + @missing.any?(&:exist?) + end + + def normalize_dirs! + @dirs.transform_keys! do |dir| + dir.exist? ? dir.realpath : dir + end + end + + def changed(modified, added, removed) + unless @updated.true? + @updated.make_true if (modified + added + removed).any? { |f| watching?(f) } + end + end + + def watching?(file) + file = Pathname(file) + + if @files.member?(file) + true + elsif file.directory? + false + else + ext = file.extname + + file.dirname.ascend do |dir| + matching = @dirs[dir] + + if matching && (matching.empty? || matching.include?(ext)) + break true + elsif dir == @common_path || dir.root? + break false + end + end + end + end + + def directories_to_watch + dtw = @dirs.keys | @files.map(&:dirname) + accounted_for = dtw.to_set + Gem.path.map { |path| Pathname(path) } + dtw.reject { |dir| dir.ascend.drop(1).any? { |parent| accounted_for.include?(parent) } } + end + + def common_path(paths) + paths.map { |path| path.ascend.to_a }.reduce(&:&)&.first + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/execution_context.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/execution_context.rb new file mode 100644 index 0000000..1c95188 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/execution_context.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +module ActiveSupport + module ExecutionContext # :nodoc: + @after_change_callbacks = [] + class << self + def after_change(&block) + @after_change_callbacks << block + end + + # Updates the execution context. If a block is given, it resets the provided keys to their + # previous value once the block exits. + def set(**options) + options.symbolize_keys! + keys = options.keys + + store = self.store + + previous_context = keys.zip(store.values_at(*keys)).to_h + + store.merge!(options) + @after_change_callbacks.each(&:call) + + if block_given? + begin + yield + ensure + store.merge!(previous_context) + @after_change_callbacks.each(&:call) + end + end + end + + def []=(key, value) + store[key.to_sym] = value + @after_change_callbacks.each(&:call) + end + + def to_h + store.dup + end + + def clear + store.clear + end + + private + def store + IsolatedExecutionState[:active_support_execution_context] ||= {} + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/execution_context/test_helper.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/execution_context/test_helper.rb new file mode 100644 index 0000000..ae8c43e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/execution_context/test_helper.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +module ActiveSupport::ExecutionContext::TestHelper # :nodoc: + def before_setup + ActiveSupport::ExecutionContext.clear + super + end + + def after_teardown + super + ActiveSupport::ExecutionContext.clear + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/execution_wrapper.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/execution_wrapper.rb new file mode 100644 index 0000000..5a4a9b2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/execution_wrapper.rb @@ -0,0 +1,151 @@ +# frozen_string_literal: true + +require "active_support/error_reporter" +require "active_support/callbacks" +require "concurrent/hash" + +module ActiveSupport + class ExecutionWrapper + include ActiveSupport::Callbacks + + Null = Object.new # :nodoc: + def Null.complete! # :nodoc: + end + + define_callbacks :run + define_callbacks :complete + + def self.to_run(*args, &block) + set_callback(:run, *args, &block) + end + + def self.to_complete(*args, &block) + set_callback(:complete, *args, &block) + end + + RunHook = Struct.new(:hook) do # :nodoc: + def before(target) + hook_state = target.send(:hook_state) + hook_state[hook] = hook.run + end + end + + CompleteHook = Struct.new(:hook) do # :nodoc: + def before(target) + hook_state = target.send(:hook_state) + if hook_state.key?(hook) + hook.complete hook_state[hook] + end + end + alias after before + end + + # Register an object to be invoked during both the +run+ and + # +complete+ steps. + # + # +hook.complete+ will be passed the value returned from +hook.run+, + # and will only be invoked if +run+ has previously been called. + # (Mostly, this means it won't be invoked if an exception occurs in + # a preceding +to_run+ block; all ordinary +to_complete+ blocks are + # invoked in that situation.) + def self.register_hook(hook, outer: false) + if outer + to_run RunHook.new(hook), prepend: true + to_complete :after, CompleteHook.new(hook) + else + to_run RunHook.new(hook) + to_complete CompleteHook.new(hook) + end + end + + # Run this execution. + # + # Returns an instance, whose +complete!+ method *must* be invoked + # after the work has been performed. + # + # Where possible, prefer +wrap+. + def self.run!(reset: false) + if reset + lost_instance = IsolatedExecutionState.delete(active_key) + lost_instance&.complete! + else + return Null if active? + end + + new.tap do |instance| + success = nil + begin + instance.run! + success = true + ensure + instance.complete! unless success + end + end + end + + # Perform the work in the supplied block as an execution. + def self.wrap + return yield if active? + + instance = run! + begin + yield + rescue => error + error_reporter.report(error, handled: false) + raise + ensure + instance.complete! + end + end + + def self.perform # :nodoc: + instance = new + instance.run + begin + yield + ensure + instance.complete + end + end + + def self.error_reporter + @error_reporter ||= ActiveSupport::ErrorReporter.new + end + + def self.active_key # :nodoc: + @active_key ||= :"active_execution_wrapper_#{object_id}" + end + + def self.active? # :nodoc: + IsolatedExecutionState.key?(active_key) + end + + def run! # :nodoc: + IsolatedExecutionState[self.class.active_key] = self + run + end + + def run # :nodoc: + run_callbacks(:run) + end + + # Complete this in-flight execution. This method *must* be called + # exactly once on the result of any call to +run!+. + # + # Where possible, prefer +wrap+. + def complete! + complete + ensure + IsolatedExecutionState.delete(self.class.active_key) + end + + def complete # :nodoc: + run_callbacks(:complete) + end + + private + def hook_state + @_hook_state ||= {} + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/executor.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/executor.rb new file mode 100644 index 0000000..ce391b0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/executor.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +require "active_support/execution_wrapper" + +module ActiveSupport + class Executor < ExecutionWrapper + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/executor/test_helper.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/executor/test_helper.rb new file mode 100644 index 0000000..97f489d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/executor/test_helper.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +module ActiveSupport::Executor::TestHelper # :nodoc: + def run(...) + Rails.application.executor.perform { super } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/file_update_checker.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/file_update_checker.rb new file mode 100644 index 0000000..9b665e7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/file_update_checker.rb @@ -0,0 +1,162 @@ +# frozen_string_literal: true + +require "active_support/core_ext/time/calculations" + +module ActiveSupport + # FileUpdateChecker specifies the API used by Rails to watch files + # and control reloading. The API depends on four methods: + # + # * +initialize+ which expects two parameters and one block as + # described below. + # + # * +updated?+ which returns a boolean if there were updates in + # the filesystem or not. + # + # * +execute+ which executes the given block on initialization + # and updates the latest watched files and timestamp. + # + # * +execute_if_updated+ which just executes the block if it was updated. + # + # After initialization, a call to +execute_if_updated+ must execute + # the block only if there was really a change in the filesystem. + # + # This class is used by Rails to reload the I18n framework whenever + # they are changed upon a new request. + # + # i18n_reloader = ActiveSupport::FileUpdateChecker.new(paths) do + # I18n.reload! + # end + # + # ActiveSupport::Reloader.to_prepare do + # i18n_reloader.execute_if_updated + # end + class FileUpdateChecker + # It accepts two parameters on initialization. The first is an array + # of files and the second is an optional hash of directories. The hash must + # have directories as keys and the value is an array of extensions to be + # watched under that directory. + # + # This method must also receive a block that will be called once a path + # changes. The array of files and list of directories cannot be changed + # after FileUpdateChecker has been initialized. + def initialize(files, dirs = {}, &block) + unless block + raise ArgumentError, "A block is required to initialize a FileUpdateChecker" + end + + @files = files.freeze + @glob = compile_glob(dirs) + @block = block + + @watched = nil + @updated_at = nil + + @last_watched = watched + @last_update_at = updated_at(@last_watched) + end + + # Check if any of the entries were updated. If so, the watched and/or + # updated_at values are cached until the block is executed via +execute+ + # or +execute_if_updated+. + def updated? + current_watched = watched + if @last_watched.size != current_watched.size + @watched = current_watched + true + else + current_updated_at = updated_at(current_watched) + if @last_update_at < current_updated_at + @watched = current_watched + @updated_at = current_updated_at + true + else + false + end + end + end + + # Executes the given block and updates the latest watched files and + # timestamp. + def execute + @last_watched = watched + @last_update_at = updated_at(@last_watched) + @block.call + ensure + @watched = nil + @updated_at = nil + end + + # Execute the block given if updated. + def execute_if_updated + if updated? + yield if block_given? + execute + true + else + false + end + end + + private + def watched + @watched || begin + all = @files.select { |f| File.exist?(f) } + all.concat(Dir[@glob]) if @glob + all + end + end + + def updated_at(paths) + @updated_at || max_mtime(paths) || Time.at(0) + end + + # This method returns the maximum mtime of the files in +paths+, or +nil+ + # if the array is empty. + # + # Files with a mtime in the future are ignored. Such abnormal situation + # can happen for example if the user changes the clock by hand. It is + # healthy to consider this edge case because with mtimes in the future + # reloading is not triggered. + def max_mtime(paths) + time_now = Time.now + max_mtime = nil + + # Time comparisons are performed with #compare_without_coercion because + # AS redefines these operators in a way that is much slower and does not + # bring any benefit in this particular code. + # + # Read t1.compare_without_coercion(t2) < 0 as t1 < t2. + paths.each do |path| + mtime = File.mtime(path) + + next if time_now.compare_without_coercion(mtime) < 0 + + if max_mtime.nil? || max_mtime.compare_without_coercion(mtime) < 0 + max_mtime = mtime + end + end + + max_mtime + end + + def compile_glob(hash) + hash.freeze # Freeze so changes aren't accidentally pushed + return if hash.empty? + + globs = hash.map do |key, value| + "#{escape(key)}/**/*#{compile_ext(value)}" + end + "{#{globs.join(",")}}" + end + + def escape(key) + key.gsub(",", '\,') + end + + def compile_ext(array) + array = Array(array) + return if array.empty? + ".{#{array.join(",")}}" + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/fork_tracker.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/fork_tracker.rb new file mode 100644 index 0000000..bc1d32b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/fork_tracker.rb @@ -0,0 +1,71 @@ +# frozen_string_literal: true + +module ActiveSupport + module ForkTracker # :nodoc: + module ModernCoreExt + def _fork + pid = super + if pid == 0 + ForkTracker.check! + end + pid + end + end + + module CoreExt + def fork(...) + if block_given? + super do + ForkTracker.check! + yield + end + else + unless pid = super + ForkTracker.check! + end + pid + end + end + end + + module CoreExtPrivate + include CoreExt + private :fork + end + + @pid = Process.pid + @callbacks = [] + + class << self + def check! + new_pid = Process.pid + if @pid != new_pid + @callbacks.each(&:call) + @pid = new_pid + end + end + + def hook! + if Process.respond_to?(:_fork) # Ruby 3.1+ + ::Process.singleton_class.prepend(ModernCoreExt) + elsif Process.respond_to?(:fork) + ::Object.prepend(CoreExtPrivate) if RUBY_VERSION < "3.0" + ::Kernel.prepend(CoreExtPrivate) + ::Kernel.singleton_class.prepend(CoreExt) + ::Process.singleton_class.prepend(CoreExt) + end + end + + def after_fork(&block) + @callbacks << block + block + end + + def unregister(callback) + @callbacks.delete(callback) + end + end + end +end + +ActiveSupport::ForkTracker.hook! diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/gem_version.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/gem_version.rb new file mode 100644 index 0000000..fdf374b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/gem_version.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +module ActiveSupport + # Returns the version of the currently loaded Active Support as a Gem::Version. + def self.gem_version + Gem::Version.new VERSION::STRING + end + + module VERSION + MAJOR = 7 + MINOR = 0 + TINY = 2 + PRE = "3" + + STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/gzip.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/gzip.rb new file mode 100644 index 0000000..7ffa6d9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/gzip.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +require "zlib" +require "stringio" + +module ActiveSupport + # A convenient wrapper for the zlib standard library that allows + # compression/decompression of strings with gzip. + # + # gzip = ActiveSupport::Gzip.compress('compress me!') + # # => "\x1F\x8B\b\x00o\x8D\xCDO\x00\x03K\xCE\xCF-(J-.V\xC8MU\x04\x00R>n\x83\f\x00\x00\x00" + # + # ActiveSupport::Gzip.decompress(gzip) + # # => "compress me!" + module Gzip + class Stream < StringIO + def initialize(*) + super + set_encoding "BINARY" + end + def close; rewind; end + end + + # Decompresses a gzipped string. + def self.decompress(source) + Zlib::GzipReader.wrap(StringIO.new(source), &:read) + end + + # Compresses a string using gzip. + def self.compress(source, level = Zlib::DEFAULT_COMPRESSION, strategy = Zlib::DEFAULT_STRATEGY) + output = Stream.new + gz = Zlib::GzipWriter.new(output, level, strategy) + gz.write(source) + gz.close + output.string + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/hash_with_indifferent_access.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/hash_with_indifferent_access.rb new file mode 100644 index 0000000..aed884f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/hash_with_indifferent_access.rb @@ -0,0 +1,425 @@ +# frozen_string_literal: true + +require "active_support/core_ext/hash/keys" +require "active_support/core_ext/hash/reverse_merge" +require "active_support/core_ext/hash/except" +require "active_support/core_ext/hash/slice" + +module ActiveSupport + # Implements a hash where keys :foo and "foo" are considered + # to be the same. + # + # rgb = ActiveSupport::HashWithIndifferentAccess.new + # + # rgb[:black] = '#000000' + # rgb[:black] # => '#000000' + # rgb['black'] # => '#000000' + # + # rgb['white'] = '#FFFFFF' + # rgb[:white] # => '#FFFFFF' + # rgb['white'] # => '#FFFFFF' + # + # Internally symbols are mapped to strings when used as keys in the entire + # writing interface (calling []=, merge, etc). This + # mapping belongs to the public interface. For example, given: + # + # hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1) + # + # You are guaranteed that the key is returned as a string: + # + # hash.keys # => ["a"] + # + # Technically other types of keys are accepted: + # + # hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1) + # hash[0] = 0 + # hash # => {"a"=>1, 0=>0} + # + # but this class is intended for use cases where strings or symbols are the + # expected keys and it is convenient to understand both as the same. For + # example the +params+ hash in Ruby on Rails. + # + # Note that core extensions define Hash#with_indifferent_access: + # + # rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access + # + # which may be handy. + # + # To access this class outside of Rails, require the core extension with: + # + # require "active_support/core_ext/hash/indifferent_access" + # + # which will, in turn, require this file. + class HashWithIndifferentAccess < Hash + # Returns +true+ so that Array#extract_options! finds members of + # this class. + def extractable_options? + true + end + + def with_indifferent_access + dup + end + + def nested_under_indifferent_access + self + end + + def initialize(constructor = nil) + if constructor.respond_to?(:to_hash) + super() + update(constructor) + + hash = constructor.is_a?(Hash) ? constructor : constructor.to_hash + self.default = hash.default if hash.default + self.default_proc = hash.default_proc if hash.default_proc + elsif constructor.nil? + super() + else + super(constructor) + end + end + + def self.[](*args) + new.merge!(Hash[*args]) + end + + alias_method :regular_writer, :[]= unless method_defined?(:regular_writer) + alias_method :regular_update, :update unless method_defined?(:regular_update) + + # Assigns a new value to the hash: + # + # hash = ActiveSupport::HashWithIndifferentAccess.new + # hash[:key] = 'value' + # + # This value can be later fetched using either +:key+ or 'key'. + def []=(key, value) + regular_writer(convert_key(key), convert_value(value, conversion: :assignment)) + end + + alias_method :store, :[]= + + # Updates the receiver in-place, merging in the hashes passed as arguments: + # + # hash_1 = ActiveSupport::HashWithIndifferentAccess.new + # hash_1[:key] = 'value' + # + # hash_2 = ActiveSupport::HashWithIndifferentAccess.new + # hash_2[:key] = 'New Value!' + # + # hash_1.update(hash_2) # => {"key"=>"New Value!"} + # + # hash = ActiveSupport::HashWithIndifferentAccess.new + # hash.update({ "a" => 1 }, { "b" => 2 }) # => { "a" => 1, "b" => 2 } + # + # The arguments can be either an + # ActiveSupport::HashWithIndifferentAccess or a regular +Hash+. + # In either case the merge respects the semantics of indifferent access. + # + # If the argument is a regular hash with keys +:key+ and "key" only one + # of the values end up in the receiver, but which one is unspecified. + # + # When given a block, the value for duplicated keys will be determined + # by the result of invoking the block with the duplicated key, the value + # in the receiver, and the value in +other_hash+. The rules for duplicated + # keys follow the semantics of indifferent access: + # + # hash_1[:key] = 10 + # hash_2['key'] = 12 + # hash_1.update(hash_2) { |key, old, new| old + new } # => {"key"=>22} + def update(*other_hashes, &block) + if other_hashes.size == 1 + update_with_single_argument(other_hashes.first, block) + else + other_hashes.each do |other_hash| + update_with_single_argument(other_hash, block) + end + end + self + end + + alias_method :merge!, :update + + # Checks the hash for a key matching the argument passed in: + # + # hash = ActiveSupport::HashWithIndifferentAccess.new + # hash['key'] = 'value' + # hash.key?(:key) # => true + # hash.key?('key') # => true + def key?(key) + super(convert_key(key)) + end + + alias_method :include?, :key? + alias_method :has_key?, :key? + alias_method :member?, :key? + + # Same as Hash#[] where the key passed as argument can be + # either a string or a symbol: + # + # counters = ActiveSupport::HashWithIndifferentAccess.new + # counters[:foo] = 1 + # + # counters['foo'] # => 1 + # counters[:foo] # => 1 + # counters[:zoo] # => nil + def [](key) + super(convert_key(key)) + end + + # Same as Hash#assoc where the key passed as argument can be + # either a string or a symbol: + # + # counters = ActiveSupport::HashWithIndifferentAccess.new + # counters[:foo] = 1 + # + # counters.assoc('foo') # => ["foo", 1] + # counters.assoc(:foo) # => ["foo", 1] + # counters.assoc(:zoo) # => nil + def assoc(key) + super(convert_key(key)) + end + + # Same as Hash#fetch where the key passed as argument can be + # either a string or a symbol: + # + # counters = ActiveSupport::HashWithIndifferentAccess.new + # counters[:foo] = 1 + # + # counters.fetch('foo') # => 1 + # counters.fetch(:bar, 0) # => 0 + # counters.fetch(:bar) { |key| 0 } # => 0 + # counters.fetch(:zoo) # => KeyError: key not found: "zoo" + def fetch(key, *extras) + super(convert_key(key), *extras) + end + + # Same as Hash#dig where the key passed as argument can be + # either a string or a symbol: + # + # counters = ActiveSupport::HashWithIndifferentAccess.new + # counters[:foo] = { bar: 1 } + # + # counters.dig('foo', 'bar') # => 1 + # counters.dig(:foo, :bar) # => 1 + # counters.dig(:zoo) # => nil + def dig(*args) + args[0] = convert_key(args[0]) if args.size > 0 + super(*args) + end + + # Same as Hash#default where the key passed as argument can be + # either a string or a symbol: + # + # hash = ActiveSupport::HashWithIndifferentAccess.new(1) + # hash.default # => 1 + # + # hash = ActiveSupport::HashWithIndifferentAccess.new { |hash, key| key } + # hash.default # => nil + # hash.default('foo') # => 'foo' + # hash.default(:foo) # => 'foo' + def default(*args) + super(*args.map { |arg| convert_key(arg) }) + end + + # Returns an array of the values at the specified indices: + # + # hash = ActiveSupport::HashWithIndifferentAccess.new + # hash[:a] = 'x' + # hash[:b] = 'y' + # hash.values_at('a', 'b') # => ["x", "y"] + def values_at(*keys) + super(*keys.map { |key| convert_key(key) }) + end + + # Returns an array of the values at the specified indices, but also + # raises an exception when one of the keys can't be found. + # + # hash = ActiveSupport::HashWithIndifferentAccess.new + # hash[:a] = 'x' + # hash[:b] = 'y' + # hash.fetch_values('a', 'b') # => ["x", "y"] + # hash.fetch_values('a', 'c') { |key| 'z' } # => ["x", "z"] + # hash.fetch_values('a', 'c') # => KeyError: key not found: "c" + def fetch_values(*indices, &block) + super(*indices.map { |key| convert_key(key) }, &block) + end + + # Returns a shallow copy of the hash. + # + # hash = ActiveSupport::HashWithIndifferentAccess.new({ a: { b: 'b' } }) + # dup = hash.dup + # dup[:a][:c] = 'c' + # + # hash[:a][:c] # => "c" + # dup[:a][:c] # => "c" + def dup + self.class.new(self).tap do |new_hash| + set_defaults(new_hash) + end + end + + # This method has the same semantics of +update+, except it does not + # modify the receiver but rather returns a new hash with indifferent + # access with the result of the merge. + def merge(*hashes, &block) + dup.update(*hashes, &block) + end + + # Like +merge+ but the other way around: Merges the receiver into the + # argument and returns a new hash with indifferent access as result: + # + # hash = ActiveSupport::HashWithIndifferentAccess.new + # hash['a'] = nil + # hash.reverse_merge(a: 0, b: 1) # => {"a"=>nil, "b"=>1} + def reverse_merge(other_hash) + super(self.class.new(other_hash)) + end + alias_method :with_defaults, :reverse_merge + + # Same semantics as +reverse_merge+ but modifies the receiver in-place. + def reverse_merge!(other_hash) + super(self.class.new(other_hash)) + end + alias_method :with_defaults!, :reverse_merge! + + # Replaces the contents of this hash with other_hash. + # + # h = { "a" => 100, "b" => 200 } + # h.replace({ "c" => 300, "d" => 400 }) # => {"c"=>300, "d"=>400} + def replace(other_hash) + super(self.class.new(other_hash)) + end + + # Removes the specified key from the hash. + def delete(key) + super(convert_key(key)) + end + + # Returns a hash with indifferent access that includes everything except given keys. + # hash = { a: "x", b: "y", c: 10 }.with_indifferent_access + # hash.except(:a, "b") # => {c: 10}.with_indifferent_access + # hash # => { a: "x", b: "y", c: 10 }.with_indifferent_access + def except(*keys) + slice(*self.keys - keys.map { |key| convert_key(key) }) + end + alias_method :without, :except + + def stringify_keys!; self end + def deep_stringify_keys!; self end + def stringify_keys; dup end + def deep_stringify_keys; dup end + undef :symbolize_keys! + undef :deep_symbolize_keys! + def symbolize_keys; to_hash.symbolize_keys! end + alias_method :to_options, :symbolize_keys + def deep_symbolize_keys; to_hash.deep_symbolize_keys! end + def to_options!; self end + + def select(*args, &block) + return to_enum(:select) unless block_given? + dup.tap { |hash| hash.select!(*args, &block) } + end + + def reject(*args, &block) + return to_enum(:reject) unless block_given? + dup.tap { |hash| hash.reject!(*args, &block) } + end + + def transform_values(*args, &block) + return to_enum(:transform_values) unless block_given? + dup.tap { |hash| hash.transform_values!(*args, &block) } + end + + def transform_keys(*args, &block) + return to_enum(:transform_keys) unless block_given? + dup.tap { |hash| hash.transform_keys!(*args, &block) } + end + + def transform_keys! + return enum_for(:transform_keys!) { size } unless block_given? + keys.each do |key| + self[yield(key)] = delete(key) + end + self + end + + def slice(*keys) + keys.map! { |key| convert_key(key) } + self.class.new(super) + end + + def slice!(*keys) + keys.map! { |key| convert_key(key) } + super + end + + def compact + dup.tap(&:compact!) + end + + # Convert to a regular hash with string keys. + def to_hash + _new_hash = Hash.new + set_defaults(_new_hash) + + each do |key, value| + _new_hash[key] = convert_value(value, conversion: :to_hash) + end + _new_hash + end + + private + if Symbol.method_defined?(:name) + def convert_key(key) + key.kind_of?(Symbol) ? key.name : key + end + else + def convert_key(key) + key.kind_of?(Symbol) ? key.to_s : key + end + end + + def convert_value(value, conversion: nil) + if value.is_a? Hash + if conversion == :to_hash + value.to_hash + else + value.nested_under_indifferent_access + end + elsif value.is_a?(Array) + if conversion != :assignment || value.frozen? + value = value.dup + end + value.map! { |e| convert_value(e, conversion: conversion) } + else + value + end + end + + def set_defaults(target) + if default_proc + target.default_proc = default_proc.dup + else + target.default = default + end + end + + def update_with_single_argument(other_hash, block) + if other_hash.is_a? HashWithIndifferentAccess + regular_update(other_hash, &block) + else + other_hash.to_hash.each_pair do |key, value| + if block && key?(key) + value = block.call(convert_key(key), self[key], value) + end + regular_writer(convert_key(key), convert_value(value)) + end + end + end + end +end + +# :stopdoc: + +HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/html_safe_translation.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/html_safe_translation.rb new file mode 100644 index 0000000..2d06a0d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/html_safe_translation.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +module ActiveSupport + module HtmlSafeTranslation # :nodoc: + extend self + + def translate(key, **options) + if html_safe_translation_key?(key) + html_safe_options = html_escape_translation_options(options) + translation = I18n.translate(key, **html_safe_options) + html_safe_translation(translation) + else + I18n.translate(key, **options) + end + end + + private + def html_safe_translation_key?(key) + /(?:_|\b)html\z/.match?(key) + end + + def html_escape_translation_options(options) + options.each do |name, value| + unless i18n_option?(name) || (name == :count && value.is_a?(Numeric)) + options[name] = ERB::Util.html_escape(value.to_s) + end + end + end + + def i18n_option?(name) + (@i18n_option_names ||= I18n::RESERVED_KEYS.to_set).include?(name) + end + + + def html_safe_translation(translation) + if translation.respond_to?(:map) + translation.map { |element| element.respond_to?(:html_safe) ? element.html_safe : element } + else + translation.respond_to?(:html_safe) ? translation.html_safe : translation + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/i18n.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/i18n.rb new file mode 100644 index 0000000..832a9fa --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/i18n.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +require "active_support/core_ext/hash/deep_merge" +require "active_support/core_ext/hash/except" +require "active_support/core_ext/hash/slice" +begin + require "i18n" + require "i18n/backend/fallbacks" +rescue LoadError => e + $stderr.puts "The i18n gem is not available. Please add it to your Gemfile and run bundle install" + raise e +end +require "active_support/lazy_load_hooks" + +ActiveSupport.run_load_hooks(:i18n) +I18n.load_path << File.expand_path("locale/en.yml", __dir__) +I18n.load_path << File.expand_path("locale/en.rb", __dir__) diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/i18n_railtie.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/i18n_railtie.rb new file mode 100644 index 0000000..1e7185e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/i18n_railtie.rb @@ -0,0 +1,125 @@ +# frozen_string_literal: true + +require "active_support" +require "active_support/core_ext/array/wrap" + +# :enddoc: + +module I18n + class Railtie < Rails::Railtie + config.i18n = ActiveSupport::OrderedOptions.new + config.i18n.railties_load_path = [] + config.i18n.load_path = [] + config.i18n.fallbacks = ActiveSupport::OrderedOptions.new + + config.eager_load_namespaces << I18n + + # Set the i18n configuration after initialization since a lot of + # configuration is still usually done in application initializers. + config.after_initialize do |app| + I18n::Railtie.initialize_i18n(app) + end + + # Trigger i18n config before any eager loading has happened + # so it's ready if any classes require it when eager loaded. + config.before_eager_load do |app| + I18n::Railtie.initialize_i18n(app) + end + + @i18n_inited = false + + # Setup i18n configuration. + def self.initialize_i18n(app) + return if @i18n_inited + + fallbacks = app.config.i18n.delete(:fallbacks) + + # Avoid issues with setting the default_locale by disabling available locales + # check while configuring. + enforce_available_locales = app.config.i18n.delete(:enforce_available_locales) + enforce_available_locales = I18n.enforce_available_locales if enforce_available_locales.nil? + I18n.enforce_available_locales = false + + reloadable_paths = [] + app.config.i18n.each do |setting, value| + case setting + when :railties_load_path + reloadable_paths = value + app.config.i18n.load_path.unshift(*value.flat_map(&:existent)) + when :load_path + I18n.load_path += value + when :raise_on_missing_translations + forward_raise_on_missing_translations_config(app) + else + I18n.public_send("#{setting}=", value) + end + end + + init_fallbacks(fallbacks) if fallbacks && validate_fallbacks(fallbacks) + + # Restore available locales check so it will take place from now on. + I18n.enforce_available_locales = enforce_available_locales + + directories = watched_dirs_with_extensions(reloadable_paths) + reloader = app.config.file_watcher.new(I18n.load_path.dup, directories) do + I18n.load_path.keep_if { |p| File.exist?(p) } + I18n.load_path |= reloadable_paths.flat_map(&:existent) + end + + app.reloaders << reloader + app.reloader.to_run do + reloader.execute_if_updated { require_unload_lock! } + end + reloader.execute + + @i18n_inited = true + end + + def self.forward_raise_on_missing_translations_config(app) + ActiveSupport.on_load(:action_view) do + ActionView::Helpers::TranslationHelper.raise_on_missing_translations = app.config.i18n.raise_on_missing_translations + end + + ActiveSupport.on_load(:action_controller) do + AbstractController::Translation.raise_on_missing_translations = app.config.i18n.raise_on_missing_translations + end + end + + def self.include_fallbacks_module + I18n.backend.class.include(I18n::Backend::Fallbacks) + end + + def self.init_fallbacks(fallbacks) + include_fallbacks_module + + args = \ + case fallbacks + when ActiveSupport::OrderedOptions + [*(fallbacks[:defaults] || []) << fallbacks[:map]].compact + when Hash, Array + Array.wrap(fallbacks) + else # TrueClass + [I18n.default_locale] + end + + I18n.fallbacks = I18n::Locale::Fallbacks.new(*args) + end + + def self.validate_fallbacks(fallbacks) + case fallbacks + when ActiveSupport::OrderedOptions + !fallbacks.empty? + when TrueClass, Array, Hash + true + else + raise "Unexpected fallback type #{fallbacks.inspect}" + end + end + + def self.watched_dirs_with_extensions(paths) + paths.each_with_object({}) do |path, result| + result[path.absolute_current] = path.extensions + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflections.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflections.rb new file mode 100644 index 0000000..baf1cb3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflections.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +require "active_support/inflector/inflections" + +#-- +# Defines the standard inflection rules. These are the starting point for +# new projects and are not considered complete. The current set of inflection +# rules is frozen. This means, we do not change them to become more complete. +# This is a safety measure to keep existing applications from breaking. +#++ +module ActiveSupport + Inflector.inflections(:en) do |inflect| + inflect.plural(/$/, "s") + inflect.plural(/s$/i, "s") + inflect.plural(/^(ax|test)is$/i, '\1es') + inflect.plural(/(octop|vir)us$/i, '\1i') + inflect.plural(/(octop|vir)i$/i, '\1i') + inflect.plural(/(alias|status)$/i, '\1es') + inflect.plural(/(bu)s$/i, '\1ses') + inflect.plural(/(buffal|tomat)o$/i, '\1oes') + inflect.plural(/([ti])um$/i, '\1a') + inflect.plural(/([ti])a$/i, '\1a') + inflect.plural(/sis$/i, "ses") + inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves') + inflect.plural(/(hive)$/i, '\1s') + inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies') + inflect.plural(/(x|ch|ss|sh)$/i, '\1es') + inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices') + inflect.plural(/^(m|l)ouse$/i, '\1ice') + inflect.plural(/^(m|l)ice$/i, '\1ice') + inflect.plural(/^(ox)$/i, '\1en') + inflect.plural(/^(oxen)$/i, '\1') + inflect.plural(/(quiz)$/i, '\1zes') + + inflect.singular(/s$/i, "") + inflect.singular(/(ss)$/i, '\1') + inflect.singular(/(n)ews$/i, '\1ews') + inflect.singular(/([ti])a$/i, '\1um') + inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis') + inflect.singular(/(^analy)(sis|ses)$/i, '\1sis') + inflect.singular(/([^f])ves$/i, '\1fe') + inflect.singular(/(hive)s$/i, '\1') + inflect.singular(/(tive)s$/i, '\1') + inflect.singular(/([lr])ves$/i, '\1f') + inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y') + inflect.singular(/(s)eries$/i, '\1eries') + inflect.singular(/(m)ovies$/i, '\1ovie') + inflect.singular(/(x|ch|ss|sh)es$/i, '\1') + inflect.singular(/^(m|l)ice$/i, '\1ouse') + inflect.singular(/(bus)(es)?$/i, '\1') + inflect.singular(/(o)es$/i, '\1') + inflect.singular(/(shoe)s$/i, '\1') + inflect.singular(/(cris|test)(is|es)$/i, '\1is') + inflect.singular(/^(a)x[ie]s$/i, '\1xis') + inflect.singular(/(octop|vir)(us|i)$/i, '\1us') + inflect.singular(/(alias|status)(es)?$/i, '\1') + inflect.singular(/^(ox)en/i, '\1') + inflect.singular(/(vert|ind)ices$/i, '\1ex') + inflect.singular(/(matr)ices$/i, '\1ix') + inflect.singular(/(quiz)zes$/i, '\1') + inflect.singular(/(database)s$/i, '\1') + + inflect.irregular("person", "people") + inflect.irregular("man", "men") + inflect.irregular("child", "children") + inflect.irregular("sex", "sexes") + inflect.irregular("move", "moves") + inflect.irregular("zombie", "zombies") + + inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police)) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector.rb new file mode 100644 index 0000000..d77f04c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +# in case active_support/inflector is required without the rest of active_support +require "active_support/inflector/inflections" +require "active_support/inflector/transliterate" +require "active_support/inflector/methods" + +require "active_support/inflections" +require "active_support/core_ext/string/inflections" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector/inflections.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector/inflections.rb new file mode 100644 index 0000000..a9943a8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector/inflections.rb @@ -0,0 +1,271 @@ +# frozen_string_literal: true + +require "concurrent/map" +require "active_support/i18n" + +module ActiveSupport + module Inflector + extend self + + # A singleton instance of this class is yielded by Inflector.inflections, + # which can then be used to specify additional inflection rules. If passed + # an optional locale, rules for other languages can be specified. The + # default locale is :en. Only rules for English are provided. + # + # ActiveSupport::Inflector.inflections(:en) do |inflect| + # inflect.plural /^(ox)$/i, '\1\2en' + # inflect.singular /^(ox)en/i, '\1' + # + # inflect.irregular 'cactus', 'cacti' + # + # inflect.uncountable 'equipment' + # end + # + # New rules are added at the top. So in the example above, the irregular + # rule for cactus will now be the first of the pluralization and + # singularization rules that is runs. This guarantees that your rules run + # before any of the rules that may already have been loaded. + class Inflections + @__instance__ = Concurrent::Map.new + + class Uncountables < Array + def initialize + @regex_array = [] + super + end + + def delete(entry) + super entry + @regex_array.delete(to_regex(entry)) + end + + def <<(*word) + add(word) + end + + def add(words) + words = words.flatten.map(&:downcase) + concat(words) + @regex_array += words.map { |word| to_regex(word) } + self + end + + def uncountable?(str) + @regex_array.any? { |regex| regex.match? str } + end + + private + def to_regex(string) + /\b#{::Regexp.escape(string)}\Z/i + end + end + + def self.instance(locale = :en) + @__instance__[locale] ||= new + end + + def self.instance_or_fallback(locale) + I18n.fallbacks[locale].each do |k| + return @__instance__[k] if @__instance__.key?(k) + end + instance(locale) + end + + attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms + + attr_reader :acronyms_camelize_regex, :acronyms_underscore_regex # :nodoc: + + def initialize + @plurals, @singulars, @uncountables, @humans, @acronyms = [], [], Uncountables.new, [], {} + define_acronym_regex_patterns + end + + # Private, for the test suite. + def initialize_dup(orig) # :nodoc: + %w(plurals singulars uncountables humans acronyms).each do |scope| + instance_variable_set("@#{scope}", orig.public_send(scope).dup) + end + define_acronym_regex_patterns + end + + # Specifies a new acronym. An acronym must be specified as it will appear + # in a camelized string. An underscore string that contains the acronym + # will retain the acronym when passed to +camelize+, +humanize+, or + # +titleize+. A camelized string that contains the acronym will maintain + # the acronym when titleized or humanized, and will convert the acronym + # into a non-delimited single lowercase word when passed to +underscore+. + # + # acronym 'HTML' + # titleize 'html' # => 'HTML' + # camelize 'html' # => 'HTML' + # underscore 'MyHTML' # => 'my_html' + # + # The acronym, however, must occur as a delimited unit and not be part of + # another word for conversions to recognize it: + # + # acronym 'HTTP' + # camelize 'my_http_delimited' # => 'MyHTTPDelimited' + # camelize 'https' # => 'Https', not 'HTTPs' + # underscore 'HTTPS' # => 'http_s', not 'https' + # + # acronym 'HTTPS' + # camelize 'https' # => 'HTTPS' + # underscore 'HTTPS' # => 'https' + # + # Note: Acronyms that are passed to +pluralize+ will no longer be + # recognized, since the acronym will not occur as a delimited unit in the + # pluralized result. To work around this, you must specify the pluralized + # form as an acronym as well: + # + # acronym 'API' + # camelize(pluralize('api')) # => 'Apis' + # + # acronym 'APIs' + # camelize(pluralize('api')) # => 'APIs' + # + # +acronym+ may be used to specify any word that contains an acronym or + # otherwise needs to maintain a non-standard capitalization. The only + # restriction is that the word must begin with a capital letter. + # + # acronym 'RESTful' + # underscore 'RESTful' # => 'restful' + # underscore 'RESTfulController' # => 'restful_controller' + # titleize 'RESTfulController' # => 'RESTful Controller' + # camelize 'restful' # => 'RESTful' + # camelize 'restful_controller' # => 'RESTfulController' + # + # acronym 'McDonald' + # underscore 'McDonald' # => 'mcdonald' + # camelize 'mcdonald' # => 'McDonald' + def acronym(word) + @acronyms[word.downcase] = word + define_acronym_regex_patterns + end + + # Specifies a new pluralization rule and its replacement. The rule can + # either be a string or a regular expression. The replacement should + # always be a string that may include references to the matched data from + # the rule. + def plural(rule, replacement) + @uncountables.delete(rule) if rule.is_a?(String) + @uncountables.delete(replacement) + @plurals.prepend([rule, replacement]) + end + + # Specifies a new singularization rule and its replacement. The rule can + # either be a string or a regular expression. The replacement should + # always be a string that may include references to the matched data from + # the rule. + def singular(rule, replacement) + @uncountables.delete(rule) if rule.is_a?(String) + @uncountables.delete(replacement) + @singulars.prepend([rule, replacement]) + end + + # Specifies a new irregular that applies to both pluralization and + # singularization at the same time. This can only be used for strings, not + # regular expressions. You simply pass the irregular in singular and + # plural form. + # + # irregular 'cactus', 'cacti' + # irregular 'person', 'people' + def irregular(singular, plural) + @uncountables.delete(singular) + @uncountables.delete(plural) + + s0 = singular[0] + srest = singular[1..-1] + + p0 = plural[0] + prest = plural[1..-1] + + if s0.upcase == p0.upcase + plural(/(#{s0})#{srest}$/i, '\1' + prest) + plural(/(#{p0})#{prest}$/i, '\1' + prest) + + singular(/(#{s0})#{srest}$/i, '\1' + srest) + singular(/(#{p0})#{prest}$/i, '\1' + srest) + else + plural(/#{s0.upcase}(?i)#{srest}$/, p0.upcase + prest) + plural(/#{s0.downcase}(?i)#{srest}$/, p0.downcase + prest) + plural(/#{p0.upcase}(?i)#{prest}$/, p0.upcase + prest) + plural(/#{p0.downcase}(?i)#{prest}$/, p0.downcase + prest) + + singular(/#{s0.upcase}(?i)#{srest}$/, s0.upcase + srest) + singular(/#{s0.downcase}(?i)#{srest}$/, s0.downcase + srest) + singular(/#{p0.upcase}(?i)#{prest}$/, s0.upcase + srest) + singular(/#{p0.downcase}(?i)#{prest}$/, s0.downcase + srest) + end + end + + # Specifies words that are uncountable and should not be inflected. + # + # uncountable 'money' + # uncountable 'money', 'information' + # uncountable %w( money information rice ) + def uncountable(*words) + @uncountables.add(words) + end + + # Specifies a humanized form of a string by a regular expression rule or + # by a string mapping. When using a regular expression based replacement, + # the normal humanize formatting is called after the replacement. When a + # string is used, the human form should be specified as desired (example: + # 'The name', not 'the_name'). + # + # human /_cnt$/i, '\1_count' + # human 'legacy_col_person_name', 'Name' + def human(rule, replacement) + @humans.prepend([rule, replacement]) + end + + # Clears the loaded inflections within a given scope (default is + # :all). Give the scope as a symbol of the inflection type, the + # options are: :plurals, :singulars, :uncountables, + # :humans, :acronyms. + # + # clear :all + # clear :plurals + def clear(scope = :all) + case scope + when :all + clear(:acronyms) + clear(:plurals) + clear(:singulars) + clear(:uncountables) + clear(:humans) + when :acronyms + @acronyms = {} + define_acronym_regex_patterns + when :uncountables + @uncountables = Uncountables.new + when :plurals, :singulars, :humans + instance_variable_set "@#{scope}", [] + end + end + + private + def define_acronym_regex_patterns + @acronym_regex = @acronyms.empty? ? /(?=a)b/ : /#{@acronyms.values.join("|")}/ + @acronyms_camelize_regex = /^(?:#{@acronym_regex}(?=\b|[A-Z_])|\w)/ + @acronyms_underscore_regex = /(?:(?<=([A-Za-z\d]))|\b)(#{@acronym_regex})(?=\b|[^a-z])/ + end + end + + # Yields a singleton instance of Inflector::Inflections so you can specify + # additional inflector rules. If passed an optional locale, rules for other + # languages can be specified. If not specified, defaults to :en. + # Only rules for English are provided. + # + # ActiveSupport::Inflector.inflections(:en) do |inflect| + # inflect.uncountable 'rails' + # end + def inflections(locale = :en) + if block_given? + yield Inflections.instance(locale) + else + Inflections.instance_or_fallback(locale) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector/methods.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector/methods.rb new file mode 100644 index 0000000..68a00d7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector/methods.rb @@ -0,0 +1,377 @@ +# frozen_string_literal: true + +require "active_support/inflections" +require "active_support/core_ext/object/blank" + +module ActiveSupport + # The Inflector transforms words from singular to plural, class names to table + # names, modularized class names to ones without, and class names to foreign + # keys. The default inflections for pluralization, singularization, and + # uncountable words are kept in inflections.rb. + # + # The Rails core team has stated patches for the inflections library will not + # be accepted in order to avoid breaking legacy applications which may be + # relying on errant inflections. If you discover an incorrect inflection and + # require it for your application or wish to define rules for languages other + # than English, please correct or add them yourself (explained below). + module Inflector + extend self + + # Returns the plural form of the word in the string. + # + # If passed an optional +locale+ parameter, the word will be + # pluralized using rules defined for that language. By default, + # this parameter is set to :en. + # + # pluralize('post') # => "posts" + # pluralize('octopus') # => "octopi" + # pluralize('sheep') # => "sheep" + # pluralize('words') # => "words" + # pluralize('CamelOctopus') # => "CamelOctopi" + # pluralize('ley', :es) # => "leyes" + def pluralize(word, locale = :en) + apply_inflections(word, inflections(locale).plurals, locale) + end + + # The reverse of #pluralize, returns the singular form of a word in a + # string. + # + # If passed an optional +locale+ parameter, the word will be + # singularized using rules defined for that language. By default, + # this parameter is set to :en. + # + # singularize('posts') # => "post" + # singularize('octopi') # => "octopus" + # singularize('sheep') # => "sheep" + # singularize('word') # => "word" + # singularize('CamelOctopi') # => "CamelOctopus" + # singularize('leyes', :es) # => "ley" + def singularize(word, locale = :en) + apply_inflections(word, inflections(locale).singulars, locale) + end + + # Converts strings to UpperCamelCase. + # If the +uppercase_first_letter+ parameter is set to false, then produces + # lowerCamelCase. + # + # Also converts '/' to '::' which is useful for converting + # paths to namespaces. + # + # camelize('active_model') # => "ActiveModel" + # camelize('active_model', false) # => "activeModel" + # camelize('active_model/errors') # => "ActiveModel::Errors" + # camelize('active_model/errors', false) # => "activeModel::Errors" + # + # As a rule of thumb you can think of +camelize+ as the inverse of + # #underscore, though there are cases where that does not hold: + # + # camelize(underscore('SSLError')) # => "SslError" + def camelize(term, uppercase_first_letter = true) + string = term.to_s + # String#camelize takes a symbol (:upper or :lower), so here we also support :lower to keep the methods consistent. + if !uppercase_first_letter || uppercase_first_letter == :lower + string = string.sub(inflections.acronyms_camelize_regex) { |match| match.downcase! || match } + else + string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize! || match } + end + string.gsub!(/(?:_|(\/))([a-z\d]*)/i) do + word = $2 + substituted = inflections.acronyms[word] || word.capitalize! || word + $1 ? "::#{substituted}" : substituted + end + string + end + + # Makes an underscored, lowercase form from the expression in the string. + # + # Changes '::' to '/' to convert namespaces to paths. + # + # underscore('ActiveModel') # => "active_model" + # underscore('ActiveModel::Errors') # => "active_model/errors" + # + # As a rule of thumb you can think of +underscore+ as the inverse of + # #camelize, though there are cases where that does not hold: + # + # camelize(underscore('SSLError')) # => "SslError" + def underscore(camel_cased_word) + return camel_cased_word.to_s unless /[A-Z-]|::/.match?(camel_cased_word) + word = camel_cased_word.to_s.gsub("::", "/") + word.gsub!(inflections.acronyms_underscore_regex) { "#{$1 && '_' }#{$2.downcase}" } + word.gsub!(/([A-Z]+)(?=[A-Z][a-z])|([a-z\d])(?=[A-Z])/) { ($1 || $2) << "_" } + word.tr!("-", "_") + word.downcase! + word + end + + # Tweaks an attribute name for display to end users. + # + # Specifically, performs these transformations: + # + # * Applies human inflection rules to the argument. + # * Deletes leading underscores, if any. + # * Removes an "_id" suffix if present. + # * Replaces underscores with spaces, if any. + # * Downcases all words except acronyms. + # * Capitalizes the first word. + # The capitalization of the first word can be turned off by setting the + # +:capitalize+ option to false (default is true). + # + # The trailing '_id' can be kept and capitalized by setting the + # optional parameter +keep_id_suffix+ to true (default is false). + # + # humanize('employee_salary') # => "Employee salary" + # humanize('author_id') # => "Author" + # humanize('author_id', capitalize: false) # => "author" + # humanize('_id') # => "Id" + # humanize('author_id', keep_id_suffix: true) # => "Author id" + # + # If "SSL" was defined to be an acronym: + # + # humanize('ssl_error') # => "SSL error" + # + def humanize(lower_case_and_underscored_word, capitalize: true, keep_id_suffix: false) + result = lower_case_and_underscored_word.to_s.dup + + inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) } + + result.tr!("_", " ") + result.lstrip! + unless keep_id_suffix + result.delete_suffix!(" id") + end + + result.gsub!(/([a-z\d]+)/i) do |match| + match.downcase! + inflections.acronyms[match] || match + end + + if capitalize + result.sub!(/\A\w/) do |match| + match.upcase! + match + end + end + + result + end + + # Converts just the first character to uppercase. + # + # upcase_first('what a Lovely Day') # => "What a Lovely Day" + # upcase_first('w') # => "W" + # upcase_first('') # => "" + def upcase_first(string) + string.length > 0 ? string[0].upcase.concat(string[1..-1]) : "" + end + + # Capitalizes all the words and replaces some characters in the string to + # create a nicer looking title. +titleize+ is meant for creating pretty + # output. It is not used in the Rails internals. + # + # The trailing '_id','Id'.. can be kept and capitalized by setting the + # optional parameter +keep_id_suffix+ to true. + # By default, this parameter is false. + # + # +titleize+ is also aliased as +titlecase+. + # + # titleize('man from the boondocks') # => "Man From The Boondocks" + # titleize('x-men: the last stand') # => "X Men: The Last Stand" + # titleize('TheManWithoutAPast') # => "The Man Without A Past" + # titleize('raiders_of_the_lost_ark') # => "Raiders Of The Lost Ark" + # titleize('string_ending_with_id', keep_id_suffix: true) # => "String Ending With Id" + def titleize(word, keep_id_suffix: false) + humanize(underscore(word), keep_id_suffix: keep_id_suffix).gsub(/\b(? "raw_scaled_scorers" + # tableize('ham_and_egg') # => "ham_and_eggs" + # tableize('fancyCategory') # => "fancy_categories" + def tableize(class_name) + pluralize(underscore(class_name)) + end + + # Creates a class name from a plural table name like Rails does for table + # names to models. Note that this returns a string and not a Class (To + # convert to an actual class follow +classify+ with #constantize). + # + # classify('ham_and_eggs') # => "HamAndEgg" + # classify('posts') # => "Post" + # + # Singular names are not handled correctly: + # + # classify('calculus') # => "Calculu" + def classify(table_name) + # strip out any leading schema name + camelize(singularize(table_name.to_s.sub(/.*\./, ""))) + end + + # Replaces underscores with dashes in the string. + # + # dasherize('puni_puni') # => "puni-puni" + def dasherize(underscored_word) + underscored_word.tr("_", "-") + end + + # Removes the module part from the expression in the string. + # + # demodulize('ActiveSupport::Inflector::Inflections') # => "Inflections" + # demodulize('Inflections') # => "Inflections" + # demodulize('::Inflections') # => "Inflections" + # demodulize('') # => "" + # + # See also #deconstantize. + def demodulize(path) + path = path.to_s + if i = path.rindex("::") + path[(i + 2)..-1] + else + path + end + end + + # Removes the rightmost segment from the constant expression in the string. + # + # deconstantize('Net::HTTP') # => "Net" + # deconstantize('::Net::HTTP') # => "::Net" + # deconstantize('String') # => "" + # deconstantize('::String') # => "" + # deconstantize('') # => "" + # + # See also #demodulize. + def deconstantize(path) + path.to_s[0, path.rindex("::") || 0] # implementation based on the one in facets' Module#spacename + end + + # Creates a foreign key name from a class name. + # +separate_class_name_and_id_with_underscore+ sets whether + # the method should put '_' between the name and 'id'. + # + # foreign_key('Message') # => "message_id" + # foreign_key('Message', false) # => "messageid" + # foreign_key('Admin::Post') # => "post_id" + def foreign_key(class_name, separate_class_name_and_id_with_underscore = true) + underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id") + end + + # Tries to find a constant with the name specified in the argument string. + # + # constantize('Module') # => Module + # constantize('Foo::Bar') # => Foo::Bar + # + # The name is assumed to be the one of a top-level constant, no matter + # whether it starts with "::" or not. No lexical context is taken into + # account: + # + # C = 'outside' + # module M + # C = 'inside' + # C # => 'inside' + # constantize('C') # => 'outside', same as ::C + # end + # + # NameError is raised when the name is not in CamelCase or the constant is + # unknown. + def constantize(camel_cased_word) + Object.const_get(camel_cased_word) + end + + # Tries to find a constant with the name specified in the argument string. + # + # safe_constantize('Module') # => Module + # safe_constantize('Foo::Bar') # => Foo::Bar + # + # The name is assumed to be the one of a top-level constant, no matter + # whether it starts with "::" or not. No lexical context is taken into + # account: + # + # C = 'outside' + # module M + # C = 'inside' + # C # => 'inside' + # safe_constantize('C') # => 'outside', same as ::C + # end + # + # +nil+ is returned when the name is not in CamelCase or the constant (or + # part of it) is unknown. + # + # safe_constantize('blargle') # => nil + # safe_constantize('UnknownModule') # => nil + # safe_constantize('UnknownModule::Foo::Bar') # => nil + def safe_constantize(camel_cased_word) + constantize(camel_cased_word) + rescue NameError => e + raise if e.name && !(camel_cased_word.to_s.split("::").include?(e.name.to_s) || + e.name.to_s == camel_cased_word.to_s) + rescue LoadError => e + message = e.respond_to?(:original_message) ? e.original_message : e.message + raise unless /Unable to autoload constant #{const_regexp(camel_cased_word)}/.match?(message) + end + + # Returns the suffix that should be added to a number to denote the position + # in an ordered sequence such as 1st, 2nd, 3rd, 4th. + # + # ordinal(1) # => "st" + # ordinal(2) # => "nd" + # ordinal(1002) # => "nd" + # ordinal(1003) # => "rd" + # ordinal(-11) # => "th" + # ordinal(-1021) # => "st" + def ordinal(number) + I18n.translate("number.nth.ordinals", number: number) + end + + # Turns a number into an ordinal string used to denote the position in an + # ordered sequence such as 1st, 2nd, 3rd, 4th. + # + # ordinalize(1) # => "1st" + # ordinalize(2) # => "2nd" + # ordinalize(1002) # => "1002nd" + # ordinalize(1003) # => "1003rd" + # ordinalize(-11) # => "-11th" + # ordinalize(-1021) # => "-1021st" + def ordinalize(number) + I18n.translate("number.nth.ordinalized", number: number) + end + + private + # Mounts a regular expression, returned as a string to ease interpolation, + # that will match part by part the given constant. + # + # const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?" + # const_regexp("::") # => "::" + def const_regexp(camel_cased_word) + parts = camel_cased_word.split("::") + + return Regexp.escape(camel_cased_word) if parts.blank? + + last = parts.pop + + parts.reverse!.inject(last) do |acc, part| + part.empty? ? acc : "#{part}(::#{acc})?" + end + end + + # Applies inflection rules for +singularize+ and +pluralize+. + # + # If passed an optional +locale+ parameter, the uncountables will be + # found for that locale. + # + # apply_inflections('post', inflections.plurals, :en) # => "posts" + # apply_inflections('posts', inflections.singulars, :en) # => "post" + def apply_inflections(word, rules, locale = :en) + result = word.to_s.dup + + if word.empty? || inflections(locale).uncountables.uncountable?(result) + result + else + rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) } + result + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector/transliterate.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector/transliterate.rb new file mode 100644 index 0000000..c398b25 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/inflector/transliterate.rb @@ -0,0 +1,147 @@ +# frozen_string_literal: true + +require "active_support/core_ext/string/multibyte" +require "active_support/i18n" + +module ActiveSupport + module Inflector + ALLOWED_ENCODINGS_FOR_TRANSLITERATE = [Encoding::UTF_8, Encoding::US_ASCII, Encoding::GB18030].freeze + + # Replaces non-ASCII characters with an ASCII approximation, or if none + # exists, a replacement character which defaults to "?". + # + # transliterate('Ærøskøbing') + # # => "AEroskobing" + # + # Default approximations are provided for Western/Latin characters, + # e.g, "ø", "ñ", "é", "ß", etc. + # + # This method is I18n aware, so you can set up custom approximations for a + # locale. This can be useful, for example, to transliterate German's "ü" + # and "ö" to "ue" and "oe", or to add support for transliterating Russian + # to ASCII. + # + # In order to make your custom transliterations available, you must set + # them as the i18n.transliterate.rule i18n key: + # + # # Store the transliterations in locales/de.yml + # i18n: + # transliterate: + # rule: + # ü: "ue" + # ö: "oe" + # + # # Or set them using Ruby + # I18n.backend.store_translations(:de, i18n: { + # transliterate: { + # rule: { + # 'ü' => 'ue', + # 'ö' => 'oe' + # } + # } + # }) + # + # The value for i18n.transliterate.rule can be a simple Hash that + # maps characters to ASCII approximations as shown above, or, for more + # complex requirements, a Proc: + # + # I18n.backend.store_translations(:de, i18n: { + # transliterate: { + # rule: ->(string) { MyTransliterator.transliterate(string) } + # } + # }) + # + # Now you can have different transliterations for each locale: + # + # transliterate('Jürgen', locale: :en) + # # => "Jurgen" + # + # transliterate('Jürgen', locale: :de) + # # => "Juergen" + # + # Transliteration is restricted to UTF-8, US-ASCII and GB18030 strings + # Other encodings will raise an ArgumentError. + def transliterate(string, replacement = "?", locale: nil) + string = string.dup if string.frozen? + raise ArgumentError, "Can only transliterate strings. Received #{string.class.name}" unless string.is_a?(String) + raise ArgumentError, "Cannot transliterate strings with #{string.encoding} encoding" unless ALLOWED_ENCODINGS_FOR_TRANSLITERATE.include?(string.encoding) + + input_encoding = string.encoding + + # US-ASCII is a subset of UTF-8 so we'll force encoding as UTF-8 if + # US-ASCII is given. This way we can let tidy_bytes handle the string + # in the same way as we do for UTF-8 + string.force_encoding(Encoding::UTF_8) if string.encoding == Encoding::US_ASCII + + # GB18030 is Unicode compatible but is not a direct mapping so needs to be + # transcoded. Using invalid/undef :replace will result in loss of data in + # the event of invalid characters, but since tidy_bytes will replace + # invalid/undef with a "?" we're safe to do the same beforehand + string.encode!(Encoding::UTF_8, invalid: :replace, undef: :replace) if string.encoding == Encoding::GB18030 + + transliterated = I18n.transliterate( + ActiveSupport::Multibyte::Unicode.tidy_bytes(string).unicode_normalize(:nfc), + replacement: replacement, + locale: locale + ) + + # Restore the string encoding of the input if it was not UTF-8. + # Apply invalid/undef :replace as tidy_bytes does + transliterated.encode!(input_encoding, invalid: :replace, undef: :replace) if input_encoding != transliterated.encoding + + transliterated + end + + # Replaces special characters in a string so that it may be used as part of + # a 'pretty' URL. + # + # parameterize("Donald E. Knuth") # => "donald-e-knuth" + # parameterize("^très|Jolie-- ") # => "tres-jolie" + # + # To use a custom separator, override the +separator+ argument. + # + # parameterize("Donald E. Knuth", separator: '_') # => "donald_e_knuth" + # parameterize("^très|Jolie__ ", separator: '_') # => "tres_jolie" + # + # To preserve the case of the characters in a string, use the +preserve_case+ argument. + # + # parameterize("Donald E. Knuth", preserve_case: true) # => "Donald-E-Knuth" + # parameterize("^très|Jolie-- ", preserve_case: true) # => "tres-Jolie" + # + # It preserves dashes and underscores unless they are used as separators: + # + # parameterize("^très|Jolie__ ") # => "tres-jolie__" + # parameterize("^très|Jolie-- ", separator: "_") # => "tres_jolie--" + # parameterize("^très_Jolie-- ", separator: ".") # => "tres_jolie--" + # + # If the optional parameter +locale+ is specified, + # the word will be parameterized as a word of that language. + # By default, this parameter is set to nil and it will use + # the configured I18n.locale. + def parameterize(string, separator: "-", preserve_case: false, locale: nil) + # Replace accented chars with their ASCII equivalents. + parameterized_string = transliterate(string, locale: locale) + + # Turn unwanted chars into the separator. + parameterized_string.gsub!(/[^a-z0-9\-_]+/i, separator) + + unless separator.nil? || separator.empty? + if separator == "-" + re_duplicate_separator = /-{2,}/ + re_leading_trailing_separator = /^-|-$/i + else + re_sep = Regexp.escape(separator) + re_duplicate_separator = /#{re_sep}{2,}/ + re_leading_trailing_separator = /^#{re_sep}|#{re_sep}$/i + end + # No more than one of the separator in a row. + parameterized_string.gsub!(re_duplicate_separator, separator) + # Remove leading/trailing separator. + parameterized_string.gsub!(re_leading_trailing_separator, "") + end + + parameterized_string.downcase! unless preserve_case + parameterized_string + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/isolated_execution_state.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/isolated_execution_state.rb new file mode 100644 index 0000000..d6322ff --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/isolated_execution_state.rb @@ -0,0 +1,64 @@ +# frozen_string_literal: true + +require "fiber" + +module ActiveSupport + module IsolatedExecutionState # :nodoc: + @isolation_level = :thread + + Thread.attr_accessor :active_support_execution_state + Fiber.attr_accessor :active_support_execution_state + + class << self + attr_reader :isolation_level + + def isolation_level=(level) + unless %i(thread fiber).include?(level) + raise ArgumentError, "isolation_level must be `:thread` or `:fiber`, got: `#{level.inspect}`" + end + + if level != isolation_level + clear + singleton_class.alias_method(:current, "current_#{level}") + singleton_class.send(:private, :current) + @isolation_level = level + end + end + + def unique_id + self[:__id__] ||= Object.new + end + + def [](key) + current[key] + end + + def []=(key, value) + current[key] = value + end + + def key?(key) + current.key?(key) + end + + def delete(key) + current.delete(key) + end + + def clear + current.clear + end + + private + def current_thread + Thread.current.active_support_execution_state ||= {} + end + + def current_fiber + Fiber.current.active_support_execution_state ||= {} + end + + alias_method :current, :current_thread + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/json.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/json.rb new file mode 100644 index 0000000..d788717 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/json.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +require "active_support/json/decoding" +require "active_support/json/encoding" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/json/decoding.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/json/decoding.rb new file mode 100644 index 0000000..e40957e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/json/decoding.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/attribute_accessors" +require "active_support/core_ext/module/delegation" +require "json" + +module ActiveSupport + # Look for and parse json strings that look like ISO 8601 times. + mattr_accessor :parse_json_times + + module JSON + # matches YAML-formatted dates + DATE_REGEX = /\A\d{4}-\d{2}-\d{2}\z/ + DATETIME_REGEX = /\A(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?)?)\z/ + + class << self + # Parses a JSON string (JavaScript Object Notation) into a hash. + # See http://www.json.org for more info. + # + # ActiveSupport::JSON.decode("{\"team\":\"rails\",\"players\":\"36\"}") + # => {"team" => "rails", "players" => "36"} + def decode(json) + data = ::JSON.parse(json, quirks_mode: true) + + if ActiveSupport.parse_json_times + convert_dates_from(data) + else + data + end + end + + # Returns the class of the error that will be raised when there is an + # error in decoding JSON. Using this method means you won't directly + # depend on the ActiveSupport's JSON implementation, in case it changes + # in the future. + # + # begin + # obj = ActiveSupport::JSON.decode(some_string) + # rescue ActiveSupport::JSON.parse_error + # Rails.logger.warn("Attempted to decode invalid JSON: #{some_string}") + # end + def parse_error + ::JSON::ParserError + end + + private + def convert_dates_from(data) + case data + when nil + nil + when DATE_REGEX + begin + Date.parse(data) + rescue ArgumentError + data + end + when DATETIME_REGEX + begin + Time.zone.parse(data) + rescue ArgumentError + data + end + when Array + data.map! { |d| convert_dates_from(d) } + when Hash + data.transform_values! do |value| + convert_dates_from(value) + end + else + data + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/json/encoding.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/json/encoding.rb new file mode 100644 index 0000000..8e08b24 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/json/encoding.rb @@ -0,0 +1,138 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/json" +require "active_support/core_ext/module/delegation" + +module ActiveSupport + class << self + delegate :use_standard_json_time_format, :use_standard_json_time_format=, + :time_precision, :time_precision=, + :escape_html_entities_in_json, :escape_html_entities_in_json=, + :json_encoder, :json_encoder=, + to: :'ActiveSupport::JSON::Encoding' + end + + module JSON + # Dumps objects in JSON (JavaScript Object Notation). + # See http://www.json.org for more info. + # + # ActiveSupport::JSON.encode({ team: 'rails', players: '36' }) + # # => "{\"team\":\"rails\",\"players\":\"36\"}" + def self.encode(value, options = nil) + Encoding.json_encoder.new(options).encode(value) + end + + module Encoding # :nodoc: + class JSONGemEncoder # :nodoc: + attr_reader :options + + def initialize(options = nil) + @options = options || {} + end + + # Encode the given object into a JSON string + def encode(value) + stringify jsonify value.as_json(options.dup) + end + + private + # Rails does more escaping than the JSON gem natively does (we + # escape \u2028 and \u2029 and optionally >, <, & to work around + # certain browser problems). + ESCAPED_CHARS = { + "\u2028" => '\u2028', + "\u2029" => '\u2029', + ">" => '\u003e', + "<" => '\u003c', + "&" => '\u0026', + } + + ESCAPE_REGEX_WITH_HTML_ENTITIES = /[\u2028\u2029><&]/u + ESCAPE_REGEX_WITHOUT_HTML_ENTITIES = /[\u2028\u2029]/u + + # This class wraps all the strings we see and does the extra escaping + class EscapedString < String # :nodoc: + def to_json(*) + if Encoding.escape_html_entities_in_json + s = super + s.gsub! ESCAPE_REGEX_WITH_HTML_ENTITIES, ESCAPED_CHARS + s + else + s = super + s.gsub! ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, ESCAPED_CHARS + s + end + end + + def to_s + self + end + end + + # Mark these as private so we don't leak encoding-specific constructs + private_constant :ESCAPED_CHARS, :ESCAPE_REGEX_WITH_HTML_ENTITIES, + :ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, :EscapedString + + # Convert an object into a "JSON-ready" representation composed of + # primitives like Hash, Array, String, Numeric, + # and +true+/+false+/+nil+. + # Recursively calls #as_json to the object to recursively build a + # fully JSON-ready object. + # + # This allows developers to implement #as_json without having to + # worry about what base types of objects they are allowed to return + # or having to remember to call #as_json recursively. + # + # Note: the +options+ hash passed to +object.to_json+ is only passed + # to +object.as_json+, not any of this method's recursive +#as_json+ + # calls. + def jsonify(value) + case value + when String + EscapedString.new(value) + when Numeric, NilClass, TrueClass, FalseClass + value.as_json + when Hash + result = {} + value.each do |k, v| + result[jsonify(k)] = jsonify(v) + end + result + when Array + value.map { |v| jsonify(v) } + else + jsonify value.as_json + end + end + + # Encode a "jsonified" Ruby data structure using the JSON gem + def stringify(jsonified) + ::JSON.generate(jsonified, quirks_mode: true, max_nesting: false) + end + end + + class << self + # If true, use ISO 8601 format for dates and times. Otherwise, fall back + # to the Active Support legacy format. + attr_accessor :use_standard_json_time_format + + # If true, encode >, <, & as escaped unicode sequences (e.g. > as \u003e) + # as a safety measure. + attr_accessor :escape_html_entities_in_json + + # Sets the precision of encoded time values. + # Defaults to 3 (equivalent to millisecond precision) + attr_accessor :time_precision + + # Sets the encoder used by Rails to encode Ruby objects into JSON strings + # in +Object#to_json+ and +ActiveSupport::JSON.encode+. + attr_accessor :json_encoder + end + + self.use_standard_json_time_format = true + self.escape_html_entities_in_json = true + self.json_encoder = JSONGemEncoder + self.time_precision = 3 + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/key_generator.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/key_generator.rb new file mode 100644 index 0000000..8312a35 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/key_generator.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true + +require "concurrent/map" +require "openssl" + +module ActiveSupport + # KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2. + # It can be used to derive a number of keys for various purposes from a given secret. + # This lets Rails applications have a single secure secret, but avoid reusing that + # key in multiple incompatible contexts. + class KeyGenerator + class << self + def hash_digest_class=(klass) + if klass.kind_of?(Class) && klass < OpenSSL::Digest + @hash_digest_class = klass + else + raise ArgumentError, "#{klass} is expected to be an OpenSSL::Digest subclass" + end + end + + def hash_digest_class + @hash_digest_class ||= OpenSSL::Digest::SHA1 + end + end + + def initialize(secret, options = {}) + @secret = secret + # The default iterations are higher than required for our key derivation uses + # on the off chance someone uses this for password storage + @iterations = options[:iterations] || 2**16 + # Also allow configuration here so people can use this to build a rotation + # scheme when switching the digest class. + @hash_digest_class = options[:hash_digest_class] || self.class.hash_digest_class + end + + # Returns a derived key suitable for use. The default key_size is chosen + # to be compatible with the default settings of ActiveSupport::MessageVerifier. + # i.e. OpenSSL::Digest::SHA1#block_length + def generate_key(salt, key_size = 64) + OpenSSL::PKCS5.pbkdf2_hmac(@secret, salt, @iterations, key_size, @hash_digest_class.new) + end + end + + # CachingKeyGenerator is a wrapper around KeyGenerator which allows users to avoid + # re-executing the key generation process when it's called using the same salt and + # key_size. + class CachingKeyGenerator + def initialize(key_generator) + @key_generator = key_generator + @cache_keys = Concurrent::Map.new + end + + # Returns a derived key suitable for use. + def generate_key(*args) + @cache_keys[args.join("|")] ||= @key_generator.generate_key(*args) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/lazy_load_hooks.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/lazy_load_hooks.rb new file mode 100644 index 0000000..c6f7ccf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/lazy_load_hooks.rb @@ -0,0 +1,81 @@ +# frozen_string_literal: true + +module ActiveSupport + # lazy_load_hooks allows Rails to lazily load a lot of components and thus + # making the app boot faster. Because of this feature now there is no need to + # require ActiveRecord::Base at boot time purely to apply + # configuration. Instead a hook is registered that applies configuration once + # ActiveRecord::Base is loaded. Here ActiveRecord::Base is + # used as example but this feature can be applied elsewhere too. + # + # Here is an example where +on_load+ method is called to register a hook. + # + # initializer 'active_record.initialize_timezone' do + # ActiveSupport.on_load(:active_record) do + # self.time_zone_aware_attributes = true + # self.default_timezone = :utc + # end + # end + # + # When the entirety of +ActiveRecord::Base+ has been + # evaluated then +run_load_hooks+ is invoked. The very last line of + # +ActiveRecord::Base+ is: + # + # ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base) + module LazyLoadHooks + def self.extended(base) # :nodoc: + base.class_eval do + @load_hooks = Hash.new { |h, k| h[k] = [] } + @loaded = Hash.new { |h, k| h[k] = [] } + @run_once = Hash.new { |h, k| h[k] = [] } + end + end + + # Declares a block that will be executed when a Rails component is fully + # loaded. + # + # Options: + # + # * :yield - Yields the object that run_load_hooks to +block+. + # * :run_once - Given +block+ will run only once. + def on_load(name, options = {}, &block) + @loaded[name].each do |base| + execute_hook(name, base, options, block) + end + + @load_hooks[name] << [block, options] + end + + def run_load_hooks(name, base = Object) + @loaded[name] << base + @load_hooks[name].each do |hook, options| + execute_hook(name, base, options, hook) + end + end + + private + def with_execution_control(name, block, once) + unless @run_once[name].include?(block) + @run_once[name] << block if once + + yield + end + end + + def execute_hook(name, base, options, block) + with_execution_control(name, block, options[:run_once]) do + if options[:yield] + block.call(base) + else + if base.is_a?(Module) + base.class_eval(&block) + else + base.instance_eval(&block) + end + end + end + end + end + + extend LazyLoadHooks +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/locale/en.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/locale/en.rb new file mode 100644 index 0000000..29eb9de --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/locale/en.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +{ + en: { + number: { + nth: { + ordinals: lambda do |_key, options| + number = options[:number] + case number + when 1; "st" + when 2; "nd" + when 3; "rd" + when 4, 5, 6, 7, 8, 9, 10, 11, 12, 13; "th" + else + num_modulo = number.to_i.abs % 100 + num_modulo %= 10 if num_modulo > 13 + case num_modulo + when 1; "st" + when 2; "nd" + when 3; "rd" + else "th" + end + end + end, + + ordinalized: lambda do |_key, options| + number = options[:number] + "#{number}#{ActiveSupport::Inflector.ordinal(number)}" + end + } + } + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/locale/en.yml b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/locale/en.yml new file mode 100644 index 0000000..0453883 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/locale/en.yml @@ -0,0 +1,139 @@ +en: + date: + formats: + # Use the strftime parameters for formats. + # When no format has been given, it uses default. + # You can provide other formats here if you like! + default: "%Y-%m-%d" + short: "%b %d" + long: "%B %d, %Y" + + day_names: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] + abbr_day_names: [Sun, Mon, Tue, Wed, Thu, Fri, Sat] + + # Don't forget the nil at the beginning; there's no such thing as a 0th month + month_names: [~, January, February, March, April, May, June, July, August, September, October, November, December] + abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec] + # Used in date_select and datetime_select. + order: + - year + - month + - day + + time: + formats: + default: "%a, %d %b %Y %H:%M:%S %z" + short: "%d %b %H:%M" + long: "%B %d, %Y %H:%M" + am: "am" + pm: "pm" + +# Used in array.to_sentence. + support: + array: + words_connector: ", " + two_words_connector: " and " + last_word_connector: ", and " + number: + # Used in NumberHelper.number_to_delimited() + # These are also the defaults for 'currency', 'percentage', 'precision', and 'human' + format: + # Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5) + separator: "." + # Delimits thousands (e.g. 1,000,000 is a million) (always in groups of three) + delimiter: "," + # Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00) + precision: 3 + # Determine how rounding is performed (see BigDecimal::mode) + round_mode: default + # If set to true, precision will mean the number of significant digits instead + # of the number of decimal digits (1234 with precision 2 becomes 1200, 1.23543 becomes 1.2) + significant: false + # If set, the zeros after the decimal separator will always be stripped (e.g.: 1.200 will be 1.2) + strip_insignificant_zeros: false + + # Used in NumberHelper.number_to_currency() + currency: + format: + # Where is the currency sign? %u is the currency unit, %n is the number (default: $5.00) + format: "%u%n" + unit: "$" + # These six are to override number.format and are optional + separator: "." + delimiter: "," + precision: 2 + # round_mode: + significant: false + strip_insignificant_zeros: false + + # Used in NumberHelper.number_to_percentage() + percentage: + format: + # These five are to override number.format and are optional + # separator: + delimiter: "" + # precision: + # significant: false + # strip_insignificant_zeros: false + format: "%n%" + + # Used in NumberHelper.number_to_rounded() + precision: + format: + # These five are to override number.format and are optional + # separator: + delimiter: "" + # precision: + # significant: false + # strip_insignificant_zeros: false + + # Used in NumberHelper.number_to_human_size() and NumberHelper.number_to_human() + human: + format: + # These six are to override number.format and are optional + # separator: + delimiter: "" + precision: 3 + # round_mode: + significant: true + strip_insignificant_zeros: true + # Used in number_to_human_size() + storage_units: + # Storage units output formatting. + # %u is the storage unit, %n is the number (default: 2 MB) + format: "%n %u" + units: + byte: + one: "Byte" + other: "Bytes" + kb: "KB" + mb: "MB" + gb: "GB" + tb: "TB" + pb: "PB" + eb: "EB" + # Used in NumberHelper.number_to_human() + decimal_units: + format: "%n %u" + # Decimal units output formatting + # By default we will only quantify some of the exponents + # but the commented ones might be defined or overridden + # by the user. + units: + # femto: Quadrillionth + # pico: Trillionth + # nano: Billionth + # micro: Millionth + # mili: Thousandth + # centi: Hundredth + # deci: Tenth + unit: "" + # ten: + # one: Ten + # other: Tens + # hundred: Hundred + thousand: Thousand + million: Million + billion: Billion + trillion: Trillion + quadrillion: Quadrillion diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/log_subscriber.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/log_subscriber.rb new file mode 100644 index 0000000..29a6941 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/log_subscriber.rb @@ -0,0 +1,152 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/attribute_accessors" +require "active_support/core_ext/class/attribute" +require "active_support/subscriber" + +module ActiveSupport + # ActiveSupport::LogSubscriber is an object set to consume + # ActiveSupport::Notifications with the sole purpose of logging them. + # The log subscriber dispatches notifications to a registered object based + # on its given namespace. + # + # An example would be Active Record log subscriber responsible for logging + # queries: + # + # module ActiveRecord + # class LogSubscriber < ActiveSupport::LogSubscriber + # def sql(event) + # info "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}" + # end + # end + # end + # + # And it's finally registered as: + # + # ActiveRecord::LogSubscriber.attach_to :active_record + # + # Since we need to know all instance methods before attaching the log + # subscriber, the line above should be called after your + # ActiveRecord::LogSubscriber definition. + # + # A logger also needs to be set with ActiveRecord::LogSubscriber.logger=. + # This is assigned automatically in a Rails environment. + # + # After configured, whenever a "sql.active_record" notification is published, + # it will properly dispatch the event + # (ActiveSupport::Notifications::Event) to the sql method. + # + # Being an ActiveSupport::Notifications consumer, + # ActiveSupport::LogSubscriber exposes a simple interface to check if + # instrumented code raises an exception. It is common to log a different + # message in case of an error, and this can be achieved by extending + # the previous example: + # + # module ActiveRecord + # class LogSubscriber < ActiveSupport::LogSubscriber + # def sql(event) + # exception = event.payload[:exception] + # + # if exception + # exception_object = event.payload[:exception_object] + # + # error "[ERROR] #{event.payload[:name]}: #{exception.join(', ')} " \ + # "(#{exception_object.backtrace.first})" + # else + # # standard logger code + # end + # end + # end + # end + # + # Log subscriber also has some helpers to deal with logging and automatically + # flushes all logs when the request finishes + # (via action_dispatch.callback notification) in a Rails environment. + class LogSubscriber < Subscriber + # Embed in a String to clear all previous ANSI sequences. + CLEAR = "\e[0m" + BOLD = "\e[1m" + + # Colors + BLACK = "\e[30m" + RED = "\e[31m" + GREEN = "\e[32m" + YELLOW = "\e[33m" + BLUE = "\e[34m" + MAGENTA = "\e[35m" + CYAN = "\e[36m" + WHITE = "\e[37m" + + mattr_accessor :colorize_logging, default: true + + class << self + def logger + @logger ||= if defined?(Rails) && Rails.respond_to?(:logger) + Rails.logger + end + end + + attr_writer :logger + + def log_subscribers + subscribers + end + + # Flush all log_subscribers' logger. + def flush_all! + logger.flush if logger.respond_to?(:flush) + end + + private + def fetch_public_methods(subscriber, inherit_all) + subscriber.public_methods(inherit_all) - LogSubscriber.public_instance_methods(true) + end + end + + def logger + LogSubscriber.logger + end + + def start(name, id, payload) + super if logger + end + + def finish(name, id, payload) + super if logger + rescue => e + log_exception(name, e) + end + + def publish_event(event) + super if logger + rescue => e + log_exception(event.name, e) + end + + private + %w(info debug warn error fatal unknown).each do |level| + class_eval <<-METHOD, __FILE__, __LINE__ + 1 + def #{level}(progname = nil, &block) + logger.#{level}(progname, &block) if logger + end + METHOD + end + + # Set color by using a symbol or one of the defined constants. If a third + # option is set to +true+, it also adds bold to the string. This is based + # on the Highline implementation and will automatically append CLEAR to the + # end of the returned String. + def color(text, color, bold = false) # :doc: + return text unless colorize_logging + color = self.class.const_get(color.upcase) if color.is_a?(Symbol) + bold = bold ? BOLD : "" + "#{bold}#{color}#{text}#{CLEAR}" + end + + def log_exception(name, e) + if logger + logger.error "Could not log #{name.inspect} event. #{e.class}: #{e.message} #{e.backtrace}" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/log_subscriber/test_helper.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/log_subscriber/test_helper.rb new file mode 100644 index 0000000..3f19ef5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/log_subscriber/test_helper.rb @@ -0,0 +1,106 @@ +# frozen_string_literal: true + +require "active_support/log_subscriber" +require "active_support/logger" +require "active_support/notifications" + +module ActiveSupport + class LogSubscriber + # Provides some helpers to deal with testing log subscribers by setting up + # notifications. Take for instance Active Record subscriber tests: + # + # class SyncLogSubscriberTest < ActiveSupport::TestCase + # include ActiveSupport::LogSubscriber::TestHelper + # + # setup do + # ActiveRecord::LogSubscriber.attach_to(:active_record) + # end + # + # def test_basic_query_logging + # Developer.all.to_a + # wait + # assert_equal 1, @logger.logged(:debug).size + # assert_match(/Developer Load/, @logger.logged(:debug).last) + # assert_match(/SELECT \* FROM "developers"/, @logger.logged(:debug).last) + # end + # end + # + # All you need to do is to ensure that your log subscriber is added to + # Rails::Subscriber, as in the second line of the code above. The test + # helpers are responsible for setting up the queue, subscriptions and + # turning colors in logs off. + # + # The messages are available in the @logger instance, which is a logger with + # limited powers (it actually does not send anything to your output), and + # you can collect them doing @logger.logged(level), where level is the level + # used in logging, like info, debug, warn and so on. + module TestHelper + def setup # :nodoc: + @logger = MockLogger.new + @notifier = ActiveSupport::Notifications::Fanout.new + + ActiveSupport::LogSubscriber.colorize_logging = false + + @old_notifier = ActiveSupport::Notifications.notifier + set_logger(@logger) + ActiveSupport::Notifications.notifier = @notifier + end + + def teardown # :nodoc: + set_logger(nil) + ActiveSupport::Notifications.notifier = @old_notifier + end + + class MockLogger + include ActiveSupport::Logger::Severity + + attr_reader :flush_count + attr_accessor :level + + def initialize(level = DEBUG) + @flush_count = 0 + @level = level + @logged = Hash.new { |h, k| h[k] = [] } + end + + def method_missing(level, message = nil) + if block_given? + @logged[level] << yield + else + @logged[level] << message + end + end + + def logged(level) + @logged[level].compact.map { |l| l.to_s.strip } + end + + def flush + @flush_count += 1 + end + + ActiveSupport::Logger::Severity.constants.each do |severity| + class_eval <<-EOT, __FILE__, __LINE__ + 1 + def #{severity.downcase}? + #{severity} >= @level + end + EOT + end + end + + # Wait notifications to be published. + def wait + @notifier.wait + end + + # Overwrite if you use another logger in your log subscriber. + # + # def logger + # ActiveRecord::Base.logger = @logger + # end + def set_logger(logger) + ActiveSupport::LogSubscriber.logger = logger + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/logger.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/logger.rb new file mode 100644 index 0000000..1e241c1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/logger.rb @@ -0,0 +1,93 @@ +# frozen_string_literal: true + +require "active_support/logger_silence" +require "active_support/logger_thread_safe_level" +require "logger" + +module ActiveSupport + class Logger < ::Logger + include LoggerSilence + + # Returns true if the logger destination matches one of the sources + # + # logger = Logger.new(STDOUT) + # ActiveSupport::Logger.logger_outputs_to?(logger, STDOUT) + # # => true + def self.logger_outputs_to?(logger, *sources) + logdev = logger.instance_variable_get(:@logdev) + logger_source = logdev.dev if logdev.respond_to?(:dev) + sources.any? { |source| source == logger_source } + end + + # Broadcasts logs to multiple loggers. + def self.broadcast(logger) # :nodoc: + Module.new do + define_method(:add) do |*args, &block| + logger.add(*args, &block) + super(*args, &block) + end + + define_method(:<<) do |x| + logger << x + super(x) + end + + define_method(:close) do + logger.close + super() + end + + define_method(:progname=) do |name| + logger.progname = name + super(name) + end + + define_method(:formatter=) do |formatter| + logger.formatter = formatter + super(formatter) + end + + define_method(:level=) do |level| + logger.level = level + super(level) + end + + define_method(:local_level=) do |level| + logger.local_level = level if logger.respond_to?(:local_level=) + super(level) if respond_to?(:local_level=) + end + + define_method(:silence) do |level = Logger::ERROR, &block| + if logger.respond_to?(:silence) + logger.silence(level) do + if defined?(super) + super(level, &block) + else + block.call(self) + end + end + else + if defined?(super) + super(level, &block) + else + block.call(self) + end + end + end + end + end + + def initialize(*args, **kwargs) + super + @formatter = SimpleFormatter.new + end + + # Simple formatter which only displays the message. + class SimpleFormatter < ::Logger::Formatter + # This method is invoked when a log event occurs + def call(severity, timestamp, progname, msg) + "#{String === msg ? msg : msg.inspect}\n" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/logger_silence.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/logger_silence.rb new file mode 100644 index 0000000..8567eff --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/logger_silence.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +require "active_support/concern" +require "active_support/core_ext/module/attribute_accessors" +require "active_support/logger_thread_safe_level" + +module ActiveSupport + module LoggerSilence + extend ActiveSupport::Concern + + included do + cattr_accessor :silencer, default: true + include ActiveSupport::LoggerThreadSafeLevel + end + + # Silences the logger for the duration of the block. + def silence(severity = Logger::ERROR) + silencer ? log_at(severity) { yield self } : yield(self) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/logger_thread_safe_level.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/logger_thread_safe_level.rb new file mode 100644 index 0000000..042f484 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/logger_thread_safe_level.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true + +require "active_support/concern" +require "active_support/core_ext/module/attribute_accessors" +require "concurrent" +require "fiber" + +module ActiveSupport + module LoggerThreadSafeLevel # :nodoc: + extend ActiveSupport::Concern + + Logger::Severity.constants.each do |severity| + class_eval(<<-EOT, __FILE__, __LINE__ + 1) + def #{severity.downcase}? # def debug? + Logger::#{severity} >= level # DEBUG >= level + end # end + EOT + end + + def local_level + IsolatedExecutionState[:logger_thread_safe_level] + end + + def local_level=(level) + case level + when Integer + when Symbol + level = Logger::Severity.const_get(level.to_s.upcase) + when nil + else + raise ArgumentError, "Invalid log level: #{level.inspect}" + end + IsolatedExecutionState[:logger_thread_safe_level] = level + end + + def level + local_level || super + end + + # Change the thread-local level for the duration of the given block. + def log_at(level) + old_local_level, self.local_level = local_level, level + yield + ensure + self.local_level = old_local_level + end + + # Redefined to check severity against #level, and thus the thread-local level, rather than +@level+. + # FIXME: Remove when the minimum Ruby version supports overriding Logger#level. + def add(severity, message = nil, progname = nil, &block) # :nodoc: + severity ||= UNKNOWN + progname ||= @progname + + return true if @logdev.nil? || severity < level + + if message.nil? + if block_given? + message = yield + else + message = progname + progname = @progname + end + end + + @logdev.write \ + format_message(format_severity(severity), Time.now, progname, message) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/message_encryptor.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/message_encryptor.rb new file mode 100644 index 0000000..634ffba --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/message_encryptor.rb @@ -0,0 +1,229 @@ +# frozen_string_literal: true + +require "openssl" +require "base64" +require "active_support/core_ext/module/attribute_accessors" +require "active_support/message_verifier" +require "active_support/messages/metadata" + +module ActiveSupport + # MessageEncryptor is a simple way to encrypt values which get stored + # somewhere you don't trust. + # + # The cipher text and initialization vector are base64 encoded and returned + # to you. + # + # This can be used in situations similar to the MessageVerifier, but + # where you don't want users to be able to determine the value of the payload. + # + # len = ActiveSupport::MessageEncryptor.key_len + # salt = SecureRandom.random_bytes(len) + # key = ActiveSupport::KeyGenerator.new('password').generate_key(salt, len) # => "\x89\xE0\x156\xAC..." + # crypt = ActiveSupport::MessageEncryptor.new(key) # => # + # encrypted_data = crypt.encrypt_and_sign('my secret data') # => "NlFBTTMwOUV5UlA1QlNEN2xkY2d6eThYWWh..." + # crypt.decrypt_and_verify(encrypted_data) # => "my secret data" + # The +decrypt_and_verify+ method will raise an + # ActiveSupport::MessageEncryptor::InvalidMessage exception if the data + # provided cannot be decrypted or verified. + # + # crypt.decrypt_and_verify('not encrypted data') # => ActiveSupport::MessageEncryptor::InvalidMessage + # + # === Confining messages to a specific purpose + # + # By default any message can be used throughout your app. But they can also be + # confined to a specific +:purpose+. + # + # token = crypt.encrypt_and_sign("this is the chair", purpose: :login) + # + # Then that same purpose must be passed when verifying to get the data back out: + # + # crypt.decrypt_and_verify(token, purpose: :login) # => "this is the chair" + # crypt.decrypt_and_verify(token, purpose: :shipping) # => nil + # crypt.decrypt_and_verify(token) # => nil + # + # Likewise, if a message has no purpose it won't be returned when verifying with + # a specific purpose. + # + # token = crypt.encrypt_and_sign("the conversation is lively") + # crypt.decrypt_and_verify(token, purpose: :scare_tactics) # => nil + # crypt.decrypt_and_verify(token) # => "the conversation is lively" + # + # === Making messages expire + # + # By default messages last forever and verifying one year from now will still + # return the original value. But messages can be set to expire at a given + # time with +:expires_in+ or +:expires_at+. + # + # crypt.encrypt_and_sign(parcel, expires_in: 1.month) + # crypt.encrypt_and_sign(doowad, expires_at: Time.now.end_of_year) + # + # Then the messages can be verified and returned up to the expire time. + # Thereafter, verifying returns +nil+. + # + # === Rotating keys + # + # MessageEncryptor also supports rotating out old configurations by falling + # back to a stack of encryptors. Call +rotate+ to build and add an encryptor + # so +decrypt_and_verify+ will also try the fallback. + # + # By default any rotated encryptors use the values of the primary + # encryptor unless specified otherwise. + # + # You'd give your encryptor the new defaults: + # + # crypt = ActiveSupport::MessageEncryptor.new(@secret, cipher: "aes-256-gcm") + # + # Then gradually rotate the old values out by adding them as fallbacks. Any message + # generated with the old values will then work until the rotation is removed. + # + # crypt.rotate old_secret # Fallback to an old secret instead of @secret. + # crypt.rotate cipher: "aes-256-cbc" # Fallback to an old cipher instead of aes-256-gcm. + # + # Though if both the secret and the cipher was changed at the same time, + # the above should be combined into: + # + # crypt.rotate old_secret, cipher: "aes-256-cbc" + class MessageEncryptor + prepend Messages::Rotator::Encryptor + + cattr_accessor :use_authenticated_message_encryption, instance_accessor: false, default: false + + class << self + def default_cipher # :nodoc: + if use_authenticated_message_encryption + "aes-256-gcm" + else + "aes-256-cbc" + end + end + end + + module NullSerializer # :nodoc: + def self.load(value) + value + end + + def self.dump(value) + value + end + end + + module NullVerifier # :nodoc: + def self.verify(value) + value + end + + def self.generate(value) + value + end + end + + class InvalidMessage < StandardError; end + OpenSSLCipherError = OpenSSL::Cipher::CipherError + + # Initialize a new MessageEncryptor. +secret+ must be at least as long as + # the cipher key size. For the default 'aes-256-gcm' cipher, this is 256 + # bits. If you are using a user-entered secret, you can generate a suitable + # key by using ActiveSupport::KeyGenerator or a similar key + # derivation function. + # + # First additional parameter is used as the signature key for +MessageVerifier+. + # This allows you to specify keys to encrypt and sign data. + # + # ActiveSupport::MessageEncryptor.new('secret', 'signature_secret') + # + # Options: + # * :cipher - Cipher to use. Can be any cipher returned by + # OpenSSL::Cipher.ciphers. Default is 'aes-256-gcm'. + # * :digest - String of digest to use for signing. Default is + # +SHA1+. Ignored when using an AEAD cipher like 'aes-256-gcm'. + # * :serializer - Object serializer to use. Default is +Marshal+. + def initialize(secret, sign_secret = nil, cipher: nil, digest: nil, serializer: nil) + @secret = secret + @sign_secret = sign_secret + @cipher = cipher || self.class.default_cipher + @digest = digest || "SHA1" unless aead_mode? + @verifier = resolve_verifier + @serializer = serializer || Marshal + end + + # Encrypt and sign a message. We need to sign the message in order to avoid + # padding attacks. Reference: https://www.limited-entropy.com/padding-oracle-attacks/. + def encrypt_and_sign(value, expires_at: nil, expires_in: nil, purpose: nil) + verifier.generate(_encrypt(value, expires_at: expires_at, expires_in: expires_in, purpose: purpose)) + end + + # Decrypt and verify a message. We need to verify the message in order to + # avoid padding attacks. Reference: https://www.limited-entropy.com/padding-oracle-attacks/. + def decrypt_and_verify(data, purpose: nil, **) + _decrypt(verifier.verify(data), purpose) + end + + # Given a cipher, returns the key length of the cipher to help generate the key of desired size + def self.key_len(cipher = default_cipher) + OpenSSL::Cipher.new(cipher).key_len + end + + private + def _encrypt(value, **metadata_options) + cipher = new_cipher + cipher.encrypt + cipher.key = @secret + + # Rely on OpenSSL for the initialization vector + iv = cipher.random_iv + cipher.auth_data = "" if aead_mode? + + encrypted_data = cipher.update(Messages::Metadata.wrap(@serializer.dump(value), **metadata_options)) + encrypted_data << cipher.final + + blob = "#{::Base64.strict_encode64 encrypted_data}--#{::Base64.strict_encode64 iv}" + blob = "#{blob}--#{::Base64.strict_encode64 cipher.auth_tag}" if aead_mode? + blob + end + + def _decrypt(encrypted_message, purpose) + cipher = new_cipher + encrypted_data, iv, auth_tag = encrypted_message.split("--").map { |v| ::Base64.strict_decode64(v) } + + # Currently the OpenSSL bindings do not raise an error if auth_tag is + # truncated, which would allow an attacker to easily forge it. See + # https://github.com/ruby/openssl/issues/63 + raise InvalidMessage if aead_mode? && (auth_tag.nil? || auth_tag.bytes.length != 16) + + cipher.decrypt + cipher.key = @secret + cipher.iv = iv + if aead_mode? + cipher.auth_tag = auth_tag + cipher.auth_data = "" + end + + decrypted_data = cipher.update(encrypted_data) + decrypted_data << cipher.final + + message = Messages::Metadata.verify(decrypted_data, purpose) + @serializer.load(message) if message + rescue OpenSSLCipherError, TypeError, ArgumentError + raise InvalidMessage + end + + def new_cipher + OpenSSL::Cipher.new(@cipher) + end + + attr_reader :verifier + + def aead_mode? + @aead_mode ||= new_cipher.authenticated? + end + + def resolve_verifier + if aead_mode? + NullVerifier + else + MessageVerifier.new(@sign_secret || @secret, digest: @digest, serializer: NullSerializer) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/message_verifier.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/message_verifier.rb new file mode 100644 index 0000000..c224bdc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/message_verifier.rb @@ -0,0 +1,237 @@ +# frozen_string_literal: true + +require "openssl" +require "base64" +require "active_support/core_ext/object/blank" +require "active_support/security_utils" +require "active_support/messages/metadata" +require "active_support/messages/rotator" + +module ActiveSupport + # +MessageVerifier+ makes it easy to generate and verify messages which are + # signed to prevent tampering. + # + # This is useful for cases like remember-me tokens and auto-unsubscribe links + # where the session store isn't suitable or available. + # + # Remember Me: + # cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now]) + # + # In the authentication filter: + # + # id, time = @verifier.verify(cookies[:remember_me]) + # if Time.now < time + # self.current_user = User.find(id) + # end + # + # By default it uses Marshal to serialize the message. If you want to use + # another serialization method, you can set the serializer in the options + # hash upon initialization: + # + # @verifier = ActiveSupport::MessageVerifier.new('s3Krit', serializer: YAML) + # + # +MessageVerifier+ creates HMAC signatures using SHA1 hash algorithm by default. + # If you want to use a different hash algorithm, you can change it by providing + # +:digest+ key as an option while initializing the verifier: + # + # @verifier = ActiveSupport::MessageVerifier.new('s3Krit', digest: 'SHA256') + # + # === Confining messages to a specific purpose + # + # By default any message can be used throughout your app. But they can also be + # confined to a specific +:purpose+. + # + # token = @verifier.generate("this is the chair", purpose: :login) + # + # Then that same purpose must be passed when verifying to get the data back out: + # + # @verifier.verified(token, purpose: :login) # => "this is the chair" + # @verifier.verified(token, purpose: :shipping) # => nil + # @verifier.verified(token) # => nil + # + # @verifier.verify(token, purpose: :login) # => "this is the chair" + # @verifier.verify(token, purpose: :shipping) # => ActiveSupport::MessageVerifier::InvalidSignature + # @verifier.verify(token) # => ActiveSupport::MessageVerifier::InvalidSignature + # + # Likewise, if a message has no purpose it won't be returned when verifying with + # a specific purpose. + # + # token = @verifier.generate("the conversation is lively") + # @verifier.verified(token, purpose: :scare_tactics) # => nil + # @verifier.verified(token) # => "the conversation is lively" + # + # @verifier.verify(token, purpose: :scare_tactics) # => ActiveSupport::MessageVerifier::InvalidSignature + # @verifier.verify(token) # => "the conversation is lively" + # + # === Making messages expire + # + # By default messages last forever and verifying one year from now will still + # return the original value. But messages can be set to expire at a given + # time with +:expires_in+ or +:expires_at+. + # + # @verifier.generate("parcel", expires_in: 1.month) + # @verifier.generate("doowad", expires_at: Time.now.end_of_year) + # + # Then the messages can be verified and returned up to the expire time. + # Thereafter, the +verified+ method returns +nil+ while +verify+ raises + # ActiveSupport::MessageVerifier::InvalidSignature. + # + # === Rotating keys + # + # MessageVerifier also supports rotating out old configurations by falling + # back to a stack of verifiers. Call +rotate+ to build and add a verifier so + # either +verified+ or +verify+ will also try verifying with the fallback. + # + # By default any rotated verifiers use the values of the primary + # verifier unless specified otherwise. + # + # You'd give your verifier the new defaults: + # + # verifier = ActiveSupport::MessageVerifier.new(@secret, digest: "SHA512", serializer: JSON) + # + # Then gradually rotate the old values out by adding them as fallbacks. Any message + # generated with the old values will then work until the rotation is removed. + # + # verifier.rotate old_secret # Fallback to an old secret instead of @secret. + # verifier.rotate digest: "SHA256" # Fallback to an old digest instead of SHA512. + # verifier.rotate serializer: Marshal # Fallback to an old serializer instead of JSON. + # + # Though the above would most likely be combined into one rotation: + # + # verifier.rotate old_secret, digest: "SHA256", serializer: Marshal + class MessageVerifier + prepend Messages::Rotator::Verifier + + class InvalidSignature < StandardError; end + + SEPARATOR = "--" # :nodoc: + SEPARATOR_LENGTH = SEPARATOR.length # :nodoc: + + def initialize(secret, digest: nil, serializer: nil) + raise ArgumentError, "Secret should not be nil." unless secret + @secret = secret + @digest = digest&.to_s || "SHA1" + @serializer = serializer || Marshal + end + + # Checks if a signed message could have been generated by signing an object + # with the +MessageVerifier+'s secret. + # + # verifier = ActiveSupport::MessageVerifier.new 's3Krit' + # signed_message = verifier.generate 'a private message' + # verifier.valid_message?(signed_message) # => true + # + # tampered_message = signed_message.chop # editing the message invalidates the signature + # verifier.valid_message?(tampered_message) # => false + def valid_message?(signed_message) + data, digest = get_data_and_digest_from(signed_message) + digest_matches_data?(digest, data) + end + + # Decodes the signed message using the +MessageVerifier+'s secret. + # + # verifier = ActiveSupport::MessageVerifier.new 's3Krit' + # + # signed_message = verifier.generate 'a private message' + # verifier.verified(signed_message) # => 'a private message' + # + # Returns +nil+ if the message was not signed with the same secret. + # + # other_verifier = ActiveSupport::MessageVerifier.new 'd1ff3r3nt-s3Krit' + # other_verifier.verified(signed_message) # => nil + # + # Returns +nil+ if the message is not Base64-encoded. + # + # invalid_message = "f--46a0120593880c733a53b6dad75b42ddc1c8996d" + # verifier.verified(invalid_message) # => nil + # + # Raises any error raised while decoding the signed message. + # + # incompatible_message = "test--dad7b06c94abba8d46a15fafaef56c327665d5ff" + # verifier.verified(incompatible_message) # => TypeError: incompatible marshal file format + def verified(signed_message, purpose: nil, **) + data, digest = get_data_and_digest_from(signed_message) + if digest_matches_data?(digest, data) + begin + message = Messages::Metadata.verify(decode(data), purpose) + @serializer.load(message) if message + rescue ArgumentError => argument_error + return if argument_error.message.include?("invalid base64") + raise + end + end + end + + # Decodes the signed message using the +MessageVerifier+'s secret. + # + # verifier = ActiveSupport::MessageVerifier.new 's3Krit' + # signed_message = verifier.generate 'a private message' + # + # verifier.verify(signed_message) # => 'a private message' + # + # Raises +InvalidSignature+ if the message was not signed with the same + # secret or was not Base64-encoded. + # + # other_verifier = ActiveSupport::MessageVerifier.new 'd1ff3r3nt-s3Krit' + # other_verifier.verify(signed_message) # => ActiveSupport::MessageVerifier::InvalidSignature + def verify(*args, **options) + verified(*args, **options) || raise(InvalidSignature) + end + + # Generates a signed message for the provided value. + # + # The message is signed with the +MessageVerifier+'s secret. + # Returns Base64-encoded message joined with the generated signature. + # + # verifier = ActiveSupport::MessageVerifier.new 's3Krit' + # verifier.generate 'a private message' # => "BAhJIhRwcml2YXRlLW1lc3NhZ2UGOgZFVA==--e2d724331ebdee96a10fb99b089508d1c72bd772" + def generate(value, expires_at: nil, expires_in: nil, purpose: nil) + data = encode(Messages::Metadata.wrap(@serializer.dump(value), expires_at: expires_at, expires_in: expires_in, purpose: purpose)) + "#{data}#{SEPARATOR}#{generate_digest(data)}" + end + + private + def encode(data) + ::Base64.strict_encode64(data) + end + + def decode(data) + ::Base64.strict_decode64(data) + end + + def generate_digest(data) + OpenSSL::HMAC.hexdigest(@digest, @secret, data) + end + + def digest_length_in_hex + # In hexadecimal (AKA base16) it takes 4 bits to represent a character, + # hence we multiply the digest's length (in bytes) by 8 to get it in + # bits and divide by 4 to get its number of characters it hex. Well, 8 + # divided by 4 is 2. + @digest_length_in_hex ||= OpenSSL::Digest.new(@digest).digest_length * 2 + end + + def separator_index_for(signed_message) + index = signed_message.length - digest_length_in_hex - SEPARATOR_LENGTH + return if index.negative? || signed_message[index, SEPARATOR_LENGTH] != SEPARATOR + + index + end + + def get_data_and_digest_from(signed_message) + return if signed_message.nil? || !signed_message.valid_encoding? || signed_message.empty? + + separator_index = separator_index_for(signed_message) + return if separator_index.nil? + + data = signed_message[0...separator_index] + digest = signed_message[separator_index + SEPARATOR_LENGTH..-1] + + [data, digest] + end + + def digest_matches_data?(digest, data) + data.present? && digest.present? && ActiveSupport::SecurityUtils.secure_compare(digest, generate_digest(data)) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/messages/metadata.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/messages/metadata.rb new file mode 100644 index 0000000..4719d8e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/messages/metadata.rb @@ -0,0 +1,80 @@ +# frozen_string_literal: true + +require "time" + +module ActiveSupport + module Messages # :nodoc: + class Metadata # :nodoc: + def initialize(message, expires_at = nil, purpose = nil) + @message, @purpose = message, purpose + @expires_at = expires_at.is_a?(String) ? parse_expires_at(expires_at) : expires_at + end + + def as_json(options = {}) + { _rails: { message: @message, exp: @expires_at, pur: @purpose } } + end + + class << self + def wrap(message, expires_at: nil, expires_in: nil, purpose: nil) + if expires_at || expires_in || purpose + JSON.encode new(encode(message), pick_expiry(expires_at, expires_in), purpose) + else + message + end + end + + def verify(message, purpose) + extract_metadata(message).verify(purpose) + end + + private + def pick_expiry(expires_at, expires_in) + if expires_at + expires_at.utc.iso8601(3) + elsif expires_in + Time.now.utc.advance(seconds: expires_in).iso8601(3) + end + end + + def extract_metadata(message) + data = JSON.decode(message) rescue nil + + if data.is_a?(Hash) && data.key?("_rails") + new(decode(data["_rails"]["message"]), data["_rails"]["exp"], data["_rails"]["pur"]) + else + new(message) + end + end + + def encode(message) + ::Base64.strict_encode64(message) + end + + def decode(message) + ::Base64.strict_decode64(message) + end + end + + def verify(purpose) + @message if match?(purpose) && fresh? + end + + private + def match?(purpose) + @purpose.to_s == purpose.to_s + end + + def fresh? + @expires_at.nil? || Time.now.utc < @expires_at + end + + def parse_expires_at(expires_at) + if ActiveSupport.use_standard_json_time_format + Time.iso8601(expires_at) + else + Time.parse(expires_at) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/messages/rotation_configuration.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/messages/rotation_configuration.rb new file mode 100644 index 0000000..eef05fe --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/messages/rotation_configuration.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +module ActiveSupport + module Messages + class RotationConfiguration # :nodoc: + attr_reader :signed, :encrypted + + def initialize + @signed, @encrypted = [], [] + end + + def rotate(kind, *args, **options) + args << options unless options.empty? + case kind + when :signed + @signed << args + when :encrypted + @encrypted << args + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/messages/rotator.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/messages/rotator.rb new file mode 100644 index 0000000..b19e185 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/messages/rotator.rb @@ -0,0 +1,57 @@ +# frozen_string_literal: true + +module ActiveSupport + module Messages + module Rotator # :nodoc: + def initialize(*secrets, on_rotation: nil, **options) + super(*secrets, **options) + + @options = options + @rotations = [] + @on_rotation = on_rotation + end + + def rotate(*secrets, **options) + @rotations << build_rotation(*secrets, @options.merge(options)) + end + + module Encryptor + include Rotator + + def decrypt_and_verify(*args, on_rotation: @on_rotation, **options) + super + rescue MessageEncryptor::InvalidMessage, MessageVerifier::InvalidSignature + run_rotations(on_rotation) { |encryptor| encryptor.decrypt_and_verify(*args, **options) } || raise + end + + private + def build_rotation(secret = @secret, sign_secret = @sign_secret, options) + self.class.new(secret, sign_secret, **options) + end + end + + module Verifier + include Rotator + + def verified(*args, on_rotation: @on_rotation, **options) + super || run_rotations(on_rotation) { |verifier| verifier.verified(*args, **options) } + end + + private + def build_rotation(secret = @secret, options) + self.class.new(secret, **options) + end + end + + private + def run_rotations(on_rotation) + @rotations.find do |rotation| + if message = yield(rotation) rescue next + on_rotation&.call + return message + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/multibyte.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/multibyte.rb new file mode 100644 index 0000000..0366350 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/multibyte.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +module ActiveSupport # :nodoc: + module Multibyte + autoload :Chars, "active_support/multibyte/chars" + autoload :Unicode, "active_support/multibyte/unicode" + + # The proxy class returned when calling mb_chars. You can use this accessor + # to configure your own proxy class so you can support other encodings. See + # the ActiveSupport::Multibyte::Chars implementation for an example how to + # do this. + # + # ActiveSupport::Multibyte.proxy_class = CharsForUTF32 + def self.proxy_class=(klass) + @proxy_class = klass + end + + # Returns the current proxy class. + def self.proxy_class + @proxy_class ||= ActiveSupport::Multibyte::Chars + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/multibyte/chars.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/multibyte/chars.rb new file mode 100644 index 0000000..79dda27 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/multibyte/chars.rb @@ -0,0 +1,176 @@ +# frozen_string_literal: true + +require "active_support/json" +require "active_support/core_ext/string/access" +require "active_support/core_ext/string/behavior" +require "active_support/core_ext/module/delegation" + +module ActiveSupport # :nodoc: + module Multibyte # :nodoc: + # Chars enables you to work transparently with UTF-8 encoding in the Ruby + # String class without having extensive knowledge about the encoding. A + # Chars object accepts a string upon initialization and proxies String + # methods in an encoding safe manner. All the normal String methods are also + # implemented on the proxy. + # + # String methods are proxied through the Chars object, and can be accessed + # through the +mb_chars+ method. Methods which would normally return a + # String object now return a Chars object so methods can be chained. + # + # 'The Perfect String '.mb_chars.downcase.strip + # # => # + # + # Chars objects are perfectly interchangeable with String objects as long as + # no explicit class checks are made. If certain methods do explicitly check + # the class, call +to_s+ before you pass chars objects to them. + # + # bad.explicit_checking_method 'T'.mb_chars.downcase.to_s + # + # The default Chars implementation assumes that the encoding of the string + # is UTF-8, if you want to handle different encodings you can write your own + # multibyte string handler and configure it through + # ActiveSupport::Multibyte.proxy_class. + # + # class CharsForUTF32 + # def size + # @wrapped_string.size / 4 + # end + # + # def self.accepts?(string) + # string.length % 4 == 0 + # end + # end + # + # ActiveSupport::Multibyte.proxy_class = CharsForUTF32 + class Chars + include Comparable + attr_reader :wrapped_string + alias to_s wrapped_string + alias to_str wrapped_string + + delegate :<=>, :=~, :match?, :acts_like_string?, to: :wrapped_string + + # Creates a new Chars instance by wrapping _string_. + def initialize(string) + @wrapped_string = string + @wrapped_string.force_encoding(Encoding::UTF_8) unless @wrapped_string.frozen? + end + + # Forward all undefined methods to the wrapped string. + def method_missing(method, *args, &block) + result = @wrapped_string.__send__(method, *args, &block) + if method.end_with?("!") + self if result + else + result.kind_of?(String) ? chars(result) : result + end + end + + # Returns +true+ if _obj_ responds to the given method. Private methods + # are included in the search only if the optional second parameter + # evaluates to +true+. + def respond_to_missing?(method, include_private) + @wrapped_string.respond_to?(method, include_private) + end + + # Works just like String#split, with the exception that the items + # in the resulting list are Chars instances instead of String. This makes + # chaining methods easier. + # + # 'Café périferôl'.mb_chars.split(/é/).map { |part| part.upcase.to_s } # => ["CAF", " P", "RIFERÔL"] + def split(*args) + @wrapped_string.split(*args).map { |i| self.class.new(i) } + end + + # Works like String#slice!, but returns an instance of + # Chars, or +nil+ if the string was not modified. The string will not be + # modified if the range given is out of bounds + # + # string = 'Welcome' + # string.mb_chars.slice!(3) # => # + # string # => 'Welome' + # string.mb_chars.slice!(0..3) # => # + # string # => 'me' + def slice!(*args) + string_sliced = @wrapped_string.slice!(*args) + if string_sliced + chars(string_sliced) + end + end + + # Reverses all characters in the string. + # + # 'Café'.mb_chars.reverse.to_s # => 'éfaC' + def reverse + chars(@wrapped_string.grapheme_clusters.reverse.join) + end + + # Limits the byte size of the string to a number of bytes without breaking + # characters. Usable when the storage for a string is limited for some + # reason. + # + # 'こんにちは'.mb_chars.limit(7).to_s # => "こん" + def limit(limit) + chars(@wrapped_string.truncate_bytes(limit, omission: nil)) + end + + # Capitalizes the first letter of every word, when possible. + # + # "ÉL QUE SE ENTERÓ".mb_chars.titleize.to_s # => "Él Que Se Enteró" + # "日本語".mb_chars.titleize.to_s # => "日本語" + def titleize + chars(downcase.to_s.gsub(/\b('?\S)/u) { $1.upcase }) + end + alias_method :titlecase, :titleize + + # Performs canonical decomposition on all the characters. + # + # 'é'.length # => 1 + # 'é'.mb_chars.decompose.to_s.length # => 2 + def decompose + chars(Unicode.decompose(:canonical, @wrapped_string.codepoints.to_a).pack("U*")) + end + + # Performs composition on all the characters. + # + # 'é'.length # => 1 + # 'é'.mb_chars.compose.to_s.length # => 1 + def compose + chars(Unicode.compose(@wrapped_string.codepoints.to_a).pack("U*")) + end + + # Returns the number of grapheme clusters in the string. + # + # 'क्षि'.mb_chars.length # => 4 + # 'क्षि'.mb_chars.grapheme_length # => 2 + def grapheme_length + @wrapped_string.grapheme_clusters.length + end + + # Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent + # resulting in a valid UTF-8 string. + # + # Passing +true+ will forcibly tidy all bytes, assuming that the string's + # encoding is entirely CP1252 or ISO-8859-1. + def tidy_bytes(force = false) + chars(Unicode.tidy_bytes(@wrapped_string, force)) + end + + def as_json(options = nil) # :nodoc: + to_s.as_json(options) + end + + %w(reverse tidy_bytes).each do |method| + define_method("#{method}!") do |*args| + @wrapped_string = public_send(method, *args).to_s + self + end + end + + private + def chars(string) + self.class.new(string) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/multibyte/unicode.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/multibyte/unicode.rb new file mode 100644 index 0000000..1c3e98b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/multibyte/unicode.rb @@ -0,0 +1,70 @@ +# frozen_string_literal: true + +module ActiveSupport + module Multibyte + module Unicode + extend self + + # The Unicode version that is supported by the implementation + UNICODE_VERSION = RbConfig::CONFIG["UNICODE_VERSION"] + + # Decompose composed characters to the decomposed form. + def decompose(type, codepoints) + if type == :compatibility + codepoints.pack("U*").unicode_normalize(:nfkd).codepoints + else + codepoints.pack("U*").unicode_normalize(:nfd).codepoints + end + end + + # Compose decomposed characters to the composed form. + def compose(codepoints) + codepoints.pack("U*").unicode_normalize(:nfc).codepoints + end + + # Rubinius' String#scrub, however, doesn't support ASCII-incompatible chars. + if !defined?(Rubinius) + # Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent + # resulting in a valid UTF-8 string. + # + # Passing +true+ will forcibly tidy all bytes, assuming that the string's + # encoding is entirely CP1252 or ISO-8859-1. + def tidy_bytes(string, force = false) + return string if string.empty? || string.ascii_only? + return recode_windows1252_chars(string) if force + string.scrub { |bad| recode_windows1252_chars(bad) } + end + else + def tidy_bytes(string, force = false) + return string if string.empty? + return recode_windows1252_chars(string) if force + + # We can't transcode to the same format, so we choose a nearly-identical encoding. + # We're going to 'transcode' bytes from UTF-8 when possible, then fall back to + # CP1252 when we get errors. The final string will be 'converted' back to UTF-8 + # before returning. + reader = Encoding::Converter.new(Encoding::UTF_8, Encoding::UTF_16LE) + + source = string.dup + out = "".force_encoding(Encoding::UTF_16LE) + + loop do + reader.primitive_convert(source, out) + _, _, _, error_bytes, _ = reader.primitive_errinfo + break if error_bytes.nil? + out << error_bytes.encode(Encoding::UTF_16LE, Encoding::Windows_1252, invalid: :replace, undef: :replace) + end + + reader.finish + + out.encode!(Encoding::UTF_8) + end + end + + private + def recode_windows1252_chars(string) + string.encode(Encoding::UTF_8, Encoding::Windows_1252, invalid: :replace, undef: :replace) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/notifications.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/notifications.rb new file mode 100644 index 0000000..c7986b8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/notifications.rb @@ -0,0 +1,274 @@ +# frozen_string_literal: true + +require "active_support/notifications/instrumenter" +require "active_support/notifications/fanout" + +module ActiveSupport + # = Notifications + # + # ActiveSupport::Notifications provides an instrumentation API for + # Ruby. + # + # == Instrumenters + # + # To instrument an event you just need to do: + # + # ActiveSupport::Notifications.instrument('render', extra: :information) do + # render plain: 'Foo' + # end + # + # That first executes the block and then notifies all subscribers once done. + # + # In the example above +render+ is the name of the event, and the rest is called + # the _payload_. The payload is a mechanism that allows instrumenters to pass + # extra information to subscribers. Payloads consist of a hash whose contents + # are arbitrary and generally depend on the event. + # + # == Subscribers + # + # You can consume those events and the information they provide by registering + # a subscriber. + # + # ActiveSupport::Notifications.subscribe('render') do |name, start, finish, id, payload| + # name # => String, name of the event (such as 'render' from above) + # start # => Time, when the instrumented block started execution + # finish # => Time, when the instrumented block ended execution + # id # => String, unique ID for the instrumenter that fired the event + # payload # => Hash, the payload + # end + # + # Here, the +start+ and +finish+ values represent wall-clock time. If you are + # concerned about accuracy, you can register a monotonic subscriber. + # + # ActiveSupport::Notifications.monotonic_subscribe('render') do |name, start, finish, id, payload| + # name # => String, name of the event (such as 'render' from above) + # start # => Monotonic time, when the instrumented block started execution + # finish # => Monotonic time, when the instrumented block ended execution + # id # => String, unique ID for the instrumenter that fired the event + # payload # => Hash, the payload + # end + # + # The +start+ and +finish+ values above represent monotonic time. + # + # For instance, let's store all "render" events in an array: + # + # events = [] + # + # ActiveSupport::Notifications.subscribe('render') do |*args| + # events << ActiveSupport::Notifications::Event.new(*args) + # end + # + # That code returns right away, you are just subscribing to "render" events. + # The block is saved and will be called whenever someone instruments "render": + # + # ActiveSupport::Notifications.instrument('render', extra: :information) do + # render plain: 'Foo' + # end + # + # event = events.first + # event.name # => "render" + # event.duration # => 10 (in milliseconds) + # event.payload # => { extra: :information } + # + # The block in the subscribe call gets the name of the event, start + # timestamp, end timestamp, a string with a unique identifier for that event's instrumenter + # (something like "535801666f04d0298cd6"), and a hash with the payload, in + # that order. + # + # If an exception happens during that particular instrumentation the payload will + # have a key :exception with an array of two elements as value: a string with + # the name of the exception class, and the exception message. + # The :exception_object key of the payload will have the exception + # itself as the value: + # + # event.payload[:exception] # => ["ArgumentError", "Invalid value"] + # event.payload[:exception_object] # => # + # + # As the earlier example depicts, the class ActiveSupport::Notifications::Event + # is able to take the arguments as they come and provide an object-oriented + # interface to that data. + # + # It is also possible to pass an object which responds to call method + # as the second parameter to the subscribe method instead of a block: + # + # module ActionController + # class PageRequest + # def call(name, started, finished, unique_id, payload) + # Rails.logger.debug ['notification:', name, started, finished, unique_id, payload].join(' ') + # end + # end + # end + # + # ActiveSupport::Notifications.subscribe('process_action.action_controller', ActionController::PageRequest.new) + # + # resulting in the following output within the logs including a hash with the payload: + # + # notification: process_action.action_controller 2012-04-13 01:08:35 +0300 2012-04-13 01:08:35 +0300 af358ed7fab884532ec7 { + # controller: "Devise::SessionsController", + # action: "new", + # params: {"action"=>"new", "controller"=>"devise/sessions"}, + # format: :html, + # method: "GET", + # path: "/login/sign_in", + # status: 200, + # view_runtime: 279.3080806732178, + # db_runtime: 40.053 + # } + # + # You can also subscribe to all events whose name matches a certain regexp: + # + # ActiveSupport::Notifications.subscribe(/render/) do |*args| + # ... + # end + # + # and even pass no argument to subscribe, in which case you are subscribing + # to all events. + # + # == Temporary Subscriptions + # + # Sometimes you do not want to subscribe to an event for the entire life of + # the application. There are two ways to unsubscribe. + # + # WARNING: The instrumentation framework is designed for long-running subscribers, + # use this feature sparingly because it wipes some internal caches and that has + # a negative impact on performance. + # + # === Subscribe While a Block Runs + # + # You can subscribe to some event temporarily while some block runs. For + # example, in + # + # callback = lambda {|*args| ... } + # ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do + # ... + # end + # + # the callback will be called for all "sql.active_record" events instrumented + # during the execution of the block. The callback is unsubscribed automatically + # after that. + # + # To record +started+ and +finished+ values with monotonic time, + # specify the optional :monotonic option to the + # subscribed method. The :monotonic option is set + # to +false+ by default. + # + # callback = lambda {|name, started, finished, unique_id, payload| ... } + # ActiveSupport::Notifications.subscribed(callback, "sql.active_record", monotonic: true) do + # ... + # end + # + # === Manual Unsubscription + # + # The +subscribe+ method returns a subscriber object: + # + # subscriber = ActiveSupport::Notifications.subscribe("render") do |*args| + # ... + # end + # + # To prevent that block from being called anymore, just unsubscribe passing + # that reference: + # + # ActiveSupport::Notifications.unsubscribe(subscriber) + # + # You can also unsubscribe by passing the name of the subscriber object. Note + # that this will unsubscribe all subscriptions with the given name: + # + # ActiveSupport::Notifications.unsubscribe("render") + # + # Subscribers using a regexp or other pattern-matching object will remain subscribed + # to all events that match their original pattern, unless those events match a string + # passed to +unsubscribe+: + # + # subscriber = ActiveSupport::Notifications.subscribe(/render/) { } + # ActiveSupport::Notifications.unsubscribe('render_template.action_view') + # subscriber.matches?('render_template.action_view') # => false + # subscriber.matches?('render_partial.action_view') # => true + # + # == Default Queue + # + # Notifications ships with a queue implementation that consumes and publishes events + # to all log subscribers. You can use any queue implementation you want. + # + module Notifications + class << self + attr_accessor :notifier + + def publish(name, *args) + notifier.publish(name, *args) + end + + def publish_event(event) # :nodoc: + notifier.publish_event(event) + end + + def instrument(name, payload = {}) + if notifier.listening?(name) + instrumenter.instrument(name, payload) { yield payload if block_given? } + else + yield payload if block_given? + end + end + + # Subscribe to a given event name with the passed +block+. + # + # You can subscribe to events by passing a String to match exact event + # names, or by passing a Regexp to match all events that match a pattern. + # + # ActiveSupport::Notifications.subscribe(/render/) do |*args| + # @event = ActiveSupport::Notifications::Event.new(*args) + # end + # + # The +block+ will receive five parameters with information about the event: + # + # ActiveSupport::Notifications.subscribe('render') do |name, start, finish, id, payload| + # name # => String, name of the event (such as 'render' from above) + # start # => Time, when the instrumented block started execution + # finish # => Time, when the instrumented block ended execution + # id # => String, unique ID for the instrumenter that fired the event + # payload # => Hash, the payload + # end + # + # If the block passed to the method only takes one parameter, + # it will yield an event object to the block: + # + # ActiveSupport::Notifications.subscribe(/render/) do |event| + # @event = event + # end + # + # Raises an error if invalid event name type is passed: + # + # ActiveSupport::Notifications.subscribe(:render) {|*args| ...} + # #=> ArgumentError (pattern must be specified as a String, Regexp or empty) + # + def subscribe(pattern = nil, callback = nil, &block) + notifier.subscribe(pattern, callback, monotonic: false, &block) + end + + def monotonic_subscribe(pattern = nil, callback = nil, &block) + notifier.subscribe(pattern, callback, monotonic: true, &block) + end + + def subscribed(callback, pattern = nil, monotonic: false, &block) + subscriber = notifier.subscribe(pattern, callback, monotonic: monotonic) + yield + ensure + unsubscribe(subscriber) + end + + def unsubscribe(subscriber_or_name) + notifier.unsubscribe(subscriber_or_name) + end + + def instrumenter + registry[notifier] ||= Instrumenter.new(notifier) + end + + private + def registry + ActiveSupport::IsolatedExecutionState[:active_support_notifications_registry] ||= {} + end + end + + self.notifier = Fanout.new + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/notifications/fanout.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/notifications/fanout.rb new file mode 100644 index 0000000..0759d3a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/notifications/fanout.rb @@ -0,0 +1,285 @@ +# frozen_string_literal: true + +require "mutex_m" +require "concurrent/map" +require "set" +require "active_support/core_ext/object/try" + +module ActiveSupport + module Notifications + class InstrumentationSubscriberError < RuntimeError + attr_reader :exceptions + + def initialize(exceptions) + @exceptions = exceptions + exception_class_names = exceptions.map { |e| e.class.name } + super "Exception(s) occurred within instrumentation subscribers: #{exception_class_names.join(', ')}" + end + end + + # This is a default queue implementation that ships with Notifications. + # It just pushes events to all registered log subscribers. + # + # This class is thread safe. All methods are reentrant. + class Fanout + include Mutex_m + + def initialize + @string_subscribers = Hash.new { |h, k| h[k] = [] } + @other_subscribers = [] + @listeners_for = Concurrent::Map.new + super + end + + def subscribe(pattern = nil, callable = nil, monotonic: false, &block) + subscriber = Subscribers.new(pattern, callable || block, monotonic) + synchronize do + case pattern + when String + @string_subscribers[pattern] << subscriber + @listeners_for.delete(pattern) + when NilClass, Regexp + @other_subscribers << subscriber + @listeners_for.clear + else + raise ArgumentError, "pattern must be specified as a String, Regexp or empty" + end + end + subscriber + end + + def unsubscribe(subscriber_or_name) + synchronize do + case subscriber_or_name + when String + @string_subscribers[subscriber_or_name].clear + @listeners_for.delete(subscriber_or_name) + @other_subscribers.each { |sub| sub.unsubscribe!(subscriber_or_name) } + else + pattern = subscriber_or_name.try(:pattern) + if String === pattern + @string_subscribers[pattern].delete(subscriber_or_name) + @listeners_for.delete(pattern) + else + @other_subscribers.delete(subscriber_or_name) + @listeners_for.clear + end + end + end + end + + def start(name, id, payload) + iterate_guarding_exceptions(listeners_for(name)) { |s| s.start(name, id, payload) } + end + + def finish(name, id, payload, listeners = listeners_for(name)) + iterate_guarding_exceptions(listeners) { |s| s.finish(name, id, payload) } + end + + def publish(name, *args) + iterate_guarding_exceptions(listeners_for(name)) { |s| s.publish(name, *args) } + end + + def publish_event(event) + iterate_guarding_exceptions(listeners_for(event.name)) { |s| s.publish_event(event) } + end + + def iterate_guarding_exceptions(listeners) + exceptions = nil + + listeners.each do |s| + yield s + rescue Exception => e + exceptions ||= [] + exceptions << e + end + + if exceptions + if exceptions.size == 1 + raise exceptions.first + else + raise InstrumentationSubscriberError.new(exceptions), cause: exceptions.first + end + end + + listeners + end + + def listeners_for(name) + # this is correctly done double-checked locking (Concurrent::Map's lookups have volatile semantics) + @listeners_for[name] || synchronize do + # use synchronisation when accessing @subscribers + @listeners_for[name] ||= + @string_subscribers[name] + @other_subscribers.select { |s| s.subscribed_to?(name) } + end + end + + def listening?(name) + listeners_for(name).any? + end + + # This is a sync queue, so there is no waiting. + def wait + end + + module Subscribers # :nodoc: + def self.new(pattern, listener, monotonic) + subscriber_class = monotonic ? MonotonicTimed : Timed + + if listener.respond_to?(:start) && listener.respond_to?(:finish) + subscriber_class = Evented + else + # Doing this to detect a single argument block or callable + # like `proc { |x| }` vs `proc { |*x| }`, `proc { |**x| }`, + # or `proc { |x, **y| }` + procish = listener.respond_to?(:parameters) ? listener : listener.method(:call) + + if procish.arity == 1 && procish.parameters.length == 1 + subscriber_class = EventObject + end + end + + subscriber_class.new(pattern, listener) + end + + class Matcher # :nodoc: + attr_reader :pattern, :exclusions + + def self.wrap(pattern) + if String === pattern + pattern + elsif pattern.nil? + AllMessages.new + else + new(pattern) + end + end + + def initialize(pattern) + @pattern = pattern + @exclusions = Set.new + end + + def unsubscribe!(name) + exclusions << -name if pattern === name + end + + def ===(name) + pattern === name && !exclusions.include?(name) + end + + class AllMessages + def ===(name) + true + end + + def unsubscribe!(*) + false + end + end + end + + class Evented # :nodoc: + attr_reader :pattern + + def initialize(pattern, delegate) + @pattern = Matcher.wrap(pattern) + @delegate = delegate + @can_publish = delegate.respond_to?(:publish) + @can_publish_event = delegate.respond_to?(:publish_event) + end + + def publish(name, *args) + if @can_publish + @delegate.publish name, *args + end + end + + def publish_event(event) + if @can_publish_event + @delegate.publish_event event + else + publish(event.name, event.time, event.end, event.transaction_id, event.payload) + end + end + + def start(name, id, payload) + @delegate.start name, id, payload + end + + def finish(name, id, payload) + @delegate.finish name, id, payload + end + + def subscribed_to?(name) + pattern === name + end + + def unsubscribe!(name) + pattern.unsubscribe!(name) + end + end + + class Timed < Evented # :nodoc: + def publish(name, *args) + @delegate.call name, *args + end + + def start(name, id, payload) + timestack = IsolatedExecutionState[:_timestack] ||= [] + timestack.push Time.now + end + + def finish(name, id, payload) + timestack = IsolatedExecutionState[:_timestack] + started = timestack.pop + @delegate.call(name, started, Time.now, id, payload) + end + end + + class MonotonicTimed < Evented # :nodoc: + def publish(name, *args) + @delegate.call name, *args + end + + def start(name, id, payload) + timestack = IsolatedExecutionState[:_timestack_monotonic] ||= [] + timestack.push Process.clock_gettime(Process::CLOCK_MONOTONIC) + end + + def finish(name, id, payload) + timestack = IsolatedExecutionState[:_timestack_monotonic] + started = timestack.pop + @delegate.call(name, started, Process.clock_gettime(Process::CLOCK_MONOTONIC), id, payload) + end + end + + class EventObject < Evented + def start(name, id, payload) + stack = IsolatedExecutionState[:_event_stack] ||= [] + event = build_event name, id, payload + event.start! + stack.push event + end + + def finish(name, id, payload) + stack = IsolatedExecutionState[:_event_stack] + event = stack.pop + event.payload = payload + event.finish! + @delegate.call event + end + + def publish_event(event) + @delegate.call event + end + + private + def build_event(name, id, payload) + ActiveSupport::Notifications::Event.new name, nil, nil, id, payload + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/notifications/instrumenter.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/notifications/instrumenter.rb new file mode 100644 index 0000000..c69e8cd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/notifications/instrumenter.rb @@ -0,0 +1,172 @@ +# frozen_string_literal: true + +require "securerandom" + +module ActiveSupport + module Notifications + # Instrumenters are stored in a thread local. + class Instrumenter + attr_reader :id + + def initialize(notifier) + @id = unique_id + @notifier = notifier + end + + # Given a block, instrument it by measuring the time taken to execute + # and publish it. Without a block, simply send a message via the + # notifier. Notice that events get sent even if an error occurs in the + # passed-in block. + def instrument(name, payload = {}) + # some of the listeners might have state + listeners_state = start name, payload + begin + yield payload if block_given? + rescue Exception => e + payload[:exception] = [e.class.name, e.message] + payload[:exception_object] = e + raise e + ensure + finish_with_state listeners_state, name, payload + end + end + + def new_event(name, payload = {}) # :nodoc: + Event.new(name, nil, nil, @id, payload) + end + + # Send a start notification with +name+ and +payload+. + def start(name, payload) + @notifier.start name, @id, payload + end + + # Send a finish notification with +name+ and +payload+. + def finish(name, payload) + @notifier.finish name, @id, payload + end + + def finish_with_state(listeners_state, name, payload) + @notifier.finish name, @id, payload, listeners_state + end + + private + def unique_id + SecureRandom.hex(10) + end + end + + class Event + attr_reader :name, :time, :end, :transaction_id, :children + attr_accessor :payload + + def initialize(name, start, ending, transaction_id, payload) + @name = name + @payload = payload.dup + @time = start ? start.to_f * 1_000.0 : start + @transaction_id = transaction_id + @end = ending ? ending.to_f * 1_000.0 : ending + @children = [] + @cpu_time_start = 0.0 + @cpu_time_finish = 0.0 + @allocation_count_start = 0 + @allocation_count_finish = 0 + end + + def record + start! + begin + yield payload if block_given? + rescue Exception => e + payload[:exception] = [e.class.name, e.message] + payload[:exception_object] = e + raise e + ensure + finish! + end + end + + # Record information at the time this event starts + def start! + @time = now + @cpu_time_start = now_cpu + @allocation_count_start = now_allocations + end + + # Record information at the time this event finishes + def finish! + @cpu_time_finish = now_cpu + @end = now + @allocation_count_finish = now_allocations + end + + # Returns the CPU time (in milliseconds) passed since the call to + # +start!+ and the call to +finish!+ + def cpu_time + @cpu_time_finish - @cpu_time_start + end + + # Returns the idle time time (in milliseconds) passed since the call to + # +start!+ and the call to +finish!+ + def idle_time + duration - cpu_time + end + + # Returns the number of allocations made since the call to +start!+ and + # the call to +finish!+ + def allocations + @allocation_count_finish - @allocation_count_start + end + + # Returns the difference in milliseconds between when the execution of the + # event started and when it ended. + # + # ActiveSupport::Notifications.subscribe('wait') do |*args| + # @event = ActiveSupport::Notifications::Event.new(*args) + # end + # + # ActiveSupport::Notifications.instrument('wait') do + # sleep 1 + # end + # + # @event.duration # => 1000.138 + def duration + self.end - time + end + + def <<(event) + @children << event + end + + def parent_of?(event) + @children.include? event + end + + private + def now + Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) + end + + begin + Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID, :float_millisecond) + + def now_cpu + Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID, :float_millisecond) + end + rescue + def now_cpu # rubocop:disable Lint/DuplicateMethods + 0.0 + end + end + + if GC.stat.key?(:total_allocated_objects) + def now_allocations + GC.stat(:total_allocated_objects) + end + else # Likely on JRuby, TruffleRuby + def now_allocations + 0 + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper.rb new file mode 100644 index 0000000..8b66e3c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper.rb @@ -0,0 +1,395 @@ +# frozen_string_literal: true + +module ActiveSupport + module NumberHelper + extend ActiveSupport::Autoload + + eager_autoload do + autoload :NumberConverter + autoload :RoundingHelper + autoload :NumberToRoundedConverter + autoload :NumberToDelimitedConverter + autoload :NumberToHumanConverter + autoload :NumberToHumanSizeConverter + autoload :NumberToPhoneConverter + autoload :NumberToCurrencyConverter + autoload :NumberToPercentageConverter + end + + extend self + + # Formats a +number+ into a phone number (US by default e.g., (555) + # 123-9876). You can customize the format in the +options+ hash. + # + # ==== Options + # + # * :area_code - Adds parentheses around the area code. + # * :delimiter - Specifies the delimiter to use + # (defaults to "-"). + # * :extension - Specifies an extension to add to the + # end of the generated number. + # * :country_code - Sets the country code for the phone + # number. + # * :pattern - Specifies how the number is divided into three + # groups with the custom regexp to override the default format. + # ==== Examples + # + # number_to_phone(5551234) # => "555-1234" + # number_to_phone('5551234') # => "555-1234" + # number_to_phone(1235551234) # => "123-555-1234" + # number_to_phone(1235551234, area_code: true) # => "(123) 555-1234" + # number_to_phone(1235551234, delimiter: ' ') # => "123 555 1234" + # number_to_phone(1235551234, area_code: true, extension: 555) # => "(123) 555-1234 x 555" + # number_to_phone(1235551234, country_code: 1) # => "+1-123-555-1234" + # number_to_phone('123a456') # => "123a456" + # + # number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: '.') + # # => "+1.123.555.1234 x 1343" + # + # number_to_phone(75561234567, pattern: /(\d{1,4})(\d{4})(\d{4})$/, area_code: true) + # # => "(755) 6123-4567" + # number_to_phone(13312345678, pattern: /(\d{3})(\d{4})(\d{4})$/) + # # => "133-1234-5678" + def number_to_phone(number, options = {}) + NumberToPhoneConverter.convert(number, options) + end + + # Formats a +number+ into a currency string (e.g., $13.65). You + # can customize the format in the +options+ hash. + # + # The currency unit and number formatting of the current locale will be used + # unless otherwise specified in the provided options. No currency conversion + # is performed. If the user is given a way to change their locale, they will + # also be able to change the relative value of the currency displayed with + # this helper. If your application will ever support multiple locales, you + # may want to specify a constant :locale option or consider + # using a library capable of currency conversion. + # + # ==== Options + # + # * :locale - Sets the locale to be used for formatting + # (defaults to current locale). + # * :precision - Sets the level of precision (defaults + # to 2). + # * :round_mode - Determine how rounding is performed + # (defaults to :default. See BigDecimal::mode) + # * :unit - Sets the denomination of the currency + # (defaults to "$"). + # * :separator - Sets the separator between the units + # (defaults to "."). + # * :delimiter - Sets the thousands delimiter (defaults + # to ","). + # * :format - Sets the format for non-negative numbers + # (defaults to "%u%n"). Fields are %u for the + # currency, and %n for the number. + # * :negative_format - Sets the format for negative + # numbers (defaults to prepending a hyphen to the formatted + # number given by :format). Accepts the same fields + # than :format, except %n is here the + # absolute value of the number. + # * :strip_insignificant_zeros - If +true+ removes + # insignificant zeros after the decimal separator (defaults to + # +false+). + # + # ==== Examples + # + # number_to_currency(1234567890.50) # => "$1,234,567,890.50" + # number_to_currency(1234567890.506) # => "$1,234,567,890.51" + # number_to_currency(1234567890.506, precision: 3) # => "$1,234,567,890.506" + # number_to_currency(1234567890.506, locale: :fr) # => "1 234 567 890,51 €" + # number_to_currency('123a456') # => "$123a456" + # + # number_to_currency(-0.456789, precision: 0) + # # => "$0" + # number_to_currency(-1234567890.50, negative_format: '(%u%n)') + # # => "($1,234,567,890.50)" + # number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '') + # # => "£1234567890,50" + # number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '', format: '%n %u') + # # => "1234567890,50 £" + # number_to_currency(1234567890.50, strip_insignificant_zeros: true) + # # => "$1,234,567,890.5" + # number_to_currency(1234567890.50, precision: 0, round_mode: :up) + # # => "$1,234,567,891" + def number_to_currency(number, options = {}) + NumberToCurrencyConverter.convert(number, options) + end + + # Formats a +number+ as a percentage string (e.g., 65%). You can + # customize the format in the +options+ hash. + # + # ==== Options + # + # * :locale - Sets the locale to be used for formatting + # (defaults to current locale). + # * :precision - Sets the precision of the number + # (defaults to 3). Keeps the number's precision if +nil+. + # * :round_mode - Determine how rounding is performed + # (defaults to :default. See BigDecimal::mode) + # * :significant - If +true+, precision will be the number + # of significant_digits. If +false+, the number of fractional + # digits (defaults to +false+). + # * :separator - Sets the separator between the + # fractional and integer digits (defaults to "."). + # * :delimiter - Sets the thousands delimiter (defaults + # to ""). + # * :strip_insignificant_zeros - If +true+ removes + # insignificant zeros after the decimal separator (defaults to + # +false+). + # * :format - Specifies the format of the percentage + # string The number field is %n (defaults to "%n%"). + # + # ==== Examples + # + # number_to_percentage(100) # => "100.000%" + # number_to_percentage('98') # => "98.000%" + # number_to_percentage(100, precision: 0) # => "100%" + # number_to_percentage(1000, delimiter: '.', separator: ',') # => "1.000,000%" + # number_to_percentage(302.24398923423, precision: 5) # => "302.24399%" + # number_to_percentage(1000, locale: :fr) # => "1000,000%" + # number_to_percentage(1000, precision: nil) # => "1000%" + # number_to_percentage('98a') # => "98a%" + # number_to_percentage(100, format: '%n %') # => "100.000 %" + # number_to_percentage(302.24398923423, precision: 5, round_mode: :down) # => "302.24398%" + def number_to_percentage(number, options = {}) + NumberToPercentageConverter.convert(number, options) + end + + # Formats a +number+ with grouped thousands using +delimiter+ + # (e.g., 12,324). You can customize the format in the +options+ + # hash. + # + # ==== Options + # + # * :locale - Sets the locale to be used for formatting + # (defaults to current locale). + # * :delimiter - Sets the thousands delimiter (defaults + # to ","). + # * :separator - Sets the separator between the + # fractional and integer digits (defaults to "."). + # * :delimiter_pattern - Sets a custom regular expression used for + # deriving the placement of delimiter. Helpful when using currency formats + # like INR. + # + # ==== Examples + # + # number_to_delimited(12345678) # => "12,345,678" + # number_to_delimited('123456') # => "123,456" + # number_to_delimited(12345678.05) # => "12,345,678.05" + # number_to_delimited(12345678, delimiter: '.') # => "12.345.678" + # number_to_delimited(12345678, delimiter: ',') # => "12,345,678" + # number_to_delimited(12345678.05, separator: ' ') # => "12,345,678 05" + # number_to_delimited(12345678.05, locale: :fr) # => "12 345 678,05" + # number_to_delimited('112a') # => "112a" + # number_to_delimited(98765432.98, delimiter: ' ', separator: ',') + # # => "98 765 432,98" + # number_to_delimited("123456.78", + # delimiter_pattern: /(\d+?)(?=(\d\d)+(\d)(?!\d))/) + # # => "1,23,456.78" + def number_to_delimited(number, options = {}) + NumberToDelimitedConverter.convert(number, options) + end + + # Formats a +number+ with the specified level of + # :precision (e.g., 112.32 has a precision of 2 if + # +:significant+ is +false+, and 5 if +:significant+ is +true+). + # You can customize the format in the +options+ hash. + # + # ==== Options + # + # * :locale - Sets the locale to be used for formatting + # (defaults to current locale). + # * :precision - Sets the precision of the number + # (defaults to 3). Keeps the number's precision if +nil+. + # * :round_mode - Determine how rounding is performed + # (defaults to :default. See BigDecimal::mode) + # * :significant - If +true+, precision will be the number + # of significant_digits. If +false+, the number of fractional + # digits (defaults to +false+). + # * :separator - Sets the separator between the + # fractional and integer digits (defaults to "."). + # * :delimiter - Sets the thousands delimiter (defaults + # to ""). + # * :strip_insignificant_zeros - If +true+ removes + # insignificant zeros after the decimal separator (defaults to + # +false+). + # + # ==== Examples + # + # number_to_rounded(111.2345) # => "111.235" + # number_to_rounded(111.2345, precision: 2) # => "111.23" + # number_to_rounded(13, precision: 5) # => "13.00000" + # number_to_rounded(389.32314, precision: 0) # => "389" + # number_to_rounded(111.2345, significant: true) # => "111" + # number_to_rounded(111.2345, precision: 1, significant: true) # => "100" + # number_to_rounded(13, precision: 5, significant: true) # => "13.000" + # number_to_rounded(13, precision: nil) # => "13" + # number_to_rounded(389.32314, precision: 0, round_mode: :up) # => "390" + # number_to_rounded(111.234, locale: :fr) # => "111,234" + # + # number_to_rounded(13, precision: 5, significant: true, strip_insignificant_zeros: true) + # # => "13" + # + # number_to_rounded(389.32314, precision: 4, significant: true) # => "389.3" + # number_to_rounded(1111.2345, precision: 2, separator: ',', delimiter: '.') + # # => "1.111,23" + def number_to_rounded(number, options = {}) + NumberToRoundedConverter.convert(number, options) + end + + # Formats the bytes in +number+ into a more understandable + # representation (e.g., giving it 1500 yields 1.46 KB). This + # method is useful for reporting file sizes to users. You can + # customize the format in the +options+ hash. + # + # See number_to_human if you want to pretty-print a + # generic number. + # + # ==== Options + # + # * :locale - Sets the locale to be used for formatting + # (defaults to current locale). + # * :precision - Sets the precision of the number + # (defaults to 3). + # * :round_mode - Determine how rounding is performed + # (defaults to :default. See BigDecimal::mode) + # * :significant - If +true+, precision will be the number + # of significant_digits. If +false+, the number of fractional + # digits (defaults to +true+) + # * :separator - Sets the separator between the + # fractional and integer digits (defaults to "."). + # * :delimiter - Sets the thousands delimiter (defaults + # to ""). + # * :strip_insignificant_zeros - If +true+ removes + # insignificant zeros after the decimal separator (defaults to + # +true+) + # + # ==== Examples + # + # number_to_human_size(123) # => "123 Bytes" + # number_to_human_size(1234) # => "1.21 KB" + # number_to_human_size(12345) # => "12.1 KB" + # number_to_human_size(1234567) # => "1.18 MB" + # number_to_human_size(1234567890) # => "1.15 GB" + # number_to_human_size(1234567890123) # => "1.12 TB" + # number_to_human_size(1234567890123456) # => "1.1 PB" + # number_to_human_size(1234567890123456789) # => "1.07 EB" + # number_to_human_size(1234567, precision: 2) # => "1.2 MB" + # number_to_human_size(483989, precision: 2) # => "470 KB" + # number_to_human_size(483989, precision: 2, round_mode: :up) # => "480 KB" + # number_to_human_size(1234567, precision: 2, separator: ',') # => "1,2 MB" + # number_to_human_size(1234567890123, precision: 5) # => "1.1228 TB" + # number_to_human_size(524288000, precision: 5) # => "500 MB" + def number_to_human_size(number, options = {}) + NumberToHumanSizeConverter.convert(number, options) + end + + # Pretty prints (formats and approximates) a number in a way it + # is more readable by humans (e.g.: 1200000000 becomes "1.2 + # Billion"). This is useful for numbers that can get very large + # (and too hard to read). + # + # See number_to_human_size if you want to print a file + # size. + # + # You can also define your own unit-quantifier names if you want + # to use other decimal units (e.g.: 1500 becomes "1.5 + # kilometers", 0.150 becomes "150 milliliters", etc). You may + # define a wide range of unit quantifiers, even fractional ones + # (centi, deci, mili, etc). + # + # ==== Options + # + # * :locale - Sets the locale to be used for formatting + # (defaults to current locale). + # * :precision - Sets the precision of the number + # (defaults to 3). + # * :round_mode - Determine how rounding is performed + # (defaults to :default. See BigDecimal::mode) + # * :significant - If +true+, precision will be the number + # of significant_digits. If +false+, the number of fractional + # digits (defaults to +true+) + # * :separator - Sets the separator between the + # fractional and integer digits (defaults to "."). + # * :delimiter - Sets the thousands delimiter (defaults + # to ""). + # * :strip_insignificant_zeros - If +true+ removes + # insignificant zeros after the decimal separator (defaults to + # +true+) + # * :units - A Hash of unit quantifier names. Or a + # string containing an i18n scope where to find this hash. It + # might have the following keys: + # * *integers*: :unit, :ten, + # :hundred, :thousand, :million, + # :billion, :trillion, + # :quadrillion + # * *fractionals*: :deci, :centi, + # :mili, :micro, :nano, + # :pico, :femto + # * :format - Sets the format of the output string + # (defaults to "%n %u"). The field types are: + # * %u - The quantifier (ex.: 'thousand') + # * %n - The number + # + # ==== Examples + # + # number_to_human(123) # => "123" + # number_to_human(1234) # => "1.23 Thousand" + # number_to_human(12345) # => "12.3 Thousand" + # number_to_human(1234567) # => "1.23 Million" + # number_to_human(1234567890) # => "1.23 Billion" + # number_to_human(1234567890123) # => "1.23 Trillion" + # number_to_human(1234567890123456) # => "1.23 Quadrillion" + # number_to_human(1234567890123456789) # => "1230 Quadrillion" + # number_to_human(489939, precision: 2) # => "490 Thousand" + # number_to_human(489939, precision: 4) # => "489.9 Thousand" + # number_to_human(489939, precision: 2 + # , round_mode: :down) # => "480 Thousand" + # number_to_human(1234567, precision: 4, + # significant: false) # => "1.2346 Million" + # number_to_human(1234567, precision: 1, + # separator: ',', + # significant: false) # => "1,2 Million" + # + # number_to_human(500000000, precision: 5) # => "500 Million" + # number_to_human(12345012345, significant: false) # => "12.345 Billion" + # + # Non-significant zeros after the decimal separator are stripped + # out by default (set :strip_insignificant_zeros to + # +false+ to change that): + # + # number_to_human(12.00001) # => "12" + # number_to_human(12.00001, strip_insignificant_zeros: false) # => "12.0" + # + # ==== Custom Unit Quantifiers + # + # You can also use your own custom unit quantifiers: + # number_to_human(500000, units: { unit: 'ml', thousand: 'lt' }) # => "500 lt" + # + # If in your I18n locale you have: + # + # distance: + # centi: + # one: "centimeter" + # other: "centimeters" + # unit: + # one: "meter" + # other: "meters" + # thousand: + # one: "kilometer" + # other: "kilometers" + # billion: "gazillion-distance" + # + # Then you could do: + # + # number_to_human(543934, units: :distance) # => "544 kilometers" + # number_to_human(54393498, units: :distance) # => "54400 kilometers" + # number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance" + # number_to_human(343, units: :distance, precision: 1) # => "300 meters" + # number_to_human(1, units: :distance) # => "1 meter" + # number_to_human(0.34, units: :distance) # => "34 centimeters" + def number_to_human(number, options = {}) + NumberToHumanConverter.convert(number, options) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_converter.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_converter.rb new file mode 100644 index 0000000..168b1a5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_converter.rb @@ -0,0 +1,181 @@ +# frozen_string_literal: true + +require "active_support/core_ext/big_decimal/conversions" +require "active_support/core_ext/object/blank" +require "active_support/core_ext/hash/keys" +require "active_support/i18n" +require "active_support/core_ext/class/attribute" + +module ActiveSupport + module NumberHelper + class NumberConverter # :nodoc: + # Default and i18n option namespace per class + class_attribute :namespace + + # Does the object need a number that is a valid float? + class_attribute :validate_float + + attr_reader :number, :opts + + DEFAULTS = { + # Used in number_to_delimited + # These are also the defaults for 'currency', 'percentage', 'precision', and 'human' + format: { + # Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5) + separator: ".", + # Delimits thousands (e.g. 1,000,000 is a million) (always in groups of three) + delimiter: ",", + # Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00) + precision: 3, + # If set to true, precision will mean the number of significant digits instead + # of the number of decimal digits (1234 with precision 2 becomes 1200, 1.23543 becomes 1.2) + significant: false, + # If set, the zeros after the decimal separator will always be stripped (e.g.: 1.200 will be 1.2) + strip_insignificant_zeros: false + }, + + # Used in number_to_currency + currency: { + format: { + format: "%u%n", + negative_format: "-%u%n", + unit: "$", + # These five are to override number.format and are optional + separator: ".", + delimiter: ",", + precision: 2, + significant: false, + strip_insignificant_zeros: false + } + }, + + # Used in number_to_percentage + percentage: { + format: { + delimiter: "", + format: "%n%" + } + }, + + # Used in number_to_rounded + precision: { + format: { + delimiter: "" + } + }, + + # Used in number_to_human_size and number_to_human + human: { + format: { + # These five are to override number.format and are optional + delimiter: "", + precision: 3, + significant: true, + strip_insignificant_zeros: true + }, + # Used in number_to_human_size + storage_units: { + # Storage units output formatting. + # %u is the storage unit, %n is the number (default: 2 MB) + format: "%n %u", + units: { + byte: "Bytes", + kb: "KB", + mb: "MB", + gb: "GB", + tb: "TB" + } + }, + # Used in number_to_human + decimal_units: { + format: "%n %u", + # Decimal units output formatting + # By default we will only quantify some of the exponents + # but the commented ones might be defined or overridden + # by the user. + units: { + # femto: Quadrillionth + # pico: Trillionth + # nano: Billionth + # micro: Millionth + # mili: Thousandth + # centi: Hundredth + # deci: Tenth + unit: "", + # ten: + # one: Ten + # other: Tens + # hundred: Hundred + thousand: "Thousand", + million: "Million", + billion: "Billion", + trillion: "Trillion", + quadrillion: "Quadrillion" + } + } + } + } + + def self.convert(number, options) + new(number, options).execute + end + + def initialize(number, options) + @number = number + @opts = options.symbolize_keys + end + + def execute + if !number + nil + elsif validate_float? && !valid_float? + number + else + convert + end + end + + private + def options + @options ||= format_options.merge(opts) + end + + def format_options + default_format_options.merge!(i18n_format_options) + end + + def default_format_options + options = DEFAULTS[:format].dup + options.merge!(DEFAULTS[namespace][:format]) if namespace + options + end + + def i18n_format_options + locale = opts[:locale] + options = I18n.translate(:'number.format', locale: locale, default: {}).dup + + if namespace + options.merge!(I18n.translate(:"number.#{namespace}.format", locale: locale, default: {})) + end + + options + end + + def translate_number_value_with_default(key, **i18n_options) + I18n.translate(key, **{ default: default_value(key), scope: :number }.merge!(i18n_options)) + end + + def translate_in_locale(key, **i18n_options) + translate_number_value_with_default(key, **{ locale: options[:locale] }.merge(i18n_options)) + end + + def default_value(key) + key.split(".").reduce(DEFAULTS) { |defaults, k| defaults[k.to_sym] } + end + + def valid_float? + Float(number, exception: false) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_currency_converter.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_currency_converter.rb new file mode 100644 index 0000000..241ec90 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_currency_converter.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +require "active_support/number_helper/number_converter" + +module ActiveSupport + module NumberHelper + class NumberToCurrencyConverter < NumberConverter # :nodoc: + self.namespace = :currency + + def convert + format = options[:format] + + number_f = valid_float? + if number_f + if number_f.negative? + number_f = number_f.abs + format = options[:negative_format] if (number_f * 10**options[:precision]) >= 0.5 + end + number_s = NumberToRoundedConverter.convert(number_f, options) + else + number_s = number.to_s.strip + format = options[:negative_format] if number_s.sub!(/^-/, "") + end + + format.gsub("%n", number_s).gsub("%u", options[:unit]) + end + + private + def options + @options ||= begin + defaults = default_format_options.merge(i18n_opts) + # Override negative format if format options are given + defaults[:negative_format] = "-#{opts[:format]}" if opts[:format] + defaults.merge!(opts) + end + end + + def i18n_opts + # Set International negative format if it does not exist + i18n = i18n_format_options + i18n[:negative_format] ||= "-#{i18n[:format]}" if i18n[:format] + i18n + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_delimited_converter.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_delimited_converter.rb new file mode 100644 index 0000000..4fb2fb7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_delimited_converter.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +require "active_support/number_helper/number_converter" + +module ActiveSupport + module NumberHelper + class NumberToDelimitedConverter < NumberConverter # :nodoc: + self.validate_float = true + + DEFAULT_DELIMITER_REGEX = /(\d)(?=(\d\d\d)+(?!\d))/ + + def convert + parts.join(options[:separator]) + end + + private + def parts + left, right = number.to_s.split(".") + left.gsub!(delimiter_pattern) do |digit_to_delimit| + "#{digit_to_delimit}#{options[:delimiter]}" + end + [left, right].compact + end + + def delimiter_pattern + options.fetch(:delimiter_pattern, DEFAULT_DELIMITER_REGEX) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_human_converter.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_human_converter.rb new file mode 100644 index 0000000..3f92628 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_human_converter.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true + +require "active_support/number_helper/number_converter" + +module ActiveSupport + module NumberHelper + class NumberToHumanConverter < NumberConverter # :nodoc: + DECIMAL_UNITS = { 0 => :unit, 1 => :ten, 2 => :hundred, 3 => :thousand, 6 => :million, 9 => :billion, 12 => :trillion, 15 => :quadrillion, + -1 => :deci, -2 => :centi, -3 => :mili, -6 => :micro, -9 => :nano, -12 => :pico, -15 => :femto } + INVERTED_DECIMAL_UNITS = DECIMAL_UNITS.invert + + self.namespace = :human + self.validate_float = true + + def convert # :nodoc: + @number = RoundingHelper.new(options).round(number) + @number = Float(number) + + # For backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files. + unless options.key?(:strip_insignificant_zeros) + options[:strip_insignificant_zeros] = true + end + + units = opts[:units] + exponent = calculate_exponent(units) + @number = number / (10**exponent) + + rounded_number = NumberToRoundedConverter.convert(number, options) + unit = determine_unit(units, exponent) + format.gsub("%n", rounded_number).gsub("%u", unit).strip + end + + private + def format + options[:format] || translate_in_locale("human.decimal_units.format") + end + + def determine_unit(units, exponent) + exp = DECIMAL_UNITS[exponent] + case units + when Hash + units[exp] || "" + when String, Symbol + I18n.translate("#{units}.#{exp}", locale: options[:locale], count: number.to_i) + else + translate_in_locale("human.decimal_units.units.#{exp}", count: number.to_i) + end + end + + def calculate_exponent(units) + exponent = number != 0 ? Math.log10(number.abs).floor : 0 + unit_exponents(units).find { |e| exponent >= e } || 0 + end + + def unit_exponents(units) + case units + when Hash + units + when String, Symbol + I18n.translate(units.to_s, locale: options[:locale], raise: true) + when nil + translate_in_locale("human.decimal_units.units", raise: true) + else + raise ArgumentError, ":units must be a Hash or String translation scope." + end.keys.map { |e_name| INVERTED_DECIMAL_UNITS[e_name] }.sort_by(&:-@) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_human_size_converter.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_human_size_converter.rb new file mode 100644 index 0000000..57e1ffe --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_human_size_converter.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +require "active_support/number_helper/number_converter" + +module ActiveSupport + module NumberHelper + class NumberToHumanSizeConverter < NumberConverter # :nodoc: + STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb, :pb, :eb] + + self.namespace = :human + self.validate_float = true + + def convert + @number = Float(number) + + # For backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files. + unless options.key?(:strip_insignificant_zeros) + options[:strip_insignificant_zeros] = true + end + + if smaller_than_base? + number_to_format = number.to_i.to_s + else + human_size = number / (base**exponent) + number_to_format = NumberToRoundedConverter.convert(human_size, options) + end + conversion_format.gsub("%n", number_to_format).gsub("%u", unit) + end + + private + def conversion_format + translate_number_value_with_default("human.storage_units.format", locale: options[:locale], raise: true) + end + + def unit + translate_number_value_with_default(storage_unit_key, locale: options[:locale], count: number.to_i, raise: true) + end + + def storage_unit_key + key_end = smaller_than_base? ? "byte" : STORAGE_UNITS[exponent] + "human.storage_units.units.#{key_end}" + end + + def exponent + max = STORAGE_UNITS.size - 1 + exp = (Math.log(number) / Math.log(base)).to_i + exp = max if exp > max # avoid overflow for the highest unit + exp + end + + def smaller_than_base? + number.to_i < base + end + + def base + 1024 + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_percentage_converter.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_percentage_converter.rb new file mode 100644 index 0000000..0c2e190 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_percentage_converter.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require "active_support/number_helper/number_converter" + +module ActiveSupport + module NumberHelper + class NumberToPercentageConverter < NumberConverter # :nodoc: + self.namespace = :percentage + + def convert + rounded_number = NumberToRoundedConverter.convert(number, options) + options[:format].gsub("%n", rounded_number) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_phone_converter.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_phone_converter.rb new file mode 100644 index 0000000..c9771d0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_phone_converter.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +require "active_support/number_helper/number_converter" + +module ActiveSupport + module NumberHelper + class NumberToPhoneConverter < NumberConverter # :nodoc: + def convert + str = country_code(opts[:country_code]).dup + str << convert_to_phone_number(number.to_s.strip) + str << phone_ext(opts[:extension]) + end + + private + def convert_to_phone_number(number) + if opts[:area_code] + convert_with_area_code(number) + else + convert_without_area_code(number) + end + end + + def convert_with_area_code(number) + default_pattern = /(\d{1,3})(\d{3})(\d{4}$)/ + number.gsub!(regexp_pattern(default_pattern), + "(\\1) \\2#{delimiter}\\3") + number + end + + def convert_without_area_code(number) + default_pattern = /(\d{0,3})(\d{3})(\d{4})$/ + number.gsub!(regexp_pattern(default_pattern), + "\\1#{delimiter}\\2#{delimiter}\\3") + number.slice!(0, 1) if start_with_delimiter?(number) + number + end + + def start_with_delimiter?(number) + delimiter.present? && number.start_with?(delimiter) + end + + def delimiter + opts[:delimiter] || "-" + end + + def country_code(code) + code.blank? ? "" : "+#{code}#{delimiter}" + end + + def phone_ext(ext) + ext.blank? ? "" : " x #{ext}" + end + + def regexp_pattern(default_pattern) + opts.fetch :pattern, default_pattern + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_rounded_converter.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_rounded_converter.rb new file mode 100644 index 0000000..f48a515 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/number_to_rounded_converter.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +require "active_support/number_helper/number_converter" + +module ActiveSupport + module NumberHelper + class NumberToRoundedConverter < NumberConverter # :nodoc: + self.namespace = :precision + self.validate_float = true + + def convert + helper = RoundingHelper.new(options) + rounded_number = helper.round(number) + + if precision = options[:precision] + if options[:significant] && precision > 0 + digits = helper.digit_count(rounded_number) + precision -= digits + precision = 0 if precision < 0 # don't let it be negative + end + + formatted_string = + if rounded_number.finite? + s = rounded_number.to_s("F") + a, b = s.split(".", 2) + if precision != 0 + b << "0" * precision + a << "." + a << b[0, precision] + end + a + else + # Infinity/NaN + "%f" % rounded_number + end + else + formatted_string = rounded_number + end + + delimited_number = NumberToDelimitedConverter.convert(formatted_string, options) + format_number(delimited_number) + end + + private + def strip_insignificant_zeros + options[:strip_insignificant_zeros] + end + + def format_number(number) + if strip_insignificant_zeros + escaped_separator = Regexp.escape(options[:separator]) + number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, "") + else + number + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/rounding_helper.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/rounding_helper.rb new file mode 100644 index 0000000..14deca1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/number_helper/rounding_helper.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +module ActiveSupport + module NumberHelper + class RoundingHelper # :nodoc: + attr_reader :options + + def initialize(options) + @options = options + end + + def round(number) + precision = absolute_precision(number) + return number unless precision + + rounded_number = convert_to_decimal(number).round(precision, options.fetch(:round_mode, :default).to_sym) + rounded_number.zero? ? rounded_number.abs : rounded_number # prevent showing negative zeros + end + + def digit_count(number) + return 1 if number.zero? + (Math.log10(number.abs) + 1).floor + end + + private + def convert_to_decimal(number) + case number + when Float, String + BigDecimal(number.to_s) + when Rational + BigDecimal(number, digit_count(number.to_i) + options[:precision]) + else + number.to_d + end + end + + def absolute_precision(number) + if options[:significant] && options[:precision] > 0 + options[:precision] - digit_count(convert_to_decimal(number)) + else + options[:precision] + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/option_merger.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/option_merger.rb new file mode 100644 index 0000000..4c7720a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/option_merger.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +require "active_support/core_ext/hash/deep_merge" + +module ActiveSupport + class OptionMerger # :nodoc: + instance_methods.each do |method| + undef_method(method) unless method.start_with?("__", "instance_eval", "class", "object_id") + end + + def initialize(context, options) + @context, @options = context, options + end + + private + def method_missing(method, *arguments, &block) + options = nil + if arguments.first.is_a?(Proc) + proc = arguments.pop + arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) } + elsif arguments.last.respond_to?(:to_hash) + options = @options.deep_merge(arguments.pop) + else + options = @options + end + + if options + @context.__send__(method, *arguments, **options, &block) + else + @context.__send__(method, *arguments, &block) + end + end + + def respond_to_missing?(*arguments) + @context.respond_to?(*arguments) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/ordered_hash.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/ordered_hash.rb new file mode 100644 index 0000000..39505bc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/ordered_hash.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true + +require "yaml" + +YAML.add_builtin_type("omap") do |type, val| + ActiveSupport::OrderedHash[val.map { |v| v.to_a.first }] +end + +module ActiveSupport + # DEPRECATED: ActiveSupport::OrderedHash implements a hash that preserves + # insertion order. + # + # oh = ActiveSupport::OrderedHash.new + # oh[:a] = 1 + # oh[:b] = 2 + # oh.keys # => [:a, :b], this order is guaranteed + # + # Also, maps the +omap+ feature for YAML files + # (See https://yaml.org/type/omap.html) to support ordered items + # when loading from yaml. + # + # ActiveSupport::OrderedHash is namespaced to prevent conflicts + # with other implementations. + class OrderedHash < ::Hash # :nodoc: + def to_yaml_type + "!tag:yaml.org,2002:omap" + end + + def encode_with(coder) + coder.represent_seq "!omap", map { |k, v| { k => v } } + end + + def select(*args, &block) + dup.tap { |hash| hash.select!(*args, &block) } + end + + def reject(*args, &block) + dup.tap { |hash| hash.reject!(*args, &block) } + end + + def nested_under_indifferent_access + self + end + + # Returns true to make sure that this hash is extractable via Array#extract_options! + def extractable_options? + true + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/ordered_options.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/ordered_options.rb new file mode 100644 index 0000000..ba14907 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/ordered_options.rb @@ -0,0 +1,95 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/blank" + +module ActiveSupport + # +OrderedOptions+ inherits from +Hash+ and provides dynamic accessor methods. + # + # With a +Hash+, key-value pairs are typically managed like this: + # + # h = {} + # h[:boy] = 'John' + # h[:girl] = 'Mary' + # h[:boy] # => 'John' + # h[:girl] # => 'Mary' + # h[:dog] # => nil + # + # Using +OrderedOptions+, the above code can be written as: + # + # h = ActiveSupport::OrderedOptions.new + # h.boy = 'John' + # h.girl = 'Mary' + # h.boy # => 'John' + # h.girl # => 'Mary' + # h.dog # => nil + # + # To raise an exception when the value is blank, append a + # bang to the key name, like: + # + # h.dog! # => raises KeyError: :dog is blank + # + class OrderedOptions < Hash + alias_method :_get, :[] # preserve the original #[] method + protected :_get # make it protected + + def []=(key, value) + super(key.to_sym, value) + end + + def [](key) + super(key.to_sym) + end + + def method_missing(name, *args) + name_string = +name.to_s + if name_string.chomp!("=") + self[name_string] = args.first + else + bangs = name_string.chomp!("!") + + if bangs + self[name_string].presence || raise(KeyError.new(":#{name_string} is blank")) + else + self[name_string] + end + end + end + + def respond_to_missing?(name, include_private) + true + end + + def extractable_options? + true + end + + def inspect + "#<#{self.class.name} #{super}>" + end + end + + # +InheritableOptions+ provides a constructor to build an +OrderedOptions+ + # hash inherited from another hash. + # + # Use this if you already have some hash and you want to create a new one based on it. + # + # h = ActiveSupport::InheritableOptions.new({ girl: 'Mary', boy: 'John' }) + # h.girl # => 'Mary' + # h.boy # => 'John' + class InheritableOptions < OrderedOptions + def initialize(parent = nil) + if parent.kind_of?(OrderedOptions) + # use the faster _get when dealing with OrderedOptions + super() { |h, k| parent._get(k) } + elsif parent + super() { |h, k| parent[k] } + else + super() + end + end + + def inheritable_copy + self.class.new(self) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/parameter_filter.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/parameter_filter.rb new file mode 100644 index 0000000..b2a19d6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/parameter_filter.rb @@ -0,0 +1,138 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/duplicable" + +module ActiveSupport + # +ParameterFilter+ allows you to specify keys for sensitive data from + # hash-like object and replace corresponding value. Filtering only certain + # sub-keys from a hash is possible by using the dot notation: + # 'credit_card.number'. If a proc is given, each key and value of a hash and + # all sub-hashes are passed to it, where the value or the key can be replaced + # using String#replace or similar methods. + # + # ActiveSupport::ParameterFilter.new([:password]) + # => replaces the value to all keys matching /password/i with "[FILTERED]" + # + # ActiveSupport::ParameterFilter.new([:foo, "bar"]) + # => replaces the value to all keys matching /foo|bar/i with "[FILTERED]" + # + # ActiveSupport::ParameterFilter.new([/\Apin\z/i, /\Apin_/i]) + # => replaces the value for the exact (case-insensitive) key 'pin' and all + # (case-insensitive) keys beginning with 'pin_', with "[FILTERED]". + # Does not match keys with 'pin' as a substring, such as 'shipping_id'. + # + # ActiveSupport::ParameterFilter.new(["credit_card.code"]) + # => replaces { credit_card: {code: "xxxx"} } with "[FILTERED]", does not + # change { file: { code: "xxxx"} } + # + # ActiveSupport::ParameterFilter.new([-> (k, v) do + # v.reverse! if /secret/i.match?(k) + # end]) + # => reverses the value to all keys matching /secret/i + class ParameterFilter + FILTERED = "[FILTERED]" # :nodoc: + + # Create instance with given filters. Supported type of filters are +String+, +Regexp+, and +Proc+. + # Other types of filters are treated as +String+ using +to_s+. + # For +Proc+ filters, key, value, and optional original hash is passed to block arguments. + # + # ==== Options + # + # * :mask - A replaced object when filtered. Defaults to "[FILTERED]". + def initialize(filters = [], mask: FILTERED) + @filters = filters + @mask = mask + end + + # Mask value of +params+ if key matches one of filters. + def filter(params) + compiled_filter.call(params) + end + + # Returns filtered value for given key. For +Proc+ filters, third block argument is not populated. + def filter_param(key, value) + @filters.empty? ? value : compiled_filter.value_for_key(key, value) + end + + private + def compiled_filter + @compiled_filter ||= CompiledFilter.compile(@filters, mask: @mask) + end + + class CompiledFilter # :nodoc: + def self.compile(filters, mask:) + return lambda { |params| params.dup } if filters.empty? + + strings, regexps, blocks, deep_regexps, deep_strings = [], [], [], nil, nil + + filters.each do |item| + case item + when Proc + blocks << item + when Regexp + if item.to_s.include?("\\.") + (deep_regexps ||= []) << item + else + regexps << item + end + else + s = Regexp.escape(item.to_s) + if s.include?("\\.") + (deep_strings ||= []) << s + else + strings << s + end + end + end + + regexps << Regexp.new(strings.join("|"), true) unless strings.empty? + (deep_regexps ||= []) << Regexp.new(deep_strings.join("|"), true) if deep_strings&.any? + + new regexps, deep_regexps, blocks, mask: mask + end + + attr_reader :regexps, :deep_regexps, :blocks + + def initialize(regexps, deep_regexps, blocks, mask:) + @regexps = regexps + @deep_regexps = deep_regexps&.any? ? deep_regexps : nil + @blocks = blocks + @mask = mask + end + + def call(params, parents = [], original_params = params) + filtered_params = params.class.new + + params.each do |key, value| + filtered_params[key] = value_for_key(key, value, parents, original_params) + end + + filtered_params + end + + def value_for_key(key, value, parents = [], original_params = nil) + parents.push(key) if deep_regexps + if regexps.any? { |r| r.match?(key.to_s) } + value = @mask + elsif deep_regexps && (joined = parents.join(".")) && deep_regexps.any? { |r| r.match?(joined) } + value = @mask + elsif value.is_a?(Hash) + value = call(value, parents, original_params) + elsif value.is_a?(Array) + # If we don't pop the current parent it will be duplicated as we + # process each array value. + parents.pop if deep_regexps + value = value.map { |v| value_for_key(key, v, parents, original_params) } + # Restore the parent stack after processing the array. + parents.push(key) if deep_regexps + elsif blocks.any? + key = key.dup if key.duplicable? + value = value.dup if value.duplicable? + blocks.each { |b| b.arity == 2 ? b.call(key, value) : b.call(key, value, original_params) } + end + parents.pop if deep_regexps + value + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/per_thread_registry.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/per_thread_registry.rb new file mode 100644 index 0000000..cd8db91 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/per_thread_registry.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/delegation" + +module ActiveSupport + # NOTE: This approach has been deprecated for end-user code in favor of {thread_mattr_accessor}[rdoc-ref:Module#thread_mattr_accessor] and friends. + # Please use that approach instead. + # + # This module is used to encapsulate access to thread local variables. + # + # Instead of polluting the thread locals namespace: + # + # Thread.current[:connection_handler] + # + # you define a class that extends this module: + # + # module ActiveRecord + # class RuntimeRegistry + # extend ActiveSupport::PerThreadRegistry + # + # attr_accessor :connection_handler + # end + # end + # + # and invoke the declared instance accessors as class methods. So + # + # ActiveRecord::RuntimeRegistry.connection_handler = connection_handler + # + # sets a connection handler local to the current thread, and + # + # ActiveRecord::RuntimeRegistry.connection_handler + # + # returns a connection handler local to the current thread. + # + # This feature is accomplished by instantiating the class and storing the + # instance as a thread local keyed by the class name. In the example above + # a key "ActiveRecord::RuntimeRegistry" is stored in Thread.current. + # The class methods proxy to said thread local instance. + # + # If the class has an initializer, it must accept no arguments. + module PerThreadRegistry + def self.extended(object) + ActiveSupport::Deprecation.warn(<<~MSG) + ActiveSupport::PerThreadRegistry is deprecated and will be removed in Rails 7.1. + Use `Module#thread_mattr_accessor` instead. + MSG + object.instance_variable_set :@per_thread_registry_key, object.name.freeze + end + + def instance + Thread.current[@per_thread_registry_key] ||= new + end + + private + def method_missing(name, *args, &block) + # Caches the method definition as a singleton method of the receiver. + # + # By letting #delegate handle it, we avoid an enclosure that'll capture args. + singleton_class.delegate name, to: :instance + + send(name, *args, &block) + end + ruby2_keywords(:method_missing) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/proxy_object.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/proxy_object.rb new file mode 100644 index 0000000..0965fcd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/proxy_object.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module ActiveSupport + # A class with no predefined methods that behaves similarly to Builder's + # BlankSlate. Used for proxy classes. + class ProxyObject < ::BasicObject + undef_method :== + undef_method :equal? + + # Let ActiveSupport::ProxyObject at least raise exceptions. + def raise(*args) + ::Object.send(:raise, *args) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/rails.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/rails.rb new file mode 100644 index 0000000..75676a2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/rails.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +# This is a private interface. +# +# Rails components cherry pick from Active Support as needed, but there are a +# few features that are used for sure in some way or another and it is not worth +# putting individual requires absolutely everywhere. Think blank? for example. +# +# This file is loaded by every Rails component except Active Support itself, +# but it does not belong to the Rails public interface. It is internal to +# Rails and can change anytime. + +# Defines Object#blank? and Object#present?. +require "active_support/core_ext/object/blank" + +# Support for ClassMethods and the included macro. +require "active_support/concern" + +# Defines Class#class_attribute. +require "active_support/core_ext/class/attribute" + +# Defines Module#delegate. +require "active_support/core_ext/module/delegation" + +# Defines ActiveSupport::Deprecation. +require "active_support/deprecation" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/railtie.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/railtie.rb new file mode 100644 index 0000000..6ddd58a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/railtie.rb @@ -0,0 +1,152 @@ +# frozen_string_literal: true + +require "active_support" +require "active_support/i18n_railtie" + +module ActiveSupport + class Railtie < Rails::Railtie # :nodoc: + config.active_support = ActiveSupport::OrderedOptions.new + config.active_support.disable_to_s_conversion = false + + config.eager_load_namespaces << ActiveSupport + + initializer "active_support.isolation_level" do |app| + if level = app.config.active_support.delete(:isolation_level) + ActiveSupport::IsolatedExecutionState.isolation_level = level + end + end + + initializer "active_support.remove_deprecated_time_with_zone_name" do |app| + config.after_initialize do + if app.config.active_support.remove_deprecated_time_with_zone_name + require "active_support/time_with_zone" + TimeWithZone.singleton_class.remove_method(:name) + end + end + end + + initializer "active_support.set_authenticated_message_encryption" do |app| + config.after_initialize do + unless app.config.active_support.use_authenticated_message_encryption.nil? + ActiveSupport::MessageEncryptor.use_authenticated_message_encryption = + app.config.active_support.use_authenticated_message_encryption + end + end + end + + initializer "active_support.reset_execution_context" do |app| + app.reloader.before_class_unload { ActiveSupport::ExecutionContext.clear } + app.executor.to_run { ActiveSupport::ExecutionContext.clear } + app.executor.to_complete { ActiveSupport::ExecutionContext.clear } + end + + initializer "active_support.reset_all_current_attributes_instances" do |app| + executor_around_test_case = app.config.active_support.executor_around_test_case + + app.reloader.before_class_unload { ActiveSupport::CurrentAttributes.clear_all } + app.executor.to_run { ActiveSupport::CurrentAttributes.reset_all } + app.executor.to_complete { ActiveSupport::CurrentAttributes.reset_all } + + ActiveSupport.on_load(:active_support_test_case) do + if executor_around_test_case + require "active_support/executor/test_helper" + include ActiveSupport::Executor::TestHelper + else + require "active_support/current_attributes/test_helper" + include ActiveSupport::CurrentAttributes::TestHelper + + require "active_support/execution_context/test_helper" + include ActiveSupport::ExecutionContext::TestHelper + end + end + end + + initializer "active_support.deprecation_behavior" do |app| + if app.config.active_support.report_deprecations == false + ActiveSupport::Deprecation.silenced = true + ActiveSupport::Deprecation.behavior = :silence + ActiveSupport::Deprecation.disallowed_behavior = :silence + else + if deprecation = app.config.active_support.deprecation + ActiveSupport::Deprecation.behavior = deprecation + end + + if disallowed_deprecation = app.config.active_support.disallowed_deprecation + ActiveSupport::Deprecation.disallowed_behavior = disallowed_deprecation + end + + if disallowed_warnings = app.config.active_support.disallowed_deprecation_warnings + ActiveSupport::Deprecation.disallowed_warnings = disallowed_warnings + end + end + end + + # Sets the default value for Time.zone + # If assigned value cannot be matched to a TimeZone, an exception will be raised. + initializer "active_support.initialize_time_zone" do |app| + begin + TZInfo::DataSource.get + rescue TZInfo::DataSourceNotFound => e + raise e.exception "tzinfo-data is not present. Please add gem 'tzinfo-data' to your Gemfile and run bundle install" + end + require "active_support/core_ext/time/zones" + Time.zone_default = Time.find_zone!(app.config.time_zone) + end + + # Sets the default week start + # If assigned value is not a valid day symbol (e.g. :sunday, :monday, ...), an exception will be raised. + initializer "active_support.initialize_beginning_of_week" do |app| + require "active_support/core_ext/date/calculations" + beginning_of_week_default = Date.find_beginning_of_week!(app.config.beginning_of_week) + + Date.beginning_of_week_default = beginning_of_week_default + end + + initializer "active_support.require_master_key" do |app| + if app.config.respond_to?(:require_master_key) && app.config.require_master_key + begin + app.credentials.key + rescue ActiveSupport::EncryptedFile::MissingKeyError => error + $stderr.puts error.message + exit 1 + end + end + end + + initializer "active_support.set_error_reporter" do |app| + ActiveSupport.error_reporter = app.executor.error_reporter + end + + initializer "active_support.set_configs" do |app| + app.config.active_support.each do |k, v| + k = "#{k}=" + ActiveSupport.public_send(k, v) if ActiveSupport.respond_to? k + end + end + + initializer "active_support.set_hash_digest_class" do |app| + config.after_initialize do + if klass = app.config.active_support.hash_digest_class + ActiveSupport::Digest.hash_digest_class = klass + end + end + end + + initializer "active_support.set_key_generator_hash_digest_class" do |app| + config.after_initialize do + if klass = app.config.active_support.key_generator_hash_digest_class + ActiveSupport::KeyGenerator.hash_digest_class = klass + end + end + end + + initializer "active_support.set_rfc4122_namespaced_uuids" do |app| + config.after_initialize do + if app.config.active_support.use_rfc4122_namespaced_uuids + require "active_support/core_ext/digest" + ::Digest::UUID.use_rfc4122_namespaced_uuids = app.config.active_support.use_rfc4122_namespaced_uuids + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/reloader.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/reloader.rb new file mode 100644 index 0000000..e751866 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/reloader.rb @@ -0,0 +1,130 @@ +# frozen_string_literal: true + +require "active_support/execution_wrapper" +require "active_support/executor" + +module ActiveSupport + #-- + # This class defines several callbacks: + # + # to_prepare -- Run once at application startup, and also from + # +to_run+. + # + # to_run -- Run before a work run that is reloading. If + # +reload_classes_only_on_change+ is true (the default), the class + # unload will have already occurred. + # + # to_complete -- Run after a work run that has reloaded. If + # +reload_classes_only_on_change+ is false, the class unload will + # have occurred after the work run, but before this callback. + # + # before_class_unload -- Run immediately before the classes are + # unloaded. + # + # after_class_unload -- Run immediately after the classes are + # unloaded. + # + class Reloader < ExecutionWrapper + define_callbacks :prepare + + define_callbacks :class_unload + + # Registers a callback that will run once at application startup and every time the code is reloaded. + def self.to_prepare(*args, &block) + set_callback(:prepare, *args, &block) + end + + # Registers a callback that will run immediately before the classes are unloaded. + def self.before_class_unload(*args, &block) + set_callback(:class_unload, *args, &block) + end + + # Registers a callback that will run immediately after the classes are unloaded. + def self.after_class_unload(*args, &block) + set_callback(:class_unload, :after, *args, &block) + end + + to_run(:after) { self.class.prepare! } + + # Initiate a manual reload + def self.reload! + executor.wrap do + new.tap do |instance| + instance.run! + ensure + instance.complete! + end + end + prepare! + end + + def self.run!(reset: false) # :nodoc: + if check! + super + else + Null + end + end + + # Run the supplied block as a work unit, reloading code as needed + def self.wrap + executor.wrap do + super + end + end + + class_attribute :executor, default: Executor + class_attribute :check, default: lambda { false } + + def self.check! # :nodoc: + @should_reload ||= check.call + end + + def self.reloaded! # :nodoc: + @should_reload = false + end + + def self.prepare! # :nodoc: + new.run_callbacks(:prepare) + end + + def initialize + super + @locked = false + end + + # Acquire the ActiveSupport::Dependencies::Interlock unload lock, + # ensuring it will be released automatically + def require_unload_lock! + unless @locked + ActiveSupport::Dependencies.interlock.start_unloading + @locked = true + end + end + + # Release the unload lock if it has been previously obtained + def release_unload_lock! + if @locked + @locked = false + ActiveSupport::Dependencies.interlock.done_unloading + end + end + + def run! # :nodoc: + super + release_unload_lock! + end + + def class_unload!(&block) # :nodoc: + require_unload_lock! + run_callbacks(:class_unload, &block) + end + + def complete! # :nodoc: + super + self.class.reloaded! + ensure + release_unload_lock! + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/rescuable.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/rescuable.rb new file mode 100644 index 0000000..3e316d0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/rescuable.rb @@ -0,0 +1,174 @@ +# frozen_string_literal: true + +require "active_support/concern" +require "active_support/core_ext/class/attribute" +require "active_support/core_ext/string/inflections" + +module ActiveSupport + # Rescuable module adds support for easier exception handling. + module Rescuable + extend Concern + + included do + class_attribute :rescue_handlers, default: [] + end + + module ClassMethods + # Registers exception classes with a handler to be called by rescue_with_handler. + # + # rescue_from receives a series of exception classes or class + # names, and an exception handler specified by a trailing :with + # option containing the name of a method or a Proc object. Alternatively, a block + # can be given as the handler. + # + # Handlers that take one argument will be called with the exception, so + # that the exception can be inspected when dealing with it. + # + # Handlers are inherited. They are searched from right to left, from + # bottom to top, and up the hierarchy. The handler of the first class for + # which exception.is_a?(klass) holds true is the one invoked, if + # any. + # + # class ApplicationController < ActionController::Base + # rescue_from User::NotAuthorized, with: :deny_access # self defined exception + # rescue_from ActiveRecord::RecordInvalid, with: :show_errors + # + # rescue_from 'MyAppError::Base' do |exception| + # render xml: exception, status: 500 + # end + # + # private + # def deny_access + # ... + # end + # + # def show_errors(exception) + # exception.record.new_record? ? ... + # end + # end + # + # Exceptions raised inside exception handlers are not propagated up. + def rescue_from(*klasses, with: nil, &block) + unless with + if block_given? + with = block + else + raise ArgumentError, "Need a handler. Pass the with: keyword argument or provide a block." + end + end + + klasses.each do |klass| + key = if klass.is_a?(Module) && klass.respond_to?(:===) + klass.name + elsif klass.is_a?(String) + klass + else + raise ArgumentError, "#{klass.inspect} must be an Exception class or a String referencing an Exception class" + end + + # Put the new handler at the end because the list is read in reverse. + self.rescue_handlers += [[key, with]] + end + end + + # Matches an exception to a handler based on the exception class. + # + # If no handler matches the exception, check for a handler matching the + # (optional) exception.cause. If no handler matches the exception or its + # cause, this returns +nil+, so you can deal with unhandled exceptions. + # Be sure to re-raise unhandled exceptions if this is what you expect. + # + # begin + # … + # rescue => exception + # rescue_with_handler(exception) || raise + # end + # + # Returns the exception if it was handled and +nil+ if it was not. + def rescue_with_handler(exception, object: self, visited_exceptions: []) + visited_exceptions << exception + + if handler = handler_for_rescue(exception, object: object) + handler.call exception + exception + elsif exception + if visited_exceptions.include?(exception.cause) + nil + else + rescue_with_handler(exception.cause, object: object, visited_exceptions: visited_exceptions) + end + end + end + + def handler_for_rescue(exception, object: self) # :nodoc: + case rescuer = find_rescue_handler(exception) + when Symbol + method = object.method(rescuer) + if method.arity == 0 + -> e { method.call } + else + method + end + when Proc + if rescuer.arity == 0 + -> e { object.instance_exec(&rescuer) } + else + -> e { object.instance_exec(e, &rescuer) } + end + end + end + + private + def find_rescue_handler(exception) + if exception + # Handlers are in order of declaration but the most recently declared + # is the highest priority match, so we search for matching handlers + # in reverse. + _, handler = rescue_handlers.reverse_each.detect do |class_or_name, _| + if klass = constantize_rescue_handler_class(class_or_name) + klass === exception + end + end + + handler + end + end + + def constantize_rescue_handler_class(class_or_name) + case class_or_name + when String, Symbol + begin + # Try a lexical lookup first since we support + # + # class Super + # rescue_from 'Error', with: … + # end + # + # class Sub + # class Error < StandardError; end + # end + # + # so an Error raised in Sub will hit the 'Error' handler. + const_get class_or_name + rescue NameError + class_or_name.safe_constantize + end + else + class_or_name + end + end + end + + # Delegates to the class method, but uses the instance as the subject for + # rescue_from handlers (method calls, instance_exec blocks). + def rescue_with_handler(exception) + self.class.rescue_with_handler exception, object: self + end + + # Internal handler lookup. Delegates to class method. Some libraries call + # this directly, so keeping it around for compatibility. + def handler_for_rescue(exception) # :nodoc: + self.class.handler_for_rescue exception, object: self + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/ruby_features.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/ruby_features.rb new file mode 100644 index 0000000..8cdb89c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/ruby_features.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +module ActiveSupport + module RubyFeatures # :nodoc: + CLASS_SUBCLASSES = Class.method_defined?(:subclasses) # RUBY_VERSION >= "3.1" + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/secure_compare_rotator.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/secure_compare_rotator.rb new file mode 100644 index 0000000..b586982 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/secure_compare_rotator.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require "active_support/security_utils" +require "active_support/messages/rotator" + +module ActiveSupport + # The ActiveSupport::SecureCompareRotator is a wrapper around +ActiveSupport::SecurityUtils.secure_compare+ + # and allows you to rotate a previously defined value to a new one. + # + # It can be used as follow: + # + # rotator = ActiveSupport::SecureCompareRotator.new('new_production_value') + # rotator.rotate('previous_production_value') + # rotator.secure_compare!('previous_production_value') + # + # One real use case example would be to rotate a basic auth credentials: + # + # class MyController < ApplicationController + # def authenticate_request + # rotator = ActiveSupport::SecureCompareRotator.new('new_password') + # rotator.rotate('old_password') + # + # authenticate_or_request_with_http_basic do |username, password| + # rotator.secure_compare!(password) + # rescue ActiveSupport::SecureCompareRotator::InvalidMatch + # false + # end + # end + # end + class SecureCompareRotator + include SecurityUtils + prepend Messages::Rotator + + InvalidMatch = Class.new(StandardError) + + def initialize(value, **_options) + @value = value + end + + def secure_compare!(other_value, on_rotation: @on_rotation) + secure_compare(@value, other_value) || + run_rotations(on_rotation) { |wrapper| wrapper.secure_compare!(other_value) } || + raise(InvalidMatch) + end + + private + def build_rotation(previous_value, _options) + self.class.new(previous_value) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/security_utils.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/security_utils.rb new file mode 100644 index 0000000..aa00474 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/security_utils.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +module ActiveSupport + module SecurityUtils + # Constant time string comparison, for fixed length strings. + # + # The values compared should be of fixed length, such as strings + # that have already been processed by HMAC. Raises in case of length mismatch. + + if defined?(OpenSSL.fixed_length_secure_compare) + def fixed_length_secure_compare(a, b) + OpenSSL.fixed_length_secure_compare(a, b) + end + else + def fixed_length_secure_compare(a, b) + raise ArgumentError, "string length mismatch." unless a.bytesize == b.bytesize + + l = a.unpack "C#{a.bytesize}" + + res = 0 + b.each_byte { |byte| res |= byte ^ l.shift } + res == 0 + end + end + module_function :fixed_length_secure_compare + + # Secure string comparison for strings of variable length. + # + # While a timing attack would not be able to discern the content of + # a secret compared via secure_compare, it is possible to determine + # the secret length. This should be considered when using secure_compare + # to compare weak, short secrets to user input. + def secure_compare(a, b) + a.bytesize == b.bytesize && fixed_length_secure_compare(a, b) + end + module_function :secure_compare + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/string_inquirer.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/string_inquirer.rb new file mode 100644 index 0000000..8c4bf55 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/string_inquirer.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +module ActiveSupport + # Wrapping a string in this class gives you a prettier way to test + # for equality. The value returned by Rails.env is wrapped + # in a StringInquirer object, so instead of calling this: + # + # Rails.env == 'production' + # + # you can call this: + # + # Rails.env.production? + # + # == Instantiating a new StringInquirer + # + # vehicle = ActiveSupport::StringInquirer.new('car') + # vehicle.car? # => true + # vehicle.bike? # => false + class StringInquirer < String + private + def respond_to_missing?(method_name, include_private = false) + method_name.end_with?("?") || super + end + + def method_missing(method_name, *arguments) + if method_name.end_with?("?") + self == method_name[0..-2] + else + super + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/subscriber.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/subscriber.rb new file mode 100644 index 0000000..0f71443 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/subscriber.rb @@ -0,0 +1,163 @@ +# frozen_string_literal: true + +require "active_support/notifications" + +module ActiveSupport + # ActiveSupport::Subscriber is an object set to consume + # ActiveSupport::Notifications. The subscriber dispatches notifications to + # a registered object based on its given namespace. + # + # An example would be an Active Record subscriber responsible for collecting + # statistics about queries: + # + # module ActiveRecord + # class StatsSubscriber < ActiveSupport::Subscriber + # attach_to :active_record + # + # def sql(event) + # Statsd.timing("sql.#{event.payload[:name]}", event.duration) + # end + # end + # end + # + # After configured, whenever a "sql.active_record" notification is published, + # it will properly dispatch the event (ActiveSupport::Notifications::Event) to + # the +sql+ method. + # + # We can detach a subscriber as well: + # + # ActiveRecord::StatsSubscriber.detach_from(:active_record) + class Subscriber + class << self + # Attach the subscriber to a namespace. + def attach_to(namespace, subscriber = new, notifier = ActiveSupport::Notifications, inherit_all: false) + @namespace = namespace + @subscriber = subscriber + @notifier = notifier + @inherit_all = inherit_all + + subscribers << subscriber + + # Add event subscribers for all existing methods on the class. + fetch_public_methods(subscriber, inherit_all).each do |event| + add_event_subscriber(event) + end + end + + # Detach the subscriber from a namespace. + def detach_from(namespace, notifier = ActiveSupport::Notifications) + @namespace = namespace + @subscriber = find_attached_subscriber + @notifier = notifier + + return unless subscriber + + subscribers.delete(subscriber) + + # Remove event subscribers of all existing methods on the class. + fetch_public_methods(subscriber, true).each do |event| + remove_event_subscriber(event) + end + + # Reset notifier so that event subscribers will not add for new methods added to the class. + @notifier = nil + end + + # Adds event subscribers for all new methods added to the class. + def method_added(event) + # Only public methods are added as subscribers, and only if a notifier + # has been set up. This means that subscribers will only be set up for + # classes that call #attach_to. + if public_method_defined?(event) && notifier + add_event_subscriber(event) + end + end + + def subscribers + @@subscribers ||= [] + end + + private + attr_reader :subscriber, :notifier, :namespace + + def add_event_subscriber(event) # :doc: + return if invalid_event?(event) + + pattern = prepare_pattern(event) + + # Don't add multiple subscribers (e.g. if methods are redefined). + return if pattern_subscribed?(pattern) + + subscriber.patterns[pattern] = notifier.subscribe(pattern, subscriber) + end + + def remove_event_subscriber(event) # :doc: + return if invalid_event?(event) + + pattern = prepare_pattern(event) + + return unless pattern_subscribed?(pattern) + + notifier.unsubscribe(subscriber.patterns[pattern]) + subscriber.patterns.delete(pattern) + end + + def find_attached_subscriber + subscribers.find { |attached_subscriber| attached_subscriber.instance_of?(self) } + end + + def invalid_event?(event) + %i{ start finish }.include?(event.to_sym) + end + + def prepare_pattern(event) + "#{event}.#{namespace}" + end + + def pattern_subscribed?(pattern) + subscriber.patterns.key?(pattern) + end + + def fetch_public_methods(subscriber, inherit_all) + subscriber.public_methods(inherit_all) - Subscriber.public_instance_methods(true) + end + end + + attr_reader :patterns # :nodoc: + + def initialize + @queue_key = [self.class.name, object_id].join "-" + @patterns = {} + super + end + + def start(name, id, payload) + event = ActiveSupport::Notifications::Event.new(name, nil, nil, id, payload) + event.start! + parent = event_stack.last + parent << event if parent + + event_stack.push event + end + + def finish(name, id, payload) + event = event_stack.pop + event.finish! + event.payload.merge!(payload) + + method = name.split(".").first + send(method, event) + end + + def publish_event(event) # :nodoc: + method = event.name.split(".").first + send(method, event) + end + + private + def event_stack + registry = ActiveSupport::IsolatedExecutionState[:active_support_subscriber_queue_registry] ||= {} + registry[@queue_key] ||= [] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/tagged_logging.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/tagged_logging.rb new file mode 100644 index 0000000..26852e5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/tagged_logging.rb @@ -0,0 +1,113 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/delegation" +require "active_support/core_ext/object/blank" +require "logger" +require "active_support/logger" + +module ActiveSupport + # Wraps any standard Logger object to provide tagging capabilities. + # + # May be called with a block: + # + # logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT)) + # logger.tagged('BCX') { logger.info 'Stuff' } # Logs "[BCX] Stuff" + # logger.tagged('BCX', "Jason") { logger.info 'Stuff' } # Logs "[BCX] [Jason] Stuff" + # logger.tagged('BCX') { logger.tagged('Jason') { logger.info 'Stuff' } } # Logs "[BCX] [Jason] Stuff" + # + # If called without a block, a new logger will be returned with applied tags: + # + # logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT)) + # logger.tagged("BCX").info "Stuff" # Logs "[BCX] Stuff" + # logger.tagged("BCX", "Jason").info "Stuff" # Logs "[BCX] [Jason] Stuff" + # logger.tagged("BCX").tagged("Jason").info "Stuff" # Logs "[BCX] [Jason] Stuff" + # + # This is used by the default Rails.logger as configured by Railties to make + # it easy to stamp log lines with subdomains, request ids, and anything else + # to aid debugging of multi-user production applications. + module TaggedLogging + module Formatter # :nodoc: + # This method is invoked when a log event occurs. + def call(severity, timestamp, progname, msg) + super(severity, timestamp, progname, "#{tags_text}#{msg}") + end + + def tagged(*tags) + new_tags = push_tags(*tags) + yield self + ensure + pop_tags(new_tags.size) + end + + def push_tags(*tags) + tags.flatten! + tags.reject!(&:blank?) + current_tags.concat tags + tags + end + + def pop_tags(size = 1) + current_tags.pop size + end + + def clear_tags! + current_tags.clear + end + + def current_tags + # We use our object ID here to avoid conflicting with other instances + thread_key = @thread_key ||= "activesupport_tagged_logging_tags:#{object_id}" + IsolatedExecutionState[thread_key] ||= [] + end + + def tags_text + tags = current_tags + if tags.one? + "[#{tags[0]}] " + elsif tags.any? + tags.collect { |tag| "[#{tag}] " }.join + end + end + end + + module LocalTagStorage # :nodoc: + attr_accessor :current_tags + + def self.extended(base) + base.current_tags = [] + end + end + + def self.new(logger) + logger = logger.clone + + if logger.formatter + logger.formatter = logger.formatter.dup + else + # Ensure we set a default formatter so we aren't extending nil! + logger.formatter = ActiveSupport::Logger::SimpleFormatter.new + end + + logger.formatter.extend Formatter + logger.extend(self) + end + + delegate :push_tags, :pop_tags, :clear_tags!, to: :formatter + + def tagged(*tags) + if block_given? + formatter.tagged(*tags) { yield self } + else + logger = ActiveSupport::TaggedLogging.new(self) + logger.formatter.extend LocalTagStorage + logger.push_tags(*formatter.current_tags, *tags) + logger + end + end + + def flush + clear_tags! + super if defined?(super) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/test_case.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/test_case.rb new file mode 100644 index 0000000..a2b205c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/test_case.rb @@ -0,0 +1,151 @@ +# frozen_string_literal: true + +gem "minitest" # make sure we get the gem, not stdlib +require "minitest" +require "active_support/testing/tagged_logging" +require "active_support/testing/setup_and_teardown" +require "active_support/testing/assertions" +require "active_support/testing/deprecation" +require "active_support/testing/declarative" +require "active_support/testing/isolation" +require "active_support/testing/constant_lookup" +require "active_support/testing/time_helpers" +require "active_support/testing/file_fixtures" +require "active_support/testing/parallelization" +require "active_support/testing/parallelize_executor" +require "concurrent/utility/processor_counter" + +module ActiveSupport + class TestCase < ::Minitest::Test + Assertion = Minitest::Assertion + + class << self + # Sets the order in which test cases are run. + # + # ActiveSupport::TestCase.test_order = :random # => :random + # + # Valid values are: + # * +:random+ (to run tests in random order) + # * +:parallel+ (to run tests in parallel) + # * +:sorted+ (to run tests alphabetically by method name) + # * +:alpha+ (equivalent to +:sorted+) + def test_order=(new_order) + ActiveSupport.test_order = new_order + end + + # Returns the order in which test cases are run. + # + # ActiveSupport::TestCase.test_order # => :random + # + # Possible values are +:random+, +:parallel+, +:alpha+, +:sorted+. + # Defaults to +:random+. + def test_order + ActiveSupport.test_order ||= :random + end + + # Parallelizes the test suite. + # + # Takes a +workers+ argument that controls how many times the process + # is forked. For each process a new database will be created suffixed + # with the worker number. + # + # test-database-0 + # test-database-1 + # + # If ENV["PARALLEL_WORKERS"] is set the workers argument will be ignored + # and the environment variable will be used instead. This is useful for CI + # environments, or other environments where you may need more workers than + # you do for local testing. + # + # If the number of workers is set to +1+ or fewer, the tests will not be + # parallelized. + # + # If +workers+ is set to +:number_of_processors+, the number of workers will be + # set to the actual core count on the machine you are on. + # + # The default parallelization method is to fork processes. If you'd like to + # use threads instead you can pass with: :threads to the +parallelize+ + # method. Note the threaded parallelization does not create multiple + # database and will not work with system tests at this time. + # + # parallelize(workers: :number_of_processors, with: :threads) + # + # The threaded parallelization uses minitest's parallel executor directly. + # The processes parallelization uses a Ruby DRb server. + # + # Because parallelization presents an overhead, it is only enabled when the + # number of tests to run is above the +threshold+ param. The default value is + # 50, and it's configurable via +config.active_support.test_parallelization_threshold+. + def parallelize(workers: :number_of_processors, with: :processes, threshold: ActiveSupport.test_parallelization_threshold) + workers = Concurrent.physical_processor_count if workers == :number_of_processors + workers = ENV["PARALLEL_WORKERS"].to_i if ENV["PARALLEL_WORKERS"] + + return if workers <= 1 + + Minitest.parallel_executor = ActiveSupport::Testing::ParallelizeExecutor.new(size: workers, with: with, threshold: threshold) + end + + # Set up hook for parallel testing. This can be used if you have multiple + # databases or any behavior that needs to be run after the process is forked + # but before the tests run. + # + # Note: this feature is not available with the threaded parallelization. + # + # In your +test_helper.rb+ add the following: + # + # class ActiveSupport::TestCase + # parallelize_setup do + # # create databases + # end + # end + def parallelize_setup(&block) + ActiveSupport::Testing::Parallelization.after_fork_hook(&block) + end + + # Clean up hook for parallel testing. This can be used to drop databases + # if your app uses multiple write/read databases or other clean up before + # the tests finish. This runs before the forked process is closed. + # + # Note: this feature is not available with the threaded parallelization. + # + # In your +test_helper.rb+ add the following: + # + # class ActiveSupport::TestCase + # parallelize_teardown do + # # drop databases + # end + # end + def parallelize_teardown(&block) + ActiveSupport::Testing::Parallelization.run_cleanup_hook(&block) + end + end + + alias_method :method_name, :name + + include ActiveSupport::Testing::TaggedLogging + prepend ActiveSupport::Testing::SetupAndTeardown + include ActiveSupport::Testing::Assertions + include ActiveSupport::Testing::Deprecation + include ActiveSupport::Testing::TimeHelpers + include ActiveSupport::Testing::FileFixtures + extend ActiveSupport::Testing::Declarative + + # test/unit backwards compatibility methods + alias :assert_raise :assert_raises + alias :assert_not_empty :refute_empty + alias :assert_not_equal :refute_equal + alias :assert_not_in_delta :refute_in_delta + alias :assert_not_in_epsilon :refute_in_epsilon + alias :assert_not_includes :refute_includes + alias :assert_not_instance_of :refute_instance_of + alias :assert_not_kind_of :refute_kind_of + alias :assert_no_match :refute_match + alias :assert_not_nil :refute_nil + alias :assert_not_operator :refute_operator + alias :assert_not_predicate :refute_predicate + alias :assert_not_respond_to :refute_respond_to + alias :assert_not_same :refute_same + + ActiveSupport.run_load_hooks(:active_support_test_case, self) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/assertions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/assertions.rb new file mode 100644 index 0000000..63344d0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/assertions.rb @@ -0,0 +1,265 @@ +# frozen_string_literal: true + +require "active_support/core_ext/enumerable" + +module ActiveSupport + module Testing + module Assertions + UNTRACKED = Object.new # :nodoc: + + # Asserts that an expression is not truthy. Passes if object is + # +nil+ or +false+. "Truthy" means "considered true in a conditional" + # like if foo. + # + # assert_not nil # => true + # assert_not false # => true + # assert_not 'foo' # => Expected "foo" to be nil or false + # + # An error message can be specified. + # + # assert_not foo, 'foo should be false' + def assert_not(object, message = nil) + message ||= "Expected #{mu_pp(object)} to be nil or false" + assert !object, message + end + + # Assertion that the block should not raise an exception. + # + # Passes if evaluated code in the yielded block raises no exception. + # + # assert_nothing_raised do + # perform_service(param: 'no_exception') + # end + def assert_nothing_raised + yield + rescue => error + raise Minitest::UnexpectedError.new(error) + end + + # Test numeric difference between the return value of an expression as a + # result of what is evaluated in the yielded block. + # + # assert_difference 'Article.count' do + # post :create, params: { article: {...} } + # end + # + # An arbitrary expression is passed in and evaluated. + # + # assert_difference 'Article.last.comments(:reload).size' do + # post :create, params: { comment: {...} } + # end + # + # An arbitrary positive or negative difference can be specified. + # The default is 1. + # + # assert_difference 'Article.count', -1 do + # post :delete, params: { id: ... } + # end + # + # An array of expressions can also be passed in and evaluated. + # + # assert_difference [ 'Article.count', 'Post.count' ], 2 do + # post :create, params: { article: {...} } + # end + # + # A hash of expressions/numeric differences can also be passed in and evaluated. + # + # assert_difference ->{ Article.count } => 1, ->{ Notification.count } => 2 do + # post :create, params: { article: {...} } + # end + # + # A lambda or a list of lambdas can be passed in and evaluated: + # + # assert_difference ->{ Article.count }, 2 do + # post :create, params: { article: {...} } + # end + # + # assert_difference [->{ Article.count }, ->{ Post.count }], 2 do + # post :create, params: { article: {...} } + # end + # + # An error message can be specified. + # + # assert_difference 'Article.count', -1, 'An Article should be destroyed' do + # post :delete, params: { id: ... } + # end + def assert_difference(expression, *args, &block) + expressions = + if expression.is_a?(Hash) + message = args[0] + expression + else + difference = args[0] || 1 + message = args[1] + Array(expression).index_with(difference) + end + + exps = expressions.keys.map { |e| + e.respond_to?(:call) ? e : lambda { eval(e, block.binding) } + } + before = exps.map(&:call) + + retval = _assert_nothing_raised_or_warn("assert_difference", &block) + + expressions.zip(exps, before) do |(code, diff), exp, before_value| + error = "#{code.inspect} didn't change by #{diff}" + error = "#{message}.\n#{error}" if message + assert_equal(before_value + diff, exp.call, error) + end + + retval + end + + # Assertion that the numeric result of evaluating an expression is not + # changed before and after invoking the passed in block. + # + # assert_no_difference 'Article.count' do + # post :create, params: { article: invalid_attributes } + # end + # + # A lambda can be passed in and evaluated. + # + # assert_no_difference -> { Article.count } do + # post :create, params: { article: invalid_attributes } + # end + # + # An error message can be specified. + # + # assert_no_difference 'Article.count', 'An Article should not be created' do + # post :create, params: { article: invalid_attributes } + # end + # + # An array of expressions can also be passed in and evaluated. + # + # assert_no_difference [ 'Article.count', -> { Post.count } ] do + # post :create, params: { article: invalid_attributes } + # end + def assert_no_difference(expression, message = nil, &block) + assert_difference expression, 0, message, &block + end + + # Assertion that the result of evaluating an expression is changed before + # and after invoking the passed in block. + # + # assert_changes 'Status.all_good?' do + # post :create, params: { status: { ok: false } } + # end + # + # You can pass the block as a string to be evaluated in the context of + # the block. A lambda can be passed for the block as well. + # + # assert_changes -> { Status.all_good? } do + # post :create, params: { status: { ok: false } } + # end + # + # The assertion is useful to test side effects. The passed block can be + # anything that can be converted to string with #to_s. + # + # assert_changes :@object do + # @object = 42 + # end + # + # The keyword arguments :from and :to can be given to specify the + # expected initial value and the expected value after the block was + # executed. + # + # assert_changes :@object, from: nil, to: :foo do + # @object = :foo + # end + # + # An error message can be specified. + # + # assert_changes -> { Status.all_good? }, 'Expected the status to be bad' do + # post :create, params: { status: { incident: true } } + # end + def assert_changes(expression, message = nil, from: UNTRACKED, to: UNTRACKED, &block) + exp = expression.respond_to?(:call) ? expression : -> { eval(expression.to_s, block.binding) } + + before = exp.call + retval = _assert_nothing_raised_or_warn("assert_changes", &block) + + unless from == UNTRACKED + error = "Expected change from #{from.inspect}" + error = "#{message}.\n#{error}" if message + assert from === before, error + end + + after = exp.call + + error = "#{expression.inspect} didn't change" + error = "#{error}. It was already #{to}" if before == to + error = "#{message}.\n#{error}" if message + refute_equal before, after, error + + unless to == UNTRACKED + error = "Expected change to #{to}\n" + error = "#{message}.\n#{error}" if message + assert to === after, error + end + + retval + end + + # Assertion that the result of evaluating an expression is not changed before + # and after invoking the passed in block. + # + # assert_no_changes 'Status.all_good?' do + # post :create, params: { status: { ok: true } } + # end + # + # Provide the optional keyword argument :from to specify the expected + # initial value. + # + # assert_no_changes -> { Status.all_good? }, from: true do + # post :create, params: { status: { ok: true } } + # end + # + # An error message can be specified. + # + # assert_no_changes -> { Status.all_good? }, 'Expected the status to be good' do + # post :create, params: { status: { ok: false } } + # end + def assert_no_changes(expression, message = nil, from: UNTRACKED, &block) + exp = expression.respond_to?(:call) ? expression : -> { eval(expression.to_s, block.binding) } + + before = exp.call + retval = _assert_nothing_raised_or_warn("assert_no_changes", &block) + + unless from == UNTRACKED + error = "Expected initial value of #{from.inspect}" + error = "#{message}.\n#{error}" if message + assert from === before, error + end + + after = exp.call + + error = "#{expression.inspect} changed" + error = "#{message}.\n#{error}" if message + + if before.nil? + assert_nil after, error + else + assert_equal before, after, error + end + + retval + end + + private + def _assert_nothing_raised_or_warn(assertion, &block) + assert_nothing_raised(&block) + rescue Minitest::UnexpectedError => e + if tagged_logger && tagged_logger.warn? + warning = <<~MSG + #{self.class} - #{name}: #{e.error.class} raised. + If you expected this exception, use `assert_raises` as near to the code that raises as possible. + Other block based assertions (e.g. `#{assertion}`) can be used, as long as `assert_raises` is inside their block. + MSG + tagged_logger.warn warning + end + + raise + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/autorun.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/autorun.rb new file mode 100644 index 0000000..889b416 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/autorun.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +gem "minitest" + +require "minitest" + +Minitest.autorun diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/constant_lookup.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/constant_lookup.rb new file mode 100644 index 0000000..51167e9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/constant_lookup.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require "active_support/concern" +require "active_support/inflector" + +module ActiveSupport + module Testing + # Resolves a constant from a minitest spec name. + # + # Given the following spec-style test: + # + # describe WidgetsController, :index do + # describe "authenticated user" do + # describe "returns widgets" do + # it "has a controller that exists" do + # assert_kind_of WidgetsController, @controller + # end + # end + # end + # end + # + # The test will have the following name: + # + # "WidgetsController::index::authenticated user::returns widgets" + # + # The constant WidgetsController can be resolved from the name. + # The following code will resolve the constant: + # + # controller = determine_constant_from_test_name(name) do |constant| + # Class === constant && constant < ::ActionController::Metal + # end + module ConstantLookup + extend ::ActiveSupport::Concern + + module ClassMethods # :nodoc: + def determine_constant_from_test_name(test_name) + names = test_name.split "::" + while names.size > 0 do + names.last.sub!(/Test$/, "") + begin + constant = names.join("::").safe_constantize + break(constant) if yield(constant) + ensure + names.pop + end + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/declarative.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/declarative.rb new file mode 100644 index 0000000..7c34036 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/declarative.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +module ActiveSupport + module Testing + module Declarative + unless defined?(Spec) + # Helper to define a test method using a String. Under the hood, it replaces + # spaces with underscores and defines the test method. + # + # test "verify something" do + # ... + # end + def test(name, &block) + test_name = "test_#{name.gsub(/\s+/, '_')}".to_sym + defined = method_defined? test_name + raise "#{test_name} is already defined in #{self}" if defined + if block_given? + define_method(test_name, &block) + else + define_method(test_name) do + flunk "No implementation provided for #{name}" + end + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/deprecation.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/deprecation.rb new file mode 100644 index 0000000..f762d24 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/deprecation.rb @@ -0,0 +1,89 @@ +# frozen_string_literal: true + +require "active_support/deprecation" + +module ActiveSupport + module Testing + module Deprecation + # Asserts that a matching deprecation warning was emitted by the given deprecator during the execution of the yielded block. + # + # assert_deprecated(/foo/, CustomDeprecator) do + # CustomDeprecator.warn "foo should no longer be used" + # end + # + # The +match+ object may be a +Regexp+, or +String+ appearing in the message. + # + # assert_deprecated('foo', CustomDeprecator) do + # CustomDeprecator.warn "foo should no longer be used" + # end + # + # If the +match+ is omitted (or explicitly +nil+), any deprecation warning will match. + # + # assert_deprecated(nil, CustomDeprecator) do + # CustomDeprecator.warn "foo should no longer be used" + # end + # + # If no +deprecator+ is given, defaults to ActiveSupport::Deprecation. + # + # assert_deprecated do + # ActiveSupport::Deprecation.warn "foo should no longer be used" + # end + def assert_deprecated(match = nil, deprecator = nil, &block) + result, warnings = collect_deprecations(deprecator, &block) + assert !warnings.empty?, "Expected a deprecation warning within the block but received none" + if match + match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp) + assert warnings.any? { |w| match.match?(w) }, "No deprecation warning matched #{match}: #{warnings.join(', ')}" + end + result + end + + # Asserts that no deprecation warnings are emitted by the given deprecator during the execution of the yielded block. + # + # assert_not_deprecated(CustomDeprecator) do + # CustomDeprecator.warn "message" # fails assertion + # end + # + # If no +deprecator+ is given, defaults to ActiveSupport::Deprecation. + # + # assert_not_deprecated do + # ActiveSupport::Deprecation.warn "message" # fails assertion + # end + # + # assert_not_deprecated do + # CustomDeprecator.warn "message" # passes assertion + # end + def assert_not_deprecated(deprecator = nil, &block) + result, deprecations = collect_deprecations(deprecator, &block) + assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n #{deprecations * "\n "}" + result + end + + # Returns an array of all the deprecation warnings emitted by the given + # +deprecator+ during the execution of the yielded block. + # + # collect_deprecations(CustomDeprecator) do + # CustomDeprecator.warn "message" + # end # => ["message"] + # + # If no +deprecator+ is given, defaults to ActiveSupport::Deprecation. + # + # collect_deprecations do + # CustomDeprecator.warn "custom message" + # ActiveSupport::Deprecation.warn "message" + # end # => ["message"] + def collect_deprecations(deprecator = nil) + deprecator ||= ActiveSupport::Deprecation + old_behavior = deprecator.behavior + deprecations = [] + deprecator.behavior = Proc.new do |message, callstack| + deprecations << message + end + result = yield + [result, deprecations] + ensure + deprecator.behavior = old_behavior + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/file_fixtures.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/file_fixtures.rb new file mode 100644 index 0000000..4eb7a88 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/file_fixtures.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +require "active_support/concern" + +module ActiveSupport + module Testing + # Adds simple access to sample files called file fixtures. + # File fixtures are normal files stored in + # ActiveSupport::TestCase.file_fixture_path. + # + # File fixtures are represented as +Pathname+ objects. + # This makes it easy to extract specific information: + # + # file_fixture("example.txt").read # get the file's content + # file_fixture("example.mp3").size # get the file size + module FileFixtures + extend ActiveSupport::Concern + + included do + class_attribute :file_fixture_path, instance_writer: false + end + + # Returns a +Pathname+ to the fixture file named +fixture_name+. + # + # Raises +ArgumentError+ if +fixture_name+ can't be found. + def file_fixture(fixture_name) + path = Pathname.new(File.join(file_fixture_path, fixture_name)) + + if path.exist? + path + else + msg = "the directory '%s' does not contain a file named '%s'" + raise ArgumentError, msg % [file_fixture_path, fixture_name] + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/isolation.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/isolation.rb new file mode 100644 index 0000000..129ea69 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/isolation.rb @@ -0,0 +1,110 @@ +# frozen_string_literal: true + +module ActiveSupport + module Testing + module Isolation + require "thread" + + def self.included(klass) # :nodoc: + klass.class_eval do + parallelize_me! + end + end + + def self.forking_env? + !ENV["NO_FORK"] && Process.respond_to?(:fork) + end + + def run + serialized = run_in_isolation do + super + end + + Marshal.load(serialized) + end + + module Forking + def run_in_isolation(&blk) + read, write = IO.pipe + read.binmode + write.binmode + + pid = fork do + read.close + yield + begin + if error? + failures.map! { |e| + begin + Marshal.dump e + e + rescue TypeError + ex = Exception.new e.message + ex.set_backtrace e.backtrace + Minitest::UnexpectedError.new ex + end + } + end + test_result = defined?(Minitest::Result) ? Minitest::Result.from(self) : dup + result = Marshal.dump(test_result) + end + + write.puts [result].pack("m") + exit! + end + + write.close + result = read.read + Process.wait2(pid) + result.unpack1("m") + end + end + + module Subprocess + ORIG_ARGV = ARGV.dup unless defined?(ORIG_ARGV) + + # Complicated H4X to get this working in windows / jruby with + # no forking. + def run_in_isolation(&blk) + require "tempfile" + + if ENV["ISOLATION_TEST"] + yield + test_result = defined?(Minitest::Result) ? Minitest::Result.from(self) : dup + File.open(ENV["ISOLATION_OUTPUT"], "w") do |file| + file.puts [Marshal.dump(test_result)].pack("m") + end + exit! + else + Tempfile.open("isolation") do |tmpfile| + env = { + "ISOLATION_TEST" => self.class.name, + "ISOLATION_OUTPUT" => tmpfile.path + } + + test_opts = "-n#{self.class.name}##{name}" + + load_path_args = [] + $-I.each do |p| + load_path_args << "-I" + load_path_args << File.expand_path(p) + end + + child = IO.popen([env, Gem.ruby, *load_path_args, $0, *ORIG_ARGV, test_opts]) + + begin + Process.wait(child.pid) + rescue Errno::ECHILD # The child process may exit before we wait + nil + end + + return tmpfile.read.unpack1("m") + end + end + end + end + + include forking_env? ? Forking : Subprocess + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/method_call_assertions.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/method_call_assertions.rb new file mode 100644 index 0000000..1d016b0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/method_call_assertions.rb @@ -0,0 +1,70 @@ +# frozen_string_literal: true + +require "minitest/mock" + +module ActiveSupport + module Testing + module MethodCallAssertions # :nodoc: + private + def assert_called(object, method_name, message = nil, times: 1, returns: nil, &block) + times_called = 0 + + object.stub(method_name, proc { times_called += 1; returns }, &block) + + error = "Expected #{method_name} to be called #{times} times, " \ + "but was called #{times_called} times" + error = "#{message}.\n#{error}" if message + assert_equal times, times_called, error + end + + def assert_called_with(object, method_name, args, returns: nil, &block) + mock = Minitest::Mock.new + + if args.all?(Array) + args.each { |arg| mock.expect(:call, returns, arg) } + else + mock.expect(:call, returns, args) + end + + object.stub(method_name, mock, &block) + + mock.verify + end + + def assert_not_called(object, method_name, message = nil, &block) + assert_called(object, method_name, message, times: 0, &block) + end + + def assert_called_on_instance_of(klass, method_name, message = nil, times: 1, returns: nil) + times_called = 0 + klass.define_method("stubbed_#{method_name}") do |*| + times_called += 1 + + returns + end + + klass.alias_method "original_#{method_name}", method_name + klass.alias_method method_name, "stubbed_#{method_name}" + + yield + + error = "Expected #{method_name} to be called #{times} times, but was called #{times_called} times" + error = "#{message}.\n#{error}" if message + + assert_equal times, times_called, error + ensure + klass.alias_method method_name, "original_#{method_name}" + klass.undef_method "original_#{method_name}" + klass.undef_method "stubbed_#{method_name}" + end + + def assert_not_called_on_instance_of(klass, method_name, message = nil, &block) + assert_called_on_instance_of(klass, method_name, message, times: 0, &block) + end + + def stub_any_instance(klass, instance: klass.new) + klass.stub(:new, instance) { yield instance } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelization.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelization.rb new file mode 100644 index 0000000..d1b2734 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelization.rb @@ -0,0 +1,55 @@ +# frozen_string_literal: true + +require "drb" +require "drb/unix" unless Gem.win_platform? +require "active_support/core_ext/module/attribute_accessors" +require "active_support/testing/parallelization/server" +require "active_support/testing/parallelization/worker" + +module ActiveSupport + module Testing + class Parallelization # :nodoc: + @@after_fork_hooks = [] + + def self.after_fork_hook(&blk) + @@after_fork_hooks << blk + end + + cattr_reader :after_fork_hooks + + @@run_cleanup_hooks = [] + + def self.run_cleanup_hook(&blk) + @@run_cleanup_hooks << blk + end + + cattr_reader :run_cleanup_hooks + + def initialize(worker_count) + @worker_count = worker_count + @queue_server = Server.new + @worker_pool = [] + @url = DRb.start_service("drbunix:", @queue_server).uri + end + + def start + @worker_pool = @worker_count.times.map do |worker| + Worker.new(worker, @url).start + end + end + + def <<(work) + @queue_server << work + end + + def size + @worker_count + end + + def shutdown + @queue_server.shutdown + @worker_pool.each { |pid| Process.waitpid pid } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelization/server.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelization/server.rb new file mode 100644 index 0000000..3961367 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelization/server.rb @@ -0,0 +1,82 @@ +# frozen_string_literal: true + +require "drb" +require "drb/unix" unless Gem.win_platform? + +module ActiveSupport + module Testing + class Parallelization # :nodoc: + class Server + include DRb::DRbUndumped + + def initialize + @queue = Queue.new + @active_workers = Concurrent::Map.new + @in_flight = Concurrent::Map.new + end + + def record(reporter, result) + raise DRb::DRbConnError if result.is_a?(DRb::DRbUnknown) + + @in_flight.delete([result.klass, result.name]) + + reporter.synchronize do + reporter.record(result) + end + end + + def <<(o) + o[2] = DRbObject.new(o[2]) if o + @queue << o + end + + def pop + if test = @queue.pop + @in_flight[[test[0].to_s, test[1]]] = test + test + end + end + + def start_worker(worker_id) + @active_workers[worker_id] = true + end + + def stop_worker(worker_id) + @active_workers.delete(worker_id) + end + + def active_workers? + @active_workers.size > 0 + end + + def interrupt + @queue.clear + end + + def shutdown + # Wait for initial queue to drain + while @queue.length != 0 + sleep 0.1 + end + + @queue.close + + # Wait until all workers have finished + while active_workers? + sleep 0.1 + end + + @in_flight.values.each do |(klass, name, reporter)| + result = Minitest::Result.from(klass.new(name)) + error = RuntimeError.new("result not reported") + error.set_backtrace([""]) + result.failures << Minitest::UnexpectedError.new(error) + reporter.synchronize do + reporter.record(result) + end + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelization/worker.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelization/worker.rb new file mode 100644 index 0000000..393355a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelization/worker.rb @@ -0,0 +1,103 @@ +# frozen_string_literal: true + +module ActiveSupport + module Testing + class Parallelization # :nodoc: + class Worker + def initialize(number, url) + @id = SecureRandom.uuid + @number = number + @url = url + @setup_exception = nil + end + + def start + fork do + set_process_title("(starting)") + + DRb.stop_service + + @queue = DRbObject.new_with_uri(@url) + @queue.start_worker(@id) + + begin + after_fork + rescue => @setup_exception; end + + work_from_queue + ensure + set_process_title("(stopping)") + + run_cleanup + @queue.stop_worker(@id) + end + end + + def work_from_queue + while job = @queue.pop + perform_job(job) + end + end + + def perform_job(job) + klass = job[0] + method = job[1] + reporter = job[2] + + set_process_title("#{klass}##{method}") + + result = klass.with_info_handler reporter do + Minitest.run_one_method(klass, method) + end + + safe_record(reporter, result) + end + + def safe_record(reporter, result) + add_setup_exception(result) if @setup_exception + + begin + @queue.record(reporter, result) + rescue DRb::DRbConnError + result.failures.map! do |failure| + if failure.respond_to?(:error) + # minitest >5.14.0 + error = DRb::DRbRemoteError.new(failure.error) + else + error = DRb::DRbRemoteError.new(failure.exception) + end + Minitest::UnexpectedError.new(error) + end + @queue.record(reporter, result) + rescue Interrupt + @queue.interrupt + raise + end + + set_process_title("(idle)") + end + + def after_fork + Parallelization.after_fork_hooks.each do |cb| + cb.call(@number) + end + end + + def run_cleanup + Parallelization.run_cleanup_hooks.each do |cb| + cb.call(@number) + end + end + + private + def add_setup_exception(result) + result.failures.prepend Minitest::UnexpectedError.new(@setup_exception) + end + + def set_process_title(status) + Process.setproctitle("Rails test worker #{@number} - #{status}") + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelize_executor.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelize_executor.rb new file mode 100644 index 0000000..88299db --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/parallelize_executor.rb @@ -0,0 +1,76 @@ +# frozen_string_literal: true + +module ActiveSupport + module Testing + class ParallelizeExecutor # :nodoc: + attr_reader :size, :parallelize_with, :threshold + + def initialize(size:, with:, threshold: ActiveSupport.test_parallelization_threshold) + @size = size + @parallelize_with = with + @threshold = threshold + end + + def start + parallelize if should_parallelize? + show_execution_info + + parallel_executor.start if parallelized? + end + + def <<(work) + parallel_executor << work if parallelized? + end + + def shutdown + parallel_executor.shutdown if parallelized? + end + + private + def parallel_executor + @parallel_executor ||= build_parallel_executor + end + + def build_parallel_executor + case parallelize_with + when :processes + Testing::Parallelization.new(size) + when :threads + ActiveSupport::TestCase.lock_threads = false if defined?(ActiveSupport::TestCase.lock_threads) + Minitest::Parallel::Executor.new(size) + else + raise ArgumentError, "#{parallelize_with} is not a supported parallelization executor." + end + end + + def parallelize + @parallelized = true + Minitest::Test.parallelize_me! + end + + def parallelized? + @parallelized if defined?(@parallelized) + end + + def should_parallelize? + ENV["PARALLEL_WORKERS"] || tests_count > threshold + end + + def tests_count + @tests_count ||= Minitest::Runnable.runnables.sum { |runnable| runnable.runnable_methods.size } + end + + def show_execution_info + puts execution_info + end + + def execution_info + if parallelized? + "Running #{tests_count} tests in parallel using #{parallel_executor.size} #{parallelize_with}" + else + "Running #{tests_count} tests in a single process (parallelization threshold is #{threshold})" + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/setup_and_teardown.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/setup_and_teardown.rb new file mode 100644 index 0000000..35321cd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/setup_and_teardown.rb @@ -0,0 +1,55 @@ +# frozen_string_literal: true + +require "active_support/callbacks" + +module ActiveSupport + module Testing + # Adds support for +setup+ and +teardown+ callbacks. + # These callbacks serve as a replacement to overwriting the + # #setup and #teardown methods of your TestCase. + # + # class ExampleTest < ActiveSupport::TestCase + # setup do + # # ... + # end + # + # teardown do + # # ... + # end + # end + module SetupAndTeardown + def self.prepended(klass) + klass.include ActiveSupport::Callbacks + klass.define_callbacks :setup, :teardown + klass.extend ClassMethods + end + + module ClassMethods + # Add a callback, which runs before TestCase#setup. + def setup(*args, &block) + set_callback(:setup, :before, *args, &block) + end + + # Add a callback, which runs after TestCase#teardown. + def teardown(*args, &block) + set_callback(:teardown, :after, *args, &block) + end + end + + def before_setup # :nodoc: + super + run_callbacks :setup + end + + def after_teardown # :nodoc: + begin + run_callbacks :teardown + rescue => e + self.failures << Minitest::UnexpectedError.new(e) + end + + super + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/stream.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/stream.rb new file mode 100644 index 0000000..55017d3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/stream.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +module ActiveSupport + module Testing + module Stream # :nodoc: + private + def silence_stream(stream) + old_stream = stream.dup + stream.reopen(IO::NULL) + stream.sync = true + yield + ensure + stream.reopen(old_stream) + old_stream.close + end + + def quietly(&block) + silence_stream(STDOUT) do + silence_stream(STDERR, &block) + end + end + + def capture(stream) + stream = stream.to_s + captured_stream = Tempfile.new(stream) + stream_io = eval("$#{stream}") + origin_stream = stream_io.dup + stream_io.reopen(captured_stream) + + yield + + stream_io.rewind + captured_stream.read + ensure + captured_stream.close + captured_stream.unlink + stream_io.reopen(origin_stream) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/tagged_logging.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/tagged_logging.rb new file mode 100644 index 0000000..7d38268 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/tagged_logging.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +module ActiveSupport + module Testing + # Logs a "PostsControllerTest: test name" heading before each test to + # make test.log easier to search and follow along with. + module TaggedLogging # :nodoc: + attr_writer :tagged_logger + + def before_setup + if tagged_logger && tagged_logger.info? + heading = "#{self.class}: #{name}" + divider = "-" * heading.size + tagged_logger.info divider + tagged_logger.info heading + tagged_logger.info divider + end + super + end + + private + def tagged_logger + @tagged_logger ||= (defined?(Rails.logger) && Rails.logger) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/time_helpers.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/time_helpers.rb new file mode 100644 index 0000000..a1155bf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/testing/time_helpers.rb @@ -0,0 +1,246 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/redefine_method" +require "active_support/core_ext/time/calculations" +require "concurrent/map" + +module ActiveSupport + module Testing + # Manages stubs for TimeHelpers + class SimpleStubs # :nodoc: + Stub = Struct.new(:object, :method_name, :original_method) + + def initialize + @stubs = Concurrent::Map.new { |h, k| h[k] = {} } + end + + # Stubs object.method_name with the given block + # If the method is already stubbed, remove that stub + # so that removing this stub will restore the original implementation. + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # target = Time.zone.local(2004, 11, 24, 1, 4, 44) + # simple_stubs.stub_object(Time, :now) { at(target.to_i) } + # Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 + def stub_object(object, method_name, &block) + if stub = stubbing(object, method_name) + unstub_object(stub) + end + + new_name = "__simple_stub__#{method_name}" + + @stubs[object.object_id][method_name] = Stub.new(object, method_name, new_name) + + object.singleton_class.alias_method new_name, method_name + object.define_singleton_method(method_name, &block) + end + + # Remove all object-method stubs held by this instance + def unstub_all! + @stubs.each_value do |object_stubs| + object_stubs.each_value do |stub| + unstub_object(stub) + end + end + @stubs.clear + end + + # Returns the Stub for object#method_name + # (nil if it is not stubbed) + def stubbing(object, method_name) + @stubs[object.object_id][method_name] + end + + # Returns true if any stubs are set, false if there are none + def stubbed? + !@stubs.empty? + end + + private + # Restores the original object.method described by the Stub + def unstub_object(stub) + singleton_class = stub.object.singleton_class + singleton_class.silence_redefinition_of_method stub.method_name + singleton_class.alias_method stub.method_name, stub.original_method + singleton_class.undef_method stub.original_method + end + end + + # Contains helpers that help you test passage of time. + module TimeHelpers + def after_teardown + travel_back + super + end + + # Changes current time to the time in the future or in the past by a given time difference by + # stubbing +Time.now+, +Date.today+, and +DateTime.now+. The stubs are automatically removed + # at the end of the test. + # + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # travel 1.day + # Time.current # => Sun, 10 Nov 2013 15:34:49 EST -05:00 + # Date.current # => Sun, 10 Nov 2013 + # DateTime.current # => Sun, 10 Nov 2013 15:34:49 -0500 + # + # This method also accepts a block, which will return the current time back to its original + # state at the end of the block: + # + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # travel 1.day do + # User.create.created_at # => Sun, 10 Nov 2013 15:34:49 EST -05:00 + # end + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + def travel(duration, &block) + travel_to Time.now + duration, &block + end + + # Changes current time to the given time by stubbing +Time.now+, + # +Date.today+, and +DateTime.now+ to return the time or date passed into this method. + # The stubs are automatically removed at the end of the test. + # + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # travel_to Time.zone.local(2004, 11, 24, 1, 4, 44) + # Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 + # Date.current # => Wed, 24 Nov 2004 + # DateTime.current # => Wed, 24 Nov 2004 01:04:44 -0500 + # + # Dates are taken as their timestamp at the beginning of the day in the + # application time zone. Time.current returns said timestamp, + # and Time.now its equivalent in the system time zone. Similarly, + # Date.current returns a date equal to the argument, and + # Date.today the date according to Time.now, which may + # be different. (Note that you rarely want to deal with Time.now, + # or Date.today, in order to honor the application time zone + # please always use Time.current and Date.current.) + # + # Note that the usec for the time passed will be set to 0 to prevent rounding + # errors with external services, like MySQL (which will round instead of floor, + # leading to off-by-one-second errors). + # + # This method also accepts a block, which will return the current time back to its original + # state at the end of the block: + # + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # travel_to Time.zone.local(2004, 11, 24, 1, 4, 44) do + # Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 + # end + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + def travel_to(date_or_time) + if block_given? && in_block + travel_to_nested_block_call = <<~MSG + + Calling `travel_to` with a block, when we have previously already made a call to `travel_to`, can lead to confusing time stubbing. + + Instead of: + + travel_to 2.days.from_now do + # 2 days from today + travel_to 3.days.from_now do + # 5 days from today + end + end + + preferred way to achieve above is: + + travel 2.days do + # 2 days from today + end + + travel 5.days do + # 5 days from today + end + + MSG + raise travel_to_nested_block_call + end + + if date_or_time.is_a?(Date) && !date_or_time.is_a?(DateTime) + now = date_or_time.midnight.to_time + elsif date_or_time.is_a?(String) + now = Time.zone.parse(date_or_time) + else + now = date_or_time.to_time.change(usec: 0) + end + + stubbed_time = Time.now if simple_stubs.stubbing(Time, :now) + simple_stubs.stub_object(Time, :now) { at(now.to_i) } + simple_stubs.stub_object(Date, :today) { jd(now.to_date.jd) } + simple_stubs.stub_object(DateTime, :now) { jd(now.to_date.jd, now.hour, now.min, now.sec, Rational(now.utc_offset, 86400)) } + + if block_given? + begin + self.in_block = true + yield + ensure + if stubbed_time + travel_to stubbed_time + else + travel_back + end + self.in_block = false + end + end + end + + # Returns the current time back to its original state, by removing the stubs added by + # +travel+, +travel_to+, and +freeze_time+. + # + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # + # travel_to Time.zone.local(2004, 11, 24, 1, 4, 44) + # Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 + # + # travel_back + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # + # This method also accepts a block, which brings the stubs back at the end of the block: + # + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # + # travel_to Time.zone.local(2004, 11, 24, 1, 4, 44) + # Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 + # + # travel_back do + # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 + # end + # + # Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 + def travel_back + stubbed_time = Time.current if block_given? && simple_stubs.stubbed? + + simple_stubs.unstub_all! + yield if block_given? + ensure + travel_to stubbed_time if stubbed_time + end + alias_method :unfreeze_time, :travel_back + + # Calls +travel_to+ with +Time.now+. + # + # Time.current # => Sun, 09 Jul 2017 15:34:49 EST -05:00 + # freeze_time + # sleep(1) + # Time.current # => Sun, 09 Jul 2017 15:34:49 EST -05:00 + # + # This method also accepts a block, which will return the current time back to its original + # state at the end of the block: + # + # Time.current # => Sun, 09 Jul 2017 15:34:49 EST -05:00 + # freeze_time do + # sleep(1) + # User.create.created_at # => Sun, 09 Jul 2017 15:34:49 EST -05:00 + # end + # Time.current # => Sun, 09 Jul 2017 15:34:50 EST -05:00 + def freeze_time(&block) + travel_to Time.now, &block + end + + private + def simple_stubs + @simple_stubs ||= SimpleStubs.new + end + + attr_accessor :in_block + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/time.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/time.rb new file mode 100644 index 0000000..5185467 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/time.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +module ActiveSupport + autoload :Duration, "active_support/duration" + autoload :TimeWithZone, "active_support/time_with_zone" + autoload :TimeZone, "active_support/values/time_zone" +end + +require "date" +require "time" + +require "active_support/core_ext/time" +require "active_support/core_ext/date" +require "active_support/core_ext/date_time" + +require "active_support/core_ext/integer/time" +require "active_support/core_ext/numeric/time" + +require "active_support/core_ext/string/conversions" +require "active_support/core_ext/string/zones" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/time_with_zone.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/time_with_zone.rb new file mode 100644 index 0000000..e967bf0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/time_with_zone.rb @@ -0,0 +1,626 @@ +# frozen_string_literal: true + +require "yaml" + +require "active_support/duration" +require "active_support/values/time_zone" +require "active_support/core_ext/object/acts_like" +require "active_support/core_ext/date_and_time/compatibility" + +module ActiveSupport + # A Time-like class that can represent a time in any time zone. Necessary + # because standard Ruby Time instances are limited to UTC and the + # system's ENV['TZ'] zone. + # + # You shouldn't ever need to create a TimeWithZone instance directly via +new+. + # Instead use methods +local+, +parse+, +at+ and +now+ on TimeZone instances, + # and +in_time_zone+ on Time and DateTime instances. + # + # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' + # Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45.000000000 EST -05:00 + # Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45.000000000 EST -05:00 + # Time.zone.at(1171139445) # => Sat, 10 Feb 2007 15:30:45.000000000 EST -05:00 + # Time.zone.now # => Sun, 18 May 2008 13:07:55.754107581 EDT -04:00 + # Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45.000000000 EST -05:00 + # + # See Time and TimeZone for further documentation of these methods. + # + # TimeWithZone instances implement the same API as Ruby Time instances, so + # that Time and TimeWithZone instances are interchangeable. + # + # t = Time.zone.now # => Sun, 18 May 2008 13:27:25.031505668 EDT -04:00 + # t.hour # => 13 + # t.dst? # => true + # t.utc_offset # => -14400 + # t.zone # => "EDT" + # t.to_fs(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400" + # t + 1.day # => Mon, 19 May 2008 13:27:25.031505668 EDT -04:00 + # t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00.000000000 EST -05:00 + # t > Time.utc(1999) # => true + # t.is_a?(Time) # => true + # t.is_a?(ActiveSupport::TimeWithZone) # => true + class TimeWithZone + # Report class name as 'Time' to thwart type checking. + def self.name + ActiveSupport::Deprecation.warn(<<~EOM) + ActiveSupport::TimeWithZone.name has been deprecated and + from Rails 7.1 will use the default Ruby implementation. + You can set `config.active_support.remove_deprecated_time_with_zone_name = true` + to enable the new behavior now. + EOM + + "Time" + end + + PRECISIONS = Hash.new { |h, n| h[n] = "%FT%T.%#{n}N" } + PRECISIONS[0] = "%FT%T" + + include Comparable, DateAndTime::Compatibility + attr_reader :time_zone + + def initialize(utc_time, time_zone, local_time = nil, period = nil) + @utc = utc_time ? transfer_time_values_to_utc_constructor(utc_time) : nil + @time_zone, @time = time_zone, local_time + @period = @utc ? period : get_period_and_ensure_valid_local_time(period) + end + + # Returns a Time instance that represents the time in +time_zone+. + def time + @time ||= incorporate_utc_offset(@utc, utc_offset) + end + + # Returns a Time instance of the simultaneous time in the UTC timezone. + def utc + @utc ||= incorporate_utc_offset(@time, -utc_offset) + end + alias_method :comparable_time, :utc + alias_method :getgm, :utc + alias_method :getutc, :utc + alias_method :gmtime, :utc + + # Returns the underlying TZInfo::TimezonePeriod. + def period + @period ||= time_zone.period_for_utc(@utc) + end + + # Returns the simultaneous time in Time.zone, or the specified zone. + def in_time_zone(new_zone = ::Time.zone) + return self if time_zone == new_zone + utc.in_time_zone(new_zone) + end + + # Returns a Time instance of the simultaneous time in the system timezone. + def localtime(utc_offset = nil) + utc.getlocal(utc_offset) + end + alias_method :getlocal, :localtime + + # Returns true if the current time is within Daylight Savings Time for the + # specified time zone. + # + # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' + # Time.zone.parse("2012-5-30").dst? # => true + # Time.zone.parse("2012-11-30").dst? # => false + def dst? + period.dst? + end + alias_method :isdst, :dst? + + # Returns true if the current time zone is set to UTC. + # + # Time.zone = 'UTC' # => 'UTC' + # Time.zone.now.utc? # => true + # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' + # Time.zone.now.utc? # => false + def utc? + zone == "UTC" || zone == "UCT" + end + alias_method :gmt?, :utc? + + # Returns the offset from current time to UTC time in seconds. + def utc_offset + period.observed_utc_offset + end + alias_method :gmt_offset, :utc_offset + alias_method :gmtoff, :utc_offset + + # Returns a formatted string of the offset from UTC, or an alternative + # string if the time zone is already UTC. + # + # Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)" + # Time.zone.now.formatted_offset(true) # => "-05:00" + # Time.zone.now.formatted_offset(false) # => "-0500" + # Time.zone = 'UTC' # => "UTC" + # Time.zone.now.formatted_offset(true, "0") # => "0" + def formatted_offset(colon = true, alternate_utc_string = nil) + utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon) + end + + # Returns the time zone abbreviation. + # + # Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)" + # Time.zone.now.zone # => "EST" + def zone + period.abbreviation + end + + # Returns a string of the object's date, time, zone, and offset from UTC. + # + # Time.zone.now.inspect # => "Thu, 04 Dec 2014 11:00:25.624541392 EST -05:00" + def inspect + "#{time.strftime('%a, %d %b %Y %H:%M:%S.%9N')} #{zone} #{formatted_offset}" + end + + # Returns a string of the object's date and time in the ISO 8601 standard + # format. + # + # Time.zone.now.xmlschema # => "2014-12-04T11:02:37-05:00" + def xmlschema(fraction_digits = 0) + "#{time.strftime(PRECISIONS[fraction_digits.to_i])}#{formatted_offset(true, 'Z')}" + end + alias_method :iso8601, :xmlschema + alias_method :rfc3339, :xmlschema + + # Coerces time to a string for JSON encoding. The default format is ISO 8601. + # You can get %Y/%m/%d %H:%M:%S +offset style by setting + # ActiveSupport::JSON::Encoding.use_standard_json_time_format + # to +false+. + # + # # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true + # Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json + # # => "2005-02-01T05:15:10.000-10:00" + # + # # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false + # Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json + # # => "2005/02/01 05:15:10 -1000" + def as_json(options = nil) + if ActiveSupport::JSON::Encoding.use_standard_json_time_format + xmlschema(ActiveSupport::JSON::Encoding.time_precision) + else + %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) + end + end + + def init_with(coder) # :nodoc: + initialize(coder["utc"], coder["zone"], coder["time"]) + end + + def encode_with(coder) # :nodoc: + coder.map = { "utc" => utc, "zone" => time_zone, "time" => time } + end + + # Returns a string of the object's date and time in the format used by + # HTTP requests. + # + # Time.zone.now.httpdate # => "Tue, 01 Jan 2013 04:39:43 GMT" + def httpdate + utc.httpdate + end + + # Returns a string of the object's date and time in the RFC 2822 standard + # format. + # + # Time.zone.now.rfc2822 # => "Tue, 01 Jan 2013 04:51:39 +0000" + def rfc2822 + to_fs(:rfc822) + end + alias_method :rfc822, :rfc2822 + + NOT_SET = Object.new # :nodoc: + + # Returns a string of the object's date and time. + def to_s(format = NOT_SET) + if format == :db + ActiveSupport::Deprecation.warn( + "TimeWithZone#to_s(:db) is deprecated. Please use TimeWithZone#to_fs(:db) instead." + ) + utc.to_fs(format) + elsif formatter = ::Time::DATE_FORMATS[format] + ActiveSupport::Deprecation.warn( + "TimeWithZone#to_s(#{format.inspect}) is deprecated. Please use TimeWithZone#to_fs(#{format.inspect}) instead." + ) + formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) + elsif format == NOT_SET + "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby Time#to_s format + else + ActiveSupport::Deprecation.warn( + "TimeWithZone#to_s(#{format.inspect}) is deprecated. Please use TimeWithZone#to_fs(#{format.inspect}) instead." + ) + "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby Time#to_s format + end + end + + # Returns a string of the object's date and time. + # + # This method is aliased to to_formatted_s. + # + # Accepts an optional format: + # * :default - default value, mimics Ruby Time#to_s format. + # * :db - format outputs time in UTC :db time. See Time#to_fs(:db). + # * Any key in Time::DATE_FORMATS can be used. See active_support/core_ext/time/conversions.rb. + def to_fs(format = :default) + if format == :db + utc.to_fs(format) + elsif formatter = ::Time::DATE_FORMATS[format] + formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) + else + # Change to to_s when deprecation is gone. + "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" + end + end + alias_method :to_formatted_s, :to_fs + + # Replaces %Z directive with +zone before passing to Time#strftime, + # so that zone information is correct. + def strftime(format) + format = format.gsub(/((?:\A|[^%])(?:%%)*)%Z/, "\\1#{zone}") + getlocal(utc_offset).strftime(format) + end + + # Use the time in UTC for comparisons. + def <=>(other) + utc <=> other + end + alias_method :before?, :< + alias_method :after?, :> + + # Returns true if the current object's time is within the specified + # +min+ and +max+ time. + def between?(min, max) + utc.between?(min, max) + end + + # Returns true if the current object's time is in the past. + def past? + utc.past? + end + + # Returns true if the current object's time falls within + # the current day. + def today? + time.today? + end + + # Returns true if the current object's time falls within + # the next day (tomorrow). + def tomorrow? + time.tomorrow? + end + alias :next_day? :tomorrow? + + # Returns true if the current object's time falls within + # the previous day (yesterday). + def yesterday? + time.yesterday? + end + alias :prev_day? :yesterday? + + # Returns true if the current object's time is in the future. + def future? + utc.future? + end + + # Returns +true+ if +other+ is equal to current object. + def eql?(other) + other.eql?(utc) + end + + def hash + utc.hash + end + + # Adds an interval of time to the current object's time and returns that + # value as a new TimeWithZone object. + # + # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' + # now = Time.zone.now # => Sun, 02 Nov 2014 01:26:28.725182881 EDT -04:00 + # now + 1000 # => Sun, 02 Nov 2014 01:43:08.725182881 EDT -04:00 + # + # If we're adding a Duration of variable length (i.e., years, months, days), + # move forward from #time, otherwise move forward from #utc, for accuracy + # when moving across DST boundaries. + # + # For instance, a time + 24.hours will advance exactly 24 hours, while a + # time + 1.day will advance 23-25 hours, depending on the day. + # + # now + 24.hours # => Mon, 03 Nov 2014 00:26:28.725182881 EST -05:00 + # now + 1.day # => Mon, 03 Nov 2014 01:26:28.725182881 EST -05:00 + def +(other) + if duration_of_variable_length?(other) + method_missing(:+, other) + else + result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other) + result.in_time_zone(time_zone) + end + end + alias_method :since, :+ + alias_method :in, :+ + + # Subtracts an interval of time and returns a new TimeWithZone object unless + # the other value +acts_like?+ time. Then it will return a Float of the difference + # between the two times that represents the difference between the current + # object's time and the +other+ time. + # + # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' + # now = Time.zone.now # => Mon, 03 Nov 2014 00:26:28.725182881 EST -05:00 + # now - 1000 # => Mon, 03 Nov 2014 00:09:48.725182881 EST -05:00 + # + # If subtracting a Duration of variable length (i.e., years, months, days), + # move backward from #time, otherwise move backward from #utc, for accuracy + # when moving across DST boundaries. + # + # For instance, a time - 24.hours will go subtract exactly 24 hours, while a + # time - 1.day will subtract 23-25 hours, depending on the day. + # + # now - 24.hours # => Sun, 02 Nov 2014 01:26:28.725182881 EDT -04:00 + # now - 1.day # => Sun, 02 Nov 2014 00:26:28.725182881 EDT -04:00 + # + # If both the TimeWithZone object and the other value act like Time, a Float + # will be returned. + # + # Time.zone.now - 1.day.ago # => 86399.999967 + # + def -(other) + if other.acts_like?(:time) + to_time - other.to_time + elsif duration_of_variable_length?(other) + method_missing(:-, other) + else + result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other) + result.in_time_zone(time_zone) + end + end + + # Subtracts an interval of time from the current object's time and returns + # the result as a new TimeWithZone object. + # + # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' + # now = Time.zone.now # => Mon, 03 Nov 2014 00:26:28.725182881 EST -05:00 + # now.ago(1000) # => Mon, 03 Nov 2014 00:09:48.725182881 EST -05:00 + # + # If we're subtracting a Duration of variable length (i.e., years, months, + # days), move backward from #time, otherwise move backward from #utc, for + # accuracy when moving across DST boundaries. + # + # For instance, time.ago(24.hours) will move back exactly 24 hours, + # while time.ago(1.day) will move back 23-25 hours, depending on + # the day. + # + # now.ago(24.hours) # => Sun, 02 Nov 2014 01:26:28.725182881 EDT -04:00 + # now.ago(1.day) # => Sun, 02 Nov 2014 00:26:28.725182881 EDT -04:00 + def ago(other) + since(-other) + end + + # Returns a new +ActiveSupport::TimeWithZone+ where one or more of the elements have + # been changed according to the +options+ parameter. The time options (:hour, + # :min, :sec, :usec, :nsec) reset cascadingly, + # so if only the hour is passed, then minute, sec, usec and nsec is set to 0. If the + # hour and minute is passed, then sec, usec and nsec is set to 0. The +options+ + # parameter takes a hash with any of these keys: :year, :month, + # :day, :hour, :min, :sec, :usec, + # :nsec, :offset, :zone. Pass either :usec + # or :nsec, not both. Similarly, pass either :zone or + # :offset, not both. + # + # t = Time.zone.now # => Fri, 14 Apr 2017 11:45:15.116992711 EST -05:00 + # t.change(year: 2020) # => Tue, 14 Apr 2020 11:45:15.116992711 EST -05:00 + # t.change(hour: 12) # => Fri, 14 Apr 2017 12:00:00.116992711 EST -05:00 + # t.change(min: 30) # => Fri, 14 Apr 2017 11:30:00.116992711 EST -05:00 + # t.change(offset: "-10:00") # => Fri, 14 Apr 2017 11:45:15.116992711 HST -10:00 + # t.change(zone: "Hawaii") # => Fri, 14 Apr 2017 11:45:15.116992711 HST -10:00 + def change(options) + if options[:zone] && options[:offset] + raise ArgumentError, "Can't change both :offset and :zone at the same time: #{options.inspect}" + end + + new_time = time.change(options) + + if options[:zone] + new_zone = ::Time.find_zone(options[:zone]) + elsif options[:offset] + new_zone = ::Time.find_zone(new_time.utc_offset) + end + + new_zone ||= time_zone + periods = new_zone.periods_for_local(new_time) + + self.class.new(nil, new_zone, new_time, periods.include?(period) ? period : nil) + end + + # Uses Date to provide precise Time calculations for years, months, and days + # according to the proleptic Gregorian calendar. The result is returned as a + # new TimeWithZone object. + # + # The +options+ parameter takes a hash with any of these keys: + # :years, :months, :weeks, :days, + # :hours, :minutes, :seconds. + # + # If advancing by a value of variable length (i.e., years, weeks, months, + # days), move forward from #time, otherwise move forward from #utc, for + # accuracy when moving across DST boundaries. + # + # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' + # now = Time.zone.now # => Sun, 02 Nov 2014 01:26:28.558049687 EDT -04:00 + # now.advance(seconds: 1) # => Sun, 02 Nov 2014 01:26:29.558049687 EDT -04:00 + # now.advance(minutes: 1) # => Sun, 02 Nov 2014 01:27:28.558049687 EDT -04:00 + # now.advance(hours: 1) # => Sun, 02 Nov 2014 01:26:28.558049687 EST -05:00 + # now.advance(days: 1) # => Mon, 03 Nov 2014 01:26:28.558049687 EST -05:00 + # now.advance(weeks: 1) # => Sun, 09 Nov 2014 01:26:28.558049687 EST -05:00 + # now.advance(months: 1) # => Tue, 02 Dec 2014 01:26:28.558049687 EST -05:00 + # now.advance(years: 1) # => Mon, 02 Nov 2015 01:26:28.558049687 EST -05:00 + def advance(options) + # If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time, + # otherwise advance from #utc, for accuracy when moving across DST boundaries + if options.values_at(:years, :weeks, :months, :days).any? + method_missing(:advance, options) + else + utc.advance(options).in_time_zone(time_zone) + end + end + + %w(year mon month day mday wday yday hour min sec usec nsec to_date).each do |method_name| + class_eval <<-EOV, __FILE__, __LINE__ + 1 + def #{method_name} # def month + time.#{method_name} # time.month + end # end + EOV + end + + # Returns Array of parts of Time in sequence of + # [seconds, minutes, hours, day, month, year, weekday, yearday, dst?, zone]. + # + # now = Time.zone.now # => Tue, 18 Aug 2015 02:29:27.485278555 UTC +00:00 + # now.to_a # => [27, 29, 2, 18, 8, 2015, 2, 230, false, "UTC"] + def to_a + [time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone] + end + + # Returns the object's date and time as a floating-point number of seconds + # since the Epoch (January 1, 1970 00:00 UTC). + # + # Time.zone.now.to_f # => 1417709320.285418 + def to_f + utc.to_f + end + + # Returns the object's date and time as an integer number of seconds + # since the Epoch (January 1, 1970 00:00 UTC). + # + # Time.zone.now.to_i # => 1417709320 + def to_i + utc.to_i + end + alias_method :tv_sec, :to_i + + # Returns the object's date and time as a rational number of seconds + # since the Epoch (January 1, 1970 00:00 UTC). + # + # Time.zone.now.to_r # => (708854548642709/500000) + def to_r + utc.to_r + end + + # Returns an instance of DateTime with the timezone's UTC offset + # + # Time.zone.now.to_datetime # => Tue, 18 Aug 2015 02:32:20 +0000 + # Time.current.in_time_zone('Hawaii').to_datetime # => Mon, 17 Aug 2015 16:32:20 -1000 + def to_datetime + @to_datetime ||= utc.to_datetime.new_offset(Rational(utc_offset, 86_400)) + end + + # Returns an instance of +Time+, either with the same UTC offset + # as +self+ or in the local system timezone depending on the setting + # of +ActiveSupport.to_time_preserves_timezone+. + def to_time + if preserve_timezone + @to_time_with_instance_offset ||= getlocal(utc_offset) + else + @to_time_with_system_offset ||= getlocal + end + end + + # So that +self+ acts_like?(:time). + def acts_like_time? + true + end + + # Say we're a Time to thwart type checking. + def is_a?(klass) + klass == ::Time || super + end + alias_method :kind_of?, :is_a? + + # An instance of ActiveSupport::TimeWithZone is never blank + def blank? + false + end + + def freeze + # preload instance variables before freezing + period; utc; time; to_datetime; to_time + super + end + + def marshal_dump + [utc, time_zone.name, time] + end + + def marshal_load(variables) + initialize(variables[0].utc, ::Time.find_zone(variables[1]), variables[2].utc) + end + + # respond_to_missing? is not called in some cases, such as when type conversion is + # performed with Kernel#String + def respond_to?(sym, include_priv = false) + # ensure that we're not going to throw and rescue from NoMethodError in method_missing which is slow + return false if sym.to_sym == :to_str + super + end + + # Ensure proxy class responds to all methods that underlying time instance + # responds to. + def respond_to_missing?(sym, include_priv) + return false if sym.to_sym == :acts_like_date? + time.respond_to?(sym, include_priv) + end + + # Send the missing method to +time+ instance, and wrap result in a new + # TimeWithZone with the existing +time_zone+. + def method_missing(sym, *args, &block) + wrap_with_time_zone time.__send__(sym, *args, &block) + rescue NoMethodError => e + raise e, e.message.sub(time.inspect, inspect).sub("Time", "ActiveSupport::TimeWithZone"), e.backtrace + end + + private + SECONDS_PER_DAY = 86400 + + def incorporate_utc_offset(time, offset) + if time.kind_of?(Date) + time + Rational(offset, SECONDS_PER_DAY) + else + time + offset + end + end + + def get_period_and_ensure_valid_local_time(period) + # we don't want a Time.local instance enforcing its own DST rules as well, + # so transfer time values to a utc constructor if necessary + @time = transfer_time_values_to_utc_constructor(@time) unless @time.utc? + begin + period || @time_zone.period_for_local(@time) + rescue ::TZInfo::PeriodNotFound + # time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again + @time += 1.hour + retry + end + end + + def transfer_time_values_to_utc_constructor(time) + # avoid creating another Time object if possible + return time if time.instance_of?(::Time) && time.utc? + ::Time.utc(time.year, time.month, time.day, time.hour, time.min, time.sec + time.subsec) + end + + def duration_of_variable_length?(obj) + ActiveSupport::Duration === obj && obj.variable? + end + + def wrap_with_time_zone(time) + if time.acts_like?(:time) + periods = time_zone.periods_for_local(time) + self.class.new(nil, time_zone, time, periods.include?(period) ? period : nil) + elsif time.is_a?(Range) + wrap_with_time_zone(time.begin)..wrap_with_time_zone(time.end) + else + time + end + end + end +end + +# These prevent Psych from calling `ActiveSupport::TimeWithZone.name` +# and triggering the deprecation warning about the change in Rails 7.1. +YAML.load_tags["!ruby/object:ActiveSupport::TimeWithZone"] = "ActiveSupport::TimeWithZone" +YAML.dump_tags[ActiveSupport::TimeWithZone] = "!ruby/object:ActiveSupport::TimeWithZone" diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/values/time_zone.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/values/time_zone.rb new file mode 100644 index 0000000..1650b91 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/values/time_zone.rb @@ -0,0 +1,601 @@ +# frozen_string_literal: true + +require "tzinfo" +require "concurrent/map" + +module ActiveSupport + # The TimeZone class serves as a wrapper around TZInfo::Timezone instances. + # It allows us to do the following: + # + # * Limit the set of zones provided by TZInfo to a meaningful subset of 134 + # zones. + # * Retrieve and display zones with a friendlier name + # (e.g., "Eastern Time (US & Canada)" instead of "America/New_York"). + # * Lazily load TZInfo::Timezone instances only when they're needed. + # * Create ActiveSupport::TimeWithZone instances via TimeZone's +local+, + # +parse+, +at+ and +now+ methods. + # + # If you set config.time_zone in the Rails Application, you can + # access this TimeZone object via Time.zone: + # + # # application.rb: + # class Application < Rails::Application + # config.time_zone = 'Eastern Time (US & Canada)' + # end + # + # Time.zone # => # + # Time.zone.name # => "Eastern Time (US & Canada)" + # Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00 + class TimeZone + # Keys are Rails TimeZone names, values are TZInfo identifiers. + MAPPING = { + "International Date Line West" => "Etc/GMT+12", + "Midway Island" => "Pacific/Midway", + "American Samoa" => "Pacific/Pago_Pago", + "Hawaii" => "Pacific/Honolulu", + "Alaska" => "America/Juneau", + "Pacific Time (US & Canada)" => "America/Los_Angeles", + "Tijuana" => "America/Tijuana", + "Mountain Time (US & Canada)" => "America/Denver", + "Arizona" => "America/Phoenix", + "Chihuahua" => "America/Chihuahua", + "Mazatlan" => "America/Mazatlan", + "Central Time (US & Canada)" => "America/Chicago", + "Saskatchewan" => "America/Regina", + "Guadalajara" => "America/Mexico_City", + "Mexico City" => "America/Mexico_City", + "Monterrey" => "America/Monterrey", + "Central America" => "America/Guatemala", + "Eastern Time (US & Canada)" => "America/New_York", + "Indiana (East)" => "America/Indiana/Indianapolis", + "Bogota" => "America/Bogota", + "Lima" => "America/Lima", + "Quito" => "America/Lima", + "Atlantic Time (Canada)" => "America/Halifax", + "Caracas" => "America/Caracas", + "La Paz" => "America/La_Paz", + "Santiago" => "America/Santiago", + "Newfoundland" => "America/St_Johns", + "Brasilia" => "America/Sao_Paulo", + "Buenos Aires" => "America/Argentina/Buenos_Aires", + "Montevideo" => "America/Montevideo", + "Georgetown" => "America/Guyana", + "Puerto Rico" => "America/Puerto_Rico", + "Greenland" => "America/Godthab", + "Mid-Atlantic" => "Atlantic/South_Georgia", + "Azores" => "Atlantic/Azores", + "Cape Verde Is." => "Atlantic/Cape_Verde", + "Dublin" => "Europe/Dublin", + "Edinburgh" => "Europe/London", + "Lisbon" => "Europe/Lisbon", + "London" => "Europe/London", + "Casablanca" => "Africa/Casablanca", + "Monrovia" => "Africa/Monrovia", + "UTC" => "Etc/UTC", + "Belgrade" => "Europe/Belgrade", + "Bratislava" => "Europe/Bratislava", + "Budapest" => "Europe/Budapest", + "Ljubljana" => "Europe/Ljubljana", + "Prague" => "Europe/Prague", + "Sarajevo" => "Europe/Sarajevo", + "Skopje" => "Europe/Skopje", + "Warsaw" => "Europe/Warsaw", + "Zagreb" => "Europe/Zagreb", + "Brussels" => "Europe/Brussels", + "Copenhagen" => "Europe/Copenhagen", + "Madrid" => "Europe/Madrid", + "Paris" => "Europe/Paris", + "Amsterdam" => "Europe/Amsterdam", + "Berlin" => "Europe/Berlin", + "Bern" => "Europe/Zurich", + "Zurich" => "Europe/Zurich", + "Rome" => "Europe/Rome", + "Stockholm" => "Europe/Stockholm", + "Vienna" => "Europe/Vienna", + "West Central Africa" => "Africa/Algiers", + "Bucharest" => "Europe/Bucharest", + "Cairo" => "Africa/Cairo", + "Helsinki" => "Europe/Helsinki", + "Kyiv" => "Europe/Kiev", + "Riga" => "Europe/Riga", + "Sofia" => "Europe/Sofia", + "Tallinn" => "Europe/Tallinn", + "Vilnius" => "Europe/Vilnius", + "Athens" => "Europe/Athens", + "Istanbul" => "Europe/Istanbul", + "Minsk" => "Europe/Minsk", + "Jerusalem" => "Asia/Jerusalem", + "Harare" => "Africa/Harare", + "Pretoria" => "Africa/Johannesburg", + "Kaliningrad" => "Europe/Kaliningrad", + "Moscow" => "Europe/Moscow", + "St. Petersburg" => "Europe/Moscow", + "Volgograd" => "Europe/Volgograd", + "Samara" => "Europe/Samara", + "Kuwait" => "Asia/Kuwait", + "Riyadh" => "Asia/Riyadh", + "Nairobi" => "Africa/Nairobi", + "Baghdad" => "Asia/Baghdad", + "Tehran" => "Asia/Tehran", + "Abu Dhabi" => "Asia/Muscat", + "Muscat" => "Asia/Muscat", + "Baku" => "Asia/Baku", + "Tbilisi" => "Asia/Tbilisi", + "Yerevan" => "Asia/Yerevan", + "Kabul" => "Asia/Kabul", + "Ekaterinburg" => "Asia/Yekaterinburg", + "Islamabad" => "Asia/Karachi", + "Karachi" => "Asia/Karachi", + "Tashkent" => "Asia/Tashkent", + "Chennai" => "Asia/Kolkata", + "Kolkata" => "Asia/Kolkata", + "Mumbai" => "Asia/Kolkata", + "New Delhi" => "Asia/Kolkata", + "Kathmandu" => "Asia/Kathmandu", + "Astana" => "Asia/Dhaka", + "Dhaka" => "Asia/Dhaka", + "Sri Jayawardenepura" => "Asia/Colombo", + "Almaty" => "Asia/Almaty", + "Novosibirsk" => "Asia/Novosibirsk", + "Rangoon" => "Asia/Rangoon", + "Bangkok" => "Asia/Bangkok", + "Hanoi" => "Asia/Bangkok", + "Jakarta" => "Asia/Jakarta", + "Krasnoyarsk" => "Asia/Krasnoyarsk", + "Beijing" => "Asia/Shanghai", + "Chongqing" => "Asia/Chongqing", + "Hong Kong" => "Asia/Hong_Kong", + "Urumqi" => "Asia/Urumqi", + "Kuala Lumpur" => "Asia/Kuala_Lumpur", + "Singapore" => "Asia/Singapore", + "Taipei" => "Asia/Taipei", + "Perth" => "Australia/Perth", + "Irkutsk" => "Asia/Irkutsk", + "Ulaanbaatar" => "Asia/Ulaanbaatar", + "Seoul" => "Asia/Seoul", + "Osaka" => "Asia/Tokyo", + "Sapporo" => "Asia/Tokyo", + "Tokyo" => "Asia/Tokyo", + "Yakutsk" => "Asia/Yakutsk", + "Darwin" => "Australia/Darwin", + "Adelaide" => "Australia/Adelaide", + "Canberra" => "Australia/Melbourne", + "Melbourne" => "Australia/Melbourne", + "Sydney" => "Australia/Sydney", + "Brisbane" => "Australia/Brisbane", + "Hobart" => "Australia/Hobart", + "Vladivostok" => "Asia/Vladivostok", + "Guam" => "Pacific/Guam", + "Port Moresby" => "Pacific/Port_Moresby", + "Magadan" => "Asia/Magadan", + "Srednekolymsk" => "Asia/Srednekolymsk", + "Solomon Is." => "Pacific/Guadalcanal", + "New Caledonia" => "Pacific/Noumea", + "Fiji" => "Pacific/Fiji", + "Kamchatka" => "Asia/Kamchatka", + "Marshall Is." => "Pacific/Majuro", + "Auckland" => "Pacific/Auckland", + "Wellington" => "Pacific/Auckland", + "Nuku'alofa" => "Pacific/Tongatapu", + "Tokelau Is." => "Pacific/Fakaofo", + "Chatham Is." => "Pacific/Chatham", + "Samoa" => "Pacific/Apia" + } + + UTC_OFFSET_WITH_COLON = "%s%02d:%02d" # :nodoc: + UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.tr(":", "") # :nodoc: + private_constant :UTC_OFFSET_WITH_COLON, :UTC_OFFSET_WITHOUT_COLON + + @lazy_zones_map = Concurrent::Map.new + @country_zones = Concurrent::Map.new + + class << self + # Assumes self represents an offset from UTC in seconds (as returned from + # Time#utc_offset) and turns this into an +HH:MM formatted string. + # + # ActiveSupport::TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00" + def seconds_to_utc_offset(seconds, colon = true) + format = colon ? UTC_OFFSET_WITH_COLON : UTC_OFFSET_WITHOUT_COLON + sign = (seconds < 0 ? "-" : "+") + hours = seconds.abs / 3600 + minutes = (seconds.abs % 3600) / 60 + format % [sign, hours, minutes] + end + + def find_tzinfo(name) + TZInfo::Timezone.get(MAPPING[name] || name) + end + + alias_method :create, :new + + # Returns a TimeZone instance with the given name, or +nil+ if no + # such TimeZone instance exists. (This exists to support the use of + # this class with the +composed_of+ macro.) + def new(name) + self[name] + end + + # Returns an array of all TimeZone objects. There are multiple + # TimeZone objects per time zone, in many cases, to make it easier + # for users to find their own time zone. + def all + @zones ||= zones_map.values.sort + end + + # Locate a specific time zone object. If the argument is a string, it + # is interpreted to mean the name of the timezone to locate. If it is a + # numeric value it is either the hour offset, or the second offset, of the + # timezone to find. (The first one with that offset will be returned.) + # Returns +nil+ if no such time zone is known to the system. + def [](arg) + case arg + when self + arg + when String + begin + @lazy_zones_map[arg] ||= create(arg) + rescue TZInfo::InvalidTimezoneIdentifier + nil + end + when TZInfo::Timezone + @lazy_zones_map[arg.name] ||= create(arg.name, nil, arg) + when Numeric, ActiveSupport::Duration + arg *= 3600 if arg.abs <= 13 + all.find { |z| z.utc_offset == arg.to_i } + else + raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}" + end + end + + # A convenience method for returning a collection of TimeZone objects + # for time zones in the USA. + def us_zones + country_zones(:us) + end + + # A convenience method for returning a collection of TimeZone objects + # for time zones in the country specified by its ISO 3166-1 Alpha2 code. + def country_zones(country_code) + code = country_code.to_s.upcase + @country_zones[code] ||= load_country_zones(code) + end + + def clear # :nodoc: + @lazy_zones_map = Concurrent::Map.new + @country_zones = Concurrent::Map.new + @zones = nil + @zones_map = nil + end + + private + def load_country_zones(code) + country = TZInfo::Country.get(code) + country.zone_identifiers.flat_map do |tz_id| + if MAPPING.value?(tz_id) + MAPPING.inject([]) do |memo, (key, value)| + memo << self[key] if value == tz_id + memo + end + else + create(tz_id, nil, TZInfo::Timezone.get(tz_id)) + end + end.sort! + end + + def zones_map + @zones_map ||= MAPPING.each_with_object({}) do |(name, _), zones| + timezone = self[name] + zones[name] = timezone if timezone + end + end + end + + include Comparable + attr_reader :name + attr_reader :tzinfo + + # Create a new TimeZone object with the given name and offset. The + # offset is the number of seconds that this time zone is offset from UTC + # (GMT). Seconds were chosen as the offset unit because that is the unit + # that Ruby uses to represent time zone offsets (see Time#utc_offset). + def initialize(name, utc_offset = nil, tzinfo = nil) + @name = name + @utc_offset = utc_offset + @tzinfo = tzinfo || TimeZone.find_tzinfo(name) + end + + # Returns the offset of this time zone from UTC in seconds. + def utc_offset + @utc_offset || tzinfo&.current_period&.base_utc_offset + end + + # Returns a formatted string of the offset from UTC, or an alternative + # string if the time zone is already UTC. + # + # zone = ActiveSupport::TimeZone['Central Time (US & Canada)'] + # zone.formatted_offset # => "-06:00" + # zone.formatted_offset(false) # => "-0600" + def formatted_offset(colon = true, alternate_utc_string = nil) + utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon) + end + + # Compare this time zone to the parameter. The two are compared first on + # their offsets, and then by name. + def <=>(zone) + return unless zone.respond_to? :utc_offset + result = (utc_offset <=> zone.utc_offset) + result = (name <=> zone.name) if result == 0 + result + end + + # Compare #name and TZInfo identifier to a supplied regexp, returning +true+ + # if a match is found. + def =~(re) + re === name || re === MAPPING[name] + end + + # Compare #name and TZInfo identifier to a supplied regexp, returning +true+ + # if a match is found. + def match?(re) + (re == name) || (re == MAPPING[name]) || + ((Regexp === re) && (re.match?(name) || re.match?(MAPPING[name]))) + end + + # Returns a textual representation of this time zone. + def to_s + "(GMT#{formatted_offset}) #{name}" + end + + # Method for creating new ActiveSupport::TimeWithZone instance in time zone + # of +self+ from given values. + # + # Time.zone = 'Hawaii' # => "Hawaii" + # Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00 + def local(*args) + time = Time.utc(*args) + ActiveSupport::TimeWithZone.new(nil, self, time) + end + + # Method for creating new ActiveSupport::TimeWithZone instance in time zone + # of +self+ from number of seconds since the Unix epoch. + # + # Time.zone = 'Hawaii' # => "Hawaii" + # Time.utc(2000).to_f # => 946684800.0 + # Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00 + # + # A second argument can be supplied to specify sub-second precision. + # + # Time.zone = 'Hawaii' # => "Hawaii" + # Time.at(946684800, 123456.789).nsec # => 123456789 + def at(*args) + Time.at(*args).utc.in_time_zone(self) + end + + # Method for creating new ActiveSupport::TimeWithZone instance in time zone + # of +self+ from an ISO 8601 string. + # + # Time.zone = 'Hawaii' # => "Hawaii" + # Time.zone.iso8601('1999-12-31T14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00 + # + # If the time components are missing then they will be set to zero. + # + # Time.zone = 'Hawaii' # => "Hawaii" + # Time.zone.iso8601('1999-12-31') # => Fri, 31 Dec 1999 00:00:00 HST -10:00 + # + # If the string is invalid then an +ArgumentError+ will be raised unlike +parse+ + # which usually returns +nil+ when given an invalid date string. + def iso8601(str) + # Historically `Date._iso8601(nil)` returns `{}`, but in the `date` gem versions `3.2.1`, `3.1.2`, `3.0.2`, + # and `2.0.1`, `Date._iso8601(nil)` raises `TypeError` https://github.com/ruby/date/issues/39 + # Future `date` releases are expected to revert back to the original behavior. + raise ArgumentError, "invalid date" if str.nil? + + parts = Date._iso8601(str) + + year = parts.fetch(:year) + + if parts.key?(:yday) + ordinal_date = Date.ordinal(year, parts.fetch(:yday)) + month = ordinal_date.month + day = ordinal_date.day + else + month = parts.fetch(:mon) + day = parts.fetch(:mday) + end + + time = Time.new( + year, + month, + day, + parts.fetch(:hour, 0), + parts.fetch(:min, 0), + parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0), + parts.fetch(:offset, 0) + ) + + if parts[:offset] + TimeWithZone.new(time.utc, self) + else + TimeWithZone.new(nil, self, time) + end + + rescue Date::Error, KeyError + raise ArgumentError, "invalid date" + end + + # Method for creating new ActiveSupport::TimeWithZone instance in time zone + # of +self+ from parsed string. + # + # Time.zone = 'Hawaii' # => "Hawaii" + # Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00 + # + # If upper components are missing from the string, they are supplied from + # TimeZone#now: + # + # Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00 + # Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00 + # + # However, if the date component is not provided, but any other upper + # components are supplied, then the day of the month defaults to 1: + # + # Time.zone.parse('Mar 2000') # => Wed, 01 Mar 2000 00:00:00 HST -10:00 + # + # If the string is invalid then an +ArgumentError+ could be raised. + def parse(str, now = now()) + parts_to_time(Date._parse(str, false), now) + end + + # Method for creating new ActiveSupport::TimeWithZone instance in time zone + # of +self+ from an RFC 3339 string. + # + # Time.zone = 'Hawaii' # => "Hawaii" + # Time.zone.rfc3339('2000-01-01T00:00:00Z') # => Fri, 31 Dec 1999 14:00:00 HST -10:00 + # + # If the time or zone components are missing then an +ArgumentError+ will + # be raised. This is much stricter than either +parse+ or +iso8601+ which + # allow for missing components. + # + # Time.zone = 'Hawaii' # => "Hawaii" + # Time.zone.rfc3339('1999-12-31') # => ArgumentError: invalid date + def rfc3339(str) + parts = Date._rfc3339(str) + + raise ArgumentError, "invalid date" if parts.empty? + + time = Time.new( + parts.fetch(:year), + parts.fetch(:mon), + parts.fetch(:mday), + parts.fetch(:hour), + parts.fetch(:min), + parts.fetch(:sec) + parts.fetch(:sec_fraction, 0), + parts.fetch(:offset) + ) + + TimeWithZone.new(time.utc, self) + end + + # Parses +str+ according to +format+ and returns an ActiveSupport::TimeWithZone. + # + # Assumes that +str+ is a time in the time zone +self+, + # unless +format+ includes an explicit time zone. + # (This is the same behavior as +parse+.) + # In either case, the returned TimeWithZone has the timezone of +self+. + # + # Time.zone = 'Hawaii' # => "Hawaii" + # Time.zone.strptime('1999-12-31 14:00:00', '%Y-%m-%d %H:%M:%S') # => Fri, 31 Dec 1999 14:00:00 HST -10:00 + # + # If upper components are missing from the string, they are supplied from + # TimeZone#now: + # + # Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00 + # Time.zone.strptime('22:30:00', '%H:%M:%S') # => Fri, 31 Dec 1999 22:30:00 HST -10:00 + # + # However, if the date component is not provided, but any other upper + # components are supplied, then the day of the month defaults to 1: + # + # Time.zone.strptime('Mar 2000', '%b %Y') # => Wed, 01 Mar 2000 00:00:00 HST -10:00 + def strptime(str, format, now = now()) + parts_to_time(DateTime._strptime(str, format), now) + end + + # Returns an ActiveSupport::TimeWithZone instance representing the current + # time in the time zone represented by +self+. + # + # Time.zone = 'Hawaii' # => "Hawaii" + # Time.zone.now # => Wed, 23 Jan 2008 20:24:27 HST -10:00 + def now + time_now.utc.in_time_zone(self) + end + + # Returns the current date in this time zone. + def today + tzinfo.now.to_date + end + + # Returns the next date in this time zone. + def tomorrow + today + 1 + end + + # Returns the previous date in this time zone. + def yesterday + today - 1 + end + + # Adjust the given time to the simultaneous time in the time zone + # represented by +self+. Returns a local time with the appropriate offset + # -- if you want an ActiveSupport::TimeWithZone instance, use + # Time#in_time_zone() instead. + # + # As of tzinfo 2, utc_to_local returns a Time with a non-zero utc_offset. + # See the +utc_to_local_returns_utc_offset_times+ config for more info. + def utc_to_local(time) + tzinfo.utc_to_local(time).yield_self do |t| + ActiveSupport.utc_to_local_returns_utc_offset_times ? + t : Time.utc(t.year, t.month, t.day, t.hour, t.min, t.sec, t.sec_fraction * 1_000_000) + end + end + + # Adjust the given time to the simultaneous time in UTC. Returns a + # Time.utc() instance. + def local_to_utc(time, dst = true) + tzinfo.local_to_utc(time, dst) + end + + # Available so that TimeZone instances respond like TZInfo::Timezone + # instances. + def period_for_utc(time) + tzinfo.period_for_utc(time) + end + + # Available so that TimeZone instances respond like TZInfo::Timezone + # instances. + def period_for_local(time, dst = true) + tzinfo.period_for_local(time, dst) { |periods| periods.last } + end + + def periods_for_local(time) # :nodoc: + tzinfo.periods_for_local(time) + end + + def init_with(coder) # :nodoc: + initialize(coder["name"]) + end + + def encode_with(coder) # :nodoc: + coder.tag = "!ruby/object:#{self.class}" + coder.map = { "name" => tzinfo.name } + end + + private + def parts_to_time(parts, now) + raise ArgumentError, "invalid date" if parts.nil? + return if parts.empty? + + if parts[:seconds] + time = Time.at(parts[:seconds]) + else + time = Time.new( + parts.fetch(:year, now.year), + parts.fetch(:mon, now.month), + parts.fetch(:mday, parts[:year] || parts[:mon] ? 1 : now.day), + parts.fetch(:hour, 0), + parts.fetch(:min, 0), + parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0), + parts.fetch(:offset, 0) + ) + end + + if parts[:offset] || parts[:seconds] + TimeWithZone.new(time.utc, self) + else + TimeWithZone.new(nil, self, time) + end + end + + def time_now + Time.now + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/version.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/version.rb new file mode 100644 index 0000000..928838c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/version.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require_relative "gem_version" + +module ActiveSupport + # Returns the version of the currently loaded ActiveSupport as a Gem::Version + def self.version + gem_version + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini.rb new file mode 100644 index 0000000..dd6bee0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini.rb @@ -0,0 +1,202 @@ +# frozen_string_literal: true + +require "time" +require "base64" +require "bigdecimal" +require "bigdecimal/util" +require "active_support/core_ext/module/delegation" +require "active_support/core_ext/string/inflections" +require "active_support/core_ext/date_time/calculations" + +module ActiveSupport + # = XmlMini + # + # To use the much faster libxml parser: + # gem 'libxml-ruby', '=0.9.7' + # XmlMini.backend = 'LibXML' + module XmlMini + extend self + + # This module decorates files deserialized using Hash.from_xml with + # the original_filename and content_type methods. + module FileLike # :nodoc: + attr_writer :original_filename, :content_type + + def original_filename + @original_filename || "untitled" + end + + def content_type + @content_type || "application/octet-stream" + end + end + + DEFAULT_ENCODINGS = { + "binary" => "base64" + } unless defined?(DEFAULT_ENCODINGS) + + unless defined?(TYPE_NAMES) + TYPE_NAMES = { + "Symbol" => "symbol", + "Integer" => "integer", + "BigDecimal" => "decimal", + "Float" => "float", + "TrueClass" => "boolean", + "FalseClass" => "boolean", + "Date" => "date", + "DateTime" => "dateTime", + "Time" => "dateTime", + "Array" => "array", + "Hash" => "hash" + } + end + TYPE_NAMES["ActiveSupport::TimeWithZone"] = TYPE_NAMES["Time"] + + FORMATTING = { + "symbol" => Proc.new { |symbol| symbol.to_s }, + "date" => Proc.new { |date| date.to_fs(:db) }, + "dateTime" => Proc.new { |time| time.xmlschema }, + "binary" => Proc.new { |binary| ::Base64.encode64(binary) }, + "yaml" => Proc.new { |yaml| yaml.to_yaml } + } unless defined?(FORMATTING) + + # TODO use regexp instead of Date.parse + unless defined?(PARSING) + PARSING = { + "symbol" => Proc.new { |symbol| symbol.to_s.to_sym }, + "date" => Proc.new { |date| ::Date.parse(date) }, + "datetime" => Proc.new { |time| Time.xmlschema(time).utc rescue ::DateTime.parse(time).utc }, + "integer" => Proc.new { |integer| integer.to_i }, + "float" => Proc.new { |float| float.to_f }, + "decimal" => Proc.new do |number| + if String === number + number.to_d + else + BigDecimal(number) + end + end, + "boolean" => Proc.new { |boolean| %w(1 true).include?(boolean.to_s.strip) }, + "string" => Proc.new { |string| string.to_s }, + "yaml" => Proc.new { |yaml| YAML.load(yaml) rescue yaml }, + "base64Binary" => Proc.new { |bin| ::Base64.decode64(bin) }, + "binary" => Proc.new { |bin, entity| _parse_binary(bin, entity) }, + "file" => Proc.new { |file, entity| _parse_file(file, entity) } + } + + PARSING.update( + "double" => PARSING["float"], + "dateTime" => PARSING["datetime"] + ) + end + + attr_accessor :depth + self.depth = 100 + + delegate :parse, to: :backend + + def backend + current_thread_backend || @backend + end + + def backend=(name) + backend = name && cast_backend_name_to_module(name) + self.current_thread_backend = backend if current_thread_backend + @backend = backend + end + + def with_backend(name) + old_backend = current_thread_backend + self.current_thread_backend = name && cast_backend_name_to_module(name) + yield + ensure + self.current_thread_backend = old_backend + end + + def to_tag(key, value, options) + type_name = options.delete(:type) + merged_options = options.merge(root: key, skip_instruct: true) + + if value.is_a?(::Method) || value.is_a?(::Proc) + if value.arity == 1 + value.call(merged_options) + else + value.call(merged_options, key.to_s.singularize) + end + elsif value.respond_to?(:to_xml) + value.to_xml(merged_options) + else + type_name ||= TYPE_NAMES[value.class.name] + type_name ||= value.class.name if value && !value.respond_to?(:to_str) + type_name = type_name.to_s if type_name + type_name = "dateTime" if type_name == "datetime" + + key = rename_key(key.to_s, options) + + attributes = options[:skip_types] || type_name.nil? ? {} : { type: type_name } + attributes[:nil] = true if value.nil? + + encoding = options[:encoding] || DEFAULT_ENCODINGS[type_name] + attributes[:encoding] = encoding if encoding + + formatted_value = FORMATTING[type_name] && !value.nil? ? + FORMATTING[type_name].call(value) : value + + options[:builder].tag!(key, formatted_value, attributes) + end + end + + def rename_key(key, options = {}) + camelize = options[:camelize] + dasherize = !options.has_key?(:dasherize) || options[:dasherize] + if camelize + key = true == camelize ? key.camelize : key.camelize(camelize) + end + key = _dasherize(key) if dasherize + key + end + + private + def _dasherize(key) + # $2 must be a non-greedy regex for this to work + left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1, 3] + "#{left}#{middle.tr('_ ', '--')}#{right}" + end + + # TODO: Add support for other encodings + def _parse_binary(bin, entity) + case entity["encoding"] + when "base64" + ::Base64.decode64(bin) + else + bin + end + end + + def _parse_file(file, entity) + f = StringIO.new(::Base64.decode64(file)) + f.extend(FileLike) + f.original_filename = entity["name"] + f.content_type = entity["content_type"] + f + end + + def current_thread_backend + IsolatedExecutionState[:xml_mini_backend] + end + + def current_thread_backend=(name) + IsolatedExecutionState[:xml_mini_backend] = name && cast_backend_name_to_module(name) + end + + def cast_backend_name_to_module(name) + if name.is_a?(Module) + name + else + require "active_support/xml_mini/#{name.downcase}" + ActiveSupport.const_get("XmlMini_#{name}") + end + end + end + + XmlMini.backend = "REXML" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/jdom.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/jdom.rb new file mode 100644 index 0000000..b5aa909 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/jdom.rb @@ -0,0 +1,182 @@ +# frozen_string_literal: true + +raise "JRuby is required to use the JDOM backend for XmlMini" unless RUBY_PLATFORM.include?("java") + +require "jruby" +include Java + +require "active_support/core_ext/object/blank" + +java_import javax.xml.parsers.DocumentBuilder unless defined? DocumentBuilder +java_import javax.xml.parsers.DocumentBuilderFactory unless defined? DocumentBuilderFactory +java_import java.io.StringReader unless defined? StringReader +java_import org.xml.sax.InputSource unless defined? InputSource +java_import org.xml.sax.Attributes unless defined? Attributes +java_import org.w3c.dom.Node unless defined? Node + +module ActiveSupport + module XmlMini_JDOM # :nodoc: + extend self + + CONTENT_KEY = "__content__" + + NODE_TYPE_NAMES = %w{ATTRIBUTE_NODE CDATA_SECTION_NODE COMMENT_NODE DOCUMENT_FRAGMENT_NODE + DOCUMENT_NODE DOCUMENT_TYPE_NODE ELEMENT_NODE ENTITY_NODE ENTITY_REFERENCE_NODE NOTATION_NODE + PROCESSING_INSTRUCTION_NODE TEXT_NODE} + + node_type_map = {} + NODE_TYPE_NAMES.each { |type| node_type_map[Node.send(type)] = type } + + # Parse an XML Document string or IO into a simple hash using Java's jdom. + # data:: + # XML Document string or IO to parse + def parse(data) + if data.respond_to?(:read) + data = data.read + end + + if data.blank? + {} + else + @dbf = DocumentBuilderFactory.new_instance + # secure processing of java xml + # https://archive.is/9xcQQ + @dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false) + @dbf.setFeature("http://xml.org/sax/features/external-general-entities", false) + @dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false) + @dbf.setFeature(javax.xml.XMLConstants::FEATURE_SECURE_PROCESSING, true) + xml_string_reader = StringReader.new(data) + xml_input_source = InputSource.new(xml_string_reader) + doc = @dbf.new_document_builder.parse(xml_input_source) + merge_element!({ CONTENT_KEY => "" }, doc.document_element, XmlMini.depth) + end + end + + private + # Convert an XML element and merge into the hash + # + # hash:: + # Hash to merge the converted element into. + # element:: + # XML element to merge into hash + def merge_element!(hash, element, depth) + raise "Document too deep!" if depth == 0 + delete_empty(hash) + merge!(hash, element.tag_name, collapse(element, depth)) + end + + def delete_empty(hash) + hash.delete(CONTENT_KEY) if hash[CONTENT_KEY] == "" + end + + # Actually converts an XML document element into a data structure. + # + # element:: + # The document element to be collapsed. + def collapse(element, depth) + hash = get_attributes(element) + + child_nodes = element.child_nodes + if child_nodes.length > 0 + (0...child_nodes.length).each do |i| + child = child_nodes.item(i) + merge_element!(hash, child, depth - 1) unless child.node_type == Node.TEXT_NODE + end + merge_texts!(hash, element) unless empty_content?(element) + hash + else + merge_texts!(hash, element) + end + end + + # Merge all the texts of an element into the hash + # + # hash:: + # Hash to add the converted element to. + # element:: + # XML element whose texts are to me merged into the hash + def merge_texts!(hash, element) + delete_empty(hash) + text_children = texts(element) + if text_children.join.empty? + hash + else + # must use value to prevent double-escaping + merge!(hash, CONTENT_KEY, text_children.join) + end + end + + # Adds a new key/value pair to an existing Hash. If the key to be added + # already exists and the existing value associated with key is not + # an Array, it will be wrapped in an Array. Then the new value is + # appended to that Array. + # + # hash:: + # Hash to add key/value pair to. + # key:: + # Key to be added. + # value:: + # Value to be associated with key. + def merge!(hash, key, value) + if hash.has_key?(key) + if hash[key].instance_of?(Array) + hash[key] << value + else + hash[key] = [hash[key], value] + end + elsif value.instance_of?(Array) + hash[key] = [value] + else + hash[key] = value + end + hash + end + + # Converts the attributes array of an XML element into a hash. + # Returns an empty Hash if node has no attributes. + # + # element:: + # XML element to extract attributes from. + def get_attributes(element) + attribute_hash = {} + attributes = element.attributes + (0...attributes.length).each do |i| + attribute_hash[CONTENT_KEY] ||= "" + attribute_hash[attributes.item(i).name] = attributes.item(i).value + end + attribute_hash + end + + # Determines if a document element has text content + # + # element:: + # XML element to be checked. + def texts(element) + texts = [] + child_nodes = element.child_nodes + (0...child_nodes.length).each do |i| + item = child_nodes.item(i) + if item.node_type == Node.TEXT_NODE + texts << item.get_data + end + end + texts + end + + # Determines if a document element has text content + # + # element:: + # XML element to be checked. + def empty_content?(element) + text = +"" + child_nodes = element.child_nodes + (0...child_nodes.length).each do |i| + item = child_nodes.item(i) + if item.node_type == Node.TEXT_NODE + text << item.get_data.strip + end + end + text.strip.length == 0 + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/libxml.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/libxml.rb new file mode 100644 index 0000000..65976a2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/libxml.rb @@ -0,0 +1,80 @@ +# frozen_string_literal: true + +require "libxml" +require "active_support/core_ext/object/blank" +require "stringio" + +module ActiveSupport + module XmlMini_LibXML # :nodoc: + extend self + + # Parse an XML Document string or IO into a simple hash using libxml. + # data:: + # XML Document string or IO to parse + def parse(data) + if !data.respond_to?(:read) + data = StringIO.new(data || "") + end + + if data.eof? + {} + else + LibXML::XML::Parser.io(data).parse.to_hash + end + end + end +end + +module LibXML # :nodoc: + module Conversions # :nodoc: + module Document # :nodoc: + def to_hash + root.to_hash + end + end + + module Node # :nodoc: + CONTENT_ROOT = "__content__" + + # Convert XML document to hash. + # + # hash:: + # Hash to merge the converted element into. + def to_hash(hash = {}) + node_hash = {} + + # Insert node hash into parent hash correctly. + case hash[name] + when Array then hash[name] << node_hash + when Hash then hash[name] = [hash[name], node_hash] + when nil then hash[name] = node_hash + end + + # Handle child elements + each_child do |c| + if c.element? + c.to_hash(node_hash) + elsif c.text? || c.cdata? + node_hash[CONTENT_ROOT] ||= +"" + node_hash[CONTENT_ROOT] << c.content + end + end + + # Remove content node if it is blank + if node_hash.length > 1 && node_hash[CONTENT_ROOT].blank? + node_hash.delete(CONTENT_ROOT) + end + + # Handle attributes + each_attr { |a| node_hash[a.name] = a.value } + + hash + end + end + end +end + +# :enddoc: + +LibXML::XML::Document.include(LibXML::Conversions::Document) +LibXML::XML::Node.include(LibXML::Conversions::Node) diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/libxmlsax.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/libxmlsax.rb new file mode 100644 index 0000000..33d594c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/libxmlsax.rb @@ -0,0 +1,83 @@ +# frozen_string_literal: true + +require "libxml" +require "active_support/core_ext/object/blank" +require "stringio" + +module ActiveSupport + module XmlMini_LibXMLSAX # :nodoc: + extend self + + # Class that will build the hash while the XML document + # is being parsed using SAX events. + class HashBuilder + include LibXML::XML::SaxParser::Callbacks + + CONTENT_KEY = "__content__" + HASH_SIZE_KEY = "__hash_size__" + + attr_reader :hash + + def current_hash + @hash_stack.last + end + + def on_start_document + @hash = { CONTENT_KEY => +"" } + @hash_stack = [@hash] + end + + def on_end_document + @hash = @hash_stack.pop + @hash.delete(CONTENT_KEY) + end + + def on_start_element(name, attrs = {}) + new_hash = { CONTENT_KEY => +"" }.merge!(attrs) + new_hash[HASH_SIZE_KEY] = new_hash.size + 1 + + case current_hash[name] + when Array then current_hash[name] << new_hash + when Hash then current_hash[name] = [current_hash[name], new_hash] + when nil then current_hash[name] = new_hash + end + + @hash_stack.push(new_hash) + end + + def on_end_element(name) + if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == "" + current_hash.delete(CONTENT_KEY) + end + @hash_stack.pop + end + + def on_characters(string) + current_hash[CONTENT_KEY] << string + end + + alias_method :on_cdata_block, :on_characters + end + + attr_accessor :document_class + self.document_class = HashBuilder + + def parse(data) + if !data.respond_to?(:read) + data = StringIO.new(data || "") + end + + if data.eof? + {} + else + LibXML::XML::Error.set_handler(&LibXML::XML::Error::QUIET_HANDLER) + parser = LibXML::XML::SaxParser.io(data) + document = document_class.new + + parser.callbacks = document + parser.parse + document.hash + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/nokogiri.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/nokogiri.rb new file mode 100644 index 0000000..3fb58bc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/nokogiri.rb @@ -0,0 +1,83 @@ +# frozen_string_literal: true + +begin + require "nokogiri" +rescue LoadError => e + $stderr.puts "You don't have nokogiri installed in your application. Please add it to your Gemfile and run bundle install" + raise e +end +require "active_support/core_ext/object/blank" +require "stringio" + +module ActiveSupport + module XmlMini_Nokogiri # :nodoc: + extend self + + # Parse an XML Document string or IO into a simple hash using libxml / nokogiri. + # data:: + # XML Document string or IO to parse + def parse(data) + if !data.respond_to?(:read) + data = StringIO.new(data || "") + end + + if data.eof? + {} + else + doc = Nokogiri::XML(data) + raise doc.errors.first if doc.errors.length > 0 + doc.to_hash + end + end + + module Conversions # :nodoc: + module Document # :nodoc: + def to_hash + root.to_hash + end + end + + module Node # :nodoc: + CONTENT_ROOT = "__content__" + + # Convert XML document to hash. + # + # hash:: + # Hash to merge the converted element into. + def to_hash(hash = {}) + node_hash = {} + + # Insert node hash into parent hash correctly. + case hash[name] + when Array then hash[name] << node_hash + when Hash then hash[name] = [hash[name], node_hash] + when nil then hash[name] = node_hash + end + + # Handle child elements + children.each do |c| + if c.element? + c.to_hash(node_hash) + elsif c.text? || c.cdata? + node_hash[CONTENT_ROOT] ||= +"" + node_hash[CONTENT_ROOT] << c.content + end + end + + # Remove content node if it is blank and there are child tags + if node_hash.length > 1 && node_hash[CONTENT_ROOT].blank? + node_hash.delete(CONTENT_ROOT) + end + + # Handle attributes + attribute_nodes.each { |a| node_hash[a.node_name] = a.value } + + hash + end + end + end + + Nokogiri::XML::Document.include(Conversions::Document) + Nokogiri::XML::Node.include(Conversions::Node) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/nokogirisax.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/nokogirisax.rb new file mode 100644 index 0000000..f3ba109 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/nokogirisax.rb @@ -0,0 +1,86 @@ +# frozen_string_literal: true + +begin + require "nokogiri" +rescue LoadError => e + $stderr.puts "You don't have nokogiri installed in your application. Please add it to your Gemfile and run bundle install" + raise e +end +require "active_support/core_ext/object/blank" +require "stringio" + +module ActiveSupport + module XmlMini_NokogiriSAX # :nodoc: + extend self + + # Class that will build the hash while the XML document + # is being parsed using SAX events. + class HashBuilder < Nokogiri::XML::SAX::Document + CONTENT_KEY = "__content__" + HASH_SIZE_KEY = "__hash_size__" + + attr_reader :hash + + def current_hash + @hash_stack.last + end + + def start_document + @hash = {} + @hash_stack = [@hash] + end + + def end_document + raise "Parse stack not empty!" if @hash_stack.size > 1 + end + + def error(error_message) + raise error_message + end + + def start_element(name, attrs = []) + new_hash = { CONTENT_KEY => +"" }.merge!(Hash[attrs]) + new_hash[HASH_SIZE_KEY] = new_hash.size + 1 + + case current_hash[name] + when Array then current_hash[name] << new_hash + when Hash then current_hash[name] = [current_hash[name], new_hash] + when nil then current_hash[name] = new_hash + end + + @hash_stack.push(new_hash) + end + + def end_element(name) + if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == "" + current_hash.delete(CONTENT_KEY) + end + @hash_stack.pop + end + + def characters(string) + current_hash[CONTENT_KEY] << string + end + + alias_method :cdata_block, :characters + end + + attr_accessor :document_class + self.document_class = HashBuilder + + def parse(data) + if !data.respond_to?(:read) + data = StringIO.new(data || "") + end + + if data.eof? + {} + else + document = document_class.new + parser = Nokogiri::XML::SAX::Parser.new(document) + parser.parse(data) + document.hash + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/rexml.rb b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/rexml.rb new file mode 100644 index 0000000..e4e1a1f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/activesupport-7.0.2.3/lib/active_support/xml_mini/rexml.rb @@ -0,0 +1,137 @@ +# frozen_string_literal: true + +require "active_support/core_ext/kernel/reporting" +require "active_support/core_ext/object/blank" +require "stringio" + +module ActiveSupport + module XmlMini_REXML # :nodoc: + extend self + + CONTENT_KEY = "__content__" + + # Parse an XML Document string or IO into a simple hash. + # + # Same as XmlSimple::xml_in but doesn't shoot itself in the foot, + # and uses the defaults from Active Support. + # + # data:: + # XML Document string or IO to parse + def parse(data) + if !data.respond_to?(:read) + data = StringIO.new(data || "") + end + + if data.eof? + {} + else + require_rexml unless defined?(REXML::Document) + doc = REXML::Document.new(data) + + if doc.root + merge_element!({}, doc.root, XmlMini.depth) + else + raise REXML::ParseException, + "The document #{doc.to_s.inspect} does not have a valid root" + end + end + end + + private + def require_rexml + silence_warnings { require "rexml/document" } + rescue LoadError => e + $stderr.puts "You don't have rexml installed in your application. Please add it to your Gemfile and run bundle install" + raise e + end + + # Convert an XML element and merge into the hash + # + # hash:: + # Hash to merge the converted element into. + # element:: + # XML element to merge into hash + def merge_element!(hash, element, depth) + raise REXML::ParseException, "The document is too deep" if depth == 0 + merge!(hash, element.name, collapse(element, depth)) + end + + # Actually converts an XML document element into a data structure. + # + # element:: + # The document element to be collapsed. + def collapse(element, depth) + hash = get_attributes(element) + + if element.has_elements? + element.each_element { |child| merge_element!(hash, child, depth - 1) } + merge_texts!(hash, element) unless empty_content?(element) + hash + else + merge_texts!(hash, element) + end + end + + # Merge all the texts of an element into the hash + # + # hash:: + # Hash to add the converted element to. + # element:: + # XML element whose texts are to me merged into the hash + def merge_texts!(hash, element) + unless element.has_text? + hash + else + # must use value to prevent double-escaping + texts = +"" + element.texts.each { |t| texts << t.value } + merge!(hash, CONTENT_KEY, texts) + end + end + + # Adds a new key/value pair to an existing Hash. If the key to be added + # already exists and the existing value associated with key is not + # an Array, it will be wrapped in an Array. Then the new value is + # appended to that Array. + # + # hash:: + # Hash to add key/value pair to. + # key:: + # Key to be added. + # value:: + # Value to be associated with key. + def merge!(hash, key, value) + if hash.has_key?(key) + if hash[key].instance_of?(Array) + hash[key] << value + else + hash[key] = [hash[key], value] + end + elsif value.instance_of?(Array) + hash[key] = [value] + else + hash[key] = value + end + hash + end + + # Converts the attributes array of an XML element into a hash. + # Returns an empty Hash if node has no attributes. + # + # element:: + # XML element to extract attributes from. + def get_attributes(element) + attributes = {} + element.attributes.each { |n, v| attributes[n] = v } + attributes + end + + # Determines if a document element has text content + # + # element:: + # XML element to be checked. + def empty_content?(element) + element.texts.join.blank? + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/.github/workflows/ruby.yml b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/.github/workflows/ruby.yml new file mode 100644 index 0000000..54a1561 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/.github/workflows/ruby.yml @@ -0,0 +1,57 @@ +name: Test Suite + +# Run against all commits and pull requests. +on: [ push, pull_request ] + +jobs: + test_matrix: + + strategy: + fail-fast: false + matrix: + os: + - ubuntu + - macos + - windows + ruby: + - 2.1 + - 2.2 + - 2.3 + - 2.4 + - 2.5 + - 2.6 + - 2.7 + - '3.0' + - 3.1 + - head + - jruby + - jruby-head + - truffleruby + - truffleruby-head + - mingw + exclude: + - { os: ubuntu, ruby: jruby } + - { os: ubuntu, ruby: jruby-head } + - { os: ubuntu, ruby: mingw } + - { os: macos, ruby: mingw } + - { os: windows, ruby: truffleruby } + - { os: windows, ruby: truffleruby-head } + + runs-on: ${{ matrix.os }}-latest + + steps: + - uses: actions/checkout@v2 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Run tests + run: bundle exec rake default + + finish: + runs-on: ubuntu-latest + needs: [ test_matrix ] + steps: + - name: Wait for status checks + run: echo "All Green!" diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/.gitignore b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/.gitignore new file mode 100644 index 0000000..633ad7c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/.gitignore @@ -0,0 +1,10 @@ +doc +pkg +tmp +*.o +*.bundle +*.so +*.jar +.DS_Store +.rbenv-gemsets +Gemfile.lock diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/.rspec b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/.rspec new file mode 100644 index 0000000..ff90c03 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/.rspec @@ -0,0 +1,3 @@ +--color +--backtrace +--format documentation diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/CHANGELOG b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/CHANGELOG new file mode 100644 index 0000000..dbc2d82 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/CHANGELOG @@ -0,0 +1,109 @@ +3.1.17 Mar 14 2022 +- Fix regex in validators to use \A and \z instead of ^ and $ [GH #121] +- Truncate secrets greater than 72 bytes in hash_secret [GH #255] +- Assorted test and doc improvements + +3.1.16 Sep 3 2020 + - Fix compilation on FreeBSD. [GH #234] + +3.1.15 July 21 2020 + - Remove GVL optimization. Apparently it breaks things [GH #230] + +3.1.14 July 21 2020 + - Start calibration from the minimum cost supported by the algorithm [GH #206 by @sergey-alekseev] + +3.1.13 May 31 2019 + - No longer include compiled binaries for Windows. See GH #173. + - Update C and Java implementations to latest versions [GH #182 by @fonica] + - Bump default cost to 12 [GH #181 by @bdewater] + - Remove explicit support for Rubies 1.8 and 1.9 + - Define SKIP_GNU token when building extension (Fixes FreeBSD >= 12) [GH #189 by @adam12] + +3.1.12 May 16 2018 + - Add support for Ruby 2.3, 2.4, and 2.5 in compiled Windows binaries + - Fix compatibility with libxcrypt - Fixes hash errors in Fedora 28 and Ubuntu 20 [GH #164 by @besser82] + +3.1.11 Mar 06 2016 + - Add support for Ruby 2.2 in compiled Windows binaries + +3.1.10 Jan 28 2015 + - Fix issue with dumping a BCrypt::Password instance to YAML in Ruby 2.2 [GH #107 by @mattwildig] + +3.1.9 Oct 23 2014 + - Rebuild corrupt binaries + +3.1.8 Oct 23 2014 + - Add support for Ruby 2.1 in compiled Windows binaries [GH #102] + +3.1.7 Feb 24 2014 + - Rebuild corrupt Java binary version of gem [GH #90] + - The 2.1 support for Windows binaries alleged in 3.1.3 was a lie -- documentation removed + +3.1.6 Feb 21 2014 + - Dummy version of "bcrypt-ruby" needed a couple version bumps to fix some + bugs. It felt wrong to have that at a higher version than the real gem, so + the real gem is getting bumped to 3.1.6. + +3.1.3 Feb 21 2014 + - Add support for Ruby 2.1 in compiled Windows binaries + - Rename gem from "bcrypt-ruby" to just "bcrypt". [GH #86 by @sferik] + +3.1.2 Aug 26 2013 + - Add support for Ruby 1.8 and 2.0 (in addition to 1.9) in compiled Windows binaries + - Add support for 64-bit Windows + +3.1.1 Jul 10 2013 + - Remove support for Ruby 1.8 in compiled win32 binaries + +3.1.0 May 07 2013 + - Add BCrypt::Password.valid_hash?(str) to check if a string is a valid bcrypt password hash + - BCrypt::Password cost should be set to DEFAULT_COST if nil + - Add BCrypt::Engine.cost attribute for getting/setting a default cost externally + +3.0.1 Sep 12 2011 + - create raises an exception if the cost is higher than 31. GH #27 + +3.0.0 Aug 24 2011 + - Bcrypt C implementation replaced with a public domain implementation. + - License changed to MIT + +2.1.2 Sep 16 2009 + - Fixed support for Solaris, OpenSolaris. + +2.1.1 Aug 14 2009 + - JVM 1.4/1.5 compatibility [Hongli Lai] + +2.1.0 Aug 12 2009 + - Improved code coverage, unit tests, and build chain. [Hongli Lai] + - Ruby 1.9 compatibility fixes. [Hongli Lai] + - JRuby support, using Damien Miller's jBCrypt. [Hongli Lai] + - Ruby 1.9 GIL releasing for high-cost hashes. [Hongli Lai] + +2.0.5 Mar 11 2009 + - Fixed Ruby 1.8.5 compatibility. [Mike Pomraning] + +2.0.4 Mar 09 2009 + - Added Ruby 1.9 compatibility. [Genki Takiuchi] + - Fixed segfaults on some different types of empty strings. [Mike Pomraning] + +2.0.3 May 07 2008 + - Made exception classes descend from StandardError, not Exception [Dan42] + - Changed BCrypt::Engine.hash to BCrypt::Engine.hash_secret to avoid Merb + sorting issues. [Lee Pope] + +2.0.2 Jun 06 2007 + - Fixed example code in the README [Winson] + - Fixed Solaris compatibility [Jeremy LaTrasse, Twitter crew] + +2.0.1 Mar 09 2007 + - Fixed load path issues + - Fixed crashes when hashing weird values (e.g., false, etc.) + +2.0.0 Mar 07 2007 + - Removed BCrypt::Password#exactly_equals -- use BCrypt::Password#eql? instead. + - Added BCrypt::Password#is_password?. + - Refactored out BCrypt::Internals into more useful BCrypt::Engine. + - Added validation of secrets -- nil is not healthy. + +1.0.0 Feb 27 2007 + - Initial release. diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/COPYING b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/COPYING new file mode 100644 index 0000000..8b4922d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/COPYING @@ -0,0 +1,28 @@ +(The MIT License) + +Copyright 2007-2011: + +* Coda Hale + +C implementation of the BCrypt algorithm by Solar Designer and placed in the +public domain. +jBCrypt is Copyright (c) 2006 Damien Miller . + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/Gemfile b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/Gemfile new file mode 100644 index 0000000..851fabc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/Gemfile @@ -0,0 +1,2 @@ +source 'https://rubygems.org' +gemspec diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/README.md b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/README.md new file mode 100644 index 0000000..23a4775 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/README.md @@ -0,0 +1,193 @@ +# bcrypt-ruby + +An easy way to keep your users' passwords secure. + +* https://github.com/bcrypt-ruby/bcrypt-ruby/tree/master + +[![Github Actions Build Status](https://github.com/bcrypt-ruby/bcrypt-ruby/actions/workflows/ruby.yml/badge.svg?branch=master)](https://github.com/bcrypt-ruby/bcrypt-ruby/actions/workflows/ruby.yml) +[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/6fplerx9lnaf0hyo?svg=true)](https://ci.appveyor.com/project/TJSchuck35975/bcrypt-ruby) + +## Why you should use `bcrypt()` + +If you store user passwords in the clear, then an attacker who steals a copy of your database has a giant list of emails +and passwords. Some of your users will only have one password -- for their email account, for their banking account, for +your application. A simple hack could escalate into massive identity theft. + +It's your responsibility as a web developer to make your web application secure -- blaming your users for not being +security experts is not a professional response to risk. + +`bcrypt()` allows you to easily harden your application against these kinds of attacks. + +*Note*: JRuby versions of the bcrypt gem `<= 2.1.3` had a [security +vulnerability](https://www.mindrot.org/files/jBCrypt/internat.adv) that +was fixed in `>= 2.1.4`. If you used a vulnerable version to hash +passwords with international characters in them, you will need to +re-hash those passwords. This vulnerability only affected the JRuby gem. + +## How to install bcrypt + + gem install bcrypt + +The bcrypt gem is available on the following Ruby platforms: + +* JRuby +* RubyInstaller 2.0 – 3.0 builds on Windows with the DevKit +* Any 2.0 – 3.0 Ruby on a BSD/OS X/Linux system with a compiler + +## How to use `bcrypt()` in your Rails application + +*Note*: Rails versions >= 3 ship with `ActiveModel::SecurePassword` which uses bcrypt-ruby. +`has_secure_password` [docs](https://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html#method-i-has_secure_password) +implements a similar authentication strategy to the code below. + +### The _User_ model +```ruby +require 'bcrypt' + +class User < ActiveRecord::Base + # users.password_hash in the database is a :string + include BCrypt + + def password + @password ||= Password.new(password_hash) + end + + def password=(new_password) + @password = Password.create(new_password) + self.password_hash = @password + end +end +``` +### Creating an account +```ruby +def create + @user = User.new(params[:user]) + @user.password = params[:password] + @user.save! +end +``` +### Authenticating a user +```ruby +def login + @user = User.find_by_email(params[:email]) + if @user.password == params[:password] + give_token + else + redirect_to home_url + end +end +``` +## How to use bcrypt-ruby in general +```ruby +require 'bcrypt' + +my_password = BCrypt::Password.create("my password") +#=> "$2a$12$K0ByB.6YI2/OYrB4fQOYLe6Tv0datUVf6VZ/2Jzwm879BW5K1cHey" + +my_password.version #=> "2a" +my_password.cost #=> 12 +my_password == "my password" #=> true +my_password == "not my password" #=> false + +my_password = BCrypt::Password.new("$2a$12$K0ByB.6YI2/OYrB4fQOYLe6Tv0datUVf6VZ/2Jzwm879BW5K1cHey") +my_password == "my password" #=> true +my_password == "not my password" #=> false +``` +Check the rdocs for more details -- BCrypt, BCrypt::Password. + +## How `bcrypt()` works + +`bcrypt()` is a hashing algorithm designed by Niels Provos and David Mazières of the OpenBSD Project. + +### Background + +Hash algorithms take a chunk of data (e.g., your user's password) and create a "digital fingerprint," or hash, of it. +Because this process is not reversible, there's no way to go from the hash back to the password. + +In other words: + + hash(p) #=> + +You can store the hash and check it against a hash made of a potentially valid password: + + =? hash(just_entered_password) + +### Rainbow Tables + +But even this has weaknesses -- attackers can just run lists of possible passwords through the same algorithm, store the +results in a big database, and then look up the passwords by their hash: + + PrecomputedPassword.find_by_hash().password #=> "secret1" + +### Salts + +The solution to this is to add a small chunk of random data -- called a salt -- to the password before it's hashed: + + hash(salt + p) #=> + +The salt is then stored along with the hash in the database, and used to check potentially valid passwords: + + =? hash(salt + just_entered_password) + +bcrypt-ruby automatically handles the storage and generation of these salts for you. + +Adding a salt means that an attacker has to have a gigantic database for each unique salt -- for a salt made of 4 +letters, that's 456,976 different databases. Pretty much no one has that much storage space, so attackers try a +different, slower method -- throw a list of potential passwords at each individual password: + + hash(salt + "aadvark") =? + hash(salt + "abacus") =? + etc. + +This is much slower than the big database approach, but most hash algorithms are pretty quick -- and therein lies the +problem. Hash algorithms aren't usually designed to be slow, they're designed to turn gigabytes of data into secure +fingerprints as quickly as possible. `bcrypt()`, though, is designed to be computationally expensive: + + Ten thousand iterations: + user system total real + md5 0.070000 0.000000 0.070000 ( 0.070415) + bcrypt 22.230000 0.080000 22.310000 ( 22.493822) + +If an attacker was using Ruby to check each password, they could check ~140,000 passwords a second with MD5 but only +~450 passwords a second with `bcrypt()`. + +### Cost Factors + +In addition, `bcrypt()` allows you to increase the amount of work required to hash a password as computers get faster. Old +passwords will still work fine, but new passwords can keep up with the times. + +The default cost factor used by bcrypt-ruby is 12, which is fine for session-based authentication. If you are using a +stateless authentication architecture (e.g., HTTP Basic Auth), you will want to lower the cost factor to reduce your +server load and keep your request times down. This will lower the security provided you, but there are few alternatives. + +To change the default cost factor used by bcrypt-ruby, use `BCrypt::Engine.cost = new_value`: +```ruby +BCrypt::Password.create('secret').cost + #=> 12, the default provided by bcrypt-ruby + +# set a new default cost +BCrypt::Engine.cost = 8 +BCrypt::Password.create('secret').cost + #=> 8 +``` +The default cost can be overridden as needed by passing an options hash with a different cost: + + BCrypt::Password.create('secret', :cost => 6).cost #=> 6 + +## More Information + +`bcrypt()` is currently used as the default password storage hash in OpenBSD, widely regarded as the most secure operating +system available. + +For a more technical explanation of the algorithm and its design criteria, please read Niels Provos and David Mazières' +Usenix99 paper: +https://www.usenix.org/events/usenix99/provos.html + +If you'd like more down-to-earth advice regarding cryptography, I suggest reading Practical Cryptography by Niels +Ferguson and Bruce Schneier: +https://www.schneier.com/book-practical.html + +# Etc + +* Author :: Coda Hale +* Website :: https://codahale.com diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/Rakefile b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/Rakefile new file mode 100644 index 0000000..a47ce55 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/Rakefile @@ -0,0 +1,72 @@ +require 'rspec/core/rake_task' +require 'rubygems/package_task' +require 'rake/extensiontask' +require 'rake/javaextensiontask' +require 'rake/clean' +require 'rdoc/task' +require 'benchmark' + +CLEAN.include( + "tmp", + "lib/bcrypt_ext.jar", + "lib/bcrypt_ext.so" +) +CLOBBER.include( + "doc", + "pkg" +) + +GEMSPEC = Gem::Specification.load("bcrypt.gemspec") + +task :default => [:compile, :spec] + +desc "Run all specs" +RSpec::Core::RakeTask.new do |t| + t.pattern = 'spec/**/*_spec.rb' + t.ruby_opts = '-w' +end + +desc "Run all specs, with coverage testing" +RSpec::Core::RakeTask.new(:rcov) do |t| + t.pattern = 'spec/**/*_spec.rb' + t.rcov = true + t.rcov_path = 'doc/coverage' + t.rcov_opts = ['--exclude', 'rspec,diff-lcs,rcov,_spec,_helper'] +end + +desc 'Generate RDoc' +RDoc::Task.new do |rdoc| + rdoc.rdoc_dir = 'doc/rdoc' + rdoc.options += GEMSPEC.rdoc_options + rdoc.template = ENV['TEMPLATE'] if ENV['TEMPLATE'] + rdoc.rdoc_files.include(*GEMSPEC.extra_rdoc_files) +end + +Gem::PackageTask.new(GEMSPEC) do |pkg| + pkg.need_zip = true + pkg.need_tar = true +end + +if RUBY_PLATFORM =~ /java/ + Rake::JavaExtensionTask.new('bcrypt_ext', GEMSPEC) do |ext| + ext.ext_dir = 'ext/jruby' + ext.source_version = "1.7" + ext.target_version = "1.7" + end +else + Rake::ExtensionTask.new("bcrypt_ext", GEMSPEC) do |ext| + ext.ext_dir = 'ext/mri' + end +end + +desc "Run a set of benchmarks on the compiled extension." +task :benchmark do + TESTS = 100 + TEST_PWD = "this is a test" + require File.expand_path(File.join(File.dirname(__FILE__), "lib", "bcrypt")) + Benchmark.bmbm do |results| + 4.upto(10) do |n| + results.report("cost #{n}:") { TESTS.times { BCrypt::Password.create(TEST_PWD, :cost => n) } } + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/appveyor.yml b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/appveyor.yml new file mode 100644 index 0000000..e832e22 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/appveyor.yml @@ -0,0 +1,50 @@ +version: "{branch}-{build}" +build: off +clone_depth: 1 + +init: + # Install Ruby head + - if %RUBY_VERSION%==head ( + appveyor DownloadFile https://github.com/oneclick/rubyinstaller2/releases/download/rubyinstaller-head/rubyinstaller-head-x86.exe -FileName C:\head_x86.exe & + C:\head_x86.exe /verysilent /dir=C:\Ruby%RUBY_VERSION% + ) + - if %RUBY_VERSION%==head-x64 ( + appveyor DownloadFile https://github.com/oneclick/rubyinstaller2/releases/download/rubyinstaller-head/rubyinstaller-head-x64.exe -FileName C:\head_x64.exe & + C:\head_x64.exe /verysilent /dir=C:\Ruby%RUBY_VERSION% + ) + + # Add Ruby to the path + - set PATH=C:\Ruby%RUBY_VERSION%\bin;%PATH% + +environment: + matrix: + - RUBY_VERSION: "head" + - RUBY_VERSION: "head-x64" + - RUBY_VERSION: "25" + - RUBY_VERSION: "25-x64" + - RUBY_VERSION: "24" + - RUBY_VERSION: "24-x64" + - RUBY_VERSION: "23" + - RUBY_VERSION: "23-x64" + - RUBY_VERSION: "22" + - RUBY_VERSION: "22-x64" + - RUBY_VERSION: "21" + - RUBY_VERSION: "21-x64" + - RUBY_VERSION: "200" + - RUBY_VERSION: "200-x64" + +install: + - ps: "Set-Content -Value 'gem: --no-ri --no-rdoc ' -Path C:\\ProgramData\\gemrc" + - if %RUBY_VERSION%==head ( gem install bundler -v'< 2' ) + - if %RUBY_VERSION%==head-x64 ( gem install bundler -v'< 2' ) + - bundle install + +before_build: + - ruby -v + - gem -v + +build_script: + - bundle exec rake compile -rdevkit + +test_script: + - bundle exec rake spec diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/bcrypt.gemspec b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/bcrypt.gemspec new file mode 100644 index 0000000..5971af1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/bcrypt.gemspec @@ -0,0 +1,27 @@ +Gem::Specification.new do |s| + s.name = 'bcrypt' + s.version = '3.1.17' + + s.summary = "OpenBSD's bcrypt() password hashing algorithm." + s.description = <<-EOF + bcrypt() is a sophisticated and secure hash algorithm designed by The OpenBSD project + for hashing passwords. The bcrypt Ruby gem provides a simple wrapper for safely handling + passwords. + EOF + + s.files = `git ls-files`.split("\n") + s.require_path = 'lib' + + s.add_development_dependency 'rake-compiler', '~> 0.9.2' + s.add_development_dependency 'rspec', '>= 3' + + s.rdoc_options += ['--title', 'bcrypt-ruby', '--line-numbers', '--inline-source', '--main', 'README.md'] + s.extra_rdoc_files += ['README.md', 'COPYING', 'CHANGELOG', *Dir['lib/**/*.rb']] + + s.extensions = 'ext/mri/extconf.rb' + + s.authors = ["Coda Hale"] + s.email = "coda.hale@gmail.com" + s.homepage = "https://github.com/bcrypt-ruby/bcrypt-ruby" + s.license = "MIT" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/jruby/bcrypt_jruby/BCrypt.java b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/jruby/bcrypt_jruby/BCrypt.java new file mode 100644 index 0000000..86db91b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/jruby/bcrypt_jruby/BCrypt.java @@ -0,0 +1,925 @@ +// Copyright (c) 2006 Damien Miller +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +package bcrypt_jruby; + +import java.io.UnsupportedEncodingException; +import java.util.Arrays; +import java.security.SecureRandom; + +/** + * BCrypt implements OpenBSD-style Blowfish password hashing using + * the scheme described in "A Future-Adaptable Password Scheme" by + * Niels Provos and David Mazieres. + *

+ * This password hashing system tries to thwart off-line password + * cracking using a computationally-intensive hashing algorithm, + * based on Bruce Schneier's Blowfish cipher. The work factor of + * the algorithm is parameterised, so it can be increased as + * computers get faster. + *

+ * Usage is really simple. To hash a password for the first time, + * call the hashpw method with a random salt, like this: + *

+ * + * String pw_hash = BCrypt.hashpw(plain_password, BCrypt.gensalt());
+ *
+ *

+ * To check whether a plaintext password matches one that has been + * hashed previously, use the checkpw method: + *

+ * + * if (BCrypt.checkpw(candidate_password, stored_hash))
+ *     System.out.println("It matches");
+ * else
+ *     System.out.println("It does not match");
+ *
+ *

+ * The gensalt() method takes an optional parameter (log_rounds) + * that determines the computational complexity of the hashing: + *

+ * + * String strong_salt = BCrypt.gensalt(10)
+ * String stronger_salt = BCrypt.gensalt(12)
+ *
+ *

+ * The amount of work increases exponentially (2**log_rounds), so + * each increment is twice as much work. The default log_rounds is + * 10, and the valid range is 4 to 31. + * + * @author Damien Miller + * @version 0.3 + */ +public class BCrypt { + // BCrypt parameters + private static final int GENSALT_DEFAULT_LOG2_ROUNDS = 10; + private static final int BCRYPT_SALT_LEN = 16; + + // Blowfish parameters + private static final int BLOWFISH_NUM_ROUNDS = 16; + + // Initial contents of key schedule + private static final int P_orig[] = { + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b + }; + private static final int S_orig[] = { + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + }; + + // bcrypt IV: "OrpheanBeholderScryDoubt" + static private final int bf_crypt_ciphertext[] = { + 0x4f727068, 0x65616e42, 0x65686f6c, + 0x64657253, 0x63727944, 0x6f756274 + }; + + // Table for Base64 encoding + static private final char base64_code[] = { + '.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', + 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', + 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', + 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9' + }; + + // Table for Base64 decoding + static private final byte index_64[] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, + -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, + 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, + -1, -1, -1, -1, -1, -1, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, + 51, 52, 53, -1, -1, -1, -1, -1 + }; + static final int MIN_LOG_ROUNDS = 4; + static final int MAX_LOG_ROUNDS = 31; + + // Expanded Blowfish key + private int P[]; + private int S[]; + + /** + * Encode a byte array using bcrypt's slightly-modified base64 encoding scheme. Note + * that this is not compatible with the standard MIME-base64 + * encoding. + * + * @param d the byte array to encode + * @param len the number of bytes to encode + * @param rs the destination buffer for the base64-encoded string + * @exception IllegalArgumentException if the length is invalid + */ + static void encode_base64(byte d[], int len, StringBuilder rs) + throws IllegalArgumentException { + int off = 0; + int c1, c2; + + if (len <= 0 || len > d.length) { + throw new IllegalArgumentException("Invalid len"); + } + + while (off < len) { + c1 = d[off++] & 0xff; + rs.append(base64_code[(c1 >> 2) & 0x3f]); + c1 = (c1 & 0x03) << 4; + if (off >= len) { + rs.append(base64_code[c1 & 0x3f]); + break; + } + c2 = d[off++] & 0xff; + c1 |= (c2 >> 4) & 0x0f; + rs.append(base64_code[c1 & 0x3f]); + c1 = (c2 & 0x0f) << 2; + if (off >= len) { + rs.append(base64_code[c1 & 0x3f]); + break; + } + c2 = d[off++] & 0xff; + c1 |= (c2 >> 6) & 0x03; + rs.append(base64_code[c1 & 0x3f]); + rs.append(base64_code[c2 & 0x3f]); + } + } + + /** + * Look up the 3 bits base64-encoded by the specified character, + * range-checking againt conversion table + * @param x the base64-encoded value + * @return the decoded value of x + */ + private static byte char64(char x) { + if ((int) x < 0 || (int) x >= index_64.length) + return -1; + return index_64[(int) x]; + } + + /** + * Decode a string encoded using bcrypt's base64 scheme to a + * byte array. Note that this is *not* compatible with + * the standard MIME-base64 encoding. + * @param s the string to decode + * @param maxolen the maximum number of bytes to decode + * @return an array containing the decoded bytes + * @throws IllegalArgumentException if maxolen is invalid + */ + static byte[] decode_base64(String s, int maxolen) + throws IllegalArgumentException { + StringBuilder rs = new StringBuilder(); + int off = 0, slen = s.length(), olen = 0; + byte ret[]; + byte c1, c2, c3, c4, o; + + if (maxolen <= 0) + throw new IllegalArgumentException ("Invalid maxolen"); + + while (off < slen - 1 && olen < maxolen) { + c1 = char64(s.charAt(off++)); + c2 = char64(s.charAt(off++)); + if (c1 == -1 || c2 == -1) + break; + o = (byte) (c1 << 2); + o |= (c2 & 0x30) >> 4; + rs.append((char) o); + if (++olen >= maxolen || off >= slen) + break; + c3 = char64(s.charAt(off++)); + if (c3 == -1) + break; + o = (byte) ((c2 & 0x0f) << 4); + o |= (c3 & 0x3c) >> 2; + rs.append((char) o); + if (++olen >= maxolen || off >= slen) + break; + c4 = char64(s.charAt(off++)); + o = (byte) ((c3 & 0x03) << 6); + o |= c4; + rs.append((char) o); + ++olen; + } + + ret = new byte[olen]; + for (off = 0; off < olen; off++) + ret[off] = (byte) rs.charAt(off); + return ret; + } + + /** + * Blowfish encipher a single 64-bit block encoded as + * two 32-bit halves + * @param lr an array containing the two 32-bit half blocks + * @param off the position in the array of the blocks + */ + private final void encipher(int lr[], int off) { + int i, n, l = lr[off], r = lr[off + 1]; + + l ^= P[0]; + for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2;) { + // Feistel substitution on left word + n = S[(l >> 24) & 0xff]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[++i]; + + // Feistel substitution on right word + n = S[(r >> 24) & 0xff]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[++i]; + } + lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1]; + lr[off + 1] = l; + } + + /** + * Cycically extract a word of key material + * @param data the string to extract the data from + * @param offp a "pointer" (as a one-entry array) to the + * current offset into data + * @param signp a "pointer" (as a one-entry array) to the + * cumulative flag for non-benign sign extension + * @return correct and buggy next word of material from data as int[2] + */ + private static int[] streamtowords(byte data[], int offp[], int signp[]) { + int i; + int words[] = { 0, 0 }; + int off = offp[0]; + int sign = signp[0]; + + for (i = 0; i < 4; i++) { + words[0] = (words[0] << 8) | (data[off] & 0xff); + words[1] = (words[1] << 8) | (int) data[off]; // sign extension bug + if (i > 0) sign |= words[1] & 0x80; + off = (off + 1) % data.length; + } + + offp[0] = off; + signp[0] = sign; + return words; + } + + /** + * Cycically extract a word of key material + * @param data the string to extract the data from + * @param offp a "pointer" (as a one-entry array) to the + * current offset into data + * @return the next word of material from data + */ + private static int streamtoword(byte data[], int offp[]) { + int signp[] = { 0 }; + return streamtowords(data, offp, signp)[0]; + } + + /** + * Cycically extract a word of key material, with sign-extension bug + * @param data the string to extract the data from + * @param offp a "pointer" (as a one-entry array) to the + * current offset into data + * @return the next word of material from data + */ + private static int streamtoword_bug(byte data[], int offp[]) { + int signp[] = { 0 }; + return streamtowords(data, offp, signp)[1]; + } + + /** + * Initialise the Blowfish key schedule + */ + private void init_key() { + P = P_orig.clone(); + S = S_orig.clone(); + } + + /** + * Key the Blowfish cipher + * @param key an array containing the key + * @param sign_ext_bug true to implement the 2x bug + * @param safety bit 16 is set when the safety measure is requested + */ + private void key(byte key[], boolean sign_ext_bug, int safety) { + int i; + int koffp[] = { 0 }; + int lr[] = { 0, 0 }; + int plen = P.length, slen = S.length; + + for (i = 0; i < plen; i++) + if (!sign_ext_bug) + P[i] = P[i] ^ streamtoword(key, koffp); + else + P[i] = P[i] ^ streamtoword_bug(key, koffp); + + for (i = 0; i < plen; i += 2) { + encipher(lr, 0); + P[i] = lr[0]; + P[i + 1] = lr[1]; + } + + for (i = 0; i < slen; i += 2) { + encipher(lr, 0); + S[i] = lr[0]; + S[i + 1] = lr[1]; + } + } + + /** + * Perform the "enhanced key schedule" step described by + * Provos and Mazieres in "A Future-Adaptable Password Scheme" + * http://www.openbsd.org/papers/bcrypt-paper.ps + * @param data salt information + * @param key password information + * @param sign_ext_bug true to implement the 2x bug + * @param safety bit 16 is set when the safety measure is requested + */ + private void ekskey(byte data[], byte key[], + boolean sign_ext_bug, int safety) { + int i; + int koffp[] = { 0 }, doffp[] = { 0 }; + int lr[] = { 0, 0 }; + int plen = P.length, slen = S.length; + int signp[] = { 0 }; // non-benign sign-extension flag + int diff = 0; // zero iff correct and buggy are same + + for (i = 0; i < plen; i++) { + int words[] = streamtowords(key, koffp, signp); + diff |= words[0] ^ words[1]; + P[i] = P[i] ^ words[sign_ext_bug ? 1 : 0]; + } + + int sign = signp[0]; + + /* + * At this point, "diff" is zero iff the correct and buggy algorithms produced + * exactly the same result. If so and if "sign" is non-zero, which indicates + * that there was a non-benign sign extension, this means that we have a + * collision between the correctly computed hash for this password and a set of + * passwords that could be supplied to the buggy algorithm. Our safety measure + * is meant to protect from such many-buggy to one-correct collisions, by + * deviating from the correct algorithm in such cases. Let's check for this. + */ + diff |= diff >> 16; /* still zero iff exact match */ + diff &= 0xffff; /* ditto */ + diff += 0xffff; /* bit 16 set iff "diff" was non-zero (on non-match) */ + sign <<= 9; /* move the non-benign sign extension flag to bit 16 */ + sign &= ~diff & safety; /* action needed? */ + + /* + * If we have determined that we need to deviate from the correct algorithm, + * flip bit 16 in initial expanded key. (The choice of 16 is arbitrary, but + * let's stick to it now. It came out of the approach we used above, and it's + * not any worse than any other choice we could make.) + * + * It is crucial that we don't do the same to the expanded key used in the main + * Eksblowfish loop. By doing it to only one of these two, we deviate from a + * state that could be directly specified by a password to the buggy algorithm + * (and to the fully correct one as well, but that's a side-effect). + */ + P[0] ^= sign; + + for (i = 0; i < plen; i += 2) { + lr[0] ^= streamtoword(data, doffp); + lr[1] ^= streamtoword(data, doffp); + encipher(lr, 0); + P[i] = lr[0]; + P[i + 1] = lr[1]; + } + + for (i = 0; i < slen; i += 2) { + lr[0] ^= streamtoword(data, doffp); + lr[1] ^= streamtoword(data, doffp); + encipher(lr, 0); + S[i] = lr[0]; + S[i + 1] = lr[1]; + } + } + + static long roundsForLogRounds(int log_rounds) { + if (log_rounds < 4 || log_rounds > 31) { + throw new IllegalArgumentException("Bad number of rounds"); + } + return 1L << log_rounds; + } + + /** + * Perform the central password hashing step in the + * bcrypt scheme + * @param password the password to hash + * @param salt the binary salt to hash with the password + * @param log_rounds the binary logarithm of the number + * of rounds of hashing to apply + * @param sign_ext_bug true to implement the 2x bug + * @param safety bit 16 is set when the safety measure is requested + * @return an array containing the binary hashed password + */ + private byte[] crypt_raw(byte password[], byte salt[], int log_rounds, + boolean sign_ext_bug, int safety) { + int rounds, i, j; + int cdata[] = bf_crypt_ciphertext.clone(); + int clen = cdata.length; + byte ret[]; + + if (log_rounds < 4 || log_rounds > 31) + throw new IllegalArgumentException ("Bad number of rounds"); + rounds = 1 << log_rounds; + if (salt.length != BCRYPT_SALT_LEN) + throw new IllegalArgumentException ("Bad salt length"); + + init_key(); + ekskey(salt, password, sign_ext_bug, safety); + for (i = 0; i < rounds; i++) { + key(password, sign_ext_bug, safety); + key(salt, false, safety); + } + + for (i = 0; i < 64; i++) { + for (j = 0; j < (clen >> 1); j++) + encipher(cdata, j << 1); + } + + ret = new byte[clen * 4]; + for (i = 0, j = 0; i < clen; i++) { + ret[j++] = (byte) ((cdata[i] >> 24) & 0xff); + ret[j++] = (byte) ((cdata[i] >> 16) & 0xff); + ret[j++] = (byte) ((cdata[i] >> 8) & 0xff); + ret[j++] = (byte) (cdata[i] & 0xff); + } + return ret; + } + + /** + * Hash a password using the OpenBSD bcrypt scheme + * @param password the password to hash + * @param salt the salt to hash with (perhaps generated + * using BCrypt.gensalt) + * @return the hashed password + */ + public static String hashpw(String password, String salt) { + byte passwordb[]; + + try { + passwordb = password.getBytes("UTF-8"); + } catch (UnsupportedEncodingException uee) { + throw new AssertionError("UTF-8 is not supported"); + } + + return hashpw(passwordb, salt); + } + + /** + * Hash a password using the OpenBSD bcrypt scheme + * @param passwordb the password to hash, as a byte array + * @param salt the salt to hash with (perhaps generated + * using BCrypt.gensalt) + * @return the hashed password + */ + public static String hashpw(byte passwordb[], String salt) { + BCrypt B; + String real_salt; + byte saltb[], hashed[]; + char minor = (char) 0; + int rounds, off; + StringBuilder rs = new StringBuilder(); + + if (salt == null) { + throw new IllegalArgumentException("salt cannot be null"); + } + + int saltLength = salt.length(); + + if (saltLength < 28) { + throw new IllegalArgumentException("Invalid salt"); + } + + if (salt.charAt(0) != '$' || salt.charAt(1) != '2') + throw new IllegalArgumentException ("Invalid salt version"); + if (salt.charAt(2) == '$') + off = 3; + else { + minor = salt.charAt(2); + if ((minor != 'a' && minor != 'x' && minor != 'y' && minor != 'b') + || salt.charAt(3) != '$') + throw new IllegalArgumentException ("Invalid salt revision"); + off = 4; + } + + // Extract number of rounds + if (salt.charAt(off + 2) > '$') + throw new IllegalArgumentException ("Missing salt rounds"); + rounds = Integer.parseInt(salt.substring(off, off + 2)); + + real_salt = salt.substring(off + 3, off + 25); + saltb = decode_base64(real_salt, BCRYPT_SALT_LEN); + + if (minor >= 'a') // add null terminator + passwordb = Arrays.copyOf(passwordb, passwordb.length + 1); + + B = new BCrypt(); + hashed = B.crypt_raw(passwordb, saltb, rounds, minor == 'x', minor == 'a' ? 0x10000 : 0); + + rs.append("$2"); + if (minor >= 'a') + rs.append(minor); + rs.append("$"); + if (rounds < 10) + rs.append("0"); + rs.append(rounds); + rs.append("$"); + encode_base64(saltb, saltb.length, rs); + encode_base64(hashed, bf_crypt_ciphertext.length * 4 - 1, rs); + return rs.toString(); + } + + /** + * Generate a salt for use with the BCrypt.hashpw() method + * @param prefix the prefix value (default $2a) + * @param log_rounds the log2 of the number of rounds of + * hashing to apply - the work factor therefore increases as + * 2**log_rounds. + * @param random an instance of SecureRandom to use + * @return an encoded salt value + * @exception IllegalArgumentException if prefix or log_rounds is invalid + */ + public static String gensalt(String prefix, int log_rounds, SecureRandom random) + throws IllegalArgumentException { + StringBuilder rs = new StringBuilder(); + byte rnd[] = new byte[BCRYPT_SALT_LEN]; + + if (!prefix.startsWith("$2") || + (prefix.charAt(2) != 'a' && prefix.charAt(2) != 'y' && + prefix.charAt(2) != 'b')) { + throw new IllegalArgumentException ("Invalid prefix"); + } + if (log_rounds < 4 || log_rounds > 31) { + throw new IllegalArgumentException ("Invalid log_rounds"); + } + + random.nextBytes(rnd); + + rs.append("$2"); + rs.append(prefix.charAt(2)); + rs.append("$"); + if (log_rounds < 10) + rs.append("0"); + rs.append(log_rounds); + rs.append("$"); + encode_base64(rnd, rnd.length, rs); + return rs.toString(); + } + + /** + * Generate a salt for use with the BCrypt.hashpw() method + * @param prefix the prefix value (default $2a) + * @param log_rounds the log2 of the number of rounds of + * hashing to apply - the work factor therefore increases as + * 2**log_rounds. + * @return an encoded salt value + * @exception IllegalArgumentException if prefix or log_rounds is invalid + */ + public static String gensalt(String prefix, int log_rounds) + throws IllegalArgumentException { + return gensalt(prefix, log_rounds, new SecureRandom()); + } + + /** + * Generate a salt for use with the BCrypt.hashpw() method + * @param log_rounds the log2 of the number of rounds of + * hashing to apply - the work factor therefore increases as + * 2**log_rounds. + * @param random an instance of SecureRandom to use + * @return an encoded salt value + * @exception IllegalArgumentException if log_rounds is invalid + */ + public static String gensalt(int log_rounds, SecureRandom random) + throws IllegalArgumentException { + return gensalt("$2a", log_rounds, random); + } + + /** + * Generate a salt for use with the BCrypt.hashpw() method + * @param log_rounds the log2 of the number of rounds of + * hashing to apply - the work factor therefore increases as + * 2**log_rounds. + * @return an encoded salt value + * @exception IllegalArgumentException if log_rounds is invalid + */ + public static String gensalt(int log_rounds) + throws IllegalArgumentException { + return gensalt(log_rounds, new SecureRandom()); + } + + public static String gensalt(String prefix) { + return gensalt(prefix, GENSALT_DEFAULT_LOG2_ROUNDS); + } + + /** + * Generate a salt for use with the BCrypt.hashpw() method, + * selecting a reasonable default for the number of hashing + * rounds to apply + * @return an encoded salt value + */ + public static String gensalt() { + return gensalt(GENSALT_DEFAULT_LOG2_ROUNDS); + } + + /** + * Check that a plaintext password matches a previously hashed + * one + * @param plaintext the plaintext password to verify + * @param hashed the previously-hashed password + * @return true if the passwords match, false otherwise + */ + public static boolean checkpw(String plaintext, String hashed) { + return equalsNoEarlyReturn(hashed, hashpw(plaintext, hashed)); + } + + static boolean equalsNoEarlyReturn(String a, String b) { + char[] caa = a.toCharArray(); + char[] cab = b.toCharArray(); + + if (caa.length != cab.length) { + return false; + } + + byte ret = 0; + for (int i = 0; i < caa.length; i++) { + ret |= caa[i] ^ cab[i]; + } + return ret == 0; + } +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/.sitearchdir.time b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/.sitearchdir.time new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/Makefile b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/Makefile new file mode 100644 index 0000000..515a26f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/Makefile @@ -0,0 +1,266 @@ + +SHELL = /bin/sh + +# V=0 quiet, V=1 verbose. other values don't work. +V = 0 +Q1 = $(V:1=) +Q = $(Q1:0=@) +ECHO1 = $(V:1=@ :) +ECHO = $(ECHO1:0=@ echo) +NULLCMD = : + +#### Start of system configuration section. #### + +srcdir = . +topdir = /usr/include/ruby-3.0.0 +hdrdir = $(topdir) +arch_hdrdir = /usr/include/ruby-3.0.0/x86_64-linux +PATH_SEPARATOR = : +VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby +prefix = $(DESTDIR)/usr +rubysitearchprefix = $(rubylibprefix)/$(sitearch) +rubyarchprefix = $(rubylibprefix)/$(arch) +rubylibprefix = $(libdir)/$(RUBY_BASE_NAME) +exec_prefix = $(prefix) +vendorarchhdrdir = $(vendorhdrdir)/$(sitearch) +sitearchhdrdir = $(sitehdrdir)/$(sitearch) +rubyarchhdrdir = $(rubyhdrdir)/$(arch) +vendorhdrdir = $(rubyhdrdir)/vendor_ruby +sitehdrdir = $(rubyhdrdir)/site_ruby +rubyhdrdir = $(includedir)/$(RUBY_VERSION_NAME) +vendorarchdir = $(vendorlibdir)/$(sitearch) +vendorlibdir = $(vendordir)/$(ruby_version) +vendordir = $(rubylibprefix)/vendor_ruby +sitearchdir = $(DESTDIR)./.gem.20220424-672384-aslyfc +sitelibdir = $(DESTDIR)./.gem.20220424-672384-aslyfc +sitedir = $(rubylibprefix)/site_ruby +rubyarchdir = $(rubylibdir)/$(arch) +rubylibdir = $(rubylibprefix)/$(ruby_version) +sitearchincludedir = $(includedir)/$(sitearch) +archincludedir = $(includedir)/$(arch) +sitearchlibdir = $(libdir)/$(sitearch) +archlibdir = $(libdir)/$(arch) +ridir = $(datarootdir)/$(RI_BASE_NAME) +mandir = $(datarootdir)/man +localedir = $(datarootdir)/locale +libdir = $(exec_prefix)/lib +psdir = $(docdir) +pdfdir = $(docdir) +dvidir = $(docdir) +htmldir = $(docdir) +infodir = $(datarootdir)/info +docdir = $(datarootdir)/doc/$(PACKAGE) +oldincludedir = $(DESTDIR)/usr/include +includedir = $(prefix)/include +runstatedir = $(localstatedir)/run +localstatedir = $(DESTDIR)/var +sharedstatedir = $(DESTDIR)/var/lib +sysconfdir = $(DESTDIR)/etc +datadir = $(datarootdir) +datarootdir = $(prefix)/share +libexecdir = $(DESTDIR)/usr/lib/ruby +sbindir = $(exec_prefix)/sbin +bindir = $(exec_prefix)/bin +archdir = $(rubyarchdir) + + +CC_WRAPPER = +CC = gcc +CXX = g++ +LIBRUBY = $(LIBRUBY_SO) +LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a +LIBRUBYARG_SHARED = -l$(RUBY_SO_NAME) +LIBRUBYARG_STATIC = -l$(RUBY_SO_NAME)-static $(MAINLIBS) +empty = +OUTFLAG = -o $(empty) +COUTFLAG = -o $(empty) +CSRCFLAG = $(empty) + +RUBY_EXTCONF_H = +cflags = $(optflags) $(debugflags) $(warnflags) +cxxflags = +optflags = -O3 +debugflags = -ggdb3 +warnflags = -Wall -Wextra -Wdeprecated-declarations -Wduplicated-cond -Wimplicit-function-declaration -Wimplicit-int -Wmisleading-indentation -Wpointer-arith -Wwrite-strings -Wimplicit-fallthrough=0 -Wmissing-noreturn -Wno-cast-function-type -Wno-constant-logical-operand -Wno-long-long -Wno-missing-field-initializers -Wno-overlength-strings -Wno-packed-bitfield-compat -Wno-parentheses-equality -Wno-self-assign -Wno-tautological-compare -Wno-unused-parameter -Wno-unused-value -Wsuggest-attribute=format -Wsuggest-attribute=noreturn -Wunused-variable +cppflags = +CCDLFLAGS = -fPIC +CFLAGS = $(CCDLFLAGS) -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC $(ARCH_FLAG) +INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir) +DEFS = +CPPFLAGS = -D__SKIP_GNU $(DEFS) $(cppflags) +CXXFLAGS = $(CCDLFLAGS) -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -Wp,-D_GLIBCXX_ASSERTIONS $(ARCH_FLAG) +ldflags = -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed +dldflags = -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -Wl,--compress-debug-sections=zlib +ARCH_FLAG = +DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG) +LDSHARED = $(CC) -shared +LDSHAREDXX = $(CXX) -shared +AR = gcc-ar +EXEEXT = + +RUBY_INSTALL_NAME = $(RUBY_BASE_NAME) +RUBY_SO_NAME = ruby +RUBYW_INSTALL_NAME = +RUBY_VERSION_NAME = $(RUBY_BASE_NAME)-$(ruby_version) +RUBYW_BASE_NAME = rubyw +RUBY_BASE_NAME = ruby + +arch = x86_64-linux +sitearch = $(arch) +ruby_version = 3.0.0 +ruby = $(bindir)/$(RUBY_BASE_NAME) +RUBY = $(ruby) +ruby_headers = $(hdrdir)/ruby.h $(hdrdir)/ruby/backward.h $(hdrdir)/ruby/ruby.h $(hdrdir)/ruby/defines.h $(hdrdir)/ruby/missing.h $(hdrdir)/ruby/intern.h $(hdrdir)/ruby/st.h $(hdrdir)/ruby/subst.h $(arch_hdrdir)/ruby/config.h + +RM = rm -f +RM_RF = $(RUBY) -run -e rm -- -rf +RMDIRS = rmdir --ignore-fail-on-non-empty -p +MAKEDIRS = /usr/bin/mkdir -p +INSTALL = /usr/bin/install -c +INSTALL_PROG = $(INSTALL) -m 0755 +INSTALL_DATA = $(INSTALL) -m 644 +COPY = cp +TOUCH = exit > + +#### End of system configuration section. #### + +preload = +libpath = . $(libdir) +LIBPATH = -L. -L$(libdir) +DEFFILE = + +CLEANFILES = mkmf.log +DISTCLEANFILES = +DISTCLEANDIRS = + +extout = +extout_prefix = +target_prefix = +LOCAL_LIBS = +LIBS = $(LIBRUBYARG_SHARED) -lm -lc +ORIG_SRCS = bcrypt_ext.c crypt.c crypt_blowfish.c crypt_gensalt.c wrapper.c +SRCS = $(ORIG_SRCS) bcrypt_ext.c crypt_blowfish.c x86.c crypt_gensalt.c wrapper.c +OBJS = bcrypt_ext.o crypt_blowfish.o x86.o crypt_gensalt.o wrapper.o +HDRS = $(srcdir)/crypt.h $(srcdir)/crypt_blowfish.h $(srcdir)/crypt_gensalt.h $(srcdir)/ow-crypt.h +LOCAL_HDRS = +TARGET = bcrypt_ext +TARGET_NAME = bcrypt_ext +TARGET_ENTRY = Init_$(TARGET_NAME) +DLLIB = $(TARGET).so +EXTSTATIC = +STATIC_LIB = + +TIMESTAMP_DIR = . +BINDIR = $(bindir) +RUBYCOMMONDIR = $(sitedir)$(target_prefix) +RUBYLIBDIR = $(sitelibdir)$(target_prefix) +RUBYARCHDIR = $(sitearchdir)$(target_prefix) +HDRDIR = $(sitehdrdir)$(target_prefix) +ARCHHDRDIR = $(sitearchhdrdir)$(target_prefix) +TARGET_SO_DIR = +TARGET_SO = $(TARGET_SO_DIR)$(DLLIB) +CLEANLIBS = $(TARGET_SO) +CLEANOBJS = *.o *.bak + +all: $(DLLIB) +static: $(STATIC_LIB) +.PHONY: all install static install-so install-rb +.PHONY: clean clean-so clean-static clean-rb + +clean-static:: +clean-rb-default:: +clean-rb:: +clean-so:: +clean: clean-so clean-static clean-rb-default clean-rb + -$(Q)$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES) .*.time + +distclean-rb-default:: +distclean-rb:: +distclean-so:: +distclean-static:: +distclean: clean distclean-so distclean-static distclean-rb-default distclean-rb + -$(Q)$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log + -$(Q)$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES) + -$(Q)$(RMDIRS) $(DISTCLEANDIRS) 2> /dev/null || true + +realclean: distclean +install: install-so install-rb + +install-so: $(DLLIB) $(TIMESTAMP_DIR)/.sitearchdir.time + $(INSTALL_PROG) $(DLLIB) $(RUBYARCHDIR) +clean-static:: + -$(Q)$(RM) $(STATIC_LIB) +install-rb: pre-install-rb do-install-rb install-rb-default +install-rb-default: pre-install-rb-default do-install-rb-default +pre-install-rb: Makefile +pre-install-rb-default: Makefile +do-install-rb: +do-install-rb-default: +pre-install-rb-default: + @$(NULLCMD) +$(TIMESTAMP_DIR)/.sitearchdir.time: + $(Q) $(MAKEDIRS) $(@D) $(RUBYARCHDIR) + $(Q) $(TOUCH) $@ + +site-install: site-install-so site-install-rb +site-install-so: install-so +site-install-rb: install-rb + +.SUFFIXES: .c .m .cc .mm .cxx .cpp .o .S + +.cc.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cc.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.mm.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.mm.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.cxx.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cxx.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.cpp.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cpp.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.c.o: + $(ECHO) compiling $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.c.S: + $(ECHO) translating $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.m.o: + $(ECHO) compiling $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.m.S: + $(ECHO) translating $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +$(TARGET_SO): $(OBJS) Makefile + $(ECHO) linking shared-object $(DLLIB) + -$(Q)$(RM) $(@) + $(Q) $(LDSHARED) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS) + + + +$(OBJS): $(HDRS) $(ruby_headers) diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/bcrypt_ext.c b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/bcrypt_ext.c new file mode 100644 index 0000000..c8db933 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/bcrypt_ext.c @@ -0,0 +1,64 @@ +#include +#include + +static VALUE mBCrypt; +static VALUE cBCryptEngine; + +/* Given a logarithmic cost parameter, generates a salt for use with +bc_crypt+. +*/ +static VALUE bc_salt(VALUE self, VALUE prefix, VALUE count, VALUE input) { + char * salt; + VALUE str_salt; + + salt = crypt_gensalt_ra( + StringValuePtr(prefix), + NUM2ULONG(count), + NIL_P(input) ? NULL : StringValuePtr(input), + NIL_P(input) ? 0 : RSTRING_LEN(input)); + + if(!salt) return Qnil; + + str_salt = rb_str_new2(salt); + free(salt); + + return str_salt; +} + +/* Given a secret and a salt, generates a salted hash (which you can then store safely). +*/ +static VALUE bc_crypt(VALUE self, VALUE key, VALUE setting) { + char * value; + void * data; + int size; + VALUE out; + + data = NULL; + size = 0xDEADBEEF; + + if(NIL_P(key) || NIL_P(setting)) return Qnil; + + value = crypt_ra( + NIL_P(key) ? NULL : StringValuePtr(key), + NIL_P(setting) ? NULL : StringValuePtr(setting), + &data, + &size); + + if(!value || !data) return Qnil; + + out = rb_str_new2(value); + + xfree(data); + + return out; +} + +/* Create the BCrypt and BCrypt::Engine modules, and populate them with methods. */ +void Init_bcrypt_ext(){ + mBCrypt = rb_define_module("BCrypt"); + cBCryptEngine = rb_define_class_under(mBCrypt, "Engine", rb_cObject); + + rb_define_singleton_method(cBCryptEngine, "__bc_salt", bc_salt, 3); + rb_define_singleton_method(cBCryptEngine, "__bc_crypt", bc_crypt, 2); +} + +/* vim: set noet sws=4 sw=4: */ diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt.c b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt.c new file mode 100644 index 0000000..522b495 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt.c @@ -0,0 +1,57 @@ +#include +#include + +VALUE mCrypt; + +static VALUE crypt_salt(VALUE self, VALUE prefix, VALUE count, VALUE input) +{ + char * salt; + VALUE str_salt; + + salt = crypt_gensalt_ra( + StringValuePtr(prefix), + NUM2ULONG(count), + NIL_P(input) ? NULL : StringValuePtr(input), + NIL_P(input) ? 0 : RSTRING_LEN(input)); + + if(!salt) return Qnil; + + str_salt = rb_str_new2(salt); + free(salt); + + return str_salt; +} + +static VALUE ra(VALUE self, VALUE key, VALUE setting) +{ + char * value; + void * data; + int size; + VALUE out; + + data = NULL; + size = 0xDEADBEEF; + + if(NIL_P(key) || NIL_P(setting)) return Qnil; + + value = crypt_ra( + NIL_P(key) ? NULL : StringValuePtr(key), + NIL_P(setting) ? NULL : StringValuePtr(setting), + &data, + &size); + + if(!value) return Qnil; + + out = rb_str_new(data, size - 1); + + free(data); + + return out; +} + +void Init_crypt() +{ + mCrypt = rb_define_module("Crypt"); + rb_define_singleton_method(mCrypt, "salt", crypt_salt, 3); + rb_define_singleton_method(mCrypt, "crypt", ra, 2); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt.h b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt.h new file mode 100644 index 0000000..12e6705 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt.h @@ -0,0 +1,24 @@ +/* + * Written by Solar Designer in 2000-2002. + * No copyright is claimed, and the software is hereby placed in the public + * domain. In case this attempt to disclaim copyright and place the software + * in the public domain is deemed null and void, then the software is + * Copyright (c) 2000-2002 Solar Designer and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * See crypt_blowfish.c for more information. + */ + +#include + +#if defined(_OW_SOURCE) || defined(__USE_OW) +#define __SKIP_GNU +#undef __SKIP_OW +#include +#undef __SKIP_GNU +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_blowfish.c b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_blowfish.c new file mode 100644 index 0000000..5760064 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_blowfish.c @@ -0,0 +1,903 @@ +/* + * The crypt_blowfish homepage is: + * + * http://www.openwall.com/crypt/ + * + * This code comes from John the Ripper password cracker, with reentrant + * and crypt(3) interfaces added, but optimizations specific to password + * cracking removed. + * + * Written by Solar Designer in 1998-2014. + * No copyright is claimed, and the software is hereby placed in the public + * domain. In case this attempt to disclaim copyright and place the software + * in the public domain is deemed null and void, then the software is + * Copyright (c) 1998-2014 Solar Designer and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * It is my intent that you should be able to use this on your system, + * as part of a software package, or anywhere else to improve security, + * ensure compatibility, or for any other purpose. I would appreciate + * it if you give credit where it is due and keep your modifications in + * the public domain as well, but I don't require that in order to let + * you place this code and any modifications you make under a license + * of your choice. + * + * This implementation is fully compatible with OpenBSD's bcrypt.c for prefix + * "$2b$", originally by Niels Provos , and it uses + * some of his ideas. The password hashing algorithm was designed by David + * Mazieres . For information on the level of + * compatibility for bcrypt hash prefixes other than "$2b$", please refer to + * the comments in BF_set_key() below and to the included crypt(3) man page. + * + * There's a paper on the algorithm that explains its design decisions: + * + * http://www.usenix.org/events/usenix99/provos.html + * + * Some of the tricks in BF_ROUND might be inspired by Eric Young's + * Blowfish library (I can't be sure if I would think of something if I + * hadn't seen his code). + */ + +#include + +#include +#ifndef __set_errno +#define __set_errno(val) errno = (val) +#endif + +/* Just to make sure the prototypes match the actual definitions */ +#include "crypt_blowfish.h" + +#ifdef __i386__ +#define BF_ASM 1 +#define BF_SCALE 1 +#elif defined(__x86_64__) || defined(__alpha__) || defined(__hppa__) +#define BF_ASM 0 +#define BF_SCALE 1 +#else +#define BF_ASM 0 +#define BF_SCALE 0 +#endif + +typedef unsigned int BF_word; +typedef signed int BF_word_signed; + +/* Number of Blowfish rounds, this is also hardcoded into a few places */ +#define BF_N 16 + +typedef BF_word BF_key[BF_N + 2]; + +typedef struct { + BF_word S[4][0x100]; + BF_key P; +} BF_ctx; + +/* + * Magic IV for 64 Blowfish encryptions that we do at the end. + * The string is "OrpheanBeholderScryDoubt" on big-endian. + */ +static BF_word BF_magic_w[6] = { + 0x4F727068, 0x65616E42, 0x65686F6C, + 0x64657253, 0x63727944, 0x6F756274 +}; + +/* + * P-box and S-box tables initialized with digits of Pi. + */ +static BF_ctx BF_init_state = { + { + { + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a + }, { + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 + }, { + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 + }, { + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + } + }, { + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b + } +}; + +static const unsigned char BF_itoa64[64 + 1] = + "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + +static unsigned char BF_atoi64[0x60] = { + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 1, + 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 64, 64, 64, 64, 64, + 64, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 64, 64, 64, 64, 64, + 64, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 64, 64, 64, 64, 64 +}; + +#define BF_safe_atoi64(dst, src) \ +{ \ + tmp = (unsigned char)(src); \ + if ((unsigned int)(tmp -= 0x20) >= 0x60) return -1; \ + tmp = BF_atoi64[tmp]; \ + if (tmp > 63) return -1; \ + (dst) = tmp; \ +} + +static int BF_decode(BF_word *dst, const char *src, int size) +{ + unsigned char *dptr = (unsigned char *)dst; + unsigned char *end = dptr + size; + const unsigned char *sptr = (const unsigned char *)src; + do { + unsigned int tmp, c1, c2, c3, c4; + BF_safe_atoi64(c1, *sptr++); + BF_safe_atoi64(c2, *sptr++); + *dptr++ = (c1 << 2) | ((c2 & 0x30) >> 4); + if (dptr >= end) break; + + BF_safe_atoi64(c3, *sptr++); + *dptr++ = ((c2 & 0x0F) << 4) | ((c3 & 0x3C) >> 2); + if (dptr >= end) break; + + BF_safe_atoi64(c4, *sptr++); + *dptr++ = ((c3 & 0x03) << 6) | c4; + } while (dptr < end); + return 0; +} + +static void BF_encode(char *dst, const BF_word *src, int size) +{ + const unsigned char *sptr = (const unsigned char *)src; + const unsigned char *end = sptr + size; + unsigned char *dptr = (unsigned char *)dst; + do { + unsigned int c1, c2; + c1 = *sptr++; + *dptr++ = BF_itoa64[c1 >> 2]; + c1 = (c1 & 0x03) << 4; + if (sptr >= end) { + *dptr++ = BF_itoa64[c1]; + break; + } + + c2 = *sptr++; + c1 |= c2 >> 4; + *dptr++ = BF_itoa64[c1]; + c1 = (c2 & 0x0f) << 2; + if (sptr >= end) { + *dptr++ = BF_itoa64[c1]; + break; + } + + c2 = *sptr++; + c1 |= c2 >> 6; + *dptr++ = BF_itoa64[c1]; + *dptr++ = BF_itoa64[c2 & 0x3f]; + } while (sptr < end); +} + +static void BF_swap(BF_word *x, int count) +{ + static int endianness_check = 1; + char *is_little_endian = (char *)&endianness_check; + if (*is_little_endian) + do { + BF_word tmp; + tmp = *x; + tmp = (tmp << 16) | (tmp >> 16); + *x++ = ((tmp & 0x00FF00FF) << 8) | ((tmp >> 8) & 0x00FF00FF); + } while (--count); +} + +#if BF_SCALE +/* Architectures which can shift addresses left by 2 bits with no extra cost */ +#define BF_ROUND(L, R, N) \ + tmp1 = L & 0xFF; \ + tmp2 = L >> 8; \ + tmp2 &= 0xFF; \ + tmp3 = L >> 16; \ + tmp3 &= 0xFF; \ + tmp4 = L >> 24; \ + tmp1 = data.ctx.S[3][tmp1]; \ + tmp2 = data.ctx.S[2][tmp2]; \ + tmp3 = data.ctx.S[1][tmp3]; \ + tmp3 += data.ctx.S[0][tmp4]; \ + tmp3 ^= tmp2; \ + R ^= data.ctx.P[N + 1]; \ + tmp3 += tmp1; \ + R ^= tmp3; +#else +/* Architectures with no complicated addressing modes supported */ +#define BF_INDEX(S, i) \ + (*((BF_word *)(((unsigned char *)S) + (i)))) +#define BF_ROUND(L, R, N) \ + tmp1 = L & 0xFF; \ + tmp1 <<= 2; \ + tmp2 = L >> 6; \ + tmp2 &= 0x3FC; \ + tmp3 = L >> 14; \ + tmp3 &= 0x3FC; \ + tmp4 = L >> 22; \ + tmp4 &= 0x3FC; \ + tmp1 = BF_INDEX(data.ctx.S[3], tmp1); \ + tmp2 = BF_INDEX(data.ctx.S[2], tmp2); \ + tmp3 = BF_INDEX(data.ctx.S[1], tmp3); \ + tmp3 += BF_INDEX(data.ctx.S[0], tmp4); \ + tmp3 ^= tmp2; \ + R ^= data.ctx.P[N + 1]; \ + tmp3 += tmp1; \ + R ^= tmp3; +#endif + +/* + * Encrypt one block, BF_N is hardcoded here. + */ +#define BF_ENCRYPT \ + L ^= data.ctx.P[0]; \ + BF_ROUND(L, R, 0); \ + BF_ROUND(R, L, 1); \ + BF_ROUND(L, R, 2); \ + BF_ROUND(R, L, 3); \ + BF_ROUND(L, R, 4); \ + BF_ROUND(R, L, 5); \ + BF_ROUND(L, R, 6); \ + BF_ROUND(R, L, 7); \ + BF_ROUND(L, R, 8); \ + BF_ROUND(R, L, 9); \ + BF_ROUND(L, R, 10); \ + BF_ROUND(R, L, 11); \ + BF_ROUND(L, R, 12); \ + BF_ROUND(R, L, 13); \ + BF_ROUND(L, R, 14); \ + BF_ROUND(R, L, 15); \ + tmp4 = R; \ + R = L; \ + L = tmp4 ^ data.ctx.P[BF_N + 1]; + +#if BF_ASM == 1 +#define BF_body() \ + _BF_body_r(&data.ctx); +#else +#define BF_body() \ + L = R = 0; \ + ptr = data.ctx.P; \ + do { \ + ptr += 2; \ + BF_ENCRYPT; \ + *(ptr - 2) = L; \ + *(ptr - 1) = R; \ + } while (ptr < &data.ctx.P[BF_N + 2]); \ +\ + ptr = data.ctx.S[0]; \ + do { \ + ptr += 2; \ + BF_ENCRYPT; \ + *(ptr - 2) = L; \ + *(ptr - 1) = R; \ + } while (ptr < &data.ctx.S[3][0xFF]); +#endif + +static void BF_set_key(const char *key, BF_key expanded, BF_key initial, + unsigned char flags) +{ + const char *ptr = key; + unsigned int bug, i, j; + BF_word safety, sign, diff, tmp[2]; + +/* + * There was a sign extension bug in older revisions of this function. While + * we would have liked to simply fix the bug and move on, we have to provide + * a backwards compatibility feature (essentially the bug) for some systems and + * a safety measure for some others. The latter is needed because for certain + * multiple inputs to the buggy algorithm there exist easily found inputs to + * the correct algorithm that produce the same hash. Thus, we optionally + * deviate from the correct algorithm just enough to avoid such collisions. + * While the bug itself affected the majority of passwords containing + * characters with the 8th bit set (although only a percentage of those in a + * collision-producing way), the anti-collision safety measure affects + * only a subset of passwords containing the '\xff' character (not even all of + * those passwords, just some of them). This character is not found in valid + * UTF-8 sequences and is rarely used in popular 8-bit character encodings. + * Thus, the safety measure is unlikely to cause much annoyance, and is a + * reasonable tradeoff to use when authenticating against existing hashes that + * are not reliably known to have been computed with the correct algorithm. + * + * We use an approach that tries to minimize side-channel leaks of password + * information - that is, we mostly use fixed-cost bitwise operations instead + * of branches or table lookups. (One conditional branch based on password + * length remains. It is not part of the bug aftermath, though, and is + * difficult and possibly unreasonable to avoid given the use of C strings by + * the caller, which results in similar timing leaks anyway.) + * + * For actual implementation, we set an array index in the variable "bug" + * (0 means no bug, 1 means sign extension bug emulation) and a flag in the + * variable "safety" (bit 16 is set when the safety measure is requested). + * Valid combinations of settings are: + * + * Prefix "$2a$": bug = 0, safety = 0x10000 + * Prefix "$2b$": bug = 0, safety = 0 + * Prefix "$2x$": bug = 1, safety = 0 + * Prefix "$2y$": bug = 0, safety = 0 + */ + bug = (unsigned int)flags & 1; + safety = ((BF_word)flags & 2) << 15; + + sign = diff = 0; + + for (i = 0; i < BF_N + 2; i++) { + tmp[0] = tmp[1] = 0; + for (j = 0; j < 4; j++) { + tmp[0] <<= 8; + tmp[0] |= (unsigned char)*ptr; /* correct */ + tmp[1] <<= 8; + tmp[1] |= (BF_word_signed)(signed char)*ptr; /* bug */ +/* + * Sign extension in the first char has no effect - nothing to overwrite yet, + * and those extra 24 bits will be fully shifted out of the 32-bit word. For + * chars 2, 3, 4 in each four-char block, we set bit 7 of "sign" if sign + * extension in tmp[1] occurs. Once this flag is set, it remains set. + */ + if (j) + sign |= tmp[1] & 0x80; + if (!*ptr) + ptr = key; + else + ptr++; + } + diff |= tmp[0] ^ tmp[1]; /* Non-zero on any differences */ + + expanded[i] = tmp[bug]; + initial[i] = BF_init_state.P[i] ^ tmp[bug]; + } + +/* + * At this point, "diff" is zero iff the correct and buggy algorithms produced + * exactly the same result. If so and if "sign" is non-zero, which indicates + * that there was a non-benign sign extension, this means that we have a + * collision between the correctly computed hash for this password and a set of + * passwords that could be supplied to the buggy algorithm. Our safety measure + * is meant to protect from such many-buggy to one-correct collisions, by + * deviating from the correct algorithm in such cases. Let's check for this. + */ + diff |= diff >> 16; /* still zero iff exact match */ + diff &= 0xffff; /* ditto */ + diff += 0xffff; /* bit 16 set iff "diff" was non-zero (on non-match) */ + sign <<= 9; /* move the non-benign sign extension flag to bit 16 */ + sign &= ~diff & safety; /* action needed? */ + +/* + * If we have determined that we need to deviate from the correct algorithm, + * flip bit 16 in initial expanded key. (The choice of 16 is arbitrary, but + * let's stick to it now. It came out of the approach we used above, and it's + * not any worse than any other choice we could make.) + * + * It is crucial that we don't do the same to the expanded key used in the main + * Eksblowfish loop. By doing it to only one of these two, we deviate from a + * state that could be directly specified by a password to the buggy algorithm + * (and to the fully correct one as well, but that's a side-effect). + */ + initial[0] ^= sign; +} + +static const unsigned char flags_by_subtype[26] = + {2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 0}; + +static char *BF_crypt(const char *key, const char *setting, + char *output, int size, + BF_word min) +{ +#if BF_ASM == 1 + extern void _BF_body_r(BF_ctx *ctx); +#endif + struct { + BF_ctx ctx; + BF_key expanded_key; + union { + BF_word salt[4]; + BF_word output[6]; + } binary; + } data; + BF_word L, R; + BF_word tmp1, tmp2, tmp3, tmp4; + BF_word *ptr; + BF_word count; + int i; + + if (size < 7 + 22 + 31 + 1) { + __set_errno(ERANGE); + return NULL; + } + + if (setting[0] != '$' || + setting[1] != '2' || + setting[2] < 'a' || setting[2] > 'z' || + !flags_by_subtype[(unsigned int)(unsigned char)setting[2] - 'a'] || + setting[3] != '$' || + setting[4] < '0' || setting[4] > '3' || + setting[5] < '0' || setting[5] > '9' || + (setting[4] == '3' && setting[5] > '1') || + setting[6] != '$') { + __set_errno(EINVAL); + return NULL; + } + + count = (BF_word)1 << ((setting[4] - '0') * 10 + (setting[5] - '0')); + if (count < min || BF_decode(data.binary.salt, &setting[7], 16)) { + __set_errno(EINVAL); + return NULL; + } + BF_swap(data.binary.salt, 4); + + BF_set_key(key, data.expanded_key, data.ctx.P, + flags_by_subtype[(unsigned int)(unsigned char)setting[2] - 'a']); + + memcpy(data.ctx.S, BF_init_state.S, sizeof(data.ctx.S)); + + L = R = 0; + for (i = 0; i < BF_N + 2; i += 2) { + L ^= data.binary.salt[i & 2]; + R ^= data.binary.salt[(i & 2) + 1]; + BF_ENCRYPT; + data.ctx.P[i] = L; + data.ctx.P[i + 1] = R; + } + + ptr = data.ctx.S[0]; + do { + ptr += 4; + L ^= data.binary.salt[(BF_N + 2) & 3]; + R ^= data.binary.salt[(BF_N + 3) & 3]; + BF_ENCRYPT; + *(ptr - 4) = L; + *(ptr - 3) = R; + + L ^= data.binary.salt[(BF_N + 4) & 3]; + R ^= data.binary.salt[(BF_N + 5) & 3]; + BF_ENCRYPT; + *(ptr - 2) = L; + *(ptr - 1) = R; + } while (ptr < &data.ctx.S[3][0xFF]); + + do { + int done; + + for (i = 0; i < BF_N + 2; i += 2) { + data.ctx.P[i] ^= data.expanded_key[i]; + data.ctx.P[i + 1] ^= data.expanded_key[i + 1]; + } + + done = 0; + do { + BF_body(); + if (done) + break; + done = 1; + + tmp1 = data.binary.salt[0]; + tmp2 = data.binary.salt[1]; + tmp3 = data.binary.salt[2]; + tmp4 = data.binary.salt[3]; + for (i = 0; i < BF_N; i += 4) { + data.ctx.P[i] ^= tmp1; + data.ctx.P[i + 1] ^= tmp2; + data.ctx.P[i + 2] ^= tmp3; + data.ctx.P[i + 3] ^= tmp4; + } + data.ctx.P[16] ^= tmp1; + data.ctx.P[17] ^= tmp2; + } while (1); + } while (--count); + + for (i = 0; i < 6; i += 2) { + L = BF_magic_w[i]; + R = BF_magic_w[i + 1]; + + count = 64; + do { + BF_ENCRYPT; + } while (--count); + + data.binary.output[i] = L; + data.binary.output[i + 1] = R; + } + + memcpy(output, setting, 7 + 22 - 1); + output[7 + 22 - 1] = BF_itoa64[(int) + BF_atoi64[(int)setting[7 + 22 - 1] - 0x20] & 0x30]; + +/* This has to be bug-compatible with the original implementation, so + * only encode 23 of the 24 bytes. :-) */ + BF_swap(data.binary.output, 6); + BF_encode(&output[7 + 22], data.binary.output, 23); + output[7 + 22 + 31] = '\0'; + + return output; +} + +int _crypt_output_magic(const char *setting, char *output, int size) +{ + if (size < 3) + return -1; + + output[0] = '*'; + output[1] = '0'; + output[2] = '\0'; + + if (setting[0] == '*' && setting[1] == '0') + output[1] = '1'; + + return 0; +} + +/* + * Please preserve the runtime self-test. It serves two purposes at once: + * + * 1. We really can't afford the risk of producing incompatible hashes e.g. + * when there's something like gcc bug 26587 again, whereas an application or + * library integrating this code might not also integrate our external tests or + * it might not run them after every build. Even if it does, the miscompile + * might only occur on the production build, but not on a testing build (such + * as because of different optimization settings). It is painful to recover + * from incorrectly-computed hashes - merely fixing whatever broke is not + * enough. Thus, a proactive measure like this self-test is needed. + * + * 2. We don't want to leave sensitive data from our actual password hash + * computation on the stack or in registers. Previous revisions of the code + * would do explicit cleanups, but simply running the self-test after hash + * computation is more reliable. + * + * The performance cost of this quick self-test is around 0.6% at the "$2a$08" + * setting. + */ +char *_crypt_blowfish_rn(const char *key, const char *setting, + char *output, int size) +{ + const char *test_key = "8b \xd0\xc1\xd2\xcf\xcc\xd8"; + const char *test_setting = "$2a$00$abcdefghijklmnopqrstuu"; + static const char * const test_hashes[2] = + {"i1D709vfamulimlGcq0qq3UvuUasvEa\0\x55", /* 'a', 'b', 'y' */ + "VUrPmXD6q/nVSSp7pNDhCR9071IfIRe\0\x55"}; /* 'x' */ + const char *test_hash = test_hashes[0]; + char *retval; + const char *p; + int save_errno, ok; + struct { + char s[7 + 22 + 1]; + char o[7 + 22 + 31 + 1 + 1 + 1]; + } buf; + +/* Hash the supplied password */ + _crypt_output_magic(setting, output, size); + retval = BF_crypt(key, setting, output, size, 16); + save_errno = errno; + +/* + * Do a quick self-test. It is important that we make both calls to BF_crypt() + * from the same scope such that they likely use the same stack locations, + * which makes the second call overwrite the first call's sensitive data on the + * stack and makes it more likely that any alignment related issues would be + * detected by the self-test. + */ + memcpy(buf.s, test_setting, sizeof(buf.s)); + if (retval) { + unsigned int flags = flags_by_subtype[ + (unsigned int)(unsigned char)setting[2] - 'a']; + test_hash = test_hashes[flags & 1]; + buf.s[2] = setting[2]; + } + memset(buf.o, 0x55, sizeof(buf.o)); + buf.o[sizeof(buf.o) - 1] = 0; + p = BF_crypt(test_key, buf.s, buf.o, sizeof(buf.o) - (1 + 1), 1); + + ok = (p == buf.o && + !memcmp(p, buf.s, 7 + 22) && + !memcmp(p + (7 + 22), test_hash, 31 + 1 + 1 + 1)); + + { + const char *k = "\xff\xa3" "34" "\xff\xff\xff\xa3" "345"; + BF_key ae, ai, ye, yi; + BF_set_key(k, ae, ai, 2); /* $2a$ */ + BF_set_key(k, ye, yi, 4); /* $2y$ */ + ai[0] ^= 0x10000; /* undo the safety (for comparison) */ + ok = ok && ai[0] == 0xdb9c59bc && ye[17] == 0x33343500 && + !memcmp(ae, ye, sizeof(ae)) && + !memcmp(ai, yi, sizeof(ai)); + } + + __set_errno(save_errno); + if (ok) + return retval; + +/* Should not happen */ + _crypt_output_magic(setting, output, size); + __set_errno(EINVAL); /* pretend we don't support this hash type */ + return NULL; +} + +char *_crypt_gensalt_blowfish_rn(const char *prefix, unsigned long count, + const char *input, int size, char *output, int output_size) +{ + if (size < 16 || output_size < 7 + 22 + 1 || + (count && (count < 4 || count > 31)) || + prefix[0] != '$' || prefix[1] != '2' || + (prefix[2] != 'a' && prefix[2] != 'b' && prefix[2] != 'y')) { + if (output_size > 0) output[0] = '\0'; + __set_errno((output_size < 7 + 22 + 1) ? ERANGE : EINVAL); + return NULL; + } + + if (!count) count = 5; + + output[0] = '$'; + output[1] = '2'; + output[2] = prefix[2]; + output[3] = '$'; + output[4] = '0' + count / 10; + output[5] = '0' + count % 10; + output[6] = '$'; + + BF_encode(&output[7], (const BF_word *)input, 16); + output[7 + 22] = '\0'; + + return output; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_blowfish.h b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_blowfish.h new file mode 100644 index 0000000..2ee0d8c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_blowfish.h @@ -0,0 +1,27 @@ +/* + * Written by Solar Designer in 2000-2011. + * No copyright is claimed, and the software is hereby placed in the public + * domain. In case this attempt to disclaim copyright and place the software + * in the public domain is deemed null and void, then the software is + * Copyright (c) 2000-2011 Solar Designer and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * See crypt_blowfish.c for more information. + */ + +#ifndef _CRYPT_BLOWFISH_H +#define _CRYPT_BLOWFISH_H + +extern int _crypt_output_magic(const char *setting, char *output, int size); +extern char *_crypt_blowfish_rn(const char *key, const char *setting, + char *output, int size); +extern char *_crypt_gensalt_blowfish_rn(const char *prefix, + unsigned long count, + const char *input, int size, char *output, int output_size); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_gensalt.c b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_gensalt.c new file mode 100644 index 0000000..744912a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_gensalt.c @@ -0,0 +1,124 @@ +/* + * Written by Solar Designer in 2000-2011. + * No copyright is claimed, and the software is hereby placed in the public + * domain. In case this attempt to disclaim copyright and place the software + * in the public domain is deemed null and void, then the software is + * Copyright (c) 2000-2011 Solar Designer and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * See crypt_blowfish.c for more information. + * + * This file contains salt generation functions for the traditional and + * other common crypt(3) algorithms, except for bcrypt which is defined + * entirely in crypt_blowfish.c. + */ + +#include + +#include +#ifndef __set_errno +#define __set_errno(val) errno = (val) +#endif + +/* Just to make sure the prototypes match the actual definitions */ +#include "crypt_gensalt.h" + +const unsigned char _crypt_itoa64[64 + 1] = + "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + +char *_crypt_gensalt_traditional_rn(const char *prefix, unsigned long count, + const char *input, int size, char *output, int output_size) +{ + (void) prefix; + + if (size < 2 || output_size < 2 + 1 || (count && count != 25)) { + if (output_size > 0) output[0] = '\0'; + __set_errno((output_size < 2 + 1) ? ERANGE : EINVAL); + return NULL; + } + + output[0] = _crypt_itoa64[(unsigned int)input[0] & 0x3f]; + output[1] = _crypt_itoa64[(unsigned int)input[1] & 0x3f]; + output[2] = '\0'; + + return output; +} + +char *_crypt_gensalt_extended_rn(const char *prefix, unsigned long count, + const char *input, int size, char *output, int output_size) +{ + unsigned long value; + + (void) prefix; + +/* Even iteration counts make it easier to detect weak DES keys from a look + * at the hash, so they should be avoided */ + if (size < 3 || output_size < 1 + 4 + 4 + 1 || + (count && (count > 0xffffff || !(count & 1)))) { + if (output_size > 0) output[0] = '\0'; + __set_errno((output_size < 1 + 4 + 4 + 1) ? ERANGE : EINVAL); + return NULL; + } + + if (!count) count = 725; + + output[0] = '_'; + output[1] = _crypt_itoa64[count & 0x3f]; + output[2] = _crypt_itoa64[(count >> 6) & 0x3f]; + output[3] = _crypt_itoa64[(count >> 12) & 0x3f]; + output[4] = _crypt_itoa64[(count >> 18) & 0x3f]; + value = (unsigned long)(unsigned char)input[0] | + ((unsigned long)(unsigned char)input[1] << 8) | + ((unsigned long)(unsigned char)input[2] << 16); + output[5] = _crypt_itoa64[value & 0x3f]; + output[6] = _crypt_itoa64[(value >> 6) & 0x3f]; + output[7] = _crypt_itoa64[(value >> 12) & 0x3f]; + output[8] = _crypt_itoa64[(value >> 18) & 0x3f]; + output[9] = '\0'; + + return output; +} + +char *_crypt_gensalt_md5_rn(const char *prefix, unsigned long count, + const char *input, int size, char *output, int output_size) +{ + unsigned long value; + + (void) prefix; + + if (size < 3 || output_size < 3 + 4 + 1 || (count && count != 1000)) { + if (output_size > 0) output[0] = '\0'; + __set_errno((output_size < 3 + 4 + 1) ? ERANGE : EINVAL); + return NULL; + } + + output[0] = '$'; + output[1] = '1'; + output[2] = '$'; + value = (unsigned long)(unsigned char)input[0] | + ((unsigned long)(unsigned char)input[1] << 8) | + ((unsigned long)(unsigned char)input[2] << 16); + output[3] = _crypt_itoa64[value & 0x3f]; + output[4] = _crypt_itoa64[(value >> 6) & 0x3f]; + output[5] = _crypt_itoa64[(value >> 12) & 0x3f]; + output[6] = _crypt_itoa64[(value >> 18) & 0x3f]; + output[7] = '\0'; + + if (size >= 6 && output_size >= 3 + 4 + 4 + 1) { + value = (unsigned long)(unsigned char)input[3] | + ((unsigned long)(unsigned char)input[4] << 8) | + ((unsigned long)(unsigned char)input[5] << 16); + output[7] = _crypt_itoa64[value & 0x3f]; + output[8] = _crypt_itoa64[(value >> 6) & 0x3f]; + output[9] = _crypt_itoa64[(value >> 12) & 0x3f]; + output[10] = _crypt_itoa64[(value >> 18) & 0x3f]; + output[11] = '\0'; + } + + return output; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_gensalt.h b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_gensalt.h new file mode 100644 index 0000000..3a5ca08 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/crypt_gensalt.h @@ -0,0 +1,30 @@ +/* + * Written by Solar Designer in 2000-2011. + * No copyright is claimed, and the software is hereby placed in the public + * domain. In case this attempt to disclaim copyright and place the software + * in the public domain is deemed null and void, then the software is + * Copyright (c) 2000-2011 Solar Designer and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * See crypt_blowfish.c for more information. + */ + +#ifndef _CRYPT_GENSALT_H +#define _CRYPT_GENSALT_H + +extern const unsigned char _crypt_itoa64[]; +extern char *_crypt_gensalt_traditional_rn(const char *prefix, + unsigned long count, + const char *input, int size, char *output, int output_size); +extern char *_crypt_gensalt_extended_rn(const char *prefix, + unsigned long count, + const char *input, int size, char *output, int output_size); +extern char *_crypt_gensalt_md5_rn(const char *prefix, unsigned long count, + const char *input, int size, char *output, int output_size); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/extconf.rb b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/extconf.rb new file mode 100644 index 0000000..c2222de --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/extconf.rb @@ -0,0 +1,22 @@ +if RUBY_PLATFORM == "java" + # Don't do anything when run in JRuby; this allows gem installation to pass. + # We need to write a dummy Makefile so that RubyGems doesn't think compilation + # failed. + File.open('Makefile', 'w') do |f| + f.puts "all:" + f.puts "\t@true" + f.puts "install:" + f.puts "\t@true" + end + exit 0 +else + require "mkmf" + + # From Openwall's crypt_blowfish Makefile. + # This is `bcrypt_ext` (our extension) + CRYPT_OBJS from that Makefile. + $objs = %w(bcrypt_ext.o crypt_blowfish.o x86.o crypt_gensalt.o wrapper.o) + + $defs << "-D__SKIP_GNU" + dir_config("bcrypt_ext") + create_makefile("bcrypt_ext") +end diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/ow-crypt.h b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/ow-crypt.h new file mode 100644 index 0000000..2e48794 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/ow-crypt.h @@ -0,0 +1,43 @@ +/* + * Written by Solar Designer in 2000-2011. + * No copyright is claimed, and the software is hereby placed in the public + * domain. In case this attempt to disclaim copyright and place the software + * in the public domain is deemed null and void, then the software is + * Copyright (c) 2000-2011 Solar Designer and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * See crypt_blowfish.c for more information. + */ + +#ifndef _OW_CRYPT_H +#define _OW_CRYPT_H + +#ifndef __GNUC__ +#undef __const +#define __const const +#endif + +#ifndef __SKIP_GNU +extern char *crypt(__const char *key, __const char *setting); +extern char *crypt_r(__const char *key, __const char *setting, void *data); +#endif + +#ifndef __SKIP_OW +extern char *crypt_rn(__const char *key, __const char *setting, + void *data, int size); +extern char *crypt_ra(__const char *key, __const char *setting, + void **data, int *size); +extern char *crypt_gensalt(__const char *prefix, unsigned long count, + __const char *input, int size); +extern char *crypt_gensalt_rn(__const char *prefix, unsigned long count, + __const char *input, int size, char *output, int output_size); +extern char *crypt_gensalt_ra(__const char *prefix, unsigned long count, + __const char *input, int size); +#endif + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/wrapper.c b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/wrapper.c new file mode 100644 index 0000000..cbba882 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/wrapper.c @@ -0,0 +1,554 @@ +/* + * Written by Solar Designer in 2000-2014. + * No copyright is claimed, and the software is hereby placed in the public + * domain. In case this attempt to disclaim copyright and place the software + * in the public domain is deemed null and void, then the software is + * Copyright (c) 2000-2014 Solar Designer and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * See crypt_blowfish.c for more information. + */ + +#include +#include + +/* Redefine strdup to ruby_strdup in case string.h doesn't export it. */ +#include + +#include +#ifndef __set_errno +#define __set_errno(val) errno = (val) +#endif + +#ifdef TEST +#include +#include +#include +#include +#include +#include +#ifdef TEST_THREADS +#include +#endif +#endif + +#define CRYPT_OUTPUT_SIZE (7 + 22 + 31 + 1) +#define CRYPT_GENSALT_OUTPUT_SIZE (7 + 22 + 1) + +#if defined(__GLIBC__) && defined(_LIBC) +#define __SKIP_GNU +#endif +#include "ow-crypt.h" + +#include "crypt_blowfish.h" +#include "crypt_gensalt.h" + +#if defined(__GLIBC__) && defined(_LIBC) +/* crypt.h from glibc-crypt-2.1 will define struct crypt_data for us */ +#include "crypt.h" +extern char *__md5_crypt_r(const char *key, const char *salt, + char *buffer, int buflen); +/* crypt-entry.c needs to be patched to define __des_crypt_r rather than + * __crypt_r, and not define crypt_r and crypt at all */ +extern char *__des_crypt_r(const char *key, const char *salt, + struct crypt_data *data); +extern struct crypt_data _ufc_foobar; +#endif + +static int _crypt_data_alloc(void **data, int *size, int need) +{ + void *updated; + + if (*data && *size >= need) return 0; + + updated = realloc(*data, need); + + if (!updated) { +#ifndef __GLIBC__ + /* realloc(3) on glibc sets errno, so we don't need to bother */ + __set_errno(ENOMEM); +#endif + return -1; + } + +#if defined(__GLIBC__) && defined(_LIBC) + if (need >= sizeof(struct crypt_data)) + ((struct crypt_data *)updated)->initialized = 0; +#endif + + *data = updated; + *size = need; + + return 0; +} + +static char *_crypt_retval_magic(char *retval, const char *setting, + char *output, int size) +{ + if (retval) + return retval; + + if (_crypt_output_magic(setting, output, size)) + return NULL; /* shouldn't happen */ + + return output; +} + +#if defined(__GLIBC__) && defined(_LIBC) +/* + * Applications may re-use the same instance of struct crypt_data without + * resetting the initialized field in order to let crypt_r() skip some of + * its initialization code. Thus, it is important that our multiple hashing + * algorithms either don't conflict with each other in their use of the + * data area or reset the initialized field themselves whenever required. + * Currently, the hashing algorithms simply have no conflicts: the first + * field of struct crypt_data is the 128-byte large DES key schedule which + * __des_crypt_r() calculates each time it is called while the two other + * hashing algorithms use less than 128 bytes of the data area. + */ + +char *__crypt_rn(__const char *key, __const char *setting, + void *data, int size) +{ + if (setting[0] == '$' && setting[1] == '2') + return _crypt_blowfish_rn(key, setting, (char *)data, size); + if (setting[0] == '$' && setting[1] == '1') + return __md5_crypt_r(key, setting, (char *)data, size); + if (setting[0] == '$' || setting[0] == '_') { + __set_errno(EINVAL); + return NULL; + } + if (size >= sizeof(struct crypt_data)) + return __des_crypt_r(key, setting, (struct crypt_data *)data); + __set_errno(ERANGE); + return NULL; +} + +char *__crypt_ra(__const char *key, __const char *setting, + void **data, int *size) +{ + if (setting[0] == '$' && setting[1] == '2') { + if (_crypt_data_alloc(data, size, CRYPT_OUTPUT_SIZE)) + return NULL; + return _crypt_blowfish_rn(key, setting, (char *)*data, *size); + } + if (setting[0] == '$' && setting[1] == '1') { + if (_crypt_data_alloc(data, size, CRYPT_OUTPUT_SIZE)) + return NULL; + return __md5_crypt_r(key, setting, (char *)*data, *size); + } + if (setting[0] == '$' || setting[0] == '_') { + __set_errno(EINVAL); + return NULL; + } + if (_crypt_data_alloc(data, size, sizeof(struct crypt_data))) + return NULL; + return __des_crypt_r(key, setting, (struct crypt_data *)*data); +} + +char *__crypt_r(__const char *key, __const char *setting, + struct crypt_data *data) +{ + return _crypt_retval_magic( + __crypt_rn(key, setting, data, sizeof(*data)), + setting, (char *)data, sizeof(*data)); +} + +char *__crypt(__const char *key, __const char *setting) +{ + return _crypt_retval_magic( + __crypt_rn(key, setting, &_ufc_foobar, sizeof(_ufc_foobar)), + setting, (char *)&_ufc_foobar, sizeof(_ufc_foobar)); +} +#else +char *crypt_rn(const char *key, const char *setting, void *data, int size) +{ + return _crypt_blowfish_rn(key, setting, (char *)data, size); +} + +char *crypt_ra(const char *key, const char *setting, + void **data, int *size) +{ + if (_crypt_data_alloc(data, size, CRYPT_OUTPUT_SIZE)) + return NULL; + return _crypt_blowfish_rn(key, setting, (char *)*data, *size); +} + +char *crypt_r(const char *key, const char *setting, struct crypt_data *data) +{ + return _crypt_retval_magic( + crypt_rn(key, setting, data, CRYPT_OUTPUT_SIZE), + setting, (char *)data, CRYPT_OUTPUT_SIZE); +} + +char *crypt(const char *key, const char *setting) +{ + static char output[CRYPT_OUTPUT_SIZE]; + + return _crypt_retval_magic( + crypt_rn(key, setting, output, sizeof(output)), + setting, output, sizeof(output)); +} + +#define __crypt_gensalt_rn crypt_gensalt_rn +#define __crypt_gensalt_ra crypt_gensalt_ra +#define __crypt_gensalt crypt_gensalt +#endif + +char *__crypt_gensalt_rn(const char *prefix, unsigned long count, + const char *input, int size, char *output, int output_size) +{ + char *(*use)(const char *_prefix, unsigned long _count, + const char *_input, int _size, + char *_output, int _output_size); + + /* This may be supported on some platforms in the future */ + if (!input) { + __set_errno(EINVAL); + return NULL; + } + + if (!strncmp(prefix, "$2a$", 4) || !strncmp(prefix, "$2b$", 4) || + !strncmp(prefix, "$2y$", 4)) + use = _crypt_gensalt_blowfish_rn; + else + if (!strncmp(prefix, "$1$", 3)) + use = _crypt_gensalt_md5_rn; + else + if (prefix[0] == '_') + use = _crypt_gensalt_extended_rn; + else + if (!prefix[0] || + (prefix[0] && prefix[1] && + memchr(_crypt_itoa64, prefix[0], 64) && + memchr(_crypt_itoa64, prefix[1], 64))) + use = _crypt_gensalt_traditional_rn; + else { + __set_errno(EINVAL); + return NULL; + } + + return use(prefix, count, input, size, output, output_size); +} + +char *__crypt_gensalt_ra(const char *prefix, unsigned long count, + const char *input, int size) +{ + char output[CRYPT_GENSALT_OUTPUT_SIZE]; + char *retval; + + retval = __crypt_gensalt_rn(prefix, count, + input, size, output, sizeof(output)); + + if (retval) { + retval = strdup(retval); +#ifndef __GLIBC__ + /* strdup(3) on glibc sets errno, so we don't need to bother */ + if (!retval) + __set_errno(ENOMEM); +#endif + } + + return retval; +} + +char *__crypt_gensalt(const char *prefix, unsigned long count, + const char *input, int size) +{ + static char output[CRYPT_GENSALT_OUTPUT_SIZE]; + + return __crypt_gensalt_rn(prefix, count, + input, size, output, sizeof(output)); +} + +#if defined(__GLIBC__) && defined(_LIBC) +weak_alias(__crypt_rn, crypt_rn) +weak_alias(__crypt_ra, crypt_ra) +weak_alias(__crypt_r, crypt_r) +weak_alias(__crypt, crypt) +weak_alias(__crypt_gensalt_rn, crypt_gensalt_rn) +weak_alias(__crypt_gensalt_ra, crypt_gensalt_ra) +weak_alias(__crypt_gensalt, crypt_gensalt) +weak_alias(crypt, fcrypt) +#endif + +#ifdef TEST +static const char *tests[][3] = { + {"$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW", + "U*U"}, + {"$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK", + "U*U*"}, + {"$2a$05$XXXXXXXXXXXXXXXXXXXXXOAcXxm9kjPGEMsLznoKqmqw7tc8WCx4a", + "U*U*U"}, + {"$2a$05$abcdefghijklmnopqrstuu5s2v8.iXieOjg/.AySBTTZIIVFJeBui", + "0123456789abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + "chars after 72 are ignored"}, + {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e", + "\xa3"}, + {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e", + "\xff\xff\xa3"}, + {"$2y$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e", + "\xff\xff\xa3"}, + {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.nqd1wy.pTMdcvrRWxyiGL2eMz.2a85.", + "\xff\xff\xa3"}, + {"$2b$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e", + "\xff\xff\xa3"}, + {"$2y$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq", + "\xa3"}, + {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq", + "\xa3"}, + {"$2b$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq", + "\xa3"}, + {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi", + "1\xa3" "345"}, + {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi", + "\xff\xa3" "345"}, + {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi", + "\xff\xa3" "34" "\xff\xff\xff\xa3" "345"}, + {"$2y$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi", + "\xff\xa3" "34" "\xff\xff\xff\xa3" "345"}, + {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.ZC1JEJ8Z4gPfpe1JOr/oyPXTWl9EFd.", + "\xff\xa3" "34" "\xff\xff\xff\xa3" "345"}, + {"$2y$05$/OK.fbVrR/bpIqNJ5ianF.nRht2l/HRhr6zmCp9vYUvvsqynflf9e", + "\xff\xa3" "345"}, + {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.nRht2l/HRhr6zmCp9vYUvvsqynflf9e", + "\xff\xa3" "345"}, + {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.6IflQkJytoRVc1yuaNtHfiuq.FRlSIS", + "\xa3" "ab"}, + {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.6IflQkJytoRVc1yuaNtHfiuq.FRlSIS", + "\xa3" "ab"}, + {"$2y$05$/OK.fbVrR/bpIqNJ5ianF.6IflQkJytoRVc1yuaNtHfiuq.FRlSIS", + "\xa3" "ab"}, + {"$2x$05$6bNw2HLQYeqHYyBfLMsv/OiwqTymGIGzFsA4hOTWebfehXHNprcAS", + "\xd1\x91"}, + {"$2x$05$6bNw2HLQYeqHYyBfLMsv/O9LIGgn8OMzuDoHfof8AQimSGfcSWxnS", + "\xd0\xc1\xd2\xcf\xcc\xd8"}, + {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.swQOIzjOiJ9GHEPuhEkvqrUyvWhEMx6", + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" + "chars after 72 are ignored as usual"}, + {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.R9xrDjiycxMbQE2bp.vgqlYpW5wx2yy", + "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55" + "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55" + "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55" + "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55" + "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55" + "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55"}, + {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.9tQZzcJfm3uj2NvJ/n5xkhpqLrMpWCe", + "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff" + "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff" + "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff" + "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff" + "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff" + "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff"}, + {"$2a$05$CCCCCCCCCCCCCCCCCCCCC.7uG0VCzI2bS7j6ymqJi9CdcdxiRTWNy", + ""}, + {"*0", "", "$2a$03$CCCCCCCCCCCCCCCCCCCCC."}, + {"*0", "", "$2a$32$CCCCCCCCCCCCCCCCCCCCC."}, + {"*0", "", "$2c$05$CCCCCCCCCCCCCCCCCCCCC."}, + {"*0", "", "$2z$05$CCCCCCCCCCCCCCCCCCCCC."}, + {"*0", "", "$2`$05$CCCCCCCCCCCCCCCCCCCCC."}, + {"*0", "", "$2{$05$CCCCCCCCCCCCCCCCCCCCC."}, + {"*1", "", "*0"}, + {NULL} +}; + +#define which tests[0] + +static volatile sig_atomic_t running; + +static void handle_timer(int signum) +{ + (void) signum; + running = 0; +} + +static void *run(void *arg) +{ + unsigned long count = 0; + int i = 0; + void *data = NULL; + int size = 0x12345678; + + do { + const char *hash = tests[i][0]; + const char *key = tests[i][1]; + const char *setting = tests[i][2]; + + if (!tests[++i][0]) + i = 0; + + if (setting && strlen(hash) < 30) /* not for benchmark */ + continue; + + if (strcmp(crypt_ra(key, hash, &data, &size), hash)) { + printf("%d: FAILED (crypt_ra/%d/%lu)\n", + (int)((char *)arg - (char *)0), i, count); + free(data); + return NULL; + } + count++; + } while (running); + + free(data); + return count + (char *)0; +} + +int main(void) +{ + struct itimerval it; + struct tms buf; + clock_t clk_tck, start_real, start_virtual, end_real, end_virtual; + unsigned long count; + void *data; + int size; + char *setting1, *setting2; + int i; +#ifdef TEST_THREADS + pthread_t t[TEST_THREADS]; + void *t_retval; +#endif + + data = NULL; + size = 0x12345678; + + for (i = 0; tests[i][0]; i++) { + const char *hash = tests[i][0]; + const char *key = tests[i][1]; + const char *setting = tests[i][2]; + const char *p; + int ok = !setting || strlen(hash) >= 30; + int o_size; + char s_buf[30], o_buf[61]; + if (!setting) { + memcpy(s_buf, hash, sizeof(s_buf) - 1); + s_buf[sizeof(s_buf) - 1] = 0; + setting = s_buf; + } + + __set_errno(0); + p = crypt(key, setting); + if ((!ok && !errno) || strcmp(p, hash)) { + printf("FAILED (crypt/%d)\n", i); + return 1; + } + + if (ok && strcmp(crypt(key, hash), hash)) { + printf("FAILED (crypt/%d)\n", i); + return 1; + } + + for (o_size = -1; o_size <= (int)sizeof(o_buf); o_size++) { + int ok_n = ok && o_size == (int)sizeof(o_buf); + const char *x = "abc"; + strcpy(o_buf, x); + if (o_size >= 3) { + x = "*0"; + if (setting[0] == '*' && setting[1] == '0') + x = "*1"; + } + __set_errno(0); + p = crypt_rn(key, setting, o_buf, o_size); + if ((ok_n && (!p || strcmp(p, hash))) || + (!ok_n && (!errno || p || strcmp(o_buf, x)))) { + printf("FAILED (crypt_rn/%d)\n", i); + return 1; + } + } + + __set_errno(0); + p = crypt_ra(key, setting, &data, &size); + if ((ok && (!p || strcmp(p, hash))) || + (!ok && (!errno || p || strcmp((char *)data, hash)))) { + printf("FAILED (crypt_ra/%d)\n", i); + return 1; + } + } + + setting1 = crypt_gensalt(which[0], 12, data, size); + if (!setting1 || strncmp(setting1, "$2a$12$", 7)) { + puts("FAILED (crypt_gensalt)\n"); + return 1; + } + + setting2 = crypt_gensalt_ra(setting1, 12, data, size); + if (strcmp(setting1, setting2)) { + puts("FAILED (crypt_gensalt_ra/1)\n"); + return 1; + } + + (*(char *)data)++; + setting1 = crypt_gensalt_ra(setting2, 12, data, size); + if (!strcmp(setting1, setting2)) { + puts("FAILED (crypt_gensalt_ra/2)\n"); + return 1; + } + + free(setting1); + free(setting2); + free(data); + +#if defined(_SC_CLK_TCK) || !defined(CLK_TCK) + clk_tck = sysconf(_SC_CLK_TCK); +#else + clk_tck = CLK_TCK; +#endif + + running = 1; + signal(SIGALRM, handle_timer); + + memset(&it, 0, sizeof(it)); + it.it_value.tv_sec = 5; + setitimer(ITIMER_REAL, &it, NULL); + + start_real = times(&buf); + start_virtual = buf.tms_utime + buf.tms_stime; + + count = (char *)run((char *)0) - (char *)0; + + end_real = times(&buf); + end_virtual = buf.tms_utime + buf.tms_stime; + if (end_virtual == start_virtual) end_virtual++; + + printf("%.1f c/s real, %.1f c/s virtual\n", + (float)count * clk_tck / (end_real - start_real), + (float)count * clk_tck / (end_virtual - start_virtual)); + +#ifdef TEST_THREADS + running = 1; + it.it_value.tv_sec = 60; + setitimer(ITIMER_REAL, &it, NULL); + start_real = times(&buf); + + for (i = 0; i < TEST_THREADS; i++) + if (pthread_create(&t[i], NULL, run, i + (char *)0)) { + perror("pthread_create"); + return 1; + } + + for (i = 0; i < TEST_THREADS; i++) { + if (pthread_join(t[i], &t_retval)) { + perror("pthread_join"); + continue; + } + if (!t_retval) continue; + count = (char *)t_retval - (char *)0; + end_real = times(&buf); + printf("%d: %.1f c/s real\n", i, + (float)count * clk_tck / (end_real - start_real)); + } +#endif + + return 0; +} +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/x86.S b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/x86.S new file mode 100644 index 0000000..4c5c069 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/ext/mri/x86.S @@ -0,0 +1,203 @@ +/* + * Written by Solar Designer in 1998-2010. + * No copyright is claimed, and the software is hereby placed in the public + * domain. In case this attempt to disclaim copyright and place the software + * in the public domain is deemed null and void, then the software is + * Copyright (c) 1998-2010 Solar Designer and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There's ABSOLUTELY NO WARRANTY, express or implied. + * + * See crypt_blowfish.c for more information. + */ + +#ifdef __i386__ + +#if defined(__OpenBSD__) && !defined(__ELF__) +#define UNDERSCORES +#define ALIGN_LOG +#endif + +#if defined(__CYGWIN32__) || defined(__MINGW32__) +#define UNDERSCORES +#endif + +#ifdef __DJGPP__ +#define UNDERSCORES +#define ALIGN_LOG +#endif + +#ifdef UNDERSCORES +#define _BF_body_r __BF_body_r +#endif + +#ifdef ALIGN_LOG +#define DO_ALIGN(log) .align (log) +#elif defined(DUMBAS) +#define DO_ALIGN(log) .align 1 << log +#else +#define DO_ALIGN(log) .align (1 << (log)) +#endif + +#define BF_FRAME 0x200 +#define ctx %esp + +#define BF_ptr (ctx) + +#define S(N, r) N+BF_FRAME(ctx,r,4) +#ifdef DUMBAS +#define P(N) 0x1000+N+N+N+N+BF_FRAME(ctx) +#else +#define P(N) 0x1000+4*N+BF_FRAME(ctx) +#endif + +/* + * This version of the assembly code is optimized primarily for the original + * Intel Pentium but is also careful to avoid partial register stalls on the + * Pentium Pro family of processors (tested up to Pentium III Coppermine). + * + * It is possible to do 15% faster on the Pentium Pro family and probably on + * many non-Intel x86 processors, but, unfortunately, that would make things + * twice slower for the original Pentium. + * + * An additional 2% speedup may be achieved with non-reentrant code. + */ + +#define L %esi +#define R %edi +#define tmp1 %eax +#define tmp1_lo %al +#define tmp2 %ecx +#define tmp2_hi %ch +#define tmp3 %edx +#define tmp3_lo %dl +#define tmp4 %ebx +#define tmp4_hi %bh +#define tmp5 %ebp + +.text + +#define BF_ROUND(L, R, N) \ + xorl L,tmp2; \ + xorl tmp1,tmp1; \ + movl tmp2,L; \ + shrl $16,tmp2; \ + movl L,tmp4; \ + movb tmp2_hi,tmp1_lo; \ + andl $0xFF,tmp2; \ + movb tmp4_hi,tmp3_lo; \ + andl $0xFF,tmp4; \ + movl S(0,tmp1),tmp1; \ + movl S(0x400,tmp2),tmp5; \ + addl tmp5,tmp1; \ + movl S(0x800,tmp3),tmp5; \ + xorl tmp5,tmp1; \ + movl S(0xC00,tmp4),tmp5; \ + addl tmp1,tmp5; \ + movl 4+P(N),tmp2; \ + xorl tmp5,R + +#define BF_ENCRYPT_START \ + BF_ROUND(L, R, 0); \ + BF_ROUND(R, L, 1); \ + BF_ROUND(L, R, 2); \ + BF_ROUND(R, L, 3); \ + BF_ROUND(L, R, 4); \ + BF_ROUND(R, L, 5); \ + BF_ROUND(L, R, 6); \ + BF_ROUND(R, L, 7); \ + BF_ROUND(L, R, 8); \ + BF_ROUND(R, L, 9); \ + BF_ROUND(L, R, 10); \ + BF_ROUND(R, L, 11); \ + BF_ROUND(L, R, 12); \ + BF_ROUND(R, L, 13); \ + BF_ROUND(L, R, 14); \ + BF_ROUND(R, L, 15); \ + movl BF_ptr,tmp5; \ + xorl L,tmp2; \ + movl P(17),L + +#define BF_ENCRYPT_END \ + xorl R,L; \ + movl tmp2,R + +DO_ALIGN(5) +.globl _BF_body_r +_BF_body_r: + movl 4(%esp),%eax + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + subl $BF_FRAME-8,%eax + xorl L,L + cmpl %esp,%eax + ja BF_die + xchgl %eax,%esp + xorl R,R + pushl %eax + leal 0x1000+BF_FRAME-4(ctx),%eax + movl 0x1000+BF_FRAME-4(ctx),tmp2 + pushl %eax + xorl tmp3,tmp3 +BF_loop_P: + BF_ENCRYPT_START + addl $8,tmp5 + BF_ENCRYPT_END + leal 0x1000+18*4+BF_FRAME(ctx),tmp1 + movl tmp5,BF_ptr + cmpl tmp5,tmp1 + movl L,-8(tmp5) + movl R,-4(tmp5) + movl P(0),tmp2 + ja BF_loop_P + leal BF_FRAME(ctx),tmp5 + xorl tmp3,tmp3 + movl tmp5,BF_ptr +BF_loop_S: + BF_ENCRYPT_START + BF_ENCRYPT_END + movl P(0),tmp2 + movl L,(tmp5) + movl R,4(tmp5) + BF_ENCRYPT_START + BF_ENCRYPT_END + movl P(0),tmp2 + movl L,8(tmp5) + movl R,12(tmp5) + BF_ENCRYPT_START + BF_ENCRYPT_END + movl P(0),tmp2 + movl L,16(tmp5) + movl R,20(tmp5) + BF_ENCRYPT_START + addl $32,tmp5 + BF_ENCRYPT_END + leal 0x1000+BF_FRAME(ctx),tmp1 + movl tmp5,BF_ptr + cmpl tmp5,tmp1 + movl P(0),tmp2 + movl L,-8(tmp5) + movl R,-4(tmp5) + ja BF_loop_S + movl 4(%esp),%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret + +BF_die: +/* Oops, need to re-compile with a larger BF_FRAME. */ + hlt + jmp BF_die + +#endif + +#if defined(__ELF__) && defined(__linux__) +.section .note.GNU-stack,"",%progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt.rb b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt.rb new file mode 100644 index 0000000..c1b9e47 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt.rb @@ -0,0 +1,16 @@ +# A Ruby library implementing OpenBSD's bcrypt()/crypt_blowfish algorithm for +# hashing passwords. +module BCrypt +end + +if RUBY_PLATFORM == "java" + require 'java' +else + require "openssl" +end + +require "bcrypt_ext" + +require 'bcrypt/error' +require 'bcrypt/engine' +require 'bcrypt/password' diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt/engine.rb b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt/engine.rb new file mode 100644 index 0000000..552b7b0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt/engine.rb @@ -0,0 +1,127 @@ +module BCrypt + # A Ruby wrapper for the bcrypt() C extension calls and the Java calls. + class Engine + # The default computational expense parameter. + DEFAULT_COST = 12 + # The minimum cost supported by the algorithm. + MIN_COST = 4 + # The maximum cost supported by the algorithm. + MAX_COST = 31 + # Maximum possible size of bcrypt() secrets. + # Older versions of the bcrypt library would truncate passwords longer + # than 72 bytes, but newer ones do not. We truncate like the old library for + # forward compatibility. This way users upgrading from Ubuntu 18.04 to 20.04 + # will not have their user passwords invalidated, for example. + # A max secret length greater than 255 leads to bcrypt returning nil. + # https://github.com/bcrypt-ruby/bcrypt-ruby/issues/225#issuecomment-875908425 + MAX_SECRET_BYTESIZE = 72 + # Maximum possible size of bcrypt() salts. + MAX_SALT_LENGTH = 16 + + if RUBY_PLATFORM != "java" + # C-level routines which, if they don't get the right input, will crash the + # hell out of the Ruby process. + private_class_method :__bc_salt + private_class_method :__bc_crypt + end + + @cost = nil + + # Returns the cost factor that will be used if one is not specified when + # creating a password hash. Defaults to DEFAULT_COST if not set. + def self.cost + @cost || DEFAULT_COST + end + + # Set a default cost factor that will be used if one is not specified when + # creating a password hash. + # + # Example: + # + # BCrypt::Engine::DEFAULT_COST #=> 12 + # BCrypt::Password.create('secret').cost #=> 12 + # + # BCrypt::Engine.cost = 8 + # BCrypt::Password.create('secret').cost #=> 8 + # + # # cost can still be overridden as needed + # BCrypt::Password.create('secret', :cost => 6).cost #=> 6 + def self.cost=(cost) + @cost = cost + end + + # Given a secret and a valid salt (see BCrypt::Engine.generate_salt) calculates + # a bcrypt() password hash. Secrets longer than 72 bytes are truncated. + def self.hash_secret(secret, salt, _ = nil) + if valid_secret?(secret) + if valid_salt?(salt) + if RUBY_PLATFORM == "java" + Java.bcrypt_jruby.BCrypt.hashpw(secret.to_s.to_java_bytes, salt.to_s) + else + secret = secret.to_s + secret = secret.byteslice(0, MAX_SECRET_BYTESIZE) if secret && secret.bytesize > MAX_SECRET_BYTESIZE + __bc_crypt(secret, salt) + end + else + raise Errors::InvalidSalt.new("invalid salt") + end + else + raise Errors::InvalidSecret.new("invalid secret") + end + end + + # Generates a random salt with a given computational cost. + def self.generate_salt(cost = self.cost) + cost = cost.to_i + if cost > 0 + if cost < MIN_COST + cost = MIN_COST + end + if RUBY_PLATFORM == "java" + Java.bcrypt_jruby.BCrypt.gensalt(cost) + else + __bc_salt("$2a$", cost, OpenSSL::Random.random_bytes(MAX_SALT_LENGTH)) + end + else + raise Errors::InvalidCost.new("cost must be numeric and > 0") + end + end + + # Returns true if +salt+ is a valid bcrypt() salt, false if not. + def self.valid_salt?(salt) + !!(salt =~ /\A\$[0-9a-z]{2,}\$[0-9]{2,}\$[A-Za-z0-9\.\/]{22,}\z/) + end + + # Returns true if +secret+ is a valid bcrypt() secret, false if not. + def self.valid_secret?(secret) + secret.respond_to?(:to_s) + end + + # Returns the cost factor which will result in computation times less than +upper_time_limit_in_ms+. + # + # Example: + # + # BCrypt::Engine.calibrate(200) #=> 10 + # BCrypt::Engine.calibrate(1000) #=> 12 + # + # # should take less than 200ms + # BCrypt::Password.create("woo", :cost => 10) + # + # # should take less than 1000ms + # BCrypt::Password.create("woo", :cost => 12) + def self.calibrate(upper_time_limit_in_ms) + (BCrypt::Engine::MIN_COST..BCrypt::Engine::MAX_COST-1).each do |i| + start_time = Time.now + Password.create("testing testing", :cost => i+1) + end_time = Time.now - start_time + return i if end_time * 1_000 > upper_time_limit_in_ms + end + end + + # Autodetects the cost from the salt string. + def self.autodetect_cost(salt) + salt[4..5].to_i + end + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt/error.rb b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt/error.rb new file mode 100644 index 0000000..c7e42a4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt/error.rb @@ -0,0 +1,22 @@ +module BCrypt + + class Error < StandardError # :nodoc: + end + + module Errors # :nodoc: + + # The salt parameter provided to bcrypt() is invalid. + class InvalidSalt < BCrypt::Error; end + + # The hash parameter provided to bcrypt() is invalid. + class InvalidHash < BCrypt::Error; end + + # The cost parameter provided to bcrypt() is invalid. + class InvalidCost < BCrypt::Error; end + + # The secret parameter provided to bcrypt() is invalid. + class InvalidSecret < BCrypt::Error; end + + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt/password.rb b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt/password.rb new file mode 100644 index 0000000..4a2c140 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/lib/bcrypt/password.rb @@ -0,0 +1,97 @@ +module BCrypt + # A password management class which allows you to safely store users' passwords and compare them. + # + # Example usage: + # + # include BCrypt + # + # # hash a user's password + # @password = Password.create("my grand secret") + # @password #=> "$2a$12$C5.FIvVDS9W4AYZ/Ib37YuWd/7ozp1UaMhU28UKrfSxp2oDchbi3K" + # + # # store it safely + # @user.update_attribute(:password, @password) + # + # # read it back + # @user.reload! + # @db_password = Password.new(@user.password) + # + # # compare it after retrieval + # @db_password == "my grand secret" #=> true + # @db_password == "a paltry guess" #=> false + # + class Password < String + # The hash portion of the stored password hash. + attr_reader :checksum + # The salt of the store password hash (including version and cost). + attr_reader :salt + # The version of the bcrypt() algorithm used to create the hash. + attr_reader :version + # The cost factor used to create the hash. + attr_reader :cost + + class << self + # Hashes a secret, returning a BCrypt::Password instance. Takes an optional :cost option, which is a + # logarithmic variable which determines how computational expensive the hash is to calculate (a :cost of + # 4 is twice as much work as a :cost of 3). The higher the :cost the harder it becomes for + # attackers to try to guess passwords (even if a copy of your database is stolen), but the slower it is to check + # users' passwords. + # + # Example: + # + # @password = BCrypt::Password.create("my secret", :cost => 13) + def create(secret, options = {}) + cost = options[:cost] || BCrypt::Engine.cost + raise ArgumentError if cost > BCrypt::Engine::MAX_COST + Password.new(BCrypt::Engine.hash_secret(secret, BCrypt::Engine.generate_salt(cost))) + end + + def valid_hash?(h) + /\A\$[0-9a-z]{2}\$[0-9]{2}\$[A-Za-z0-9\.\/]{53}\z/ === h + end + end + + # Initializes a BCrypt::Password instance with the data from a stored hash. + def initialize(raw_hash) + if valid_hash?(raw_hash) + self.replace(raw_hash) + @version, @cost, @salt, @checksum = split_hash(self) + else + raise Errors::InvalidHash.new("invalid hash") + end + end + + # Compares a potential secret against the hash. Returns true if the secret is the original secret, false otherwise. + # + # Comparison edge case/gotcha: + # + # secret = "my secret" + # @password = BCrypt::Password.create(secret) + # + # @password == secret # => True + # @password == @password # => False + # @password == @password.to_s # => False + # @password.to_s == @password # => True + # @password.to_s == @password.to_s # => True + def ==(secret) + super(BCrypt::Engine.hash_secret(secret, @salt)) + end + alias_method :is_password?, :== + + private + + # Returns true if +h+ is a valid hash. + def valid_hash?(h) + self.class.valid_hash?(h) + end + + # call-seq: + # split_hash(raw_hash) -> version, cost, salt, hash + # + # Splits +h+ into version, cost, salt, and hash and returns them in that order. + def split_hash(h) + _, v, c, mash = h.split('$') + return v.to_str, c.to_i, h[0, 29].to_str, mash[-31, 31].to_str + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/TestBCrypt.java b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/TestBCrypt.java new file mode 100644 index 0000000..c481ff3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/TestBCrypt.java @@ -0,0 +1,194 @@ +// Copyright (c) 2006 Damien Miller +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import junit.framework.TestCase; + +/** + * JUnit unit tests for BCrypt routines + * @author Damien Miller + * @version 0.2 + */ +public class TestBCrypt extends TestCase { + String test_vectors[][] = { + { "", + "$2a$06$DCq7YPn5Rq63x1Lad4cll.", + "$2a$06$DCq7YPn5Rq63x1Lad4cll.TV4S6ytwfsfvkgY8jIucDrjc8deX1s." }, + { "", + "$2a$08$HqWuK6/Ng6sg9gQzbLrgb.", + "$2a$08$HqWuK6/Ng6sg9gQzbLrgb.Tl.ZHfXLhvt/SgVyWhQqgqcZ7ZuUtye" }, + { "", + "$2a$10$k1wbIrmNyFAPwPVPSVa/ze", + "$2a$10$k1wbIrmNyFAPwPVPSVa/zecw2BCEnBwVS2GbrmgzxFUOqW9dk4TCW" }, + { "", + "$2a$12$k42ZFHFWqBp3vWli.nIn8u", + "$2a$12$k42ZFHFWqBp3vWli.nIn8uYyIkbvYRvodzbfbK18SSsY.CsIQPlxO" }, + { "a", + "$2a$06$m0CrhHm10qJ3lXRY.5zDGO", + "$2a$06$m0CrhHm10qJ3lXRY.5zDGO3rS2KdeeWLuGmsfGlMfOxih58VYVfxe" }, + { "a", + "$2a$08$cfcvVd2aQ8CMvoMpP2EBfe", + "$2a$08$cfcvVd2aQ8CMvoMpP2EBfeodLEkkFJ9umNEfPD18.hUF62qqlC/V." }, + { "a", + "$2a$10$k87L/MF28Q673VKh8/cPi.", + "$2a$10$k87L/MF28Q673VKh8/cPi.SUl7MU/rWuSiIDDFayrKk/1tBsSQu4u" }, + { "a", + "$2a$12$8NJH3LsPrANStV6XtBakCe", + "$2a$12$8NJH3LsPrANStV6XtBakCez0cKHXVxmvxIlcz785vxAIZrihHZpeS" }, + { "abc", + "$2a$06$If6bvum7DFjUnE9p2uDeDu", + "$2a$06$If6bvum7DFjUnE9p2uDeDu0YHzrHM6tf.iqN8.yx.jNN1ILEf7h0i" }, + { "abc", + "$2a$08$Ro0CUfOqk6cXEKf3dyaM7O", + "$2a$08$Ro0CUfOqk6cXEKf3dyaM7OhSCvnwM9s4wIX9JeLapehKK5YdLxKcm" }, + { "abc", + "$2a$10$WvvTPHKwdBJ3uk0Z37EMR.", + "$2a$10$WvvTPHKwdBJ3uk0Z37EMR.hLA2W6N9AEBhEgrAOljy2Ae5MtaSIUi" }, + { "abc", + "$2a$12$EXRkfkdmXn2gzds2SSitu.", + "$2a$12$EXRkfkdmXn2gzds2SSitu.MW9.gAVqa9eLS1//RYtYCmB1eLHg.9q" }, + { "abcdefghijklmnopqrstuvwxyz", + "$2a$06$.rCVZVOThsIa97pEDOxvGu", + "$2a$06$.rCVZVOThsIa97pEDOxvGuRRgzG64bvtJ0938xuqzv18d3ZpQhstC" }, + { "abcdefghijklmnopqrstuvwxyz", + "$2a$08$aTsUwsyowQuzRrDqFflhge", + "$2a$08$aTsUwsyowQuzRrDqFflhgekJ8d9/7Z3GV3UcgvzQW3J5zMyrTvlz." }, + { "abcdefghijklmnopqrstuvwxyz", + "$2a$10$fVH8e28OQRj9tqiDXs1e1u", + "$2a$10$fVH8e28OQRj9tqiDXs1e1uxpsjN0c7II7YPKXua2NAKYvM6iQk7dq" }, + { "abcdefghijklmnopqrstuvwxyz", + "$2a$12$D4G5f18o7aMMfwasBL7Gpu", + "$2a$12$D4G5f18o7aMMfwasBL7GpuQWuP3pkrZrOAnqP.bmezbMng.QwJ/pG" }, + { "~!@#$%^&*() ~!@#$%^&*()PNBFRD", + "$2a$06$fPIsBO8qRqkjj273rfaOI.", + "$2a$06$fPIsBO8qRqkjj273rfaOI.HtSV9jLDpTbZn782DC6/t7qT67P6FfO" }, + { "~!@#$%^&*() ~!@#$%^&*()PNBFRD", + "$2a$08$Eq2r4G/76Wv39MzSX262hu", + "$2a$08$Eq2r4G/76Wv39MzSX262huzPz612MZiYHVUJe/OcOql2jo4.9UxTW" }, + { "~!@#$%^&*() ~!@#$%^&*()PNBFRD", + "$2a$10$LgfYWkbzEvQ4JakH7rOvHe", + "$2a$10$LgfYWkbzEvQ4JakH7rOvHe0y8pHKF9OaFgwUZ2q7W2FFZmZzJYlfS" }, + { "~!@#$%^&*() ~!@#$%^&*()PNBFRD", + "$2a$12$WApznUOJfkEGSmYRfnkrPO", + "$2a$12$WApznUOJfkEGSmYRfnkrPOr466oFDCaj4b6HY3EXGvfxm43seyhgC" }, + }; + + /** + * Entry point for unit tests + * @param args unused + */ + public static void main(String[] args) { + junit.textui.TestRunner.run(TestBCrypt.class); + } + + /** + * Test method for 'BCrypt.hashpw(String, String)' + */ + public void testHashpw() { + System.out.print("BCrypt.hashpw(): "); + for (int i = 0; i < test_vectors.length; i++) { + String plain = test_vectors[i][0]; + String salt = test_vectors[i][1]; + String expected = test_vectors[i][2]; + String hashed = BCrypt.hashpw(plain, salt); + assertEquals(hashed, expected); + System.out.print("."); + } + System.out.println(""); + } + + /** + * Test method for 'BCrypt.gensalt(int)' + */ + public void testGensaltInt() { + System.out.print("BCrypt.gensalt(log_rounds):"); + for (int i = 4; i <= 12; i++) { + System.out.print(" " + Integer.toString(i) + ":"); + for (int j = 0; j < test_vectors.length; j += 4) { + String plain = test_vectors[j][0]; + String salt = BCrypt.gensalt(i); + String hashed1 = BCrypt.hashpw(plain, salt); + String hashed2 = BCrypt.hashpw(plain, hashed1); + assertEquals(hashed1, hashed2); + System.out.print("."); + } + } + System.out.println(""); + } + + /** + * Test method for 'BCrypt.gensalt()' + */ + public void testGensalt() { + System.out.print("BCrypt.gensalt(): "); + for (int i = 0; i < test_vectors.length; i += 4) { + String plain = test_vectors[i][0]; + String salt = BCrypt.gensalt(); + String hashed1 = BCrypt.hashpw(plain, salt); + String hashed2 = BCrypt.hashpw(plain, hashed1); + assertEquals(hashed1, hashed2); + System.out.print("."); + } + System.out.println(""); + } + + /** + * Test method for 'BCrypt.checkpw(String, String)' + * expecting success + */ + public void testCheckpw_success() { + System.out.print("BCrypt.checkpw w/ good passwords: "); + for (int i = 0; i < test_vectors.length; i++) { + String plain = test_vectors[i][0]; + String expected = test_vectors[i][2]; + assertTrue(BCrypt.checkpw(plain, expected)); + System.out.print("."); + } + System.out.println(""); + } + + /** + * Test method for 'BCrypt.checkpw(String, String)' + * expecting failure + */ + public void testCheckpw_failure() { + System.out.print("BCrypt.checkpw w/ bad passwords: "); + for (int i = 0; i < test_vectors.length; i++) { + int broken_index = (i + 4) % test_vectors.length; + String plain = test_vectors[i][0]; + String expected = test_vectors[broken_index][2]; + assertFalse(BCrypt.checkpw(plain, expected)); + System.out.print("."); + } + System.out.println(""); + } + + /** + * Test for correct hashing of non-US-ASCII passwords + */ + public void testInternationalChars() { + System.out.print("BCrypt.hashpw w/ international chars: "); + String pw1 = "ππππππππ"; + String pw2 = "????????"; + + String h1 = BCrypt.hashpw(pw1, BCrypt.gensalt()); + assertFalse(BCrypt.checkpw(pw2, h1)); + System.out.print("."); + + String h2 = BCrypt.hashpw(pw2, BCrypt.gensalt()); + assertFalse(BCrypt.checkpw(pw1, h2)); + System.out.print("."); + System.out.println(""); + } + +} diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/bcrypt/engine_spec.rb b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/bcrypt/engine_spec.rb new file mode 100644 index 0000000..b527a6b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/bcrypt/engine_spec.rb @@ -0,0 +1,176 @@ +require File.expand_path(File.join(File.dirname(__FILE__), "..", "spec_helper")) +require 'securerandom' + +describe 'BCrypt::Engine' do + describe '.calibrate(upper_time_limit_in_ms)' do + context 'a tiny upper time limit provided' do + it 'returns a minimum cost supported by the algorithm' do + expect(BCrypt::Engine.calibrate(0.001)).to eq(4) + end + end + end +end + +describe "The BCrypt engine" do + specify "should calculate the optimal cost factor to fit in a specific time" do + start_time = Time.now + BCrypt::Password.create("testing testing", :cost => BCrypt::Engine::MIN_COST + 1) + min_time_ms = (Time.now - start_time) * 1000 + first = BCrypt::Engine.calibrate(min_time_ms) + second = BCrypt::Engine.calibrate(min_time_ms * 4) + expect(second).to be > first + end +end + +describe "Generating BCrypt salts" do + + specify "should produce strings" do + expect(BCrypt::Engine.generate_salt).to be_an_instance_of(String) + end + + specify "should produce random data" do + expect(BCrypt::Engine.generate_salt).to_not equal(BCrypt::Engine.generate_salt) + end + + specify "should raise a InvalidCostError if the cost parameter isn't numeric" do + expect { BCrypt::Engine.generate_salt('woo') }.to raise_error(BCrypt::Errors::InvalidCost) + end + + specify "should raise a InvalidCostError if the cost parameter isn't greater than 0" do + expect { BCrypt::Engine.generate_salt(-1) }.to raise_error(BCrypt::Errors::InvalidCost) + end +end + +describe "Autodetecting of salt cost" do + + specify "should work" do + expect(BCrypt::Engine.autodetect_cost("$2a$08$hRx2IVeHNsTSYYtUWn61Ou")).to eq 8 + expect(BCrypt::Engine.autodetect_cost("$2a$05$XKd1bMnLgUnc87qvbAaCUu")).to eq 5 + expect(BCrypt::Engine.autodetect_cost("$2a$13$Lni.CZ6z5A7344POTFBBV.")).to eq 13 + end + +end + +describe "Generating BCrypt hashes" do + + class MyInvalidSecret + undef to_s + end + + before :each do + @salt = BCrypt::Engine.generate_salt(4) + @password = "woo" + end + + specify "should produce a string" do + expect(BCrypt::Engine.hash_secret(@password, @salt)).to be_an_instance_of(String) + end + + specify "should raise an InvalidSalt error if the salt is invalid" do + expect { BCrypt::Engine.hash_secret(@password, 'nino') }.to raise_error(BCrypt::Errors::InvalidSalt) + end + + specify "should raise an InvalidSecret error if the secret is invalid" do + expect { BCrypt::Engine.hash_secret(MyInvalidSecret.new, @salt) }.to raise_error(BCrypt::Errors::InvalidSecret) + expect { BCrypt::Engine.hash_secret(nil, @salt) }.not_to raise_error + expect { BCrypt::Engine.hash_secret(false, @salt) }.not_to raise_error + end + + specify "should call #to_s on the secret and use the return value as the actual secret data" do + expect(BCrypt::Engine.hash_secret(false, @salt)).to eq BCrypt::Engine.hash_secret("false", @salt) + end + + specify "should be interoperable with other implementations" do + test_vectors = [ + # test vectors from the OpenWall implementation , found in wrapper.c + ["U*U", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"], + ["U*U*", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK"], + ["U*U*U", "$2a$05$XXXXXXXXXXXXXXXXXXXXXO", "$2a$05$XXXXXXXXXXXXXXXXXXXXXOAcXxm9kjPGEMsLznoKqmqw7tc8WCx4a"], + ["0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789chars after 72 are ignored", "$2a$05$abcdefghijklmnopqrstuu", "$2a$05$abcdefghijklmnopqrstuu5s2v8.iXieOjg/.AySBTTZIIVFJeBui"], + ["\xa3", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e"], + ["\xff\xff\xa3", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e"], + ["\xff\xff\xa3", "$2y$05$/OK.fbVrR/bpIqNJ5ianF.", "$2y$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e"], + ["\xff\xff\xa3", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.nqd1wy.pTMdcvrRWxyiGL2eMz.2a85."], + ["\xff\xff\xa3", "$2b$05$/OK.fbVrR/bpIqNJ5ianF.", "$2b$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e"], + ["\xa3", "$2y$05$/OK.fbVrR/bpIqNJ5ianF.", "$2y$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq"], + ["\xa3", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq"], + ["\xa3", "$2b$05$/OK.fbVrR/bpIqNJ5ianF.", "$2b$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq"], + ["1\xa3" "345", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi"], + ["\xff\xa3" "345", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi"], + ["\xff\xa3" "34" "\xff\xff\xff\xa3" "345", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi"], + ["\xff\xa3" "34" "\xff\xff\xff\xa3" "345", "$2y$05$/OK.fbVrR/bpIqNJ5ianF.", "$2y$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi"], + ["\xff\xa3" "34" "\xff\xff\xff\xa3" "345", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.ZC1JEJ8Z4gPfpe1JOr/oyPXTWl9EFd."], + ["\xff\xa3" "345", "$2y$05$/OK.fbVrR/bpIqNJ5ianF.", "$2y$05$/OK.fbVrR/bpIqNJ5ianF.nRht2l/HRhr6zmCp9vYUvvsqynflf9e"], + ["\xff\xa3" "345", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.nRht2l/HRhr6zmCp9vYUvvsqynflf9e"], + ["\xa3" "ab", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.6IflQkJytoRVc1yuaNtHfiuq.FRlSIS"], + ["\xa3" "ab", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.", "$2x$05$/OK.fbVrR/bpIqNJ5ianF.6IflQkJytoRVc1yuaNtHfiuq.FRlSIS"], + ["\xa3" "ab", "$2y$05$/OK.fbVrR/bpIqNJ5ianF.", "$2y$05$/OK.fbVrR/bpIqNJ5ianF.6IflQkJytoRVc1yuaNtHfiuq.FRlSIS"], + ["\xd1\x91", "$2x$05$6bNw2HLQYeqHYyBfLMsv/O", "$2x$05$6bNw2HLQYeqHYyBfLMsv/OiwqTymGIGzFsA4hOTWebfehXHNprcAS"], + ["\xd0\xc1\xd2\xcf\xcc\xd8", "$2x$05$6bNw2HLQYeqHYyBfLMsv/O", "$2x$05$6bNw2HLQYeqHYyBfLMsv/O9LIGgn8OMzuDoHfof8AQimSGfcSWxnS"], + ["\xaa"*72+"chars after 72 are ignored as usual", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.swQOIzjOiJ9GHEPuhEkvqrUyvWhEMx6"], + ["\xaa\x55"*36, "$2a$05$/OK.fbVrR/bpIqNJ5ianF.", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.R9xrDjiycxMbQE2bp.vgqlYpW5wx2yy"], + ["\x55\xaa\xff"*24, "$2a$05$/OK.fbVrR/bpIqNJ5ianF.", "$2a$05$/OK.fbVrR/bpIqNJ5ianF.9tQZzcJfm3uj2NvJ/n5xkhpqLrMpWCe"], + ["", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.7uG0VCzI2bS7j6ymqJi9CdcdxiRTWNy"], + + # test vectors from the Java implementation, found in https://github.com/spring-projects/spring-security/blob/master/crypto/src/test/java/org/springframework/security/crypto/bcrypt/BCryptTests.java + ["", "$2a$06$DCq7YPn5Rq63x1Lad4cll.", "$2a$06$DCq7YPn5Rq63x1Lad4cll.TV4S6ytwfsfvkgY8jIucDrjc8deX1s."], + ["", "$2a$08$HqWuK6/Ng6sg9gQzbLrgb.", "$2a$08$HqWuK6/Ng6sg9gQzbLrgb.Tl.ZHfXLhvt/SgVyWhQqgqcZ7ZuUtye"], + ["", "$2a$10$k1wbIrmNyFAPwPVPSVa/ze", "$2a$10$k1wbIrmNyFAPwPVPSVa/zecw2BCEnBwVS2GbrmgzxFUOqW9dk4TCW"], + ["", "$2a$12$k42ZFHFWqBp3vWli.nIn8u", "$2a$12$k42ZFHFWqBp3vWli.nIn8uYyIkbvYRvodzbfbK18SSsY.CsIQPlxO"], + ["", "$2b$06$8eVN9RiU8Yki430X.wBvN.", "$2b$06$8eVN9RiU8Yki430X.wBvN.LWaqh2962emLVSVXVZIXJvDYLsV0oFu"], + ["", "$2b$06$NlgfNgpIc6GlHciCkMEW8u", "$2b$06$NlgfNgpIc6GlHciCkMEW8uKOBsyvAp7QwlHpysOlKdtyEw50WQua2"], + ["", "$2y$06$mFDtkz6UN7B3GZ2qi2hhaO", "$2y$06$mFDtkz6UN7B3GZ2qi2hhaO3OFWzNEdcY84ELw6iHCPruuQfSAXBLK"], + ["", "$2y$06$88kSqVttBx.e9iXTPCLa5u", "$2y$06$88kSqVttBx.e9iXTPCLa5uFPrVFjfLH4D.KcO6pBiAmvUkvdg0EYy"], + ["a", "$2a$06$m0CrhHm10qJ3lXRY.5zDGO", "$2a$06$m0CrhHm10qJ3lXRY.5zDGO3rS2KdeeWLuGmsfGlMfOxih58VYVfxe"], + ["a", "$2a$08$cfcvVd2aQ8CMvoMpP2EBfe", "$2a$08$cfcvVd2aQ8CMvoMpP2EBfeodLEkkFJ9umNEfPD18.hUF62qqlC/V."], + ["a", "$2a$10$k87L/MF28Q673VKh8/cPi.", "$2a$10$k87L/MF28Q673VKh8/cPi.SUl7MU/rWuSiIDDFayrKk/1tBsSQu4u"], + ["a", "$2a$12$8NJH3LsPrANStV6XtBakCe", "$2a$12$8NJH3LsPrANStV6XtBakCez0cKHXVxmvxIlcz785vxAIZrihHZpeS"], + ["a", "$2b$06$ehKGYiS4wt2HAr7KQXS5z.", "$2b$06$ehKGYiS4wt2HAr7KQXS5z.OaRjB4jHO7rBHJKlGXbqEH3QVJfO7iO"], + ["a", "$2b$06$PWxFFHA3HiCD46TNOZh30e", "$2b$06$PWxFFHA3HiCD46TNOZh30eNto1hg5uM9tHBlI4q/b03SW/gGKUYk6"], + ["a", "$2y$06$LUdD6/aD0e/UbnxVAVbvGu", "$2y$06$LUdD6/aD0e/UbnxVAVbvGuUmIoJ3l/OK94ThhadpMWwKC34LrGEey"], + ["a", "$2y$06$eqgY.T2yloESMZxgp76deO", "$2y$06$eqgY.T2yloESMZxgp76deOROa7nzXDxbO0k.PJvuClTa.Vu1AuemG"], + ["abc", "$2a$06$If6bvum7DFjUnE9p2uDeDu", "$2a$06$If6bvum7DFjUnE9p2uDeDu0YHzrHM6tf.iqN8.yx.jNN1ILEf7h0i"], + ["abc", "$2a$08$Ro0CUfOqk6cXEKf3dyaM7O", "$2a$08$Ro0CUfOqk6cXEKf3dyaM7OhSCvnwM9s4wIX9JeLapehKK5YdLxKcm"], + ["abc", "$2a$10$WvvTPHKwdBJ3uk0Z37EMR.", "$2a$10$WvvTPHKwdBJ3uk0Z37EMR.hLA2W6N9AEBhEgrAOljy2Ae5MtaSIUi"], + ["abc", "$2a$12$EXRkfkdmXn2gzds2SSitu.", "$2a$12$EXRkfkdmXn2gzds2SSitu.MW9.gAVqa9eLS1//RYtYCmB1eLHg.9q"], + ["abc", "$2b$06$5FyQoicpbox1xSHFfhhdXu", "$2b$06$5FyQoicpbox1xSHFfhhdXuR2oxLpO1rYsQh5RTkI/9.RIjtoF0/ta"], + ["abc", "$2b$06$1kJyuho8MCVP3HHsjnRMkO", "$2b$06$1kJyuho8MCVP3HHsjnRMkO1nvCOaKTqLnjG2TX1lyMFbXH/aOkgc."], + ["abc", "$2y$06$ACfku9dT6.H8VjdKb8nhlu", "$2y$06$ACfku9dT6.H8VjdKb8nhluaoBmhJyK7GfoNScEfOfrJffUxoUeCjK"], + ["abc", "$2y$06$9JujYcoWPmifvFA3RUP90e", "$2y$06$9JujYcoWPmifvFA3RUP90e5rSEHAb5Ye6iv3.G9ikiHNv5cxjNEse"], + ["abcdefghijklmnopqrstuvwxyz", "$2a$06$.rCVZVOThsIa97pEDOxvGu", "$2a$06$.rCVZVOThsIa97pEDOxvGuRRgzG64bvtJ0938xuqzv18d3ZpQhstC"], + ["abcdefghijklmnopqrstuvwxyz", "$2a$08$aTsUwsyowQuzRrDqFflhge", "$2a$08$aTsUwsyowQuzRrDqFflhgekJ8d9/7Z3GV3UcgvzQW3J5zMyrTvlz."], + ["abcdefghijklmnopqrstuvwxyz", "$2a$10$fVH8e28OQRj9tqiDXs1e1u", "$2a$10$fVH8e28OQRj9tqiDXs1e1uxpsjN0c7II7YPKXua2NAKYvM6iQk7dq"], + ["abcdefghijklmnopqrstuvwxyz", "$2a$12$D4G5f18o7aMMfwasBL7Gpu", "$2a$12$D4G5f18o7aMMfwasBL7GpuQWuP3pkrZrOAnqP.bmezbMng.QwJ/pG"], + ["abcdefghijklmnopqrstuvwxyz", "$2b$06$O8E89AQPj1zJQA05YvIAU.", "$2b$06$O8E89AQPj1zJQA05YvIAU.hMpj25BXri1bupl/Q7CJMlpLwZDNBoO"], + ["abcdefghijklmnopqrstuvwxyz", "$2b$06$PDqIWr./o/P3EE/P.Q0A/u", "$2b$06$PDqIWr./o/P3EE/P.Q0A/uFg86WL/PXTbaW267TDALEwDylqk00Z."], + ["abcdefghijklmnopqrstuvwxyz", "$2y$06$34MG90ZLah8/ZNr3ltlHCu", "$2y$06$34MG90ZLah8/ZNr3ltlHCuz6bachF8/3S5jTuzF1h2qg2cUk11sFW"], + ["abcdefghijklmnopqrstuvwxyz", "$2y$06$AK.hSLfMyw706iEW24i68u", "$2y$06$AK.hSLfMyw706iEW24i68uKAc2yorPTrB0cimvjJHEBUrPkOq7VvG"], + ["~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2a$06$fPIsBO8qRqkjj273rfaOI.", "$2a$06$fPIsBO8qRqkjj273rfaOI.HtSV9jLDpTbZn782DC6/t7qT67P6FfO"], + ["~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2a$08$Eq2r4G/76Wv39MzSX262hu", "$2a$08$Eq2r4G/76Wv39MzSX262huzPz612MZiYHVUJe/OcOql2jo4.9UxTW"], + ["~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2a$10$LgfYWkbzEvQ4JakH7rOvHe", "$2a$10$LgfYWkbzEvQ4JakH7rOvHe0y8pHKF9OaFgwUZ2q7W2FFZmZzJYlfS"], + ["~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2a$12$WApznUOJfkEGSmYRfnkrPO", "$2a$12$WApznUOJfkEGSmYRfnkrPOr466oFDCaj4b6HY3EXGvfxm43seyhgC"], + ["~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2b$06$FGWA8OlY6RtQhXBXuCJ8Wu", "$2b$06$FGWA8OlY6RtQhXBXuCJ8WusVipRI15cWOgJK8MYpBHEkktMfbHRIG"], + ["~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2b$06$G6aYU7UhUEUDJBdTgq3CRe", "$2b$06$G6aYU7UhUEUDJBdTgq3CRekiopCN4O4sNitFXrf5NUscsVZj3a2r6"], + ["~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2y$06$sYDFHqOcXTjBgOsqC0WCKe", "$2y$06$sYDFHqOcXTjBgOsqC0WCKeMd3T1UhHuWQSxncLGtXDLMrcE6vFDti"], + ["~!@#$%^&*() ~!@#$%^&*()PNBFRD", "$2y$06$6Xm0gCw4g7ZNDCEp4yTise", "$2y$06$6Xm0gCw4g7ZNDCEp4yTisez0kSdpXEl66MvdxGidnmChIe8dFmMnq"] + ] + for secret, salt, test_vector in test_vectors + expect(BCrypt::Engine.hash_secret(secret, salt)).to eql(test_vector) + end + end + + specify "should truncate long 1-byte character secrets to 72 bytes" do + # 'b' as a base triggers the failure at 256 characters, but 'a' does not. + too_long_secret = 'b'*(BCrypt::Engine::MAX_SECRET_BYTESIZE + 1) + just_right_secret = 'b'*BCrypt::Engine::MAX_SECRET_BYTESIZE + expect(BCrypt::Engine.hash_secret(too_long_secret, @salt)).to eq(BCrypt::Engine.hash_secret(just_right_secret, @salt)) + end + + specify "should truncate long multi-byte character secrets to 72 bytes" do + # 256 times causes bcrypt to return nil for libxcrypt > 4.4.18-4. + too_long_secret = '𐐷'*256 + # 𐐷 takes 4 bytes in UTF-8. 18 times is 72 bytes + just_right_secret = '𐐷'*18 + expect(BCrypt::Engine.hash_secret(too_long_secret, @salt)).to eq(BCrypt::Engine.hash_secret(just_right_secret, @salt)) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/bcrypt/error_spec.rb b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/bcrypt/error_spec.rb new file mode 100644 index 0000000..6f90048 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/bcrypt/error_spec.rb @@ -0,0 +1,37 @@ +require File.expand_path(File.join(File.dirname(__FILE__), "..", "spec_helper")) + +describe "Errors" do + + shared_examples "descends from StandardError" do + it "can be rescued as a StandardError" do + expect(described_class).to be < StandardError + end + end + + shared_examples "descends from BCrypt::Error" do + it "can be rescued as a BCrypt::Error" do + expect(described_class).to be < BCrypt::Error + end + end + + describe BCrypt::Error do + include_examples "descends from StandardError" + end + + describe BCrypt::Errors::InvalidCost do + include_examples "descends from BCrypt::Error" + end + + describe BCrypt::Errors::InvalidHash do + include_examples "descends from BCrypt::Error" + end + + describe BCrypt::Errors::InvalidSalt do + include_examples "descends from BCrypt::Error" + end + + describe BCrypt::Errors::InvalidSecret do + include_examples "descends from BCrypt::Error" + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/bcrypt/password_spec.rb b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/bcrypt/password_spec.rb new file mode 100644 index 0000000..1899221 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/bcrypt/password_spec.rb @@ -0,0 +1,131 @@ +require File.expand_path(File.join(File.dirname(__FILE__), "..", "spec_helper")) +require 'securerandom' + +describe "Creating a hashed password" do + + before :each do + @secret = "wheedle" + @password = BCrypt::Password.create(@secret, :cost => 4) + end + + specify "should return a BCrypt::Password" do + expect(@password).to be_an_instance_of(BCrypt::Password) + end + + specify "should return a valid bcrypt password" do + expect { BCrypt::Password.new(@password) }.not_to raise_error + end + + specify "should behave normally if the secret is not a string" do + expect { BCrypt::Password.create(nil) }.not_to raise_error + expect { BCrypt::Password.create({:woo => "yeah"}) }.not_to raise_error + expect { BCrypt::Password.create(false) }.not_to raise_error + end + + specify "should tolerate empty string secrets" do + expect { BCrypt::Password.create( "\n".chop ) }.not_to raise_error + expect { BCrypt::Password.create( "" ) }.not_to raise_error + expect { BCrypt::Password.create( String.new ) }.not_to raise_error + end + + specify "should tolerate very long string secrets" do + expect { BCrypt::Password.create("abcd"*1024) }.not_to raise_error + end +end + +describe "Reading a hashed password" do + before :each do + @secret = "U*U" + @hash = "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW" + end + + specify "the cost is too damn high" do + expect { + BCrypt::Password.create("hello", :cost => 32) + }.to raise_error(ArgumentError) + end + + specify "the cost should be set to the default if nil" do + expect(BCrypt::Password.create("hello", :cost => nil).cost).to equal(BCrypt::Engine::DEFAULT_COST) + end + + specify "the cost should be set to the default if empty hash" do + expect(BCrypt::Password.create("hello", {}).cost).to equal(BCrypt::Engine::DEFAULT_COST) + end + + specify "the cost should be set to the passed value if provided" do + expect(BCrypt::Password.create("hello", :cost => 5).cost).to equal(5) + end + + specify "the cost should be set to the global value if set" do + BCrypt::Engine.cost = 5 + expect(BCrypt::Password.create("hello").cost).to equal(5) + # unset the global value to not affect other tests + BCrypt::Engine.cost = nil + end + + specify "the cost should be set to an overridden constant for backwards compatibility" do + # suppress "already initialized constant" warning + old_verbose, $VERBOSE = $VERBOSE, nil + old_default_cost = BCrypt::Engine::DEFAULT_COST + + BCrypt::Engine::DEFAULT_COST = 5 + expect(BCrypt::Password.create("hello").cost).to equal(5) + + # reset default to not affect other tests + BCrypt::Engine::DEFAULT_COST = old_default_cost + $VERBOSE = old_verbose + end + + specify "should read the version, cost, salt, and hash" do + password = BCrypt::Password.new(@hash) + expect(password.version).to eql("2a") + expect(password.version.class).to eq String + expect(password.cost).to equal(5) + expect(password.salt).to eql("$2a$05$CCCCCCCCCCCCCCCCCCCCC.") + expect(password.salt.class).to eq String + expect(password.checksum).to eq("E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW") + expect(password.checksum.class).to eq String + expect(password.to_s).to eql(@hash) + end + + specify "should raise an InvalidHashError when given an invalid hash" do + expect { BCrypt::Password.new('weedle') }.to raise_error(BCrypt::Errors::InvalidHash) + end +end + +describe "Comparing a hashed password with a secret" do + before :each do + @secret = "U*U" + @hash = "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW" + @password = BCrypt::Password.create(@secret) + end + + specify "should compare successfully to the original secret" do + expect((@password == @secret)).to be(true) + end + + specify "should compare unsuccessfully to anything besides original secret" do + expect((@password == "@secret")).to be(false) + end +end + +describe "Validating a generated salt" do + specify "should not accept an invalid salt" do + expect(BCrypt::Engine.valid_salt?("invalid")).to eq(false) + expect(BCrypt::Engine.valid_salt?("invalid\n#{BCrypt::Engine.generate_salt}\ninvalid")).to eq(false) + end + specify "should accept a valid salt" do + expect(BCrypt::Engine.valid_salt?(BCrypt::Engine.generate_salt)).to eq(true) + end +end + +describe "Validating a password hash" do + specify "should not accept an invalid password" do + expect(BCrypt::Password.valid_hash?("i_am_so_not_valid")).to be(false) + expect(BCrypt::Password.valid_hash?("invalid\n#{BCrypt::Password.create "i_am_so_valid"}\ninvalid")).to be(false) + end + specify "should accept a valid password" do + expect(BCrypt::Password.valid_hash?(BCrypt::Password.create "i_am_so_valid")).to be(true) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/spec_helper.rb b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/spec_helper.rb new file mode 100644 index 0000000..5488250 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/bcrypt-3.1.17/spec/spec_helper.rb @@ -0,0 +1,2 @@ +$:.unshift File.expand_path('../../lib', __FILE__) +require 'bcrypt' diff --git a/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/CHANGELOG b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/CHANGELOG new file mode 100644 index 0000000..bf3af18 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/CHANGELOG @@ -0,0 +1,65 @@ +== 0.8.1 / 2016-06-29 + * fix gemspec bug + +== 0.8.0 / 2016-06-27 + * add ColorizedString class + * update README file + * add rubocop.yml and follow style + * add italic mode + * remove interpreter warrnings + +== 0.7.7 / 2015-04-19 + * update gems + +== 0.7.6 / 2015-04-18 + * fix bugs + +== 0.7.5 / 2014-12-11 + * big code refactoring + * disable_colorization feature added + +== 0.7.4 / 2014-12-10 + * code cleanups + +== 0.7.3 / 2014-05-19 + * fix new line maching + +== 0.7.2 / 2014-04-08 + * tests cleanups + * gem release date fixed + +== 0.7.1 / 2014-04-02 + * handling wrong color values + +== 0.7.0 / 2014-03-12 + * refactored to use regexp pattern matching + * works with frozen strings + * works with concatenated string + +== 0.6.0 / 2013-09-25 + * code cleanups + * bold mode fixed + * STDOUT.isatty condition removed + * doc updated + * jeweler tasks removed + * Rakefile updated + +== 0.5.8 / 2009-12-02 + * code cleanups + * removed 'ruby -w' warnings + +== 0.5.7 / 2009-11-24 + * moved to github/gemcutter + * 1.9 compatible + +== 0.5.6 / 2007-08-27 + * rdocs Allison template + * cleanups + +== 0.5.5 / 2007-08-11 + * added effects methods + * README files + * new rake file + +== 0.5.0 / 2007-04-22 + * initial rewritten version diff --git a/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/LICENSE b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/LICENSE new file mode 100644 index 0000000..d7f1051 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/LICENSE @@ -0,0 +1,339 @@ +GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/README.md b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/README.md new file mode 100644 index 0000000..dc55167 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/README.md @@ -0,0 +1,105 @@ +colorize [![Gem Version](https://badge.fury.io/rb/colorize.svg)](http://badge.fury.io/rb/colorize) [![Build Status](https://travis-ci.org/fazibear/colorize.svg?branch=master)](https://travis-ci.org/fazibear/colorize) [![Code Climate](https://codeclimate.com/github/fazibear/colorize/badges/gpa.svg)](https://codeclimate.com/github/fazibear/colorize) [![Test Coverage](https://codeclimate.com/github/fazibear/colorize/badges/coverage.svg)](https://codeclimate.com/github/fazibear/colorize) +======== + +Ruby gem for colorizing text using ANSI escape sequences. +Extends `String` class or add a `ColorizedString` with methods to set text color, background color and text effects. + +modes +----- + +* `require 'colorize'` - Extends String class +* `require 'colorized_string'` - add ColorizedString class + +features +-------- + +* change string color +* change string background +* change string effect +* display color samples +* disable colorization + +usage +----- + +```ruby +require 'colorize' + +String.colors # return array of all possible colors names +String.modes # return array of all possible modes +String.color_samples # displays color samples in all combinations +String.disable_colorization # check if colorization is disabled +String.disable_colorization = false # enable colorization +String.disable_colorization false # enable colorization +String.disable_colorization = true # disable colorization +String.disable_colorization true # disable colorization + +puts "This is blue".colorize(:blue) +puts "This is light blue".colorize(:light_blue) +puts "This is also blue".colorize(:color => :blue) +puts "This is light blue with red background".colorize(:color => :light_blue, :background => :red) +puts "This is light blue with red background".colorize(:light_blue ).colorize( :background => :red) +puts "This is blue text on red".blue.on_red +puts "This is red on blue".colorize(:red).on_blue +puts "This is red on blue and underline".colorize(:red).on_blue.underline +puts "This is blue text on red".blue.on_red.blink +puts "This is uncolorized".blue.on_red.uncolorize +``` + +```ruby +require 'colorized_string' + +ColorizedString.colors # return array of all possible colors names +ColorizedString.modes # return array of all possible modes +ColorizedString.color_samples # displays color samples in all combinations +ColorizedString.disable_colorization # check if colorization is disabled +ColorizedString.disable_colorization = false # enable colorization +ColorizedString.disable_colorization false # enable colorization +ColorizedString.disable_colorization = true # disable colorization +ColorizedString.disable_colorization true # disable colorization + +puts ColorizedString["This is blue"].colorize(:blue) +puts ColorizedString["This is light blue"].colorize(:light_blue) +puts ColorizedString["This is also blue"].colorize(:color => :blue) +puts ColorizedString["This is light blue with red background"].colorize(:color => :light_blue, :background => :red) +puts ColorizedString["This is light blue with red background"].colorize(:light_blue ).colorize( :background => :red) +puts ColorizedString["This is blue text on red"].blue.on_red +puts ColorizedString["This is red on blue"].colorize(:red).on_blue +puts ColorizedString["This is red on blue and underline"].colorize(:red).on_blue.underline +puts ColorizedString["This is blue text on red"].blue.on_red.blink +puts ColorizedString["This is uncolorized"].blue.on_red.uncolorize + +puts ColorizedString.new("This is blue").blue +puts ColorizedString.new("This is light blue").colorize(:light_blue) +``` + +requirements +------------ + +* Win32/Console/ANSI (for Windows) + +install +------- + +* gem install colorize + +*Note:* You may need to use sudo to install gems + +license +------- + +Copyright (C) 2007-2016 Michał Kalbarczyk + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. diff --git a/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/Rakefile b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/Rakefile new file mode 100644 index 0000000..e1d05c5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/Rakefile @@ -0,0 +1,13 @@ +require 'rake/testtask' + +Rake::TestTask.new do |t| + t.libs << 'test' +end + +desc 'Run tests' +task :default do + ENV['TEST'] = 'test/test_colorize.rb' + Rake::Task[:test].execute + ENV['TEST'] = 'test/test_colorized_string.rb' + Rake::Task[:test].execute +end diff --git a/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/colorize.gemspec b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/colorize.gemspec new file mode 100644 index 0000000..de0f968 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/colorize.gemspec @@ -0,0 +1,36 @@ +Gem::Specification.new do |s| + s.name = 'colorize' + s.version = '0.8.1' + + s.authors = ['Michał Kalbarczyk'] + s.email = 'fazibear@gmail.com' + + s.date = Time.now.strftime('%Y-%m-%d') + + s.homepage = 'http://github.com/fazibear/colorize' + s.description = 'Extends String class or add a ColorizedString with methods to set text color, background color and text effects.' + s.summary = 'Ruby gem for colorizing text using ANSI escape sequences.' + s.license = 'GPL-2.0' + + s.require_paths = ['lib'] + + s.add_development_dependency 'rake', '~> 10.0' + s.add_development_dependency 'minitest', '~> 5.0' + s.add_development_dependency 'codeclimate-test-reporter', '~> 0.4' + + s.files = [ + 'LICENSE', + 'CHANGELOG', + 'README.md', + 'Rakefile', + 'colorize.gemspec', + 'lib/colorize.rb', + 'lib/colorized_string.rb', + 'lib/colorize/class_methods.rb', + 'lib/colorize/instance_methods.rb', + 'test/test_colorize.rb', + ] + s.test_files = [ + 'test/test_colorize.rb' + ] +end diff --git a/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorize.rb b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorize.rb new file mode 100644 index 0000000..b10455c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorize.rb @@ -0,0 +1,12 @@ +require File.expand_path('colorize/class_methods', File.dirname(__FILE__)) +require File.expand_path('colorize/instance_methods', File.dirname(__FILE__)) +# +# String class extension. +# +class String + extend Colorize::ClassMethods + include Colorize::InstanceMethods + + color_methods + modes_methods +end diff --git a/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorize/class_methods.rb b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorize/class_methods.rb new file mode 100644 index 0000000..25fc274 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorize/class_methods.rb @@ -0,0 +1,120 @@ +module Colorize + module ClassMethods + # + # Property to disable colorization + # + def disable_colorization(value = nil) + if value.nil? + if defined?(@disable_colorization) + @disable_colorization || false + else + false + end + else + @disable_colorization = (value || false) + end + end + + # + # Setter for disable colorization + # + def disable_colorization=(value) + @disable_colorization = (value || false) + end + + # + # Return array of available colors used by colorize + # + def colors + color_codes.keys + end + + # + # Return array of available modes used by colorize + # + def modes + mode_codes.keys + end + + # + # Display color samples + # + def color_samples + colors.permutation(2).each do |background, color| + sample_text = "#{color.inspect.rjust(15)} on #{background.inspect.ljust(15)}" + puts "#{new(sample_text).colorize(:color => color, :background => background)} #{sample_text}" + end + end + + # + # Method removed, raise NoMethodError + # + def color_matrix(_ = '') + fail NoMethodError, '#color_matrix method was removed, try #color_samples instead' + end + + # private + + # + # Color codes hash + # + def color_codes + { + :black => 0, :light_black => 60, + :red => 1, :light_red => 61, + :green => 2, :light_green => 62, + :yellow => 3, :light_yellow => 63, + :blue => 4, :light_blue => 64, + :magenta => 5, :light_magenta => 65, + :cyan => 6, :light_cyan => 66, + :white => 7, :light_white => 67, + :default => 9 + } + end + + # + # Mode codes hash + # + def mode_codes + { + :default => 0, # Turn off all attributes + :bold => 1, # Set bold mode + :italic => 3, # Set italic mode + :underline => 4, # Set underline mode + :blink => 5, # Set blink mode + :swap => 7, # Exchange foreground and background colors + :hide => 8 # Hide text (foreground color would be the same as background) + } + end + + # + # Generate color and on_color methods + # + def color_methods + colors.each do |key| + next if key == :default + + define_method key do + colorize(:color => key) + end + + define_method "on_#{key}" do + colorize(:background => key) + end + end + end + + # + # Generate modes methods + # + def modes_methods + modes.each do |key| + next if key == :default + + define_method key do + colorize(:mode => key) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorize/instance_methods.rb b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorize/instance_methods.rb new file mode 100644 index 0000000..5f7d017 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorize/instance_methods.rb @@ -0,0 +1,132 @@ +module Colorize + module InstanceMethods + # + # Change color of string + # + # Examples: + # + # puts "This is blue".colorize(:blue) + # puts "This is light blue".colorize(:light_blue) + # puts "This is also blue".colorize(:color => :blue) + # puts "This is light blue with red background".colorize(:color => :light_blue, :background => :red) + # puts "This is light blue with red background".colorize(:light_blue ).colorize( :background => :red) + # puts "This is blue text on red".blue.on_red + # puts "This is red on blue".colorize(:red).on_blue + # puts "This is red on blue and underline".colorize(:red).on_blue.underline + # puts "This is blue text on red".blue.on_red.blink + # puts "This is uncolorized".blue.on_red.uncolorize + # + def colorize(params) + return self if self.class.disable_colorization + require_windows_libs + scan_for_colors.inject(self.class.new) do |str, match| + colors_from_params(match, params) + defaults_colors(match) + str << "\033[#{match[0]};#{match[1]};#{match[2]}m#{match[3]}\033[0m" + end + end + + # + # Return uncolorized string + # + def uncolorize + scan_for_colors.inject(self.class.new) do |str, match| + str << match[3] + end + end + + # + # Return true if string is colorized + # + def colorized? + scan_for_colors.inject([]) do |colors, match| + colors << match.tap(&:pop) + end.flatten.compact.any? + end + + private + + # + # Set default colors + # + def defaults_colors(match) + match[0] ||= mode(:default) + match[1] ||= color(:default) + match[2] ||= background_color(:default) + end + + # + # Set color from params + # + def colors_from_params(match, params) + case params + when Hash then colors_from_hash(match, params) + when Symbol then color_from_symbol(match, params) + end + end + + # + # Set colors from params hash + # + def colors_from_hash(match, hash) + match[0] = mode(hash[:mode]) if mode(hash[:mode]) + match[1] = color(hash[:color]) if color(hash[:color]) + match[2] = background_color(hash[:background]) if background_color(hash[:background]) + end + + # + # Set color from params symbol + # + def color_from_symbol(match, symbol) + match[1] = color(symbol) if color(symbol) + end + + # + # Color for foreground (offset 30) + # + def color(color) + self.class.color_codes[color] + 30 if self.class.color_codes[color] + end + + # + # Color for background (offset 40) + # + def background_color(color) + self.class.color_codes[color] + 40 if self.class.color_codes[color] + end + + # + # Mode + # + def mode(mode) + self.class.mode_codes[mode] + end + + # + # Scan for colorized string + # + def scan_for_colors + scan(/\033\[([0-9;]+)m(.+?)\033\[0m|([^\033]+)/m).map do |match| + split_colors(match) + end + end + + def split_colors(match) + colors = (match[0] || '').split(';') + array = Array.new(3) + array[0], array[1], array[2] = colors if colors.length == 3 + array[1] = colors if colors.length == 1 + array[3] = match[1] || match[2] + array + end + + # + # Require windows libs + # + def require_windows_libs + require 'Win32/Console/ANSI' if RUBY_VERSION < '2.0.0' && RUBY_PLATFORM =~ /win32/ + rescue LoadError + raise 'You must gem install win32console to use colorize on Windows' + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorized_string.rb b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorized_string.rb new file mode 100644 index 0000000..e4ac2ce --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/lib/colorized_string.rb @@ -0,0 +1,19 @@ +require File.expand_path('colorize/class_methods', File.dirname(__FILE__)) +require File.expand_path('colorize/instance_methods', File.dirname(__FILE__)) +# +# ColorizedString class extension. +# +class ColorizedString < String + extend Colorize::ClassMethods + include Colorize::InstanceMethods + + color_methods + modes_methods + + # + # Sortcut to create ColorizedString with ColorizedString['test']. + # + def self.[](string) + ColorizedString.new(string) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/test/test_colorize.rb b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/test/test_colorize.rb new file mode 100644 index 0000000..b7f1d72 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/colorize-0.8.1/test/test_colorize.rb @@ -0,0 +1,164 @@ +require 'codeclimate-test-reporter' +CodeClimate::TestReporter.start + +require 'minitest/autorun' +require File.dirname(__FILE__) + '/../lib/colorize' + +class TestColorize < Minitest::Test + def test_blue_symbol + assert_equal 'This is blue'.colorize(:blue), + "\e[0;34;49mThis is blue\e[0m" + end + + def test_incorrect_symbol + assert_equal 'This is incorrect color'.colorize(:bold), + "\e[0;39;49mThis is incorrect color\e[0m" + end + + def test_incorrect_hash + assert_equal 'This is incorrect color'.colorize(:color => :bold), + "\e[0;39;49mThis is incorrect color\e[0m" + + assert_equal 'This is incorrect color'.colorize(:mode => :green), + "\e[0;39;49mThis is incorrect color\e[0m" + + assert_equal 'This is incorrect color'.colorize(:background => :bold), + "\e[0;39;49mThis is incorrect color\e[0m" + end + + def test_blue_hash + assert_equal 'This is also blue'.colorize(:color => :blue), + "\e[0;34;49mThis is also blue\e[0m" + end + + def test_light_blue_symbol + assert_equal 'This is light blue'.colorize(:light_blue), + "\e[0;94;49mThis is light blue\e[0m" + end + + def test_light_blue_with_red_background_hash + assert_equal 'This is light blue with red background'.colorize(:color => :light_blue, :background => :red), + "\e[0;94;41mThis is light blue with red background\e[0m" + end + + def test_light_blue_with_red_background_symbol_and_hash + assert_equal 'This is light blue with red background'.colorize(:light_blue).colorize(:background => :red), + "\e[0;94;41mThis is light blue with red background\e[0m" + end + + def test_blue_with_red_background_method + assert_equal 'This is blue text on red'.blue.on_red, + "\e[0;34;41mThis is blue text on red\e[0m" + end + + def test_red_with_blue_background_symbol_and_method + assert_equal 'This is red on blue'.colorize(:red).on_blue, + "\e[0;31;44mThis is red on blue\e[0m" + end + + def test_red_with_blue_background_and_underline_sumbol_and_methods + assert_equal 'This is red on blue and underline'.colorize(:red).on_blue.underline, + "\e[4;31;44mThis is red on blue and underline\e[0m" + end + + def test_blue_with_red_background_and_blink_methods + assert_equal 'This is blue text on red'.blue.on_red.blink, + "\e[5;34;41mThis is blue text on red\e[0m" + end + + def test_uncolorize + assert_equal 'This is uncolorized'.blue.on_red.uncolorize, + 'This is uncolorized' + end + + def test_colorized? + assert_equal 'Red'.red.colorized?, true + assert_equal 'Blue'.colorized?, false + assert_equal 'Green'.blue.green.uncolorize.colorized?, false + end + + def test_concatenated__colorize? + assert_equal "none #{'red'.red} none #{'blue'.blue} none".colorized?, true + assert_equal "none #{'red'.red} none #{'blue'.blue} none".uncolorize.colorized?, false + end + + def test_concatenated_strings_on_green + assert_equal "none #{'red'.red} none #{'blue'.blue} none".on_green, + "\e[0;39;42mnone \e[0m\e[0;31;42mred\e[0m\e[0;39;42m none \e[0m\e[0;34;42mblue\e[0m\e[0;39;42m none\e[0m" + end + + def test_concatenated_strings_uncolorize + assert_equal "none #{'red'.red} none #{'blue'.blue} none".uncolorize, + 'none red none blue none' + end + + def test_frozen_strings + assert_equal 'This is blue text on red'.freeze.blue.on_red.blink, + "\e[5;34;41mThis is blue text on red\e[0m" + end + + def test_new_line + assert_equal "This is blue\ntext on red".freeze.blue.on_red.blink, + "\e[5;34;41mThis is blue\ntext on red\e[0m" + end + + def test_disable_colorization_with_= + String.disable_colorization = true + assert_equal String.disable_colorization, true + String.disable_colorization = false + end + + def test_disable_colorization_with_method + String.disable_colorization true + assert_equal String.disable_colorization, true + String.disable_colorization false + end + + def test_string_disable_colorization_with_= + String.disable_colorization = true + + assert_equal String.disable_colorization, true + + assert_equal 'This is blue after disabling'.blue, + 'This is blue after disabling' + + String.disable_colorization = false + + assert_equal 'This is blue after enabling'.colorize(:blue), + "\e[0;34;49mThis is blue after enabling\e[0m" + end + + def test_string_disable_colorization_with_method + assert_equal 'This is blue before disabling'.colorize(:blue), + "\e[0;34;49mThis is blue before disabling\e[0m" + + String.disable_colorization true + + assert_equal String.disable_colorization, true + + assert_equal 'This is blue after disabling'.blue, + 'This is blue after disabling' + + String.disable_colorization false + + assert_equal 'This is blue after enabling'.colorize(:blue), + "\e[0;34;49mThis is blue after enabling\e[0m" + end + + def test_already_colored_string_with_one_value + assert_equal "\e[31mThis is red\e[0m".red, + 'This is red'.red + end + + def test_color_matrix_method + assert_raises NoMethodError do + String.color_matrix + end + end + + def test_color_samples_method + assert_output do + String.color_samples + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/CHANGELOG.md b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/CHANGELOG.md new file mode 100644 index 0000000..bad0044 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/CHANGELOG.md @@ -0,0 +1,542 @@ +## Current + +## Release v1.1.10 + +concurrent-ruby: + +* (#951) Set the Ruby compatibility version at 2.2 +* (#939, #933) The `caller_runs` fallback policy no longer blocks reads from the job queue by worker threads +* (#938, #761, #652) You can now explicitly `prune_pool` a thread pool (Sylvain Joyeux) +* (#937, #757, #670) We switched the Yahoo stock API for demos to Alpha Vantage (Gustavo Caso) +* (#932, #931) We changed how `SafeTaskExecutor` handles local jump errors (Aaron Jensen) +* (#927) You can use keyword arguments in your initialize when using `Async` (Matt Larraz) +* (#926, #639) We removed timeout from `TimerTask` because it wasn't sound, and now it's a no-op with a warning (Jacob Atzen) +* (#919) If you double-lock a re-entrant read-write lock, we promote to locked for writing (zp yuan) +* (#915) `monotonic_time` now accepts an optional unit parameter, as Ruby's `clock_gettime` (Jean Boussier) + +## Release v1.1.9 (5 Jun 2021) + +concurrent-ruby: + +* (#866) Child promise state not set to :pending immediately after #execute when parent has completed +* (#905, #872) Fix RubyNonConcurrentPriorityQueue#delete method +* (2df0337d) Make sure locks are not shared on shared when objects are dup/cloned +* (#900, #906, #796, #847, #911) Fix Concurrent::Set tread-safety issues on CRuby +* (#907) Add new ConcurrentMap backend for TruffleRuby + +## Release v1.1.8 (20 January 2021) + +concurrent-ruby: + +* (#885) Fix race condition in TVar for stale reads +* (#884) RubyThreadLocalVar: Do not iterate over hash which might conflict with new pair addition + +## Release v1.1.7 (6 August 2020) + +concurrent-ruby: + +* (#879) Consider falsy value on `Concurrent::Map#compute_if_absent` for fast non-blocking path +* (#876) Reset Async queue on forking, makes Async fork-safe +* (#856) Avoid running problematic code in RubyThreadLocalVar on MRI that occasionally results in segfault +* (#853) Introduce ThreadPoolExecutor without a Queue + +## Release v1.1.6, edge v0.6.0 (10 Feb 2020) + +concurrent-ruby: + +* (#841) Concurrent.disable_at_exit_handlers! is no longer needed and was deprecated. +* (#841) AbstractExecutorService#auto_terminate= was deprecated and has no effect. + Set :auto_terminate option instead when executor is initialized. + +## Release v1.1.6.pre1, edge v0.6.0.pre1 (26 Jan 2020) + +concurrent-ruby: + +* (#828) Allow to name executors, the name is also used to name their threads +* (#838) Implement #dup and #clone for structs +* (#821) Safer finalizers for thread local variables +* Documentation fixes +* (#814) Use Ruby's Etc.nprocessors if available +* (#812) Fix directory structure not to mess with packaging tools +* (#840) Fix termination of pools on JRuby + +concurrent-ruby-edge: + +* Add WrappingExecutor (#830) + +## Release v1.1.5, edge v0.5.0 (10 Mar 2019) + +concurrent-ruby: + +* fix potential leak of context on JRuby and Java 7 + +concurrent-ruby-edge: + +* Add finalized Concurrent::Cancellation +* Add finalized Concurrent::Throttle +* Add finalized Concurrent::Promises::Channel +* Add new Concurrent::ErlangActor + +## Release v1.1.4 (14 Dec 2018) + +* (#780) Remove java_alias of 'submit' method of Runnable to let executor service work on java 11 +* (#776) Fix NameError on defining a struct with a name which is already taken in an ancestor + +## Release v1.1.3 (7 Nov 2018) + +* (#775) fix partial require of the gem (although not officially supported) + +## Release v1.1.2 (6 Nov 2018) + +* (#773) more defensive 1.9.3 support + +## Release v1.1.1, edge v0.4.1 (1 Nov 2018) + +* (#768) add support for 1.9.3 back + +## Release v1.1.0, edge v0.4.0 (31 OCt 2018) (yanked) + +* (#768) yanked because of issues with removed 1.9.3 support + +## Release v1.1.0.pre2, edge v0.4.0.pre2 (18 Sep 2018) + +concurrent-ruby: + +* fixed documentation and README links +* fix Set for TruffleRuby and Rubinius +* use properly supported TruffleRuby APIs + +concurrent-ruby-edge: + +* add Promises.zip_futures_over_on + +## Release v1.1.0.pre1, edge v0.4.0.pre1 (15 Aug 2018) + +concurrent-ruby: + +* requires at least Ruby 2.0 +* [Promises](http://ruby-concurrency.github.io/concurrent-ruby/1.1.0/Concurrent/Promises.html) + are moved from `concurrent-ruby-edge` to `concurrent-ruby` +* Add support for TruffleRuby + * (#734) Fix Array/Hash/Set construction broken on TruffleRuby + * AtomicReference fixed +* CI stabilization +* remove sharp dependency edge -> core +* remove warnings +* documentation updates +* Exchanger is no longer documented as edge since it was already available in + `concurrent-ruby` +* (#644) Fix Map#each and #each_pair not returning enumerator outside of MRI +* (#659) Edge promises fail during error handling +* (#741) Raise on recursive Delay#value call +* (#727) #717 fix global IO executor on JRuby +* (#740) Drop support for CRuby 1.9, JRuby 1.7, Rubinius. +* (#737) Move AtomicMarkableReference out of Edge +* (#708) Prefer platform specific memory barriers +* (#735) Fix wrong expected exception in channel spec assertion +* (#729) Allow executor option in `Promise#then` +* (#725) fix timeout check to use timeout_interval +* (#719) update engine detection +* (#660) Add specs for Promise#zip/Promise.zip ordering +* (#654) Promise.zip execution changes +* (#666) Add thread safe set implementation +* (#651) #699 #to_s, #inspect should not output negative object IDs. +* (#685) Avoid RSpec warnings about raise_error +* (#680) Avoid RSpec monkey patching, persist spec results locally, use RSpec + v3.7.0 +* (#665) Initialize the monitor for new subarrays on Rubinius +* (#661) Fix error handling in edge promises + +concurrent-ruby-edge: + +* (#659) Edge promises fail during error handling +* Edge files clearly separated in `lib-edge` +* added ReInclude + +## Release v1.0.5, edge v0.3.1 (26 Feb 2017) + +concurrent-ruby: + +* Documentation for Event and Semaphore +* Use Unsafe#fullFence and #loadFence directly since the shortcuts were removed in JRuby +* Do not depend on org.jruby.util.unsafe.UnsafeHolder + +concurrent-ruby-edge: + +* (#620) Actors on Pool raise an error +* (#624) Delayed promises did not interact correctly with flatting + * Fix arguments yielded by callback methods +* Overridable default executor in promises factory methods +* Asking actor to terminate will always resolve to `true` + +## Release v1.0.4, edge v0.3.0 (27 Dec 2016) + +concurrent-ruby: + +* Nothing + +concurrent-ruby-edge: + +* New promises' API renamed, lots of improvements, edge bumped to 0.3.0 + * **Incompatible** with previous 0.2.3 version + * see https://github.com/ruby-concurrency/concurrent-ruby/pull/522 + +## Release v1.0.3 (17 Dec 2016) + +* Trigger execution of flattened delayed futures +* Avoid forking for processor_count if possible +* Semaphore Mutex and JRuby parity +* Adds Map#each as alias to Map#each_pair +* Fix uninitialized instance variables +* Make Fixnum, Bignum merger ready +* Allows Promise#then to receive an executor +* TimerSet now survives a fork +* Reject promise on any exception +* Allow ThreadLocalVar to be initialized with a block +* Support Alpha with `Concurrent::processor_count` +* Fixes format-security error when compiling ruby_193_compatible.h +* Concurrent::Atom#swap fixed: reraise the exceptions from block + +## Release v1.0.2 (2 May 2016) + +* Fix bug with `Concurrent::Map` MRI backend `#inspect` method +* Fix bug with `Concurrent::Map` MRI backend using `Hash#value?` +* Improved documentation and examples +* Minor updates to Edge + +## Release v1.0.1 (27 February 2016) + +* Fix "uninitialized constant Concurrent::ReentrantReadWriteLock" error. +* Better handling of `autoload` vs. `require`. +* Improved API for Edge `Future` zipping. +* Fix reference leak in Edge `Future` constructor . +* Fix bug which prevented thread pools from surviving a `fork`. +* Fix bug in which `TimerTask` did not correctly specify all its dependencies. +* Improved support for JRuby+Truffle +* Improved error messages. +* Improved documentation. +* Updated README and CONTRIBUTING. + +## Release v1.0.0 (13 November 2015) + +* Rename `attr_volatile_with_cas` to `attr_atomic` +* Add `clear_each` to `LockFreeStack` +* Update `AtomicReference` documentation +* Further updates and improvements to the synchronization layer. +* Performance and memory usage performance with `Actor` logging. +* Fixed `ThreadPoolExecutor` task count methods. +* Improved `Async` performance for both short and long-lived objects. +* Fixed bug in `LockFreeLinkedSet`. +* Fixed bug in which `Agent#await` triggered a validation failure. +* Further `Channel` updates. +* Adopted a project Code of Conduct +* Cleared interpreter warnings +* Fixed bug in `ThreadPoolExecutor` task count methods +* Fixed bug in 'LockFreeLinkedSet' +* Improved Java extension loading +* Handle Exception children in Edge::Future +* Continued improvements to channel +* Removed interpreter warnings. +* Shared constants now in `lib/concurrent/constants.rb` +* Refactored many tests. +* Improved synchronization layer/memory model documentation. +* Bug fix in Edge `Future#flat` +* Brand new `Channel` implementation in Edge gem. +* Simplification of `RubySingleThreadExecutor` +* `Async` improvements + - Each object uses its own `SingleThreadExecutor` instead of the global thread pool. + - No longers supports executor injection + - Much better documentation +* `Atom` updates + - No longer `Dereferenceable` + - Now `Observable` + - Added a `#reset` method +* Brand new `Agent` API and implementation. Now functionally equivalent to Clojure. +* Continued improvements to the synchronization layer +* Merged in the `thread_safe` gem + - `Concurrent::Array` + - `Concurrent::Hash` + - `Concurrent::Map` (formerly ThreadSafe::Cache) + - `Concurrent::Tuple` +* Minor improvements to Concurrent::Map +* Complete rewrite of `Exchanger` +* Removed all deprecated code (classes, methods, constants, etc.) +* Updated Agent, MutexAtomic, and BufferedChannel to inherit from Synchronization::Object. +* Many improved tests +* Some internal reorganization + +## Release v0.9.1 (09 August 2015) + +* Fixed a Rubiniux bug in synchronization object +* Fixed all interpreter warnings (except circular references) +* Fixed require statements when requiring `Atom` alone +* Significantly improved `ThreadLocalVar` on non-JRuby platforms +* Fixed error handling in Edge `Concurrent.zip` +* `AtomicFixnum` methods `#increment` and `#decrement` now support optional delta +* New `AtomicFixnum#update` method +* Minor optimizations in `ReadWriteLock` +* New `ReentrantReadWriteLock` class +* `ThreadLocalVar#bind` method is now public +* Refactored many tests + +## Release v0.9.0 (10 July 2015) + +* Updated `AtomicReference` + - `AtomicReference#try_update` now simply returns instead of raising exception + - `AtomicReference#try_update!` was added to raise exceptions if an update + fails. Note: this is the same behavior as the old `try_update` +* Pure Java implementations of + - `AtomicBoolean` + - `AtomicFixnum` + - `Semaphore` +* Fixed bug when pruning Ruby thread pools +* Fixed bug in time calculations within `ScheduledTask` +* Default `count` in `CountDownLatch` to 1 +* Use monotonic clock for all timers via `Concurrent.monotonic_time` + - Use `Process.clock_gettime(Process::CLOCK_MONOTONIC)` when available + - Fallback to `java.lang.System.nanoTime()` on unsupported JRuby versions + - Pure Ruby implementation for everything else + - Effects `Concurrent.timer`, `Concurrent.timeout`, `TimerSet`, `TimerTask`, and `ScheduledTask` +* Deprecated all clock-time based timer scheduling + - Only support scheduling by delay + - Effects `Concurrent.timer`, `TimerSet`, and `ScheduledTask` +* Added new `ReadWriteLock` class +* Consistent `at_exit` behavior for Java and Ruby thread pools. +* Added `at_exit` handler to Ruby thread pools (already in Java thread pools) + - Ruby handler stores the object id and retrieves from `ObjectSpace` + - JRuby disables `ObjectSpace` by default so that handler stores the object reference +* Added a `:stop_on_exit` option to thread pools to enable/disable `at_exit` handler +* Updated thread pool docs to better explain shutting down thread pools +* Simpler `:executor` option syntax for all abstractions which support this option +* Added `Executor#auto_terminate?` predicate method (for thread pools) +* Added `at_exit` handler to `TimerSet` +* Simplified auto-termination of the global executors + - Can now disable auto-termination of global executors + - Added shutdown/kill/wait_for_termination variants for global executors +* Can now disable auto-termination for *all* executors (the nuclear option) +* Simplified auto-termination of the global executors +* Deprecated terms "task pool" and "operation pool" + - New terms are "io executor" and "fast executor" + - New functions added with new names + - Deprecation warnings added to functions referencing old names +* Moved all thread pool related functions from `Concurrent::Configuration` to `Concurrent` + - Old functions still exist with deprecation warnings + - New functions have updated names as appropriate +* All high-level abstractions default to the "io executor" +* Fixed bug in `Actor` causing it to prematurely warm global thread pools on gem load + - This also fixed a `RejectedExecutionError` bug when running with minitest/autorun via JRuby +* Moved global logger up to the `Concurrent` namespace and refactored the code +* Optimized the performance of `Delay` + - Fixed a bug in which no executor option on construction caused block execution on a global thread pool +* Numerous improvements and bug fixes to `TimerSet` +* Fixed deadlock of `Future` when the handler raises Exception +* Added shared specs for more classes +* New concurrency abstractions including: + - `Atom` + - `Maybe` + - `ImmutableStruct` + - `MutableStruct` + - `SettableStruct` +* Created an Edge gem for unstable abstractions including + - `Actor` + - `Agent` + - `Channel` + - `Exchanger` + - `LazyRegister` + - **new Future Framework** - unified + implementation of Futures and Promises which combines Features of previous `Future`, + `Promise`, `IVar`, `Event`, `Probe`, `dataflow`, `Delay`, `TimerTask` into single framework. It uses extensively + new synchronization layer to make all the paths **lock-free** with exception of blocking threads on `#wait`. + It offers better performance and does not block threads when not required. +* Actor framework changes: + - fixed reset loop in Pool + - Pool can use any actor as a worker, abstract worker class is no longer needed. + - Actor events not have format `[:event_name, *payload]` instead of just the Symbol. + - Actor now uses new Future/Promise Framework instead of `IVar` for better interoperability + - Behaviour definition array was simplified to `[BehaviourClass1, [BehaviourClass2, *initialization_args]]` + - Linking behavior responds to :linked message by returning array of linked actors + - Supervised behavior is removed in favour of just Linking + - RestartingContext is supervised by default now, `supervise: true` is not required any more + - Events can be private and public, so far only difference is that Linking will + pass to linked actors only public messages. Adding private :restarting and + :resetting events which are send before the actor restarts or resets allowing + to add callbacks to cleanup current child actors. + - Print also object_id in Reference to_s + - Add AbstractContext#default_executor to be able to override executor class wide + - Add basic IO example + - Documentation somewhat improved + - All messages should have same priority. It's now possible to send `actor << job1 << job2 << :terminate!` and + be sure that both jobs are processed first. +* Refactored `Channel` to use newer synchronization objects +* Added `#reset` and `#cancel` methods to `TimerSet` +* Added `#cancel` method to `Future` and `ScheduledTask` +* Refactored `TimerSet` to use `ScheduledTask` +* Updated `Async` with a factory that initializes the object +* Deprecated `Concurrent.timer` and `Concurrent.timeout` +* Reduced max threads on pure-Ruby thread pools (abends around 14751 threads) +* Moved many private/internal classes/modules into "namespace" modules +* Removed brute-force killing of threads in tests +* Fixed a thread pool bug when the operating system cannot allocate more threads + +## Release v0.8.0 (25 January 2015) + +* C extension for MRI have been extracted into the `concurrent-ruby-ext` companion gem. + Please see the README for more detail. +* Better variable isolation in `Promise` and `Future` via an `:args` option +* Continued to update intermittently failing tests + +## Release v0.7.2 (24 January 2015) + +* New `Semaphore` class based on [java.util.concurrent.Semaphore](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html) +* New `Promise.all?` and `Promise.any?` class methods +* Renamed `:overflow_policy` on thread pools to `:fallback_policy` +* Thread pools still accept the `:overflow_policy` option but display a warning +* Thread pools now implement `fallback_policy` behavior when not running (rather than universally rejecting tasks) +* Fixed minor `set_deref_options` constructor bug in `Promise` class +* Fixed minor `require` bug in `ThreadLocalVar` class +* Fixed race condition bug in `TimerSet` class +* Fixed race condition bug in `TimerSet` class +* Fixed signal bug in `TimerSet#post` method +* Numerous non-functional updates to clear warning when running in debug mode +* Fixed more intermittently failing tests +* Tests now run on new Travis build environment +* Multiple documentation updates + +## Release v0.7.1 (4 December 2014) + +Please see the [roadmap](https://github.com/ruby-concurrency/concurrent-ruby/issues/142) for more information on the next planned release. + +* Added `flat_map` method to `Promise` +* Added `zip` method to `Promise` +* Fixed bug with logging in `Actor` +* Improvements to `Promise` tests +* Removed actor-experimental warning +* Added an `IndirectImmediateExecutor` class +* Allow disabling auto termination of global executors +* Fix thread leaking in `ThreadLocalVar` (uses `Ref` gem on non-JRuby systems) +* Fix thread leaking when pruning pure-Ruby thread pools +* Prevent `Actor` from using an `ImmediateExecutor` (causes deadlock) +* Added missing synchronizations to `TimerSet` +* Fixed bug with return value of `Concurrent::Actor::Utils::Pool#ask` +* Fixed timing bug in `TimerTask` +* Fixed bug when creating a `JavaThreadPoolExecutor` with minimum pool size of zero +* Removed confusing warning when not using native extenstions +* Improved documentation + +## Release v0.7.0 (13 August 2014) + +* Merge the [atomic](https://github.com/ruby-concurrency/atomic) gem + - Pure Ruby `MutexAtomic` atomic reference class + - Platform native atomic reference classes `CAtomic`, `JavaAtomic`, and `RbxAtomic` + - Automated [build process](https://github.com/ruby-concurrency/rake-compiler-dev-box) + - Fat binary releases for [multiple platforms](https://rubygems.org/gems/concurrent-ruby/versions) including Windows (32/64), Linux (32/64), OS X (64-bit), Solaris (64-bit), and JRuby +* C native `CAtomicBoolean` +* C native `CAtomicFixnum` +* Refactored intermittently failing tests +* Added `dataflow!` and `dataflow_with!` methods to match `Future#value!` method +* Better handling of timeout in `Agent` +* Actor Improvements + - Fine-grained implementation using chain of behaviors. Each behavior is responsible for single aspect like: `Termination`, `Pausing`, `Linking`, `Supervising`, etc. Users can create custom Actors easily based on their needs. + - Supervision was added. `RestartingContext` will pause on error waiting on its supervisor to decide what to do next ( options are `:terminate!`, `:resume!`, `:reset!`, `:restart!`). Supervising behavior also supports strategies `:one_for_one` and `:one_for_all`. + - Linking was added to be able to monitor actor's events like: `:terminated`, `:paused`, `:restarted`, etc. + - Dead letter routing added. Rejected envelopes are collected in a configurable actor (default: `Concurrent::Actor.root.ask!(:dead_letter_routing)`) + - Old `Actor` class removed and replaced by new implementation previously called `Actress`. `Actress` was kept as an alias for `Actor` to keep compatibility. + - `Utils::Broadcast` actor which allows Publish–subscribe pattern. +* More executors for managing serialized operations + - `SerializedExecution` mixin module + - `SerializedExecutionDelegator` for serializing *any* executor +* Updated `Async` with serialized execution +* Updated `ImmediateExecutor` and `PerThreadExecutor` with full executor service lifecycle +* Added a `Delay` to root `Actress` initialization +* Minor bug fixes to thread pools +* Refactored many intermittently failing specs +* Removed Java interop warning `executor.rb:148 warning: ambiguous Java methods found, using submit(java.lang.Runnable)` +* Fixed minor bug in `RubyCachedThreadPool` overflow policy +* Updated tests to use [RSpec 3.0](http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3) +* Removed deprecated `Actor` class +* Better support for Rubinius + +## Release v0.6.1 (14 June 2014) + +* Many improvements to `Concurrent::Actress` +* Bug fixes to `Concurrent::RubyThreadPoolExecutor` +* Fixed several brittle tests +* Moved documentation to http://ruby-concurrency.github.io/concurrent-ruby/frames.html + +## Release v0.6.0 (25 May 2014) + +* Added `Concurrent::Observable` to encapsulate our thread safe observer sets +* Improvements to new `Channel` +* Major improvements to `CachedThreadPool` and `FixedThreadPool` +* Added `SingleThreadExecutor` +* Added `Current::timer` function +* Added `TimerSet` executor +* Added `AtomicBoolean` +* `ScheduledTask` refactoring +* Pure Ruby and JRuby-optimized `PriorityQueue` classes +* Updated `Agent` behavior to more closely match Clojure +* Observer sets support block callbacks to the `add_observer` method +* New algorithm for thread creation in `RubyThreadPoolExecutor` +* Minor API updates to `Event` +* Rewritten `TimerTask` now an `Executor` instead of a `Runnable` +* Fixed many brittle specs +* Renamed `FixedThreadPool` and `CachedThreadPool` to `RubyFixedThreadPool` and `RubyCachedThreadPool` +* Created JRuby optimized `JavaFixedThreadPool` and `JavaCachedThreadPool` +* Consolidated fixed thread pool tests into `spec/concurrent/fixed_thread_pool_shared.rb` and `spec/concurrent/cached_thread_pool_shared.rb` +* `FixedThreadPool` now subclasses `RubyFixedThreadPool` or `JavaFixedThreadPool` as appropriate +* `CachedThreadPool` now subclasses `RubyCachedThreadPool` or `JavaCachedThreadPool` as appropriate +* New `Delay` class +* `Concurrent::processor_count` helper function +* New `Async` module +* Renamed `NullThreadPool` to `PerThreadExecutor` +* Deprecated `Channel` (we are planning a new implementation based on [Go](http://golangtutorials.blogspot.com/2011/06/channels-in-go.html)) +* Added gem-level [configuration](http://robots.thoughtbot.com/mygem-configure-block) +* Deprecated `$GLOBAL_THREAD_POOL` in lieu of gem-level configuration +* Removed support for Ruby [1.9.2](https://www.ruby-lang.org/en/news/2013/12/17/maintenance-of-1-8-7-and-1-9-2/) +* New `RubyThreadPoolExecutor` and `JavaThreadPoolExecutor` classes +* All thread pools now extend the appropriate thread pool executor classes +* All thread pools now support `:overflow_policy` (based on Java's [reject policies](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html)) +* Deprecated `UsesGlobalThreadPool` in lieu of explicit `:executor` option (dependency injection) on `Future`, `Promise`, and `Agent` +* Added `Concurrent::dataflow_with(executor, *inputs)` method to support executor dependency injection for dataflow +* Software transactional memory with `TVar` and `Concurrent::atomically` +* First implementation of [new, high-performance](https://github.com/ruby-concurrency/concurrent-ruby/pull/49) `Channel` +* `Actor` is deprecated in favor of new experimental actor implementation [#73](https://github.com/ruby-concurrency/concurrent-ruby/pull/73). To avoid namespace collision it is living in `Actress` namespace until `Actor` is removed in next release. + +## Release v0.5.0 + +This is the most significant release of this gem since its inception. This release includes many improvements and optimizations. It also includes several bug fixes. The major areas of focus for this release were: + +* Stability improvements on Ruby versions with thread-level parallelism ([JRuby](http://jruby.org/) and [Rubinius](http://rubini.us/)) +* Creation of new low-level concurrency abstractions +* Internal refactoring to use the new low-level abstractions + +Most of these updates had no effect on the gem API. There are a few notable exceptions which were unavoidable. Please read the [release notes](API-Updates-in-v0.5.0) for more information. + +Specific changes include: + +* New class `IVar` +* New class `MVar` +* New class `ThreadLocalVar` +* New class `AtomicFixnum` +* New class method `dataflow` +* New class `Condition` +* New class `CountDownLatch` +* New class `DependencyCounter` +* New class `SafeTaskExecutor` +* New class `CopyOnNotifyObserverSet` +* New class `CopyOnWriteObserverSet` +* `Future` updated with `execute` API +* `ScheduledTask` updated with `execute` API +* New `Promise` API +* `Future` now extends `IVar` +* `Postable#post?` now returns an `IVar` +* Thread safety fixes to `Dereferenceable` +* Thread safety fixes to `Obligation` +* Thread safety fixes to `Supervisor` +* Thread safety fixes to `Event` +* Various other thread safety (race condition) fixes +* Refactored brittle tests +* Implemented pending tests +* Added JRuby and Rubinius as Travis CI build targets +* Added [CodeClimate](https://codeclimate.com/) code review +* Improved YARD documentation diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/Gemfile b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/Gemfile new file mode 100644 index 0000000..f9ef172 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/Gemfile @@ -0,0 +1,37 @@ +source 'https://rubygems.org' + +require File.join(File.dirname(__FILE__), 'lib/concurrent-ruby/concurrent/version') +require File.join(File.dirname(__FILE__ ), 'lib/concurrent-ruby-edge/concurrent/edge/version') +require File.join(File.dirname(__FILE__ ), 'lib/concurrent-ruby/concurrent/utility/engine') + +no_path = ENV['NO_PATH'] +options = no_path ? {} : { path: '.' } + +gem 'concurrent-ruby', Concurrent::VERSION, options +gem 'concurrent-ruby-edge', Concurrent::EDGE_VERSION, options +gem 'concurrent-ruby-ext', Concurrent::VERSION, options.merge(platform: :mri) + +group :development do + gem 'rake', '~> 13.0' + gem 'rake-compiler', '~> 1.0', '>= 1.0.7' + gem 'rake-compiler-dock', '~> 1.0' + gem 'pry', '~> 0.11', platforms: :mri +end + +group :documentation, optional: true do + gem 'yard', '~> 0.9.0', require: false + gem 'redcarpet', '~> 3.0', platforms: :mri # understands github markdown + gem 'md-ruby-eval', '~> 0.6' +end + +group :testing do + gem 'rspec', '~> 3.7' + gem 'timecop', '~> 0.9' + gem 'sigdump', require: false +end + +# made opt-in since it will not install on jruby 1.7 +group :coverage, optional: !ENV['COVERAGE'] do + gem 'simplecov', '~> 0.16.0', require: false + gem 'coveralls', '~> 0.8.2', require: false +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/LICENSE.txt b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/LICENSE.txt new file mode 100644 index 0000000..1026f28 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/LICENSE.txt @@ -0,0 +1,21 @@ +Copyright (c) Jerry D'Antonio -- released under the MIT license. + +http://www.opensource.org/licenses/mit-license.php + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/README.md b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/README.md new file mode 100644 index 0000000..767f009 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/README.md @@ -0,0 +1,404 @@ +# Concurrent Ruby + +[![Gem Version](https://badge.fury.io/rb/concurrent-ruby.svg)](http://badge.fury.io/rb/concurrent-ruby) +[![License](https://img.shields.io/badge/license-MIT-green.svg)](http://opensource.org/licenses/MIT) +[![Gitter chat](https://img.shields.io/badge/IRC%20(gitter)-devs%20%26%20users-brightgreen.svg)](https://gitter.im/ruby-concurrency/concurrent-ruby) + +Modern concurrency tools for Ruby. Inspired by +[Erlang](http://www.erlang.org/doc/reference_manual/processes.html), +[Clojure](http://clojure.org/concurrent_programming), +[Scala](http://akka.io/), +[Haskell](http://www.haskell.org/haskellwiki/Applications_and_libraries/Concurrency_and_parallelism#Concurrent_Haskell), +[F#](http://blogs.msdn.com/b/dsyme/archive/2010/02/15/async-and-parallel-design-patterns-in-f-part-3-agents.aspx), +[C#](http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx), +[Java](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html), +and classic concurrency patterns. + + + +The design goals of this gem are: + +* Be an 'unopinionated' toolbox that provides useful utilities without debating which is better + or why +* Remain free of external gem dependencies +* Stay true to the spirit of the languages providing inspiration +* But implement in a way that makes sense for Ruby +* Keep the semantics as idiomatic Ruby as possible +* Support features that make sense in Ruby +* Exclude features that don't make sense in Ruby +* Be small, lean, and loosely coupled +* Thread-safety +* Backward compatibility + +## Contributing + +**This gem depends on +[contributions](https://github.com/ruby-concurrency/concurrent-ruby/graphs/contributors) and we +appreciate your help. Would you like to contribute? Great! Have a look at +[issues with `looking-for-contributor` label](https://github.com/ruby-concurrency/concurrent-ruby/issues?q=is%3Aissue+is%3Aopen+label%3Alooking-for-contributor).** And if you pick something up let us know on the issue. + +You can also get started by triaging issues which may include reproducing bug reports or asking for vital information, such as version numbers or reproduction instructions. If you would like to start triaging issues, one easy way to get started is to [subscribe to concurrent-ruby on CodeTriage](https://www.codetriage.com/ruby-concurrency/concurrent-ruby). [![Open Source Helpers](https://www.codetriage.com/ruby-concurrency/concurrent-ruby/badges/users.svg)](https://www.codetriage.com/ruby-concurrency/concurrent-ruby) + +## Thread Safety + +*Concurrent Ruby makes one of the strongest thread safety guarantees of any Ruby concurrency +library, providing consistent behavior and guarantees on all four of the main Ruby interpreters +(MRI/CRuby, JRuby, Rubinius, TruffleRuby).* + +Every abstraction in this library is thread safe. Specific thread safety guarantees are documented +with each abstraction. + +It is critical to remember, however, that Ruby is a language of mutable references. *No* +concurrency library for Ruby can ever prevent the user from making thread safety mistakes (such as +sharing a mutable object between threads and modifying it on both threads) or from creating +deadlocks through incorrect use of locks. All the library can do is provide safe abstractions which +encourage safe practices. Concurrent Ruby provides more safe concurrency abstractions than any +other Ruby library, many of which support the mantra of +["Do not communicate by sharing memory; instead, share memory by communicating"](https://blog.golang.org/share-memory-by-communicating). +Concurrent Ruby is also the only Ruby library which provides a full suite of thread safe and +immutable variable types and data structures. + +We've also initiated discussion to document [memory model](docs-source/synchronization.md) of Ruby which +would provide consistent behaviour and guarantees on all four of the main Ruby interpreters +(MRI/CRuby, JRuby, Rubinius, TruffleRuby). + +## Features & Documentation + +**The primary site for documentation is the automatically generated +[API documentation](http://ruby-concurrency.github.io/concurrent-ruby/index.html) which is up to +date with latest release.** This readme matches the master so may contain new stuff not yet +released. + +We also have a [IRC (gitter)](https://gitter.im/ruby-concurrency/concurrent-ruby). + +### Versioning + +* `concurrent-ruby` uses [Semantic Versioning](http://semver.org/) +* `concurrent-ruby-ext` has always same version as `concurrent-ruby` +* `concurrent-ruby-edge` will always be 0.y.z therefore following + [point 4](http://semver.org/#spec-item-4) applies *"Major version zero + (0.y.z) is for initial development. Anything may change at any time. The + public API should not be considered stable."* However we additionally use + following rules: + * Minor version increment means incompatible changes were made + * Patch version increment means only compatible changes were made + + +#### General-purpose Concurrency Abstractions + +* [Async](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Async.html): + A mixin module that provides simple asynchronous behavior to a class. Loosely based on Erlang's + [gen_server](http://www.erlang.org/doc/man/gen_server.html). +* [ScheduledTask](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/ScheduledTask.html): + Like a Future scheduled for a specific future time. +* [TimerTask](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/TimerTask.html): + A Thread that periodically wakes up to perform work at regular intervals. +* [Promises](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Promises.html): + Unified implementation of futures and promises which combines features of previous `Future`, + `Promise`, `IVar`, `Event`, `dataflow`, `Delay`, and (partially) `TimerTask` into a single + framework. It extensively uses the new synchronization layer to make all the features + **non-blocking** and **lock-free**, with the exception of obviously blocking operations like + `#wait`, `#value`. It also offers better performance. + +#### Thread-safe Value Objects, Structures, and Collections + +Collection classes that were originally part of the (deprecated) `thread_safe` gem: + +* [Array](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Array.html) A thread-safe + subclass of Ruby's standard [Array](http://ruby-doc.org/core/Array.html). +* [Hash](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Hash.html) A thread-safe + subclass of Ruby's standard [Hash](http://ruby-doc.org/core/Hash.html). +* [Set](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Set.html) A thread-safe + subclass of Ruby's standard [Set](http://ruby-doc.org/stdlib-2.4.0/libdoc/set/rdoc/Set.html). +* [Map](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Map.html) A hash-like object + that should have much better performance characteristics, especially under high concurrency, + than `Concurrent::Hash`. +* [Tuple](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Tuple.html) A fixed size + array with volatile (synchronized, thread safe) getters/setters. + +Value objects inspired by other languages: + +* [Maybe](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Maybe.html) A thread-safe, + immutable object representing an optional value, based on + [Haskell Data.Maybe](https://hackage.haskell.org/package/base-4.2.0.1/docs/Data-Maybe.html). + +Structure classes derived from Ruby's [Struct](http://ruby-doc.org/core/Struct.html): + +* [ImmutableStruct](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/ImmutableStruct.html) + Immutable struct where values are set at construction and cannot be changed later. +* [MutableStruct](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/MutableStruct.html) + Synchronized, mutable struct where values can be safely changed at any time. +* [SettableStruct](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/SettableStruct.html) + Synchronized, write-once struct where values can be set at most once, either at construction + or any time thereafter. + +Thread-safe variables: + +* [Agent](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Agent.html): A way to + manage shared, mutable, *asynchronous*, independent state. Based on Clojure's + [Agent](http://clojure.org/agents). +* [Atom](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Atom.html): A way to manage + shared, mutable, *synchronous*, independent state. Based on Clojure's + [Atom](http://clojure.org/atoms). +* [AtomicBoolean](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/AtomicBoolean.html) + A boolean value that can be updated atomically. +* [AtomicFixnum](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/AtomicFixnum.html) + A numeric value that can be updated atomically. +* [AtomicReference](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/AtomicReference.html) + An object reference that may be updated atomically. +* [Exchanger](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Exchanger.html) + A synchronization point at which threads can pair and swap elements within pairs. Based on + Java's [Exchanger](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Exchanger.html). +* [MVar](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/MVar.html) A synchronized + single element container. Based on Haskell's + [MVar](https://hackage.haskell.org/package/base-4.8.1.0/docs/Control-Concurrent-MVar.html) and + Scala's [MVar](http://docs.typelevel.org/api/scalaz/nightly/index.html#scalaz.concurrent.MVar$). +* [ThreadLocalVar](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/ThreadLocalVar.html) + A variable where the value is different for each thread. +* [TVar](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/TVar.html) A transactional + variable implementing software transactional memory (STM). Based on Clojure's + [Ref](http://clojure.org/refs). + +#### Java-inspired ThreadPools and Other Executors + +* See the [thread pool](http://ruby-concurrency.github.io/concurrent-ruby/master/file.thread_pools.html) + overview, which also contains a list of other Executors available. + +#### Thread Synchronization Classes and Algorithms + +* [CountDownLatch](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/CountDownLatch.html) + A synchronization object that allows one thread to wait on multiple other threads. +* [CyclicBarrier](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/CyclicBarrier.html) + A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. +* [Event](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Event.html) Old school + kernel-style event. +* [ReadWriteLock](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/ReadWriteLock.html) + A lock that supports multiple readers but only one writer. +* [ReentrantReadWriteLock](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/ReentrantReadWriteLock.html) + A read/write lock with reentrant and upgrade features. +* [Semaphore](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Semaphore.html) + A counting-based locking mechanism that uses permits. +* [AtomicMarkableReference](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/AtomicMarkableReference.html) + +#### Deprecated + +Deprecated features are still available and bugs are being fixed, but new features will not be added. + +* ~~[Future](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Future.html): + An asynchronous operation that produces a value.~~ Replaced by + [Promises](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Promises.html). + * ~~[.dataflow](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent.html#dataflow-class_method): + Built on Futures, Dataflow allows you to create a task that will be scheduled when all of + its data dependencies are available.~~ Replaced by + [Promises](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Promises.html). +* ~~[Promise](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Promise.html): Similar + to Futures, with more features.~~ Replaced by + [Promises](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Promises.html). +* ~~[Delay](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Delay.html) Lazy evaluation + of a block yielding an immutable result. Based on Clojure's + [delay](https://clojuredocs.org/clojure.core/delay).~~ Replaced by + [Promises](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Promises.html). +* ~~[IVar](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/IVar.html) Similar to a + "future" but can be manually assigned once, after which it becomes immutable.~~ Replaced by + [Promises](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Promises.html). + +### Edge Features + +These are available in the `concurrent-ruby-edge` companion gem. + +These features are under active development and may change frequently. They are expected not to +keep backward compatibility (there may also lack tests and documentation). Semantic versions will +be obeyed though. Features developed in `concurrent-ruby-edge` are expected to move to +`concurrent-ruby` when final. + +* [Actor](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Actor.html): Implements + the Actor Model, where concurrent actors exchange messages. + *Status: Partial documentation and tests; depends on new future/promise framework; stability is good.* +* [Channel](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Channel.html): + Communicating Sequential Processes ([CSP](https://en.wikipedia.org/wiki/Communicating_sequential_processes)). + Functionally equivalent to Go [channels](https://tour.golang.org/concurrency/2) with additional + inspiration from Clojure [core.async](https://clojure.github.io/core.async/). + *Status: Partial documentation and tests.* +* [LazyRegister](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/LazyRegister.html) +* [LockFreeLinkedSet](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Edge/LockFreeLinkedSet.html) + *Status: will be moved to core soon.* +* [LockFreeStack](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/LockFreeStack.html) + *Status: missing documentation and tests.* +* [Promises::Channel](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Promises/Channel.html) + A first in first out channel that accepts messages with push family of methods and returns + messages with pop family of methods. + Pop and push operations can be represented as futures, see `#pop_op` and `#push_op`. + The capacity of the channel can be limited to support back pressure, use capacity option in `#initialize`. + `#pop` method blocks ans `#pop_op` returns pending future if there is no message in the channel. + If the capacity is limited the `#push` method blocks and `#push_op` returns pending future. +* [Cancellation](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Cancellation.html) + The Cancellation abstraction provides cooperative cancellation. + + The standard methods `Thread#raise` of `Thread#kill` available in Ruby + are very dangerous (see linked the blog posts bellow). + Therefore concurrent-ruby provides an alternative. + + * + * + * + + It provides an object which represents a task which can be executed, + the task has to get the reference to the object and periodically cooperatively check that it is not cancelled. + Good practices to make tasks cancellable: + * check cancellation every cycle of a loop which does significant work, + * do all blocking actions in a loop with a timeout then on timeout check cancellation + and if ok block again with the timeout +* [Throttle](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/Throttle.html) + A tool managing concurrency level of tasks. +* [ErlangActor](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/ErlangActor.html) + Actor implementation which precisely matches Erlang actor behaviour. + Requires at least Ruby 2.1 otherwise it's not loaded. +* [WrappingExecutor](http://ruby-concurrency.github.io/concurrent-ruby/master/Concurrent/WrappingExecutor.html) + A delegating executor which modifies each task before the task is given to + the target executor it delegates to. + +## Supported Ruby versions + +* MRI 2.2 and above +* Latest JRuby 9000 +* Latest TruffleRuby + +The legacy support for Rubinius is kept for the moment but it is no longer maintained and is liable to be removed. If you would like to help +please respond to [#739](https://github.com/ruby-concurrency/concurrent-ruby/issues/739). + +## Usage + +Everything within this gem can be loaded simply by requiring it: + +```ruby +require 'concurrent' +``` + +*Requiring only specific abstractions from Concurrent Ruby is not yet supported.* + +To use the tools in the Edge gem it must be required separately: + +```ruby +require 'concurrent-edge' +``` + +If the library does not behave as expected, `Concurrent.use_stdlib_logger(Logger::DEBUG)` could +help to reveal the problem. + +## Installation + +```shell +gem install concurrent-ruby +``` + +or add the following line to Gemfile: + +```ruby +gem 'concurrent-ruby', require: 'concurrent' +``` + +and run `bundle install` from your shell. + +### Edge Gem Installation + +The Edge gem must be installed separately from the core gem: + +```shell +gem install concurrent-ruby-edge +``` + +or add the following line to Gemfile: + +```ruby +gem 'concurrent-ruby-edge', require: 'concurrent-edge' +``` + +and run `bundle install` from your shell. + + +### C Extensions for MRI + +Potential performance improvements may be achieved under MRI by installing optional C extensions. +To minimise installation errors the C extensions are available in the `concurrent-ruby-ext` +extension gem. `concurrent-ruby` and `concurrent-ruby-ext` are always released together with same +version. Simply install the extension gem too: + +```ruby +gem install concurrent-ruby-ext +``` + +or add the following line to Gemfile: + +```ruby +gem 'concurrent-ruby-ext' +``` + +and run `bundle install` from your shell. + +In code it is only necessary to + +```ruby +require 'concurrent' +``` + +The `concurrent-ruby` gem will automatically detect the presence of the `concurrent-ruby-ext` gem +and load the appropriate C extensions. + +#### Note For gem developers + +No gems should depend on `concurrent-ruby-ext`. Doing so will force C extensions on your users. The +best practice is to depend on `concurrent-ruby` and let users to decide if they want C extensions. + +## Building the gem + +### Requirements + +* Recent CRuby +* JRuby, `rbenv install jruby-9.2.17.0` +* Set env variable `CONCURRENT_JRUBY_HOME` to point to it, e.g. `/usr/local/opt/rbenv/versions/jruby-9.2.17.0` +* Install Docker, required for Windows builds + +### Publishing the Gem + +* Update `version.rb` +* Update the CHANGELOG +* Update the Yard documentation + - Add the new version to `docs-source/signpost.md`. Needs to be done only if there are visible changes in the + documentation. + - Run `bundle exec rake yard` to update the master documentation and signpost. + - Run `bundle exec rake yard:` to add or update the documentation of the new version. +* Commit (and push) the changes. +* Use `be rake release` to release the gem. It consists + of `['release:checks', 'release:build', 'release:test', 'release:publish']` steps. It will ask at the end before + publishing anything. Steps can also be executed individually. + +## Maintainers + +* [Chris Seaton](https://github.com/chrisseaton) — Lead maintainer, point-of-contact. +* [Benoit Daloze](https://github.com/eregon) — If Chris is not available Benoit can help. + +### Special Thanks to + +* [Jerry D'Antonio](https://github.com/jdantonio) for creating the gem +* [Brian Durand](https://github.com/bdurand) for the `ref` gem +* [Charles Oliver Nutter](https://github.com/headius) for the `atomic` and `thread_safe` gems +* [thedarkone](https://github.com/thedarkone) for the `thread_safe` gem + +to the past maintainers + +* [Petr Chalupa](https://github.com/pitr-ch) +* [Michele Della Torre](https://github.com/mighe) +* [Paweł Obrok](https://github.com/obrok) +* [Lucas Allan](https://github.com/lucasallan) + +and to [Ruby Association](https://www.ruby.or.jp/en/) for sponsoring a project +["Enhancing Ruby’s concurrency tooling"](https://www.ruby.or.jp/en/news/20181106) in 2018. + +## License and Copyright + +*Concurrent Ruby* is free software released under the +[MIT License](http://www.opensource.org/licenses/MIT). + +The *Concurrent Ruby* [logo](https://raw.githubusercontent.com/ruby-concurrency/concurrent-ruby/master/docs-source/logo/concurrent-ruby-logo-300x300.png) was +designed by [David Jones](https://twitter.com/zombyboy). It is Copyright © 2014 +[Jerry D'Antonio](https://twitter.com/jerrydantonio). All Rights Reserved. diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/Rakefile b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/Rakefile new file mode 100644 index 0000000..55e78b7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/Rakefile @@ -0,0 +1,329 @@ +require_relative 'lib/concurrent-ruby/concurrent/version' +require_relative 'lib/concurrent-ruby-edge/concurrent/edge/version' +require_relative 'lib/concurrent-ruby/concurrent/utility/engine' + +core_gemspec = Gem::Specification.load File.join(__dir__, 'concurrent-ruby.gemspec') +ext_gemspec = Gem::Specification.load File.join(__dir__, 'concurrent-ruby-ext.gemspec') +edge_gemspec = Gem::Specification.load File.join(__dir__, 'concurrent-ruby-edge.gemspec') + +require 'rake/javaextensiontask' + +ENV['JRUBY_HOME'] = ENV['CONCURRENT_JRUBY_HOME'] if ENV['CONCURRENT_JRUBY_HOME'] && !Concurrent.on_jruby? + +Rake::JavaExtensionTask.new('concurrent_ruby', core_gemspec) do |ext| + ext.ext_dir = 'ext/concurrent-ruby' + ext.lib_dir = 'lib/concurrent-ruby/concurrent' +end + +unless Concurrent.on_jruby? || Concurrent.on_truffleruby? + require 'rake/extensiontask' + + Rake::ExtensionTask.new('concurrent_ruby_ext', ext_gemspec) do |ext| + ext.ext_dir = 'ext/concurrent-ruby-ext' + ext.lib_dir = 'lib/concurrent-ruby/concurrent' + ext.source_pattern = '*.{c,h}' + + ext.cross_compile = true + ext.cross_platform = ['x86-mingw32', 'x64-mingw32'] + end +end + +require 'rake_compiler_dock' +namespace :repackage do + desc '* with Windows fat distributions' + task :all do + Dir.chdir(__dir__) do + # store gems in vendor cache for docker + sh 'bundle package' + + # build only the jar file not the whole gem for java platform, the jar is part the concurrent-ruby-x.y.z.gem + Rake::Task['lib/concurrent-ruby/concurrent/concurrent_ruby.jar'].invoke + + # build all gem files + %w[x86-mingw32 x64-mingw32].each do |plat| + RakeCompilerDock.sh "bundle install --local && bundle exec rake native:#{plat} gem --trace", platform: plat + end + end + end +end + +require 'rubygems' +require 'rubygems/package_task' + +Gem::PackageTask.new(core_gemspec) {} if core_gemspec +Gem::PackageTask.new(ext_gemspec) {} if ext_gemspec && !Concurrent.on_jruby? +Gem::PackageTask.new(edge_gemspec) {} if edge_gemspec + +CLEAN.include('lib/concurrent-ruby/concurrent/2.*', 'lib/concurrent-ruby/concurrent/*.jar') + +begin + require 'rspec' + require 'rspec/core/rake_task' + + RSpec::Core::RakeTask.new(:spec) + + namespace :spec do + desc '* Configured for ci' + RSpec::Core::RakeTask.new(:ci) do |t| + options = %w[ --color + --backtrace + --order defined + --format documentation ] + t.rspec_opts = [*options].join(' ') + end + + desc '* test packaged and installed gems instead of local files' + task :installed do + Dir.chdir(__dir__) do + sh "gem install pkg/concurrent-ruby-#{Concurrent::VERSION}.gem" + sh "gem install pkg/concurrent-ruby-ext-#{Concurrent::VERSION}.gem" if Concurrent.on_cruby? + sh "gem install pkg/concurrent-ruby-edge-#{Concurrent::EDGE_VERSION}.gem" + ENV['NO_PATH'] = 'true' + sh 'bundle update' + sh 'bundle exec rake spec:ci' + end + end + end + + desc 'executed in CI' + task :ci => [:compile, 'spec:ci'] + + task :default => [:clobber, :compile, :spec] +rescue LoadError => e + puts 'RSpec is not installed, skipping test task definitions: ' + e.message +end + +current_yard_version_name = Concurrent::VERSION + +begin + require 'yard' + require 'md_ruby_eval' + require_relative 'support/yard_full_types' + + common_yard_options = ['--no-yardopts', + '--no-document', + '--no-private', + '--embed-mixins', + '--markup', 'markdown', + '--title', 'Concurrent Ruby', + '--template', 'default', + '--template-path', 'yard-template', + '--default-return', 'undocumented'] + + desc 'Generate YARD Documentation (signpost, master)' + task :yard => ['yard:signpost', 'yard:master'] + + namespace :yard do + + desc '* eval markdown files' + task :eval_md do + Dir.chdir File.join(__dir__, 'docs-source') do + sh 'bundle exec md-ruby-eval --auto' + end + end + + task :update_readme do + Dir.chdir __dir__ do + content = File.read(File.join('README.md')). + gsub(/\[([\w ]+)\]\(http:\/\/ruby-concurrency\.github\.io\/concurrent-ruby\/master\/.*\)/) do |_| + case $1 + when 'LockFreeLinkedSet' + "{Concurrent::Edge::#{$1} #{$1}}" + when '.dataflow' + '{Concurrent.dataflow Concurrent.dataflow}' + when 'thread pool' + '{file:thread_pools.md thread pool}' + else + "{Concurrent::#{$1} #{$1}}" + end + end + FileUtils.mkpath 'tmp' + File.write 'tmp/README.md', content + end + end + + define_yard_task = -> name do + output_dir = "docs/#{name}" + + removal_name = "remove.#{name}" + task removal_name do + Dir.chdir __dir__ do + FileUtils.rm_rf output_dir + end + end + + desc "* of #{name} into subdir #{name}" + YARD::Rake::YardocTask.new(name) do |yard| + yard.options.push( + '--output-dir', output_dir, + '--main', 'tmp/README.md', + *common_yard_options) + yard.files = ['./lib/concurrent-ruby/**/*.rb', + './lib/concurrent-ruby-edge/**/*.rb', + './ext/concurrent_ruby_ext/**/*.c', + '-', + 'docs-source/thread_pools.md', + 'docs-source/promises.out.md', + 'docs-source/medium-example.out.rb', + 'LICENSE.txt', + 'CHANGELOG.md'] + end + Rake::Task[name].prerequisites.push removal_name, + # 'yard:eval_md', + 'yard:update_readme' + end + + define_yard_task.call current_yard_version_name + define_yard_task.call 'master' + + desc "* signpost for versions" + YARD::Rake::YardocTask.new(:signpost) do |yard| + yard.options.push( + '--output-dir', 'docs', + '--main', 'docs-source/signpost.md', + *common_yard_options) + yard.files = ['no-lib'] + end + + define_uptodate_task = -> name do + namespace name do + desc "** ensure that #{name} generated documentation is matching the source code" + task :uptodate do + Dir.chdir(__dir__) do + begin + FileUtils.cp_r 'docs', 'docs-copy', verbose: true + Rake::Task["yard:#{name}"].invoke + sh 'diff -r docs/ docs-copy/' do |ok, res| + unless ok + begin + STDOUT.puts "yard:#{name} is not properly generated and committed.", "Continue? (y/n)" + input = STDIN.gets.strip.downcase + end until %w(y n).include?(input) + exit 1 if input == 'n' + end + end + ensure + FileUtils.rm_rf 'docs-copy', verbose: true + end + end + end + end + end + + define_uptodate_task.call current_yard_version_name + define_uptodate_task.call 'master' + end + +rescue LoadError => e + puts 'YARD is not installed, skipping documentation task definitions: ' + e.message +end + +desc 'build, test, and publish the gem' +task :release => ['release:checks', 'release:build', 'release:test', 'release:publish'] + +namespace :release do + # Depends on environment of @pitr-ch + + task :checks => "yard:#{current_yard_version_name}:uptodate" do + Dir.chdir(__dir__) do + sh 'test -z "$(git status --porcelain)"' do |ok, res| + unless ok + begin + status = `git status --porcelain` + STDOUT.puts 'There are local changes that you might want to commit.', status, 'Continue? (y/n)' + input = STDIN.gets.strip.downcase + end until %w(y n).include?(input) + exit 1 if input == 'n' + end + end + sh 'git fetch' + sh 'test $(git show-ref --verify --hash refs/heads/master) = ' + + '$(git show-ref --verify --hash refs/remotes/origin/master)' do |ok, res| + unless ok + begin + STDOUT.puts 'Local master branch is not pushed to origin.', 'Continue? (y/n)' + input = STDIN.gets.strip.downcase + end until %w(y n).include?(input) + exit 1 if input == 'n' + end + end + end + end + + desc '* build all *.gem files necessary for release' + task :build => [:clobber, 'repackage:all'] + + desc '* test actual installed gems instead of cloned repository on MRI and JRuby' + task :test do + Dir.chdir(__dir__) do + old = ENV['RBENV_VERSION'] + + mri_version = `ruby -e 'puts RUBY_VERSION'`.chomp + jruby_version = File.basename(ENV['CONCURRENT_JRUBY_HOME']) + + puts "Using following version:" + pp mri_version: mri_version, jruby_version: jruby_version + + ENV['RBENV_VERSION'] = mri_version + sh 'rbenv version' + sh 'bundle exec rake spec:installed' + + ENV['RBENV_VERSION'] = jruby_version + sh 'rbenv version' + sh 'bundle exec rake spec:installed' + + puts 'Windows build is untested' + + ENV['RBENV_VERSION'] = old + end + end + + desc '* do all nested steps' + task :publish => ['publish:ask', 'publish:tag', 'publish:rubygems', 'publish:post_steps'] + + namespace :publish do + publish_edge = false + + task :ask do + begin + STDOUT.puts 'Do you want to publish anything now? (y/n)' + input = STDIN.gets.strip.downcase + end until %w(y n).include?(input) + exit 1 if input == 'n' + begin + STDOUT.puts 'It will publish `concurrent-ruby`. Do you want to publish `concurrent-ruby-edge`? (y/n)' + input = STDIN.gets.strip.downcase + end until %w(y n).include?(input) + publish_edge = input == 'y' + end + + desc '** tag HEAD with current version and push to github' + task :tag => :ask do + Dir.chdir(__dir__) do + sh "git tag v#{Concurrent::VERSION}" + sh "git push origin v#{Concurrent::VERSION}" + sh "git tag edge-v#{Concurrent::EDGE_VERSION}" if publish_edge + sh "git push origin edge-v#{Concurrent::EDGE_VERSION}" if publish_edge + end + end + + desc '** push all *.gem files to rubygems' + task :rubygems => :ask do + Dir.chdir(__dir__) do + sh "gem push pkg/concurrent-ruby-#{Concurrent::VERSION}.gem" + sh "gem push pkg/concurrent-ruby-edge-#{Concurrent::EDGE_VERSION}.gem" if publish_edge + sh "gem push pkg/concurrent-ruby-ext-#{Concurrent::VERSION}.gem" + sh "gem push pkg/concurrent-ruby-ext-#{Concurrent::VERSION}-x64-mingw32.gem" + sh "gem push pkg/concurrent-ruby-ext-#{Concurrent::VERSION}-x86-mingw32.gem" + end + end + + desc '** print post release steps' + task :post_steps do + # TODO: (petr 05-Jun-2021) automate and renew the process + # puts 'Manually: create a release on GitHub with relevant changelog part' + # puts 'Manually: send email same as release with relevant changelog part' + # puts 'Manually: tweet' + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/ConcurrentRubyService.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/ConcurrentRubyService.java new file mode 100644 index 0000000..fb6be96 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/ConcurrentRubyService.java @@ -0,0 +1,17 @@ +import org.jruby.Ruby; +import org.jruby.runtime.load.BasicLibraryService; + +import java.io.IOException; + +public class ConcurrentRubyService implements BasicLibraryService { + + public boolean basicLoad(final Ruby runtime) throws IOException { + new com.concurrent_ruby.ext.AtomicReferenceLibrary().load(runtime, false); + new com.concurrent_ruby.ext.JavaAtomicBooleanLibrary().load(runtime, false); + new com.concurrent_ruby.ext.JavaAtomicFixnumLibrary().load(runtime, false); + new com.concurrent_ruby.ext.JavaSemaphoreLibrary().load(runtime, false); + new com.concurrent_ruby.ext.SynchronizationLibrary().load(runtime, false); + new com.concurrent_ruby.ext.JRubyMapBackendLibrary().load(runtime, false); + return true; + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/AtomicReferenceLibrary.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/AtomicReferenceLibrary.java new file mode 100644 index 0000000..dfa9e77 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/AtomicReferenceLibrary.java @@ -0,0 +1,175 @@ +package com.concurrent_ruby.ext; + +import java.lang.reflect.Field; +import java.io.IOException; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; +import org.jruby.Ruby; +import org.jruby.RubyClass; +import org.jruby.RubyModule; +import org.jruby.RubyNumeric; +import org.jruby.RubyObject; +import org.jruby.anno.JRubyClass; +import org.jruby.anno.JRubyMethod; +import org.jruby.runtime.ObjectAllocator; +import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.builtin.IRubyObject; +import org.jruby.runtime.load.Library; + +/** + * This library adds an atomic reference type to JRuby for use in the atomic + * library. We do a native version to avoid the implicit value coercion that + * normally happens through JI. + * + * @author headius + */ +public class AtomicReferenceLibrary implements Library { + public void load(Ruby runtime, boolean wrap) throws IOException { + RubyModule concurrentMod = runtime.defineModule("Concurrent"); + RubyClass atomicCls = concurrentMod.defineClassUnder("JavaAtomicReference", runtime.getObject(), JRUBYREFERENCE_ALLOCATOR); + try { + sun.misc.Unsafe.class.getMethod("getAndSetObject", Object.class); + atomicCls.setAllocator(JRUBYREFERENCE8_ALLOCATOR); + } catch (Exception e) { + // leave it as Java 6/7 version + } + atomicCls.defineAnnotatedMethods(JRubyReference.class); + } + + private static final ObjectAllocator JRUBYREFERENCE_ALLOCATOR = new ObjectAllocator() { + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new JRubyReference(runtime, klazz); + } + }; + + private static final ObjectAllocator JRUBYREFERENCE8_ALLOCATOR = new ObjectAllocator() { + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new JRubyReference8(runtime, klazz); + } + }; + + @JRubyClass(name="JRubyReference", parent="Object") + public static class JRubyReference extends RubyObject { + volatile IRubyObject reference; + + static final sun.misc.Unsafe UNSAFE; + static final long referenceOffset; + + static { + try { + UNSAFE = UnsafeHolder.U; + Class k = JRubyReference.class; + referenceOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("reference")); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public JRubyReference(Ruby runtime, RubyClass klass) { + super(runtime, klass); + } + + @JRubyMethod + public IRubyObject initialize(ThreadContext context) { + UNSAFE.putObject(this, referenceOffset, context.nil); + return context.nil; + } + + @JRubyMethod + public IRubyObject initialize(ThreadContext context, IRubyObject value) { + UNSAFE.putObject(this, referenceOffset, value); + return context.nil; + } + + @JRubyMethod(name = {"get", "value"}) + public IRubyObject get() { + return reference; + } + + @JRubyMethod(name = {"set", "value="}) + public IRubyObject set(IRubyObject newValue) { + UNSAFE.putObjectVolatile(this, referenceOffset, newValue); + return newValue; + } + + @JRubyMethod(name = {"compare_and_set", "compare_and_swap"}) + public IRubyObject compare_and_set(ThreadContext context, IRubyObject expectedValue, IRubyObject newValue) { + Ruby runtime = context.runtime; + + if (expectedValue instanceof RubyNumeric) { + // numerics are not always idempotent in Ruby, so we need to do slower logic + return compareAndSetNumeric(context, expectedValue, newValue); + } + + return runtime.newBoolean(UNSAFE.compareAndSwapObject(this, referenceOffset, expectedValue, newValue)); + } + + @JRubyMethod(name = {"get_and_set", "swap"}) + public IRubyObject get_and_set(ThreadContext context, IRubyObject newValue) { + // less-efficient version for Java 6 and 7 + while (true) { + IRubyObject oldValue = get(); + if (UNSAFE.compareAndSwapObject(this, referenceOffset, oldValue, newValue)) { + return oldValue; + } + } + } + + private IRubyObject compareAndSetNumeric(ThreadContext context, IRubyObject expectedValue, IRubyObject newValue) { + Ruby runtime = context.runtime; + + // loop until: + // * reference CAS would succeed for same-valued objects + // * current and expected have different values as determined by #equals + while (true) { + IRubyObject current = reference; + + if (!(current instanceof RubyNumeric)) { + // old value is not numeric, CAS fails + return runtime.getFalse(); + } + + RubyNumeric currentNumber = (RubyNumeric)current; + if (!currentNumber.equals(expectedValue)) { + // current number does not equal expected, fail CAS + return runtime.getFalse(); + } + + // check that current has not changed, or else allow loop to repeat + boolean success = UNSAFE.compareAndSwapObject(this, referenceOffset, current, newValue); + if (success) { + // value is same and did not change in interim...success + return runtime.getTrue(); + } + } + } + } + + private static final class UnsafeHolder { + private UnsafeHolder(){} + + public static final sun.misc.Unsafe U = loadUnsafe(); + + private static sun.misc.Unsafe loadUnsafe() { + try { + Class unsafeClass = Class.forName("sun.misc.Unsafe"); + Field f = unsafeClass.getDeclaredField("theUnsafe"); + f.setAccessible(true); + return (sun.misc.Unsafe) f.get(null); + } catch (Exception e) { + return null; + } + } + } + + public static class JRubyReference8 extends JRubyReference { + public JRubyReference8(Ruby runtime, RubyClass klass) { + super(runtime, klass); + } + + @Override + public IRubyObject get_and_set(ThreadContext context, IRubyObject newValue) { + // efficient version for Java 8 + return (IRubyObject)UNSAFE.getAndSetObject(this, referenceOffset, newValue); + } + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JRubyMapBackendLibrary.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JRubyMapBackendLibrary.java new file mode 100644 index 0000000..a09f916 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JRubyMapBackendLibrary.java @@ -0,0 +1,248 @@ +package com.concurrent_ruby.ext; + +import org.jruby.*; +import org.jruby.anno.JRubyClass; +import org.jruby.anno.JRubyMethod; +import com.concurrent_ruby.ext.jsr166e.ConcurrentHashMap; +import com.concurrent_ruby.ext.jsr166e.ConcurrentHashMapV8; +import com.concurrent_ruby.ext.jsr166e.nounsafe.*; +import org.jruby.runtime.Block; +import org.jruby.runtime.ObjectAllocator; +import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.builtin.IRubyObject; +import org.jruby.runtime.load.Library; + +import java.io.IOException; +import java.util.Map; + +import static org.jruby.runtime.Visibility.PRIVATE; + +/** + * Native Java implementation to avoid the JI overhead. + * + * @author thedarkone + */ +public class JRubyMapBackendLibrary implements Library { + public void load(Ruby runtime, boolean wrap) throws IOException { + + RubyModule concurrentMod = runtime.defineModule("Concurrent"); + RubyModule thread_safeMod = concurrentMod.defineModuleUnder("Collection"); + RubyClass jrubyRefClass = thread_safeMod.defineClassUnder("JRubyMapBackend", runtime.getObject(), BACKEND_ALLOCATOR); + jrubyRefClass.setAllocator(BACKEND_ALLOCATOR); + jrubyRefClass.defineAnnotatedMethods(JRubyMapBackend.class); + } + + private static final ObjectAllocator BACKEND_ALLOCATOR = new ObjectAllocator() { + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new JRubyMapBackend(runtime, klazz); + } + }; + + @JRubyClass(name="JRubyMapBackend", parent="Object") + public static class JRubyMapBackend extends RubyObject { + // Defaults used by the CHM + static final int DEFAULT_INITIAL_CAPACITY = 16; + static final float DEFAULT_LOAD_FACTOR = 0.75f; + + public static final boolean CAN_USE_UNSAFE_CHM = canUseUnsafeCHM(); + + private ConcurrentHashMap map; + + private static ConcurrentHashMap newCHM(int initialCapacity, float loadFactor) { + if (CAN_USE_UNSAFE_CHM) { + return new ConcurrentHashMapV8(initialCapacity, loadFactor); + } else { + return new com.concurrent_ruby.ext.jsr166e.nounsafe.ConcurrentHashMapV8(initialCapacity, loadFactor); + } + } + + private static ConcurrentHashMap newCHM() { + return newCHM(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); + } + + private static boolean canUseUnsafeCHM() { + try { + new com.concurrent_ruby.ext.jsr166e.ConcurrentHashMapV8(); // force class load and initialization + return true; + } catch (Throwable t) { // ensuring we really do catch everything + // Doug's Unsafe setup errors always have this "Could not ini.." message + if (isCausedBySecurityException(t)) { + return false; + } + throw (t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t)); + } + } + + private static boolean isCausedBySecurityException(Throwable t) { + while (t != null) { + if ((t.getMessage() != null && t.getMessage().contains("Could not initialize intrinsics")) || t instanceof SecurityException) { + return true; + } + t = t.getCause(); + } + return false; + } + + public JRubyMapBackend(Ruby runtime, RubyClass klass) { + super(runtime, klass); + } + + @JRubyMethod + public IRubyObject initialize(ThreadContext context) { + map = newCHM(); + return context.getRuntime().getNil(); + } + + @JRubyMethod + public IRubyObject initialize(ThreadContext context, IRubyObject options) { + map = toCHM(context, options); + return context.getRuntime().getNil(); + } + + private ConcurrentHashMap toCHM(ThreadContext context, IRubyObject options) { + Ruby runtime = context.getRuntime(); + if (!options.isNil() && options.respondsTo("[]")) { + IRubyObject rInitialCapacity = options.callMethod(context, "[]", runtime.newSymbol("initial_capacity")); + IRubyObject rLoadFactor = options.callMethod(context, "[]", runtime.newSymbol("load_factor")); + int initialCapacity = !rInitialCapacity.isNil() ? RubyNumeric.num2int(rInitialCapacity.convertToInteger()) : DEFAULT_INITIAL_CAPACITY; + float loadFactor = !rLoadFactor.isNil() ? (float)RubyNumeric.num2dbl(rLoadFactor.convertToFloat()) : DEFAULT_LOAD_FACTOR; + return newCHM(initialCapacity, loadFactor); + } else { + return newCHM(); + } + } + + @JRubyMethod(name = "[]", required = 1) + public IRubyObject op_aref(ThreadContext context, IRubyObject key) { + IRubyObject value; + return ((value = map.get(key)) == null) ? context.getRuntime().getNil() : value; + } + + @JRubyMethod(name = {"[]="}, required = 2) + public IRubyObject op_aset(IRubyObject key, IRubyObject value) { + map.put(key, value); + return value; + } + + @JRubyMethod + public IRubyObject put_if_absent(IRubyObject key, IRubyObject value) { + IRubyObject result = map.putIfAbsent(key, value); + return result == null ? getRuntime().getNil() : result; + } + + @JRubyMethod + public IRubyObject compute_if_absent(final ThreadContext context, final IRubyObject key, final Block block) { + return map.computeIfAbsent(key, new ConcurrentHashMap.Fun() { + @Override + public IRubyObject apply(IRubyObject key) { + return block.yieldSpecific(context); + } + }); + } + + @JRubyMethod + public IRubyObject compute_if_present(final ThreadContext context, final IRubyObject key, final Block block) { + IRubyObject result = map.computeIfPresent(key, new ConcurrentHashMap.BiFun() { + @Override + public IRubyObject apply(IRubyObject key, IRubyObject oldValue) { + IRubyObject result = block.yieldSpecific(context, oldValue == null ? context.getRuntime().getNil() : oldValue); + return result.isNil() ? null : result; + } + }); + return result == null ? context.getRuntime().getNil() : result; + } + + @JRubyMethod + public IRubyObject compute(final ThreadContext context, final IRubyObject key, final Block block) { + IRubyObject result = map.compute(key, new ConcurrentHashMap.BiFun() { + @Override + public IRubyObject apply(IRubyObject key, IRubyObject oldValue) { + IRubyObject result = block.yieldSpecific(context, oldValue == null ? context.getRuntime().getNil() : oldValue); + return result.isNil() ? null : result; + } + }); + return result == null ? context.getRuntime().getNil() : result; + } + + @JRubyMethod + public IRubyObject merge_pair(final ThreadContext context, final IRubyObject key, final IRubyObject value, final Block block) { + IRubyObject result = map.merge(key, value, new ConcurrentHashMap.BiFun() { + @Override + public IRubyObject apply(IRubyObject oldValue, IRubyObject newValue) { + IRubyObject result = block.yieldSpecific(context, oldValue == null ? context.getRuntime().getNil() : oldValue); + return result.isNil() ? null : result; + } + }); + return result == null ? context.getRuntime().getNil() : result; + } + + @JRubyMethod + public RubyBoolean replace_pair(IRubyObject key, IRubyObject oldValue, IRubyObject newValue) { + return getRuntime().newBoolean(map.replace(key, oldValue, newValue)); + } + + @JRubyMethod(name = "key?", required = 1) + public RubyBoolean has_key_p(IRubyObject key) { + return map.containsKey(key) ? getRuntime().getTrue() : getRuntime().getFalse(); + } + + @JRubyMethod + public IRubyObject key(IRubyObject value) { + final IRubyObject key = map.findKey(value); + return key == null ? getRuntime().getNil() : key; + } + + @JRubyMethod + public IRubyObject replace_if_exists(IRubyObject key, IRubyObject value) { + IRubyObject result = map.replace(key, value); + return result == null ? getRuntime().getNil() : result; + } + + @JRubyMethod + public IRubyObject get_and_set(IRubyObject key, IRubyObject value) { + IRubyObject result = map.put(key, value); + return result == null ? getRuntime().getNil() : result; + } + + @JRubyMethod + public IRubyObject delete(IRubyObject key) { + IRubyObject result = map.remove(key); + return result == null ? getRuntime().getNil() : result; + } + + @JRubyMethod + public RubyBoolean delete_pair(IRubyObject key, IRubyObject value) { + return getRuntime().newBoolean(map.remove(key, value)); + } + + @JRubyMethod + public IRubyObject clear() { + map.clear(); + return this; + } + + @JRubyMethod + public IRubyObject each_pair(ThreadContext context, Block block) { + for (Map.Entry entry : map.entrySet()) { + block.yieldSpecific(context, entry.getKey(), entry.getValue()); + } + return this; + } + + @JRubyMethod + public RubyFixnum size(ThreadContext context) { + return context.getRuntime().newFixnum(map.size()); + } + + @JRubyMethod + public IRubyObject get_or_default(IRubyObject key, IRubyObject defaultValue) { + return map.getValueOrDefault(key, defaultValue); + } + + @JRubyMethod(visibility = PRIVATE) + public JRubyMapBackend initialize_copy(ThreadContext context, IRubyObject other) { + map = newCHM(); + return this; + } + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaAtomicBooleanLibrary.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaAtomicBooleanLibrary.java new file mode 100644 index 0000000..b566076 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaAtomicBooleanLibrary.java @@ -0,0 +1,93 @@ +package com.concurrent_ruby.ext; + +import org.jruby.Ruby; +import org.jruby.RubyBoolean; +import org.jruby.RubyClass; +import org.jruby.RubyModule; +import org.jruby.RubyNil; +import org.jruby.RubyObject; +import org.jruby.anno.JRubyClass; +import org.jruby.anno.JRubyMethod; +import org.jruby.runtime.ObjectAllocator; +import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.builtin.IRubyObject; +import org.jruby.runtime.load.Library; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicBoolean; + +public class JavaAtomicBooleanLibrary implements Library { + + public void load(Ruby runtime, boolean wrap) throws IOException { + RubyModule concurrentMod = runtime.defineModule("Concurrent"); + RubyClass atomicCls = concurrentMod.defineClassUnder("JavaAtomicBoolean", runtime.getObject(), JRUBYREFERENCE_ALLOCATOR); + atomicCls.defineAnnotatedMethods(JavaAtomicBoolean.class); + } + + private static final ObjectAllocator JRUBYREFERENCE_ALLOCATOR = new ObjectAllocator() { + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new JavaAtomicBoolean(runtime, klazz); + } + }; + + @JRubyClass(name = "JavaAtomicBoolean", parent = "Object") + public static class JavaAtomicBoolean extends RubyObject { + + private AtomicBoolean atomicBoolean; + + public JavaAtomicBoolean(Ruby runtime, RubyClass metaClass) { + super(runtime, metaClass); + } + + @JRubyMethod + public IRubyObject initialize(ThreadContext context, IRubyObject value) { + atomicBoolean = new AtomicBoolean(convertRubyBooleanToJavaBoolean(value)); + return context.nil; + } + + @JRubyMethod + public IRubyObject initialize(ThreadContext context) { + atomicBoolean = new AtomicBoolean(); + return context.nil; + } + + @JRubyMethod(name = "value") + public IRubyObject value() { + return getRuntime().newBoolean(atomicBoolean.get()); + } + + @JRubyMethod(name = "true?") + public IRubyObject isAtomicTrue() { + return getRuntime().newBoolean(atomicBoolean.get()); + } + + @JRubyMethod(name = "false?") + public IRubyObject isAtomicFalse() { + return getRuntime().newBoolean((atomicBoolean.get() == false)); + } + + @JRubyMethod(name = "value=") + public IRubyObject setAtomic(ThreadContext context, IRubyObject newValue) { + atomicBoolean.set(convertRubyBooleanToJavaBoolean(newValue)); + return context.nil; + } + + @JRubyMethod(name = "make_true") + public IRubyObject makeTrue() { + return getRuntime().newBoolean(atomicBoolean.compareAndSet(false, true)); + } + + @JRubyMethod(name = "make_false") + public IRubyObject makeFalse() { + return getRuntime().newBoolean(atomicBoolean.compareAndSet(true, false)); + } + + private boolean convertRubyBooleanToJavaBoolean(IRubyObject newValue) { + if (newValue instanceof RubyBoolean.False || newValue instanceof RubyNil) { + return false; + } else { + return true; + } + } + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaAtomicFixnumLibrary.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaAtomicFixnumLibrary.java new file mode 100644 index 0000000..672bfc0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaAtomicFixnumLibrary.java @@ -0,0 +1,113 @@ +package com.concurrent_ruby.ext; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicLong; +import org.jruby.Ruby; +import org.jruby.RubyClass; +import org.jruby.RubyFixnum; +import org.jruby.RubyModule; +import org.jruby.RubyObject; +import org.jruby.anno.JRubyClass; +import org.jruby.anno.JRubyMethod; +import org.jruby.runtime.ObjectAllocator; +import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.builtin.IRubyObject; +import org.jruby.runtime.load.Library; +import org.jruby.runtime.Block; + +public class JavaAtomicFixnumLibrary implements Library { + + public void load(Ruby runtime, boolean wrap) throws IOException { + RubyModule concurrentMod = runtime.defineModule("Concurrent"); + RubyClass atomicCls = concurrentMod.defineClassUnder("JavaAtomicFixnum", runtime.getObject(), JRUBYREFERENCE_ALLOCATOR); + + atomicCls.defineAnnotatedMethods(JavaAtomicFixnum.class); + } + + private static final ObjectAllocator JRUBYREFERENCE_ALLOCATOR = new ObjectAllocator() { + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new JavaAtomicFixnum(runtime, klazz); + } + }; + + @JRubyClass(name = "JavaAtomicFixnum", parent = "Object") + public static class JavaAtomicFixnum extends RubyObject { + + private AtomicLong atomicLong; + + public JavaAtomicFixnum(Ruby runtime, RubyClass metaClass) { + super(runtime, metaClass); + } + + @JRubyMethod + public IRubyObject initialize(ThreadContext context) { + this.atomicLong = new AtomicLong(0); + return context.nil; + } + + @JRubyMethod + public IRubyObject initialize(ThreadContext context, IRubyObject value) { + this.atomicLong = new AtomicLong(rubyFixnumToLong(value)); + return context.nil; + } + + @JRubyMethod(name = "value") + public IRubyObject getValue() { + return getRuntime().newFixnum(atomicLong.get()); + } + + @JRubyMethod(name = "value=") + public IRubyObject setValue(ThreadContext context, IRubyObject newValue) { + atomicLong.set(rubyFixnumToLong(newValue)); + return context.nil; + } + + @JRubyMethod(name = {"increment", "up"}) + public IRubyObject increment() { + return getRuntime().newFixnum(atomicLong.incrementAndGet()); + } + + @JRubyMethod(name = {"increment", "up"}) + public IRubyObject increment(IRubyObject value) { + long delta = rubyFixnumToLong(value); + return getRuntime().newFixnum(atomicLong.addAndGet(delta)); + } + + @JRubyMethod(name = {"decrement", "down"}) + public IRubyObject decrement() { + return getRuntime().newFixnum(atomicLong.decrementAndGet()); + } + + @JRubyMethod(name = {"decrement", "down"}) + public IRubyObject decrement(IRubyObject value) { + long delta = rubyFixnumToLong(value); + return getRuntime().newFixnum(atomicLong.addAndGet(-delta)); + } + + @JRubyMethod(name = "compare_and_set") + public IRubyObject compareAndSet(ThreadContext context, IRubyObject expect, IRubyObject update) { + return getRuntime().newBoolean(atomicLong.compareAndSet(rubyFixnumToLong(expect), rubyFixnumToLong(update))); + } + + @JRubyMethod + public IRubyObject update(ThreadContext context, Block block) { + for (;;) { + long _oldValue = atomicLong.get(); + IRubyObject oldValue = getRuntime().newFixnum(_oldValue); + IRubyObject newValue = block.yield(context, oldValue); + if (atomicLong.compareAndSet(_oldValue, rubyFixnumToLong(newValue))) { + return newValue; + } + } + } + + private long rubyFixnumToLong(IRubyObject value) { + if (value instanceof RubyFixnum) { + RubyFixnum fixNum = (RubyFixnum) value; + return fixNum.getLongValue(); + } else { + throw getRuntime().newArgumentError("value must be a Fixnum"); + } + } + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaSemaphoreLibrary.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaSemaphoreLibrary.java new file mode 100644 index 0000000..d887f25 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaSemaphoreLibrary.java @@ -0,0 +1,189 @@ +package com.concurrent_ruby.ext; + +import java.io.IOException; +import java.util.concurrent.Semaphore; +import org.jruby.Ruby; +import org.jruby.RubyClass; +import org.jruby.RubyFixnum; +import org.jruby.RubyModule; +import org.jruby.RubyNumeric; +import org.jruby.RubyObject; +import org.jruby.anno.JRubyClass; +import org.jruby.anno.JRubyMethod; +import org.jruby.runtime.Block; +import org.jruby.runtime.ObjectAllocator; +import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.builtin.IRubyObject; + +public class JavaSemaphoreLibrary { + + public void load(Ruby runtime, boolean wrap) throws IOException { + RubyModule concurrentMod = runtime.defineModule("Concurrent"); + RubyClass atomicCls = concurrentMod.defineClassUnder("JavaSemaphore", runtime.getObject(), JRUBYREFERENCE_ALLOCATOR); + + atomicCls.defineAnnotatedMethods(JavaSemaphore.class); + } + + private static final ObjectAllocator JRUBYREFERENCE_ALLOCATOR = new ObjectAllocator() { + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new JavaSemaphore(runtime, klazz); + } + }; + + @JRubyClass(name = "JavaSemaphore", parent = "Object") + public static class JavaSemaphore extends RubyObject { + + private JRubySemaphore semaphore; + + public JavaSemaphore(Ruby runtime, RubyClass metaClass) { + super(runtime, metaClass); + } + + @JRubyMethod + public IRubyObject initialize(ThreadContext context, IRubyObject value) { + this.semaphore = new JRubySemaphore(rubyFixnumInt(value, "count")); + return context.nil; + } + + @JRubyMethod + public IRubyObject acquire(ThreadContext context, final Block block) throws InterruptedException { + return this.acquire(context, 1, block); + } + + @JRubyMethod + public IRubyObject acquire(ThreadContext context, IRubyObject permits, final Block block) throws InterruptedException { + return this.acquire(context, rubyFixnumToPositiveInt(permits, "permits"), block); + } + + @JRubyMethod(name = "available_permits") + public IRubyObject availablePermits(ThreadContext context) { + return getRuntime().newFixnum(this.semaphore.availablePermits()); + } + + @JRubyMethod(name = "drain_permits") + public IRubyObject drainPermits(ThreadContext context) { + return getRuntime().newFixnum(this.semaphore.drainPermits()); + } + + @JRubyMethod(name = "try_acquire") + public IRubyObject tryAcquire(ThreadContext context, final Block block) throws InterruptedException { + int permitsInt = 1; + boolean acquired = semaphore.tryAcquire(permitsInt); + + return triedAcquire(context, permitsInt, acquired, block); + } + + @JRubyMethod(name = "try_acquire") + public IRubyObject tryAcquire(ThreadContext context, IRubyObject permits, final Block block) throws InterruptedException { + int permitsInt = rubyFixnumToPositiveInt(permits, "permits"); + boolean acquired = semaphore.tryAcquire(permitsInt); + + return triedAcquire(context, permitsInt, acquired, block); + } + + @JRubyMethod(name = "try_acquire") + public IRubyObject tryAcquire(ThreadContext context, IRubyObject permits, IRubyObject timeout, final Block block) throws InterruptedException { + int permitsInt = rubyFixnumToPositiveInt(permits, "permits"); + boolean acquired = semaphore.tryAcquire( + permitsInt, + rubyNumericToLong(timeout, "timeout"), + java.util.concurrent.TimeUnit.SECONDS + ); + + return triedAcquire(context, permitsInt, acquired, block); + } + + @JRubyMethod + public IRubyObject release(ThreadContext context) { + this.semaphore.release(1); + return getRuntime().newBoolean(true); + } + + @JRubyMethod + public IRubyObject release(ThreadContext context, IRubyObject permits) { + this.semaphore.release(rubyFixnumToPositiveInt(permits, "permits")); + return getRuntime().newBoolean(true); + } + + @JRubyMethod(name = "reduce_permits") + public IRubyObject reducePermits(ThreadContext context, IRubyObject reduction) throws InterruptedException { + this.semaphore.publicReducePermits(rubyFixnumToNonNegativeInt(reduction, "reduction")); + return context.nil; + } + + private IRubyObject acquire(ThreadContext context, int permits, final Block block) throws InterruptedException { + this.semaphore.acquire(permits); + + if (!block.isGiven()) return context.nil; + + try { + return block.yieldSpecific(context); + } finally { + this.semaphore.release(permits); + } + } + + private IRubyObject triedAcquire(ThreadContext context, int permits, boolean acquired, final Block block) { + if (!block.isGiven()) return getRuntime().newBoolean(acquired); + if (!acquired) return context.nil; + + try { + return block.yieldSpecific(context); + } finally { + this.semaphore.release(permits); + } + } + + private int rubyFixnumInt(IRubyObject value, String paramName) { + if (value instanceof RubyFixnum) { + RubyFixnum fixNum = (RubyFixnum) value; + return (int) fixNum.getLongValue(); + } else { + throw getRuntime().newArgumentError(paramName + " must be integer"); + } + } + + private int rubyFixnumToNonNegativeInt(IRubyObject value, String paramName) { + if (value instanceof RubyFixnum && ((RubyFixnum) value).getLongValue() >= 0) { + RubyFixnum fixNum = (RubyFixnum) value; + return (int) fixNum.getLongValue(); + } else { + throw getRuntime().newArgumentError(paramName + " must be a non-negative integer"); + } + } + + private int rubyFixnumToPositiveInt(IRubyObject value, String paramName) { + if (value instanceof RubyFixnum && ((RubyFixnum) value).getLongValue() > 0) { + RubyFixnum fixNum = (RubyFixnum) value; + return (int) fixNum.getLongValue(); + } else { + throw getRuntime().newArgumentError(paramName + " must be an integer greater than zero"); + } + } + + private long rubyNumericToLong(IRubyObject value, String paramName) { + if (value instanceof RubyNumeric && ((RubyNumeric) value).getDoubleValue() > 0) { + RubyNumeric fixNum = (RubyNumeric) value; + return fixNum.getLongValue(); + } else { + throw getRuntime().newArgumentError(paramName + " must be a float greater than zero"); + } + } + + class JRubySemaphore extends Semaphore { + + public JRubySemaphore(int permits) { + super(permits); + } + + public JRubySemaphore(int permits, boolean value) { + super(permits, value); + } + + public void publicReducePermits(int i) { + reducePermits(i); + } + + } + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/SynchronizationLibrary.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/SynchronizationLibrary.java new file mode 100644 index 0000000..bfcc0d0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/SynchronizationLibrary.java @@ -0,0 +1,307 @@ +package com.concurrent_ruby.ext; + +import org.jruby.Ruby; +import org.jruby.RubyBasicObject; +import org.jruby.RubyClass; +import org.jruby.RubyModule; +import org.jruby.RubyObject; +import org.jruby.RubyThread; +import org.jruby.anno.JRubyClass; +import org.jruby.anno.JRubyMethod; +import org.jruby.runtime.Block; +import org.jruby.runtime.ObjectAllocator; +import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.Visibility; +import org.jruby.runtime.builtin.IRubyObject; +import org.jruby.runtime.load.Library; +import sun.misc.Unsafe; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +public class SynchronizationLibrary implements Library { + + private static final Unsafe UNSAFE = loadUnsafe(); + private static final boolean FULL_FENCE = supportsFences(); + + private static Unsafe loadUnsafe() { + try { + Class ncdfe = Class.forName("sun.misc.Unsafe"); + Field f = ncdfe.getDeclaredField("theUnsafe"); + f.setAccessible(true); + return (Unsafe) f.get((java.lang.Object) null); + } catch (Exception var2) { + return null; + } catch (NoClassDefFoundError var3) { + return null; + } + } + + private static boolean supportsFences() { + if (UNSAFE == null) { + return false; + } else { + try { + Method m = UNSAFE.getClass().getDeclaredMethod("fullFence", new Class[0]); + if (m != null) { + return true; + } + } catch (Exception var1) { + // nothing + } + + return false; + } + } + + private static final ObjectAllocator JRUBY_OBJECT_ALLOCATOR = new ObjectAllocator() { + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new JRubyObject(runtime, klazz); + } + }; + + private static final ObjectAllocator OBJECT_ALLOCATOR = new ObjectAllocator() { + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new Object(runtime, klazz); + } + }; + + private static final ObjectAllocator ABSTRACT_LOCKABLE_OBJECT_ALLOCATOR = new ObjectAllocator() { + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new AbstractLockableObject(runtime, klazz); + } + }; + + private static final ObjectAllocator JRUBY_LOCKABLE_OBJECT_ALLOCATOR = new ObjectAllocator() { + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new JRubyLockableObject(runtime, klazz); + } + }; + + public void load(Ruby runtime, boolean wrap) throws IOException { + RubyModule synchronizationModule = runtime. + defineModule("Concurrent"). + defineModuleUnder("Synchronization"); + + RubyModule jrubyAttrVolatileModule = synchronizationModule.defineModuleUnder("JRubyAttrVolatile"); + jrubyAttrVolatileModule.defineAnnotatedMethods(JRubyAttrVolatile.class); + + defineClass(runtime, synchronizationModule, "AbstractObject", "JRubyObject", + JRubyObject.class, JRUBY_OBJECT_ALLOCATOR); + + defineClass(runtime, synchronizationModule, "JRubyObject", "Object", + Object.class, OBJECT_ALLOCATOR); + + defineClass(runtime, synchronizationModule, "Object", "AbstractLockableObject", + AbstractLockableObject.class, ABSTRACT_LOCKABLE_OBJECT_ALLOCATOR); + + defineClass(runtime, synchronizationModule, "AbstractLockableObject", "JRubyLockableObject", + JRubyLockableObject.class, JRUBY_LOCKABLE_OBJECT_ALLOCATOR); + + defineClass(runtime, synchronizationModule, "Object", "JRuby", + JRuby.class, new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new JRuby(runtime, klazz); + } + }); + } + + private RubyClass defineClass( + Ruby runtime, + RubyModule namespace, + String parentName, + String name, + Class javaImplementation, + ObjectAllocator allocator) { + final RubyClass parentClass = namespace.getClass(parentName); + + if (parentClass == null) { + System.out.println("not found " + parentName); + throw runtime.newRuntimeError(namespace.toString() + "::" + parentName + " is missing"); + } + + final RubyClass newClass = namespace.defineClassUnder(name, parentClass, allocator); + newClass.defineAnnotatedMethods(javaImplementation); + return newClass; + } + + // Facts: + // - all ivar reads are without any synchronisation of fences see + // https://github.com/jruby/jruby/blob/master/core/src/main/java/org/jruby/runtime/ivars/VariableAccessor.java#L110-110 + // - writes depend on UnsafeHolder.U, null -> SynchronizedVariableAccessor, !null -> StampedVariableAccessor + // SynchronizedVariableAccessor wraps with synchronized block, StampedVariableAccessor uses fullFence or + // volatilePut + // TODO (pitr 16-Sep-2015): what do we do in Java 9 ? + + // module JRubyAttrVolatile + public static class JRubyAttrVolatile { + + // volatile threadContext is used as a memory barrier per the JVM memory model happens-before semantic + // on volatile fields. any volatile field could have been used but using the thread context is an + // attempt to avoid code elimination. + private static volatile int volatileField; + + @JRubyMethod(name = "full_memory_barrier", visibility = Visibility.PUBLIC) + public static IRubyObject fullMemoryBarrier(ThreadContext context, IRubyObject self) { + // Prevent reordering of ivar writes with publication of this instance + if (!FULL_FENCE) { + // Assuming that following volatile read and write is not eliminated it simulates fullFence. + // If it's eliminated it'll cause problems only on non-x86 platforms. + // http://shipilev.net/blog/2014/jmm-pragmatics/#_happens_before_test_your_understanding + final int volatileRead = volatileField; + volatileField = context.getLine(); + } else { + UNSAFE.fullFence(); + } + return context.nil; + } + + @JRubyMethod(name = "instance_variable_get_volatile", visibility = Visibility.PUBLIC) + public static IRubyObject instanceVariableGetVolatile( + ThreadContext context, + IRubyObject self, + IRubyObject name) { + // Ensure we ses latest value with loadFence + if (!FULL_FENCE) { + // piggybacking on volatile read, simulating loadFence + final int volatileRead = volatileField; + return ((RubyBasicObject) self).instance_variable_get(context, name); + } else { + UNSAFE.loadFence(); + return ((RubyBasicObject) self).instance_variable_get(context, name); + } + } + + @JRubyMethod(name = "instance_variable_set_volatile", visibility = Visibility.PUBLIC) + public static IRubyObject InstanceVariableSetVolatile( + ThreadContext context, + IRubyObject self, + IRubyObject name, + IRubyObject value) { + // Ensure we make last update visible + if (!FULL_FENCE) { + // piggybacking on volatile write, simulating storeFence + final IRubyObject result = ((RubyBasicObject) self).instance_variable_set(name, value); + volatileField = context.getLine(); + return result; + } else { + // JRuby uses StampedVariableAccessor which calls fullFence + // so no additional steps needed. + // See https://github.com/jruby/jruby/blob/master/core/src/main/java/org/jruby/runtime/ivars/StampedVariableAccessor.java#L151-L159 + return ((RubyBasicObject) self).instance_variable_set(name, value); + } + } + } + + @JRubyClass(name = "JRubyObject", parent = "AbstractObject") + public static class JRubyObject extends RubyObject { + + public JRubyObject(Ruby runtime, RubyClass metaClass) { + super(runtime, metaClass); + } + } + + @JRubyClass(name = "Object", parent = "JRubyObject") + public static class Object extends JRubyObject { + + public Object(Ruby runtime, RubyClass metaClass) { + super(runtime, metaClass); + } + } + + @JRubyClass(name = "AbstractLockableObject", parent = "Object") + public static class AbstractLockableObject extends Object { + + public AbstractLockableObject(Ruby runtime, RubyClass metaClass) { + super(runtime, metaClass); + } + } + + @JRubyClass(name = "JRubyLockableObject", parent = "AbstractLockableObject") + public static class JRubyLockableObject extends JRubyObject { + + public JRubyLockableObject(Ruby runtime, RubyClass metaClass) { + super(runtime, metaClass); + } + + @JRubyMethod(name = "synchronize", visibility = Visibility.PROTECTED) + public IRubyObject rubySynchronize(ThreadContext context, Block block) { + synchronized (this) { + return block.yield(context, null); + } + } + + @JRubyMethod(name = "ns_wait", optional = 1, visibility = Visibility.PROTECTED) + public IRubyObject nsWait(ThreadContext context, IRubyObject[] args) { + Ruby runtime = context.runtime; + if (args.length > 1) { + throw runtime.newArgumentError(args.length, 1); + } + Double timeout = null; + if (args.length > 0 && !args[0].isNil()) { + timeout = args[0].convertToFloat().getDoubleValue(); + if (timeout < 0) { + throw runtime.newArgumentError("time interval must be positive"); + } + } + if (Thread.interrupted()) { + throw runtime.newConcurrencyError("thread interrupted"); + } + boolean success = false; + try { + success = context.getThread().wait_timeout(this, timeout); + } catch (InterruptedException ie) { + throw runtime.newConcurrencyError(ie.getLocalizedMessage()); + } finally { + // An interrupt or timeout may have caused us to miss + // a notify that we consumed, so do another notify in + // case someone else is available to pick it up. + if (!success) { + this.notify(); + } + } + return this; + } + + @JRubyMethod(name = "ns_signal", visibility = Visibility.PROTECTED) + public IRubyObject nsSignal(ThreadContext context) { + notify(); + return this; + } + + @JRubyMethod(name = "ns_broadcast", visibility = Visibility.PROTECTED) + public IRubyObject nsBroadcast(ThreadContext context) { + notifyAll(); + return this; + } + } + + @JRubyClass(name = "JRuby") + public static class JRuby extends RubyObject { + public JRuby(Ruby runtime, RubyClass metaClass) { + super(runtime, metaClass); + } + + @JRubyMethod(name = "sleep_interruptibly", visibility = Visibility.PUBLIC, module = true) + public static IRubyObject sleepInterruptibly(final ThreadContext context, IRubyObject receiver, final Block block) { + try { + context.getThread().executeBlockingTask(new RubyThread.BlockingTask() { + @Override + public void run() throws InterruptedException { + block.call(context); + } + + @Override + public void wakeup() { + context.getThread().getNativeThread().interrupt(); + } + }); + } catch (InterruptedException e) { + throw context.runtime.newThreadError("interrupted in Concurrent::Synchronization::JRuby.sleep_interruptibly"); + } + return context.nil; + } + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/ConcurrentHashMap.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/ConcurrentHashMap.java new file mode 100644 index 0000000..e11e15a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/ConcurrentHashMap.java @@ -0,0 +1,31 @@ +package com.concurrent_ruby.ext.jsr166e; + +import java.util.Map; +import java.util.Set; + +public interface ConcurrentHashMap { + /** Interface describing a function of one argument */ + public interface Fun { T apply(A a); } + /** Interface describing a function of two arguments */ + public interface BiFun { T apply(A a, B b); } + + public V get(K key); + public V put(K key, V value); + public V putIfAbsent(K key, V value); + public V computeIfAbsent(K key, Fun mf); + public V computeIfPresent(K key, BiFun mf); + public V compute(K key, BiFun mf); + public V merge(K key, V value, BiFun mf); + public boolean replace(K key, V oldVal, V newVal); + public V replace(K key, V value); + public boolean containsKey(K key); + public boolean remove(Object key, Object value); + public V remove(K key); + public void clear(); + public Set> entrySet(); + public int size(); + public V getValueOrDefault(Object key, V defaultValue); + + public boolean containsValue(V value); + public K findKey(V value); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/ConcurrentHashMapV8.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/ConcurrentHashMapV8.java new file mode 100644 index 0000000..86aa4eb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/ConcurrentHashMapV8.java @@ -0,0 +1,3863 @@ +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +// This is based on the 1.79 version. + +package com.concurrent_ruby.ext.jsr166e; + +import org.jruby.RubyClass; +import org.jruby.RubyNumeric; +import org.jruby.RubyObject; +import org.jruby.exceptions.RaiseException; +import com.concurrent_ruby.ext.jsr166y.ThreadLocalRandom; +import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.builtin.IRubyObject; + +import java.util.Arrays; +import java.util.Map; +import java.util.Set; +import java.util.Collection; +import java.util.Hashtable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Enumeration; +import java.util.ConcurrentModificationException; +import java.util.NoSuchElementException; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.locks.AbstractQueuedSynchronizer; + +import java.io.Serializable; + +/** + * A hash table supporting full concurrency of retrievals and + * high expected concurrency for updates. This class obeys the + * same functional specification as {@link java.util.Hashtable}, and + * includes versions of methods corresponding to each method of + * {@code Hashtable}. However, even though all operations are + * thread-safe, retrieval operations do not entail locking, + * and there is not any support for locking the entire table + * in a way that prevents all access. This class is fully + * interoperable with {@code Hashtable} in programs that rely on its + * thread safety but not on its synchronization details. + * + *

Retrieval operations (including {@code get}) generally do not + * block, so may overlap with update operations (including {@code put} + * and {@code remove}). Retrievals reflect the results of the most + * recently completed update operations holding upon their + * onset. (More formally, an update operation for a given key bears a + * happens-before relation with any (non-null) retrieval for + * that key reporting the updated value.) For aggregate operations + * such as {@code putAll} and {@code clear}, concurrent retrievals may + * reflect insertion or removal of only some entries. Similarly, + * Iterators and Enumerations return elements reflecting the state of + * the hash table at some point at or since the creation of the + * iterator/enumeration. They do not throw {@link + * ConcurrentModificationException}. However, iterators are designed + * to be used by only one thread at a time. Bear in mind that the + * results of aggregate status methods including {@code size}, {@code + * isEmpty}, and {@code containsValue} are typically useful only when + * a map is not undergoing concurrent updates in other threads. + * Otherwise the results of these methods reflect transient states + * that may be adequate for monitoring or estimation purposes, but not + * for program control. + * + *

The table is dynamically expanded when there are too many + * collisions (i.e., keys that have distinct hash codes but fall into + * the same slot modulo the table size), with the expected average + * effect of maintaining roughly two bins per mapping (corresponding + * to a 0.75 load factor threshold for resizing). There may be much + * variance around this average as mappings are added and removed, but + * overall, this maintains a commonly accepted time/space tradeoff for + * hash tables. However, resizing this or any other kind of hash + * table may be a relatively slow operation. When possible, it is a + * good idea to provide a size estimate as an optional {@code + * initialCapacity} constructor argument. An additional optional + * {@code loadFactor} constructor argument provides a further means of + * customizing initial table capacity by specifying the table density + * to be used in calculating the amount of space to allocate for the + * given number of elements. Also, for compatibility with previous + * versions of this class, constructors may optionally specify an + * expected {@code concurrencyLevel} as an additional hint for + * internal sizing. Note that using many keys with exactly the same + * {@code hashCode()} is a sure way to slow down performance of any + * hash table. + * + *

A {@link Set} projection of a ConcurrentHashMapV8 may be created + * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed + * (using {@link #keySet(Object)} when only keys are of interest, and the + * mapped values are (perhaps transiently) not used or all take the + * same mapping value. + * + *

A ConcurrentHashMapV8 can be used as scalable frequency map (a + * form of histogram or multiset) by using {@link LongAdder} values + * and initializing via {@link #computeIfAbsent}. For example, to add + * a count to a {@code ConcurrentHashMapV8 freqs}, you + * can use {@code freqs.computeIfAbsent(k -> new + * LongAdder()).increment();} + * + *

This class and its views and iterators implement all of the + * optional methods of the {@link Map} and {@link Iterator} + * interfaces. + * + *

Like {@link Hashtable} but unlike {@link HashMap}, this class + * does not allow {@code null} to be used as a key or value. + * + *

ConcurrentHashMapV8s support parallel operations using the {@link + * ForkJoinPool#commonPool}. (Tasks that may be used in other contexts + * are available in class {@link ForkJoinTasks}). These operations are + * designed to be safely, and often sensibly, applied even with maps + * that are being concurrently updated by other threads; for example, + * when computing a snapshot summary of the values in a shared + * registry. There are three kinds of operation, each with four + * forms, accepting functions with Keys, Values, Entries, and (Key, + * Value) arguments and/or return values. (The first three forms are + * also available via the {@link #keySet()}, {@link #values()} and + * {@link #entrySet()} views). Because the elements of a + * ConcurrentHashMapV8 are not ordered in any particular way, and may be + * processed in different orders in different parallel executions, the + * correctness of supplied functions should not depend on any + * ordering, or on any other objects or values that may transiently + * change while computation is in progress; and except for forEach + * actions, should ideally be side-effect-free. + * + *

    + *
  • forEach: Perform a given action on each element. + * A variant form applies a given transformation on each element + * before performing the action.
  • + * + *
  • search: Return the first available non-null result of + * applying a given function on each element; skipping further + * search when a result is found.
  • + * + *
  • reduce: Accumulate each element. The supplied reduction + * function cannot rely on ordering (more formally, it should be + * both associative and commutative). There are five variants: + * + *
      + * + *
    • Plain reductions. (There is not a form of this method for + * (key, value) function arguments since there is no corresponding + * return type.)
    • + * + *
    • Mapped reductions that accumulate the results of a given + * function applied to each element.
    • + * + *
    • Reductions to scalar doubles, longs, and ints, using a + * given basis value.
    • + * + * + *
    + *
+ * + *

The concurrency properties of bulk operations follow + * from those of ConcurrentHashMapV8: Any non-null result returned + * from {@code get(key)} and related access methods bears a + * happens-before relation with the associated insertion or + * update. The result of any bulk operation reflects the + * composition of these per-element relations (but is not + * necessarily atomic with respect to the map as a whole unless it + * is somehow known to be quiescent). Conversely, because keys + * and values in the map are never null, null serves as a reliable + * atomic indicator of the current lack of any result. To + * maintain this property, null serves as an implicit basis for + * all non-scalar reduction operations. For the double, long, and + * int versions, the basis should be one that, when combined with + * any other value, returns that other value (more formally, it + * should be the identity element for the reduction). Most common + * reductions have these properties; for example, computing a sum + * with basis 0 or a minimum with basis MAX_VALUE. + * + *

Search and transformation functions provided as arguments + * should similarly return null to indicate the lack of any result + * (in which case it is not used). In the case of mapped + * reductions, this also enables transformations to serve as + * filters, returning null (or, in the case of primitive + * specializations, the identity basis) if the element should not + * be combined. You can create compound transformations and + * filterings by composing them yourself under this "null means + * there is nothing there now" rule before using them in search or + * reduce operations. + * + *

Methods accepting and/or returning Entry arguments maintain + * key-value associations. They may be useful for example when + * finding the key for the greatest value. Note that "plain" Entry + * arguments can be supplied using {@code new + * AbstractMap.SimpleEntry(k,v)}. + * + *

Bulk operations may complete abruptly, throwing an + * exception encountered in the application of a supplied + * function. Bear in mind when handling such exceptions that other + * concurrently executing functions could also have thrown + * exceptions, or would have done so if the first exception had + * not occurred. + * + *

Parallel speedups for bulk operations compared to sequential + * processing are common but not guaranteed. Operations involving + * brief functions on small maps may execute more slowly than + * sequential loops if the underlying work to parallelize the + * computation is more expensive than the computation itself. + * Similarly, parallelization may not lead to much actual parallelism + * if all processors are busy performing unrelated tasks. + * + *

All arguments to all task methods must be non-null. + * + *

jsr166e note: During transition, this class + * uses nested functional interfaces with different names but the + * same forms as those expected for JDK8. + * + *

This class is a member of the + * + * Java Collections Framework. + * + * @since 1.5 + * @author Doug Lea + * @param the type of keys maintained by this map + * @param the type of mapped values + */ +public class ConcurrentHashMapV8 + implements ConcurrentMap, Serializable, ConcurrentHashMap { + private static final long serialVersionUID = 7249069246763182397L; + + /** + * A partitionable iterator. A Spliterator can be traversed + * directly, but can also be partitioned (before traversal) by + * creating another Spliterator that covers a non-overlapping + * portion of the elements, and so may be amenable to parallel + * execution. + * + *

This interface exports a subset of expected JDK8 + * functionality. + * + *

Sample usage: Here is one (of the several) ways to compute + * the sum of the values held in a map using the ForkJoin + * framework. As illustrated here, Spliterators are well suited to + * designs in which a task repeatedly splits off half its work + * into forked subtasks until small enough to process directly, + * and then joins these subtasks. Variants of this style can also + * be used in completion-based designs. + * + *

+     * {@code ConcurrentHashMapV8 m = ...
+     * // split as if have 8 * parallelism, for load balance
+     * int n = m.size();
+     * int p = aForkJoinPool.getParallelism() * 8;
+     * int split = (n < p)? n : p;
+     * long sum = aForkJoinPool.invoke(new SumValues(m.valueSpliterator(), split, null));
+     * // ...
+     * static class SumValues extends RecursiveTask {
+     *   final Spliterator s;
+     *   final int split;             // split while > 1
+     *   final SumValues nextJoin;    // records forked subtasks to join
+     *   SumValues(Spliterator s, int depth, SumValues nextJoin) {
+     *     this.s = s; this.depth = depth; this.nextJoin = nextJoin;
+     *   }
+     *   public Long compute() {
+     *     long sum = 0;
+     *     SumValues subtasks = null; // fork subtasks
+     *     for (int s = split >>> 1; s > 0; s >>>= 1)
+     *       (subtasks = new SumValues(s.split(), s, subtasks)).fork();
+     *     while (s.hasNext())        // directly process remaining elements
+     *       sum += s.next();
+     *     for (SumValues t = subtasks; t != null; t = t.nextJoin)
+     *       sum += t.join();         // collect subtask results
+     *     return sum;
+     *   }
+     * }
+     * }
+ */ + public static interface Spliterator extends Iterator { + /** + * Returns a Spliterator covering approximately half of the + * elements, guaranteed not to overlap with those subsequently + * returned by this Spliterator. After invoking this method, + * the current Spliterator will not produce any of + * the elements of the returned Spliterator, but the two + * Spliterators together will produce all of the elements that + * would have been produced by this Spliterator had this + * method not been called. The exact number of elements + * produced by the returned Spliterator is not guaranteed, and + * may be zero (i.e., with {@code hasNext()} reporting {@code + * false}) if this Spliterator cannot be further split. + * + * @return a Spliterator covering approximately half of the + * elements + * @throws IllegalStateException if this Spliterator has + * already commenced traversing elements + */ + Spliterator split(); + } + + + /* + * Overview: + * + * The primary design goal of this hash table is to maintain + * concurrent readability (typically method get(), but also + * iterators and related methods) while minimizing update + * contention. Secondary goals are to keep space consumption about + * the same or better than java.util.HashMap, and to support high + * initial insertion rates on an empty table by many threads. + * + * Each key-value mapping is held in a Node. Because Node fields + * can contain special values, they are defined using plain Object + * types. Similarly in turn, all internal methods that use them + * work off Object types. And similarly, so do the internal + * methods of auxiliary iterator and view classes. All public + * generic typed methods relay in/out of these internal methods, + * supplying null-checks and casts as needed. This also allows + * many of the public methods to be factored into a smaller number + * of internal methods (although sadly not so for the five + * variants of put-related operations). The validation-based + * approach explained below leads to a lot of code sprawl because + * retry-control precludes factoring into smaller methods. + * + * The table is lazily initialized to a power-of-two size upon the + * first insertion. Each bin in the table normally contains a + * list of Nodes (most often, the list has only zero or one Node). + * Table accesses require volatile/atomic reads, writes, and + * CASes. Because there is no other way to arrange this without + * adding further indirections, we use intrinsics + * (sun.misc.Unsafe) operations. The lists of nodes within bins + * are always accurately traversable under volatile reads, so long + * as lookups check hash code and non-nullness of value before + * checking key equality. + * + * We use the top two bits of Node hash fields for control + * purposes -- they are available anyway because of addressing + * constraints. As explained further below, these top bits are + * used as follows: + * 00 - Normal + * 01 - Locked + * 11 - Locked and may have a thread waiting for lock + * 10 - Node is a forwarding node + * + * The lower 30 bits of each Node's hash field contain a + * transformation of the key's hash code, except for forwarding + * nodes, for which the lower bits are zero (and so always have + * hash field == MOVED). + * + * Insertion (via put or its variants) of the first node in an + * empty bin is performed by just CASing it to the bin. This is + * by far the most common case for put operations under most + * key/hash distributions. Other update operations (insert, + * delete, and replace) require locks. We do not want to waste + * the space required to associate a distinct lock object with + * each bin, so instead use the first node of a bin list itself as + * a lock. Blocking support for these locks relies on the builtin + * "synchronized" monitors. However, we also need a tryLock + * construction, so we overlay these by using bits of the Node + * hash field for lock control (see above), and so normally use + * builtin monitors only for blocking and signalling using + * wait/notifyAll constructions. See Node.tryAwaitLock. + * + * Using the first node of a list as a lock does not by itself + * suffice though: When a node is locked, any update must first + * validate that it is still the first node after locking it, and + * retry if not. Because new nodes are always appended to lists, + * once a node is first in a bin, it remains first until deleted + * or the bin becomes invalidated (upon resizing). However, + * operations that only conditionally update may inspect nodes + * until the point of update. This is a converse of sorts to the + * lazy locking technique described by Herlihy & Shavit. + * + * The main disadvantage of per-bin locks is that other update + * operations on other nodes in a bin list protected by the same + * lock can stall, for example when user equals() or mapping + * functions take a long time. However, statistically, under + * random hash codes, this is not a common problem. Ideally, the + * frequency of nodes in bins follows a Poisson distribution + * (http://en.wikipedia.org/wiki/Poisson_distribution) with a + * parameter of about 0.5 on average, given the resizing threshold + * of 0.75, although with a large variance because of resizing + * granularity. Ignoring variance, the expected occurrences of + * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The + * first values are: + * + * 0: 0.60653066 + * 1: 0.30326533 + * 2: 0.07581633 + * 3: 0.01263606 + * 4: 0.00157952 + * 5: 0.00015795 + * 6: 0.00001316 + * 7: 0.00000094 + * 8: 0.00000006 + * more: less than 1 in ten million + * + * Lock contention probability for two threads accessing distinct + * elements is roughly 1 / (8 * #elements) under random hashes. + * + * Actual hash code distributions encountered in practice + * sometimes deviate significantly from uniform randomness. This + * includes the case when N > (1<<30), so some keys MUST collide. + * Similarly for dumb or hostile usages in which multiple keys are + * designed to have identical hash codes. Also, although we guard + * against the worst effects of this (see method spread), sets of + * hashes may differ only in bits that do not impact their bin + * index for a given power-of-two mask. So we use a secondary + * strategy that applies when the number of nodes in a bin exceeds + * a threshold, and at least one of the keys implements + * Comparable. These TreeBins use a balanced tree to hold nodes + * (a specialized form of red-black trees), bounding search time + * to O(log N). Each search step in a TreeBin is around twice as + * slow as in a regular list, but given that N cannot exceed + * (1<<64) (before running out of addresses) this bounds search + * steps, lock hold times, etc, to reasonable constants (roughly + * 100 nodes inspected per operation worst case) so long as keys + * are Comparable (which is very common -- String, Long, etc). + * TreeBin nodes (TreeNodes) also maintain the same "next" + * traversal pointers as regular nodes, so can be traversed in + * iterators in the same way. + * + * The table is resized when occupancy exceeds a percentage + * threshold (nominally, 0.75, but see below). Only a single + * thread performs the resize (using field "sizeCtl", to arrange + * exclusion), but the table otherwise remains usable for reads + * and updates. Resizing proceeds by transferring bins, one by + * one, from the table to the next table. Because we are using + * power-of-two expansion, the elements from each bin must either + * stay at same index, or move with a power of two offset. We + * eliminate unnecessary node creation by catching cases where old + * nodes can be reused because their next fields won't change. On + * average, only about one-sixth of them need cloning when a table + * doubles. The nodes they replace will be garbage collectable as + * soon as they are no longer referenced by any reader thread that + * may be in the midst of concurrently traversing table. Upon + * transfer, the old table bin contains only a special forwarding + * node (with hash field "MOVED") that contains the next table as + * its key. On encountering a forwarding node, access and update + * operations restart, using the new table. + * + * Each bin transfer requires its bin lock. However, unlike other + * cases, a transfer can skip a bin if it fails to acquire its + * lock, and revisit it later (unless it is a TreeBin). Method + * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that + * have been skipped because of failure to acquire a lock, and + * blocks only if none are available (i.e., only very rarely). + * The transfer operation must also ensure that all accessible + * bins in both the old and new table are usable by any traversal. + * When there are no lock acquisition failures, this is arranged + * simply by proceeding from the last bin (table.length - 1) up + * towards the first. Upon seeing a forwarding node, traversals + * (see class Iter) arrange to move to the new table + * without revisiting nodes. However, when any node is skipped + * during a transfer, all earlier table bins may have become + * visible, so are initialized with a reverse-forwarding node back + * to the old table until the new ones are established. (This + * sometimes requires transiently locking a forwarding node, which + * is possible under the above encoding.) These more expensive + * mechanics trigger only when necessary. + * + * The traversal scheme also applies to partial traversals of + * ranges of bins (via an alternate Traverser constructor) + * to support partitioned aggregate operations. Also, read-only + * operations give up if ever forwarded to a null table, which + * provides support for shutdown-style clearing, which is also not + * currently implemented. + * + * Lazy table initialization minimizes footprint until first use, + * and also avoids resizings when the first operation is from a + * putAll, constructor with map argument, or deserialization. + * These cases attempt to override the initial capacity settings, + * but harmlessly fail to take effect in cases of races. + * + * The element count is maintained using a LongAdder, which avoids + * contention on updates but can encounter cache thrashing if read + * too frequently during concurrent access. To avoid reading so + * often, resizing is attempted either when a bin lock is + * contended, or upon adding to a bin already holding two or more + * nodes (checked before adding in the xIfAbsent methods, after + * adding in others). Under uniform hash distributions, the + * probability of this occurring at threshold is around 13%, + * meaning that only about 1 in 8 puts check threshold (and after + * resizing, many fewer do so). But this approximation has high + * variance for small table sizes, so we check on any collision + * for sizes <= 64. The bulk putAll operation further reduces + * contention by only committing count updates upon these size + * checks. + * + * Maintaining API and serialization compatibility with previous + * versions of this class introduces several oddities. Mainly: We + * leave untouched but unused constructor arguments refering to + * concurrencyLevel. We accept a loadFactor constructor argument, + * but apply it only to initial table capacity (which is the only + * time that we can guarantee to honor it.) We also declare an + * unused "Segment" class that is instantiated in minimal form + * only when serializing. + */ + + /* ---------------- Constants -------------- */ + + /** + * The largest possible table capacity. This value must be + * exactly 1<<30 to stay within Java array allocation and indexing + * bounds for power of two table sizes, and is further required + * because the top two bits of 32bit hash fields are used for + * control purposes. + */ + private static final int MAXIMUM_CAPACITY = 1 << 30; + + /** + * The default initial table capacity. Must be a power of 2 + * (i.e., at least 1) and at most MAXIMUM_CAPACITY. + */ + private static final int DEFAULT_CAPACITY = 16; + + /** + * The largest possible (non-power of two) array size. + * Needed by toArray and related methods. + */ + static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; + + /** + * The default concurrency level for this table. Unused but + * defined for compatibility with previous versions of this class. + */ + private static final int DEFAULT_CONCURRENCY_LEVEL = 16; + + /** + * The load factor for this table. Overrides of this value in + * constructors affect only the initial table capacity. The + * actual floating point value isn't normally used -- it is + * simpler to use expressions such as {@code n - (n >>> 2)} for + * the associated resizing threshold. + */ + private static final float LOAD_FACTOR = 0.75f; + + /** + * The buffer size for skipped bins during transfers. The + * value is arbitrary but should be large enough to avoid + * most locking stalls during resizes. + */ + private static final int TRANSFER_BUFFER_SIZE = 32; + + /** + * The bin count threshold for using a tree rather than list for a + * bin. The value reflects the approximate break-even point for + * using tree-based operations. + * Note that Doug's version defaults to 8, but when dealing with + * Ruby objects it is actually beneficial to avoid TreeNodes + * as long as possible as it usually means going into Ruby land. + */ + private static final int TREE_THRESHOLD = 16; + + /* + * Encodings for special uses of Node hash fields. See above for + * explanation. + */ + static final int MOVED = 0x80000000; // hash field for forwarding nodes + static final int LOCKED = 0x40000000; // set/tested only as a bit + static final int WAITING = 0xc0000000; // both bits set/tested together + static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash + + /* ---------------- Fields -------------- */ + + /** + * The array of bins. Lazily initialized upon first insertion. + * Size is always a power of two. Accessed directly by iterators. + */ + transient volatile Node[] table; + + /** + * The counter maintaining number of elements. + */ + private transient final LongAdder counter; + + /** + * Table initialization and resizing control. When negative, the + * table is being initialized or resized. Otherwise, when table is + * null, holds the initial table size to use upon creation, or 0 + * for default. After initialization, holds the next element count + * value upon which to resize the table. + */ + private transient volatile int sizeCtl; + + // views + private transient KeySetView keySet; + private transient ValuesView values; + private transient EntrySetView entrySet; + + /** For serialization compatibility. Null unless serialized; see below */ + private Segment[] segments; + + /* ---------------- Table element access -------------- */ + + /* + * Volatile access methods are used for table elements as well as + * elements of in-progress next table while resizing. Uses are + * null checked by callers, and implicitly bounds-checked, relying + * on the invariants that tab arrays have non-zero size, and all + * indices are masked with (tab.length - 1) which is never + * negative and always less than length. Note that, to be correct + * wrt arbitrary concurrency errors by users, bounds checks must + * operate on local variables, which accounts for some odd-looking + * inline assignments below. + */ + + static final Node tabAt(Node[] tab, int i) { // used by Iter + return (Node)UNSAFE.getObjectVolatile(tab, ((long)i< 1 ? 64 : 1; + + /** + * Spins a while if LOCKED bit set and this node is the first + * of its bin, and then sets WAITING bits on hash field and + * blocks (once) if they are still set. It is OK for this + * method to return even if lock is not available upon exit, + * which enables these simple single-wait mechanics. + * + * The corresponding signalling operation is performed within + * callers: Upon detecting that WAITING has been set when + * unlocking lock (via a failed CAS from non-waiting LOCKED + * state), unlockers acquire the sync lock and perform a + * notifyAll. + * + * The initial sanity check on tab and bounds is not currently + * necessary in the only usages of this method, but enables + * use in other future contexts. + */ + final void tryAwaitLock(Node[] tab, int i) { + if (tab != null && i >= 0 && i < tab.length) { // sanity check + int r = ThreadLocalRandom.current().nextInt(); // randomize spins + int spins = MAX_SPINS, h; + while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) { + if (spins >= 0) { + r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift + if (r >= 0 && --spins == 0) + Thread.yield(); // yield before block + } + else if (casHash(h, h | WAITING)) { + synchronized (this) { + if (tabAt(tab, i) == this && + (hash & WAITING) == WAITING) { + try { + wait(); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + } + } + else + notifyAll(); // possibly won race vs signaller + } + break; + } + } + } + } + + // Unsafe mechanics for casHash + private static final sun.misc.Unsafe UNSAFE; + private static final long hashOffset; + + static { + try { + UNSAFE = getUnsafe(); + Class k = Node.class; + hashOffset = UNSAFE.objectFieldOffset + (k.getDeclaredField("hash")); + } catch (Exception e) { + throw new Error(e); + } + } + } + + /* ---------------- TreeBins -------------- */ + + /** + * Nodes for use in TreeBins + */ + static final class TreeNode extends Node { + TreeNode parent; // red-black tree links + TreeNode left; + TreeNode right; + TreeNode prev; // needed to unlink next upon deletion + boolean red; + + TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) { + super(hash, key, val, next); + this.parent = parent; + } + } + + /** + * A specialized form of red-black tree for use in bins + * whose size exceeds a threshold. + * + * TreeBins use a special form of comparison for search and + * related operations (which is the main reason we cannot use + * existing collections such as TreeMaps). TreeBins contain + * Comparable elements, but may contain others, as well as + * elements that are Comparable but not necessarily Comparable + * for the same T, so we cannot invoke compareTo among them. To + * handle this, the tree is ordered primarily by hash value, then + * by getClass().getName() order, and then by Comparator order + * among elements of the same class. On lookup at a node, if + * elements are not comparable or compare as 0, both left and + * right children may need to be searched in the case of tied hash + * values. (This corresponds to the full list search that would be + * necessary if all elements were non-Comparable and had tied + * hashes.) The red-black balancing code is updated from + * pre-jdk-collections + * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java) + * based in turn on Cormen, Leiserson, and Rivest "Introduction to + * Algorithms" (CLR). + * + * TreeBins also maintain a separate locking discipline than + * regular bins. Because they are forwarded via special MOVED + * nodes at bin heads (which can never change once established), + * we cannot use those nodes as locks. Instead, TreeBin + * extends AbstractQueuedSynchronizer to support a simple form of + * read-write lock. For update operations and table validation, + * the exclusive form of lock behaves in the same way as bin-head + * locks. However, lookups use shared read-lock mechanics to allow + * multiple readers in the absence of writers. Additionally, + * these lookups do not ever block: While the lock is not + * available, they proceed along the slow traversal path (via + * next-pointers) until the lock becomes available or the list is + * exhausted, whichever comes first. (These cases are not fast, + * but maximize aggregate expected throughput.) The AQS mechanics + * for doing this are straightforward. The lock state is held as + * AQS getState(). Read counts are negative; the write count (1) + * is positive. There are no signalling preferences among readers + * and writers. Since we don't need to export full Lock API, we + * just override the minimal AQS methods and use them directly. + */ + static final class TreeBin extends AbstractQueuedSynchronizer { + private static final long serialVersionUID = 2249069246763182397L; + transient TreeNode root; // root of tree + transient TreeNode first; // head of next-pointer list + + /* AQS overrides */ + public final boolean isHeldExclusively() { return getState() > 0; } + public final boolean tryAcquire(int ignore) { + if (compareAndSetState(0, 1)) { + setExclusiveOwnerThread(Thread.currentThread()); + return true; + } + return false; + } + public final boolean tryRelease(int ignore) { + setExclusiveOwnerThread(null); + setState(0); + return true; + } + public final int tryAcquireShared(int ignore) { + for (int c;;) { + if ((c = getState()) > 0) + return -1; + if (compareAndSetState(c, c -1)) + return 1; + } + } + public final boolean tryReleaseShared(int ignore) { + int c; + do {} while (!compareAndSetState(c = getState(), c + 1)); + return c == -1; + } + + /** From CLR */ + private void rotateLeft(TreeNode p) { + if (p != null) { + TreeNode r = p.right, pp, rl; + if ((rl = p.right = r.left) != null) + rl.parent = p; + if ((pp = r.parent = p.parent) == null) + root = r; + else if (pp.left == p) + pp.left = r; + else + pp.right = r; + r.left = p; + p.parent = r; + } + } + + /** From CLR */ + private void rotateRight(TreeNode p) { + if (p != null) { + TreeNode l = p.left, pp, lr; + if ((lr = p.left = l.right) != null) + lr.parent = p; + if ((pp = l.parent = p.parent) == null) + root = l; + else if (pp.right == p) + pp.right = l; + else + pp.left = l; + l.right = p; + p.parent = l; + } + } + + @SuppressWarnings("unchecked") final TreeNode getTreeNode + (int h, Object k, TreeNode p) { + return getTreeNode(h, (RubyObject)k, p); + } + + /** + * Returns the TreeNode (or null if not found) for the given key + * starting at given root. + */ + @SuppressWarnings("unchecked") final TreeNode getTreeNode + (int h, RubyObject k, TreeNode p) { + RubyClass c = k.getMetaClass(); boolean kNotComparable = !k.respondsTo("<=>"); + while (p != null) { + int dir, ph; RubyObject pk; RubyClass pc; + if ((ph = p.hash) == h) { + if ((pk = (RubyObject)p.key) == k || k.equals(pk)) + return p; + if (c != (pc = (RubyClass)pk.getMetaClass()) || + kNotComparable || + (dir = rubyCompare(k, pk)) == 0) { + dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName()); + if (dir == 0) { // if still stuck, need to check both sides + TreeNode r = null, pl, pr; + // try to recurse on the right + if ((pr = p.right) != null && h >= pr.hash && (r = getTreeNode(h, k, pr)) != null) + return r; + // try to continue iterating on the left side + else if ((pl = p.left) != null && h <= pl.hash) + dir = -1; + else // no matching node found + return null; + } + } + } + else + dir = (h < ph) ? -1 : 1; + p = (dir > 0) ? p.right : p.left; + } + return null; + } + + int rubyCompare(RubyObject l, RubyObject r) { + ThreadContext context = l.getMetaClass().getRuntime().getCurrentContext(); + IRubyObject result; + try { + result = l.callMethod(context, "<=>", r); + } catch (RaiseException e) { + // handle objects "lying" about responding to <=>, ie: an Array containing non-comparable keys + if (context.runtime.getNoMethodError().isInstance(e.getException())) { + return 0; + } + throw e; + } + + return result.isNil() ? 0 : RubyNumeric.num2int(result.convertToInteger()); + } + + /** + * Wrapper for getTreeNode used by CHM.get. Tries to obtain + * read-lock to call getTreeNode, but during failure to get + * lock, searches along next links. + */ + final Object getValue(int h, Object k) { + Node r = null; + int c = getState(); // Must read lock state first + for (Node e = first; e != null; e = e.next) { + if (c <= 0 && compareAndSetState(c, c - 1)) { + try { + r = getTreeNode(h, k, root); + } finally { + releaseShared(0); + } + break; + } + else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) { + r = e; + break; + } + else + c = getState(); + } + return r == null ? null : r.val; + } + + @SuppressWarnings("unchecked") final TreeNode putTreeNode + (int h, Object k, Object v) { + return putTreeNode(h, (RubyObject)k, v); + } + + /** + * Finds or adds a node. + * @return null if added + */ + @SuppressWarnings("unchecked") final TreeNode putTreeNode + (int h, RubyObject k, Object v) { + RubyClass c = k.getMetaClass(); + boolean kNotComparable = !k.respondsTo("<=>"); + TreeNode pp = root, p = null; + int dir = 0; + while (pp != null) { // find existing node or leaf to insert at + int ph; RubyObject pk; RubyClass pc; + p = pp; + if ((ph = p.hash) == h) { + if ((pk = (RubyObject)p.key) == k || k.equals(pk)) + return p; + if (c != (pc = pk.getMetaClass()) || + kNotComparable || + (dir = rubyCompare(k, pk)) == 0) { + dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName()); + if (dir == 0) { // if still stuck, need to check both sides + TreeNode r = null, pr; + // try to recurse on the right + if ((pr = p.right) != null && h >= pr.hash && (r = getTreeNode(h, k, pr)) != null) + return r; + else // continue descending down the left subtree + dir = -1; + } + } + } + else + dir = (h < ph) ? -1 : 1; + pp = (dir > 0) ? p.right : p.left; + } + + TreeNode f = first; + TreeNode x = first = new TreeNode(h, (Object)k, v, f, p); + if (p == null) + root = x; + else { // attach and rebalance; adapted from CLR + TreeNode xp, xpp; + if (f != null) + f.prev = x; + if (dir <= 0) + p.left = x; + else + p.right = x; + x.red = true; + while (x != null && (xp = x.parent) != null && xp.red && + (xpp = xp.parent) != null) { + TreeNode xppl = xpp.left; + if (xp == xppl) { + TreeNode y = xpp.right; + if (y != null && y.red) { + y.red = false; + xp.red = false; + xpp.red = true; + x = xpp; + } + else { + if (x == xp.right) { + rotateLeft(x = xp); + xpp = (xp = x.parent) == null ? null : xp.parent; + } + if (xp != null) { + xp.red = false; + if (xpp != null) { + xpp.red = true; + rotateRight(xpp); + } + } + } + } + else { + TreeNode y = xppl; + if (y != null && y.red) { + y.red = false; + xp.red = false; + xpp.red = true; + x = xpp; + } + else { + if (x == xp.left) { + rotateRight(x = xp); + xpp = (xp = x.parent) == null ? null : xp.parent; + } + if (xp != null) { + xp.red = false; + if (xpp != null) { + xpp.red = true; + rotateLeft(xpp); + } + } + } + } + } + TreeNode r = root; + if (r != null && r.red) + r.red = false; + } + return null; + } + + /** + * Removes the given node, that must be present before this + * call. This is messier than typical red-black deletion code + * because we cannot swap the contents of an interior node + * with a leaf successor that is pinned by "next" pointers + * that are accessible independently of lock. So instead we + * swap the tree linkages. + */ + final void deleteTreeNode(TreeNode p) { + TreeNode next = (TreeNode)p.next; // unlink traversal pointers + TreeNode pred = p.prev; + if (pred == null) + first = next; + else + pred.next = next; + if (next != null) + next.prev = pred; + TreeNode replacement; + TreeNode pl = p.left; + TreeNode pr = p.right; + if (pl != null && pr != null) { + TreeNode s = pr, sl; + while ((sl = s.left) != null) // find successor + s = sl; + boolean c = s.red; s.red = p.red; p.red = c; // swap colors + TreeNode sr = s.right; + TreeNode pp = p.parent; + if (s == pr) { // p was s's direct parent + p.parent = s; + s.right = p; + } + else { + TreeNode sp = s.parent; + if ((p.parent = sp) != null) { + if (s == sp.left) + sp.left = p; + else + sp.right = p; + } + if ((s.right = pr) != null) + pr.parent = s; + } + p.left = null; + if ((p.right = sr) != null) + sr.parent = p; + if ((s.left = pl) != null) + pl.parent = s; + if ((s.parent = pp) == null) + root = s; + else if (p == pp.left) + pp.left = s; + else + pp.right = s; + replacement = sr; + } + else + replacement = (pl != null) ? pl : pr; + TreeNode pp = p.parent; + if (replacement == null) { + if (pp == null) { + root = null; + return; + } + replacement = p; + } + else { + replacement.parent = pp; + if (pp == null) + root = replacement; + else if (p == pp.left) + pp.left = replacement; + else + pp.right = replacement; + p.left = p.right = p.parent = null; + } + if (!p.red) { // rebalance, from CLR + TreeNode x = replacement; + while (x != null) { + TreeNode xp, xpl; + if (x.red || (xp = x.parent) == null) { + x.red = false; + break; + } + if (x == (xpl = xp.left)) { + TreeNode sib = xp.right; + if (sib != null && sib.red) { + sib.red = false; + xp.red = true; + rotateLeft(xp); + sib = (xp = x.parent) == null ? null : xp.right; + } + if (sib == null) + x = xp; + else { + TreeNode sl = sib.left, sr = sib.right; + if ((sr == null || !sr.red) && + (sl == null || !sl.red)) { + sib.red = true; + x = xp; + } + else { + if (sr == null || !sr.red) { + if (sl != null) + sl.red = false; + sib.red = true; + rotateRight(sib); + sib = (xp = x.parent) == null ? null : xp.right; + } + if (sib != null) { + sib.red = (xp == null) ? false : xp.red; + if ((sr = sib.right) != null) + sr.red = false; + } + if (xp != null) { + xp.red = false; + rotateLeft(xp); + } + x = root; + } + } + } + else { // symmetric + TreeNode sib = xpl; + if (sib != null && sib.red) { + sib.red = false; + xp.red = true; + rotateRight(xp); + sib = (xp = x.parent) == null ? null : xp.left; + } + if (sib == null) + x = xp; + else { + TreeNode sl = sib.left, sr = sib.right; + if ((sl == null || !sl.red) && + (sr == null || !sr.red)) { + sib.red = true; + x = xp; + } + else { + if (sl == null || !sl.red) { + if (sr != null) + sr.red = false; + sib.red = true; + rotateLeft(sib); + sib = (xp = x.parent) == null ? null : xp.left; + } + if (sib != null) { + sib.red = (xp == null) ? false : xp.red; + if ((sl = sib.left) != null) + sl.red = false; + } + if (xp != null) { + xp.red = false; + rotateRight(xp); + } + x = root; + } + } + } + } + } + if (p == replacement && (pp = p.parent) != null) { + if (p == pp.left) // detach pointers + pp.left = null; + else if (p == pp.right) + pp.right = null; + p.parent = null; + } + } + } + + /* ---------------- Collision reduction methods -------------- */ + + /** + * Spreads higher bits to lower, and also forces top 2 bits to 0. + * Because the table uses power-of-two masking, sets of hashes + * that vary only in bits above the current mask will always + * collide. (Among known examples are sets of Float keys holding + * consecutive whole numbers in small tables.) To counter this, + * we apply a transform that spreads the impact of higher bits + * downward. There is a tradeoff between speed, utility, and + * quality of bit-spreading. Because many common sets of hashes + * are already reasonably distributed across bits (so don't benefit + * from spreading), and because we use trees to handle large sets + * of collisions in bins, we don't need excessively high quality. + */ + private static final int spread(int h) { + h ^= (h >>> 18) ^ (h >>> 12); + return (h ^ (h >>> 10)) & HASH_BITS; + } + + /** + * Replaces a list bin with a tree bin. Call only when locked. + * Fails to replace if the given key is non-comparable or table + * is, or needs, resizing. + */ + private final void replaceWithTreeBin(Node[] tab, int index, Object key) { + if ((key instanceof Comparable) && + (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) { + TreeBin t = new TreeBin(); + for (Node e = tabAt(tab, index); e != null; e = e.next) + t.putTreeNode(e.hash & HASH_BITS, e.key, e.val); + setTabAt(tab, index, new Node(MOVED, t, null, null)); + } + } + + /* ---------------- Internal access and update methods -------------- */ + + /** Implementation for get and containsKey */ + private final Object internalGet(Object k) { + int h = spread(k.hashCode()); + retry: for (Node[] tab = table; tab != null;) { + Node e, p; Object ek, ev; int eh; // locals to read fields once + for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) { + if ((eh = e.hash) == MOVED) { + if ((ek = e.key) instanceof TreeBin) // search TreeBin + return ((TreeBin)ek).getValue(h, k); + else { // restart with new table + tab = (Node[])ek; + continue retry; + } + } + else if ((eh & HASH_BITS) == h && (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) + return ev; + } + break; + } + return null; + } + + /** + * Implementation for the four public remove/replace methods: + * Replaces node value with v, conditional upon match of cv if + * non-null. If resulting value is null, delete. + */ + private final Object internalReplace(Object k, Object v, Object cv) { + int h = spread(k.hashCode()); + Object oldVal = null; + for (Node[] tab = table;;) { + Node f; int i, fh; Object fk; + if (tab == null || + (f = tabAt(tab, i = (tab.length - 1) & h)) == null) + break; + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + boolean validated = false; + boolean deleted = false; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + validated = true; + TreeNode p = t.getTreeNode(h, k, t.root); + if (p != null) { + Object pv = p.val; + if (cv == null || cv == pv || cv.equals(pv)) { + oldVal = pv; + if ((p.val = v) == null) { + deleted = true; + t.deleteTreeNode(p); + } + } + } + } + } finally { + t.release(0); + } + if (validated) { + if (deleted) + counter.add(-1L); + break; + } + } + else + tab = (Node[])fk; + } + else if ((fh & HASH_BITS) != h && f.next == null) // precheck + break; // rules out possible existence + else if ((fh & LOCKED) != 0) { + checkForResize(); // try resizing if can't get lock + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + boolean validated = false; + boolean deleted = false; + try { + if (tabAt(tab, i) == f) { + validated = true; + for (Node e = f, pred = null;;) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + ((ev = e.val) != null) && + ((ek = e.key) == k || k.equals(ek))) { + if (cv == null || cv == ev || cv.equals(ev)) { + oldVal = ev; + if ((e.val = v) == null) { + deleted = true; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); + } + } + break; + } + pred = e; + if ((e = e.next) == null) + break; + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (validated) { + if (deleted) + counter.add(-1L); + break; + } + } + } + return oldVal; + } + + /* + * Internal versions of the six insertion methods, each a + * little more complicated than the last. All have + * the same basic structure as the first (internalPut): + * 1. If table uninitialized, create + * 2. If bin empty, try to CAS new node + * 3. If bin stale, use new table + * 4. if bin converted to TreeBin, validate and relay to TreeBin methods + * 5. Lock and validate; if valid, scan and add or update + * + * The others interweave other checks and/or alternative actions: + * * Plain put checks for and performs resize after insertion. + * * putIfAbsent prescans for mapping without lock (and fails to add + * if present), which also makes pre-emptive resize checks worthwhile. + * * computeIfAbsent extends form used in putIfAbsent with additional + * mechanics to deal with, calls, potential exceptions and null + * returns from function call. + * * compute uses the same function-call mechanics, but without + * the prescans + * * merge acts as putIfAbsent in the absent case, but invokes the + * update function if present + * * putAll attempts to pre-allocate enough table space + * and more lazily performs count updates and checks. + * + * Someday when details settle down a bit more, it might be worth + * some factoring to reduce sprawl. + */ + + /** Implementation for put */ + private final Object internalPut(Object k, Object v) { + int h = spread(k.hashCode()); + int count = 0; + for (Node[] tab = table;;) { + int i; Node f; int fh; Object fk; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) { + if (casTabAt(tab, i, null, new Node(h, k, v, null))) + break; // no lock when adding to empty bin + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + Object oldVal = null; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + count = 2; + TreeNode p = t.putTreeNode(h, k, v); + if (p != null) { + oldVal = p.val; + p.val = v; + } + } + } finally { + t.release(0); + } + if (count != 0) { + if (oldVal != null) + return oldVal; + break; + } + } + else + tab = (Node[])fk; + } + else if ((fh & LOCKED) != 0) { + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + Object oldVal = null; + try { // needed in case equals() throws + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + oldVal = ev; + e.val = v; + break; + } + Node last = e; + if ((e = e.next) == null) { + last.next = new Node(h, k, v, null); + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + break; + } + } + } + } finally { // unlock and signal if needed + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (oldVal != null) + return oldVal; + if (tab.length <= 64) + count = 2; + break; + } + } + } + counter.add(1L); + if (count > 1) + checkForResize(); + return null; + } + + /** Implementation for putIfAbsent */ + private final Object internalPutIfAbsent(Object k, Object v) { + int h = spread(k.hashCode()); + int count = 0; + for (Node[] tab = table;;) { + int i; Node f; int fh; Object fk, fv; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) { + if (casTabAt(tab, i, null, new Node(h, k, v, null))) + break; + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + Object oldVal = null; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + count = 2; + TreeNode p = t.putTreeNode(h, k, v); + if (p != null) + oldVal = p.val; + } + } finally { + t.release(0); + } + if (count != 0) { + if (oldVal != null) + return oldVal; + break; + } + } + else + tab = (Node[])fk; + } + else if ((fh & HASH_BITS) == h && (fv = f.val) != null && + ((fk = f.key) == k || k.equals(fk))) + return fv; + else { + Node g = f.next; + if (g != null) { // at least 2 nodes -- search and maybe resize + for (Node e = g;;) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) + return ev; + if ((e = e.next) == null) { + checkForResize(); + break; + } + } + } + if (((fh = f.hash) & LOCKED) != 0) { + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) { + Object oldVal = null; + try { + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + oldVal = ev; + break; + } + Node last = e; + if ((e = e.next) == null) { + last.next = new Node(h, k, v, null); + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + break; + } + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (oldVal != null) + return oldVal; + if (tab.length <= 64) + count = 2; + break; + } + } + } + } + counter.add(1L); + if (count > 1) + checkForResize(); + return null; + } + + /** Implementation for computeIfAbsent */ + private final Object internalComputeIfAbsent(K k, + Fun mf) { + int h = spread(k.hashCode()); + Object val = null; + int count = 0; + for (Node[] tab = table;;) { + Node f; int i, fh; Object fk, fv; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) { + Node node = new Node(fh = h | LOCKED, k, null, null); + if (casTabAt(tab, i, null, node)) { + count = 1; + try { + if ((val = mf.apply(k)) != null) + node.val = val; + } finally { + if (val == null) + setTabAt(tab, i, null); + if (!node.casHash(fh, h)) { + node.hash = h; + synchronized (node) { node.notifyAll(); }; + } + } + } + if (count != 0) + break; + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + boolean added = false; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + count = 1; + TreeNode p = t.getTreeNode(h, k, t.root); + if (p != null) + val = p.val; + else if ((val = mf.apply(k)) != null) { + added = true; + count = 2; + t.putTreeNode(h, k, val); + } + } + } finally { + t.release(0); + } + if (count != 0) { + if (!added) + return val; + break; + } + } + else + tab = (Node[])fk; + } + else if ((fh & HASH_BITS) == h && (fv = f.val) != null && + ((fk = f.key) == k || k.equals(fk))) + return fv; + else { + Node g = f.next; + if (g != null) { + for (Node e = g;;) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) + return ev; + if ((e = e.next) == null) { + checkForResize(); + break; + } + } + } + if (((fh = f.hash) & LOCKED) != 0) { + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) { + boolean added = false; + try { + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + val = ev; + break; + } + Node last = e; + if ((e = e.next) == null) { + if ((val = mf.apply(k)) != null) { + added = true; + last.next = new Node(h, k, val, null); + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + } + break; + } + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (!added) + return val; + if (tab.length <= 64) + count = 2; + break; + } + } + } + } + if (val != null) { + counter.add(1L); + if (count > 1) + checkForResize(); + } + return val; + } + + /** Implementation for compute */ + @SuppressWarnings("unchecked") private final Object internalCompute + (K k, boolean onlyIfPresent, BiFun mf) { + int h = spread(k.hashCode()); + Object val = null; + int delta = 0; + int count = 0; + for (Node[] tab = table;;) { + Node f; int i, fh; Object fk; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) { + if (onlyIfPresent) + break; + Node node = new Node(fh = h | LOCKED, k, null, null); + if (casTabAt(tab, i, null, node)) { + try { + count = 1; + if ((val = mf.apply(k, null)) != null) { + node.val = val; + delta = 1; + } + } finally { + if (delta == 0) + setTabAt(tab, i, null); + if (!node.casHash(fh, h)) { + node.hash = h; + synchronized (node) { node.notifyAll(); }; + } + } + } + if (count != 0) + break; + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + count = 1; + TreeNode p = t.getTreeNode(h, k, t.root); + Object pv; + if (p == null) { + if (onlyIfPresent) + break; + pv = null; + } else + pv = p.val; + if ((val = mf.apply(k, (V)pv)) != null) { + if (p != null) + p.val = val; + else { + count = 2; + delta = 1; + t.putTreeNode(h, k, val); + } + } + else if (p != null) { + delta = -1; + t.deleteTreeNode(p); + } + } + } finally { + t.release(0); + } + if (count != 0) + break; + } + else + tab = (Node[])fk; + } + else if ((fh & LOCKED) != 0) { + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + try { + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f, pred = null;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + val = mf.apply(k, (V)ev); + if (val != null) + e.val = val; + else { + delta = -1; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); + } + break; + } + pred = e; + if ((e = e.next) == null) { + if (!onlyIfPresent && (val = mf.apply(k, null)) != null) { + pred.next = new Node(h, k, val, null); + delta = 1; + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + } + break; + } + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (tab.length <= 64) + count = 2; + break; + } + } + } + if (delta != 0) { + counter.add((long)delta); + if (count > 1) + checkForResize(); + } + return val; + } + + /** Implementation for merge */ + @SuppressWarnings("unchecked") private final Object internalMerge + (K k, V v, BiFun mf) { + int h = spread(k.hashCode()); + Object val = null; + int delta = 0; + int count = 0; + for (Node[] tab = table;;) { + int i; Node f; int fh; Object fk, fv; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) { + if (casTabAt(tab, i, null, new Node(h, k, v, null))) { + delta = 1; + val = v; + break; + } + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + count = 1; + TreeNode p = t.getTreeNode(h, k, t.root); + val = (p == null) ? v : mf.apply((V)p.val, v); + if (val != null) { + if (p != null) + p.val = val; + else { + count = 2; + delta = 1; + t.putTreeNode(h, k, val); + } + } + else if (p != null) { + delta = -1; + t.deleteTreeNode(p); + } + } + } finally { + t.release(0); + } + if (count != 0) + break; + } + else + tab = (Node[])fk; + } + else if ((fh & LOCKED) != 0) { + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + try { + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f, pred = null;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + val = mf.apply((V)ev, v); + if (val != null) + e.val = val; + else { + delta = -1; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); + } + break; + } + pred = e; + if ((e = e.next) == null) { + val = v; + pred.next = new Node(h, k, val, null); + delta = 1; + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + break; + } + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (tab.length <= 64) + count = 2; + break; + } + } + } + if (delta != 0) { + counter.add((long)delta); + if (count > 1) + checkForResize(); + } + return val; + } + + /** Implementation for putAll */ + private final void internalPutAll(Map m) { + tryPresize(m.size()); + long delta = 0L; // number of uncommitted additions + boolean npe = false; // to throw exception on exit for nulls + try { // to clean up counts on other exceptions + for (Map.Entry entry : m.entrySet()) { + Object k, v; + if (entry == null || (k = entry.getKey()) == null || + (v = entry.getValue()) == null) { + npe = true; + break; + } + int h = spread(k.hashCode()); + for (Node[] tab = table;;) { + int i; Node f; int fh; Object fk; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){ + if (casTabAt(tab, i, null, new Node(h, k, v, null))) { + ++delta; + break; + } + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + boolean validated = false; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + validated = true; + TreeNode p = t.getTreeNode(h, k, t.root); + if (p != null) + p.val = v; + else { + t.putTreeNode(h, k, v); + ++delta; + } + } + } finally { + t.release(0); + } + if (validated) + break; + } + else + tab = (Node[])fk; + } + else if ((fh & LOCKED) != 0) { + counter.add(delta); + delta = 0L; + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + int count = 0; + try { + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + e.val = v; + break; + } + Node last = e; + if ((e = e.next) == null) { + ++delta; + last.next = new Node(h, k, v, null); + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + break; + } + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (count > 1) { + counter.add(delta); + delta = 0L; + checkForResize(); + } + break; + } + } + } + } + } finally { + if (delta != 0) + counter.add(delta); + } + if (npe) + throw new NullPointerException(); + } + + /* ---------------- Table Initialization and Resizing -------------- */ + + /** + * Returns a power of two table size for the given desired capacity. + * See Hackers Delight, sec 3.2 + */ + private static final int tableSizeFor(int c) { + int n = c - 1; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; + } + + /** + * Initializes table, using the size recorded in sizeCtl. + */ + private final Node[] initTable() { + Node[] tab; int sc; + while ((tab = table) == null) { + if ((sc = sizeCtl) < 0) + Thread.yield(); // lost initialization race; just spin + else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) { + try { + if ((tab = table) == null) { + int n = (sc > 0) ? sc : DEFAULT_CAPACITY; + tab = table = new Node[n]; + sc = n - (n >>> 2); + } + } finally { + sizeCtl = sc; + } + break; + } + } + return tab; + } + + /** + * If table is too small and not already resizing, creates next + * table and transfers bins. Rechecks occupancy after a transfer + * to see if another resize is already needed because resizings + * are lagging additions. + */ + private final void checkForResize() { + Node[] tab; int n, sc; + while ((tab = table) != null && + (n = tab.length) < MAXIMUM_CAPACITY && + (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc && + UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) { + try { + if (tab == table) { + table = rebuild(tab); + sc = (n << 1) - (n >>> 1); + } + } finally { + sizeCtl = sc; + } + } + } + + /** + * Tries to presize table to accommodate the given number of elements. + * + * @param size number of elements (doesn't need to be perfectly accurate) + */ + private final void tryPresize(int size) { + int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : + tableSizeFor(size + (size >>> 1) + 1); + int sc; + while ((sc = sizeCtl) >= 0) { + Node[] tab = table; int n; + if (tab == null || (n = tab.length) == 0) { + n = (sc > c) ? sc : c; + if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) { + try { + if (table == tab) { + table = new Node[n]; + sc = n - (n >>> 2); + } + } finally { + sizeCtl = sc; + } + } + } + else if (c <= sc || n >= MAXIMUM_CAPACITY) + break; + else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) { + try { + if (table == tab) { + table = rebuild(tab); + sc = (n << 1) - (n >>> 1); + } + } finally { + sizeCtl = sc; + } + } + } + } + + /* + * Moves and/or copies the nodes in each bin to new table. See + * above for explanation. + * + * @return the new table + */ + private static final Node[] rebuild(Node[] tab) { + int n = tab.length; + Node[] nextTab = new Node[n << 1]; + Node fwd = new Node(MOVED, nextTab, null, null); + int[] buffer = null; // holds bins to revisit; null until needed + Node rev = null; // reverse forwarder; null until needed + int nbuffered = 0; // the number of bins in buffer list + int bufferIndex = 0; // buffer index of current buffered bin + int bin = n - 1; // current non-buffered bin or -1 if none + + for (int i = bin;;) { // start upwards sweep + int fh; Node f; + if ((f = tabAt(tab, i)) == null) { + if (bin >= 0) { // Unbuffered; no lock needed (or available) + if (!casTabAt(tab, i, f, fwd)) + continue; + } + else { // transiently use a locked forwarding node + Node g = new Node(MOVED|LOCKED, nextTab, null, null); + if (!casTabAt(tab, i, f, g)) + continue; + setTabAt(nextTab, i, null); + setTabAt(nextTab, i + n, null); + setTabAt(tab, i, fwd); + if (!g.casHash(MOVED|LOCKED, MOVED)) { + g.hash = MOVED; + synchronized (g) { g.notifyAll(); } + } + } + } + else if ((fh = f.hash) == MOVED) { + Object fk = f.key; + if (fk instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + boolean validated = false; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + validated = true; + splitTreeBin(nextTab, i, t); + setTabAt(tab, i, fwd); + } + } finally { + t.release(0); + } + if (!validated) + continue; + } + } + else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) { + boolean validated = false; + try { // split to lo and hi lists; copying as needed + if (tabAt(tab, i) == f) { + validated = true; + splitBin(nextTab, i, f); + setTabAt(tab, i, fwd); + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (!validated) + continue; + } + else { + if (buffer == null) // initialize buffer for revisits + buffer = new int[TRANSFER_BUFFER_SIZE]; + if (bin < 0 && bufferIndex > 0) { + int j = buffer[--bufferIndex]; + buffer[bufferIndex] = i; + i = j; // swap with another bin + continue; + } + if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) { + f.tryAwaitLock(tab, i); + continue; // no other options -- block + } + if (rev == null) // initialize reverse-forwarder + rev = new Node(MOVED, tab, null, null); + if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0) + continue; // recheck before adding to list + buffer[nbuffered++] = i; + setTabAt(nextTab, i, rev); // install place-holders + setTabAt(nextTab, i + n, rev); + } + + if (bin > 0) + i = --bin; + else if (buffer != null && nbuffered > 0) { + bin = -1; + i = buffer[bufferIndex = --nbuffered]; + } + else + return nextTab; + } + } + + /** + * Splits a normal bin with list headed by e into lo and hi parts; + * installs in given table. + */ + private static void splitBin(Node[] nextTab, int i, Node e) { + int bit = nextTab.length >>> 1; // bit to split on + int runBit = e.hash & bit; + Node lastRun = e, lo = null, hi = null; + for (Node p = e.next; p != null; p = p.next) { + int b = p.hash & bit; + if (b != runBit) { + runBit = b; + lastRun = p; + } + } + if (runBit == 0) + lo = lastRun; + else + hi = lastRun; + for (Node p = e; p != lastRun; p = p.next) { + int ph = p.hash & HASH_BITS; + Object pk = p.key, pv = p.val; + if ((ph & bit) == 0) + lo = new Node(ph, pk, pv, lo); + else + hi = new Node(ph, pk, pv, hi); + } + setTabAt(nextTab, i, lo); + setTabAt(nextTab, i + bit, hi); + } + + /** + * Splits a tree bin into lo and hi parts; installs in given table. + */ + private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) { + int bit = nextTab.length >>> 1; + TreeBin lt = new TreeBin(); + TreeBin ht = new TreeBin(); + int lc = 0, hc = 0; + for (Node e = t.first; e != null; e = e.next) { + int h = e.hash & HASH_BITS; + Object k = e.key, v = e.val; + if ((h & bit) == 0) { + ++lc; + lt.putTreeNode(h, k, v); + } + else { + ++hc; + ht.putTreeNode(h, k, v); + } + } + Node ln, hn; // throw away trees if too small + if (lc <= (TREE_THRESHOLD >>> 1)) { + ln = null; + for (Node p = lt.first; p != null; p = p.next) + ln = new Node(p.hash, p.key, p.val, ln); + } + else + ln = new Node(MOVED, lt, null, null); + setTabAt(nextTab, i, ln); + if (hc <= (TREE_THRESHOLD >>> 1)) { + hn = null; + for (Node p = ht.first; p != null; p = p.next) + hn = new Node(p.hash, p.key, p.val, hn); + } + else + hn = new Node(MOVED, ht, null, null); + setTabAt(nextTab, i + bit, hn); + } + + /** + * Implementation for clear. Steps through each bin, removing all + * nodes. + */ + private final void internalClear() { + long delta = 0L; // negative number of deletions + int i = 0; + Node[] tab = table; + while (tab != null && i < tab.length) { + int fh; Object fk; + Node f = tabAt(tab, i); + if (f == null) + ++i; + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + for (Node p = t.first; p != null; p = p.next) { + if (p.val != null) { // (currently always true) + p.val = null; + --delta; + } + } + t.first = null; + t.root = null; + ++i; + } + } finally { + t.release(0); + } + } + else + tab = (Node[])fk; + } + else if ((fh & LOCKED) != 0) { + counter.add(delta); // opportunistically update count + delta = 0L; + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + try { + if (tabAt(tab, i) == f) { + for (Node e = f; e != null; e = e.next) { + if (e.val != null) { // (currently always true) + e.val = null; + --delta; + } + } + setTabAt(tab, i, null); + ++i; + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + } + } + if (delta != 0) + counter.add(delta); + } + + /* ----------------Table Traversal -------------- */ + + /** + * Encapsulates traversal for methods such as containsValue; also + * serves as a base class for other iterators and bulk tasks. + * + * At each step, the iterator snapshots the key ("nextKey") and + * value ("nextVal") of a valid node (i.e., one that, at point of + * snapshot, has a non-null user value). Because val fields can + * change (including to null, indicating deletion), field nextVal + * might not be accurate at point of use, but still maintains the + * weak consistency property of holding a value that was once + * valid. To support iterator.remove, the nextKey field is not + * updated (nulled out) when the iterator cannot advance. + * + * Internal traversals directly access these fields, as in: + * {@code while (it.advance() != null) { process(it.nextKey); }} + * + * Exported iterators must track whether the iterator has advanced + * (in hasNext vs next) (by setting/checking/nulling field + * nextVal), and then extract key, value, or key-value pairs as + * return values of next(). + * + * The iterator visits once each still-valid node that was + * reachable upon iterator construction. It might miss some that + * were added to a bin after the bin was visited, which is OK wrt + * consistency guarantees. Maintaining this property in the face + * of possible ongoing resizes requires a fair amount of + * bookkeeping state that is difficult to optimize away amidst + * volatile accesses. Even so, traversal maintains reasonable + * throughput. + * + * Normally, iteration proceeds bin-by-bin traversing lists. + * However, if the table has been resized, then all future steps + * must traverse both the bin at the current index as well as at + * (index + baseSize); and so on for further resizings. To + * paranoically cope with potential sharing by users of iterators + * across threads, iteration terminates if a bounds checks fails + * for a table read. + * + * This class extends ForkJoinTask to streamline parallel + * iteration in bulk operations (see BulkTask). This adds only an + * int of space overhead, which is close enough to negligible in + * cases where it is not needed to not worry about it. Because + * ForkJoinTask is Serializable, but iterators need not be, we + * need to add warning suppressions. + */ + @SuppressWarnings("serial") static class Traverser { + final ConcurrentHashMapV8 map; + Node next; // the next entry to use + K nextKey; // cached key field of next + V nextVal; // cached val field of next + Node[] tab; // current table; updated if resized + int index; // index of bin to use next + int baseIndex; // current index of initial table + int baseLimit; // index bound for initial table + int baseSize; // initial table size + + /** Creates iterator for all entries in the table. */ + Traverser(ConcurrentHashMapV8 map) { + this.map = map; + } + + /** Creates iterator for split() methods */ + Traverser(Traverser it) { + ConcurrentHashMapV8 m; Node[] t; + if ((m = this.map = it.map) == null) + t = null; + else if ((t = it.tab) == null && // force parent tab initialization + (t = it.tab = m.table) != null) + it.baseLimit = it.baseSize = t.length; + this.tab = t; + this.baseSize = it.baseSize; + it.baseLimit = this.index = this.baseIndex = + ((this.baseLimit = it.baseLimit) + it.baseIndex + 1) >>> 1; + } + + /** + * Advances next; returns nextVal or null if terminated. + * See above for explanation. + */ + final V advance() { + Node e = next; + V ev = null; + outer: do { + if (e != null) // advance past used/skipped node + e = e.next; + while (e == null) { // get to next non-null bin + ConcurrentHashMapV8 m; + Node[] t; int b, i, n; Object ek; // checks must use locals + if ((t = tab) != null) + n = t.length; + else if ((m = map) != null && (t = tab = m.table) != null) + n = baseLimit = baseSize = t.length; + else + break outer; + if ((b = baseIndex) >= baseLimit || + (i = index) < 0 || i >= n) + break outer; + if ((e = tabAt(t, i)) != null && e.hash == MOVED) { + if ((ek = e.key) instanceof TreeBin) + e = ((TreeBin)ek).first; + else { + tab = (Node[])ek; + continue; // restarts due to null val + } + } // visit upper slots if present + index = (i += baseSize) < n ? i : (baseIndex = b + 1); + } + nextKey = (K) e.key; + } while ((ev = (V) e.val) == null); // skip deleted or special nodes + next = e; + return nextVal = ev; + } + + public final void remove() { + Object k = nextKey; + if (k == null && (advance() == null || (k = nextKey) == null)) + throw new IllegalStateException(); + map.internalReplace(k, null, null); + } + + public final boolean hasNext() { + return nextVal != null || advance() != null; + } + + public final boolean hasMoreElements() { return hasNext(); } + public final void setRawResult(Object x) { } + public R getRawResult() { return null; } + public boolean exec() { return true; } + } + + /* ---------------- Public operations -------------- */ + + /** + * Creates a new, empty map with the default initial table size (16). + */ + public ConcurrentHashMapV8() { + this.counter = new LongAdder(); + } + + /** + * Creates a new, empty map with an initial table size + * accommodating the specified number of elements without the need + * to dynamically resize. + * + * @param initialCapacity The implementation performs internal + * sizing to accommodate this many elements. + * @throws IllegalArgumentException if the initial capacity of + * elements is negative + */ + public ConcurrentHashMapV8(int initialCapacity) { + if (initialCapacity < 0) + throw new IllegalArgumentException(); + int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ? + MAXIMUM_CAPACITY : + tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1)); + this.counter = new LongAdder(); + this.sizeCtl = cap; + } + + /** + * Creates a new map with the same mappings as the given map. + * + * @param m the map + */ + public ConcurrentHashMapV8(Map m) { + this.counter = new LongAdder(); + this.sizeCtl = DEFAULT_CAPACITY; + internalPutAll(m); + } + + /** + * Creates a new, empty map with an initial table size based on + * the given number of elements ({@code initialCapacity}) and + * initial table density ({@code loadFactor}). + * + * @param initialCapacity the initial capacity. The implementation + * performs internal sizing to accommodate this many elements, + * given the specified load factor. + * @param loadFactor the load factor (table density) for + * establishing the initial table size + * @throws IllegalArgumentException if the initial capacity of + * elements is negative or the load factor is nonpositive + * + * @since 1.6 + */ + public ConcurrentHashMapV8(int initialCapacity, float loadFactor) { + this(initialCapacity, loadFactor, 1); + } + + /** + * Creates a new, empty map with an initial table size based on + * the given number of elements ({@code initialCapacity}), table + * density ({@code loadFactor}), and number of concurrently + * updating threads ({@code concurrencyLevel}). + * + * @param initialCapacity the initial capacity. The implementation + * performs internal sizing to accommodate this many elements, + * given the specified load factor. + * @param loadFactor the load factor (table density) for + * establishing the initial table size + * @param concurrencyLevel the estimated number of concurrently + * updating threads. The implementation may use this value as + * a sizing hint. + * @throws IllegalArgumentException if the initial capacity is + * negative or the load factor or concurrencyLevel are + * nonpositive + */ + public ConcurrentHashMapV8(int initialCapacity, + float loadFactor, int concurrencyLevel) { + if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0) + throw new IllegalArgumentException(); + if (initialCapacity < concurrencyLevel) // Use at least as many bins + initialCapacity = concurrencyLevel; // as estimated threads + long size = (long)(1.0 + (long)initialCapacity / loadFactor); + int cap = (size >= (long)MAXIMUM_CAPACITY) ? + MAXIMUM_CAPACITY : tableSizeFor((int)size); + this.counter = new LongAdder(); + this.sizeCtl = cap; + } + + /** + * Creates a new {@link Set} backed by a ConcurrentHashMapV8 + * from the given type to {@code Boolean.TRUE}. + * + * @return the new set + */ + public static KeySetView newKeySet() { + return new KeySetView(new ConcurrentHashMapV8(), + Boolean.TRUE); + } + + /** + * Creates a new {@link Set} backed by a ConcurrentHashMapV8 + * from the given type to {@code Boolean.TRUE}. + * + * @param initialCapacity The implementation performs internal + * sizing to accommodate this many elements. + * @throws IllegalArgumentException if the initial capacity of + * elements is negative + * @return the new set + */ + public static KeySetView newKeySet(int initialCapacity) { + return new KeySetView(new ConcurrentHashMapV8(initialCapacity), + Boolean.TRUE); + } + + /** + * {@inheritDoc} + */ + public boolean isEmpty() { + return counter.sum() <= 0L; // ignore transient negative values + } + + /** + * {@inheritDoc} + */ + public int size() { + long n = counter.sum(); + return ((n < 0L) ? 0 : + (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE : + (int)n); + } + + /** + * Returns the number of mappings. This method should be used + * instead of {@link #size} because a ConcurrentHashMapV8 may + * contain more mappings than can be represented as an int. The + * value returned is a snapshot; the actual count may differ if + * there are ongoing concurrent insertions or removals. + * + * @return the number of mappings + */ + public long mappingCount() { + long n = counter.sum(); + return (n < 0L) ? 0L : n; // ignore transient negative values + } + + /** + * Returns the value to which the specified key is mapped, + * or {@code null} if this map contains no mapping for the key. + * + *

More formally, if this map contains a mapping from a key + * {@code k} to a value {@code v} such that {@code key.equals(k)}, + * then this method returns {@code v}; otherwise it returns + * {@code null}. (There can be at most one such mapping.) + * + * @throws NullPointerException if the specified key is null + */ + @SuppressWarnings("unchecked") public V get(Object key) { + if (key == null) + throw new NullPointerException(); + return (V)internalGet(key); + } + + /** + * Returns the value to which the specified key is mapped, + * or the given defaultValue if this map contains no mapping for the key. + * + * @param key the key + * @param defaultValue the value to return if this map contains + * no mapping for the given key + * @return the mapping for the key, if present; else the defaultValue + * @throws NullPointerException if the specified key is null + */ + @SuppressWarnings("unchecked") public V getValueOrDefault(Object key, V defaultValue) { + if (key == null) + throw new NullPointerException(); + V v = (V) internalGet(key); + return v == null ? defaultValue : v; + } + + /** + * Tests if the specified object is a key in this table. + * + * @param key possible key + * @return {@code true} if and only if the specified object + * is a key in this table, as determined by the + * {@code equals} method; {@code false} otherwise + * @throws NullPointerException if the specified key is null + */ + public boolean containsKey(Object key) { + if (key == null) + throw new NullPointerException(); + return internalGet(key) != null; + } + + /** + * Returns {@code true} if this map maps one or more keys to the + * specified value. Note: This method may require a full traversal + * of the map, and is much slower than method {@code containsKey}. + * + * @param value value whose presence in this map is to be tested + * @return {@code true} if this map maps one or more keys to the + * specified value + * @throws NullPointerException if the specified value is null + */ + public boolean containsValue(Object value) { + if (value == null) + throw new NullPointerException(); + Object v; + Traverser it = new Traverser(this); + while ((v = it.advance()) != null) { + if (v == value || value.equals(v)) + return true; + } + return false; + } + + public K findKey(Object value) { + if (value == null) + throw new NullPointerException(); + Object v; + Traverser it = new Traverser(this); + while ((v = it.advance()) != null) { + if (v == value || value.equals(v)) + return it.nextKey; + } + return null; + } + + /** + * Legacy method testing if some key maps into the specified value + * in this table. This method is identical in functionality to + * {@link #containsValue}, and exists solely to ensure + * full compatibility with class {@link java.util.Hashtable}, + * which supported this method prior to introduction of the + * Java Collections framework. + * + * @param value a value to search for + * @return {@code true} if and only if some key maps to the + * {@code value} argument in this table as + * determined by the {@code equals} method; + * {@code false} otherwise + * @throws NullPointerException if the specified value is null + */ + public boolean contains(Object value) { + return containsValue(value); + } + + /** + * Maps the specified key to the specified value in this table. + * Neither the key nor the value can be null. + * + *

The value can be retrieved by calling the {@code get} method + * with a key that is equal to the original key. + * + * @param key key with which the specified value is to be associated + * @param value value to be associated with the specified key + * @return the previous value associated with {@code key}, or + * {@code null} if there was no mapping for {@code key} + * @throws NullPointerException if the specified key or value is null + */ + @SuppressWarnings("unchecked") public V put(K key, V value) { + if (key == null || value == null) + throw new NullPointerException(); + return (V)internalPut(key, value); + } + + /** + * {@inheritDoc} + * + * @return the previous value associated with the specified key, + * or {@code null} if there was no mapping for the key + * @throws NullPointerException if the specified key or value is null + */ + @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) { + if (key == null || value == null) + throw new NullPointerException(); + return (V)internalPutIfAbsent(key, value); + } + + /** + * Copies all of the mappings from the specified map to this one. + * These mappings replace any mappings that this map had for any of the + * keys currently in the specified map. + * + * @param m mappings to be stored in this map + */ + public void putAll(Map m) { + internalPutAll(m); + } + + /** + * If the specified key is not already associated with a value, + * computes its value using the given mappingFunction and enters + * it into the map unless null. This is equivalent to + *

 {@code
+     * if (map.containsKey(key))
+     *   return map.get(key);
+     * value = mappingFunction.apply(key);
+     * if (value != null)
+     *   map.put(key, value);
+     * return value;}
+ * + * except that the action is performed atomically. If the + * function returns {@code null} no mapping is recorded. If the + * function itself throws an (unchecked) exception, the exception + * is rethrown to its caller, and no mapping is recorded. Some + * attempted update operations on this map by other threads may be + * blocked while computation is in progress, so the computation + * should be short and simple, and must not attempt to update any + * other mappings of this Map. The most appropriate usage is to + * construct a new object serving as an initial mapped value, or + * memoized result, as in: + * + *
 {@code
+     * map.computeIfAbsent(key, new Fun() {
+     *   public V map(K k) { return new Value(f(k)); }});}
+ * + * @param key key with which the specified value is to be associated + * @param mappingFunction the function to compute a value + * @return the current (existing or computed) value associated with + * the specified key, or null if the computed value is null + * @throws NullPointerException if the specified key or mappingFunction + * is null + * @throws IllegalStateException if the computation detectably + * attempts a recursive update to this map that would + * otherwise never complete + * @throws RuntimeException or Error if the mappingFunction does so, + * in which case the mapping is left unestablished + */ + @SuppressWarnings("unchecked") public V computeIfAbsent + (K key, Fun mappingFunction) { + if (key == null || mappingFunction == null) + throw new NullPointerException(); + return (V)internalComputeIfAbsent(key, mappingFunction); + } + + /** + * If the given key is present, computes a new mapping value given a key and + * its current mapped value. This is equivalent to + *
 {@code
+     *   if (map.containsKey(key)) {
+     *     value = remappingFunction.apply(key, map.get(key));
+     *     if (value != null)
+     *       map.put(key, value);
+     *     else
+     *       map.remove(key);
+     *   }
+     * }
+ * + * except that the action is performed atomically. If the + * function returns {@code null}, the mapping is removed. If the + * function itself throws an (unchecked) exception, the exception + * is rethrown to its caller, and the current mapping is left + * unchanged. Some attempted update operations on this map by + * other threads may be blocked while computation is in progress, + * so the computation should be short and simple, and must not + * attempt to update any other mappings of this Map. For example, + * to either create or append new messages to a value mapping: + * + * @param key key with which the specified value is to be associated + * @param remappingFunction the function to compute a value + * @return the new value associated with the specified key, or null if none + * @throws NullPointerException if the specified key or remappingFunction + * is null + * @throws IllegalStateException if the computation detectably + * attempts a recursive update to this map that would + * otherwise never complete + * @throws RuntimeException or Error if the remappingFunction does so, + * in which case the mapping is unchanged + */ + @SuppressWarnings("unchecked") public V computeIfPresent + (K key, BiFun remappingFunction) { + if (key == null || remappingFunction == null) + throw new NullPointerException(); + return (V)internalCompute(key, true, remappingFunction); + } + + /** + * Computes a new mapping value given a key and + * its current mapped value (or {@code null} if there is no current + * mapping). This is equivalent to + *
 {@code
+     *   value = remappingFunction.apply(key, map.get(key));
+     *   if (value != null)
+     *     map.put(key, value);
+     *   else
+     *     map.remove(key);
+     * }
+ * + * except that the action is performed atomically. If the + * function returns {@code null}, the mapping is removed. If the + * function itself throws an (unchecked) exception, the exception + * is rethrown to its caller, and the current mapping is left + * unchanged. Some attempted update operations on this map by + * other threads may be blocked while computation is in progress, + * so the computation should be short and simple, and must not + * attempt to update any other mappings of this Map. For example, + * to either create or append new messages to a value mapping: + * + *
 {@code
+     * Map map = ...;
+     * final String msg = ...;
+     * map.compute(key, new BiFun() {
+     *   public String apply(Key k, String v) {
+     *    return (v == null) ? msg : v + msg;});}}
+ * + * @param key key with which the specified value is to be associated + * @param remappingFunction the function to compute a value + * @return the new value associated with the specified key, or null if none + * @throws NullPointerException if the specified key or remappingFunction + * is null + * @throws IllegalStateException if the computation detectably + * attempts a recursive update to this map that would + * otherwise never complete + * @throws RuntimeException or Error if the remappingFunction does so, + * in which case the mapping is unchanged + */ + @SuppressWarnings("unchecked") public V compute + (K key, BiFun remappingFunction) { + if (key == null || remappingFunction == null) + throw new NullPointerException(); + return (V)internalCompute(key, false, remappingFunction); + } + + /** + * If the specified key is not already associated + * with a value, associate it with the given value. + * Otherwise, replace the value with the results of + * the given remapping function. This is equivalent to: + *
 {@code
+     *   if (!map.containsKey(key))
+     *     map.put(value);
+     *   else {
+     *     newValue = remappingFunction.apply(map.get(key), value);
+     *     if (value != null)
+     *       map.put(key, value);
+     *     else
+     *       map.remove(key);
+     *   }
+     * }
+ * except that the action is performed atomically. If the + * function returns {@code null}, the mapping is removed. If the + * function itself throws an (unchecked) exception, the exception + * is rethrown to its caller, and the current mapping is left + * unchanged. Some attempted update operations on this map by + * other threads may be blocked while computation is in progress, + * so the computation should be short and simple, and must not + * attempt to update any other mappings of this Map. + */ + @SuppressWarnings("unchecked") public V merge + (K key, V value, BiFun remappingFunction) { + if (key == null || value == null || remappingFunction == null) + throw new NullPointerException(); + return (V)internalMerge(key, value, remappingFunction); + } + + /** + * Removes the key (and its corresponding value) from this map. + * This method does nothing if the key is not in the map. + * + * @param key the key that needs to be removed + * @return the previous value associated with {@code key}, or + * {@code null} if there was no mapping for {@code key} + * @throws NullPointerException if the specified key is null + */ + @SuppressWarnings("unchecked") public V remove(Object key) { + if (key == null) + throw new NullPointerException(); + return (V)internalReplace(key, null, null); + } + + /** + * {@inheritDoc} + * + * @throws NullPointerException if the specified key is null + */ + public boolean remove(Object key, Object value) { + if (key == null) + throw new NullPointerException(); + if (value == null) + return false; + return internalReplace(key, null, value) != null; + } + + /** + * {@inheritDoc} + * + * @throws NullPointerException if any of the arguments are null + */ + public boolean replace(K key, V oldValue, V newValue) { + if (key == null || oldValue == null || newValue == null) + throw new NullPointerException(); + return internalReplace(key, newValue, oldValue) != null; + } + + /** + * {@inheritDoc} + * + * @return the previous value associated with the specified key, + * or {@code null} if there was no mapping for the key + * @throws NullPointerException if the specified key or value is null + */ + @SuppressWarnings("unchecked") public V replace(K key, V value) { + if (key == null || value == null) + throw new NullPointerException(); + return (V)internalReplace(key, value, null); + } + + /** + * Removes all of the mappings from this map. + */ + public void clear() { + internalClear(); + } + + /** + * Returns a {@link Set} view of the keys contained in this map. + * The set is backed by the map, so changes to the map are + * reflected in the set, and vice-versa. + * + * @return the set view + */ + public KeySetView keySet() { + KeySetView ks = keySet; + return (ks != null) ? ks : (keySet = new KeySetView(this, null)); + } + + /** + * Returns a {@link Set} view of the keys in this map, using the + * given common mapped value for any additions (i.e., {@link + * Collection#add} and {@link Collection#addAll}). This is of + * course only appropriate if it is acceptable to use the same + * value for all additions from this view. + * + * @param mappedValue the mapped value to use for any + * additions. + * @return the set view + * @throws NullPointerException if the mappedValue is null + */ + public KeySetView keySet(V mappedValue) { + if (mappedValue == null) + throw new NullPointerException(); + return new KeySetView(this, mappedValue); + } + + /** + * Returns a {@link Collection} view of the values contained in this map. + * The collection is backed by the map, so changes to the map are + * reflected in the collection, and vice-versa. + */ + public ValuesView values() { + ValuesView vs = values; + return (vs != null) ? vs : (values = new ValuesView(this)); + } + + /** + * Returns a {@link Set} view of the mappings contained in this map. + * The set is backed by the map, so changes to the map are + * reflected in the set, and vice-versa. The set supports element + * removal, which removes the corresponding mapping from the map, + * via the {@code Iterator.remove}, {@code Set.remove}, + * {@code removeAll}, {@code retainAll}, and {@code clear} + * operations. It does not support the {@code add} or + * {@code addAll} operations. + * + *

The view's {@code iterator} is a "weakly consistent" iterator + * that will never throw {@link ConcurrentModificationException}, + * and guarantees to traverse elements as they existed upon + * construction of the iterator, and may (but is not guaranteed to) + * reflect any modifications subsequent to construction. + */ + public Set> entrySet() { + EntrySetView es = entrySet; + return (es != null) ? es : (entrySet = new EntrySetView(this)); + } + + /** + * Returns an enumeration of the keys in this table. + * + * @return an enumeration of the keys in this table + * @see #keySet() + */ + public Enumeration keys() { + return new KeyIterator(this); + } + + /** + * Returns an enumeration of the values in this table. + * + * @return an enumeration of the values in this table + * @see #values() + */ + public Enumeration elements() { + return new ValueIterator(this); + } + + /** + * Returns a partitionable iterator of the keys in this map. + * + * @return a partitionable iterator of the keys in this map + */ + public Spliterator keySpliterator() { + return new KeyIterator(this); + } + + /** + * Returns a partitionable iterator of the values in this map. + * + * @return a partitionable iterator of the values in this map + */ + public Spliterator valueSpliterator() { + return new ValueIterator(this); + } + + /** + * Returns a partitionable iterator of the entries in this map. + * + * @return a partitionable iterator of the entries in this map + */ + public Spliterator> entrySpliterator() { + return new EntryIterator(this); + } + + /** + * Returns the hash code value for this {@link Map}, i.e., + * the sum of, for each key-value pair in the map, + * {@code key.hashCode() ^ value.hashCode()}. + * + * @return the hash code value for this map + */ + public int hashCode() { + int h = 0; + Traverser it = new Traverser(this); + Object v; + while ((v = it.advance()) != null) { + h += it.nextKey.hashCode() ^ v.hashCode(); + } + return h; + } + + /** + * Returns a string representation of this map. The string + * representation consists of a list of key-value mappings (in no + * particular order) enclosed in braces ("{@code {}}"). Adjacent + * mappings are separated by the characters {@code ", "} (comma + * and space). Each key-value mapping is rendered as the key + * followed by an equals sign ("{@code =}") followed by the + * associated value. + * + * @return a string representation of this map + */ + public String toString() { + Traverser it = new Traverser(this); + StringBuilder sb = new StringBuilder(); + sb.append('{'); + Object v; + if ((v = it.advance()) != null) { + for (;;) { + Object k = it.nextKey; + sb.append(k == this ? "(this Map)" : k); + sb.append('='); + sb.append(v == this ? "(this Map)" : v); + if ((v = it.advance()) == null) + break; + sb.append(',').append(' '); + } + } + return sb.append('}').toString(); + } + + /** + * Compares the specified object with this map for equality. + * Returns {@code true} if the given object is a map with the same + * mappings as this map. This operation may return misleading + * results if either map is concurrently modified during execution + * of this method. + * + * @param o object to be compared for equality with this map + * @return {@code true} if the specified object is equal to this map + */ + public boolean equals(Object o) { + if (o != this) { + if (!(o instanceof Map)) + return false; + Map m = (Map) o; + Traverser it = new Traverser(this); + Object val; + while ((val = it.advance()) != null) { + Object v = m.get(it.nextKey); + if (v == null || (v != val && !v.equals(val))) + return false; + } + for (Map.Entry e : m.entrySet()) { + Object mk, mv, v; + if ((mk = e.getKey()) == null || + (mv = e.getValue()) == null || + (v = internalGet(mk)) == null || + (mv != v && !mv.equals(v))) + return false; + } + } + return true; + } + + /* ----------------Iterators -------------- */ + + @SuppressWarnings("serial") static final class KeyIterator extends Traverser + implements Spliterator, Enumeration { + KeyIterator(ConcurrentHashMapV8 map) { super(map); } + KeyIterator(Traverser it) { + super(it); + } + public KeyIterator split() { + if (nextKey != null) + throw new IllegalStateException(); + return new KeyIterator(this); + } + @SuppressWarnings("unchecked") public final K next() { + if (nextVal == null && advance() == null) + throw new NoSuchElementException(); + Object k = nextKey; + nextVal = null; + return (K) k; + } + + public final K nextElement() { return next(); } + } + + @SuppressWarnings("serial") static final class ValueIterator extends Traverser + implements Spliterator, Enumeration { + ValueIterator(ConcurrentHashMapV8 map) { super(map); } + ValueIterator(Traverser it) { + super(it); + } + public ValueIterator split() { + if (nextKey != null) + throw new IllegalStateException(); + return new ValueIterator(this); + } + + @SuppressWarnings("unchecked") public final V next() { + Object v; + if ((v = nextVal) == null && (v = advance()) == null) + throw new NoSuchElementException(); + nextVal = null; + return (V) v; + } + + public final V nextElement() { return next(); } + } + + @SuppressWarnings("serial") static final class EntryIterator extends Traverser + implements Spliterator> { + EntryIterator(ConcurrentHashMapV8 map) { super(map); } + EntryIterator(Traverser it) { + super(it); + } + public EntryIterator split() { + if (nextKey != null) + throw new IllegalStateException(); + return new EntryIterator(this); + } + + @SuppressWarnings("unchecked") public final Map.Entry next() { + Object v; + if ((v = nextVal) == null && (v = advance()) == null) + throw new NoSuchElementException(); + Object k = nextKey; + nextVal = null; + return new MapEntry((K)k, (V)v, map); + } + } + + /** + * Exported Entry for iterators + */ + static final class MapEntry implements Map.Entry { + final K key; // non-null + V val; // non-null + final ConcurrentHashMapV8 map; + MapEntry(K key, V val, ConcurrentHashMapV8 map) { + this.key = key; + this.val = val; + this.map = map; + } + public final K getKey() { return key; } + public final V getValue() { return val; } + public final int hashCode() { return key.hashCode() ^ val.hashCode(); } + public final String toString(){ return key + "=" + val; } + + public final boolean equals(Object o) { + Object k, v; Map.Entry e; + return ((o instanceof Map.Entry) && + (k = (e = (Map.Entry)o).getKey()) != null && + (v = e.getValue()) != null && + (k == key || k.equals(key)) && + (v == val || v.equals(val))); + } + + /** + * Sets our entry's value and writes through to the map. The + * value to return is somewhat arbitrary here. Since we do not + * necessarily track asynchronous changes, the most recent + * "previous" value could be different from what we return (or + * could even have been removed in which case the put will + * re-establish). We do not and cannot guarantee more. + */ + public final V setValue(V value) { + if (value == null) throw new NullPointerException(); + V v = val; + val = value; + map.put(key, value); + return v; + } + } + + /* ---------------- Serialization Support -------------- */ + + /** + * Stripped-down version of helper class used in previous version, + * declared for the sake of serialization compatibility + */ + static class Segment implements Serializable { + private static final long serialVersionUID = 2249069246763182397L; + final float loadFactor; + Segment(float lf) { this.loadFactor = lf; } + } + + /** + * Saves the state of the {@code ConcurrentHashMapV8} instance to a + * stream (i.e., serializes it). + * @param s the stream + * @serialData + * the key (Object) and value (Object) + * for each key-value mapping, followed by a null pair. + * The key-value mappings are emitted in no particular order. + */ + @SuppressWarnings("unchecked") private void writeObject(java.io.ObjectOutputStream s) + throws java.io.IOException { + if (segments == null) { // for serialization compatibility + segments = (Segment[]) + new Segment[DEFAULT_CONCURRENCY_LEVEL]; + for (int i = 0; i < segments.length; ++i) + segments[i] = new Segment(LOAD_FACTOR); + } + s.defaultWriteObject(); + Traverser it = new Traverser(this); + Object v; + while ((v = it.advance()) != null) { + s.writeObject(it.nextKey); + s.writeObject(v); + } + s.writeObject(null); + s.writeObject(null); + segments = null; // throw away + } + + /** + * Reconstitutes the instance from a stream (that is, deserializes it). + * @param s the stream + */ + @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s) + throws java.io.IOException, ClassNotFoundException { + s.defaultReadObject(); + this.segments = null; // unneeded + // initialize transient final field + UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder()); + + // Create all nodes, then place in table once size is known + long size = 0L; + Node p = null; + for (;;) { + K k = (K) s.readObject(); + V v = (V) s.readObject(); + if (k != null && v != null) { + int h = spread(k.hashCode()); + p = new Node(h, k, v, p); + ++size; + } + else + break; + } + if (p != null) { + boolean init = false; + int n; + if (size >= (long)(MAXIMUM_CAPACITY >>> 1)) + n = MAXIMUM_CAPACITY; + else { + int sz = (int)size; + n = tableSizeFor(sz + (sz >>> 1) + 1); + } + int sc = sizeCtl; + boolean collide = false; + if (n > sc && + UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) { + try { + if (table == null) { + init = true; + Node[] tab = new Node[n]; + int mask = n - 1; + while (p != null) { + int j = p.hash & mask; + Node next = p.next; + Node q = p.next = tabAt(tab, j); + setTabAt(tab, j, p); + if (!collide && q != null && q.hash == p.hash) + collide = true; + p = next; + } + table = tab; + counter.add(size); + sc = n - (n >>> 2); + } + } finally { + sizeCtl = sc; + } + if (collide) { // rescan and convert to TreeBins + Node[] tab = table; + for (int i = 0; i < tab.length; ++i) { + int c = 0; + for (Node e = tabAt(tab, i); e != null; e = e.next) { + if (++c > TREE_THRESHOLD && + (e.key instanceof Comparable)) { + replaceWithTreeBin(tab, i, e.key); + break; + } + } + } + } + } + if (!init) { // Can only happen if unsafely published. + while (p != null) { + internalPut(p.key, p.val); + p = p.next; + } + } + } + } + + + // ------------------------------------------------------- + + // Sams + /** Interface describing a void action of one argument */ + public interface Action { void apply(A a); } + /** Interface describing a void action of two arguments */ + public interface BiAction { void apply(A a, B b); } + /** Interface describing a function of one argument */ + public interface Generator { T apply(); } + /** Interface describing a function mapping its argument to a double */ + public interface ObjectToDouble { double apply(A a); } + /** Interface describing a function mapping its argument to a long */ + public interface ObjectToLong { long apply(A a); } + /** Interface describing a function mapping its argument to an int */ + public interface ObjectToInt {int apply(A a); } + /** Interface describing a function mapping two arguments to a double */ + public interface ObjectByObjectToDouble { double apply(A a, B b); } + /** Interface describing a function mapping two arguments to a long */ + public interface ObjectByObjectToLong { long apply(A a, B b); } + /** Interface describing a function mapping two arguments to an int */ + public interface ObjectByObjectToInt {int apply(A a, B b); } + /** Interface describing a function mapping a double to a double */ + public interface DoubleToDouble { double apply(double a); } + /** Interface describing a function mapping a long to a long */ + public interface LongToLong { long apply(long a); } + /** Interface describing a function mapping an int to an int */ + public interface IntToInt { int apply(int a); } + /** Interface describing a function mapping two doubles to a double */ + public interface DoubleByDoubleToDouble { double apply(double a, double b); } + /** Interface describing a function mapping two longs to a long */ + public interface LongByLongToLong { long apply(long a, long b); } + /** Interface describing a function mapping two ints to an int */ + public interface IntByIntToInt { int apply(int a, int b); } + + + /* ----------------Views -------------- */ + + /** + * Base class for views. + */ + static abstract class CHMView { + final ConcurrentHashMapV8 map; + CHMView(ConcurrentHashMapV8 map) { this.map = map; } + + /** + * Returns the map backing this view. + * + * @return the map backing this view + */ + public ConcurrentHashMapV8 getMap() { return map; } + + public final int size() { return map.size(); } + public final boolean isEmpty() { return map.isEmpty(); } + public final void clear() { map.clear(); } + + // implementations below rely on concrete classes supplying these + abstract public Iterator iterator(); + abstract public boolean contains(Object o); + abstract public boolean remove(Object o); + + private static final String oomeMsg = "Required array size too large"; + + public final Object[] toArray() { + long sz = map.mappingCount(); + if (sz > (long)(MAX_ARRAY_SIZE)) + throw new OutOfMemoryError(oomeMsg); + int n = (int)sz; + Object[] r = new Object[n]; + int i = 0; + Iterator it = iterator(); + while (it.hasNext()) { + if (i == n) { + if (n >= MAX_ARRAY_SIZE) + throw new OutOfMemoryError(oomeMsg); + if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1) + n = MAX_ARRAY_SIZE; + else + n += (n >>> 1) + 1; + r = Arrays.copyOf(r, n); + } + r[i++] = it.next(); + } + return (i == n) ? r : Arrays.copyOf(r, i); + } + + @SuppressWarnings("unchecked") public final T[] toArray(T[] a) { + long sz = map.mappingCount(); + if (sz > (long)(MAX_ARRAY_SIZE)) + throw new OutOfMemoryError(oomeMsg); + int m = (int)sz; + T[] r = (a.length >= m) ? a : + (T[])java.lang.reflect.Array + .newInstance(a.getClass().getComponentType(), m); + int n = r.length; + int i = 0; + Iterator it = iterator(); + while (it.hasNext()) { + if (i == n) { + if (n >= MAX_ARRAY_SIZE) + throw new OutOfMemoryError(oomeMsg); + if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1) + n = MAX_ARRAY_SIZE; + else + n += (n >>> 1) + 1; + r = Arrays.copyOf(r, n); + } + r[i++] = (T)it.next(); + } + if (a == r && i < n) { + r[i] = null; // null-terminate + return r; + } + return (i == n) ? r : Arrays.copyOf(r, i); + } + + public final int hashCode() { + int h = 0; + for (Iterator it = iterator(); it.hasNext();) + h += it.next().hashCode(); + return h; + } + + public final String toString() { + StringBuilder sb = new StringBuilder(); + sb.append('['); + Iterator it = iterator(); + if (it.hasNext()) { + for (;;) { + Object e = it.next(); + sb.append(e == this ? "(this Collection)" : e); + if (!it.hasNext()) + break; + sb.append(',').append(' '); + } + } + return sb.append(']').toString(); + } + + public final boolean containsAll(Collection c) { + if (c != this) { + for (Iterator it = c.iterator(); it.hasNext();) { + Object e = it.next(); + if (e == null || !contains(e)) + return false; + } + } + return true; + } + + public final boolean removeAll(Collection c) { + boolean modified = false; + for (Iterator it = iterator(); it.hasNext();) { + if (c.contains(it.next())) { + it.remove(); + modified = true; + } + } + return modified; + } + + public final boolean retainAll(Collection c) { + boolean modified = false; + for (Iterator it = iterator(); it.hasNext();) { + if (!c.contains(it.next())) { + it.remove(); + modified = true; + } + } + return modified; + } + + } + + /** + * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in + * which additions may optionally be enabled by mapping to a + * common value. This class cannot be directly instantiated. See + * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()}, + * {@link #newKeySet(int)}. + */ + public static class KeySetView extends CHMView implements Set, java.io.Serializable { + private static final long serialVersionUID = 7249069246763182397L; + private final V value; + KeySetView(ConcurrentHashMapV8 map, V value) { // non-public + super(map); + this.value = value; + } + + /** + * Returns the default mapped value for additions, + * or {@code null} if additions are not supported. + * + * @return the default mapped value for additions, or {@code null} + * if not supported. + */ + public V getMappedValue() { return value; } + + // implement Set API + + public boolean contains(Object o) { return map.containsKey(o); } + public boolean remove(Object o) { return map.remove(o) != null; } + + /** + * Returns a "weakly consistent" iterator that will never + * throw {@link ConcurrentModificationException}, and + * guarantees to traverse elements as they existed upon + * construction of the iterator, and may (but is not + * guaranteed to) reflect any modifications subsequent to + * construction. + * + * @return an iterator over the keys of this map + */ + public Iterator iterator() { return new KeyIterator(map); } + public boolean add(K e) { + V v; + if ((v = value) == null) + throw new UnsupportedOperationException(); + if (e == null) + throw new NullPointerException(); + return map.internalPutIfAbsent(e, v) == null; + } + public boolean addAll(Collection c) { + boolean added = false; + V v; + if ((v = value) == null) + throw new UnsupportedOperationException(); + for (K e : c) { + if (e == null) + throw new NullPointerException(); + if (map.internalPutIfAbsent(e, v) == null) + added = true; + } + return added; + } + public boolean equals(Object o) { + Set c; + return ((o instanceof Set) && + ((c = (Set)o) == this || + (containsAll(c) && c.containsAll(this)))); + } + } + + /** + * A view of a ConcurrentHashMapV8 as a {@link Collection} of + * values, in which additions are disabled. This class cannot be + * directly instantiated. See {@link #values}, + * + *

The view's {@code iterator} is a "weakly consistent" iterator + * that will never throw {@link ConcurrentModificationException}, + * and guarantees to traverse elements as they existed upon + * construction of the iterator, and may (but is not guaranteed to) + * reflect any modifications subsequent to construction. + */ + public static final class ValuesView extends CHMView + implements Collection { + ValuesView(ConcurrentHashMapV8 map) { super(map); } + public final boolean contains(Object o) { return map.containsValue(o); } + public final boolean remove(Object o) { + if (o != null) { + Iterator it = new ValueIterator(map); + while (it.hasNext()) { + if (o.equals(it.next())) { + it.remove(); + return true; + } + } + } + return false; + } + + /** + * Returns a "weakly consistent" iterator that will never + * throw {@link ConcurrentModificationException}, and + * guarantees to traverse elements as they existed upon + * construction of the iterator, and may (but is not + * guaranteed to) reflect any modifications subsequent to + * construction. + * + * @return an iterator over the values of this map + */ + public final Iterator iterator() { + return new ValueIterator(map); + } + public final boolean add(V e) { + throw new UnsupportedOperationException(); + } + public final boolean addAll(Collection c) { + throw new UnsupportedOperationException(); + } + } + + /** + * A view of a ConcurrentHashMapV8 as a {@link Set} of (key, value) + * entries. This class cannot be directly instantiated. See + * {@link #entrySet}. + */ + public static final class EntrySetView extends CHMView + implements Set> { + EntrySetView(ConcurrentHashMapV8 map) { super(map); } + public final boolean contains(Object o) { + Object k, v, r; Map.Entry e; + return ((o instanceof Map.Entry) && + (k = (e = (Map.Entry)o).getKey()) != null && + (r = map.get(k)) != null && + (v = e.getValue()) != null && + (v == r || v.equals(r))); + } + public final boolean remove(Object o) { + Object k, v; Map.Entry e; + return ((o instanceof Map.Entry) && + (k = (e = (Map.Entry)o).getKey()) != null && + (v = e.getValue()) != null && + map.remove(k, v)); + } + + /** + * Returns a "weakly consistent" iterator that will never + * throw {@link ConcurrentModificationException}, and + * guarantees to traverse elements as they existed upon + * construction of the iterator, and may (but is not + * guaranteed to) reflect any modifications subsequent to + * construction. + * + * @return an iterator over the entries of this map + */ + public final Iterator> iterator() { + return new EntryIterator(map); + } + + public final boolean add(Entry e) { + K key = e.getKey(); + V value = e.getValue(); + if (key == null || value == null) + throw new NullPointerException(); + return map.internalPut(key, value) == null; + } + public final boolean addAll(Collection> c) { + boolean added = false; + for (Entry e : c) { + if (add(e)) + added = true; + } + return added; + } + public boolean equals(Object o) { + Set c; + return ((o instanceof Set) && + ((c = (Set)o) == this || + (containsAll(c) && c.containsAll(this)))); + } + } + + // Unsafe mechanics + private static final sun.misc.Unsafe UNSAFE; + private static final long counterOffset; + private static final long sizeCtlOffset; + private static final long ABASE; + private static final int ASHIFT; + + static { + int ss; + try { + UNSAFE = getUnsafe(); + Class k = ConcurrentHashMapV8.class; + counterOffset = UNSAFE.objectFieldOffset + (k.getDeclaredField("counter")); + sizeCtlOffset = UNSAFE.objectFieldOffset + (k.getDeclaredField("sizeCtl")); + Class sc = Node[].class; + ABASE = UNSAFE.arrayBaseOffset(sc); + ss = UNSAFE.arrayIndexScale(sc); + } catch (Exception e) { + throw new Error(e); + } + if ((ss & (ss-1)) != 0) + throw new Error("data type scale not a power of two"); + ASHIFT = 31 - Integer.numberOfLeadingZeros(ss); + } + + /** + * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. + * Replace with a simple call to Unsafe.getUnsafe when integrating + * into a jdk. + * + * @return a sun.misc.Unsafe + */ + private static sun.misc.Unsafe getUnsafe() { + try { + return sun.misc.Unsafe.getUnsafe(); + } catch (SecurityException se) { + try { + return java.security.AccessController.doPrivileged + (new java.security + .PrivilegedExceptionAction() { + public sun.misc.Unsafe run() throws Exception { + java.lang.reflect.Field f = sun.misc + .Unsafe.class.getDeclaredField("theUnsafe"); + f.setAccessible(true); + return (sun.misc.Unsafe) f.get(null); + }}); + } catch (java.security.PrivilegedActionException e) { + throw new RuntimeException("Could not initialize intrinsics", + e.getCause()); + } + } + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/LongAdder.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/LongAdder.java new file mode 100644 index 0000000..47a923c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/LongAdder.java @@ -0,0 +1,203 @@ +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +// This is based on 1.9 version. + +package com.concurrent_ruby.ext.jsr166e; +import java.util.concurrent.atomic.AtomicLong; +import java.io.IOException; +import java.io.Serializable; +import java.io.ObjectInputStream; + +/** + * One or more variables that together maintain an initially zero + * {@code long} sum. When updates (method {@link #add}) are contended + * across threads, the set of variables may grow dynamically to reduce + * contention. Method {@link #sum} (or, equivalently, {@link + * #longValue}) returns the current total combined across the + * variables maintaining the sum. + * + *

This class is usually preferable to {@link AtomicLong} when + * multiple threads update a common sum that is used for purposes such + * as collecting statistics, not for fine-grained synchronization + * control. Under low update contention, the two classes have similar + * characteristics. But under high contention, expected throughput of + * this class is significantly higher, at the expense of higher space + * consumption. + * + *

This class extends {@link Number}, but does not define + * methods such as {@code hashCode} and {@code compareTo} because + * instances are expected to be mutated, and so are not useful as + * collection keys. + * + *

jsr166e note: This class is targeted to be placed in + * java.util.concurrent.atomic. + * + * @since 1.8 + * @author Doug Lea + */ +public class LongAdder extends Striped64 implements Serializable { + private static final long serialVersionUID = 7249069246863182397L; + + /** + * Version of plus for use in retryUpdate + */ + final long fn(long v, long x) { return v + x; } + + /** + * Creates a new adder with initial sum of zero. + */ + public LongAdder() { + } + + /** + * Adds the given value. + * + * @param x the value to add + */ + public void add(long x) { + Cell[] as; long b, v; HashCode hc; Cell a; int n; + if ((as = cells) != null || !casBase(b = base, b + x)) { + boolean uncontended = true; + int h = (hc = threadHashCode.get()).code; + if (as == null || (n = as.length) < 1 || + (a = as[(n - 1) & h]) == null || + !(uncontended = a.cas(v = a.value, v + x))) + retryUpdate(x, hc, uncontended); + } + } + + /** + * Equivalent to {@code add(1)}. + */ + public void increment() { + add(1L); + } + + /** + * Equivalent to {@code add(-1)}. + */ + public void decrement() { + add(-1L); + } + + /** + * Returns the current sum. The returned value is NOT an + * atomic snapshot: Invocation in the absence of concurrent + * updates returns an accurate result, but concurrent updates that + * occur while the sum is being calculated might not be + * incorporated. + * + * @return the sum + */ + public long sum() { + long sum = base; + Cell[] as = cells; + if (as != null) { + int n = as.length; + for (int i = 0; i < n; ++i) { + Cell a = as[i]; + if (a != null) + sum += a.value; + } + } + return sum; + } + + /** + * Resets variables maintaining the sum to zero. This method may + * be a useful alternative to creating a new adder, but is only + * effective if there are no concurrent updates. Because this + * method is intrinsically racy, it should only be used when it is + * known that no threads are concurrently updating. + */ + public void reset() { + internalReset(0L); + } + + /** + * Equivalent in effect to {@link #sum} followed by {@link + * #reset}. This method may apply for example during quiescent + * points between multithreaded computations. If there are + * updates concurrent with this method, the returned value is + * not guaranteed to be the final value occurring before + * the reset. + * + * @return the sum + */ + public long sumThenReset() { + long sum = base; + Cell[] as = cells; + base = 0L; + if (as != null) { + int n = as.length; + for (int i = 0; i < n; ++i) { + Cell a = as[i]; + if (a != null) { + sum += a.value; + a.value = 0L; + } + } + } + return sum; + } + + /** + * Returns the String representation of the {@link #sum}. + * @return the String representation of the {@link #sum} + */ + public String toString() { + return Long.toString(sum()); + } + + /** + * Equivalent to {@link #sum}. + * + * @return the sum + */ + public long longValue() { + return sum(); + } + + /** + * Returns the {@link #sum} as an {@code int} after a narrowing + * primitive conversion. + */ + public int intValue() { + return (int)sum(); + } + + /** + * Returns the {@link #sum} as a {@code float} + * after a widening primitive conversion. + */ + public float floatValue() { + return (float)sum(); + } + + /** + * Returns the {@link #sum} as a {@code double} after a widening + * primitive conversion. + */ + public double doubleValue() { + return (double)sum(); + } + + private void writeObject(java.io.ObjectOutputStream s) + throws java.io.IOException { + s.defaultWriteObject(); + s.writeLong(sum()); + } + + private void readObject(ObjectInputStream s) + throws IOException, ClassNotFoundException { + s.defaultReadObject(); + busy = 0; + cells = null; + base = s.readLong(); + } + +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/Striped64.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/Striped64.java new file mode 100644 index 0000000..93a277f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/Striped64.java @@ -0,0 +1,342 @@ +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +// This is based on 1.5 version. + +package com.concurrent_ruby.ext.jsr166e; +import java.util.Random; + +/** + * A package-local class holding common representation and mechanics + * for classes supporting dynamic striping on 64bit values. The class + * extends Number so that concrete subclasses must publicly do so. + */ +abstract class Striped64 extends Number { + /* + * This class maintains a lazily-initialized table of atomically + * updated variables, plus an extra "base" field. The table size + * is a power of two. Indexing uses masked per-thread hash codes. + * Nearly all declarations in this class are package-private, + * accessed directly by subclasses. + * + * Table entries are of class Cell; a variant of AtomicLong padded + * to reduce cache contention on most processors. Padding is + * overkill for most Atomics because they are usually irregularly + * scattered in memory and thus don't interfere much with each + * other. But Atomic objects residing in arrays will tend to be + * placed adjacent to each other, and so will most often share + * cache lines (with a huge negative performance impact) without + * this precaution. + * + * In part because Cells are relatively large, we avoid creating + * them until they are needed. When there is no contention, all + * updates are made to the base field. Upon first contention (a + * failed CAS on base update), the table is initialized to size 2. + * The table size is doubled upon further contention until + * reaching the nearest power of two greater than or equal to the + * number of CPUS. Table slots remain empty (null) until they are + * needed. + * + * A single spinlock ("busy") is used for initializing and + * resizing the table, as well as populating slots with new Cells. + * There is no need for a blocking lock: When the lock is not + * available, threads try other slots (or the base). During these + * retries, there is increased contention and reduced locality, + * which is still better than alternatives. + * + * Per-thread hash codes are initialized to random values. + * Contention and/or table collisions are indicated by failed + * CASes when performing an update operation (see method + * retryUpdate). Upon a collision, if the table size is less than + * the capacity, it is doubled in size unless some other thread + * holds the lock. If a hashed slot is empty, and lock is + * available, a new Cell is created. Otherwise, if the slot + * exists, a CAS is tried. Retries proceed by "double hashing", + * using a secondary hash (Marsaglia XorShift) to try to find a + * free slot. + * + * The table size is capped because, when there are more threads + * than CPUs, supposing that each thread were bound to a CPU, + * there would exist a perfect hash function mapping threads to + * slots that eliminates collisions. When we reach capacity, we + * search for this mapping by randomly varying the hash codes of + * colliding threads. Because search is random, and collisions + * only become known via CAS failures, convergence can be slow, + * and because threads are typically not bound to CPUS forever, + * may not occur at all. However, despite these limitations, + * observed contention rates are typically low in these cases. + * + * It is possible for a Cell to become unused when threads that + * once hashed to it terminate, as well as in the case where + * doubling the table causes no thread to hash to it under + * expanded mask. We do not try to detect or remove such cells, + * under the assumption that for long-running instances, observed + * contention levels will recur, so the cells will eventually be + * needed again; and for short-lived ones, it does not matter. + */ + + /** + * Padded variant of AtomicLong supporting only raw accesses plus CAS. + * The value field is placed between pads, hoping that the JVM doesn't + * reorder them. + * + * JVM intrinsics note: It would be possible to use a release-only + * form of CAS here, if it were provided. + */ + static final class Cell { + volatile long p0, p1, p2, p3, p4, p5, p6; + volatile long value; + volatile long q0, q1, q2, q3, q4, q5, q6; + Cell(long x) { value = x; } + + final boolean cas(long cmp, long val) { + return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val); + } + + // Unsafe mechanics + private static final sun.misc.Unsafe UNSAFE; + private static final long valueOffset; + static { + try { + UNSAFE = getUnsafe(); + Class ak = Cell.class; + valueOffset = UNSAFE.objectFieldOffset + (ak.getDeclaredField("value")); + } catch (Exception e) { + throw new Error(e); + } + } + + } + + /** + * Holder for the thread-local hash code. The code is initially + * random, but may be set to a different value upon collisions. + */ + static final class HashCode { + static final Random rng = new Random(); + int code; + HashCode() { + int h = rng.nextInt(); // Avoid zero to allow xorShift rehash + code = (h == 0) ? 1 : h; + } + } + + /** + * The corresponding ThreadLocal class + */ + static final class ThreadHashCode extends ThreadLocal { + public HashCode initialValue() { return new HashCode(); } + } + + /** + * Static per-thread hash codes. Shared across all instances to + * reduce ThreadLocal pollution and because adjustments due to + * collisions in one table are likely to be appropriate for + * others. + */ + static final ThreadHashCode threadHashCode = new ThreadHashCode(); + + /** Number of CPUS, to place bound on table size */ + static final int NCPU = Runtime.getRuntime().availableProcessors(); + + /** + * Table of cells. When non-null, size is a power of 2. + */ + transient volatile Cell[] cells; + + /** + * Base value, used mainly when there is no contention, but also as + * a fallback during table initialization races. Updated via CAS. + */ + transient volatile long base; + + /** + * Spinlock (locked via CAS) used when resizing and/or creating Cells. + */ + transient volatile int busy; + + /** + * Package-private default constructor + */ + Striped64() { + } + + /** + * CASes the base field. + */ + final boolean casBase(long cmp, long val) { + return UNSAFE.compareAndSwapLong(this, baseOffset, cmp, val); + } + + /** + * CASes the busy field from 0 to 1 to acquire lock. + */ + final boolean casBusy() { + return UNSAFE.compareAndSwapInt(this, busyOffset, 0, 1); + } + + /** + * Computes the function of current and new value. Subclasses + * should open-code this update function for most uses, but the + * virtualized form is needed within retryUpdate. + * + * @param currentValue the current value (of either base or a cell) + * @param newValue the argument from a user update call + * @return result of the update function + */ + abstract long fn(long currentValue, long newValue); + + /** + * Handles cases of updates involving initialization, resizing, + * creating new Cells, and/or contention. See above for + * explanation. This method suffers the usual non-modularity + * problems of optimistic retry code, relying on rechecked sets of + * reads. + * + * @param x the value + * @param hc the hash code holder + * @param wasUncontended false if CAS failed before call + */ + final void retryUpdate(long x, HashCode hc, boolean wasUncontended) { + int h = hc.code; + boolean collide = false; // True if last slot nonempty + for (;;) { + Cell[] as; Cell a; int n; long v; + if ((as = cells) != null && (n = as.length) > 0) { + if ((a = as[(n - 1) & h]) == null) { + if (busy == 0) { // Try to attach new Cell + Cell r = new Cell(x); // Optimistically create + if (busy == 0 && casBusy()) { + boolean created = false; + try { // Recheck under lock + Cell[] rs; int m, j; + if ((rs = cells) != null && + (m = rs.length) > 0 && + rs[j = (m - 1) & h] == null) { + rs[j] = r; + created = true; + } + } finally { + busy = 0; + } + if (created) + break; + continue; // Slot is now non-empty + } + } + collide = false; + } + else if (!wasUncontended) // CAS already known to fail + wasUncontended = true; // Continue after rehash + else if (a.cas(v = a.value, fn(v, x))) + break; + else if (n >= NCPU || cells != as) + collide = false; // At max size or stale + else if (!collide) + collide = true; + else if (busy == 0 && casBusy()) { + try { + if (cells == as) { // Expand table unless stale + Cell[] rs = new Cell[n << 1]; + for (int i = 0; i < n; ++i) + rs[i] = as[i]; + cells = rs; + } + } finally { + busy = 0; + } + collide = false; + continue; // Retry with expanded table + } + h ^= h << 13; // Rehash + h ^= h >>> 17; + h ^= h << 5; + } + else if (busy == 0 && cells == as && casBusy()) { + boolean init = false; + try { // Initialize table + if (cells == as) { + Cell[] rs = new Cell[2]; + rs[h & 1] = new Cell(x); + cells = rs; + init = true; + } + } finally { + busy = 0; + } + if (init) + break; + } + else if (casBase(v = base, fn(v, x))) + break; // Fall back on using base + } + hc.code = h; // Record index for next time + } + + + /** + * Sets base and all cells to the given value. + */ + final void internalReset(long initialValue) { + Cell[] as = cells; + base = initialValue; + if (as != null) { + int n = as.length; + for (int i = 0; i < n; ++i) { + Cell a = as[i]; + if (a != null) + a.value = initialValue; + } + } + } + + // Unsafe mechanics + private static final sun.misc.Unsafe UNSAFE; + private static final long baseOffset; + private static final long busyOffset; + static { + try { + UNSAFE = getUnsafe(); + Class sk = Striped64.class; + baseOffset = UNSAFE.objectFieldOffset + (sk.getDeclaredField("base")); + busyOffset = UNSAFE.objectFieldOffset + (sk.getDeclaredField("busy")); + } catch (Exception e) { + throw new Error(e); + } + } + + /** + * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. + * Replace with a simple call to Unsafe.getUnsafe when integrating + * into a jdk. + * + * @return a sun.misc.Unsafe + */ + private static sun.misc.Unsafe getUnsafe() { + try { + return sun.misc.Unsafe.getUnsafe(); + } catch (SecurityException se) { + try { + return java.security.AccessController.doPrivileged + (new java.security + .PrivilegedExceptionAction() { + public sun.misc.Unsafe run() throws Exception { + java.lang.reflect.Field f = sun.misc + .Unsafe.class.getDeclaredField("theUnsafe"); + f.setAccessible(true); + return (sun.misc.Unsafe) f.get(null); + }}); + } catch (java.security.PrivilegedActionException e) { + throw new RuntimeException("Could not initialize intrinsics", + e.getCause()); + } + } + } + +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/ConcurrentHashMapV8.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/ConcurrentHashMapV8.java new file mode 100644 index 0000000..b7fc5a9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/ConcurrentHashMapV8.java @@ -0,0 +1,3800 @@ +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +// This is based on the 1.79 version. + +package com.concurrent_ruby.ext.jsr166e.nounsafe; + +import org.jruby.RubyClass; +import org.jruby.RubyNumeric; +import org.jruby.RubyObject; +import org.jruby.exceptions.RaiseException; +import com.concurrent_ruby.ext.jsr166e.ConcurrentHashMap; +import com.concurrent_ruby.ext.jsr166y.ThreadLocalRandom; +import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.builtin.IRubyObject; + +import java.util.Arrays; +import java.util.Map; +import java.util.Set; +import java.util.Collection; +import java.util.Hashtable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Enumeration; +import java.util.ConcurrentModificationException; +import java.util.NoSuchElementException; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicReferenceArray; +import java.util.concurrent.locks.AbstractQueuedSynchronizer; + +import java.io.Serializable; + +/** + * A hash table supporting full concurrency of retrievals and + * high expected concurrency for updates. This class obeys the + * same functional specification as {@link java.util.Hashtable}, and + * includes versions of methods corresponding to each method of + * {@code Hashtable}. However, even though all operations are + * thread-safe, retrieval operations do not entail locking, + * and there is not any support for locking the entire table + * in a way that prevents all access. This class is fully + * interoperable with {@code Hashtable} in programs that rely on its + * thread safety but not on its synchronization details. + * + *

Retrieval operations (including {@code get}) generally do not + * block, so may overlap with update operations (including {@code put} + * and {@code remove}). Retrievals reflect the results of the most + * recently completed update operations holding upon their + * onset. (More formally, an update operation for a given key bears a + * happens-before relation with any (non-null) retrieval for + * that key reporting the updated value.) For aggregate operations + * such as {@code putAll} and {@code clear}, concurrent retrievals may + * reflect insertion or removal of only some entries. Similarly, + * Iterators and Enumerations return elements reflecting the state of + * the hash table at some point at or since the creation of the + * iterator/enumeration. They do not throw {@link + * ConcurrentModificationException}. However, iterators are designed + * to be used by only one thread at a time. Bear in mind that the + * results of aggregate status methods including {@code size}, {@code + * isEmpty}, and {@code containsValue} are typically useful only when + * a map is not undergoing concurrent updates in other threads. + * Otherwise the results of these methods reflect transient states + * that may be adequate for monitoring or estimation purposes, but not + * for program control. + * + *

The table is dynamically expanded when there are too many + * collisions (i.e., keys that have distinct hash codes but fall into + * the same slot modulo the table size), with the expected average + * effect of maintaining roughly two bins per mapping (corresponding + * to a 0.75 load factor threshold for resizing). There may be much + * variance around this average as mappings are added and removed, but + * overall, this maintains a commonly accepted time/space tradeoff for + * hash tables. However, resizing this or any other kind of hash + * table may be a relatively slow operation. When possible, it is a + * good idea to provide a size estimate as an optional {@code + * initialCapacity} constructor argument. An additional optional + * {@code loadFactor} constructor argument provides a further means of + * customizing initial table capacity by specifying the table density + * to be used in calculating the amount of space to allocate for the + * given number of elements. Also, for compatibility with previous + * versions of this class, constructors may optionally specify an + * expected {@code concurrencyLevel} as an additional hint for + * internal sizing. Note that using many keys with exactly the same + * {@code hashCode()} is a sure way to slow down performance of any + * hash table. + * + *

A {@link Set} projection of a ConcurrentHashMapV8 may be created + * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed + * (using {@link #keySet(Object)} when only keys are of interest, and the + * mapped values are (perhaps transiently) not used or all take the + * same mapping value. + * + *

A ConcurrentHashMapV8 can be used as scalable frequency map (a + * form of histogram or multiset) by using {@link LongAdder} values + * and initializing via {@link #computeIfAbsent}. For example, to add + * a count to a {@code ConcurrentHashMapV8 freqs}, you + * can use {@code freqs.computeIfAbsent(k -> new + * LongAdder()).increment();} + * + *

This class and its views and iterators implement all of the + * optional methods of the {@link Map} and {@link Iterator} + * interfaces. + * + *

Like {@link Hashtable} but unlike {@link HashMap}, this class + * does not allow {@code null} to be used as a key or value. + * + *

ConcurrentHashMapV8s support parallel operations using the {@link + * ForkJoinPool#commonPool}. (Tasks that may be used in other contexts + * are available in class {@link ForkJoinTasks}). These operations are + * designed to be safely, and often sensibly, applied even with maps + * that are being concurrently updated by other threads; for example, + * when computing a snapshot summary of the values in a shared + * registry. There are three kinds of operation, each with four + * forms, accepting functions with Keys, Values, Entries, and (Key, + * Value) arguments and/or return values. (The first three forms are + * also available via the {@link #keySet()}, {@link #values()} and + * {@link #entrySet()} views). Because the elements of a + * ConcurrentHashMapV8 are not ordered in any particular way, and may be + * processed in different orders in different parallel executions, the + * correctness of supplied functions should not depend on any + * ordering, or on any other objects or values that may transiently + * change while computation is in progress; and except for forEach + * actions, should ideally be side-effect-free. + * + *

+ * + *

The concurrency properties of bulk operations follow + * from those of ConcurrentHashMapV8: Any non-null result returned + * from {@code get(key)} and related access methods bears a + * happens-before relation with the associated insertion or + * update. The result of any bulk operation reflects the + * composition of these per-element relations (but is not + * necessarily atomic with respect to the map as a whole unless it + * is somehow known to be quiescent). Conversely, because keys + * and values in the map are never null, null serves as a reliable + * atomic indicator of the current lack of any result. To + * maintain this property, null serves as an implicit basis for + * all non-scalar reduction operations. For the double, long, and + * int versions, the basis should be one that, when combined with + * any other value, returns that other value (more formally, it + * should be the identity element for the reduction). Most common + * reductions have these properties; for example, computing a sum + * with basis 0 or a minimum with basis MAX_VALUE. + * + *

Search and transformation functions provided as arguments + * should similarly return null to indicate the lack of any result + * (in which case it is not used). In the case of mapped + * reductions, this also enables transformations to serve as + * filters, returning null (or, in the case of primitive + * specializations, the identity basis) if the element should not + * be combined. You can create compound transformations and + * filterings by composing them yourself under this "null means + * there is nothing there now" rule before using them in search or + * reduce operations. + * + *

Methods accepting and/or returning Entry arguments maintain + * key-value associations. They may be useful for example when + * finding the key for the greatest value. Note that "plain" Entry + * arguments can be supplied using {@code new + * AbstractMap.SimpleEntry(k,v)}. + * + *

Bulk operations may complete abruptly, throwing an + * exception encountered in the application of a supplied + * function. Bear in mind when handling such exceptions that other + * concurrently executing functions could also have thrown + * exceptions, or would have done so if the first exception had + * not occurred. + * + *

Parallel speedups for bulk operations compared to sequential + * processing are common but not guaranteed. Operations involving + * brief functions on small maps may execute more slowly than + * sequential loops if the underlying work to parallelize the + * computation is more expensive than the computation itself. + * Similarly, parallelization may not lead to much actual parallelism + * if all processors are busy performing unrelated tasks. + * + *

All arguments to all task methods must be non-null. + * + *

jsr166e note: During transition, this class + * uses nested functional interfaces with different names but the + * same forms as those expected for JDK8. + * + *

This class is a member of the + * + * Java Collections Framework. + * + * @since 1.5 + * @author Doug Lea + * @param the type of keys maintained by this map + * @param the type of mapped values + */ +public class ConcurrentHashMapV8 + implements ConcurrentMap, Serializable, ConcurrentHashMap { + private static final long serialVersionUID = 7249069246763182397L; + + /** + * A partitionable iterator. A Spliterator can be traversed + * directly, but can also be partitioned (before traversal) by + * creating another Spliterator that covers a non-overlapping + * portion of the elements, and so may be amenable to parallel + * execution. + * + *

This interface exports a subset of expected JDK8 + * functionality. + * + *

Sample usage: Here is one (of the several) ways to compute + * the sum of the values held in a map using the ForkJoin + * framework. As illustrated here, Spliterators are well suited to + * designs in which a task repeatedly splits off half its work + * into forked subtasks until small enough to process directly, + * and then joins these subtasks. Variants of this style can also + * be used in completion-based designs. + * + *

+     * {@code ConcurrentHashMapV8 m = ...
+     * // split as if have 8 * parallelism, for load balance
+     * int n = m.size();
+     * int p = aForkJoinPool.getParallelism() * 8;
+     * int split = (n < p)? n : p;
+     * long sum = aForkJoinPool.invoke(new SumValues(m.valueSpliterator(), split, null));
+     * // ...
+     * static class SumValues extends RecursiveTask {
+     *   final Spliterator s;
+     *   final int split;             // split while > 1
+     *   final SumValues nextJoin;    // records forked subtasks to join
+     *   SumValues(Spliterator s, int depth, SumValues nextJoin) {
+     *     this.s = s; this.depth = depth; this.nextJoin = nextJoin;
+     *   }
+     *   public Long compute() {
+     *     long sum = 0;
+     *     SumValues subtasks = null; // fork subtasks
+     *     for (int s = split >>> 1; s > 0; s >>>= 1)
+     *       (subtasks = new SumValues(s.split(), s, subtasks)).fork();
+     *     while (s.hasNext())        // directly process remaining elements
+     *       sum += s.next();
+     *     for (SumValues t = subtasks; t != null; t = t.nextJoin)
+     *       sum += t.join();         // collect subtask results
+     *     return sum;
+     *   }
+     * }
+     * }
+ */ + public static interface Spliterator extends Iterator { + /** + * Returns a Spliterator covering approximately half of the + * elements, guaranteed not to overlap with those subsequently + * returned by this Spliterator. After invoking this method, + * the current Spliterator will not produce any of + * the elements of the returned Spliterator, but the two + * Spliterators together will produce all of the elements that + * would have been produced by this Spliterator had this + * method not been called. The exact number of elements + * produced by the returned Spliterator is not guaranteed, and + * may be zero (i.e., with {@code hasNext()} reporting {@code + * false}) if this Spliterator cannot be further split. + * + * @return a Spliterator covering approximately half of the + * elements + * @throws IllegalStateException if this Spliterator has + * already commenced traversing elements + */ + Spliterator split(); + } + + + /* + * Overview: + * + * The primary design goal of this hash table is to maintain + * concurrent readability (typically method get(), but also + * iterators and related methods) while minimizing update + * contention. Secondary goals are to keep space consumption about + * the same or better than java.util.HashMap, and to support high + * initial insertion rates on an empty table by many threads. + * + * Each key-value mapping is held in a Node. Because Node fields + * can contain special values, they are defined using plain Object + * types. Similarly in turn, all internal methods that use them + * work off Object types. And similarly, so do the internal + * methods of auxiliary iterator and view classes. All public + * generic typed methods relay in/out of these internal methods, + * supplying null-checks and casts as needed. This also allows + * many of the public methods to be factored into a smaller number + * of internal methods (although sadly not so for the five + * variants of put-related operations). The validation-based + * approach explained below leads to a lot of code sprawl because + * retry-control precludes factoring into smaller methods. + * + * The table is lazily initialized to a power-of-two size upon the + * first insertion. Each bin in the table normally contains a + * list of Nodes (most often, the list has only zero or one Node). + * Table accesses require volatile/atomic reads, writes, and + * CASes. Because there is no other way to arrange this without + * adding further indirections, we use intrinsics + * (sun.misc.Unsafe) operations. The lists of nodes within bins + * are always accurately traversable under volatile reads, so long + * as lookups check hash code and non-nullness of value before + * checking key equality. + * + * We use the top two bits of Node hash fields for control + * purposes -- they are available anyway because of addressing + * constraints. As explained further below, these top bits are + * used as follows: + * 00 - Normal + * 01 - Locked + * 11 - Locked and may have a thread waiting for lock + * 10 - Node is a forwarding node + * + * The lower 30 bits of each Node's hash field contain a + * transformation of the key's hash code, except for forwarding + * nodes, for which the lower bits are zero (and so always have + * hash field == MOVED). + * + * Insertion (via put or its variants) of the first node in an + * empty bin is performed by just CASing it to the bin. This is + * by far the most common case for put operations under most + * key/hash distributions. Other update operations (insert, + * delete, and replace) require locks. We do not want to waste + * the space required to associate a distinct lock object with + * each bin, so instead use the first node of a bin list itself as + * a lock. Blocking support for these locks relies on the builtin + * "synchronized" monitors. However, we also need a tryLock + * construction, so we overlay these by using bits of the Node + * hash field for lock control (see above), and so normally use + * builtin monitors only for blocking and signalling using + * wait/notifyAll constructions. See Node.tryAwaitLock. + * + * Using the first node of a list as a lock does not by itself + * suffice though: When a node is locked, any update must first + * validate that it is still the first node after locking it, and + * retry if not. Because new nodes are always appended to lists, + * once a node is first in a bin, it remains first until deleted + * or the bin becomes invalidated (upon resizing). However, + * operations that only conditionally update may inspect nodes + * until the point of update. This is a converse of sorts to the + * lazy locking technique described by Herlihy & Shavit. + * + * The main disadvantage of per-bin locks is that other update + * operations on other nodes in a bin list protected by the same + * lock can stall, for example when user equals() or mapping + * functions take a long time. However, statistically, under + * random hash codes, this is not a common problem. Ideally, the + * frequency of nodes in bins follows a Poisson distribution + * (http://en.wikipedia.org/wiki/Poisson_distribution) with a + * parameter of about 0.5 on average, given the resizing threshold + * of 0.75, although with a large variance because of resizing + * granularity. Ignoring variance, the expected occurrences of + * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The + * first values are: + * + * 0: 0.60653066 + * 1: 0.30326533 + * 2: 0.07581633 + * 3: 0.01263606 + * 4: 0.00157952 + * 5: 0.00015795 + * 6: 0.00001316 + * 7: 0.00000094 + * 8: 0.00000006 + * more: less than 1 in ten million + * + * Lock contention probability for two threads accessing distinct + * elements is roughly 1 / (8 * #elements) under random hashes. + * + * Actual hash code distributions encountered in practice + * sometimes deviate significantly from uniform randomness. This + * includes the case when N > (1<<30), so some keys MUST collide. + * Similarly for dumb or hostile usages in which multiple keys are + * designed to have identical hash codes. Also, although we guard + * against the worst effects of this (see method spread), sets of + * hashes may differ only in bits that do not impact their bin + * index for a given power-of-two mask. So we use a secondary + * strategy that applies when the number of nodes in a bin exceeds + * a threshold, and at least one of the keys implements + * Comparable. These TreeBins use a balanced tree to hold nodes + * (a specialized form of red-black trees), bounding search time + * to O(log N). Each search step in a TreeBin is around twice as + * slow as in a regular list, but given that N cannot exceed + * (1<<64) (before running out of addresses) this bounds search + * steps, lock hold times, etc, to reasonable constants (roughly + * 100 nodes inspected per operation worst case) so long as keys + * are Comparable (which is very common -- String, Long, etc). + * TreeBin nodes (TreeNodes) also maintain the same "next" + * traversal pointers as regular nodes, so can be traversed in + * iterators in the same way. + * + * The table is resized when occupancy exceeds a percentage + * threshold (nominally, 0.75, but see below). Only a single + * thread performs the resize (using field "sizeCtl", to arrange + * exclusion), but the table otherwise remains usable for reads + * and updates. Resizing proceeds by transferring bins, one by + * one, from the table to the next table. Because we are using + * power-of-two expansion, the elements from each bin must either + * stay at same index, or move with a power of two offset. We + * eliminate unnecessary node creation by catching cases where old + * nodes can be reused because their next fields won't change. On + * average, only about one-sixth of them need cloning when a table + * doubles. The nodes they replace will be garbage collectable as + * soon as they are no longer referenced by any reader thread that + * may be in the midst of concurrently traversing table. Upon + * transfer, the old table bin contains only a special forwarding + * node (with hash field "MOVED") that contains the next table as + * its key. On encountering a forwarding node, access and update + * operations restart, using the new table. + * + * Each bin transfer requires its bin lock. However, unlike other + * cases, a transfer can skip a bin if it fails to acquire its + * lock, and revisit it later (unless it is a TreeBin). Method + * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that + * have been skipped because of failure to acquire a lock, and + * blocks only if none are available (i.e., only very rarely). + * The transfer operation must also ensure that all accessible + * bins in both the old and new table are usable by any traversal. + * When there are no lock acquisition failures, this is arranged + * simply by proceeding from the last bin (table.length - 1) up + * towards the first. Upon seeing a forwarding node, traversals + * (see class Iter) arrange to move to the new table + * without revisiting nodes. However, when any node is skipped + * during a transfer, all earlier table bins may have become + * visible, so are initialized with a reverse-forwarding node back + * to the old table until the new ones are established. (This + * sometimes requires transiently locking a forwarding node, which + * is possible under the above encoding.) These more expensive + * mechanics trigger only when necessary. + * + * The traversal scheme also applies to partial traversals of + * ranges of bins (via an alternate Traverser constructor) + * to support partitioned aggregate operations. Also, read-only + * operations give up if ever forwarded to a null table, which + * provides support for shutdown-style clearing, which is also not + * currently implemented. + * + * Lazy table initialization minimizes footprint until first use, + * and also avoids resizings when the first operation is from a + * putAll, constructor with map argument, or deserialization. + * These cases attempt to override the initial capacity settings, + * but harmlessly fail to take effect in cases of races. + * + * The element count is maintained using a LongAdder, which avoids + * contention on updates but can encounter cache thrashing if read + * too frequently during concurrent access. To avoid reading so + * often, resizing is attempted either when a bin lock is + * contended, or upon adding to a bin already holding two or more + * nodes (checked before adding in the xIfAbsent methods, after + * adding in others). Under uniform hash distributions, the + * probability of this occurring at threshold is around 13%, + * meaning that only about 1 in 8 puts check threshold (and after + * resizing, many fewer do so). But this approximation has high + * variance for small table sizes, so we check on any collision + * for sizes <= 64. The bulk putAll operation further reduces + * contention by only committing count updates upon these size + * checks. + * + * Maintaining API and serialization compatibility with previous + * versions of this class introduces several oddities. Mainly: We + * leave untouched but unused constructor arguments refering to + * concurrencyLevel. We accept a loadFactor constructor argument, + * but apply it only to initial table capacity (which is the only + * time that we can guarantee to honor it.) We also declare an + * unused "Segment" class that is instantiated in minimal form + * only when serializing. + */ + + /* ---------------- Constants -------------- */ + + /** + * The largest possible table capacity. This value must be + * exactly 1<<30 to stay within Java array allocation and indexing + * bounds for power of two table sizes, and is further required + * because the top two bits of 32bit hash fields are used for + * control purposes. + */ + private static final int MAXIMUM_CAPACITY = 1 << 30; + + /** + * The default initial table capacity. Must be a power of 2 + * (i.e., at least 1) and at most MAXIMUM_CAPACITY. + */ + private static final int DEFAULT_CAPACITY = 16; + + /** + * The largest possible (non-power of two) array size. + * Needed by toArray and related methods. + */ + static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; + + /** + * The default concurrency level for this table. Unused but + * defined for compatibility with previous versions of this class. + */ + private static final int DEFAULT_CONCURRENCY_LEVEL = 16; + + /** + * The load factor for this table. Overrides of this value in + * constructors affect only the initial table capacity. The + * actual floating point value isn't normally used -- it is + * simpler to use expressions such as {@code n - (n >>> 2)} for + * the associated resizing threshold. + */ + private static final float LOAD_FACTOR = 0.75f; + + /** + * The buffer size for skipped bins during transfers. The + * value is arbitrary but should be large enough to avoid + * most locking stalls during resizes. + */ + private static final int TRANSFER_BUFFER_SIZE = 32; + + /** + * The bin count threshold for using a tree rather than list for a + * bin. The value reflects the approximate break-even point for + * using tree-based operations. + * Note that Doug's version defaults to 8, but when dealing with + * Ruby objects it is actually beneficial to avoid TreeNodes + * as long as possible as it usually means going into Ruby land. + */ + private static final int TREE_THRESHOLD = 16; + + /* + * Encodings for special uses of Node hash fields. See above for + * explanation. + */ + static final int MOVED = 0x80000000; // hash field for forwarding nodes + static final int LOCKED = 0x40000000; // set/tested only as a bit + static final int WAITING = 0xc0000000; // both bits set/tested together + static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash + + /* ---------------- Fields -------------- */ + + /** + * The array of bins. Lazily initialized upon first insertion. + * Size is always a power of two. Accessed directly by iterators. + */ + transient volatile AtomicReferenceArray table; + + /** + * The counter maintaining number of elements. + */ + private transient LongAdder counter; + + /** + * Table initialization and resizing control. When negative, the + * table is being initialized or resized. Otherwise, when table is + * null, holds the initial table size to use upon creation, or 0 + * for default. After initialization, holds the next element count + * value upon which to resize the table. + */ + private transient volatile int sizeCtl; + + // views + private transient KeySetView keySet; + private transient ValuesView values; + private transient EntrySetView entrySet; + + /** For serialization compatibility. Null unless serialized; see below */ + private Segment[] segments; + + static AtomicIntegerFieldUpdater SIZE_CTRL_UPDATER = AtomicIntegerFieldUpdater.newUpdater(ConcurrentHashMapV8.class, "sizeCtl"); + + /* ---------------- Table element access -------------- */ + + /* + * Volatile access methods are used for table elements as well as + * elements of in-progress next table while resizing. Uses are + * null checked by callers, and implicitly bounds-checked, relying + * on the invariants that tab arrays have non-zero size, and all + * indices are masked with (tab.length - 1) which is never + * negative and always less than length. Note that, to be correct + * wrt arbitrary concurrency errors by users, bounds checks must + * operate on local variables, which accounts for some odd-looking + * inline assignments below. + */ + + static final Node tabAt(AtomicReferenceArray tab, int i) { // used by Iter + return tab.get(i); + } + + private static final boolean casTabAt(AtomicReferenceArray tab, int i, Node c, Node v) { + return tab.compareAndSet(i, c, v); + } + + private static final void setTabAt(AtomicReferenceArray tab, int i, Node v) { + tab.set(i, v); + } + + /* ---------------- Nodes -------------- */ + + /** + * Key-value entry. Note that this is never exported out as a + * user-visible Map.Entry (see MapEntry below). Nodes with a hash + * field of MOVED are special, and do not contain user keys or + * values. Otherwise, keys are never null, and null val fields + * indicate that a node is in the process of being deleted or + * created. For purposes of read-only access, a key may be read + * before a val, but can only be used after checking val to be + * non-null. + */ + static class Node { + volatile int hash; + final Object key; + volatile Object val; + volatile Node next; + + static AtomicIntegerFieldUpdater HASH_UPDATER = AtomicIntegerFieldUpdater.newUpdater(Node.class, "hash"); + + Node(int hash, Object key, Object val, Node next) { + this.hash = hash; + this.key = key; + this.val = val; + this.next = next; + } + + /** CompareAndSet the hash field */ + final boolean casHash(int cmp, int val) { + return HASH_UPDATER.compareAndSet(this, cmp, val); + } + + /** The number of spins before blocking for a lock */ + static final int MAX_SPINS = + Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1; + + /** + * Spins a while if LOCKED bit set and this node is the first + * of its bin, and then sets WAITING bits on hash field and + * blocks (once) if they are still set. It is OK for this + * method to return even if lock is not available upon exit, + * which enables these simple single-wait mechanics. + * + * The corresponding signalling operation is performed within + * callers: Upon detecting that WAITING has been set when + * unlocking lock (via a failed CAS from non-waiting LOCKED + * state), unlockers acquire the sync lock and perform a + * notifyAll. + * + * The initial sanity check on tab and bounds is not currently + * necessary in the only usages of this method, but enables + * use in other future contexts. + */ + final void tryAwaitLock(AtomicReferenceArray tab, int i) { + if (tab != null && i >= 0 && i < tab.length()) { // sanity check + int r = ThreadLocalRandom.current().nextInt(); // randomize spins + int spins = MAX_SPINS, h; + while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) { + if (spins >= 0) { + r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift + if (r >= 0 && --spins == 0) + Thread.yield(); // yield before block + } + else if (casHash(h, h | WAITING)) { + synchronized (this) { + if (tabAt(tab, i) == this && + (hash & WAITING) == WAITING) { + try { + wait(); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + } + } + else + notifyAll(); // possibly won race vs signaller + } + break; + } + } + } + } + } + + /* ---------------- TreeBins -------------- */ + + /** + * Nodes for use in TreeBins + */ + static final class TreeNode extends Node { + TreeNode parent; // red-black tree links + TreeNode left; + TreeNode right; + TreeNode prev; // needed to unlink next upon deletion + boolean red; + + TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) { + super(hash, key, val, next); + this.parent = parent; + } + } + + /** + * A specialized form of red-black tree for use in bins + * whose size exceeds a threshold. + * + * TreeBins use a special form of comparison for search and + * related operations (which is the main reason we cannot use + * existing collections such as TreeMaps). TreeBins contain + * Comparable elements, but may contain others, as well as + * elements that are Comparable but not necessarily Comparable + * for the same T, so we cannot invoke compareTo among them. To + * handle this, the tree is ordered primarily by hash value, then + * by getClass().getName() order, and then by Comparator order + * among elements of the same class. On lookup at a node, if + * elements are not comparable or compare as 0, both left and + * right children may need to be searched in the case of tied hash + * values. (This corresponds to the full list search that would be + * necessary if all elements were non-Comparable and had tied + * hashes.) The red-black balancing code is updated from + * pre-jdk-collections + * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java) + * based in turn on Cormen, Leiserson, and Rivest "Introduction to + * Algorithms" (CLR). + * + * TreeBins also maintain a separate locking discipline than + * regular bins. Because they are forwarded via special MOVED + * nodes at bin heads (which can never change once established), + * we cannot use those nodes as locks. Instead, TreeBin + * extends AbstractQueuedSynchronizer to support a simple form of + * read-write lock. For update operations and table validation, + * the exclusive form of lock behaves in the same way as bin-head + * locks. However, lookups use shared read-lock mechanics to allow + * multiple readers in the absence of writers. Additionally, + * these lookups do not ever block: While the lock is not + * available, they proceed along the slow traversal path (via + * next-pointers) until the lock becomes available or the list is + * exhausted, whichever comes first. (These cases are not fast, + * but maximize aggregate expected throughput.) The AQS mechanics + * for doing this are straightforward. The lock state is held as + * AQS getState(). Read counts are negative; the write count (1) + * is positive. There are no signalling preferences among readers + * and writers. Since we don't need to export full Lock API, we + * just override the minimal AQS methods and use them directly. + */ + static final class TreeBin extends AbstractQueuedSynchronizer { + private static final long serialVersionUID = 2249069246763182397L; + transient TreeNode root; // root of tree + transient TreeNode first; // head of next-pointer list + + /* AQS overrides */ + public final boolean isHeldExclusively() { return getState() > 0; } + public final boolean tryAcquire(int ignore) { + if (compareAndSetState(0, 1)) { + setExclusiveOwnerThread(Thread.currentThread()); + return true; + } + return false; + } + public final boolean tryRelease(int ignore) { + setExclusiveOwnerThread(null); + setState(0); + return true; + } + public final int tryAcquireShared(int ignore) { + for (int c;;) { + if ((c = getState()) > 0) + return -1; + if (compareAndSetState(c, c -1)) + return 1; + } + } + public final boolean tryReleaseShared(int ignore) { + int c; + do {} while (!compareAndSetState(c = getState(), c + 1)); + return c == -1; + } + + /** From CLR */ + private void rotateLeft(TreeNode p) { + if (p != null) { + TreeNode r = p.right, pp, rl; + if ((rl = p.right = r.left) != null) + rl.parent = p; + if ((pp = r.parent = p.parent) == null) + root = r; + else if (pp.left == p) + pp.left = r; + else + pp.right = r; + r.left = p; + p.parent = r; + } + } + + /** From CLR */ + private void rotateRight(TreeNode p) { + if (p != null) { + TreeNode l = p.left, pp, lr; + if ((lr = p.left = l.right) != null) + lr.parent = p; + if ((pp = l.parent = p.parent) == null) + root = l; + else if (pp.right == p) + pp.right = l; + else + pp.left = l; + l.right = p; + p.parent = l; + } + } + + @SuppressWarnings("unchecked") final TreeNode getTreeNode + (int h, Object k, TreeNode p) { + return getTreeNode(h, (RubyObject)k, p); + } + + /** + * Returns the TreeNode (or null if not found) for the given key + * starting at given root. + */ + @SuppressWarnings("unchecked") final TreeNode getTreeNode + (int h, RubyObject k, TreeNode p) { + RubyClass c = k.getMetaClass(); boolean kNotComparable = !k.respondsTo("<=>"); + while (p != null) { + int dir, ph; RubyObject pk; RubyClass pc; + if ((ph = p.hash) == h) { + if ((pk = (RubyObject)p.key) == k || k.equals(pk)) + return p; + if (c != (pc = (RubyClass)pk.getMetaClass()) || + kNotComparable || + (dir = rubyCompare(k, pk)) == 0) { + dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName()); + if (dir == 0) { // if still stuck, need to check both sides + TreeNode r = null, pl, pr; + // try to recurse on the right + if ((pr = p.right) != null && h >= pr.hash && (r = getTreeNode(h, k, pr)) != null) + return r; + // try to continue iterating on the left side + else if ((pl = p.left) != null && h <= pl.hash) + dir = -1; + else // no matching node found + return null; + } + } + } + else + dir = (h < ph) ? -1 : 1; + p = (dir > 0) ? p.right : p.left; + } + return null; + } + + int rubyCompare(RubyObject l, RubyObject r) { + ThreadContext context = l.getMetaClass().getRuntime().getCurrentContext(); + IRubyObject result; + try { + result = l.callMethod(context, "<=>", r); + } catch (RaiseException e) { + // handle objects "lying" about responding to <=>, ie: an Array containing non-comparable keys + if (context.runtime.getNoMethodError().isInstance(e.getException())) { + return 0; + } + throw e; + } + + return result.isNil() ? 0 : RubyNumeric.num2int(result.convertToInteger()); + } + + /** + * Wrapper for getTreeNode used by CHM.get. Tries to obtain + * read-lock to call getTreeNode, but during failure to get + * lock, searches along next links. + */ + final Object getValue(int h, Object k) { + Node r = null; + int c = getState(); // Must read lock state first + for (Node e = first; e != null; e = e.next) { + if (c <= 0 && compareAndSetState(c, c - 1)) { + try { + r = getTreeNode(h, k, root); + } finally { + releaseShared(0); + } + break; + } + else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) { + r = e; + break; + } + else + c = getState(); + } + return r == null ? null : r.val; + } + + @SuppressWarnings("unchecked") final TreeNode putTreeNode + (int h, Object k, Object v) { + return putTreeNode(h, (RubyObject)k, v); + } + + /** + * Finds or adds a node. + * @return null if added + */ + @SuppressWarnings("unchecked") final TreeNode putTreeNode + (int h, RubyObject k, Object v) { + RubyClass c = k.getMetaClass(); + boolean kNotComparable = !k.respondsTo("<=>"); + TreeNode pp = root, p = null; + int dir = 0; + while (pp != null) { // find existing node or leaf to insert at + int ph; RubyObject pk; RubyClass pc; + p = pp; + if ((ph = p.hash) == h) { + if ((pk = (RubyObject)p.key) == k || k.equals(pk)) + return p; + if (c != (pc = pk.getMetaClass()) || + kNotComparable || + (dir = rubyCompare(k, pk)) == 0) { + dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName()); + if (dir == 0) { // if still stuck, need to check both sides + TreeNode r = null, pr; + // try to recurse on the right + if ((pr = p.right) != null && h >= pr.hash && (r = getTreeNode(h, k, pr)) != null) + return r; + else // continue descending down the left subtree + dir = -1; + } + } + } + else + dir = (h < ph) ? -1 : 1; + pp = (dir > 0) ? p.right : p.left; + } + + TreeNode f = first; + TreeNode x = first = new TreeNode(h, (Object)k, v, f, p); + if (p == null) + root = x; + else { // attach and rebalance; adapted from CLR + TreeNode xp, xpp; + if (f != null) + f.prev = x; + if (dir <= 0) + p.left = x; + else + p.right = x; + x.red = true; + while (x != null && (xp = x.parent) != null && xp.red && + (xpp = xp.parent) != null) { + TreeNode xppl = xpp.left; + if (xp == xppl) { + TreeNode y = xpp.right; + if (y != null && y.red) { + y.red = false; + xp.red = false; + xpp.red = true; + x = xpp; + } + else { + if (x == xp.right) { + rotateLeft(x = xp); + xpp = (xp = x.parent) == null ? null : xp.parent; + } + if (xp != null) { + xp.red = false; + if (xpp != null) { + xpp.red = true; + rotateRight(xpp); + } + } + } + } + else { + TreeNode y = xppl; + if (y != null && y.red) { + y.red = false; + xp.red = false; + xpp.red = true; + x = xpp; + } + else { + if (x == xp.left) { + rotateRight(x = xp); + xpp = (xp = x.parent) == null ? null : xp.parent; + } + if (xp != null) { + xp.red = false; + if (xpp != null) { + xpp.red = true; + rotateLeft(xpp); + } + } + } + } + } + TreeNode r = root; + if (r != null && r.red) + r.red = false; + } + return null; + } + + /** + * Removes the given node, that must be present before this + * call. This is messier than typical red-black deletion code + * because we cannot swap the contents of an interior node + * with a leaf successor that is pinned by "next" pointers + * that are accessible independently of lock. So instead we + * swap the tree linkages. + */ + final void deleteTreeNode(TreeNode p) { + TreeNode next = (TreeNode)p.next; // unlink traversal pointers + TreeNode pred = p.prev; + if (pred == null) + first = next; + else + pred.next = next; + if (next != null) + next.prev = pred; + TreeNode replacement; + TreeNode pl = p.left; + TreeNode pr = p.right; + if (pl != null && pr != null) { + TreeNode s = pr, sl; + while ((sl = s.left) != null) // find successor + s = sl; + boolean c = s.red; s.red = p.red; p.red = c; // swap colors + TreeNode sr = s.right; + TreeNode pp = p.parent; + if (s == pr) { // p was s's direct parent + p.parent = s; + s.right = p; + } + else { + TreeNode sp = s.parent; + if ((p.parent = sp) != null) { + if (s == sp.left) + sp.left = p; + else + sp.right = p; + } + if ((s.right = pr) != null) + pr.parent = s; + } + p.left = null; + if ((p.right = sr) != null) + sr.parent = p; + if ((s.left = pl) != null) + pl.parent = s; + if ((s.parent = pp) == null) + root = s; + else if (p == pp.left) + pp.left = s; + else + pp.right = s; + replacement = sr; + } + else + replacement = (pl != null) ? pl : pr; + TreeNode pp = p.parent; + if (replacement == null) { + if (pp == null) { + root = null; + return; + } + replacement = p; + } + else { + replacement.parent = pp; + if (pp == null) + root = replacement; + else if (p == pp.left) + pp.left = replacement; + else + pp.right = replacement; + p.left = p.right = p.parent = null; + } + if (!p.red) { // rebalance, from CLR + TreeNode x = replacement; + while (x != null) { + TreeNode xp, xpl; + if (x.red || (xp = x.parent) == null) { + x.red = false; + break; + } + if (x == (xpl = xp.left)) { + TreeNode sib = xp.right; + if (sib != null && sib.red) { + sib.red = false; + xp.red = true; + rotateLeft(xp); + sib = (xp = x.parent) == null ? null : xp.right; + } + if (sib == null) + x = xp; + else { + TreeNode sl = sib.left, sr = sib.right; + if ((sr == null || !sr.red) && + (sl == null || !sl.red)) { + sib.red = true; + x = xp; + } + else { + if (sr == null || !sr.red) { + if (sl != null) + sl.red = false; + sib.red = true; + rotateRight(sib); + sib = (xp = x.parent) == null ? null : xp.right; + } + if (sib != null) { + sib.red = (xp == null) ? false : xp.red; + if ((sr = sib.right) != null) + sr.red = false; + } + if (xp != null) { + xp.red = false; + rotateLeft(xp); + } + x = root; + } + } + } + else { // symmetric + TreeNode sib = xpl; + if (sib != null && sib.red) { + sib.red = false; + xp.red = true; + rotateRight(xp); + sib = (xp = x.parent) == null ? null : xp.left; + } + if (sib == null) + x = xp; + else { + TreeNode sl = sib.left, sr = sib.right; + if ((sl == null || !sl.red) && + (sr == null || !sr.red)) { + sib.red = true; + x = xp; + } + else { + if (sl == null || !sl.red) { + if (sr != null) + sr.red = false; + sib.red = true; + rotateLeft(sib); + sib = (xp = x.parent) == null ? null : xp.left; + } + if (sib != null) { + sib.red = (xp == null) ? false : xp.red; + if ((sl = sib.left) != null) + sl.red = false; + } + if (xp != null) { + xp.red = false; + rotateRight(xp); + } + x = root; + } + } + } + } + } + if (p == replacement && (pp = p.parent) != null) { + if (p == pp.left) // detach pointers + pp.left = null; + else if (p == pp.right) + pp.right = null; + p.parent = null; + } + } + } + + /* ---------------- Collision reduction methods -------------- */ + + /** + * Spreads higher bits to lower, and also forces top 2 bits to 0. + * Because the table uses power-of-two masking, sets of hashes + * that vary only in bits above the current mask will always + * collide. (Among known examples are sets of Float keys holding + * consecutive whole numbers in small tables.) To counter this, + * we apply a transform that spreads the impact of higher bits + * downward. There is a tradeoff between speed, utility, and + * quality of bit-spreading. Because many common sets of hashes + * are already reasonably distributed across bits (so don't benefit + * from spreading), and because we use trees to handle large sets + * of collisions in bins, we don't need excessively high quality. + */ + private static final int spread(int h) { + h ^= (h >>> 18) ^ (h >>> 12); + return (h ^ (h >>> 10)) & HASH_BITS; + } + + /** + * Replaces a list bin with a tree bin. Call only when locked. + * Fails to replace if the given key is non-comparable or table + * is, or needs, resizing. + */ + private final void replaceWithTreeBin(AtomicReferenceArray tab, int index, Object key) { + if ((key instanceof Comparable) && + (tab.length() >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) { + TreeBin t = new TreeBin(); + for (Node e = tabAt(tab, index); e != null; e = e.next) + t.putTreeNode(e.hash & HASH_BITS, e.key, e.val); + setTabAt(tab, index, new Node(MOVED, t, null, null)); + } + } + + /* ---------------- Internal access and update methods -------------- */ + + /** Implementation for get and containsKey */ + private final Object internalGet(Object k) { + int h = spread(k.hashCode()); + retry: for (AtomicReferenceArray tab = table; tab != null;) { + Node e, p; Object ek, ev; int eh; // locals to read fields once + for (e = tabAt(tab, (tab.length() - 1) & h); e != null; e = e.next) { + if ((eh = e.hash) == MOVED) { + if ((ek = e.key) instanceof TreeBin) // search TreeBin + return ((TreeBin)ek).getValue(h, k); + else { // restart with new table + tab = (AtomicReferenceArray)ek; + continue retry; + } + } + else if ((eh & HASH_BITS) == h && (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) + return ev; + } + break; + } + return null; + } + + /** + * Implementation for the four public remove/replace methods: + * Replaces node value with v, conditional upon match of cv if + * non-null. If resulting value is null, delete. + */ + private final Object internalReplace(Object k, Object v, Object cv) { + int h = spread(k.hashCode()); + Object oldVal = null; + for (AtomicReferenceArray tab = table;;) { + Node f; int i, fh; Object fk; + if (tab == null || + (f = tabAt(tab, i = (tab.length() - 1) & h)) == null) + break; + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + boolean validated = false; + boolean deleted = false; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + validated = true; + TreeNode p = t.getTreeNode(h, k, t.root); + if (p != null) { + Object pv = p.val; + if (cv == null || cv == pv || cv.equals(pv)) { + oldVal = pv; + if ((p.val = v) == null) { + deleted = true; + t.deleteTreeNode(p); + } + } + } + } + } finally { + t.release(0); + } + if (validated) { + if (deleted) + counter.add(-1L); + break; + } + } + else + tab = (AtomicReferenceArray)fk; + } + else if ((fh & HASH_BITS) != h && f.next == null) // precheck + break; // rules out possible existence + else if ((fh & LOCKED) != 0) { + checkForResize(); // try resizing if can't get lock + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + boolean validated = false; + boolean deleted = false; + try { + if (tabAt(tab, i) == f) { + validated = true; + for (Node e = f, pred = null;;) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + ((ev = e.val) != null) && + ((ek = e.key) == k || k.equals(ek))) { + if (cv == null || cv == ev || cv.equals(ev)) { + oldVal = ev; + if ((e.val = v) == null) { + deleted = true; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); + } + } + break; + } + pred = e; + if ((e = e.next) == null) + break; + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (validated) { + if (deleted) + counter.add(-1L); + break; + } + } + } + return oldVal; + } + + /* + * Internal versions of the six insertion methods, each a + * little more complicated than the last. All have + * the same basic structure as the first (internalPut): + * 1. If table uninitialized, create + * 2. If bin empty, try to CAS new node + * 3. If bin stale, use new table + * 4. if bin converted to TreeBin, validate and relay to TreeBin methods + * 5. Lock and validate; if valid, scan and add or update + * + * The others interweave other checks and/or alternative actions: + * * Plain put checks for and performs resize after insertion. + * * putIfAbsent prescans for mapping without lock (and fails to add + * if present), which also makes pre-emptive resize checks worthwhile. + * * computeIfAbsent extends form used in putIfAbsent with additional + * mechanics to deal with, calls, potential exceptions and null + * returns from function call. + * * compute uses the same function-call mechanics, but without + * the prescans + * * merge acts as putIfAbsent in the absent case, but invokes the + * update function if present + * * putAll attempts to pre-allocate enough table space + * and more lazily performs count updates and checks. + * + * Someday when details settle down a bit more, it might be worth + * some factoring to reduce sprawl. + */ + + /** Implementation for put */ + private final Object internalPut(Object k, Object v) { + int h = spread(k.hashCode()); + int count = 0; + for (AtomicReferenceArray tab = table;;) { + int i; Node f; int fh; Object fk; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length() - 1) & h)) == null) { + if (casTabAt(tab, i, null, new Node(h, k, v, null))) + break; // no lock when adding to empty bin + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + Object oldVal = null; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + count = 2; + TreeNode p = t.putTreeNode(h, k, v); + if (p != null) { + oldVal = p.val; + p.val = v; + } + } + } finally { + t.release(0); + } + if (count != 0) { + if (oldVal != null) + return oldVal; + break; + } + } + else + tab = (AtomicReferenceArray)fk; + } + else if ((fh & LOCKED) != 0) { + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + Object oldVal = null; + try { // needed in case equals() throws + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + oldVal = ev; + e.val = v; + break; + } + Node last = e; + if ((e = e.next) == null) { + last.next = new Node(h, k, v, null); + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + break; + } + } + } + } finally { // unlock and signal if needed + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (oldVal != null) + return oldVal; + if (tab.length() <= 64) + count = 2; + break; + } + } + } + counter.add(1L); + if (count > 1) + checkForResize(); + return null; + } + + /** Implementation for putIfAbsent */ + private final Object internalPutIfAbsent(Object k, Object v) { + int h = spread(k.hashCode()); + int count = 0; + for (AtomicReferenceArray tab = table;;) { + int i; Node f; int fh; Object fk, fv; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length() - 1) & h)) == null) { + if (casTabAt(tab, i, null, new Node(h, k, v, null))) + break; + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + Object oldVal = null; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + count = 2; + TreeNode p = t.putTreeNode(h, k, v); + if (p != null) + oldVal = p.val; + } + } finally { + t.release(0); + } + if (count != 0) { + if (oldVal != null) + return oldVal; + break; + } + } + else + tab = (AtomicReferenceArray)fk; + } + else if ((fh & HASH_BITS) == h && (fv = f.val) != null && + ((fk = f.key) == k || k.equals(fk))) + return fv; + else { + Node g = f.next; + if (g != null) { // at least 2 nodes -- search and maybe resize + for (Node e = g;;) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) + return ev; + if ((e = e.next) == null) { + checkForResize(); + break; + } + } + } + if (((fh = f.hash) & LOCKED) != 0) { + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) { + Object oldVal = null; + try { + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + oldVal = ev; + break; + } + Node last = e; + if ((e = e.next) == null) { + last.next = new Node(h, k, v, null); + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + break; + } + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (oldVal != null) + return oldVal; + if (tab.length() <= 64) + count = 2; + break; + } + } + } + } + counter.add(1L); + if (count > 1) + checkForResize(); + return null; + } + + /** Implementation for computeIfAbsent */ + private final Object internalComputeIfAbsent(K k, + Fun mf) { + int h = spread(k.hashCode()); + Object val = null; + int count = 0; + for (AtomicReferenceArray tab = table;;) { + Node f; int i, fh; Object fk, fv; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length() - 1) & h)) == null) { + Node node = new Node(fh = h | LOCKED, k, null, null); + if (casTabAt(tab, i, null, node)) { + count = 1; + try { + if ((val = mf.apply(k)) != null) + node.val = val; + } finally { + if (val == null) + setTabAt(tab, i, null); + if (!node.casHash(fh, h)) { + node.hash = h; + synchronized (node) { node.notifyAll(); }; + } + } + } + if (count != 0) + break; + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + boolean added = false; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + count = 1; + TreeNode p = t.getTreeNode(h, k, t.root); + if (p != null) + val = p.val; + else if ((val = mf.apply(k)) != null) { + added = true; + count = 2; + t.putTreeNode(h, k, val); + } + } + } finally { + t.release(0); + } + if (count != 0) { + if (!added) + return val; + break; + } + } + else + tab = (AtomicReferenceArray)fk; + } + else if ((fh & HASH_BITS) == h && (fv = f.val) != null && + ((fk = f.key) == k || k.equals(fk))) + return fv; + else { + Node g = f.next; + if (g != null) { + for (Node e = g;;) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) + return ev; + if ((e = e.next) == null) { + checkForResize(); + break; + } + } + } + if (((fh = f.hash) & LOCKED) != 0) { + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) { + boolean added = false; + try { + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + val = ev; + break; + } + Node last = e; + if ((e = e.next) == null) { + if ((val = mf.apply(k)) != null) { + added = true; + last.next = new Node(h, k, val, null); + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + } + break; + } + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (!added) + return val; + if (tab.length() <= 64) + count = 2; + break; + } + } + } + } + if (val != null) { + counter.add(1L); + if (count > 1) + checkForResize(); + } + return val; + } + + /** Implementation for compute */ + @SuppressWarnings("unchecked") private final Object internalCompute + (K k, boolean onlyIfPresent, BiFun mf) { + int h = spread(k.hashCode()); + Object val = null; + int delta = 0; + int count = 0; + for (AtomicReferenceArray tab = table;;) { + Node f; int i, fh; Object fk; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length() - 1) & h)) == null) { + if (onlyIfPresent) + break; + Node node = new Node(fh = h | LOCKED, k, null, null); + if (casTabAt(tab, i, null, node)) { + try { + count = 1; + if ((val = mf.apply(k, null)) != null) { + node.val = val; + delta = 1; + } + } finally { + if (delta == 0) + setTabAt(tab, i, null); + if (!node.casHash(fh, h)) { + node.hash = h; + synchronized (node) { node.notifyAll(); }; + } + } + } + if (count != 0) + break; + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + count = 1; + TreeNode p = t.getTreeNode(h, k, t.root); + Object pv; + if (p == null) { + if (onlyIfPresent) + break; + pv = null; + } else + pv = p.val; + if ((val = mf.apply(k, (V)pv)) != null) { + if (p != null) + p.val = val; + else { + count = 2; + delta = 1; + t.putTreeNode(h, k, val); + } + } + else if (p != null) { + delta = -1; + t.deleteTreeNode(p); + } + } + } finally { + t.release(0); + } + if (count != 0) + break; + } + else + tab = (AtomicReferenceArray)fk; + } + else if ((fh & LOCKED) != 0) { + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + try { + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f, pred = null;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + val = mf.apply(k, (V)ev); + if (val != null) + e.val = val; + else { + delta = -1; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); + } + break; + } + pred = e; + if ((e = e.next) == null) { + if (!onlyIfPresent && (val = mf.apply(k, null)) != null) { + pred.next = new Node(h, k, val, null); + delta = 1; + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + } + break; + } + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (tab.length() <= 64) + count = 2; + break; + } + } + } + if (delta != 0) { + counter.add((long)delta); + if (count > 1) + checkForResize(); + } + return val; + } + + /** Implementation for merge */ + @SuppressWarnings("unchecked") private final Object internalMerge + (K k, V v, BiFun mf) { + int h = spread(k.hashCode()); + Object val = null; + int delta = 0; + int count = 0; + for (AtomicReferenceArray tab = table;;) { + int i; Node f; int fh; Object fk, fv; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length() - 1) & h)) == null) { + if (casTabAt(tab, i, null, new Node(h, k, v, null))) { + delta = 1; + val = v; + break; + } + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + count = 1; + TreeNode p = t.getTreeNode(h, k, t.root); + val = (p == null) ? v : mf.apply((V)p.val, v); + if (val != null) { + if (p != null) + p.val = val; + else { + count = 2; + delta = 1; + t.putTreeNode(h, k, val); + } + } + else if (p != null) { + delta = -1; + t.deleteTreeNode(p); + } + } + } finally { + t.release(0); + } + if (count != 0) + break; + } + else + tab = (AtomicReferenceArray)fk; + } + else if ((fh & LOCKED) != 0) { + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + try { + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f, pred = null;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + val = mf.apply((V)ev, v); + if (val != null) + e.val = val; + else { + delta = -1; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); + } + break; + } + pred = e; + if ((e = e.next) == null) { + val = v; + pred.next = new Node(h, k, val, null); + delta = 1; + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + break; + } + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (tab.length() <= 64) + count = 2; + break; + } + } + } + if (delta != 0) { + counter.add((long)delta); + if (count > 1) + checkForResize(); + } + return val; + } + + /** Implementation for putAll */ + private final void internalPutAll(Map m) { + tryPresize(m.size()); + long delta = 0L; // number of uncommitted additions + boolean npe = false; // to throw exception on exit for nulls + try { // to clean up counts on other exceptions + for (Map.Entry entry : m.entrySet()) { + Object k, v; + if (entry == null || (k = entry.getKey()) == null || + (v = entry.getValue()) == null) { + npe = true; + break; + } + int h = spread(k.hashCode()); + for (AtomicReferenceArray tab = table;;) { + int i; Node f; int fh; Object fk; + if (tab == null) + tab = initTable(); + else if ((f = tabAt(tab, i = (tab.length() - 1) & h)) == null){ + if (casTabAt(tab, i, null, new Node(h, k, v, null))) { + ++delta; + break; + } + } + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + boolean validated = false; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + validated = true; + TreeNode p = t.getTreeNode(h, k, t.root); + if (p != null) + p.val = v; + else { + t.putTreeNode(h, k, v); + ++delta; + } + } + } finally { + t.release(0); + } + if (validated) + break; + } + else + tab = (AtomicReferenceArray)fk; + } + else if ((fh & LOCKED) != 0) { + counter.add(delta); + delta = 0L; + checkForResize(); + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + int count = 0; + try { + if (tabAt(tab, i) == f) { + count = 1; + for (Node e = f;; ++count) { + Object ek, ev; + if ((e.hash & HASH_BITS) == h && + (ev = e.val) != null && + ((ek = e.key) == k || k.equals(ek))) { + e.val = v; + break; + } + Node last = e; + if ((e = e.next) == null) { + ++delta; + last.next = new Node(h, k, v, null); + if (count >= TREE_THRESHOLD) + replaceWithTreeBin(tab, i, k); + break; + } + } + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (count != 0) { + if (count > 1) { + counter.add(delta); + delta = 0L; + checkForResize(); + } + break; + } + } + } + } + } finally { + if (delta != 0) + counter.add(delta); + } + if (npe) + throw new NullPointerException(); + } + + /* ---------------- Table Initialization and Resizing -------------- */ + + /** + * Returns a power of two table size for the given desired capacity. + * See Hackers Delight, sec 3.2 + */ + private static final int tableSizeFor(int c) { + int n = c - 1; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; + } + + /** + * Initializes table, using the size recorded in sizeCtl. + */ + private final AtomicReferenceArray initTable() { + AtomicReferenceArray tab; int sc; + while ((tab = table) == null) { + if ((sc = sizeCtl) < 0) + Thread.yield(); // lost initialization race; just spin + else if (SIZE_CTRL_UPDATER.compareAndSet(this, sc, -1)) { + try { + if ((tab = table) == null) { + int n = (sc > 0) ? sc : DEFAULT_CAPACITY; + tab = table = new AtomicReferenceArray(n); + sc = n - (n >>> 2); + } + } finally { + sizeCtl = sc; + } + break; + } + } + return tab; + } + + /** + * If table is too small and not already resizing, creates next + * table and transfers bins. Rechecks occupancy after a transfer + * to see if another resize is already needed because resizings + * are lagging additions. + */ + private final void checkForResize() { + AtomicReferenceArray tab; int n, sc; + while ((tab = table) != null && + (n = tab.length()) < MAXIMUM_CAPACITY && + (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc && + SIZE_CTRL_UPDATER.compareAndSet(this, sc, -1)) { + try { + if (tab == table) { + table = rebuild(tab); + sc = (n << 1) - (n >>> 1); + } + } finally { + sizeCtl = sc; + } + } + } + + /** + * Tries to presize table to accommodate the given number of elements. + * + * @param size number of elements (doesn't need to be perfectly accurate) + */ + private final void tryPresize(int size) { + int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : + tableSizeFor(size + (size >>> 1) + 1); + int sc; + while ((sc = sizeCtl) >= 0) { + AtomicReferenceArray tab = table; int n; + if (tab == null || (n = tab.length()) == 0) { + n = (sc > c) ? sc : c; + if (SIZE_CTRL_UPDATER.compareAndSet(this, sc, -1)) { + try { + if (table == tab) { + table = new AtomicReferenceArray(n); + sc = n - (n >>> 2); + } + } finally { + sizeCtl = sc; + } + } + } + else if (c <= sc || n >= MAXIMUM_CAPACITY) + break; + else if (SIZE_CTRL_UPDATER.compareAndSet(this, sc, -1)) { + try { + if (table == tab) { + table = rebuild(tab); + sc = (n << 1) - (n >>> 1); + } + } finally { + sizeCtl = sc; + } + } + } + } + + /* + * Moves and/or copies the nodes in each bin to new table. See + * above for explanation. + * + * @return the new table + */ + private static final AtomicReferenceArray rebuild(AtomicReferenceArray tab) { + int n = tab.length(); + AtomicReferenceArray nextTab = new AtomicReferenceArray(n << 1); + Node fwd = new Node(MOVED, nextTab, null, null); + int[] buffer = null; // holds bins to revisit; null until needed + Node rev = null; // reverse forwarder; null until needed + int nbuffered = 0; // the number of bins in buffer list + int bufferIndex = 0; // buffer index of current buffered bin + int bin = n - 1; // current non-buffered bin or -1 if none + + for (int i = bin;;) { // start upwards sweep + int fh; Node f; + if ((f = tabAt(tab, i)) == null) { + if (bin >= 0) { // Unbuffered; no lock needed (or available) + if (!casTabAt(tab, i, f, fwd)) + continue; + } + else { // transiently use a locked forwarding node + Node g = new Node(MOVED|LOCKED, nextTab, null, null); + if (!casTabAt(tab, i, f, g)) + continue; + setTabAt(nextTab, i, null); + setTabAt(nextTab, i + n, null); + setTabAt(tab, i, fwd); + if (!g.casHash(MOVED|LOCKED, MOVED)) { + g.hash = MOVED; + synchronized (g) { g.notifyAll(); } + } + } + } + else if ((fh = f.hash) == MOVED) { + Object fk = f.key; + if (fk instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + boolean validated = false; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + validated = true; + splitTreeBin(nextTab, i, t); + setTabAt(tab, i, fwd); + } + } finally { + t.release(0); + } + if (!validated) + continue; + } + } + else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) { + boolean validated = false; + try { // split to lo and hi lists; copying as needed + if (tabAt(tab, i) == f) { + validated = true; + splitBin(nextTab, i, f); + setTabAt(tab, i, fwd); + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + if (!validated) + continue; + } + else { + if (buffer == null) // initialize buffer for revisits + buffer = new int[TRANSFER_BUFFER_SIZE]; + if (bin < 0 && bufferIndex > 0) { + int j = buffer[--bufferIndex]; + buffer[bufferIndex] = i; + i = j; // swap with another bin + continue; + } + if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) { + f.tryAwaitLock(tab, i); + continue; // no other options -- block + } + if (rev == null) // initialize reverse-forwarder + rev = new Node(MOVED, tab, null, null); + if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0) + continue; // recheck before adding to list + buffer[nbuffered++] = i; + setTabAt(nextTab, i, rev); // install place-holders + setTabAt(nextTab, i + n, rev); + } + + if (bin > 0) + i = --bin; + else if (buffer != null && nbuffered > 0) { + bin = -1; + i = buffer[bufferIndex = --nbuffered]; + } + else + return nextTab; + } + } + + /** + * Splits a normal bin with list headed by e into lo and hi parts; + * installs in given table. + */ + private static void splitBin(AtomicReferenceArray nextTab, int i, Node e) { + int bit = nextTab.length() >>> 1; // bit to split on + int runBit = e.hash & bit; + Node lastRun = e, lo = null, hi = null; + for (Node p = e.next; p != null; p = p.next) { + int b = p.hash & bit; + if (b != runBit) { + runBit = b; + lastRun = p; + } + } + if (runBit == 0) + lo = lastRun; + else + hi = lastRun; + for (Node p = e; p != lastRun; p = p.next) { + int ph = p.hash & HASH_BITS; + Object pk = p.key, pv = p.val; + if ((ph & bit) == 0) + lo = new Node(ph, pk, pv, lo); + else + hi = new Node(ph, pk, pv, hi); + } + setTabAt(nextTab, i, lo); + setTabAt(nextTab, i + bit, hi); + } + + /** + * Splits a tree bin into lo and hi parts; installs in given table. + */ + private static void splitTreeBin(AtomicReferenceArray nextTab, int i, TreeBin t) { + int bit = nextTab.length() >>> 1; + TreeBin lt = new TreeBin(); + TreeBin ht = new TreeBin(); + int lc = 0, hc = 0; + for (Node e = t.first; e != null; e = e.next) { + int h = e.hash & HASH_BITS; + Object k = e.key, v = e.val; + if ((h & bit) == 0) { + ++lc; + lt.putTreeNode(h, k, v); + } + else { + ++hc; + ht.putTreeNode(h, k, v); + } + } + Node ln, hn; // throw away trees if too small + if (lc <= (TREE_THRESHOLD >>> 1)) { + ln = null; + for (Node p = lt.first; p != null; p = p.next) + ln = new Node(p.hash, p.key, p.val, ln); + } + else + ln = new Node(MOVED, lt, null, null); + setTabAt(nextTab, i, ln); + if (hc <= (TREE_THRESHOLD >>> 1)) { + hn = null; + for (Node p = ht.first; p != null; p = p.next) + hn = new Node(p.hash, p.key, p.val, hn); + } + else + hn = new Node(MOVED, ht, null, null); + setTabAt(nextTab, i + bit, hn); + } + + /** + * Implementation for clear. Steps through each bin, removing all + * nodes. + */ + private final void internalClear() { + long delta = 0L; // negative number of deletions + int i = 0; + AtomicReferenceArray tab = table; + while (tab != null && i < tab.length()) { + int fh; Object fk; + Node f = tabAt(tab, i); + if (f == null) + ++i; + else if ((fh = f.hash) == MOVED) { + if ((fk = f.key) instanceof TreeBin) { + TreeBin t = (TreeBin)fk; + t.acquire(0); + try { + if (tabAt(tab, i) == f) { + for (Node p = t.first; p != null; p = p.next) { + if (p.val != null) { // (currently always true) + p.val = null; + --delta; + } + } + t.first = null; + t.root = null; + ++i; + } + } finally { + t.release(0); + } + } + else + tab = (AtomicReferenceArray)fk; + } + else if ((fh & LOCKED) != 0) { + counter.add(delta); // opportunistically update count + delta = 0L; + f.tryAwaitLock(tab, i); + } + else if (f.casHash(fh, fh | LOCKED)) { + try { + if (tabAt(tab, i) == f) { + for (Node e = f; e != null; e = e.next) { + if (e.val != null) { // (currently always true) + e.val = null; + --delta; + } + } + setTabAt(tab, i, null); + ++i; + } + } finally { + if (!f.casHash(fh | LOCKED, fh)) { + f.hash = fh; + synchronized (f) { f.notifyAll(); }; + } + } + } + } + if (delta != 0) + counter.add(delta); + } + + /* ----------------Table Traversal -------------- */ + + /** + * Encapsulates traversal for methods such as containsValue; also + * serves as a base class for other iterators and bulk tasks. + * + * At each step, the iterator snapshots the key ("nextKey") and + * value ("nextVal") of a valid node (i.e., one that, at point of + * snapshot, has a non-null user value). Because val fields can + * change (including to null, indicating deletion), field nextVal + * might not be accurate at point of use, but still maintains the + * weak consistency property of holding a value that was once + * valid. To support iterator.remove, the nextKey field is not + * updated (nulled out) when the iterator cannot advance. + * + * Internal traversals directly access these fields, as in: + * {@code while (it.advance() != null) { process(it.nextKey); }} + * + * Exported iterators must track whether the iterator has advanced + * (in hasNext vs next) (by setting/checking/nulling field + * nextVal), and then extract key, value, or key-value pairs as + * return values of next(). + * + * The iterator visits once each still-valid node that was + * reachable upon iterator construction. It might miss some that + * were added to a bin after the bin was visited, which is OK wrt + * consistency guarantees. Maintaining this property in the face + * of possible ongoing resizes requires a fair amount of + * bookkeeping state that is difficult to optimize away amidst + * volatile accesses. Even so, traversal maintains reasonable + * throughput. + * + * Normally, iteration proceeds bin-by-bin traversing lists. + * However, if the table has been resized, then all future steps + * must traverse both the bin at the current index as well as at + * (index + baseSize); and so on for further resizings. To + * paranoically cope with potential sharing by users of iterators + * across threads, iteration terminates if a bounds checks fails + * for a table read. + * + * This class extends ForkJoinTask to streamline parallel + * iteration in bulk operations (see BulkTask). This adds only an + * int of space overhead, which is close enough to negligible in + * cases where it is not needed to not worry about it. Because + * ForkJoinTask is Serializable, but iterators need not be, we + * need to add warning suppressions. + */ + @SuppressWarnings("serial") static class Traverser { + final ConcurrentHashMapV8 map; + Node next; // the next entry to use + K nextKey; // cached key field of next + V nextVal; // cached val field of next + AtomicReferenceArray tab; // current table; updated if resized + int index; // index of bin to use next + int baseIndex; // current index of initial table + int baseLimit; // index bound for initial table + int baseSize; // initial table size + + /** Creates iterator for all entries in the table. */ + Traverser(ConcurrentHashMapV8 map) { + this.map = map; + } + + /** Creates iterator for split() methods */ + Traverser(Traverser it) { + ConcurrentHashMapV8 m; AtomicReferenceArray t; + if ((m = this.map = it.map) == null) + t = null; + else if ((t = it.tab) == null && // force parent tab initialization + (t = it.tab = m.table) != null) + it.baseLimit = it.baseSize = t.length(); + this.tab = t; + this.baseSize = it.baseSize; + it.baseLimit = this.index = this.baseIndex = + ((this.baseLimit = it.baseLimit) + it.baseIndex + 1) >>> 1; + } + + /** + * Advances next; returns nextVal or null if terminated. + * See above for explanation. + */ + final V advance() { + Node e = next; + V ev = null; + outer: do { + if (e != null) // advance past used/skipped node + e = e.next; + while (e == null) { // get to next non-null bin + ConcurrentHashMapV8 m; + AtomicReferenceArray t; int b, i, n; Object ek; // checks must use locals + if ((t = tab) != null) + n = t.length(); + else if ((m = map) != null && (t = tab = m.table) != null) + n = baseLimit = baseSize = t.length(); + else + break outer; + if ((b = baseIndex) >= baseLimit || + (i = index) < 0 || i >= n) + break outer; + if ((e = tabAt(t, i)) != null && e.hash == MOVED) { + if ((ek = e.key) instanceof TreeBin) + e = ((TreeBin)ek).first; + else { + tab = (AtomicReferenceArray)ek; + continue; // restarts due to null val + } + } // visit upper slots if present + index = (i += baseSize) < n ? i : (baseIndex = b + 1); + } + nextKey = (K) e.key; + } while ((ev = (V) e.val) == null); // skip deleted or special nodes + next = e; + return nextVal = ev; + } + + public final void remove() { + Object k = nextKey; + if (k == null && (advance() == null || (k = nextKey) == null)) + throw new IllegalStateException(); + map.internalReplace(k, null, null); + } + + public final boolean hasNext() { + return nextVal != null || advance() != null; + } + + public final boolean hasMoreElements() { return hasNext(); } + public final void setRawResult(Object x) { } + public R getRawResult() { return null; } + public boolean exec() { return true; } + } + + /* ---------------- Public operations -------------- */ + + /** + * Creates a new, empty map with the default initial table size (16). + */ + public ConcurrentHashMapV8() { + this.counter = new LongAdder(); + } + + /** + * Creates a new, empty map with an initial table size + * accommodating the specified number of elements without the need + * to dynamically resize. + * + * @param initialCapacity The implementation performs internal + * sizing to accommodate this many elements. + * @throws IllegalArgumentException if the initial capacity of + * elements is negative + */ + public ConcurrentHashMapV8(int initialCapacity) { + if (initialCapacity < 0) + throw new IllegalArgumentException(); + int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ? + MAXIMUM_CAPACITY : + tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1)); + this.counter = new LongAdder(); + this.sizeCtl = cap; + } + + /** + * Creates a new map with the same mappings as the given map. + * + * @param m the map + */ + public ConcurrentHashMapV8(Map m) { + this.counter = new LongAdder(); + this.sizeCtl = DEFAULT_CAPACITY; + internalPutAll(m); + } + + /** + * Creates a new, empty map with an initial table size based on + * the given number of elements ({@code initialCapacity}) and + * initial table density ({@code loadFactor}). + * + * @param initialCapacity the initial capacity. The implementation + * performs internal sizing to accommodate this many elements, + * given the specified load factor. + * @param loadFactor the load factor (table density) for + * establishing the initial table size + * @throws IllegalArgumentException if the initial capacity of + * elements is negative or the load factor is nonpositive + * + * @since 1.6 + */ + public ConcurrentHashMapV8(int initialCapacity, float loadFactor) { + this(initialCapacity, loadFactor, 1); + } + + /** + * Creates a new, empty map with an initial table size based on + * the given number of elements ({@code initialCapacity}), table + * density ({@code loadFactor}), and number of concurrently + * updating threads ({@code concurrencyLevel}). + * + * @param initialCapacity the initial capacity. The implementation + * performs internal sizing to accommodate this many elements, + * given the specified load factor. + * @param loadFactor the load factor (table density) for + * establishing the initial table size + * @param concurrencyLevel the estimated number of concurrently + * updating threads. The implementation may use this value as + * a sizing hint. + * @throws IllegalArgumentException if the initial capacity is + * negative or the load factor or concurrencyLevel are + * nonpositive + */ + public ConcurrentHashMapV8(int initialCapacity, + float loadFactor, int concurrencyLevel) { + if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0) + throw new IllegalArgumentException(); + if (initialCapacity < concurrencyLevel) // Use at least as many bins + initialCapacity = concurrencyLevel; // as estimated threads + long size = (long)(1.0 + (long)initialCapacity / loadFactor); + int cap = (size >= (long)MAXIMUM_CAPACITY) ? + MAXIMUM_CAPACITY : tableSizeFor((int)size); + this.counter = new LongAdder(); + this.sizeCtl = cap; + } + + /** + * Creates a new {@link Set} backed by a ConcurrentHashMapV8 + * from the given type to {@code Boolean.TRUE}. + * + * @return the new set + */ + public static KeySetView newKeySet() { + return new KeySetView(new ConcurrentHashMapV8(), + Boolean.TRUE); + } + + /** + * Creates a new {@link Set} backed by a ConcurrentHashMapV8 + * from the given type to {@code Boolean.TRUE}. + * + * @param initialCapacity The implementation performs internal + * sizing to accommodate this many elements. + * @throws IllegalArgumentException if the initial capacity of + * elements is negative + * @return the new set + */ + public static KeySetView newKeySet(int initialCapacity) { + return new KeySetView(new ConcurrentHashMapV8(initialCapacity), + Boolean.TRUE); + } + + /** + * {@inheritDoc} + */ + public boolean isEmpty() { + return counter.sum() <= 0L; // ignore transient negative values + } + + /** + * {@inheritDoc} + */ + public int size() { + long n = counter.sum(); + return ((n < 0L) ? 0 : + (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE : + (int)n); + } + + /** + * Returns the number of mappings. This method should be used + * instead of {@link #size} because a ConcurrentHashMapV8 may + * contain more mappings than can be represented as an int. The + * value returned is a snapshot; the actual count may differ if + * there are ongoing concurrent insertions or removals. + * + * @return the number of mappings + */ + public long mappingCount() { + long n = counter.sum(); + return (n < 0L) ? 0L : n; // ignore transient negative values + } + + /** + * Returns the value to which the specified key is mapped, + * or {@code null} if this map contains no mapping for the key. + * + *

More formally, if this map contains a mapping from a key + * {@code k} to a value {@code v} such that {@code key.equals(k)}, + * then this method returns {@code v}; otherwise it returns + * {@code null}. (There can be at most one such mapping.) + * + * @throws NullPointerException if the specified key is null + */ + @SuppressWarnings("unchecked") public V get(Object key) { + if (key == null) + throw new NullPointerException(); + return (V)internalGet(key); + } + + /** + * Returns the value to which the specified key is mapped, + * or the given defaultValue if this map contains no mapping for the key. + * + * @param key the key + * @param defaultValue the value to return if this map contains + * no mapping for the given key + * @return the mapping for the key, if present; else the defaultValue + * @throws NullPointerException if the specified key is null + */ + @SuppressWarnings("unchecked") public V getValueOrDefault(Object key, V defaultValue) { + if (key == null) + throw new NullPointerException(); + V v = (V) internalGet(key); + return v == null ? defaultValue : v; + } + + /** + * Tests if the specified object is a key in this table. + * + * @param key possible key + * @return {@code true} if and only if the specified object + * is a key in this table, as determined by the + * {@code equals} method; {@code false} otherwise + * @throws NullPointerException if the specified key is null + */ + public boolean containsKey(Object key) { + if (key == null) + throw new NullPointerException(); + return internalGet(key) != null; + } + + /** + * Returns {@code true} if this map maps one or more keys to the + * specified value. Note: This method may require a full traversal + * of the map, and is much slower than method {@code containsKey}. + * + * @param value value whose presence in this map is to be tested + * @return {@code true} if this map maps one or more keys to the + * specified value + * @throws NullPointerException if the specified value is null + */ + public boolean containsValue(Object value) { + if (value == null) + throw new NullPointerException(); + Object v; + Traverser it = new Traverser(this); + while ((v = it.advance()) != null) { + if (v == value || value.equals(v)) + return true; + } + return false; + } + + public K findKey(Object value) { + if (value == null) + throw new NullPointerException(); + Object v; + Traverser it = new Traverser(this); + while ((v = it.advance()) != null) { + if (v == value || value.equals(v)) + return it.nextKey; + } + return null; + } + + /** + * Legacy method testing if some key maps into the specified value + * in this table. This method is identical in functionality to + * {@link #containsValue}, and exists solely to ensure + * full compatibility with class {@link java.util.Hashtable}, + * which supported this method prior to introduction of the + * Java Collections framework. + * + * @param value a value to search for + * @return {@code true} if and only if some key maps to the + * {@code value} argument in this table as + * determined by the {@code equals} method; + * {@code false} otherwise + * @throws NullPointerException if the specified value is null + */ + public boolean contains(Object value) { + return containsValue(value); + } + + /** + * Maps the specified key to the specified value in this table. + * Neither the key nor the value can be null. + * + *

The value can be retrieved by calling the {@code get} method + * with a key that is equal to the original key. + * + * @param key key with which the specified value is to be associated + * @param value value to be associated with the specified key + * @return the previous value associated with {@code key}, or + * {@code null} if there was no mapping for {@code key} + * @throws NullPointerException if the specified key or value is null + */ + @SuppressWarnings("unchecked") public V put(K key, V value) { + if (key == null || value == null) + throw new NullPointerException(); + return (V)internalPut(key, value); + } + + /** + * {@inheritDoc} + * + * @return the previous value associated with the specified key, + * or {@code null} if there was no mapping for the key + * @throws NullPointerException if the specified key or value is null + */ + @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) { + if (key == null || value == null) + throw new NullPointerException(); + return (V)internalPutIfAbsent(key, value); + } + + /** + * Copies all of the mappings from the specified map to this one. + * These mappings replace any mappings that this map had for any of the + * keys currently in the specified map. + * + * @param m mappings to be stored in this map + */ + public void putAll(Map m) { + internalPutAll(m); + } + + /** + * If the specified key is not already associated with a value, + * computes its value using the given mappingFunction and enters + * it into the map unless null. This is equivalent to + *

 {@code
+     * if (map.containsKey(key))
+     *   return map.get(key);
+     * value = mappingFunction.apply(key);
+     * if (value != null)
+     *   map.put(key, value);
+     * return value;}
+ * + * except that the action is performed atomically. If the + * function returns {@code null} no mapping is recorded. If the + * function itself throws an (unchecked) exception, the exception + * is rethrown to its caller, and no mapping is recorded. Some + * attempted update operations on this map by other threads may be + * blocked while computation is in progress, so the computation + * should be short and simple, and must not attempt to update any + * other mappings of this Map. The most appropriate usage is to + * construct a new object serving as an initial mapped value, or + * memoized result, as in: + * + *
 {@code
+     * map.computeIfAbsent(key, new Fun() {
+     *   public V map(K k) { return new Value(f(k)); }});}
+ * + * @param key key with which the specified value is to be associated + * @param mappingFunction the function to compute a value + * @return the current (existing or computed) value associated with + * the specified key, or null if the computed value is null + * @throws NullPointerException if the specified key or mappingFunction + * is null + * @throws IllegalStateException if the computation detectably + * attempts a recursive update to this map that would + * otherwise never complete + * @throws RuntimeException or Error if the mappingFunction does so, + * in which case the mapping is left unestablished + */ + @SuppressWarnings("unchecked") public V computeIfAbsent + (K key, Fun mappingFunction) { + if (key == null || mappingFunction == null) + throw new NullPointerException(); + return (V)internalComputeIfAbsent(key, mappingFunction); + } + + /** + * If the given key is present, computes a new mapping value given a key and + * its current mapped value. This is equivalent to + *
 {@code
+     *   if (map.containsKey(key)) {
+     *     value = remappingFunction.apply(key, map.get(key));
+     *     if (value != null)
+     *       map.put(key, value);
+     *     else
+     *       map.remove(key);
+     *   }
+     * }
+ * + * except that the action is performed atomically. If the + * function returns {@code null}, the mapping is removed. If the + * function itself throws an (unchecked) exception, the exception + * is rethrown to its caller, and the current mapping is left + * unchanged. Some attempted update operations on this map by + * other threads may be blocked while computation is in progress, + * so the computation should be short and simple, and must not + * attempt to update any other mappings of this Map. For example, + * to either create or append new messages to a value mapping: + * + * @param key key with which the specified value is to be associated + * @param remappingFunction the function to compute a value + * @return the new value associated with the specified key, or null if none + * @throws NullPointerException if the specified key or remappingFunction + * is null + * @throws IllegalStateException if the computation detectably + * attempts a recursive update to this map that would + * otherwise never complete + * @throws RuntimeException or Error if the remappingFunction does so, + * in which case the mapping is unchanged + */ + @SuppressWarnings("unchecked") public V computeIfPresent + (K key, BiFun remappingFunction) { + if (key == null || remappingFunction == null) + throw new NullPointerException(); + return (V)internalCompute(key, true, remappingFunction); + } + + /** + * Computes a new mapping value given a key and + * its current mapped value (or {@code null} if there is no current + * mapping). This is equivalent to + *
 {@code
+     *   value = remappingFunction.apply(key, map.get(key));
+     *   if (value != null)
+     *     map.put(key, value);
+     *   else
+     *     map.remove(key);
+     * }
+ * + * except that the action is performed atomically. If the + * function returns {@code null}, the mapping is removed. If the + * function itself throws an (unchecked) exception, the exception + * is rethrown to its caller, and the current mapping is left + * unchanged. Some attempted update operations on this map by + * other threads may be blocked while computation is in progress, + * so the computation should be short and simple, and must not + * attempt to update any other mappings of this Map. For example, + * to either create or append new messages to a value mapping: + * + *
 {@code
+     * Map map = ...;
+     * final String msg = ...;
+     * map.compute(key, new BiFun() {
+     *   public String apply(Key k, String v) {
+     *    return (v == null) ? msg : v + msg;});}}
+ * + * @param key key with which the specified value is to be associated + * @param remappingFunction the function to compute a value + * @return the new value associated with the specified key, or null if none + * @throws NullPointerException if the specified key or remappingFunction + * is null + * @throws IllegalStateException if the computation detectably + * attempts a recursive update to this map that would + * otherwise never complete + * @throws RuntimeException or Error if the remappingFunction does so, + * in which case the mapping is unchanged + */ + @SuppressWarnings("unchecked") public V compute + (K key, BiFun remappingFunction) { + if (key == null || remappingFunction == null) + throw new NullPointerException(); + return (V)internalCompute(key, false, remappingFunction); + } + + /** + * If the specified key is not already associated + * with a value, associate it with the given value. + * Otherwise, replace the value with the results of + * the given remapping function. This is equivalent to: + *
 {@code
+     *   if (!map.containsKey(key))
+     *     map.put(value);
+     *   else {
+     *     newValue = remappingFunction.apply(map.get(key), value);
+     *     if (value != null)
+     *       map.put(key, value);
+     *     else
+     *       map.remove(key);
+     *   }
+     * }
+ * except that the action is performed atomically. If the + * function returns {@code null}, the mapping is removed. If the + * function itself throws an (unchecked) exception, the exception + * is rethrown to its caller, and the current mapping is left + * unchanged. Some attempted update operations on this map by + * other threads may be blocked while computation is in progress, + * so the computation should be short and simple, and must not + * attempt to update any other mappings of this Map. + */ + @SuppressWarnings("unchecked") public V merge + (K key, V value, BiFun remappingFunction) { + if (key == null || value == null || remappingFunction == null) + throw new NullPointerException(); + return (V)internalMerge(key, value, remappingFunction); + } + + /** + * Removes the key (and its corresponding value) from this map. + * This method does nothing if the key is not in the map. + * + * @param key the key that needs to be removed + * @return the previous value associated with {@code key}, or + * {@code null} if there was no mapping for {@code key} + * @throws NullPointerException if the specified key is null + */ + @SuppressWarnings("unchecked") public V remove(Object key) { + if (key == null) + throw new NullPointerException(); + return (V)internalReplace(key, null, null); + } + + /** + * {@inheritDoc} + * + * @throws NullPointerException if the specified key is null + */ + public boolean remove(Object key, Object value) { + if (key == null) + throw new NullPointerException(); + if (value == null) + return false; + return internalReplace(key, null, value) != null; + } + + /** + * {@inheritDoc} + * + * @throws NullPointerException if any of the arguments are null + */ + public boolean replace(K key, V oldValue, V newValue) { + if (key == null || oldValue == null || newValue == null) + throw new NullPointerException(); + return internalReplace(key, newValue, oldValue) != null; + } + + /** + * {@inheritDoc} + * + * @return the previous value associated with the specified key, + * or {@code null} if there was no mapping for the key + * @throws NullPointerException if the specified key or value is null + */ + @SuppressWarnings("unchecked") public V replace(K key, V value) { + if (key == null || value == null) + throw new NullPointerException(); + return (V)internalReplace(key, value, null); + } + + /** + * Removes all of the mappings from this map. + */ + public void clear() { + internalClear(); + } + + /** + * Returns a {@link Set} view of the keys contained in this map. + * The set is backed by the map, so changes to the map are + * reflected in the set, and vice-versa. + * + * @return the set view + */ + public KeySetView keySet() { + KeySetView ks = keySet; + return (ks != null) ? ks : (keySet = new KeySetView(this, null)); + } + + /** + * Returns a {@link Set} view of the keys in this map, using the + * given common mapped value for any additions (i.e., {@link + * Collection#add} and {@link Collection#addAll}). This is of + * course only appropriate if it is acceptable to use the same + * value for all additions from this view. + * + * @param mappedValue the mapped value to use for any + * additions. + * @return the set view + * @throws NullPointerException if the mappedValue is null + */ + public KeySetView keySet(V mappedValue) { + if (mappedValue == null) + throw new NullPointerException(); + return new KeySetView(this, mappedValue); + } + + /** + * Returns a {@link Collection} view of the values contained in this map. + * The collection is backed by the map, so changes to the map are + * reflected in the collection, and vice-versa. + */ + public ValuesView values() { + ValuesView vs = values; + return (vs != null) ? vs : (values = new ValuesView(this)); + } + + /** + * Returns a {@link Set} view of the mappings contained in this map. + * The set is backed by the map, so changes to the map are + * reflected in the set, and vice-versa. The set supports element + * removal, which removes the corresponding mapping from the map, + * via the {@code Iterator.remove}, {@code Set.remove}, + * {@code removeAll}, {@code retainAll}, and {@code clear} + * operations. It does not support the {@code add} or + * {@code addAll} operations. + * + *

The view's {@code iterator} is a "weakly consistent" iterator + * that will never throw {@link ConcurrentModificationException}, + * and guarantees to traverse elements as they existed upon + * construction of the iterator, and may (but is not guaranteed to) + * reflect any modifications subsequent to construction. + */ + public Set> entrySet() { + EntrySetView es = entrySet; + return (es != null) ? es : (entrySet = new EntrySetView(this)); + } + + /** + * Returns an enumeration of the keys in this table. + * + * @return an enumeration of the keys in this table + * @see #keySet() + */ + public Enumeration keys() { + return new KeyIterator(this); + } + + /** + * Returns an enumeration of the values in this table. + * + * @return an enumeration of the values in this table + * @see #values() + */ + public Enumeration elements() { + return new ValueIterator(this); + } + + /** + * Returns a partitionable iterator of the keys in this map. + * + * @return a partitionable iterator of the keys in this map + */ + public Spliterator keySpliterator() { + return new KeyIterator(this); + } + + /** + * Returns a partitionable iterator of the values in this map. + * + * @return a partitionable iterator of the values in this map + */ + public Spliterator valueSpliterator() { + return new ValueIterator(this); + } + + /** + * Returns a partitionable iterator of the entries in this map. + * + * @return a partitionable iterator of the entries in this map + */ + public Spliterator> entrySpliterator() { + return new EntryIterator(this); + } + + /** + * Returns the hash code value for this {@link Map}, i.e., + * the sum of, for each key-value pair in the map, + * {@code key.hashCode() ^ value.hashCode()}. + * + * @return the hash code value for this map + */ + public int hashCode() { + int h = 0; + Traverser it = new Traverser(this); + Object v; + while ((v = it.advance()) != null) { + h += it.nextKey.hashCode() ^ v.hashCode(); + } + return h; + } + + /** + * Returns a string representation of this map. The string + * representation consists of a list of key-value mappings (in no + * particular order) enclosed in braces ("{@code {}}"). Adjacent + * mappings are separated by the characters {@code ", "} (comma + * and space). Each key-value mapping is rendered as the key + * followed by an equals sign ("{@code =}") followed by the + * associated value. + * + * @return a string representation of this map + */ + public String toString() { + Traverser it = new Traverser(this); + StringBuilder sb = new StringBuilder(); + sb.append('{'); + Object v; + if ((v = it.advance()) != null) { + for (;;) { + Object k = it.nextKey; + sb.append(k == this ? "(this Map)" : k); + sb.append('='); + sb.append(v == this ? "(this Map)" : v); + if ((v = it.advance()) == null) + break; + sb.append(',').append(' '); + } + } + return sb.append('}').toString(); + } + + /** + * Compares the specified object with this map for equality. + * Returns {@code true} if the given object is a map with the same + * mappings as this map. This operation may return misleading + * results if either map is concurrently modified during execution + * of this method. + * + * @param o object to be compared for equality with this map + * @return {@code true} if the specified object is equal to this map + */ + public boolean equals(Object o) { + if (o != this) { + if (!(o instanceof Map)) + return false; + Map m = (Map) o; + Traverser it = new Traverser(this); + Object val; + while ((val = it.advance()) != null) { + Object v = m.get(it.nextKey); + if (v == null || (v != val && !v.equals(val))) + return false; + } + for (Map.Entry e : m.entrySet()) { + Object mk, mv, v; + if ((mk = e.getKey()) == null || + (mv = e.getValue()) == null || + (v = internalGet(mk)) == null || + (mv != v && !mv.equals(v))) + return false; + } + } + return true; + } + + /* ----------------Iterators -------------- */ + + @SuppressWarnings("serial") static final class KeyIterator extends Traverser + implements Spliterator, Enumeration { + KeyIterator(ConcurrentHashMapV8 map) { super(map); } + KeyIterator(Traverser it) { + super(it); + } + public KeyIterator split() { + if (nextKey != null) + throw new IllegalStateException(); + return new KeyIterator(this); + } + @SuppressWarnings("unchecked") public final K next() { + if (nextVal == null && advance() == null) + throw new NoSuchElementException(); + Object k = nextKey; + nextVal = null; + return (K) k; + } + + public final K nextElement() { return next(); } + } + + @SuppressWarnings("serial") static final class ValueIterator extends Traverser + implements Spliterator, Enumeration { + ValueIterator(ConcurrentHashMapV8 map) { super(map); } + ValueIterator(Traverser it) { + super(it); + } + public ValueIterator split() { + if (nextKey != null) + throw new IllegalStateException(); + return new ValueIterator(this); + } + + @SuppressWarnings("unchecked") public final V next() { + Object v; + if ((v = nextVal) == null && (v = advance()) == null) + throw new NoSuchElementException(); + nextVal = null; + return (V) v; + } + + public final V nextElement() { return next(); } + } + + @SuppressWarnings("serial") static final class EntryIterator extends Traverser + implements Spliterator> { + EntryIterator(ConcurrentHashMapV8 map) { super(map); } + EntryIterator(Traverser it) { + super(it); + } + public EntryIterator split() { + if (nextKey != null) + throw new IllegalStateException(); + return new EntryIterator(this); + } + + @SuppressWarnings("unchecked") public final Map.Entry next() { + Object v; + if ((v = nextVal) == null && (v = advance()) == null) + throw new NoSuchElementException(); + Object k = nextKey; + nextVal = null; + return new MapEntry((K)k, (V)v, map); + } + } + + /** + * Exported Entry for iterators + */ + static final class MapEntry implements Map.Entry { + final K key; // non-null + V val; // non-null + final ConcurrentHashMapV8 map; + MapEntry(K key, V val, ConcurrentHashMapV8 map) { + this.key = key; + this.val = val; + this.map = map; + } + public final K getKey() { return key; } + public final V getValue() { return val; } + public final int hashCode() { return key.hashCode() ^ val.hashCode(); } + public final String toString(){ return key + "=" + val; } + + public final boolean equals(Object o) { + Object k, v; Map.Entry e; + return ((o instanceof Map.Entry) && + (k = (e = (Map.Entry)o).getKey()) != null && + (v = e.getValue()) != null && + (k == key || k.equals(key)) && + (v == val || v.equals(val))); + } + + /** + * Sets our entry's value and writes through to the map. The + * value to return is somewhat arbitrary here. Since we do not + * necessarily track asynchronous changes, the most recent + * "previous" value could be different from what we return (or + * could even have been removed in which case the put will + * re-establish). We do not and cannot guarantee more. + */ + public final V setValue(V value) { + if (value == null) throw new NullPointerException(); + V v = val; + val = value; + map.put(key, value); + return v; + } + } + + /* ---------------- Serialization Support -------------- */ + + /** + * Stripped-down version of helper class used in previous version, + * declared for the sake of serialization compatibility + */ + static class Segment implements Serializable { + private static final long serialVersionUID = 2249069246763182397L; + final float loadFactor; + Segment(float lf) { this.loadFactor = lf; } + } + + /** + * Saves the state of the {@code ConcurrentHashMapV8} instance to a + * stream (i.e., serializes it). + * @param s the stream + * @serialData + * the key (Object) and value (Object) + * for each key-value mapping, followed by a null pair. + * The key-value mappings are emitted in no particular order. + */ + @SuppressWarnings("unchecked") private void writeObject(java.io.ObjectOutputStream s) + throws java.io.IOException { + if (segments == null) { // for serialization compatibility + segments = (Segment[]) + new Segment[DEFAULT_CONCURRENCY_LEVEL]; + for (int i = 0; i < segments.length; ++i) + segments[i] = new Segment(LOAD_FACTOR); + } + s.defaultWriteObject(); + Traverser it = new Traverser(this); + Object v; + while ((v = it.advance()) != null) { + s.writeObject(it.nextKey); + s.writeObject(v); + } + s.writeObject(null); + s.writeObject(null); + segments = null; // throw away + } + + /** + * Reconstitutes the instance from a stream (that is, deserializes it). + * @param s the stream + */ + @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s) + throws java.io.IOException, ClassNotFoundException { + s.defaultReadObject(); + this.segments = null; // unneeded + // initialize transient final field + this.counter = new LongAdder(); + + // Create all nodes, then place in table once size is known + long size = 0L; + Node p = null; + for (;;) { + K k = (K) s.readObject(); + V v = (V) s.readObject(); + if (k != null && v != null) { + int h = spread(k.hashCode()); + p = new Node(h, k, v, p); + ++size; + } + else + break; + } + if (p != null) { + boolean init = false; + int n; + if (size >= (long)(MAXIMUM_CAPACITY >>> 1)) + n = MAXIMUM_CAPACITY; + else { + int sz = (int)size; + n = tableSizeFor(sz + (sz >>> 1) + 1); + } + int sc = sizeCtl; + boolean collide = false; + if (n > sc && + SIZE_CTRL_UPDATER.compareAndSet(this, sc, -1)) { + try { + if (table == null) { + init = true; + AtomicReferenceArray tab = new AtomicReferenceArray(n); + int mask = n - 1; + while (p != null) { + int j = p.hash & mask; + Node next = p.next; + Node q = p.next = tabAt(tab, j); + setTabAt(tab, j, p); + if (!collide && q != null && q.hash == p.hash) + collide = true; + p = next; + } + table = tab; + counter.add(size); + sc = n - (n >>> 2); + } + } finally { + sizeCtl = sc; + } + if (collide) { // rescan and convert to TreeBins + AtomicReferenceArray tab = table; + for (int i = 0; i < tab.length(); ++i) { + int c = 0; + for (Node e = tabAt(tab, i); e != null; e = e.next) { + if (++c > TREE_THRESHOLD && + (e.key instanceof Comparable)) { + replaceWithTreeBin(tab, i, e.key); + break; + } + } + } + } + } + if (!init) { // Can only happen if unsafely published. + while (p != null) { + internalPut(p.key, p.val); + p = p.next; + } + } + } + } + + + // ------------------------------------------------------- + + // Sams + /** Interface describing a void action of one argument */ + public interface Action { void apply(A a); } + /** Interface describing a void action of two arguments */ + public interface BiAction { void apply(A a, B b); } + /** Interface describing a function of one argument */ + public interface Generator { T apply(); } + /** Interface describing a function mapping its argument to a double */ + public interface ObjectToDouble { double apply(A a); } + /** Interface describing a function mapping its argument to a long */ + public interface ObjectToLong { long apply(A a); } + /** Interface describing a function mapping its argument to an int */ + public interface ObjectToInt {int apply(A a); } + /** Interface describing a function mapping two arguments to a double */ + public interface ObjectByObjectToDouble { double apply(A a, B b); } + /** Interface describing a function mapping two arguments to a long */ + public interface ObjectByObjectToLong { long apply(A a, B b); } + /** Interface describing a function mapping two arguments to an int */ + public interface ObjectByObjectToInt {int apply(A a, B b); } + /** Interface describing a function mapping a double to a double */ + public interface DoubleToDouble { double apply(double a); } + /** Interface describing a function mapping a long to a long */ + public interface LongToLong { long apply(long a); } + /** Interface describing a function mapping an int to an int */ + public interface IntToInt { int apply(int a); } + /** Interface describing a function mapping two doubles to a double */ + public interface DoubleByDoubleToDouble { double apply(double a, double b); } + /** Interface describing a function mapping two longs to a long */ + public interface LongByLongToLong { long apply(long a, long b); } + /** Interface describing a function mapping two ints to an int */ + public interface IntByIntToInt { int apply(int a, int b); } + + + /* ----------------Views -------------- */ + + /** + * Base class for views. + */ + static abstract class CHMView { + final ConcurrentHashMapV8 map; + CHMView(ConcurrentHashMapV8 map) { this.map = map; } + + /** + * Returns the map backing this view. + * + * @return the map backing this view + */ + public ConcurrentHashMapV8 getMap() { return map; } + + public final int size() { return map.size(); } + public final boolean isEmpty() { return map.isEmpty(); } + public final void clear() { map.clear(); } + + // implementations below rely on concrete classes supplying these + abstract public Iterator iterator(); + abstract public boolean contains(Object o); + abstract public boolean remove(Object o); + + private static final String oomeMsg = "Required array size too large"; + + public final Object[] toArray() { + long sz = map.mappingCount(); + if (sz > (long)(MAX_ARRAY_SIZE)) + throw new OutOfMemoryError(oomeMsg); + int n = (int)sz; + Object[] r = new Object[n]; + int i = 0; + Iterator it = iterator(); + while (it.hasNext()) { + if (i == n) { + if (n >= MAX_ARRAY_SIZE) + throw new OutOfMemoryError(oomeMsg); + if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1) + n = MAX_ARRAY_SIZE; + else + n += (n >>> 1) + 1; + r = Arrays.copyOf(r, n); + } + r[i++] = it.next(); + } + return (i == n) ? r : Arrays.copyOf(r, i); + } + + @SuppressWarnings("unchecked") public final T[] toArray(T[] a) { + long sz = map.mappingCount(); + if (sz > (long)(MAX_ARRAY_SIZE)) + throw new OutOfMemoryError(oomeMsg); + int m = (int)sz; + T[] r = (a.length >= m) ? a : + (T[])java.lang.reflect.Array + .newInstance(a.getClass().getComponentType(), m); + int n = r.length; + int i = 0; + Iterator it = iterator(); + while (it.hasNext()) { + if (i == n) { + if (n >= MAX_ARRAY_SIZE) + throw new OutOfMemoryError(oomeMsg); + if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1) + n = MAX_ARRAY_SIZE; + else + n += (n >>> 1) + 1; + r = Arrays.copyOf(r, n); + } + r[i++] = (T)it.next(); + } + if (a == r && i < n) { + r[i] = null; // null-terminate + return r; + } + return (i == n) ? r : Arrays.copyOf(r, i); + } + + public final int hashCode() { + int h = 0; + for (Iterator it = iterator(); it.hasNext();) + h += it.next().hashCode(); + return h; + } + + public final String toString() { + StringBuilder sb = new StringBuilder(); + sb.append('['); + Iterator it = iterator(); + if (it.hasNext()) { + for (;;) { + Object e = it.next(); + sb.append(e == this ? "(this Collection)" : e); + if (!it.hasNext()) + break; + sb.append(',').append(' '); + } + } + return sb.append(']').toString(); + } + + public final boolean containsAll(Collection c) { + if (c != this) { + for (Iterator it = c.iterator(); it.hasNext();) { + Object e = it.next(); + if (e == null || !contains(e)) + return false; + } + } + return true; + } + + public final boolean removeAll(Collection c) { + boolean modified = false; + for (Iterator it = iterator(); it.hasNext();) { + if (c.contains(it.next())) { + it.remove(); + modified = true; + } + } + return modified; + } + + public final boolean retainAll(Collection c) { + boolean modified = false; + for (Iterator it = iterator(); it.hasNext();) { + if (!c.contains(it.next())) { + it.remove(); + modified = true; + } + } + return modified; + } + + } + + /** + * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in + * which additions may optionally be enabled by mapping to a + * common value. This class cannot be directly instantiated. See + * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()}, + * {@link #newKeySet(int)}. + */ + public static class KeySetView extends CHMView implements Set, java.io.Serializable { + private static final long serialVersionUID = 7249069246763182397L; + private final V value; + KeySetView(ConcurrentHashMapV8 map, V value) { // non-public + super(map); + this.value = value; + } + + /** + * Returns the default mapped value for additions, + * or {@code null} if additions are not supported. + * + * @return the default mapped value for additions, or {@code null} + * if not supported. + */ + public V getMappedValue() { return value; } + + // implement Set API + + public boolean contains(Object o) { return map.containsKey(o); } + public boolean remove(Object o) { return map.remove(o) != null; } + + /** + * Returns a "weakly consistent" iterator that will never + * throw {@link ConcurrentModificationException}, and + * guarantees to traverse elements as they existed upon + * construction of the iterator, and may (but is not + * guaranteed to) reflect any modifications subsequent to + * construction. + * + * @return an iterator over the keys of this map + */ + public Iterator iterator() { return new KeyIterator(map); } + public boolean add(K e) { + V v; + if ((v = value) == null) + throw new UnsupportedOperationException(); + if (e == null) + throw new NullPointerException(); + return map.internalPutIfAbsent(e, v) == null; + } + public boolean addAll(Collection c) { + boolean added = false; + V v; + if ((v = value) == null) + throw new UnsupportedOperationException(); + for (K e : c) { + if (e == null) + throw new NullPointerException(); + if (map.internalPutIfAbsent(e, v) == null) + added = true; + } + return added; + } + public boolean equals(Object o) { + Set c; + return ((o instanceof Set) && + ((c = (Set)o) == this || + (containsAll(c) && c.containsAll(this)))); + } + } + + /** + * A view of a ConcurrentHashMapV8 as a {@link Collection} of + * values, in which additions are disabled. This class cannot be + * directly instantiated. See {@link #values}, + * + *

The view's {@code iterator} is a "weakly consistent" iterator + * that will never throw {@link ConcurrentModificationException}, + * and guarantees to traverse elements as they existed upon + * construction of the iterator, and may (but is not guaranteed to) + * reflect any modifications subsequent to construction. + */ + public static final class ValuesView extends CHMView + implements Collection { + ValuesView(ConcurrentHashMapV8 map) { super(map); } + public final boolean contains(Object o) { return map.containsValue(o); } + public final boolean remove(Object o) { + if (o != null) { + Iterator it = new ValueIterator(map); + while (it.hasNext()) { + if (o.equals(it.next())) { + it.remove(); + return true; + } + } + } + return false; + } + + /** + * Returns a "weakly consistent" iterator that will never + * throw {@link ConcurrentModificationException}, and + * guarantees to traverse elements as they existed upon + * construction of the iterator, and may (but is not + * guaranteed to) reflect any modifications subsequent to + * construction. + * + * @return an iterator over the values of this map + */ + public final Iterator iterator() { + return new ValueIterator(map); + } + public final boolean add(V e) { + throw new UnsupportedOperationException(); + } + public final boolean addAll(Collection c) { + throw new UnsupportedOperationException(); + } + } + + /** + * A view of a ConcurrentHashMapV8 as a {@link Set} of (key, value) + * entries. This class cannot be directly instantiated. See + * {@link #entrySet}. + */ + public static final class EntrySetView extends CHMView + implements Set> { + EntrySetView(ConcurrentHashMapV8 map) { super(map); } + public final boolean contains(Object o) { + Object k, v, r; Map.Entry e; + return ((o instanceof Map.Entry) && + (k = (e = (Map.Entry)o).getKey()) != null && + (r = map.get(k)) != null && + (v = e.getValue()) != null && + (v == r || v.equals(r))); + } + public final boolean remove(Object o) { + Object k, v; Map.Entry e; + return ((o instanceof Map.Entry) && + (k = (e = (Map.Entry)o).getKey()) != null && + (v = e.getValue()) != null && + map.remove(k, v)); + } + + /** + * Returns a "weakly consistent" iterator that will never + * throw {@link ConcurrentModificationException}, and + * guarantees to traverse elements as they existed upon + * construction of the iterator, and may (but is not + * guaranteed to) reflect any modifications subsequent to + * construction. + * + * @return an iterator over the entries of this map + */ + public final Iterator> iterator() { + return new EntryIterator(map); + } + + public final boolean add(Entry e) { + K key = e.getKey(); + V value = e.getValue(); + if (key == null || value == null) + throw new NullPointerException(); + return map.internalPut(key, value) == null; + } + public final boolean addAll(Collection> c) { + boolean added = false; + for (Entry e : c) { + if (add(e)) + added = true; + } + return added; + } + public boolean equals(Object o) { + Set c; + return ((o instanceof Set) && + ((c = (Set)o) == this || + (containsAll(c) && c.containsAll(this)))); + } + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/LongAdder.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/LongAdder.java new file mode 100644 index 0000000..ecf552a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/LongAdder.java @@ -0,0 +1,204 @@ +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +// This is based on 1.9 version. + +package com.concurrent_ruby.ext.jsr166e.nounsafe; + +import java.util.concurrent.atomic.AtomicLong; +import java.io.IOException; +import java.io.Serializable; +import java.io.ObjectInputStream; + +/** + * One or more variables that together maintain an initially zero + * {@code long} sum. When updates (method {@link #add}) are contended + * across threads, the set of variables may grow dynamically to reduce + * contention. Method {@link #sum} (or, equivalently, {@link + * #longValue}) returns the current total combined across the + * variables maintaining the sum. + * + *

This class is usually preferable to {@link AtomicLong} when + * multiple threads update a common sum that is used for purposes such + * as collecting statistics, not for fine-grained synchronization + * control. Under low update contention, the two classes have similar + * characteristics. But under high contention, expected throughput of + * this class is significantly higher, at the expense of higher space + * consumption. + * + *

This class extends {@link Number}, but does not define + * methods such as {@code hashCode} and {@code compareTo} because + * instances are expected to be mutated, and so are not useful as + * collection keys. + * + *

jsr166e note: This class is targeted to be placed in + * java.util.concurrent.atomic. + * + * @since 1.8 + * @author Doug Lea + */ +public class LongAdder extends Striped64 implements Serializable { + private static final long serialVersionUID = 7249069246863182397L; + + /** + * Version of plus for use in retryUpdate + */ + final long fn(long v, long x) { return v + x; } + + /** + * Creates a new adder with initial sum of zero. + */ + public LongAdder() { + } + + /** + * Adds the given value. + * + * @param x the value to add + */ + public void add(long x) { + Cell[] as; long b, v; HashCode hc; Cell a; int n; + if ((as = cells) != null || !casBase(b = base, b + x)) { + boolean uncontended = true; + int h = (hc = threadHashCode.get()).code; + if (as == null || (n = as.length) < 1 || + (a = as[(n - 1) & h]) == null || + !(uncontended = a.cas(v = a.value, v + x))) + retryUpdate(x, hc, uncontended); + } + } + + /** + * Equivalent to {@code add(1)}. + */ + public void increment() { + add(1L); + } + + /** + * Equivalent to {@code add(-1)}. + */ + public void decrement() { + add(-1L); + } + + /** + * Returns the current sum. The returned value is NOT an + * atomic snapshot: Invocation in the absence of concurrent + * updates returns an accurate result, but concurrent updates that + * occur while the sum is being calculated might not be + * incorporated. + * + * @return the sum + */ + public long sum() { + long sum = base; + Cell[] as = cells; + if (as != null) { + int n = as.length; + for (int i = 0; i < n; ++i) { + Cell a = as[i]; + if (a != null) + sum += a.value; + } + } + return sum; + } + + /** + * Resets variables maintaining the sum to zero. This method may + * be a useful alternative to creating a new adder, but is only + * effective if there are no concurrent updates. Because this + * method is intrinsically racy, it should only be used when it is + * known that no threads are concurrently updating. + */ + public void reset() { + internalReset(0L); + } + + /** + * Equivalent in effect to {@link #sum} followed by {@link + * #reset}. This method may apply for example during quiescent + * points between multithreaded computations. If there are + * updates concurrent with this method, the returned value is + * not guaranteed to be the final value occurring before + * the reset. + * + * @return the sum + */ + public long sumThenReset() { + long sum = base; + Cell[] as = cells; + base = 0L; + if (as != null) { + int n = as.length; + for (int i = 0; i < n; ++i) { + Cell a = as[i]; + if (a != null) { + sum += a.value; + a.value = 0L; + } + } + } + return sum; + } + + /** + * Returns the String representation of the {@link #sum}. + * @return the String representation of the {@link #sum} + */ + public String toString() { + return Long.toString(sum()); + } + + /** + * Equivalent to {@link #sum}. + * + * @return the sum + */ + public long longValue() { + return sum(); + } + + /** + * Returns the {@link #sum} as an {@code int} after a narrowing + * primitive conversion. + */ + public int intValue() { + return (int)sum(); + } + + /** + * Returns the {@link #sum} as a {@code float} + * after a widening primitive conversion. + */ + public float floatValue() { + return (float)sum(); + } + + /** + * Returns the {@link #sum} as a {@code double} after a widening + * primitive conversion. + */ + public double doubleValue() { + return (double)sum(); + } + + private void writeObject(java.io.ObjectOutputStream s) + throws java.io.IOException { + s.defaultWriteObject(); + s.writeLong(sum()); + } + + private void readObject(ObjectInputStream s) + throws IOException, ClassNotFoundException { + s.defaultReadObject(); + busy = 0; + cells = null; + base = s.readLong(); + } + +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/Striped64.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/Striped64.java new file mode 100644 index 0000000..f521642 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/Striped64.java @@ -0,0 +1,291 @@ +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +// This is based on 1.5 version. + +package com.concurrent_ruby.ext.jsr166e.nounsafe; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; + +/** + * A package-local class holding common representation and mechanics + * for classes supporting dynamic striping on 64bit values. The class + * extends Number so that concrete subclasses must publicly do so. + */ +abstract class Striped64 extends Number { + /* + * This class maintains a lazily-initialized table of atomically + * updated variables, plus an extra "base" field. The table size + * is a power of two. Indexing uses masked per-thread hash codes. + * Nearly all declarations in this class are package-private, + * accessed directly by subclasses. + * + * Table entries are of class Cell; a variant of AtomicLong padded + * to reduce cache contention on most processors. Padding is + * overkill for most Atomics because they are usually irregularly + * scattered in memory and thus don't interfere much with each + * other. But Atomic objects residing in arrays will tend to be + * placed adjacent to each other, and so will most often share + * cache lines (with a huge negative performance impact) without + * this precaution. + * + * In part because Cells are relatively large, we avoid creating + * them until they are needed. When there is no contention, all + * updates are made to the base field. Upon first contention (a + * failed CAS on base update), the table is initialized to size 2. + * The table size is doubled upon further contention until + * reaching the nearest power of two greater than or equal to the + * number of CPUS. Table slots remain empty (null) until they are + * needed. + * + * A single spinlock ("busy") is used for initializing and + * resizing the table, as well as populating slots with new Cells. + * There is no need for a blocking lock: When the lock is not + * available, threads try other slots (or the base). During these + * retries, there is increased contention and reduced locality, + * which is still better than alternatives. + * + * Per-thread hash codes are initialized to random values. + * Contention and/or table collisions are indicated by failed + * CASes when performing an update operation (see method + * retryUpdate). Upon a collision, if the table size is less than + * the capacity, it is doubled in size unless some other thread + * holds the lock. If a hashed slot is empty, and lock is + * available, a new Cell is created. Otherwise, if the slot + * exists, a CAS is tried. Retries proceed by "double hashing", + * using a secondary hash (Marsaglia XorShift) to try to find a + * free slot. + * + * The table size is capped because, when there are more threads + * than CPUs, supposing that each thread were bound to a CPU, + * there would exist a perfect hash function mapping threads to + * slots that eliminates collisions. When we reach capacity, we + * search for this mapping by randomly varying the hash codes of + * colliding threads. Because search is random, and collisions + * only become known via CAS failures, convergence can be slow, + * and because threads are typically not bound to CPUS forever, + * may not occur at all. However, despite these limitations, + * observed contention rates are typically low in these cases. + * + * It is possible for a Cell to become unused when threads that + * once hashed to it terminate, as well as in the case where + * doubling the table causes no thread to hash to it under + * expanded mask. We do not try to detect or remove such cells, + * under the assumption that for long-running instances, observed + * contention levels will recur, so the cells will eventually be + * needed again; and for short-lived ones, it does not matter. + */ + + /** + * Padded variant of AtomicLong supporting only raw accesses plus CAS. + * The value field is placed between pads, hoping that the JVM doesn't + * reorder them. + * + * JVM intrinsics note: It would be possible to use a release-only + * form of CAS here, if it were provided. + */ + static final class Cell { + volatile long p0, p1, p2, p3, p4, p5, p6; + volatile long value; + volatile long q0, q1, q2, q3, q4, q5, q6; + + static AtomicLongFieldUpdater VALUE_UPDATER = AtomicLongFieldUpdater.newUpdater(Cell.class, "value"); + + Cell(long x) { value = x; } + + final boolean cas(long cmp, long val) { + return VALUE_UPDATER.compareAndSet(this, cmp, val); + } + + } + + /** + * Holder for the thread-local hash code. The code is initially + * random, but may be set to a different value upon collisions. + */ + static final class HashCode { + static final Random rng = new Random(); + int code; + HashCode() { + int h = rng.nextInt(); // Avoid zero to allow xorShift rehash + code = (h == 0) ? 1 : h; + } + } + + /** + * The corresponding ThreadLocal class + */ + static final class ThreadHashCode extends ThreadLocal { + public HashCode initialValue() { return new HashCode(); } + } + + /** + * Static per-thread hash codes. Shared across all instances to + * reduce ThreadLocal pollution and because adjustments due to + * collisions in one table are likely to be appropriate for + * others. + */ + static final ThreadHashCode threadHashCode = new ThreadHashCode(); + + /** Number of CPUS, to place bound on table size */ + static final int NCPU = Runtime.getRuntime().availableProcessors(); + + /** + * Table of cells. When non-null, size is a power of 2. + */ + transient volatile Cell[] cells; + + /** + * Base value, used mainly when there is no contention, but also as + * a fallback during table initialization races. Updated via CAS. + */ + transient volatile long base; + + /** + * Spinlock (locked via CAS) used when resizing and/or creating Cells. + */ + transient volatile int busy; + + AtomicLongFieldUpdater BASE_UPDATER = AtomicLongFieldUpdater.newUpdater(Striped64.class, "base"); + AtomicIntegerFieldUpdater BUSY_UPDATER = AtomicIntegerFieldUpdater.newUpdater(Striped64.class, "busy"); + + /** + * Package-private default constructor + */ + Striped64() { + } + + /** + * CASes the base field. + */ + final boolean casBase(long cmp, long val) { + return BASE_UPDATER.compareAndSet(this, cmp, val); + } + + /** + * CASes the busy field from 0 to 1 to acquire lock. + */ + final boolean casBusy() { + return BUSY_UPDATER.compareAndSet(this, 0, 1); + } + + /** + * Computes the function of current and new value. Subclasses + * should open-code this update function for most uses, but the + * virtualized form is needed within retryUpdate. + * + * @param currentValue the current value (of either base or a cell) + * @param newValue the argument from a user update call + * @return result of the update function + */ + abstract long fn(long currentValue, long newValue); + + /** + * Handles cases of updates involving initialization, resizing, + * creating new Cells, and/or contention. See above for + * explanation. This method suffers the usual non-modularity + * problems of optimistic retry code, relying on rechecked sets of + * reads. + * + * @param x the value + * @param hc the hash code holder + * @param wasUncontended false if CAS failed before call + */ + final void retryUpdate(long x, HashCode hc, boolean wasUncontended) { + int h = hc.code; + boolean collide = false; // True if last slot nonempty + for (;;) { + Cell[] as; Cell a; int n; long v; + if ((as = cells) != null && (n = as.length) > 0) { + if ((a = as[(n - 1) & h]) == null) { + if (busy == 0) { // Try to attach new Cell + Cell r = new Cell(x); // Optimistically create + if (busy == 0 && casBusy()) { + boolean created = false; + try { // Recheck under lock + Cell[] rs; int m, j; + if ((rs = cells) != null && + (m = rs.length) > 0 && + rs[j = (m - 1) & h] == null) { + rs[j] = r; + created = true; + } + } finally { + busy = 0; + } + if (created) + break; + continue; // Slot is now non-empty + } + } + collide = false; + } + else if (!wasUncontended) // CAS already known to fail + wasUncontended = true; // Continue after rehash + else if (a.cas(v = a.value, fn(v, x))) + break; + else if (n >= NCPU || cells != as) + collide = false; // At max size or stale + else if (!collide) + collide = true; + else if (busy == 0 && casBusy()) { + try { + if (cells == as) { // Expand table unless stale + Cell[] rs = new Cell[n << 1]; + for (int i = 0; i < n; ++i) + rs[i] = as[i]; + cells = rs; + } + } finally { + busy = 0; + } + collide = false; + continue; // Retry with expanded table + } + h ^= h << 13; // Rehash + h ^= h >>> 17; + h ^= h << 5; + } + else if (busy == 0 && cells == as && casBusy()) { + boolean init = false; + try { // Initialize table + if (cells == as) { + Cell[] rs = new Cell[2]; + rs[h & 1] = new Cell(x); + cells = rs; + init = true; + } + } finally { + busy = 0; + } + if (init) + break; + } + else if (casBase(v = base, fn(v, x))) + break; // Fall back on using base + } + hc.code = h; // Record index for next time + } + + + /** + * Sets base and all cells to the given value. + */ + final void internalReset(long initialValue) { + Cell[] as = cells; + base = initialValue; + if (as != null) { + int n = as.length; + for (int i = 0; i < n; ++i) { + Cell a = as[i]; + if (a != null) + a.value = initialValue; + } + } + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166y/ThreadLocalRandom.java b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166y/ThreadLocalRandom.java new file mode 100644 index 0000000..3ea409f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166y/ThreadLocalRandom.java @@ -0,0 +1,199 @@ +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +// This is based on 1.16 version + +package com.concurrent_ruby.ext.jsr166y; + +import java.util.Random; + +/** + * A random number generator isolated to the current thread. Like the + * global {@link java.util.Random} generator used by the {@link + * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized + * with an internally generated seed that may not otherwise be + * modified. When applicable, use of {@code ThreadLocalRandom} rather + * than shared {@code Random} objects in concurrent programs will + * typically encounter much less overhead and contention. Use of + * {@code ThreadLocalRandom} is particularly appropriate when multiple + * tasks (for example, each a {@link ForkJoinTask}) use random numbers + * in parallel in thread pools. + * + *

Usages of this class should typically be of the form: + * {@code ThreadLocalRandom.current().nextX(...)} (where + * {@code X} is {@code Int}, {@code Long}, etc). + * When all usages are of this form, it is never possible to + * accidently share a {@code ThreadLocalRandom} across multiple threads. + * + *

This class also provides additional commonly used bounded random + * generation methods. + * + * @since 1.7 + * @author Doug Lea + */ +public class ThreadLocalRandom extends Random { + // same constants as Random, but must be redeclared because private + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; + + /** + * The random seed. We can't use super.seed. + */ + private long rnd; + + /** + * Initialization flag to permit calls to setSeed to succeed only + * while executing the Random constructor. We can't allow others + * since it would cause setting seed in one part of a program to + * unintentionally impact other usages by the thread. + */ + boolean initialized; + + // Padding to help avoid memory contention among seed updates in + // different TLRs in the common case that they are located near + // each other. + private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; + + /** + * The actual ThreadLocal + */ + private static final ThreadLocal localRandom = + new ThreadLocal() { + protected ThreadLocalRandom initialValue() { + return new ThreadLocalRandom(); + } + }; + + + /** + * Constructor called only by localRandom.initialValue. + */ + ThreadLocalRandom() { + super(); + initialized = true; + } + + /** + * Returns the current thread's {@code ThreadLocalRandom}. + * + * @return the current thread's {@code ThreadLocalRandom} + */ + public static ThreadLocalRandom current() { + return localRandom.get(); + } + + /** + * Throws {@code UnsupportedOperationException}. Setting seeds in + * this generator is not supported. + * + * @throws UnsupportedOperationException always + */ + public void setSeed(long seed) { + if (initialized) + throw new UnsupportedOperationException(); + rnd = (seed ^ multiplier) & mask; + } + + protected int next(int bits) { + rnd = (rnd * multiplier + addend) & mask; + return (int) (rnd >>> (48-bits)); + } + + /** + * Returns a pseudorandom, uniformly distributed value between the + * given least value (inclusive) and bound (exclusive). + * + * @param least the least value returned + * @param bound the upper bound (exclusive) + * @throws IllegalArgumentException if least greater than or equal + * to bound + * @return the next value + */ + public int nextInt(int least, int bound) { + if (least >= bound) + throw new IllegalArgumentException(); + return nextInt(bound - least) + least; + } + + /** + * Returns a pseudorandom, uniformly distributed value + * between 0 (inclusive) and the specified value (exclusive). + * + * @param n the bound on the random number to be returned. Must be + * positive. + * @return the next value + * @throws IllegalArgumentException if n is not positive + */ + public long nextLong(long n) { + if (n <= 0) + throw new IllegalArgumentException("n must be positive"); + // Divide n by two until small enough for nextInt. On each + // iteration (at most 31 of them but usually much less), + // randomly choose both whether to include high bit in result + // (offset) and whether to continue with the lower vs upper + // half (which makes a difference only if odd). + long offset = 0; + while (n >= Integer.MAX_VALUE) { + int bits = next(2); + long half = n >>> 1; + long nextn = ((bits & 2) == 0) ? half : n - half; + if ((bits & 1) == 0) + offset += n - nextn; + n = nextn; + } + return offset + nextInt((int) n); + } + + /** + * Returns a pseudorandom, uniformly distributed value between the + * given least value (inclusive) and bound (exclusive). + * + * @param least the least value returned + * @param bound the upper bound (exclusive) + * @return the next value + * @throws IllegalArgumentException if least greater than or equal + * to bound + */ + public long nextLong(long least, long bound) { + if (least >= bound) + throw new IllegalArgumentException(); + return nextLong(bound - least) + least; + } + + /** + * Returns a pseudorandom, uniformly distributed {@code double} value + * between 0 (inclusive) and the specified value (exclusive). + * + * @param n the bound on the random number to be returned. Must be + * positive. + * @return the next value + * @throws IllegalArgumentException if n is not positive + */ + public double nextDouble(double n) { + if (n <= 0) + throw new IllegalArgumentException("n must be positive"); + return nextDouble() * n; + } + + /** + * Returns a pseudorandom, uniformly distributed value between the + * given least value (inclusive) and bound (exclusive). + * + * @param least the least value returned + * @param bound the upper bound (exclusive) + * @return the next value + * @throws IllegalArgumentException if least greater than or equal + * to bound + */ + public double nextDouble(double least, double bound) { + if (least >= bound) + throw new IllegalArgumentException(); + return nextDouble() * (bound - least) + least; + } + + private static final long serialVersionUID = -5851777807851030925L; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent-ruby.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent-ruby.rb new file mode 100644 index 0000000..e9a3dea --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent-ruby.rb @@ -0,0 +1,5 @@ +# This file is here so that there is a file with the same name as the gem that +# can be required by Bundler.require. Applications should normally +# require 'concurrent'. + +require_relative "concurrent" diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent.rb new file mode 100644 index 0000000..87de46f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent.rb @@ -0,0 +1,134 @@ +require 'concurrent/version' +require 'concurrent/constants' +require 'concurrent/errors' +require 'concurrent/configuration' + +require 'concurrent/atomics' +require 'concurrent/executors' +require 'concurrent/synchronization' + +require 'concurrent/atomic/atomic_markable_reference' +require 'concurrent/atomic/atomic_reference' +require 'concurrent/agent' +require 'concurrent/atom' +require 'concurrent/array' +require 'concurrent/hash' +require 'concurrent/set' +require 'concurrent/map' +require 'concurrent/tuple' +require 'concurrent/async' +require 'concurrent/dataflow' +require 'concurrent/delay' +require 'concurrent/exchanger' +require 'concurrent/future' +require 'concurrent/immutable_struct' +require 'concurrent/ivar' +require 'concurrent/maybe' +require 'concurrent/mutable_struct' +require 'concurrent/mvar' +require 'concurrent/promise' +require 'concurrent/scheduled_task' +require 'concurrent/settable_struct' +require 'concurrent/timer_task' +require 'concurrent/tvar' +require 'concurrent/promises' + +require 'concurrent/thread_safe/synchronized_delegator' +require 'concurrent/thread_safe/util' + +require 'concurrent/options' + +# @!macro internal_implementation_note +# +# @note **Private Implementation:** This abstraction is a private, internal +# implementation detail. It should never be used directly. + +# @!macro monotonic_clock_warning +# +# @note Time calculations on all platforms and languages are sensitive to +# changes to the system clock. To alleviate the potential problems +# associated with changing the system clock while an application is running, +# most modern operating systems provide a monotonic clock that operates +# independently of the system clock. A monotonic clock cannot be used to +# determine human-friendly clock times. A monotonic clock is used exclusively +# for calculating time intervals. Not all Ruby platforms provide access to an +# operating system monotonic clock. On these platforms a pure-Ruby monotonic +# clock will be used as a fallback. An operating system monotonic clock is both +# faster and more reliable than the pure-Ruby implementation. The pure-Ruby +# implementation should be fast and reliable enough for most non-realtime +# operations. At this time the common Ruby platforms that provide access to an +# operating system monotonic clock are MRI 2.1 and above and JRuby (all versions). +# +# @see http://linux.die.net/man/3/clock_gettime Linux clock_gettime(3) + +# @!macro copy_options +# +# ## Copy Options +# +# Object references in Ruby are mutable. This can lead to serious +# problems when the {#value} of an object is a mutable reference. Which +# is always the case unless the value is a `Fixnum`, `Symbol`, or similar +# "primitive" data type. Each instance can be configured with a few +# options that can help protect the program from potentially dangerous +# operations. Each of these options can be optionally set when the object +# instance is created: +# +# * `:dup_on_deref` When true the object will call the `#dup` method on +# the `value` object every time the `#value` method is called +# (default: false) +# * `:freeze_on_deref` When true the object will call the `#freeze` +# method on the `value` object every time the `#value` method is called +# (default: false) +# * `:copy_on_deref` When given a `Proc` object the `Proc` will be run +# every time the `#value` method is called. The `Proc` will be given +# the current `value` as its only argument and the result returned by +# the block will be the return value of the `#value` call. When `nil` +# this option will be ignored (default: nil) +# +# When multiple deref options are set the order of operations is strictly defined. +# The order of deref operations is: +# * `:copy_on_deref` +# * `:dup_on_deref` +# * `:freeze_on_deref` +# +# Because of this ordering there is no need to `#freeze` an object created by a +# provided `:copy_on_deref` block. Simply set `:freeze_on_deref` to `true`. +# Setting both `:dup_on_deref` to `true` and `:freeze_on_deref` to `true` is +# as close to the behavior of a "pure" functional language (like Erlang, Clojure, +# or Haskell) as we are likely to get in Ruby. + +# @!macro deref_options +# +# @option opts [Boolean] :dup_on_deref (false) Call `#dup` before +# returning the data from {#value} +# @option opts [Boolean] :freeze_on_deref (false) Call `#freeze` before +# returning the data from {#value} +# @option opts [Proc] :copy_on_deref (nil) When calling the {#value} +# method, call the given proc passing the internal value as the sole +# argument then return the new value returned from the proc. + +# @!macro executor_and_deref_options +# +# @param [Hash] opts the options used to define the behavior at update and deref +# and to specify the executor on which to perform actions +# @option opts [Executor] :executor when set use the given `Executor` instance. +# Three special values are also supported: `:io` returns the global pool for +# long, blocking (IO) tasks, `:fast` returns the global pool for short, fast +# operations, and `:immediate` returns the global `ImmediateExecutor` object. +# @!macro deref_options + +# @!macro warn.edge +# @api Edge +# @note **Edge Features** are under active development and may change frequently. +# +# - Deprecations are not added before incompatible changes. +# - Edge version: _major_ is always 0, _minor_ bump means incompatible change, +# _patch_ bump means compatible change. +# - Edge features may also lack tests and documentation. +# - Features developed in `concurrent-ruby-edge` are expected to move +# to `concurrent-ruby` when finalised. + + +# {include:file:README.md} +module Concurrent +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/agent.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/agent.rb new file mode 100644 index 0000000..815dca0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/agent.rb @@ -0,0 +1,587 @@ +require 'concurrent/configuration' +require 'concurrent/atomic/atomic_reference' +require 'concurrent/atomic/thread_local_var' +require 'concurrent/collection/copy_on_write_observer_set' +require 'concurrent/concern/observable' +require 'concurrent/synchronization' + +module Concurrent + + # `Agent` is inspired by Clojure's [agent](http://clojure.org/agents) + # function. An agent is a shared, mutable variable providing independent, + # uncoordinated, *asynchronous* change of individual values. Best used when + # the value will undergo frequent, complex updates. Suitable when the result + # of an update does not need to be known immediately. `Agent` is (mostly) + # functionally equivalent to Clojure's agent, except where the runtime + # prevents parity. + # + # Agents are reactive, not autonomous - there is no imperative message loop + # and no blocking receive. The state of an Agent should be itself immutable + # and the `#value` of an Agent is always immediately available for reading by + # any thread without any messages, i.e. observation does not require + # cooperation or coordination. + # + # Agent action dispatches are made using the various `#send` methods. These + # methods always return immediately. At some point later, in another thread, + # the following will happen: + # + # 1. The given `action` will be applied to the state of the Agent and the + # `args`, if any were supplied. + # 2. The return value of `action` will be passed to the validator lambda, + # if one has been set on the Agent. + # 3. If the validator succeeds or if no validator was given, the return value + # of the given `action` will become the new `#value` of the Agent. See + # `#initialize` for details. + # 4. If any observers were added to the Agent, they will be notified. See + # `#add_observer` for details. + # 5. If during the `action` execution any other dispatches are made (directly + # or indirectly), they will be held until after the `#value` of the Agent + # has been changed. + # + # If any exceptions are thrown by an action function, no nested dispatches + # will occur, and the exception will be cached in the Agent itself. When an + # Agent has errors cached, any subsequent interactions will immediately throw + # an exception, until the agent's errors are cleared. Agent errors can be + # examined with `#error` and the agent restarted with `#restart`. + # + # The actions of all Agents get interleaved amongst threads in a thread pool. + # At any point in time, at most one action for each Agent is being executed. + # Actions dispatched to an agent from another single agent or thread will + # occur in the order they were sent, potentially interleaved with actions + # dispatched to the same agent from other sources. The `#send` method should + # be used for actions that are CPU limited, while the `#send_off` method is + # appropriate for actions that may block on IO. + # + # Unlike in Clojure, `Agent` cannot participate in `Concurrent::TVar` transactions. + # + # ## Example + # + # ``` + # def next_fibonacci(set = nil) + # return [0, 1] if set.nil? + # set + [set[-2..-1].reduce{|sum,x| sum + x }] + # end + # + # # create an agent with an initial value + # agent = Concurrent::Agent.new(next_fibonacci) + # + # # send a few update requests + # 5.times do + # agent.send{|set| next_fibonacci(set) } + # end + # + # # wait for them to complete + # agent.await + # + # # get the current value + # agent.value #=> [0, 1, 1, 2, 3, 5, 8] + # ``` + # + # ## Observation + # + # Agents support observers through the {Concurrent::Observable} mixin module. + # Notification of observers occurs every time an action dispatch returns and + # the new value is successfully validated. Observation will *not* occur if the + # action raises an exception, if validation fails, or when a {#restart} occurs. + # + # When notified the observer will receive three arguments: `time`, `old_value`, + # and `new_value`. The `time` argument is the time at which the value change + # occurred. The `old_value` is the value of the Agent when the action began + # processing. The `new_value` is the value to which the Agent was set when the + # action completed. Note that `old_value` and `new_value` may be the same. + # This is not an error. It simply means that the action returned the same + # value. + # + # ## Nested Actions + # + # It is possible for an Agent action to post further actions back to itself. + # The nested actions will be enqueued normally then processed *after* the + # outer action completes, in the order they were sent, possibly interleaved + # with action dispatches from other threads. Nested actions never deadlock + # with one another and a failure in a nested action will never affect the + # outer action. + # + # Nested actions can be called using the Agent reference from the enclosing + # scope or by passing the reference in as a "send" argument. Nested actions + # cannot be post using `self` from within the action block/proc/lambda; `self` + # in this context will not reference the Agent. The preferred method for + # dispatching nested actions is to pass the Agent as an argument. This allows + # Ruby to more effectively manage the closing scope. + # + # Prefer this: + # + # ``` + # agent = Concurrent::Agent.new(0) + # agent.send(agent) do |value, this| + # this.send {|v| v + 42 } + # 3.14 + # end + # agent.value #=> 45.14 + # ``` + # + # Over this: + # + # ``` + # agent = Concurrent::Agent.new(0) + # agent.send do |value| + # agent.send {|v| v + 42 } + # 3.14 + # end + # ``` + # + # @!macro agent_await_warning + # + # **NOTE** Never, *under any circumstances*, call any of the "await" methods + # ({#await}, {#await_for}, {#await_for!}, and {#wait}) from within an action + # block/proc/lambda. The call will block the Agent and will always fail. + # Calling either {#await} or {#wait} (with a timeout of `nil`) will + # hopelessly deadlock the Agent with no possibility of recovery. + # + # @!macro thread_safe_variable_comparison + # + # @see http://clojure.org/Agents Clojure Agents + # @see http://clojure.org/state Values and Change - Clojure's approach to Identity and State + class Agent < Synchronization::LockableObject + include Concern::Observable + + ERROR_MODES = [:continue, :fail].freeze + private_constant :ERROR_MODES + + AWAIT_FLAG = ::Object.new + private_constant :AWAIT_FLAG + + AWAIT_ACTION = ->(value, latch) { latch.count_down; AWAIT_FLAG } + private_constant :AWAIT_ACTION + + DEFAULT_ERROR_HANDLER = ->(agent, error) { nil } + private_constant :DEFAULT_ERROR_HANDLER + + DEFAULT_VALIDATOR = ->(value) { true } + private_constant :DEFAULT_VALIDATOR + + Job = Struct.new(:action, :args, :executor, :caller) + private_constant :Job + + # Raised during action processing or any other time in an Agent's lifecycle. + class Error < StandardError + def initialize(message = nil) + message ||= 'agent must be restarted before jobs can post' + super(message) + end + end + + # Raised when a new value obtained during action processing or at `#restart` + # fails validation. + class ValidationError < Error + def initialize(message = nil) + message ||= 'invalid value' + super(message) + end + end + + # The error mode this Agent is operating in. See {#initialize} for details. + attr_reader :error_mode + + # Create a new `Agent` with the given initial value and options. + # + # The `:validator` option must be `nil` or a side-effect free proc/lambda + # which takes one argument. On any intended value change the validator, if + # provided, will be called. If the new value is invalid the validator should + # return `false` or raise an error. + # + # The `:error_handler` option must be `nil` or a proc/lambda which takes two + # arguments. When an action raises an error or validation fails, either by + # returning false or raising an error, the error handler will be called. The + # arguments to the error handler will be a reference to the agent itself and + # the error object which was raised. + # + # The `:error_mode` may be either `:continue` (the default if an error + # handler is given) or `:fail` (the default if error handler nil or not + # given). + # + # If an action being run by the agent throws an error or doesn't pass + # validation the error handler, if present, will be called. After the + # handler executes if the error mode is `:continue` the Agent will continue + # as if neither the action that caused the error nor the error itself ever + # happened. + # + # If the mode is `:fail` the Agent will become {#failed?} and will stop + # accepting new action dispatches. Any previously queued actions will be + # held until {#restart} is called. The {#value} method will still work, + # returning the value of the Agent before the error. + # + # @param [Object] initial the initial value + # @param [Hash] opts the configuration options + # + # @option opts [Symbol] :error_mode either `:continue` or `:fail` + # @option opts [nil, Proc] :error_handler the (optional) error handler + # @option opts [nil, Proc] :validator the (optional) validation procedure + def initialize(initial, opts = {}) + super() + synchronize { ns_initialize(initial, opts) } + end + + # The current value (state) of the Agent, irrespective of any pending or + # in-progress actions. The value is always available and is non-blocking. + # + # @return [Object] the current value + def value + @current.value # TODO (pitr 12-Sep-2015): broken unsafe read? + end + + alias_method :deref, :value + + # When {#failed?} and {#error_mode} is `:fail`, returns the error object + # which caused the failure, else `nil`. When {#error_mode} is `:continue` + # will *always* return `nil`. + # + # @return [nil, Error] the error which caused the failure when {#failed?} + def error + @error.value + end + + alias_method :reason, :error + + # @!macro agent_send + # + # Dispatches an action to the Agent and returns immediately. Subsequently, + # in a thread from a thread pool, the {#value} will be set to the return + # value of the action. Action dispatches are only allowed when the Agent + # is not {#failed?}. + # + # The action must be a block/proc/lambda which takes 1 or more arguments. + # The first argument is the current {#value} of the Agent. Any arguments + # passed to the send method via the `args` parameter will be passed to the + # action as the remaining arguments. The action must return the new value + # of the Agent. + # + # * {#send} and {#send!} should be used for actions that are CPU limited + # * {#send_off}, {#send_off!}, and {#<<} are appropriate for actions that + # may block on IO + # * {#send_via} and {#send_via!} are used when a specific executor is to + # be used for the action + # + # @param [Array] args zero or more arguments to be passed to + # the action + # @param [Proc] action the action dispatch to be enqueued + # + # @yield [agent, value, *args] process the old value and return the new + # @yieldparam [Object] value the current {#value} of the Agent + # @yieldparam [Array] args zero or more arguments to pass to the + # action + # @yieldreturn [Object] the new value of the Agent + # + # @!macro send_return + # @return [Boolean] true if the action is successfully enqueued, false if + # the Agent is {#failed?} + def send(*args, &action) + enqueue_action_job(action, args, Concurrent.global_fast_executor) + end + + # @!macro agent_send + # + # @!macro send_bang_return_and_raise + # @return [Boolean] true if the action is successfully enqueued + # @raise [Concurrent::Agent::Error] if the Agent is {#failed?} + def send!(*args, &action) + raise Error.new unless send(*args, &action) + true + end + + # @!macro agent_send + # @!macro send_return + def send_off(*args, &action) + enqueue_action_job(action, args, Concurrent.global_io_executor) + end + + alias_method :post, :send_off + + # @!macro agent_send + # @!macro send_bang_return_and_raise + def send_off!(*args, &action) + raise Error.new unless send_off(*args, &action) + true + end + + # @!macro agent_send + # @!macro send_return + # @param [Concurrent::ExecutorService] executor the executor on which the + # action is to be dispatched + def send_via(executor, *args, &action) + enqueue_action_job(action, args, executor) + end + + # @!macro agent_send + # @!macro send_bang_return_and_raise + # @param [Concurrent::ExecutorService] executor the executor on which the + # action is to be dispatched + def send_via!(executor, *args, &action) + raise Error.new unless send_via(executor, *args, &action) + true + end + + # Dispatches an action to the Agent and returns immediately. Subsequently, + # in a thread from a thread pool, the {#value} will be set to the return + # value of the action. Appropriate for actions that may block on IO. + # + # @param [Proc] action the action dispatch to be enqueued + # @return [Concurrent::Agent] self + # @see #send_off + def <<(action) + send_off(&action) + self + end + + # Blocks the current thread (indefinitely!) until all actions dispatched + # thus far, from this thread or nested by the Agent, have occurred. Will + # block when {#failed?}. Will never return if a failed Agent is {#restart} + # with `:clear_actions` true. + # + # Returns a reference to `self` to support method chaining: + # + # ``` + # current_value = agent.await.value + # ``` + # + # @return [Boolean] self + # + # @!macro agent_await_warning + def await + wait(nil) + self + end + + # Blocks the current thread until all actions dispatched thus far, from this + # thread or nested by the Agent, have occurred, or the timeout (in seconds) + # has elapsed. + # + # @param [Float] timeout the maximum number of seconds to wait + # @return [Boolean] true if all actions complete before timeout else false + # + # @!macro agent_await_warning + def await_for(timeout) + wait(timeout.to_f) + end + + # Blocks the current thread until all actions dispatched thus far, from this + # thread or nested by the Agent, have occurred, or the timeout (in seconds) + # has elapsed. + # + # @param [Float] timeout the maximum number of seconds to wait + # @return [Boolean] true if all actions complete before timeout + # + # @raise [Concurrent::TimeoutError] when timout is reached + # + # @!macro agent_await_warning + def await_for!(timeout) + raise Concurrent::TimeoutError unless wait(timeout.to_f) + true + end + + # Blocks the current thread until all actions dispatched thus far, from this + # thread or nested by the Agent, have occurred, or the timeout (in seconds) + # has elapsed. Will block indefinitely when timeout is nil or not given. + # + # Provided mainly for consistency with other classes in this library. Prefer + # the various `await` methods instead. + # + # @param [Float] timeout the maximum number of seconds to wait + # @return [Boolean] true if all actions complete before timeout else false + # + # @!macro agent_await_warning + def wait(timeout = nil) + latch = Concurrent::CountDownLatch.new(1) + enqueue_await_job(latch) + latch.wait(timeout) + end + + # Is the Agent in a failed state? + # + # @see #restart + def failed? + !@error.value.nil? + end + + alias_method :stopped?, :failed? + + # When an Agent is {#failed?}, changes the Agent {#value} to `new_value` + # then un-fails the Agent so that action dispatches are allowed again. If + # the `:clear_actions` option is give and true, any actions queued on the + # Agent that were being held while it was failed will be discarded, + # otherwise those held actions will proceed. The `new_value` must pass the + # validator if any, or `restart` will raise an exception and the Agent will + # remain failed with its old {#value} and {#error}. Observers, if any, will + # not be notified of the new state. + # + # @param [Object] new_value the new value for the Agent once restarted + # @param [Hash] opts the configuration options + # @option opts [Symbol] :clear_actions true if all enqueued but unprocessed + # actions should be discarded on restart, else false (default: false) + # @return [Boolean] true + # + # @raise [Concurrent:AgentError] when not failed + def restart(new_value, opts = {}) + clear_actions = opts.fetch(:clear_actions, false) + synchronize do + raise Error.new('agent is not failed') unless failed? + raise ValidationError unless ns_validate(new_value) + @current.value = new_value + @error.value = nil + @queue.clear if clear_actions + ns_post_next_job unless @queue.empty? + end + true + end + + class << self + + # Blocks the current thread (indefinitely!) until all actions dispatched + # thus far to all the given Agents, from this thread or nested by the + # given Agents, have occurred. Will block when any of the agents are + # failed. Will never return if a failed Agent is restart with + # `:clear_actions` true. + # + # @param [Array] agents the Agents on which to wait + # @return [Boolean] true + # + # @!macro agent_await_warning + def await(*agents) + agents.each { |agent| agent.await } + true + end + + # Blocks the current thread until all actions dispatched thus far to all + # the given Agents, from this thread or nested by the given Agents, have + # occurred, or the timeout (in seconds) has elapsed. + # + # @param [Float] timeout the maximum number of seconds to wait + # @param [Array] agents the Agents on which to wait + # @return [Boolean] true if all actions complete before timeout else false + # + # @!macro agent_await_warning + def await_for(timeout, *agents) + end_at = Concurrent.monotonic_time + timeout.to_f + ok = agents.length.times do |i| + break false if (delay = end_at - Concurrent.monotonic_time) < 0 + break false unless agents[i].await_for(delay) + end + !!ok + end + + # Blocks the current thread until all actions dispatched thus far to all + # the given Agents, from this thread or nested by the given Agents, have + # occurred, or the timeout (in seconds) has elapsed. + # + # @param [Float] timeout the maximum number of seconds to wait + # @param [Array] agents the Agents on which to wait + # @return [Boolean] true if all actions complete before timeout + # + # @raise [Concurrent::TimeoutError] when timout is reached + # @!macro agent_await_warning + def await_for!(timeout, *agents) + raise Concurrent::TimeoutError unless await_for(timeout, *agents) + true + end + end + + private + + def ns_initialize(initial, opts) + @error_mode = opts[:error_mode] + @error_handler = opts[:error_handler] + + if @error_mode && !ERROR_MODES.include?(@error_mode) + raise ArgumentError.new('unrecognized error mode') + elsif @error_mode.nil? + @error_mode = @error_handler ? :continue : :fail + end + + @error_handler ||= DEFAULT_ERROR_HANDLER + @validator = opts.fetch(:validator, DEFAULT_VALIDATOR) + @current = Concurrent::AtomicReference.new(initial) + @error = Concurrent::AtomicReference.new(nil) + @caller = Concurrent::ThreadLocalVar.new(nil) + @queue = [] + + self.observers = Collection::CopyOnNotifyObserverSet.new + end + + def enqueue_action_job(action, args, executor) + raise ArgumentError.new('no action given') unless action + job = Job.new(action, args, executor, @caller.value || Thread.current.object_id) + synchronize { ns_enqueue_job(job) } + end + + def enqueue_await_job(latch) + synchronize do + if (index = ns_find_last_job_for_thread) + job = Job.new(AWAIT_ACTION, [latch], Concurrent.global_immediate_executor, + Thread.current.object_id) + ns_enqueue_job(job, index+1) + else + latch.count_down + true + end + end + end + + def ns_enqueue_job(job, index = nil) + # a non-nil index means this is an await job + return false if index.nil? && failed? + index ||= @queue.length + @queue.insert(index, job) + # if this is the only job, post to executor + ns_post_next_job if @queue.length == 1 + true + end + + def ns_post_next_job + @queue.first.executor.post { execute_next_job } + end + + def execute_next_job + job = synchronize { @queue.first } + old_value = @current.value + + @caller.value = job.caller # for nested actions + new_value = job.action.call(old_value, *job.args) + @caller.value = nil + + return if new_value == AWAIT_FLAG + + if ns_validate(new_value) + @current.value = new_value + observers.notify_observers(Time.now, old_value, new_value) + else + handle_error(ValidationError.new) + end + rescue => error + handle_error(error) + ensure + synchronize do + @queue.shift + unless failed? || @queue.empty? + ns_post_next_job + end + end + end + + def ns_validate(value) + @validator.call(value) + rescue + false + end + + def handle_error(error) + # stop new jobs from posting + @error.value = error if @error_mode == :fail + @error_handler.call(self, error) + rescue + # do nothing + end + + def ns_find_last_job_for_thread + @queue.rindex { |job| job.caller == Thread.current.object_id } + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/array.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/array.rb new file mode 100644 index 0000000..60e5b56 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/array.rb @@ -0,0 +1,66 @@ +require 'concurrent/utility/engine' +require 'concurrent/thread_safe/util' + +module Concurrent + + # @!macro concurrent_array + # + # A thread-safe subclass of Array. This version locks against the object + # itself for every method call, ensuring only one thread can be reading + # or writing at a time. This includes iteration methods like `#each`. + # + # @note `a += b` is **not** a **thread-safe** operation on + # `Concurrent::Array`. It reads array `a`, then it creates new `Concurrent::Array` + # which is concatenation of `a` and `b`, then it writes the concatenation to `a`. + # The read and write are independent operations they do not form a single atomic + # operation therefore when two `+=` operations are executed concurrently updates + # may be lost. Use `#concat` instead. + # + # @see http://ruby-doc.org/core/Array.html Ruby standard library `Array` + + # @!macro internal_implementation_note + ArrayImplementation = case + when Concurrent.on_cruby? + # Array is thread-safe in practice because CRuby runs + # threads one at a time and does not do context + # switching during the execution of C functions. + ::Array + + when Concurrent.on_jruby? + require 'jruby/synchronized' + + class JRubyArray < ::Array + include JRuby::Synchronized + end + JRubyArray + + when Concurrent.on_rbx? + require 'monitor' + require 'concurrent/thread_safe/util/data_structures' + + class RbxArray < ::Array + end + + ThreadSafe::Util.make_synchronized_on_rbx RbxArray + RbxArray + + when Concurrent.on_truffleruby? + require 'concurrent/thread_safe/util/data_structures' + + class TruffleRubyArray < ::Array + end + + ThreadSafe::Util.make_synchronized_on_truffleruby TruffleRubyArray + TruffleRubyArray + + else + warn 'Possibly unsupported Ruby implementation' + ::Array + end + private_constant :ArrayImplementation + + # @!macro concurrent_array + class Array < ArrayImplementation + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/async.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/async.rb new file mode 100644 index 0000000..f9f8adf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/async.rb @@ -0,0 +1,449 @@ +require 'concurrent/configuration' +require 'concurrent/ivar' +require 'concurrent/synchronization/lockable_object' + +module Concurrent + + # A mixin module that provides simple asynchronous behavior to a class, + # turning it into a simple actor. Loosely based on Erlang's + # [gen_server](http://www.erlang.org/doc/man/gen_server.html), but without + # supervision or linking. + # + # A more feature-rich {Concurrent::Actor} is also available when the + # capabilities of `Async` are too limited. + # + # ```cucumber + # Feature: + # As a stateful, plain old Ruby class + # I want safe, asynchronous behavior + # So my long-running methods don't block the main thread + # ``` + # + # The `Async` module is a way to mix simple yet powerful asynchronous + # capabilities into any plain old Ruby object or class, turning each object + # into a simple Actor. Method calls are processed on a background thread. The + # caller is free to perform other actions while processing occurs in the + # background. + # + # Method calls to the asynchronous object are made via two proxy methods: + # `async` (alias `cast`) and `await` (alias `call`). These proxy methods post + # the method call to the object's background thread and return a "future" + # which will eventually contain the result of the method call. + # + # This behavior is loosely patterned after Erlang's `gen_server` behavior. + # When an Erlang module implements the `gen_server` behavior it becomes + # inherently asynchronous. The `start` or `start_link` function spawns a + # process (similar to a thread but much more lightweight and efficient) and + # returns the ID of the process. Using the process ID, other processes can + # send messages to the `gen_server` via the `cast` and `call` methods. Unlike + # Erlang's `gen_server`, however, `Async` classes do not support linking or + # supervision trees. + # + # ## Basic Usage + # + # When this module is mixed into a class, objects of the class become inherently + # asynchronous. Each object gets its own background thread on which to post + # asynchronous method calls. Asynchronous method calls are executed in the + # background one at a time in the order they are received. + # + # To create an asynchronous class, simply mix in the `Concurrent::Async` module: + # + # ``` + # class Hello + # include Concurrent::Async + # + # def hello(name) + # "Hello, #{name}!" + # end + # end + # ``` + # + # Mixing this module into a class provides each object two proxy methods: + # `async` and `await`. These methods are thread safe with respect to the + # enclosing object. The former proxy allows methods to be called + # asynchronously by posting to the object's internal thread. The latter proxy + # allows a method to be called synchronously but does so safely with respect + # to any pending asynchronous method calls and ensures proper ordering. Both + # methods return a {Concurrent::IVar} which can be inspected for the result + # of the proxied method call. Calling a method with `async` will return a + # `:pending` `IVar` whereas `await` will return a `:complete` `IVar`. + # + # ``` + # class Echo + # include Concurrent::Async + # + # def echo(msg) + # print "#{msg}\n" + # end + # end + # + # horn = Echo.new + # horn.echo('zero') # synchronous, not thread-safe + # # returns the actual return value of the method + # + # horn.async.echo('one') # asynchronous, non-blocking, thread-safe + # # returns an IVar in the :pending state + # + # horn.await.echo('two') # synchronous, blocking, thread-safe + # # returns an IVar in the :complete state + # ``` + # + # ## Let It Fail + # + # The `async` and `await` proxy methods have built-in error protection based + # on Erlang's famous "let it fail" philosophy. Instance methods should not be + # programmed defensively. When an exception is raised by a delegated method + # the proxy will rescue the exception, expose it to the caller as the `reason` + # attribute of the returned future, then process the next method call. + # + # ## Calling Methods Internally + # + # External method calls should *always* use the `async` and `await` proxy + # methods. When one method calls another method, the `async` proxy should + # rarely be used and the `await` proxy should *never* be used. + # + # When an object calls one of its own methods using the `await` proxy the + # second call will be enqueued *behind* the currently running method call. + # Any attempt to wait on the result will fail as the second call will never + # run until after the current call completes. + # + # Calling a method using the `await` proxy from within a method that was + # itself called using `async` or `await` will irreversibly deadlock the + # object. Do *not* do this, ever. + # + # ## Instance Variables and Attribute Accessors + # + # Instance variables do not need to be thread-safe so long as they are private. + # Asynchronous method calls are processed in the order they are received and + # are processed one at a time. Therefore private instance variables can only + # be accessed by one thread at a time. This is inherently thread-safe. + # + # When using private instance variables within asynchronous methods, the best + # practice is to read the instance variable into a local variable at the start + # of the method then update the instance variable at the *end* of the method. + # This way, should an exception be raised during method execution the internal + # state of the object will not have been changed. + # + # ### Reader Attributes + # + # The use of `attr_reader` is discouraged. Internal state exposed externally, + # when necessary, should be done through accessor methods. The instance + # variables exposed by these methods *must* be thread-safe, or they must be + # called using the `async` and `await` proxy methods. These two approaches are + # subtly different. + # + # When internal state is accessed via the `async` and `await` proxy methods, + # the returned value represents the object's state *at the time the call is + # processed*, which may *not* be the state of the object at the time the call + # is made. + # + # To get the state *at the current* time, irrespective of an enqueued method + # calls, a reader method must be called directly. This is inherently unsafe + # unless the instance variable is itself thread-safe, preferably using one + # of the thread-safe classes within this library. Because the thread-safe + # classes within this library are internally-locking or non-locking, they can + # be safely used from within asynchronous methods without causing deadlocks. + # + # Generally speaking, the best practice is to *not* expose internal state via + # reader methods. The best practice is to simply use the method's return value. + # + # ### Writer Attributes + # + # Writer attributes should never be used with asynchronous classes. Changing + # the state externally, even when done in the thread-safe way, is not logically + # consistent. Changes to state need to be timed with respect to all asynchronous + # method calls which my be in-process or enqueued. The only safe practice is to + # pass all necessary data to each method as arguments and let the method update + # the internal state as necessary. + # + # ## Class Constants, Variables, and Methods + # + # ### Class Constants + # + # Class constants do not need to be thread-safe. Since they are read-only and + # immutable they may be safely read both externally and from within + # asynchronous methods. + # + # ### Class Variables + # + # Class variables should be avoided. Class variables represent shared state. + # Shared state is anathema to concurrency. Should there be a need to share + # state using class variables they *must* be thread-safe, preferably + # using the thread-safe classes within this library. When updating class + # variables, never assign a new value/object to the variable itself. Assignment + # is not thread-safe in Ruby. Instead, use the thread-safe update functions + # of the variable itself to change the value. + # + # The best practice is to *never* use class variables with `Async` classes. + # + # ### Class Methods + # + # Class methods which are pure functions are safe. Class methods which modify + # class variables should be avoided, for all the reasons listed above. + # + # ## An Important Note About Thread Safe Guarantees + # + # > Thread safe guarantees can only be made when asynchronous method calls + # > are not mixed with direct method calls. Use only direct method calls + # > when the object is used exclusively on a single thread. Use only + # > `async` and `await` when the object is shared between threads. Once you + # > call a method using `async` or `await`, you should no longer call methods + # > directly on the object. Use `async` and `await` exclusively from then on. + # + # @example + # + # class Echo + # include Concurrent::Async + # + # def echo(msg) + # print "#{msg}\n" + # end + # end + # + # horn = Echo.new + # horn.echo('zero') # synchronous, not thread-safe + # # returns the actual return value of the method + # + # horn.async.echo('one') # asynchronous, non-blocking, thread-safe + # # returns an IVar in the :pending state + # + # horn.await.echo('two') # synchronous, blocking, thread-safe + # # returns an IVar in the :complete state + # + # @see Concurrent::Actor + # @see https://en.wikipedia.org/wiki/Actor_model "Actor Model" at Wikipedia + # @see http://www.erlang.org/doc/man/gen_server.html Erlang gen_server + # @see http://c2.com/cgi/wiki?LetItCrash "Let It Crash" at http://c2.com/ + module Async + + # @!method self.new(*args, &block) + # + # Instanciate a new object and ensure proper initialization of the + # synchronization mechanisms. + # + # @param [Array] args Zero or more arguments to be passed to the + # object's initializer. + # @param [Proc] block Optional block to pass to the object's initializer. + # @return [Object] A properly initialized object of the asynchronous class. + + # Check for the presence of a method on an object and determine if a given + # set of arguments matches the required arity. + # + # @param [Object] obj the object to check against + # @param [Symbol] method the method to check the object for + # @param [Array] args zero or more arguments for the arity check + # + # @raise [NameError] the object does not respond to `method` method + # @raise [ArgumentError] the given `args` do not match the arity of `method` + # + # @note This check is imperfect because of the way Ruby reports the arity of + # methods with a variable number of arguments. It is possible to determine + # if too few arguments are given but impossible to determine if too many + # arguments are given. This check may also fail to recognize dynamic behavior + # of the object, such as methods simulated with `method_missing`. + # + # @see http://www.ruby-doc.org/core-2.1.1/Method.html#method-i-arity Method#arity + # @see http://ruby-doc.org/core-2.1.0/Object.html#method-i-respond_to-3F Object#respond_to? + # @see http://www.ruby-doc.org/core-2.1.0/BasicObject.html#method-i-method_missing BasicObject#method_missing + # + # @!visibility private + def self.validate_argc(obj, method, *args) + argc = args.length + arity = obj.method(method).arity + + if arity >= 0 && argc != arity + raise ArgumentError.new("wrong number of arguments (#{argc} for #{arity})") + elsif arity < 0 && (arity = (arity + 1).abs) > argc + raise ArgumentError.new("wrong number of arguments (#{argc} for #{arity}..*)") + end + end + + # @!visibility private + def self.included(base) + base.singleton_class.send(:alias_method, :original_new, :new) + base.extend(ClassMethods) + super(base) + end + + # @!visibility private + module ClassMethods + def new(*args, &block) + obj = original_new(*args, &block) + obj.send(:init_synchronization) + obj + end + ruby2_keywords :new if respond_to?(:ruby2_keywords, true) + end + private_constant :ClassMethods + + # Delegates asynchronous, thread-safe method calls to the wrapped object. + # + # @!visibility private + class AsyncDelegator < Synchronization::LockableObject + safe_initialization! + + # Create a new delegator object wrapping the given delegate. + # + # @param [Object] delegate the object to wrap and delegate method calls to + def initialize(delegate) + super() + @delegate = delegate + @queue = [] + @executor = Concurrent.global_io_executor + @ruby_pid = $$ + end + + # Delegates method calls to the wrapped object. + # + # @param [Symbol] method the method being called + # @param [Array] args zero or more arguments to the method + # + # @return [IVar] the result of the method call + # + # @raise [NameError] the object does not respond to `method` method + # @raise [ArgumentError] the given `args` do not match the arity of `method` + def method_missing(method, *args, &block) + super unless @delegate.respond_to?(method) + Async::validate_argc(@delegate, method, *args) + + ivar = Concurrent::IVar.new + synchronize do + reset_if_forked + @queue.push [ivar, method, args, block] + @executor.post { perform } if @queue.length == 1 + end + + ivar + end + + # Check whether the method is responsive + # + # @param [Symbol] method the method being called + def respond_to_missing?(method, include_private = false) + @delegate.respond_to?(method) || super + end + + # Perform all enqueued tasks. + # + # This method must be called from within the executor. It must not be + # called while already running. It will loop until the queue is empty. + def perform + loop do + ivar, method, args, block = synchronize { @queue.first } + break unless ivar # queue is empty + + begin + ivar.set(@delegate.send(method, *args, &block)) + rescue => error + ivar.fail(error) + end + + synchronize do + @queue.shift + return if @queue.empty? + end + end + end + + def reset_if_forked + if $$ != @ruby_pid + @queue.clear + @ruby_pid = $$ + end + end + end + private_constant :AsyncDelegator + + # Delegates synchronous, thread-safe method calls to the wrapped object. + # + # @!visibility private + class AwaitDelegator + + # Create a new delegator object wrapping the given delegate. + # + # @param [AsyncDelegator] delegate the object to wrap and delegate method calls to + def initialize(delegate) + @delegate = delegate + end + + # Delegates method calls to the wrapped object. + # + # @param [Symbol] method the method being called + # @param [Array] args zero or more arguments to the method + # + # @return [IVar] the result of the method call + # + # @raise [NameError] the object does not respond to `method` method + # @raise [ArgumentError] the given `args` do not match the arity of `method` + def method_missing(method, *args, &block) + ivar = @delegate.send(method, *args, &block) + ivar.wait + ivar + end + + # Check whether the method is responsive + # + # @param [Symbol] method the method being called + def respond_to_missing?(method, include_private = false) + @delegate.respond_to?(method) || super + end + end + private_constant :AwaitDelegator + + # Causes the chained method call to be performed asynchronously on the + # object's thread. The delegated method will return a future in the + # `:pending` state and the method call will have been scheduled on the + # object's thread. The final disposition of the method call can be obtained + # by inspecting the returned future. + # + # @!macro async_thread_safety_warning + # @note The method call is guaranteed to be thread safe with respect to + # all other method calls against the same object that are called with + # either `async` or `await`. The mutable nature of Ruby references + # (and object orientation in general) prevent any other thread safety + # guarantees. Do NOT mix direct method calls with delegated method calls. + # Use *only* delegated method calls when sharing the object between threads. + # + # @return [Concurrent::IVar] the pending result of the asynchronous operation + # + # @raise [NameError] the object does not respond to the requested method + # @raise [ArgumentError] the given `args` do not match the arity of + # the requested method + def async + @__async_delegator__ + end + alias_method :cast, :async + + # Causes the chained method call to be performed synchronously on the + # current thread. The delegated will return a future in either the + # `:fulfilled` or `:rejected` state and the delegated method will have + # completed. The final disposition of the delegated method can be obtained + # by inspecting the returned future. + # + # @!macro async_thread_safety_warning + # + # @return [Concurrent::IVar] the completed result of the synchronous operation + # + # @raise [NameError] the object does not respond to the requested method + # @raise [ArgumentError] the given `args` do not match the arity of the + # requested method + def await + @__await_delegator__ + end + alias_method :call, :await + + # Initialize the internal serializer and other stnchronization mechanisms. + # + # @note This method *must* be called immediately upon object construction. + # This is the only way thread-safe initialization can be guaranteed. + # + # @!visibility private + def init_synchronization + return self if defined?(@__async_initialized__) && @__async_initialized__ + @__async_initialized__ = true + @__async_delegator__ = AsyncDelegator.new(self) + @__await_delegator__ = AwaitDelegator.new(@__async_delegator__) + self + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atom.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atom.rb new file mode 100644 index 0000000..8a45730 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atom.rb @@ -0,0 +1,222 @@ +require 'concurrent/atomic/atomic_reference' +require 'concurrent/collection/copy_on_notify_observer_set' +require 'concurrent/concern/observable' +require 'concurrent/synchronization' + +# @!macro thread_safe_variable_comparison +# +# ## Thread-safe Variable Classes +# +# Each of the thread-safe variable classes is designed to solve a different +# problem. In general: +# +# * *{Concurrent::Agent}:* Shared, mutable variable providing independent, +# uncoordinated, *asynchronous* change of individual values. Best used when +# the value will undergo frequent, complex updates. Suitable when the result +# of an update does not need to be known immediately. +# * *{Concurrent::Atom}:* Shared, mutable variable providing independent, +# uncoordinated, *synchronous* change of individual values. Best used when +# the value will undergo frequent reads but only occasional, though complex, +# updates. Suitable when the result of an update must be known immediately. +# * *{Concurrent::AtomicReference}:* A simple object reference that can be updated +# atomically. Updates are synchronous but fast. Best used when updates a +# simple set operations. Not suitable when updates are complex. +# {Concurrent::AtomicBoolean} and {Concurrent::AtomicFixnum} are similar +# but optimized for the given data type. +# * *{Concurrent::Exchanger}:* Shared, stateless synchronization point. Used +# when two or more threads need to exchange data. The threads will pair then +# block on each other until the exchange is complete. +# * *{Concurrent::MVar}:* Shared synchronization point. Used when one thread +# must give a value to another, which must take the value. The threads will +# block on each other until the exchange is complete. +# * *{Concurrent::ThreadLocalVar}:* Shared, mutable, isolated variable which +# holds a different value for each thread which has access. Often used as +# an instance variable in objects which must maintain different state +# for different threads. +# * *{Concurrent::TVar}:* Shared, mutable variables which provide +# *coordinated*, *synchronous*, change of *many* stated. Used when multiple +# value must change together, in an all-or-nothing transaction. + + +module Concurrent + + # Atoms provide a way to manage shared, synchronous, independent state. + # + # An atom is initialized with an initial value and an optional validation + # proc. At any time the value of the atom can be synchronously and safely + # changed. If a validator is given at construction then any new value + # will be checked against the validator and will be rejected if the + # validator returns false or raises an exception. + # + # There are two ways to change the value of an atom: {#compare_and_set} and + # {#swap}. The former will set the new value if and only if it validates and + # the current value matches the new value. The latter will atomically set the + # new value to the result of running the given block if and only if that + # value validates. + # + # ## Example + # + # ``` + # def next_fibonacci(set = nil) + # return [0, 1] if set.nil? + # set + [set[-2..-1].reduce{|sum,x| sum + x }] + # end + # + # # create an atom with an initial value + # atom = Concurrent::Atom.new(next_fibonacci) + # + # # send a few update requests + # 5.times do + # atom.swap{|set| next_fibonacci(set) } + # end + # + # # get the current value + # atom.value #=> [0, 1, 1, 2, 3, 5, 8] + # ``` + # + # ## Observation + # + # Atoms support observers through the {Concurrent::Observable} mixin module. + # Notification of observers occurs every time the value of the Atom changes. + # When notified the observer will receive three arguments: `time`, `old_value`, + # and `new_value`. The `time` argument is the time at which the value change + # occurred. The `old_value` is the value of the Atom when the change began + # The `new_value` is the value to which the Atom was set when the change + # completed. Note that `old_value` and `new_value` may be the same. This is + # not an error. It simply means that the change operation returned the same + # value. + # + # Unlike in Clojure, `Atom` cannot participate in {Concurrent::TVar} transactions. + # + # @!macro thread_safe_variable_comparison + # + # @see http://clojure.org/atoms Clojure Atoms + # @see http://clojure.org/state Values and Change - Clojure's approach to Identity and State + class Atom < Synchronization::Object + include Concern::Observable + + safe_initialization! + attr_atomic(:value) + private :value=, :swap_value, :compare_and_set_value, :update_value + public :value + alias_method :deref, :value + + # @!method value + # The current value of the atom. + # + # @return [Object] The current value. + + # Create a new atom with the given initial value. + # + # @param [Object] value The initial value + # @param [Hash] opts The options used to configure the atom + # @option opts [Proc] :validator (nil) Optional proc used to validate new + # values. It must accept one and only one argument which will be the + # intended new value. The validator will return true if the new value + # is acceptable else return false (preferrably) or raise an exception. + # + # @!macro deref_options + # + # @raise [ArgumentError] if the validator is not a `Proc` (when given) + def initialize(value, opts = {}) + super() + @Validator = opts.fetch(:validator, -> v { true }) + self.observers = Collection::CopyOnNotifyObserverSet.new + self.value = value + end + + # Atomically swaps the value of atom using the given block. The current + # value will be passed to the block, as will any arguments passed as + # arguments to the function. The new value will be validated against the + # (optional) validator proc given at construction. If validation fails the + # value will not be changed. + # + # Internally, {#swap} reads the current value, applies the block to it, and + # attempts to compare-and-set it in. Since another thread may have changed + # the value in the intervening time, it may have to retry, and does so in a + # spin loop. The net effect is that the value will always be the result of + # the application of the supplied block to a current value, atomically. + # However, because the block might be called multiple times, it must be free + # of side effects. + # + # @note The given block may be called multiple times, and thus should be free + # of side effects. + # + # @param [Object] args Zero or more arguments passed to the block. + # + # @yield [value, args] Calculates a new value for the atom based on the + # current value and any supplied arguments. + # @yieldparam value [Object] The current value of the atom. + # @yieldparam args [Object] All arguments passed to the function, in order. + # @yieldreturn [Object] The intended new value of the atom. + # + # @return [Object] The final value of the atom after all operations and + # validations are complete. + # + # @raise [ArgumentError] When no block is given. + def swap(*args) + raise ArgumentError.new('no block given') unless block_given? + + loop do + old_value = value + new_value = yield(old_value, *args) + begin + break old_value unless valid?(new_value) + break new_value if compare_and_set(old_value, new_value) + rescue + break old_value + end + end + end + + # Atomically sets the value of atom to the new value if and only if the + # current value of the atom is identical to the old value and the new + # value successfully validates against the (optional) validator given + # at construction. + # + # @param [Object] old_value The expected current value. + # @param [Object] new_value The intended new value. + # + # @return [Boolean] True if the value is changed else false. + def compare_and_set(old_value, new_value) + if valid?(new_value) && compare_and_set_value(old_value, new_value) + observers.notify_observers(Time.now, old_value, new_value) + true + else + false + end + end + + # Atomically sets the value of atom to the new value without regard for the + # current value so long as the new value successfully validates against the + # (optional) validator given at construction. + # + # @param [Object] new_value The intended new value. + # + # @return [Object] The final value of the atom after all operations and + # validations are complete. + def reset(new_value) + old_value = value + if valid?(new_value) + self.value = new_value + observers.notify_observers(Time.now, old_value, new_value) + new_value + else + old_value + end + end + + private + + # Is the new value valid? + # + # @param [Object] new_value The intended new value. + # @return [Boolean] false if the validator function returns false or raises + # an exception else true + def valid?(new_value) + @Validator.call(new_value) + rescue + false + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/abstract_thread_local_var.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/abstract_thread_local_var.rb new file mode 100644 index 0000000..fcdeed7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/abstract_thread_local_var.rb @@ -0,0 +1,66 @@ +require 'concurrent/constants' + +module Concurrent + + # @!macro thread_local_var + # @!macro internal_implementation_note + # @!visibility private + class AbstractThreadLocalVar + + # @!macro thread_local_var_method_initialize + def initialize(default = nil, &default_block) + if default && block_given? + raise ArgumentError, "Cannot use both value and block as default value" + end + + if block_given? + @default_block = default_block + @default = nil + else + @default_block = nil + @default = default + end + + allocate_storage + end + + # @!macro thread_local_var_method_get + def value + raise NotImplementedError + end + + # @!macro thread_local_var_method_set + def value=(value) + raise NotImplementedError + end + + # @!macro thread_local_var_method_bind + def bind(value, &block) + if block_given? + old_value = self.value + begin + self.value = value + yield + ensure + self.value = old_value + end + end + end + + protected + + # @!visibility private + def allocate_storage + raise NotImplementedError + end + + # @!visibility private + def default + if @default_block + self.value = @default_block.call + else + @default + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_boolean.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_boolean.rb new file mode 100644 index 0000000..0b0373d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_boolean.rb @@ -0,0 +1,126 @@ +require 'concurrent/atomic/mutex_atomic_boolean' +require 'concurrent/synchronization' + +module Concurrent + + ################################################################### + + # @!macro atomic_boolean_method_initialize + # + # Creates a new `AtomicBoolean` with the given initial value. + # + # @param [Boolean] initial the initial value + + # @!macro atomic_boolean_method_value_get + # + # Retrieves the current `Boolean` value. + # + # @return [Boolean] the current value + + # @!macro atomic_boolean_method_value_set + # + # Explicitly sets the value. + # + # @param [Boolean] value the new value to be set + # + # @return [Boolean] the current value + + # @!macro atomic_boolean_method_true_question + # + # Is the current value `true` + # + # @return [Boolean] true if the current value is `true`, else false + + # @!macro atomic_boolean_method_false_question + # + # Is the current value `false` + # + # @return [Boolean] true if the current value is `false`, else false + + # @!macro atomic_boolean_method_make_true + # + # Explicitly sets the value to true. + # + # @return [Boolean] true if value has changed, otherwise false + + # @!macro atomic_boolean_method_make_false + # + # Explicitly sets the value to false. + # + # @return [Boolean] true if value has changed, otherwise false + + ################################################################### + + # @!macro atomic_boolean_public_api + # + # @!method initialize(initial = false) + # @!macro atomic_boolean_method_initialize + # + # @!method value + # @!macro atomic_boolean_method_value_get + # + # @!method value=(value) + # @!macro atomic_boolean_method_value_set + # + # @!method true? + # @!macro atomic_boolean_method_true_question + # + # @!method false? + # @!macro atomic_boolean_method_false_question + # + # @!method make_true + # @!macro atomic_boolean_method_make_true + # + # @!method make_false + # @!macro atomic_boolean_method_make_false + + ################################################################### + + # @!visibility private + # @!macro internal_implementation_note + AtomicBooleanImplementation = case + when defined?(JavaAtomicBoolean) + JavaAtomicBoolean + when defined?(CAtomicBoolean) + CAtomicBoolean + else + MutexAtomicBoolean + end + private_constant :AtomicBooleanImplementation + + # @!macro atomic_boolean + # + # A boolean value that can be updated atomically. Reads and writes to an atomic + # boolean and thread-safe and guaranteed to succeed. Reads and writes may block + # briefly but no explicit locking is required. + # + # @!macro thread_safe_variable_comparison + # + # Performance: + # + # ``` + # Testing with ruby 2.1.2 + # Testing with Concurrent::MutexAtomicBoolean... + # 2.790000 0.000000 2.790000 ( 2.791454) + # Testing with Concurrent::CAtomicBoolean... + # 0.740000 0.000000 0.740000 ( 0.740206) + # + # Testing with jruby 1.9.3 + # Testing with Concurrent::MutexAtomicBoolean... + # 5.240000 2.520000 7.760000 ( 3.683000) + # Testing with Concurrent::JavaAtomicBoolean... + # 3.340000 0.010000 3.350000 ( 0.855000) + # ``` + # + # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html java.util.concurrent.atomic.AtomicBoolean + # + # @!macro atomic_boolean_public_api + class AtomicBoolean < AtomicBooleanImplementation + # @return [String] Short string representation. + def to_s + format '%s value:%s>', super[0..-2], value + end + + alias_method :inspect, :to_s + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_fixnum.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_fixnum.rb new file mode 100644 index 0000000..c67166d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_fixnum.rb @@ -0,0 +1,143 @@ +require 'concurrent/atomic/mutex_atomic_fixnum' +require 'concurrent/synchronization' + +module Concurrent + + ################################################################### + + # @!macro atomic_fixnum_method_initialize + # + # Creates a new `AtomicFixnum` with the given initial value. + # + # @param [Fixnum] initial the initial value + # @raise [ArgumentError] if the initial value is not a `Fixnum` + + # @!macro atomic_fixnum_method_value_get + # + # Retrieves the current `Fixnum` value. + # + # @return [Fixnum] the current value + + # @!macro atomic_fixnum_method_value_set + # + # Explicitly sets the value. + # + # @param [Fixnum] value the new value to be set + # + # @return [Fixnum] the current value + # + # @raise [ArgumentError] if the new value is not a `Fixnum` + + # @!macro atomic_fixnum_method_increment + # + # Increases the current value by the given amount (defaults to 1). + # + # @param [Fixnum] delta the amount by which to increase the current value + # + # @return [Fixnum] the current value after incrementation + + # @!macro atomic_fixnum_method_decrement + # + # Decreases the current value by the given amount (defaults to 1). + # + # @param [Fixnum] delta the amount by which to decrease the current value + # + # @return [Fixnum] the current value after decrementation + + # @!macro atomic_fixnum_method_compare_and_set + # + # Atomically sets the value to the given updated value if the current + # value == the expected value. + # + # @param [Fixnum] expect the expected value + # @param [Fixnum] update the new value + # + # @return [Boolean] true if the value was updated else false + + # @!macro atomic_fixnum_method_update + # + # Pass the current value to the given block, replacing it + # with the block's result. May retry if the value changes + # during the block's execution. + # + # @yield [Object] Calculate a new value for the atomic reference using + # given (old) value + # @yieldparam [Object] old_value the starting value of the atomic reference + # + # @return [Object] the new value + + ################################################################### + + # @!macro atomic_fixnum_public_api + # + # @!method initialize(initial = 0) + # @!macro atomic_fixnum_method_initialize + # + # @!method value + # @!macro atomic_fixnum_method_value_get + # + # @!method value=(value) + # @!macro atomic_fixnum_method_value_set + # + # @!method increment(delta = 1) + # @!macro atomic_fixnum_method_increment + # + # @!method decrement(delta = 1) + # @!macro atomic_fixnum_method_decrement + # + # @!method compare_and_set(expect, update) + # @!macro atomic_fixnum_method_compare_and_set + # + # @!method update + # @!macro atomic_fixnum_method_update + + ################################################################### + + # @!visibility private + # @!macro internal_implementation_note + AtomicFixnumImplementation = case + when defined?(JavaAtomicFixnum) + JavaAtomicFixnum + when defined?(CAtomicFixnum) + CAtomicFixnum + else + MutexAtomicFixnum + end + private_constant :AtomicFixnumImplementation + + # @!macro atomic_fixnum + # + # A numeric value that can be updated atomically. Reads and writes to an atomic + # fixnum and thread-safe and guaranteed to succeed. Reads and writes may block + # briefly but no explicit locking is required. + # + # @!macro thread_safe_variable_comparison + # + # Performance: + # + # ``` + # Testing with ruby 2.1.2 + # Testing with Concurrent::MutexAtomicFixnum... + # 3.130000 0.000000 3.130000 ( 3.136505) + # Testing with Concurrent::CAtomicFixnum... + # 0.790000 0.000000 0.790000 ( 0.785550) + # + # Testing with jruby 1.9.3 + # Testing with Concurrent::MutexAtomicFixnum... + # 5.460000 2.460000 7.920000 ( 3.715000) + # Testing with Concurrent::JavaAtomicFixnum... + # 4.520000 0.030000 4.550000 ( 1.187000) + # ``` + # + # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicLong.html java.util.concurrent.atomic.AtomicLong + # + # @!macro atomic_fixnum_public_api + class AtomicFixnum < AtomicFixnumImplementation + # @return [String] Short string representation. + def to_s + format '%s value:%s>', super[0..-2], value + end + + alias_method :inspect, :to_s + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_markable_reference.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_markable_reference.rb new file mode 100644 index 0000000..f20cd46 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_markable_reference.rb @@ -0,0 +1,164 @@ +module Concurrent + # An atomic reference which maintains an object reference along with a mark bit + # that can be updated atomically. + # + # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicMarkableReference.html + # java.util.concurrent.atomic.AtomicMarkableReference + class AtomicMarkableReference < ::Concurrent::Synchronization::Object + + attr_atomic(:reference) + private :reference, :reference=, :swap_reference, :compare_and_set_reference, :update_reference + + def initialize(value = nil, mark = false) + super() + self.reference = immutable_array(value, mark) + end + + # Atomically sets the value and mark to the given updated value and + # mark given both: + # - the current value == the expected value && + # - the current mark == the expected mark + # + # @param [Object] expected_val the expected value + # @param [Object] new_val the new value + # @param [Boolean] expected_mark the expected mark + # @param [Boolean] new_mark the new mark + # + # @return [Boolean] `true` if successful. A `false` return indicates + # that the actual value was not equal to the expected value or the + # actual mark was not equal to the expected mark + def compare_and_set(expected_val, new_val, expected_mark, new_mark) + # Memoize a valid reference to the current AtomicReference for + # later comparison. + current = reference + curr_val, curr_mark = current + + # Ensure that that the expected marks match. + return false unless expected_mark == curr_mark + + if expected_val.is_a? Numeric + # If the object is a numeric, we need to ensure we are comparing + # the numerical values + return false unless expected_val == curr_val + else + # Otherwise, we need to ensure we are comparing the object identity. + # Theoretically, this could be incorrect if a user monkey-patched + # `Object#equal?`, but they should know that they are playing with + # fire at that point. + return false unless expected_val.equal? curr_val + end + + prospect = immutable_array(new_val, new_mark) + + compare_and_set_reference current, prospect + end + + alias_method :compare_and_swap, :compare_and_set + + # Gets the current reference and marked values. + # + # @return [Array] the current reference and marked values + def get + reference + end + + # Gets the current value of the reference + # + # @return [Object] the current value of the reference + def value + reference[0] + end + + # Gets the current marked value + # + # @return [Boolean] the current marked value + def mark + reference[1] + end + + alias_method :marked?, :mark + + # _Unconditionally_ sets to the given value of both the reference and + # the mark. + # + # @param [Object] new_val the new value + # @param [Boolean] new_mark the new mark + # + # @return [Array] both the new value and the new mark + def set(new_val, new_mark) + self.reference = immutable_array(new_val, new_mark) + end + + # Pass the current value and marked state to the given block, replacing it + # with the block's results. May retry if the value changes during the + # block's execution. + # + # @yield [Object] Calculate a new value and marked state for the atomic + # reference using given (old) value and (old) marked + # @yieldparam [Object] old_val the starting value of the atomic reference + # @yieldparam [Boolean] old_mark the starting state of marked + # + # @return [Array] the new value and new mark + def update + loop do + old_val, old_mark = reference + new_val, new_mark = yield old_val, old_mark + + if compare_and_set old_val, new_val, old_mark, new_mark + return immutable_array(new_val, new_mark) + end + end + end + + # Pass the current value to the given block, replacing it + # with the block's result. Raise an exception if the update + # fails. + # + # @yield [Object] Calculate a new value and marked state for the atomic + # reference using given (old) value and (old) marked + # @yieldparam [Object] old_val the starting value of the atomic reference + # @yieldparam [Boolean] old_mark the starting state of marked + # + # @return [Array] the new value and marked state + # + # @raise [Concurrent::ConcurrentUpdateError] if the update fails + def try_update! + old_val, old_mark = reference + new_val, new_mark = yield old_val, old_mark + + unless compare_and_set old_val, new_val, old_mark, new_mark + fail ::Concurrent::ConcurrentUpdateError, + 'AtomicMarkableReference: Update failed due to race condition.', + 'Note: If you would like to guarantee an update, please use ' + + 'the `AtomicMarkableReference#update` method.' + end + + immutable_array(new_val, new_mark) + end + + # Pass the current value to the given block, replacing it with the + # block's result. Simply return nil if update fails. + # + # @yield [Object] Calculate a new value and marked state for the atomic + # reference using given (old) value and (old) marked + # @yieldparam [Object] old_val the starting value of the atomic reference + # @yieldparam [Boolean] old_mark the starting state of marked + # + # @return [Array] the new value and marked state, or nil if + # the update failed + def try_update + old_val, old_mark = reference + new_val, new_mark = yield old_val, old_mark + + return unless compare_and_set old_val, new_val, old_mark, new_mark + + immutable_array(new_val, new_mark) + end + + private + + def immutable_array(*args) + args.freeze + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_reference.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_reference.rb new file mode 100644 index 0000000..674f866 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/atomic_reference.rb @@ -0,0 +1,205 @@ +require 'concurrent/synchronization' +require 'concurrent/utility/engine' +require 'concurrent/atomic_reference/numeric_cas_wrapper' + +# Shim for TruffleRuby::AtomicReference +if Concurrent.on_truffleruby? && !defined?(TruffleRuby::AtomicReference) + # @!visibility private + module TruffleRuby + AtomicReference = Truffle::AtomicReference + end +end + +module Concurrent + + # Define update methods that use direct paths + # + # @!visibility private + # @!macro internal_implementation_note + module AtomicDirectUpdate + + # @!macro atomic_reference_method_update + # + # Pass the current value to the given block, replacing it + # with the block's result. May retry if the value changes + # during the block's execution. + # + # @yield [Object] Calculate a new value for the atomic reference using + # given (old) value + # @yieldparam [Object] old_value the starting value of the atomic reference + # @return [Object] the new value + def update + true until compare_and_set(old_value = get, new_value = yield(old_value)) + new_value + end + + # @!macro atomic_reference_method_try_update + # + # Pass the current value to the given block, replacing it + # with the block's result. Return nil if the update fails. + # + # @yield [Object] Calculate a new value for the atomic reference using + # given (old) value + # @yieldparam [Object] old_value the starting value of the atomic reference + # @note This method was altered to avoid raising an exception by default. + # Instead, this method now returns `nil` in case of failure. For more info, + # please see: https://github.com/ruby-concurrency/concurrent-ruby/pull/336 + # @return [Object] the new value, or nil if update failed + def try_update + old_value = get + new_value = yield old_value + + return unless compare_and_set old_value, new_value + + new_value + end + + # @!macro atomic_reference_method_try_update! + # + # Pass the current value to the given block, replacing it + # with the block's result. Raise an exception if the update + # fails. + # + # @yield [Object] Calculate a new value for the atomic reference using + # given (old) value + # @yieldparam [Object] old_value the starting value of the atomic reference + # @note This behavior mimics the behavior of the original + # `AtomicReference#try_update` API. The reason this was changed was to + # avoid raising exceptions (which are inherently slow) by default. For more + # info: https://github.com/ruby-concurrency/concurrent-ruby/pull/336 + # @return [Object] the new value + # @raise [Concurrent::ConcurrentUpdateError] if the update fails + def try_update! + old_value = get + new_value = yield old_value + unless compare_and_set(old_value, new_value) + if $VERBOSE + raise ConcurrentUpdateError, "Update failed" + else + raise ConcurrentUpdateError, "Update failed", ConcurrentUpdateError::CONC_UP_ERR_BACKTRACE + end + end + new_value + end + end + + require 'concurrent/atomic_reference/mutex_atomic' + + # @!macro atomic_reference + # + # An object reference that may be updated atomically. All read and write + # operations have java volatile semantic. + # + # @!macro thread_safe_variable_comparison + # + # @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicReference.html + # @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html + # + # @!method initialize(value = nil) + # @!macro atomic_reference_method_initialize + # @param [Object] value The initial value. + # + # @!method get + # @!macro atomic_reference_method_get + # Gets the current value. + # @return [Object] the current value + # + # @!method set(new_value) + # @!macro atomic_reference_method_set + # Sets to the given value. + # @param [Object] new_value the new value + # @return [Object] the new value + # + # @!method get_and_set(new_value) + # @!macro atomic_reference_method_get_and_set + # Atomically sets to the given value and returns the old value. + # @param [Object] new_value the new value + # @return [Object] the old value + # + # @!method compare_and_set(old_value, new_value) + # @!macro atomic_reference_method_compare_and_set + # + # Atomically sets the value to the given updated value if + # the current value == the expected value. + # + # @param [Object] old_value the expected value + # @param [Object] new_value the new value + # + # @return [Boolean] `true` if successful. A `false` return indicates + # that the actual value was not equal to the expected value. + # + # @!method update + # @!macro atomic_reference_method_update + # + # @!method try_update + # @!macro atomic_reference_method_try_update + # + # @!method try_update! + # @!macro atomic_reference_method_try_update! + + + # @!macro internal_implementation_note + class ConcurrentUpdateError < ThreadError + # frozen pre-allocated backtrace to speed ConcurrentUpdateError + CONC_UP_ERR_BACKTRACE = ['backtrace elided; set verbose to enable'].freeze + end + + # @!macro internal_implementation_note + AtomicReferenceImplementation = case + when Concurrent.on_cruby? && Concurrent.c_extensions_loaded? + # @!visibility private + # @!macro internal_implementation_note + class CAtomicReference + include AtomicDirectUpdate + include AtomicNumericCompareAndSetWrapper + alias_method :compare_and_swap, :compare_and_set + end + CAtomicReference + when Concurrent.on_jruby? + # @!visibility private + # @!macro internal_implementation_note + class JavaAtomicReference + include AtomicDirectUpdate + end + JavaAtomicReference + when Concurrent.on_truffleruby? + class TruffleRubyAtomicReference < TruffleRuby::AtomicReference + include AtomicDirectUpdate + alias_method :value, :get + alias_method :value=, :set + alias_method :compare_and_swap, :compare_and_set + alias_method :swap, :get_and_set + end + TruffleRubyAtomicReference + when Concurrent.on_rbx? + # @note Extends `Rubinius::AtomicReference` version adding aliases + # and numeric logic. + # + # @!visibility private + # @!macro internal_implementation_note + class RbxAtomicReference < Rubinius::AtomicReference + alias_method :_compare_and_set, :compare_and_set + include AtomicDirectUpdate + include AtomicNumericCompareAndSetWrapper + alias_method :value, :get + alias_method :value=, :set + alias_method :swap, :get_and_set + alias_method :compare_and_swap, :compare_and_set + end + RbxAtomicReference + else + MutexAtomicReference + end + private_constant :AtomicReferenceImplementation + + # @!macro atomic_reference + class AtomicReference < AtomicReferenceImplementation + + # @return [String] Short string representation. + def to_s + format '%s value:%s>', super[0..-2], get + end + + alias_method :inspect, :to_s + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/count_down_latch.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/count_down_latch.rb new file mode 100644 index 0000000..d883aed --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/count_down_latch.rb @@ -0,0 +1,100 @@ +require 'concurrent/utility/engine' +require 'concurrent/atomic/mutex_count_down_latch' +require 'concurrent/atomic/java_count_down_latch' + +module Concurrent + + ################################################################### + + # @!macro count_down_latch_method_initialize + # + # Create a new `CountDownLatch` with the initial `count`. + # + # @param [new] count the initial count + # + # @raise [ArgumentError] if `count` is not an integer or is less than zero + + # @!macro count_down_latch_method_wait + # + # Block on the latch until the counter reaches zero or until `timeout` is reached. + # + # @param [Fixnum] timeout the number of seconds to wait for the counter or `nil` + # to block indefinitely + # @return [Boolean] `true` if the `count` reaches zero else false on `timeout` + + # @!macro count_down_latch_method_count_down + # + # Signal the latch to decrement the counter. Will signal all blocked threads when + # the `count` reaches zero. + + # @!macro count_down_latch_method_count + # + # The current value of the counter. + # + # @return [Fixnum] the current value of the counter + + ################################################################### + + # @!macro count_down_latch_public_api + # + # @!method initialize(count = 1) + # @!macro count_down_latch_method_initialize + # + # @!method wait(timeout = nil) + # @!macro count_down_latch_method_wait + # + # @!method count_down + # @!macro count_down_latch_method_count_down + # + # @!method count + # @!macro count_down_latch_method_count + + ################################################################### + + # @!visibility private + # @!macro internal_implementation_note + CountDownLatchImplementation = case + when Concurrent.on_jruby? + JavaCountDownLatch + else + MutexCountDownLatch + end + private_constant :CountDownLatchImplementation + + # @!macro count_down_latch + # + # A synchronization object that allows one thread to wait on multiple other threads. + # The thread that will wait creates a `CountDownLatch` and sets the initial value + # (normally equal to the number of other threads). The initiating thread passes the + # latch to the other threads then waits for the other threads by calling the `#wait` + # method. Each of the other threads calls `#count_down` when done with its work. + # When the latch counter reaches zero the waiting thread is unblocked and continues + # with its work. A `CountDownLatch` can be used only once. Its value cannot be reset. + # + # @!macro count_down_latch_public_api + # @example Waiter and Decrementer + # latch = Concurrent::CountDownLatch.new(3) + # + # waiter = Thread.new do + # latch.wait() + # puts ("Waiter released") + # end + # + # decrementer = Thread.new do + # sleep(1) + # latch.count_down + # puts latch.count + # + # sleep(1) + # latch.count_down + # puts latch.count + # + # sleep(1) + # latch.count_down + # puts latch.count + # end + # + # [waiter, decrementer].each(&:join) + class CountDownLatch < CountDownLatchImplementation + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/cyclic_barrier.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/cyclic_barrier.rb new file mode 100644 index 0000000..42f5a94 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/cyclic_barrier.rb @@ -0,0 +1,128 @@ +require 'concurrent/synchronization' +require 'concurrent/utility/native_integer' + +module Concurrent + + # A synchronization aid that allows a set of threads to all wait for each + # other to reach a common barrier point. + # @example + # barrier = Concurrent::CyclicBarrier.new(3) + # jobs = Array.new(3) { |i| -> { sleep i; p done: i } } + # process = -> (i) do + # # waiting to start at the same time + # barrier.wait + # # execute job + # jobs[i].call + # # wait for others to finish + # barrier.wait + # end + # threads = 2.times.map do |i| + # Thread.new(i, &process) + # end + # + # # use main as well + # process.call 2 + # + # # here we can be sure that all jobs are processed + class CyclicBarrier < Synchronization::LockableObject + + # @!visibility private + Generation = Struct.new(:status) + private_constant :Generation + + # Create a new `CyclicBarrier` that waits for `parties` threads + # + # @param [Fixnum] parties the number of parties + # @yield an optional block that will be executed that will be executed after + # the last thread arrives and before the others are released + # + # @raise [ArgumentError] if `parties` is not an integer or is less than zero + def initialize(parties, &block) + Utility::NativeInteger.ensure_integer_and_bounds parties + Utility::NativeInteger.ensure_positive_and_no_zero parties + + super(&nil) + synchronize { ns_initialize parties, &block } + end + + # @return [Fixnum] the number of threads needed to pass the barrier + def parties + synchronize { @parties } + end + + # @return [Fixnum] the number of threads currently waiting on the barrier + def number_waiting + synchronize { @number_waiting } + end + + # Blocks on the barrier until the number of waiting threads is equal to + # `parties` or until `timeout` is reached or `reset` is called + # If a block has been passed to the constructor, it will be executed once by + # the last arrived thread before releasing the others + # @param [Fixnum] timeout the number of seconds to wait for the counter or + # `nil` to block indefinitely + # @return [Boolean] `true` if the `count` reaches zero else false on + # `timeout` or on `reset` or if the barrier is broken + def wait(timeout = nil) + synchronize do + + return false unless @generation.status == :waiting + + @number_waiting += 1 + + if @number_waiting == @parties + @action.call if @action + ns_generation_done @generation, :fulfilled + true + else + generation = @generation + if ns_wait_until(timeout) { generation.status != :waiting } + generation.status == :fulfilled + else + ns_generation_done generation, :broken, false + false + end + end + end + end + + # resets the barrier to its initial state + # If there is at least one waiting thread, it will be woken up, the `wait` + # method will return false and the barrier will be broken + # If the barrier is broken, this method restores it to the original state + # + # @return [nil] + def reset + synchronize { ns_generation_done @generation, :reset } + end + + # A barrier can be broken when: + # - a thread called the `reset` method while at least one other thread was waiting + # - at least one thread timed out on `wait` method + # + # A broken barrier can be restored using `reset` it's safer to create a new one + # @return [Boolean] true if the barrier is broken otherwise false + def broken? + synchronize { @generation.status != :waiting } + end + + protected + + def ns_generation_done(generation, status, continue = true) + generation.status = status + ns_next_generation if continue + ns_broadcast + end + + def ns_next_generation + @generation = Generation.new(:waiting) + @number_waiting = 0 + end + + def ns_initialize(parties, &block) + @parties = parties + @action = block + ns_next_generation + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/event.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/event.rb new file mode 100644 index 0000000..31700ce --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/event.rb @@ -0,0 +1,109 @@ +require 'thread' +require 'concurrent/synchronization' + +module Concurrent + + # Old school kernel-style event reminiscent of Win32 programming in C++. + # + # When an `Event` is created it is in the `unset` state. Threads can choose to + # `#wait` on the event, blocking until released by another thread. When one + # thread wants to alert all blocking threads it calls the `#set` method which + # will then wake up all listeners. Once an `Event` has been set it remains set. + # New threads calling `#wait` will return immediately. An `Event` may be + # `#reset` at any time once it has been set. + # + # @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms682655.aspx + # @example + # event = Concurrent::Event.new + # + # t1 = Thread.new do + # puts "t1 is waiting" + # event.wait(1) + # puts "event occurred" + # end + # + # t2 = Thread.new do + # puts "t2 calling set" + # event.set + # end + # + # [t1, t2].each(&:join) + # + # # prints: + # # t1 is waiting + # # t2 calling set + # # event occurred + class Event < Synchronization::LockableObject + + # Creates a new `Event` in the unset state. Threads calling `#wait` on the + # `Event` will block. + def initialize + super + synchronize { ns_initialize } + end + + # Is the object in the set state? + # + # @return [Boolean] indicating whether or not the `Event` has been set + def set? + synchronize { @set } + end + + # Trigger the event, setting the state to `set` and releasing all threads + # waiting on the event. Has no effect if the `Event` has already been set. + # + # @return [Boolean] should always return `true` + def set + synchronize { ns_set } + end + + def try? + synchronize { @set ? false : ns_set } + end + + # Reset a previously set event back to the `unset` state. + # Has no effect if the `Event` has not yet been set. + # + # @return [Boolean] should always return `true` + def reset + synchronize do + if @set + @set = false + @iteration +=1 + end + true + end + end + + # Wait a given number of seconds for the `Event` to be set by another + # thread. Will wait forever when no `timeout` value is given. Returns + # immediately if the `Event` has already been set. + # + # @return [Boolean] true if the `Event` was set before timeout else false + def wait(timeout = nil) + synchronize do + unless @set + iteration = @iteration + ns_wait_until(timeout) { iteration < @iteration || @set } + else + true + end + end + end + + protected + + def ns_set + unless @set + @set = true + ns_broadcast + end + true + end + + def ns_initialize + @set = false + @iteration = 0 + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/java_count_down_latch.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/java_count_down_latch.rb new file mode 100644 index 0000000..cb5b35a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/java_count_down_latch.rb @@ -0,0 +1,42 @@ +if Concurrent.on_jruby? + + module Concurrent + + # @!macro count_down_latch + # @!visibility private + # @!macro internal_implementation_note + class JavaCountDownLatch + + # @!macro count_down_latch_method_initialize + def initialize(count = 1) + Utility::NativeInteger.ensure_integer_and_bounds(count) + Utility::NativeInteger.ensure_positive(count) + @latch = java.util.concurrent.CountDownLatch.new(count) + end + + # @!macro count_down_latch_method_wait + def wait(timeout = nil) + result = nil + if timeout.nil? + Synchronization::JRuby.sleep_interruptibly { @latch.await } + result = true + else + Synchronization::JRuby.sleep_interruptibly do + result = @latch.await(1000 * timeout, java.util.concurrent.TimeUnit::MILLISECONDS) + end + end + result + end + + # @!macro count_down_latch_method_count_down + def count_down + @latch.countDown + end + + # @!macro count_down_latch_method_count + def count + @latch.getCount + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/java_thread_local_var.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/java_thread_local_var.rb new file mode 100644 index 0000000..b41018f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/java_thread_local_var.rb @@ -0,0 +1,37 @@ +require 'concurrent/atomic/abstract_thread_local_var' + +if Concurrent.on_jruby? + + module Concurrent + + # @!visibility private + # @!macro internal_implementation_note + class JavaThreadLocalVar < AbstractThreadLocalVar + + # @!macro thread_local_var_method_get + def value + value = @var.get + + if value.nil? + default + elsif value == NULL + nil + else + value + end + end + + # @!macro thread_local_var_method_set + def value=(value) + @var.set(value) + end + + protected + + # @!visibility private + def allocate_storage + @var = java.lang.ThreadLocal.new + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_atomic_boolean.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_atomic_boolean.rb new file mode 100644 index 0000000..a033de4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_atomic_boolean.rb @@ -0,0 +1,62 @@ +require 'concurrent/synchronization' + +module Concurrent + + # @!macro atomic_boolean + # @!visibility private + # @!macro internal_implementation_note + class MutexAtomicBoolean < Synchronization::LockableObject + + # @!macro atomic_boolean_method_initialize + def initialize(initial = false) + super() + synchronize { ns_initialize(initial) } + end + + # @!macro atomic_boolean_method_value_get + def value + synchronize { @value } + end + + # @!macro atomic_boolean_method_value_set + def value=(value) + synchronize { @value = !!value } + end + + # @!macro atomic_boolean_method_true_question + def true? + synchronize { @value } + end + + # @!macro atomic_boolean_method_false_question + def false? + synchronize { !@value } + end + + # @!macro atomic_boolean_method_make_true + def make_true + synchronize { ns_make_value(true) } + end + + # @!macro atomic_boolean_method_make_false + def make_false + synchronize { ns_make_value(false) } + end + + protected + + # @!visibility private + def ns_initialize(initial) + @value = !!initial + end + + private + + # @!visibility private + def ns_make_value(value) + old = @value + @value = value + old != @value + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_atomic_fixnum.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_atomic_fixnum.rb new file mode 100644 index 0000000..77b91d2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_atomic_fixnum.rb @@ -0,0 +1,75 @@ +require 'concurrent/synchronization' +require 'concurrent/utility/native_integer' + +module Concurrent + + # @!macro atomic_fixnum + # @!visibility private + # @!macro internal_implementation_note + class MutexAtomicFixnum < Synchronization::LockableObject + + # @!macro atomic_fixnum_method_initialize + def initialize(initial = 0) + super() + synchronize { ns_initialize(initial) } + end + + # @!macro atomic_fixnum_method_value_get + def value + synchronize { @value } + end + + # @!macro atomic_fixnum_method_value_set + def value=(value) + synchronize { ns_set(value) } + end + + # @!macro atomic_fixnum_method_increment + def increment(delta = 1) + synchronize { ns_set(@value + delta.to_i) } + end + + alias_method :up, :increment + + # @!macro atomic_fixnum_method_decrement + def decrement(delta = 1) + synchronize { ns_set(@value - delta.to_i) } + end + + alias_method :down, :decrement + + # @!macro atomic_fixnum_method_compare_and_set + def compare_and_set(expect, update) + synchronize do + if @value == expect.to_i + @value = update.to_i + true + else + false + end + end + end + + # @!macro atomic_fixnum_method_update + def update + synchronize do + @value = yield @value + end + end + + protected + + # @!visibility private + def ns_initialize(initial) + ns_set(initial) + end + + private + + # @!visibility private + def ns_set(value) + Utility::NativeInteger.ensure_integer_and_bounds value + @value = value + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_count_down_latch.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_count_down_latch.rb new file mode 100644 index 0000000..e99744c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_count_down_latch.rb @@ -0,0 +1,44 @@ +require 'concurrent/synchronization' +require 'concurrent/utility/native_integer' + +module Concurrent + + # @!macro count_down_latch + # @!visibility private + # @!macro internal_implementation_note + class MutexCountDownLatch < Synchronization::LockableObject + + # @!macro count_down_latch_method_initialize + def initialize(count = 1) + Utility::NativeInteger.ensure_integer_and_bounds count + Utility::NativeInteger.ensure_positive count + + super() + synchronize { ns_initialize count } + end + + # @!macro count_down_latch_method_wait + def wait(timeout = nil) + synchronize { ns_wait_until(timeout) { @count == 0 } } + end + + # @!macro count_down_latch_method_count_down + def count_down + synchronize do + @count -= 1 if @count > 0 + ns_broadcast if @count == 0 + end + end + + # @!macro count_down_latch_method_count + def count + synchronize { @count } + end + + protected + + def ns_initialize(count) + @count = count + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_semaphore.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_semaphore.rb new file mode 100644 index 0000000..b6ac45f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/mutex_semaphore.rb @@ -0,0 +1,131 @@ +require 'concurrent/synchronization' +require 'concurrent/utility/native_integer' + +module Concurrent + + # @!macro semaphore + # @!visibility private + # @!macro internal_implementation_note + class MutexSemaphore < Synchronization::LockableObject + + # @!macro semaphore_method_initialize + def initialize(count) + Utility::NativeInteger.ensure_integer_and_bounds count + + super() + synchronize { ns_initialize count } + end + + # @!macro semaphore_method_acquire + def acquire(permits = 1) + Utility::NativeInteger.ensure_integer_and_bounds permits + Utility::NativeInteger.ensure_positive permits + + synchronize do + try_acquire_timed(permits, nil) + end + + return unless block_given? + + begin + yield + ensure + release(permits) + end + end + + # @!macro semaphore_method_available_permits + def available_permits + synchronize { @free } + end + + # @!macro semaphore_method_drain_permits + # + # Acquires and returns all permits that are immediately available. + # + # @return [Integer] + def drain_permits + synchronize do + @free.tap { |_| @free = 0 } + end + end + + # @!macro semaphore_method_try_acquire + def try_acquire(permits = 1, timeout = nil) + Utility::NativeInteger.ensure_integer_and_bounds permits + Utility::NativeInteger.ensure_positive permits + + acquired = synchronize do + if timeout.nil? + try_acquire_now(permits) + else + try_acquire_timed(permits, timeout) + end + end + + return acquired unless block_given? + return unless acquired + + begin + yield + ensure + release(permits) + end + end + + # @!macro semaphore_method_release + def release(permits = 1) + Utility::NativeInteger.ensure_integer_and_bounds permits + Utility::NativeInteger.ensure_positive permits + + synchronize do + @free += permits + permits.times { ns_signal } + end + nil + end + + # Shrinks the number of available permits by the indicated reduction. + # + # @param [Fixnum] reduction Number of permits to remove. + # + # @raise [ArgumentError] if `reduction` is not an integer or is negative + # + # @raise [ArgumentError] if `@free` - `@reduction` is less than zero + # + # @return [nil] + # + # @!visibility private + def reduce_permits(reduction) + Utility::NativeInteger.ensure_integer_and_bounds reduction + Utility::NativeInteger.ensure_positive reduction + + synchronize { @free -= reduction } + nil + end + + protected + + # @!visibility private + def ns_initialize(count) + @free = count + end + + private + + # @!visibility private + def try_acquire_now(permits) + if @free >= permits + @free -= permits + true + else + false + end + end + + # @!visibility private + def try_acquire_timed(permits, timeout) + ns_wait_until(timeout) { try_acquire_now(permits) } + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/read_write_lock.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/read_write_lock.rb new file mode 100644 index 0000000..246f21a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/read_write_lock.rb @@ -0,0 +1,254 @@ +require 'thread' +require 'concurrent/atomic/atomic_fixnum' +require 'concurrent/errors' +require 'concurrent/synchronization' + +module Concurrent + + # Ruby read-write lock implementation + # + # Allows any number of concurrent readers, but only one concurrent writer + # (And if the "write" lock is taken, any readers who come along will have to wait) + # + # If readers are already active when a writer comes along, the writer will wait for + # all the readers to finish before going ahead. + # Any additional readers that come when the writer is already waiting, will also + # wait (so writers are not starved). + # + # This implementation is based on `java.util.concurrent.ReentrantReadWriteLock`. + # + # @example + # lock = Concurrent::ReadWriteLock.new + # lock.with_read_lock { data.retrieve } + # lock.with_write_lock { data.modify! } + # + # @note Do **not** try to acquire the write lock while already holding a read lock + # **or** try to acquire the write lock while you already have it. + # This will lead to deadlock + # + # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html java.util.concurrent.ReentrantReadWriteLock + class ReadWriteLock < Synchronization::Object + + # @!visibility private + WAITING_WRITER = 1 << 15 + + # @!visibility private + RUNNING_WRITER = 1 << 29 + + # @!visibility private + MAX_READERS = WAITING_WRITER - 1 + + # @!visibility private + MAX_WRITERS = RUNNING_WRITER - MAX_READERS - 1 + + safe_initialization! + + # Implementation notes: + # A goal is to make the uncontended path for both readers/writers lock-free + # Only if there is reader-writer or writer-writer contention, should locks be used + # Internal state is represented by a single integer ("counter"), and updated + # using atomic compare-and-swap operations + # When the counter is 0, the lock is free + # Each reader increments the counter by 1 when acquiring a read lock + # (and decrements by 1 when releasing the read lock) + # The counter is increased by (1 << 15) for each writer waiting to acquire the + # write lock, and by (1 << 29) if the write lock is taken + + # Create a new `ReadWriteLock` in the unlocked state. + def initialize + super() + @Counter = AtomicFixnum.new(0) # single integer which represents lock state + @ReadLock = Synchronization::Lock.new + @WriteLock = Synchronization::Lock.new + end + + # Execute a block operation within a read lock. + # + # @yield the task to be performed within the lock. + # + # @return [Object] the result of the block operation. + # + # @raise [ArgumentError] when no block is given. + # @raise [Concurrent::ResourceLimitError] if the maximum number of readers + # is exceeded. + def with_read_lock + raise ArgumentError.new('no block given') unless block_given? + acquire_read_lock + begin + yield + ensure + release_read_lock + end + end + + # Execute a block operation within a write lock. + # + # @yield the task to be performed within the lock. + # + # @return [Object] the result of the block operation. + # + # @raise [ArgumentError] when no block is given. + # @raise [Concurrent::ResourceLimitError] if the maximum number of readers + # is exceeded. + def with_write_lock + raise ArgumentError.new('no block given') unless block_given? + acquire_write_lock + begin + yield + ensure + release_write_lock + end + end + + # Acquire a read lock. If a write lock has been acquired will block until + # it is released. Will not block if other read locks have been acquired. + # + # @return [Boolean] true if the lock is successfully acquired + # + # @raise [Concurrent::ResourceLimitError] if the maximum number of readers + # is exceeded. + def acquire_read_lock + while true + c = @Counter.value + raise ResourceLimitError.new('Too many reader threads') if max_readers?(c) + + # If a writer is waiting when we first queue up, we need to wait + if waiting_writer?(c) + @ReadLock.wait_until { !waiting_writer? } + + # after a reader has waited once, they are allowed to "barge" ahead of waiting writers + # but if a writer is *running*, the reader still needs to wait (naturally) + while true + c = @Counter.value + if running_writer?(c) + @ReadLock.wait_until { !running_writer? } + else + return if @Counter.compare_and_set(c, c+1) + end + end + else + break if @Counter.compare_and_set(c, c+1) + end + end + true + end + + # Release a previously acquired read lock. + # + # @return [Boolean] true if the lock is successfully released + def release_read_lock + while true + c = @Counter.value + if @Counter.compare_and_set(c, c-1) + # If one or more writers were waiting, and we were the last reader, wake a writer up + if waiting_writer?(c) && running_readers(c) == 1 + @WriteLock.signal + end + break + end + end + true + end + + # Acquire a write lock. Will block and wait for all active readers and writers. + # + # @return [Boolean] true if the lock is successfully acquired + # + # @raise [Concurrent::ResourceLimitError] if the maximum number of writers + # is exceeded. + def acquire_write_lock + while true + c = @Counter.value + raise ResourceLimitError.new('Too many writer threads') if max_writers?(c) + + if c == 0 # no readers OR writers running + # if we successfully swap the RUNNING_WRITER bit on, then we can go ahead + break if @Counter.compare_and_set(0, RUNNING_WRITER) + elsif @Counter.compare_and_set(c, c+WAITING_WRITER) + while true + # Now we have successfully incremented, so no more readers will be able to increment + # (they will wait instead) + # However, readers OR writers could decrement right here, OR another writer could increment + @WriteLock.wait_until do + # So we have to do another check inside the synchronized section + # If a writer OR reader is running, then go to sleep + c = @Counter.value + !running_writer?(c) && !running_readers?(c) + end + + # We just came out of a wait + # If we successfully turn the RUNNING_WRITER bit on with an atomic swap, + # Then we are OK to stop waiting and go ahead + # Otherwise go back and wait again + c = @Counter.value + break if !running_writer?(c) && !running_readers?(c) && @Counter.compare_and_set(c, c+RUNNING_WRITER-WAITING_WRITER) + end + break + end + end + true + end + + # Release a previously acquired write lock. + # + # @return [Boolean] true if the lock is successfully released + def release_write_lock + return true unless running_writer? + c = @Counter.update { |counter| counter - RUNNING_WRITER } + @ReadLock.broadcast + @WriteLock.signal if waiting_writers(c) > 0 + true + end + + # Queries if the write lock is held by any thread. + # + # @return [Boolean] true if the write lock is held else false` + def write_locked? + @Counter.value >= RUNNING_WRITER + end + + # Queries whether any threads are waiting to acquire the read or write lock. + # + # @return [Boolean] true if any threads are waiting for a lock else false + def has_waiters? + waiting_writer?(@Counter.value) + end + + private + + # @!visibility private + def running_readers(c = @Counter.value) + c & MAX_READERS + end + + # @!visibility private + def running_readers?(c = @Counter.value) + (c & MAX_READERS) > 0 + end + + # @!visibility private + def running_writer?(c = @Counter.value) + c >= RUNNING_WRITER + end + + # @!visibility private + def waiting_writers(c = @Counter.value) + (c & MAX_WRITERS) / WAITING_WRITER + end + + # @!visibility private + def waiting_writer?(c = @Counter.value) + c >= WAITING_WRITER + end + + # @!visibility private + def max_readers?(c = @Counter.value) + (c & MAX_READERS) == MAX_READERS + end + + # @!visibility private + def max_writers?(c = @Counter.value) + (c & MAX_WRITERS) == MAX_WRITERS + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/reentrant_read_write_lock.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/reentrant_read_write_lock.rb new file mode 100644 index 0000000..92c96fd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/reentrant_read_write_lock.rb @@ -0,0 +1,377 @@ +require 'thread' +require 'concurrent/atomic/atomic_reference' +require 'concurrent/errors' +require 'concurrent/synchronization' +require 'concurrent/atomic/thread_local_var' + +module Concurrent + + # Re-entrant read-write lock implementation + # + # Allows any number of concurrent readers, but only one concurrent writer + # (And while the "write" lock is taken, no read locks can be obtained either. + # Hence, the write lock can also be called an "exclusive" lock.) + # + # If another thread has taken a read lock, any thread which wants a write lock + # will block until all the readers release their locks. However, once a thread + # starts waiting to obtain a write lock, any additional readers that come along + # will also wait (so writers are not starved). + # + # A thread can acquire both a read and write lock at the same time. A thread can + # also acquire a read lock OR a write lock more than once. Only when the read (or + # write) lock is released as many times as it was acquired, will the thread + # actually let it go, allowing other threads which might have been waiting + # to proceed. Therefore the lock can be upgraded by first acquiring + # read lock and then write lock and that the lock can be downgraded by first + # having both read and write lock a releasing just the write lock. + # + # If both read and write locks are acquired by the same thread, it is not strictly + # necessary to release them in the same order they were acquired. In other words, + # the following code is legal: + # + # @example + # lock = Concurrent::ReentrantReadWriteLock.new + # lock.acquire_write_lock + # lock.acquire_read_lock + # lock.release_write_lock + # # At this point, the current thread is holding only a read lock, not a write + # # lock. So other threads can take read locks, but not a write lock. + # lock.release_read_lock + # # Now the current thread is not holding either a read or write lock, so + # # another thread could potentially acquire a write lock. + # + # This implementation was inspired by `java.util.concurrent.ReentrantReadWriteLock`. + # + # @example + # lock = Concurrent::ReentrantReadWriteLock.new + # lock.with_read_lock { data.retrieve } + # lock.with_write_lock { data.modify! } + # + # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html java.util.concurrent.ReentrantReadWriteLock + class ReentrantReadWriteLock < Synchronization::Object + + # Implementation notes: + # + # A goal is to make the uncontended path for both readers/writers mutex-free + # Only if there is reader-writer or writer-writer contention, should mutexes be used + # Otherwise, a single CAS operation is all we need to acquire/release a lock + # + # Internal state is represented by a single integer ("counter"), and updated + # using atomic compare-and-swap operations + # When the counter is 0, the lock is free + # Each thread which has one OR MORE read locks increments the counter by 1 + # (and decrements by 1 when releasing the read lock) + # The counter is increased by (1 << 15) for each writer waiting to acquire the + # write lock, and by (1 << 29) if the write lock is taken + # + # Additionally, each thread uses a thread-local variable to count how many times + # it has acquired a read lock, AND how many times it has acquired a write lock. + # It uses a similar trick; an increment of 1 means a read lock was taken, and + # an increment of (1 << 15) means a write lock was taken + # This is what makes re-entrancy possible + # + # 2 rules are followed to ensure good liveness properties: + # 1) Once a writer has queued up and is waiting for a write lock, no other thread + # can take a lock without waiting + # 2) When a write lock is released, readers are given the "first chance" to wake + # up and acquire a read lock + # Following these rules means readers and writers tend to "take turns", so neither + # can starve the other, even under heavy contention + + # @!visibility private + READER_BITS = 15 + # @!visibility private + WRITER_BITS = 14 + + # Used with @Counter: + # @!visibility private + WAITING_WRITER = 1 << READER_BITS + # @!visibility private + RUNNING_WRITER = 1 << (READER_BITS + WRITER_BITS) + # @!visibility private + MAX_READERS = WAITING_WRITER - 1 + # @!visibility private + MAX_WRITERS = RUNNING_WRITER - MAX_READERS - 1 + + # Used with @HeldCount: + # @!visibility private + WRITE_LOCK_HELD = 1 << READER_BITS + # @!visibility private + READ_LOCK_MASK = WRITE_LOCK_HELD - 1 + # @!visibility private + WRITE_LOCK_MASK = MAX_WRITERS + + safe_initialization! + + # Create a new `ReentrantReadWriteLock` in the unlocked state. + def initialize + super() + @Counter = AtomicFixnum.new(0) # single integer which represents lock state + @ReadQueue = Synchronization::Lock.new # used to queue waiting readers + @WriteQueue = Synchronization::Lock.new # used to queue waiting writers + @HeldCount = ThreadLocalVar.new(0) # indicates # of R & W locks held by this thread + end + + # Execute a block operation within a read lock. + # + # @yield the task to be performed within the lock. + # + # @return [Object] the result of the block operation. + # + # @raise [ArgumentError] when no block is given. + # @raise [Concurrent::ResourceLimitError] if the maximum number of readers + # is exceeded. + def with_read_lock + raise ArgumentError.new('no block given') unless block_given? + acquire_read_lock + begin + yield + ensure + release_read_lock + end + end + + # Execute a block operation within a write lock. + # + # @yield the task to be performed within the lock. + # + # @return [Object] the result of the block operation. + # + # @raise [ArgumentError] when no block is given. + # @raise [Concurrent::ResourceLimitError] if the maximum number of readers + # is exceeded. + def with_write_lock + raise ArgumentError.new('no block given') unless block_given? + acquire_write_lock + begin + yield + ensure + release_write_lock + end + end + + # Acquire a read lock. If a write lock is held by another thread, will block + # until it is released. + # + # @return [Boolean] true if the lock is successfully acquired + # + # @raise [Concurrent::ResourceLimitError] if the maximum number of readers + # is exceeded. + def acquire_read_lock + if (held = @HeldCount.value) > 0 + # If we already have a lock, there's no need to wait + if held & READ_LOCK_MASK == 0 + # But we do need to update the counter, if we were holding a write + # lock but not a read lock + @Counter.update { |c| c + 1 } + end + @HeldCount.value = held + 1 + return true + end + + while true + c = @Counter.value + raise ResourceLimitError.new('Too many reader threads') if max_readers?(c) + + # If a writer is waiting OR running when we first queue up, we need to wait + if waiting_or_running_writer?(c) + # Before going to sleep, check again with the ReadQueue mutex held + @ReadQueue.synchronize do + @ReadQueue.ns_wait if waiting_or_running_writer? + end + # Note: the above 'synchronize' block could have used #wait_until, + # but that waits repeatedly in a loop, checking the wait condition + # each time it wakes up (to protect against spurious wakeups) + # But we are already in a loop, which is only broken when we successfully + # acquire the lock! So we don't care about spurious wakeups, and would + # rather not pay the extra overhead of using #wait_until + + # After a reader has waited once, they are allowed to "barge" ahead of waiting writers + # But if a writer is *running*, the reader still needs to wait (naturally) + while true + c = @Counter.value + if running_writer?(c) + @ReadQueue.synchronize do + @ReadQueue.ns_wait if running_writer? + end + elsif @Counter.compare_and_set(c, c+1) + @HeldCount.value = held + 1 + return true + end + end + elsif @Counter.compare_and_set(c, c+1) + @HeldCount.value = held + 1 + return true + end + end + end + + # Try to acquire a read lock and return true if we succeed. If it cannot be + # acquired immediately, return false. + # + # @return [Boolean] true if the lock is successfully acquired + def try_read_lock + if (held = @HeldCount.value) > 0 + if held & READ_LOCK_MASK == 0 + # If we hold a write lock, but not a read lock... + @Counter.update { |c| c + 1 } + end + @HeldCount.value = held + 1 + return true + else + c = @Counter.value + if !waiting_or_running_writer?(c) && @Counter.compare_and_set(c, c+1) + @HeldCount.value = held + 1 + return true + end + end + false + end + + # Release a previously acquired read lock. + # + # @return [Boolean] true if the lock is successfully released + def release_read_lock + held = @HeldCount.value = @HeldCount.value - 1 + rlocks_held = held & READ_LOCK_MASK + if rlocks_held == 0 + c = @Counter.update { |counter| counter - 1 } + # If one or more writers were waiting, and we were the last reader, wake a writer up + if waiting_or_running_writer?(c) && running_readers(c) == 0 + @WriteQueue.signal + end + elsif rlocks_held == READ_LOCK_MASK + raise IllegalOperationError, "Cannot release a read lock which is not held" + end + true + end + + # Acquire a write lock. Will block and wait for all active readers and writers. + # + # @return [Boolean] true if the lock is successfully acquired + # + # @raise [Concurrent::ResourceLimitError] if the maximum number of writers + # is exceeded. + def acquire_write_lock + if (held = @HeldCount.value) >= WRITE_LOCK_HELD + # if we already have a write (exclusive) lock, there's no need to wait + @HeldCount.value = held + WRITE_LOCK_HELD + return true + end + + while true + c = @Counter.value + raise ResourceLimitError.new('Too many writer threads') if max_writers?(c) + + # To go ahead and take the lock without waiting, there must be no writer + # running right now, AND no writers who came before us still waiting to + # acquire the lock + # Additionally, if any read locks have been taken, we must hold all of them + if held > 0 && @Counter.compare_and_set(1, c+RUNNING_WRITER) + # If we are the only one reader and successfully swap the RUNNING_WRITER bit on, then we can go ahead + @HeldCount.value = held + WRITE_LOCK_HELD + return true + elsif @Counter.compare_and_set(c, c+WAITING_WRITER) + while true + # Now we have successfully incremented, so no more readers will be able to increment + # (they will wait instead) + # However, readers OR writers could decrement right here + @WriteQueue.synchronize do + # So we have to do another check inside the synchronized section + # If a writer OR another reader is running, then go to sleep + c = @Counter.value + @WriteQueue.ns_wait if running_writer?(c) || running_readers(c) != held + end + # Note: if you are thinking of replacing the above 'synchronize' block + # with #wait_until, read the comment in #acquire_read_lock first! + + # We just came out of a wait + # If we successfully turn the RUNNING_WRITER bit on with an atomic swap, + # then we are OK to stop waiting and go ahead + # Otherwise go back and wait again + c = @Counter.value + if !running_writer?(c) && + running_readers(c) == held && + @Counter.compare_and_set(c, c+RUNNING_WRITER-WAITING_WRITER) + @HeldCount.value = held + WRITE_LOCK_HELD + return true + end + end + end + end + end + + # Try to acquire a write lock and return true if we succeed. If it cannot be + # acquired immediately, return false. + # + # @return [Boolean] true if the lock is successfully acquired + def try_write_lock + if (held = @HeldCount.value) >= WRITE_LOCK_HELD + @HeldCount.value = held + WRITE_LOCK_HELD + return true + else + c = @Counter.value + if !waiting_or_running_writer?(c) && + running_readers(c) == held && + @Counter.compare_and_set(c, c+RUNNING_WRITER) + @HeldCount.value = held + WRITE_LOCK_HELD + return true + end + end + false + end + + # Release a previously acquired write lock. + # + # @return [Boolean] true if the lock is successfully released + def release_write_lock + held = @HeldCount.value = @HeldCount.value - WRITE_LOCK_HELD + wlocks_held = held & WRITE_LOCK_MASK + if wlocks_held == 0 + c = @Counter.update { |counter| counter - RUNNING_WRITER } + @ReadQueue.broadcast + @WriteQueue.signal if waiting_writers(c) > 0 + elsif wlocks_held == WRITE_LOCK_MASK + raise IllegalOperationError, "Cannot release a write lock which is not held" + end + true + end + + private + + # @!visibility private + def running_readers(c = @Counter.value) + c & MAX_READERS + end + + # @!visibility private + def running_readers?(c = @Counter.value) + (c & MAX_READERS) > 0 + end + + # @!visibility private + def running_writer?(c = @Counter.value) + c >= RUNNING_WRITER + end + + # @!visibility private + def waiting_writers(c = @Counter.value) + (c & MAX_WRITERS) >> READER_BITS + end + + # @!visibility private + def waiting_or_running_writer?(c = @Counter.value) + c >= WAITING_WRITER + end + + # @!visibility private + def max_readers?(c = @Counter.value) + (c & MAX_READERS) == MAX_READERS + end + + # @!visibility private + def max_writers?(c = @Counter.value) + (c & MAX_WRITERS) == MAX_WRITERS + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/ruby_thread_local_var.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/ruby_thread_local_var.rb new file mode 100644 index 0000000..9a51eb2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/ruby_thread_local_var.rb @@ -0,0 +1,181 @@ +require 'thread' +require 'concurrent/atomic/abstract_thread_local_var' + +module Concurrent + + # @!visibility private + # @!macro internal_implementation_note + class RubyThreadLocalVar < AbstractThreadLocalVar + + # Each thread has a (lazily initialized) array of thread-local variable values + # Each time a new thread-local var is created, we allocate an "index" for it + # For example, if the allocated index is 1, that means slot #1 in EVERY + # thread's thread-local array will be used for the value of that TLV + # + # The good thing about using a per-THREAD structure to hold values, rather + # than a per-TLV structure, is that no synchronization is needed when + # reading and writing those values (since the structure is only ever + # accessed by a single thread) + # + # Of course, when a TLV is GC'd, 1) we need to recover its index for use + # by other new TLVs (otherwise the thread-local arrays could get bigger + # and bigger with time), and 2) we need to null out all the references + # held in the now-unused slots (both to avoid blocking GC of those objects, + # and also to prevent "stale" values from being passed on to a new TLV + # when the index is reused) + # Because we need to null out freed slots, we need to keep references to + # ALL the thread-local arrays -- ARRAYS is for that + # But when a Thread is GC'd, we need to drop the reference to its thread-local + # array, so we don't leak memory + + FREE = [] + LOCK = Mutex.new + THREAD_LOCAL_ARRAYS = {} # used as a hash set + + # synchronize when not on MRI + # on MRI using lock in finalizer leads to "can't be called from trap context" error + # so the code is carefully written to be tread-safe on MRI relying on GIL + + if Concurrent.on_cruby? + # @!visibility private + def self.semi_sync(&block) + block.call + end + else + # @!visibility private + def self.semi_sync(&block) + LOCK.synchronize(&block) + end + end + + private_constant :FREE, :LOCK, :THREAD_LOCAL_ARRAYS + + # @!macro thread_local_var_method_get + def value + if (array = get_threadlocal_array) + value = array[@index] + if value.nil? + default + elsif value.equal?(NULL) + nil + else + value + end + else + default + end + end + + # @!macro thread_local_var_method_set + def value=(value) + me = Thread.current + # We could keep the thread-local arrays in a hash, keyed by Thread + # But why? That would require locking + # Using Ruby's built-in thread-local storage is faster + unless (array = get_threadlocal_array(me)) + array = set_threadlocal_array([], me) + self.class.semi_sync { THREAD_LOCAL_ARRAYS[array.object_id] = array } + ObjectSpace.define_finalizer(me, self.class.thread_finalizer(array.object_id)) + end + array[@index] = (value.nil? ? NULL : value) + value + end + + protected + + # @!visibility private + def allocate_storage + @index = FREE.pop || next_index + + ObjectSpace.define_finalizer(self, self.class.thread_local_finalizer(@index)) + end + + # @!visibility private + def self.thread_local_finalizer(index) + proc do + semi_sync do + # The cost of GC'ing a TLV is linear in the number of threads using TLVs + # But that is natural! More threads means more storage is used per TLV + # So naturally more CPU time is required to free more storage + # + # DO NOT use each_value which might conflict with new pair assignment + # into the hash in #value= method + THREAD_LOCAL_ARRAYS.values.each { |array| array[index] = nil } + # free index has to be published after the arrays are cleared + FREE.push(index) + end + end + end + + # @!visibility private + def self.thread_finalizer(id) + proc do + semi_sync do + # The thread which used this thread-local array is now gone + # So don't hold onto a reference to the array (thus blocking GC) + THREAD_LOCAL_ARRAYS.delete(id) + end + end + end + + private + + # noinspection RubyClassVariableUsageInspection + @@next = 0 + # noinspection RubyClassVariableUsageInspection + def next_index + LOCK.synchronize do + result = @@next + @@next += 1 + result + end + end + + if Thread.instance_methods.include?(:thread_variable_get) + + def get_threadlocal_array(thread = Thread.current) + thread.thread_variable_get(:__threadlocal_array__) + end + + def set_threadlocal_array(array, thread = Thread.current) + thread.thread_variable_set(:__threadlocal_array__, array) + end + + else + + def get_threadlocal_array(thread = Thread.current) + thread[:__threadlocal_array__] + end + + def set_threadlocal_array(array, thread = Thread.current) + thread[:__threadlocal_array__] = array + end + end + + # This exists only for use in testing + # @!visibility private + def value_for(thread) + if (array = get_threadlocal_array(thread)) + value = array[@index] + if value.nil? + get_default + elsif value.equal?(NULL) + nil + else + value + end + else + get_default + end + end + + # @!visibility private + def get_default + if @default_block + raise "Cannot use default_for with default block" + else + @default + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/semaphore.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/semaphore.rb new file mode 100644 index 0000000..cc6a892 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/semaphore.rb @@ -0,0 +1,166 @@ +require 'concurrent/atomic/mutex_semaphore' +require 'concurrent/synchronization' + +module Concurrent + + ################################################################### + + # @!macro semaphore_method_initialize + # + # Create a new `Semaphore` with the initial `count`. + # + # @param [Fixnum] count the initial count + # + # @raise [ArgumentError] if `count` is not an integer or is less than zero + + # @!macro semaphore_method_acquire + # + # Acquires the given number of permits from this semaphore, + # blocking until all are available. If a block is given, + # yields to it and releases the permits afterwards. + # + # @param [Fixnum] permits Number of permits to acquire + # + # @raise [ArgumentError] if `permits` is not an integer or is less than + # one + # + # @return [nil, BasicObject] Without a block, `nil` is returned. If a block + # is given, its return value is returned. + + # @!macro semaphore_method_available_permits + # + # Returns the current number of permits available in this semaphore. + # + # @return [Integer] + + # @!macro semaphore_method_drain_permits + # + # Acquires and returns all permits that are immediately available. + # + # @return [Integer] + + # @!macro semaphore_method_try_acquire + # + # Acquires the given number of permits from this semaphore, + # only if all are available at the time of invocation or within + # `timeout` interval. If a block is given, yields to it if the permits + # were successfully acquired, and releases them afterward, returning the + # block's return value. + # + # @param [Fixnum] permits the number of permits to acquire + # + # @param [Fixnum] timeout the number of seconds to wait for the counter + # or `nil` to return immediately + # + # @raise [ArgumentError] if `permits` is not an integer or is less than + # one + # + # @return [true, false, nil, BasicObject] `false` if no permits are + # available, `true` when acquired a permit. If a block is given, the + # block's return value is returned if the permits were acquired; if not, + # `nil` is returned. + + # @!macro semaphore_method_release + # + # Releases the given number of permits, returning them to the semaphore. + # + # @param [Fixnum] permits Number of permits to return to the semaphore. + # + # @raise [ArgumentError] if `permits` is not a number or is less than one + # + # @return [nil] + + ################################################################### + + # @!macro semaphore_public_api + # + # @!method initialize(count) + # @!macro semaphore_method_initialize + # + # @!method acquire(permits = 1) + # @!macro semaphore_method_acquire + # + # @!method available_permits + # @!macro semaphore_method_available_permits + # + # @!method drain_permits + # @!macro semaphore_method_drain_permits + # + # @!method try_acquire(permits = 1, timeout = nil) + # @!macro semaphore_method_try_acquire + # + # @!method release(permits = 1) + # @!macro semaphore_method_release + + ################################################################### + + # @!visibility private + # @!macro internal_implementation_note + SemaphoreImplementation = case + when defined?(JavaSemaphore) + JavaSemaphore + else + MutexSemaphore + end + private_constant :SemaphoreImplementation + + # @!macro semaphore + # + # A counting semaphore. Conceptually, a semaphore maintains a set of + # permits. Each {#acquire} blocks if necessary until a permit is + # available, and then takes it. Each {#release} adds a permit, potentially + # releasing a blocking acquirer. + # However, no actual permit objects are used; the Semaphore just keeps a + # count of the number available and acts accordingly. + # Alternatively, permits may be acquired within a block, and automatically + # released after the block finishes executing. + # + # @!macro semaphore_public_api + # @example + # semaphore = Concurrent::Semaphore.new(2) + # + # t1 = Thread.new do + # semaphore.acquire + # puts "Thread 1 acquired semaphore" + # end + # + # t2 = Thread.new do + # semaphore.acquire + # puts "Thread 2 acquired semaphore" + # end + # + # t3 = Thread.new do + # semaphore.acquire + # puts "Thread 3 acquired semaphore" + # end + # + # t4 = Thread.new do + # sleep(2) + # puts "Thread 4 releasing semaphore" + # semaphore.release + # end + # + # [t1, t2, t3, t4].each(&:join) + # + # # prints: + # # Thread 3 acquired semaphore + # # Thread 2 acquired semaphore + # # Thread 4 releasing semaphore + # # Thread 1 acquired semaphore + # + # @example + # semaphore = Concurrent::Semaphore.new(1) + # + # puts semaphore.available_permits + # semaphore.acquire do + # puts semaphore.available_permits + # end + # puts semaphore.available_permits + # + # # prints: + # # 1 + # # 0 + # # 1 + class Semaphore < SemaphoreImplementation + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/thread_local_var.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/thread_local_var.rb new file mode 100644 index 0000000..100cc8d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic/thread_local_var.rb @@ -0,0 +1,104 @@ +require 'concurrent/utility/engine' +require 'concurrent/atomic/ruby_thread_local_var' +require 'concurrent/atomic/java_thread_local_var' + +module Concurrent + + ################################################################### + + # @!macro thread_local_var_method_initialize + # + # Creates a thread local variable. + # + # @param [Object] default the default value when otherwise unset + # @param [Proc] default_block Optional block that gets called to obtain the + # default value for each thread + + # @!macro thread_local_var_method_get + # + # Returns the value in the current thread's copy of this thread-local variable. + # + # @return [Object] the current value + + # @!macro thread_local_var_method_set + # + # Sets the current thread's copy of this thread-local variable to the specified value. + # + # @param [Object] value the value to set + # @return [Object] the new value + + # @!macro thread_local_var_method_bind + # + # Bind the given value to thread local storage during + # execution of the given block. + # + # @param [Object] value the value to bind + # @yield the operation to be performed with the bound variable + # @return [Object] the value + + + ################################################################### + + # @!macro thread_local_var_public_api + # + # @!method initialize(default = nil, &default_block) + # @!macro thread_local_var_method_initialize + # + # @!method value + # @!macro thread_local_var_method_get + # + # @!method value=(value) + # @!macro thread_local_var_method_set + # + # @!method bind(value, &block) + # @!macro thread_local_var_method_bind + + ################################################################### + + # @!visibility private + # @!macro internal_implementation_note + ThreadLocalVarImplementation = case + when Concurrent.on_jruby? + JavaThreadLocalVar + else + RubyThreadLocalVar + end + private_constant :ThreadLocalVarImplementation + + # @!macro thread_local_var + # + # A `ThreadLocalVar` is a variable where the value is different for each thread. + # Each variable may have a default value, but when you modify the variable only + # the current thread will ever see that change. + # + # @!macro thread_safe_variable_comparison + # + # @example + # v = ThreadLocalVar.new(14) + # v.value #=> 14 + # v.value = 2 + # v.value #=> 2 + # + # @example + # v = ThreadLocalVar.new(14) + # + # t1 = Thread.new do + # v.value #=> 14 + # v.value = 1 + # v.value #=> 1 + # end + # + # t2 = Thread.new do + # v.value #=> 14 + # v.value = 2 + # v.value #=> 2 + # end + # + # v.value #=> 14 + # + # @see https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html Java ThreadLocal + # + # @!macro thread_local_var_public_api + class ThreadLocalVar < ThreadLocalVarImplementation + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic_reference/mutex_atomic.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic_reference/mutex_atomic.rb new file mode 100644 index 0000000..d092aed --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic_reference/mutex_atomic.rb @@ -0,0 +1,56 @@ +module Concurrent + + # @!visibility private + # @!macro internal_implementation_note + class MutexAtomicReference < Synchronization::LockableObject + include AtomicDirectUpdate + include AtomicNumericCompareAndSetWrapper + alias_method :compare_and_swap, :compare_and_set + + # @!macro atomic_reference_method_initialize + def initialize(value = nil) + super() + synchronize { ns_initialize(value) } + end + + # @!macro atomic_reference_method_get + def get + synchronize { @value } + end + alias_method :value, :get + + # @!macro atomic_reference_method_set + def set(new_value) + synchronize { @value = new_value } + end + alias_method :value=, :set + + # @!macro atomic_reference_method_get_and_set + def get_and_set(new_value) + synchronize do + old_value = @value + @value = new_value + old_value + end + end + alias_method :swap, :get_and_set + + # @!macro atomic_reference_method_compare_and_set + def _compare_and_set(old_value, new_value) + synchronize do + if @value.equal? old_value + @value = new_value + true + else + false + end + end + end + + protected + + def ns_initialize(value) + @value = value + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic_reference/numeric_cas_wrapper.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic_reference/numeric_cas_wrapper.rb new file mode 100644 index 0000000..709a382 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomic_reference/numeric_cas_wrapper.rb @@ -0,0 +1,28 @@ +module Concurrent + + # Special "compare and set" handling of numeric values. + # + # @!visibility private + # @!macro internal_implementation_note + module AtomicNumericCompareAndSetWrapper + + # @!macro atomic_reference_method_compare_and_set + def compare_and_set(old_value, new_value) + if old_value.kind_of? Numeric + while true + old = get + + return false unless old.kind_of? Numeric + + return false unless old == old_value + + result = _compare_and_set(old, new_value) + return result if result + end + else + _compare_and_set(old_value, new_value) + end + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomics.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomics.rb new file mode 100644 index 0000000..16cbe66 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/atomics.rb @@ -0,0 +1,10 @@ +require 'concurrent/atomic/atomic_reference' +require 'concurrent/atomic/atomic_boolean' +require 'concurrent/atomic/atomic_fixnum' +require 'concurrent/atomic/cyclic_barrier' +require 'concurrent/atomic/count_down_latch' +require 'concurrent/atomic/event' +require 'concurrent/atomic/read_write_lock' +require 'concurrent/atomic/reentrant_read_write_lock' +require 'concurrent/atomic/semaphore' +require 'concurrent/atomic/thread_local_var' diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/copy_on_notify_observer_set.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/copy_on_notify_observer_set.rb new file mode 100644 index 0000000..50d52a6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/copy_on_notify_observer_set.rb @@ -0,0 +1,107 @@ +require 'concurrent/synchronization' + +module Concurrent + module Collection + + # A thread safe observer set implemented using copy-on-read approach: + # observers are added and removed from a thread safe collection; every time + # a notification is required the internal data structure is copied to + # prevent concurrency issues + # + # @api private + class CopyOnNotifyObserverSet < Synchronization::LockableObject + + def initialize + super() + synchronize { ns_initialize } + end + + # @!macro observable_add_observer + def add_observer(observer = nil, func = :update, &block) + if observer.nil? && block.nil? + raise ArgumentError, 'should pass observer as a first argument or block' + elsif observer && block + raise ArgumentError.new('cannot provide both an observer and a block') + end + + if block + observer = block + func = :call + end + + synchronize do + @observers[observer] = func + observer + end + end + + # @!macro observable_delete_observer + def delete_observer(observer) + synchronize do + @observers.delete(observer) + observer + end + end + + # @!macro observable_delete_observers + def delete_observers + synchronize do + @observers.clear + self + end + end + + # @!macro observable_count_observers + def count_observers + synchronize { @observers.count } + end + + # Notifies all registered observers with optional args + # @param [Object] args arguments to be passed to each observer + # @return [CopyOnWriteObserverSet] self + def notify_observers(*args, &block) + observers = duplicate_observers + notify_to(observers, *args, &block) + self + end + + # Notifies all registered observers with optional args and deletes them. + # + # @param [Object] args arguments to be passed to each observer + # @return [CopyOnWriteObserverSet] self + def notify_and_delete_observers(*args, &block) + observers = duplicate_and_clear_observers + notify_to(observers, *args, &block) + self + end + + protected + + def ns_initialize + @observers = {} + end + + private + + def duplicate_and_clear_observers + synchronize do + observers = @observers.dup + @observers.clear + observers + end + end + + def duplicate_observers + synchronize { @observers.dup } + end + + def notify_to(observers, *args) + raise ArgumentError.new('cannot give arguments and a block') if block_given? && !args.empty? + observers.each do |observer, function| + args = yield if block_given? + observer.send(function, *args) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/copy_on_write_observer_set.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/copy_on_write_observer_set.rb new file mode 100644 index 0000000..3f3f7cc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/copy_on_write_observer_set.rb @@ -0,0 +1,111 @@ +require 'concurrent/synchronization' + +module Concurrent + module Collection + + # A thread safe observer set implemented using copy-on-write approach: + # every time an observer is added or removed the whole internal data structure is + # duplicated and replaced with a new one. + # + # @api private + class CopyOnWriteObserverSet < Synchronization::LockableObject + + def initialize + super() + synchronize { ns_initialize } + end + + # @!macro observable_add_observer + def add_observer(observer = nil, func = :update, &block) + if observer.nil? && block.nil? + raise ArgumentError, 'should pass observer as a first argument or block' + elsif observer && block + raise ArgumentError.new('cannot provide both an observer and a block') + end + + if block + observer = block + func = :call + end + + synchronize do + new_observers = @observers.dup + new_observers[observer] = func + @observers = new_observers + observer + end + end + + # @!macro observable_delete_observer + def delete_observer(observer) + synchronize do + new_observers = @observers.dup + new_observers.delete(observer) + @observers = new_observers + observer + end + end + + # @!macro observable_delete_observers + def delete_observers + self.observers = {} + self + end + + # @!macro observable_count_observers + def count_observers + observers.count + end + + # Notifies all registered observers with optional args + # @param [Object] args arguments to be passed to each observer + # @return [CopyOnWriteObserverSet] self + def notify_observers(*args, &block) + notify_to(observers, *args, &block) + self + end + + # Notifies all registered observers with optional args and deletes them. + # + # @param [Object] args arguments to be passed to each observer + # @return [CopyOnWriteObserverSet] self + def notify_and_delete_observers(*args, &block) + old = clear_observers_and_return_old + notify_to(old, *args, &block) + self + end + + protected + + def ns_initialize + @observers = {} + end + + private + + def notify_to(observers, *args) + raise ArgumentError.new('cannot give arguments and a block') if block_given? && !args.empty? + observers.each do |observer, function| + args = yield if block_given? + observer.send(function, *args) + end + end + + def observers + synchronize { @observers } + end + + def observers=(new_set) + synchronize { @observers = new_set } + end + + def clear_observers_and_return_old + synchronize do + old_observers = @observers + @observers = {} + old_observers + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/java_non_concurrent_priority_queue.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/java_non_concurrent_priority_queue.rb new file mode 100644 index 0000000..2be9e43 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/java_non_concurrent_priority_queue.rb @@ -0,0 +1,84 @@ +if Concurrent.on_jruby? + + module Concurrent + module Collection + + + # @!macro priority_queue + # + # @!visibility private + # @!macro internal_implementation_note + class JavaNonConcurrentPriorityQueue + + # @!macro priority_queue_method_initialize + def initialize(opts = {}) + order = opts.fetch(:order, :max) + if [:min, :low].include?(order) + @queue = java.util.PriorityQueue.new(11) # 11 is the default initial capacity + else + @queue = java.util.PriorityQueue.new(11, java.util.Collections.reverseOrder()) + end + end + + # @!macro priority_queue_method_clear + def clear + @queue.clear + true + end + + # @!macro priority_queue_method_delete + def delete(item) + found = false + while @queue.remove(item) do + found = true + end + found + end + + # @!macro priority_queue_method_empty + def empty? + @queue.size == 0 + end + + # @!macro priority_queue_method_include + def include?(item) + @queue.contains(item) + end + alias_method :has_priority?, :include? + + # @!macro priority_queue_method_length + def length + @queue.size + end + alias_method :size, :length + + # @!macro priority_queue_method_peek + def peek + @queue.peek + end + + # @!macro priority_queue_method_pop + def pop + @queue.poll + end + alias_method :deq, :pop + alias_method :shift, :pop + + # @!macro priority_queue_method_push + def push(item) + raise ArgumentError.new('cannot enqueue nil') if item.nil? + @queue.add(item) + end + alias_method :<<, :push + alias_method :enq, :push + + # @!macro priority_queue_method_from_list + def self.from_list(list, opts = {}) + queue = new(opts) + list.each{|item| queue << item } + queue + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/lock_free_stack.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/lock_free_stack.rb new file mode 100644 index 0000000..d003d3c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/lock_free_stack.rb @@ -0,0 +1,158 @@ +module Concurrent + + # @!macro warn.edge + class LockFreeStack < Synchronization::Object + + safe_initialization! + + class Node + # TODO (pitr-ch 20-Dec-2016): Could be unified with Stack class? + + # @return [Node] + attr_reader :next_node + + # @return [Object] + attr_reader :value + + # @!visibility private + # allow to nil-ify to free GC when the entry is no longer relevant, not synchronised + attr_writer :value + + def initialize(value, next_node) + @value = value + @next_node = next_node + end + + singleton_class.send :alias_method, :[], :new + end + + # The singleton for empty node + EMPTY = Node[nil, nil] + def EMPTY.next_node + self + end + + attr_atomic(:head) + private :head, :head=, :swap_head, :compare_and_set_head, :update_head + + # @!visibility private + def self.of1(value) + new Node[value, EMPTY] + end + + # @!visibility private + def self.of2(value1, value2) + new Node[value1, Node[value2, EMPTY]] + end + + # @param [Node] head + def initialize(head = EMPTY) + super() + self.head = head + end + + # @param [Node] head + # @return [true, false] + def empty?(head = head()) + head.equal? EMPTY + end + + # @param [Node] head + # @param [Object] value + # @return [true, false] + def compare_and_push(head, value) + compare_and_set_head head, Node[value, head] + end + + # @param [Object] value + # @return [self] + def push(value) + while true + current_head = head + return self if compare_and_set_head current_head, Node[value, current_head] + end + end + + # @return [Node] + def peek + head + end + + # @param [Node] head + # @return [true, false] + def compare_and_pop(head) + compare_and_set_head head, head.next_node + end + + # @return [Object] + def pop + while true + current_head = head + return current_head.value if compare_and_set_head current_head, current_head.next_node + end + end + + # @param [Node] head + # @return [true, false] + def compare_and_clear(head) + compare_and_set_head head, EMPTY + end + + include Enumerable + + # @param [Node] head + # @return [self] + def each(head = nil) + return to_enum(:each, head) unless block_given? + it = head || peek + until it.equal?(EMPTY) + yield it.value + it = it.next_node + end + self + end + + # @return [true, false] + def clear + while true + current_head = head + return false if current_head == EMPTY + return true if compare_and_set_head current_head, EMPTY + end + end + + # @param [Node] head + # @return [true, false] + def clear_if(head) + compare_and_set_head head, EMPTY + end + + # @param [Node] head + # @param [Node] new_head + # @return [true, false] + def replace_if(head, new_head) + compare_and_set_head head, new_head + end + + # @return [self] + # @yield over the cleared stack + # @yieldparam [Object] value + def clear_each(&block) + while true + current_head = head + return self if current_head == EMPTY + if compare_and_set_head current_head, EMPTY + each current_head, &block + return self + end + end + end + + # @return [String] Short string representation. + def to_s + format '%s %s>', super[0..-2], to_a.to_s + end + + alias_method :inspect, :to_s + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/atomic_reference_map_backend.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/atomic_reference_map_backend.rb new file mode 100644 index 0000000..dc51893 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/atomic_reference_map_backend.rb @@ -0,0 +1,927 @@ +require 'concurrent/constants' +require 'concurrent/thread_safe/util' +require 'concurrent/thread_safe/util/adder' +require 'concurrent/thread_safe/util/cheap_lockable' +require 'concurrent/thread_safe/util/power_of_two_tuple' +require 'concurrent/thread_safe/util/volatile' +require 'concurrent/thread_safe/util/xor_shift_random' + +module Concurrent + + # @!visibility private + module Collection + + # A Ruby port of the Doug Lea's jsr166e.ConcurrentHashMapV8 class version 1.59 + # available in public domain. + # + # Original source code available here: + # http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/ConcurrentHashMapV8.java?revision=1.59 + # + # The Ruby port skips out the +TreeBin+ (red-black trees for use in bins whose + # size exceeds a threshold). + # + # A hash table supporting full concurrency of retrievals and high expected + # concurrency for updates. However, even though all operations are + # thread-safe, retrieval operations do _not_ entail locking, and there is + # _not_ any support for locking the entire table in a way that prevents all + # access. + # + # Retrieval operations generally do not block, so may overlap with update + # operations. Retrievals reflect the results of the most recently _completed_ + # update operations holding upon their onset. (More formally, an update + # operation for a given key bears a _happens-before_ relation with any (non + # +nil+) retrieval for that key reporting the updated value.) For aggregate + # operations such as +clear()+, concurrent retrievals may reflect insertion or + # removal of only some entries. Similarly, the +each_pair+ iterator yields + # elements reflecting the state of the hash table at some point at or since + # the start of the +each_pair+. Bear in mind that the results of aggregate + # status methods including +size()+ and +empty?+} are typically useful only + # when a map is not undergoing concurrent updates in other threads. Otherwise + # the results of these methods reflect transient states that may be adequate + # for monitoring or estimation purposes, but not for program control. + # + # The table is dynamically expanded when there are too many collisions (i.e., + # keys that have distinct hash codes but fall into the same slot modulo the + # table size), with the expected average effect of maintaining roughly two + # bins per mapping (corresponding to a 0.75 load factor threshold for + # resizing). There may be much variance around this average as mappings are + # added and removed, but overall, this maintains a commonly accepted + # time/space tradeoff for hash tables. However, resizing this or any other + # kind of hash table may be a relatively slow operation. When possible, it is + # a good idea to provide a size estimate as an optional :initial_capacity + # initializer argument. An additional optional :load_factor constructor + # argument provides a further means of customizing initial table capacity by + # specifying the table density to be used in calculating the amount of space + # to allocate for the given number of elements. Note that using many keys with + # exactly the same +hash+ is a sure way to slow down performance of any hash + # table. + # + # ## Design overview + # + # The primary design goal of this hash table is to maintain concurrent + # readability (typically method +[]+, but also iteration and related methods) + # while minimizing update contention. Secondary goals are to keep space + # consumption about the same or better than plain +Hash+, and to support high + # initial insertion rates on an empty table by many threads. + # + # Each key-value mapping is held in a +Node+. The validation-based approach + # explained below leads to a lot of code sprawl because retry-control + # precludes factoring into smaller methods. + # + # The table is lazily initialized to a power-of-two size upon the first + # insertion. Each bin in the table normally contains a list of +Node+s (most + # often, the list has only zero or one +Node+). Table accesses require + # volatile/atomic reads, writes, and CASes. The lists of nodes within bins are + # always accurately traversable under volatile reads, so long as lookups check + # hash code and non-nullness of value before checking key equality. + # + # We use the top two bits of +Node+ hash fields for control purposes -- they + # are available anyway because of addressing constraints. As explained further + # below, these top bits are used as follows: + # + # - 00 - Normal + # - 01 - Locked + # - 11 - Locked and may have a thread waiting for lock + # - 10 - +Node+ is a forwarding node + # + # The lower 28 bits of each +Node+'s hash field contain a the key's hash code, + # except for forwarding nodes, for which the lower bits are zero (and so + # always have hash field == +MOVED+). + # + # Insertion (via +[]=+ or its variants) of the first node in an empty bin is + # performed by just CASing it to the bin. This is by far the most common case + # for put operations under most key/hash distributions. Other update + # operations (insert, delete, and replace) require locks. We do not want to + # waste the space required to associate a distinct lock object with each bin, + # so instead use the first node of a bin list itself as a lock. Blocking + # support for these locks relies +Concurrent::ThreadSafe::Util::CheapLockable. However, we also need a + # +try_lock+ construction, so we overlay these by using bits of the +Node+ + # hash field for lock control (see above), and so normally use builtin + # monitors only for blocking and signalling using + # +cheap_wait+/+cheap_broadcast+ constructions. See +Node#try_await_lock+. + # + # Using the first node of a list as a lock does not by itself suffice though: + # When a node is locked, any update must first validate that it is still the + # first node after locking it, and retry if not. Because new nodes are always + # appended to lists, once a node is first in a bin, it remains first until + # deleted or the bin becomes invalidated (upon resizing). However, operations + # that only conditionally update may inspect nodes until the point of update. + # This is a converse of sorts to the lazy locking technique described by + # Herlihy & Shavit. + # + # The main disadvantage of per-bin locks is that other update operations on + # other nodes in a bin list protected by the same lock can stall, for example + # when user +eql?+ or mapping functions take a long time. However, + # statistically, under random hash codes, this is not a common problem. + # Ideally, the frequency of nodes in bins follows a Poisson distribution + # (http://en.wikipedia.org/wiki/Poisson_distribution) with a parameter of + # about 0.5 on average, given the resizing threshold of 0.75, although with a + # large variance because of resizing granularity. Ignoring variance, the + # expected occurrences of list size k are (exp(-0.5) * pow(0.5, k) / + # factorial(k)). The first values are: + # + # - 0: 0.60653066 + # - 1: 0.30326533 + # - 2: 0.07581633 + # - 3: 0.01263606 + # - 4: 0.00157952 + # - 5: 0.00015795 + # - 6: 0.00001316 + # - 7: 0.00000094 + # - 8: 0.00000006 + # - more: less than 1 in ten million + # + # Lock contention probability for two threads accessing distinct elements is + # roughly 1 / (8 * #elements) under random hashes. + # + # The table is resized when occupancy exceeds a percentage threshold + # (nominally, 0.75, but see below). Only a single thread performs the resize + # (using field +size_control+, to arrange exclusion), but the table otherwise + # remains usable for reads and updates. Resizing proceeds by transferring + # bins, one by one, from the table to the next table. Because we are using + # power-of-two expansion, the elements from each bin must either stay at same + # index, or move with a power of two offset. We eliminate unnecessary node + # creation by catching cases where old nodes can be reused because their next + # fields won't change. On average, only about one-sixth of them need cloning + # when a table doubles. The nodes they replace will be garbage collectable as + # soon as they are no longer referenced by any reader thread that may be in + # the midst of concurrently traversing table. Upon transfer, the old table bin + # contains only a special forwarding node (with hash field +MOVED+) that + # contains the next table as its key. On encountering a forwarding node, + # access and update operations restart, using the new table. + # + # Each bin transfer requires its bin lock. However, unlike other cases, a + # transfer can skip a bin if it fails to acquire its lock, and revisit it + # later. Method +rebuild+ maintains a buffer of TRANSFER_BUFFER_SIZE bins that + # have been skipped because of failure to acquire a lock, and blocks only if + # none are available (i.e., only very rarely). The transfer operation must + # also ensure that all accessible bins in both the old and new table are + # usable by any traversal. When there are no lock acquisition failures, this + # is arranged simply by proceeding from the last bin (+table.size - 1+) up + # towards the first. Upon seeing a forwarding node, traversals arrange to move + # to the new table without revisiting nodes. However, when any node is skipped + # during a transfer, all earlier table bins may have become visible, so are + # initialized with a reverse-forwarding node back to the old table until the + # new ones are established. (This sometimes requires transiently locking a + # forwarding node, which is possible under the above encoding.) These more + # expensive mechanics trigger only when necessary. + # + # The traversal scheme also applies to partial traversals of + # ranges of bins (via an alternate Traverser constructor) + # to support partitioned aggregate operations. Also, read-only + # operations give up if ever forwarded to a null table, which + # provides support for shutdown-style clearing, which is also not + # currently implemented. + # + # Lazy table initialization minimizes footprint until first use. + # + # The element count is maintained using a +Concurrent::ThreadSafe::Util::Adder+, + # which avoids contention on updates but can encounter cache thrashing + # if read too frequently during concurrent access. To avoid reading so + # often, resizing is attempted either when a bin lock is + # contended, or upon adding to a bin already holding two or more + # nodes (checked before adding in the +x_if_absent+ methods, after + # adding in others). Under uniform hash distributions, the + # probability of this occurring at threshold is around 13%, + # meaning that only about 1 in 8 puts check threshold (and after + # resizing, many fewer do so). But this approximation has high + # variance for small table sizes, so we check on any collision + # for sizes <= 64. The bulk putAll operation further reduces + # contention by only committing count updates upon these size + # checks. + # + # @!visibility private + class AtomicReferenceMapBackend + + # @!visibility private + class Table < Concurrent::ThreadSafe::Util::PowerOfTwoTuple + def cas_new_node(i, hash, key, value) + cas(i, nil, Node.new(hash, key, value)) + end + + def try_to_cas_in_computed(i, hash, key) + succeeded = false + new_value = nil + new_node = Node.new(locked_hash = hash | LOCKED, key, NULL) + if cas(i, nil, new_node) + begin + if NULL == (new_value = yield(NULL)) + was_null = true + else + new_node.value = new_value + end + succeeded = true + ensure + volatile_set(i, nil) if !succeeded || was_null + new_node.unlock_via_hash(locked_hash, hash) + end + end + return succeeded, new_value + end + + def try_lock_via_hash(i, node, node_hash) + node.try_lock_via_hash(node_hash) do + yield if volatile_get(i) == node + end + end + + def delete_node_at(i, node, predecessor_node) + if predecessor_node + predecessor_node.next = node.next + else + volatile_set(i, node.next) + end + end + end + + # Key-value entry. Nodes with a hash field of +MOVED+ are special, and do + # not contain user keys or values. Otherwise, keys are never +nil+, and + # +NULL+ +value+ fields indicate that a node is in the process of being + # deleted or created. For purposes of read-only access, a key may be read + # before a value, but can only be used after checking value to be +!= NULL+. + # + # @!visibility private + class Node + extend Concurrent::ThreadSafe::Util::Volatile + attr_volatile :hash, :value, :next + + include Concurrent::ThreadSafe::Util::CheapLockable + + bit_shift = Concurrent::ThreadSafe::Util::FIXNUM_BIT_SIZE - 2 # need 2 bits for ourselves + # Encodings for special uses of Node hash fields. See above for explanation. + MOVED = ('10' << ('0' * bit_shift)).to_i(2) # hash field for forwarding nodes + LOCKED = ('01' << ('0' * bit_shift)).to_i(2) # set/tested only as a bit + WAITING = ('11' << ('0' * bit_shift)).to_i(2) # both bits set/tested together + HASH_BITS = ('00' << ('1' * bit_shift)).to_i(2) # usable bits of normal node hash + + SPIN_LOCK_ATTEMPTS = Concurrent::ThreadSafe::Util::CPU_COUNT > 1 ? Concurrent::ThreadSafe::Util::CPU_COUNT * 2 : 0 + + attr_reader :key + + def initialize(hash, key, value, next_node = nil) + super() + @key = key + self.lazy_set_hash(hash) + self.lazy_set_value(value) + self.next = next_node + end + + # Spins a while if +LOCKED+ bit set and this node is the first of its bin, + # and then sets +WAITING+ bits on hash field and blocks (once) if they are + # still set. It is OK for this method to return even if lock is not + # available upon exit, which enables these simple single-wait mechanics. + # + # The corresponding signalling operation is performed within callers: Upon + # detecting that +WAITING+ has been set when unlocking lock (via a failed + # CAS from non-waiting +LOCKED+ state), unlockers acquire the + # +cheap_synchronize+ lock and perform a +cheap_broadcast+. + def try_await_lock(table, i) + if table && i >= 0 && i < table.size # bounds check, TODO: why are we bounds checking? + spins = SPIN_LOCK_ATTEMPTS + randomizer = base_randomizer = Concurrent::ThreadSafe::Util::XorShiftRandom.get + while equal?(table.volatile_get(i)) && self.class.locked_hash?(my_hash = hash) + if spins >= 0 + if (randomizer = (randomizer >> 1)).even? # spin at random + if (spins -= 1) == 0 + Thread.pass # yield before blocking + else + randomizer = base_randomizer = Concurrent::ThreadSafe::Util::XorShiftRandom.xorshift(base_randomizer) if randomizer.zero? + end + end + elsif cas_hash(my_hash, my_hash | WAITING) + force_acquire_lock(table, i) + break + end + end + end + end + + def key?(key) + @key.eql?(key) + end + + def matches?(key, hash) + pure_hash == hash && key?(key) + end + + def pure_hash + hash & HASH_BITS + end + + def try_lock_via_hash(node_hash = hash) + if cas_hash(node_hash, locked_hash = node_hash | LOCKED) + begin + yield + ensure + unlock_via_hash(locked_hash, node_hash) + end + end + end + + def locked? + self.class.locked_hash?(hash) + end + + def unlock_via_hash(locked_hash, node_hash) + unless cas_hash(locked_hash, node_hash) + self.hash = node_hash + cheap_synchronize { cheap_broadcast } + end + end + + private + def force_acquire_lock(table, i) + cheap_synchronize do + if equal?(table.volatile_get(i)) && (hash & WAITING) == WAITING + cheap_wait + else + cheap_broadcast # possibly won race vs signaller + end + end + end + + class << self + def locked_hash?(hash) + (hash & LOCKED) != 0 + end + end + end + + # shorthands + MOVED = Node::MOVED + LOCKED = Node::LOCKED + WAITING = Node::WAITING + HASH_BITS = Node::HASH_BITS + + NOW_RESIZING = -1 + DEFAULT_CAPACITY = 16 + MAX_CAPACITY = Concurrent::ThreadSafe::Util::MAX_INT + + # The buffer size for skipped bins during transfers. The + # value is arbitrary but should be large enough to avoid + # most locking stalls during resizes. + TRANSFER_BUFFER_SIZE = 32 + + extend Concurrent::ThreadSafe::Util::Volatile + attr_volatile :table, # The array of bins. Lazily initialized upon first insertion. Size is always a power of two. + + # Table initialization and resizing control. When negative, the + # table is being initialized or resized. Otherwise, when table is + # null, holds the initial table size to use upon creation, or 0 + # for default. After initialization, holds the next element count + # value upon which to resize the table. + :size_control + + def initialize(options = nil) + super() + @counter = Concurrent::ThreadSafe::Util::Adder.new + initial_capacity = options && options[:initial_capacity] || DEFAULT_CAPACITY + self.size_control = (capacity = table_size_for(initial_capacity)) > MAX_CAPACITY ? MAX_CAPACITY : capacity + end + + def get_or_default(key, else_value = nil) + hash = key_hash(key) + current_table = table + while current_table + node = current_table.volatile_get_by_hash(hash) + current_table = + while node + if (node_hash = node.hash) == MOVED + break node.key + elsif (node_hash & HASH_BITS) == hash && node.key?(key) && NULL != (value = node.value) + return value + end + node = node.next + end + end + else_value + end + + def [](key) + get_or_default(key) + end + + def key?(key) + get_or_default(key, NULL) != NULL + end + + def []=(key, value) + get_and_set(key, value) + value + end + + def compute_if_absent(key) + hash = key_hash(key) + current_table = table || initialize_table + while true + if !(node = current_table.volatile_get(i = current_table.hash_to_index(hash))) + succeeded, new_value = current_table.try_to_cas_in_computed(i, hash, key) { yield } + if succeeded + increment_size + return new_value + end + elsif (node_hash = node.hash) == MOVED + current_table = node.key + elsif NULL != (current_value = find_value_in_node_list(node, key, hash, node_hash & HASH_BITS)) + return current_value + elsif Node.locked_hash?(node_hash) + try_await_lock(current_table, i, node) + else + succeeded, value = attempt_internal_compute_if_absent(key, hash, current_table, i, node, node_hash) { yield } + return value if succeeded + end + end + end + + def compute_if_present(key) + new_value = nil + internal_replace(key) do |old_value| + if (new_value = yield(NULL == old_value ? nil : old_value)).nil? + NULL + else + new_value + end + end + new_value + end + + def compute(key) + internal_compute(key) do |old_value| + if (new_value = yield(NULL == old_value ? nil : old_value)).nil? + NULL + else + new_value + end + end + end + + def merge_pair(key, value) + internal_compute(key) do |old_value| + if NULL == old_value || !(value = yield(old_value)).nil? + value + else + NULL + end + end + end + + def replace_pair(key, old_value, new_value) + NULL != internal_replace(key, old_value) { new_value } + end + + def replace_if_exists(key, new_value) + if (result = internal_replace(key) { new_value }) && NULL != result + result + end + end + + def get_and_set(key, value) # internalPut in the original CHMV8 + hash = key_hash(key) + current_table = table || initialize_table + while true + if !(node = current_table.volatile_get(i = current_table.hash_to_index(hash))) + if current_table.cas_new_node(i, hash, key, value) + increment_size + break + end + elsif (node_hash = node.hash) == MOVED + current_table = node.key + elsif Node.locked_hash?(node_hash) + try_await_lock(current_table, i, node) + else + succeeded, old_value = attempt_get_and_set(key, value, hash, current_table, i, node, node_hash) + break old_value if succeeded + end + end + end + + def delete(key) + replace_if_exists(key, NULL) + end + + def delete_pair(key, value) + result = internal_replace(key, value) { NULL } + if result && NULL != result + !!result + else + false + end + end + + def each_pair + return self unless current_table = table + current_table_size = base_size = current_table.size + i = base_index = 0 + while base_index < base_size + if node = current_table.volatile_get(i) + if node.hash == MOVED + current_table = node.key + current_table_size = current_table.size + else + begin + if NULL != (value = node.value) # skip deleted or special nodes + yield node.key, value + end + end while node = node.next + end + end + + if (i_with_base = i + base_size) < current_table_size + i = i_with_base # visit upper slots if present + else + i = base_index += 1 + end + end + self + end + + def size + (sum = @counter.sum) < 0 ? 0 : sum # ignore transient negative values + end + + def empty? + size == 0 + end + + # Implementation for clear. Steps through each bin, removing all nodes. + def clear + return self unless current_table = table + current_table_size = current_table.size + deleted_count = i = 0 + while i < current_table_size + if !(node = current_table.volatile_get(i)) + i += 1 + elsif (node_hash = node.hash) == MOVED + current_table = node.key + current_table_size = current_table.size + elsif Node.locked_hash?(node_hash) + decrement_size(deleted_count) # opportunistically update count + deleted_count = 0 + node.try_await_lock(current_table, i) + else + current_table.try_lock_via_hash(i, node, node_hash) do + begin + deleted_count += 1 if NULL != node.value # recheck under lock + node.value = nil + end while node = node.next + current_table.volatile_set(i, nil) + i += 1 + end + end + end + decrement_size(deleted_count) + self + end + + private + # Internal versions of the insertion methods, each a + # little more complicated than the last. All have + # the same basic structure: + # 1. If table uninitialized, create + # 2. If bin empty, try to CAS new node + # 3. If bin stale, use new table + # 4. Lock and validate; if valid, scan and add or update + # + # The others interweave other checks and/or alternative actions: + # * Plain +get_and_set+ checks for and performs resize after insertion. + # * compute_if_absent prescans for mapping without lock (and fails to add + # if present), which also makes pre-emptive resize checks worthwhile. + # + # Someday when details settle down a bit more, it might be worth + # some factoring to reduce sprawl. + def internal_replace(key, expected_old_value = NULL, &block) + hash = key_hash(key) + current_table = table + while current_table + if !(node = current_table.volatile_get(i = current_table.hash_to_index(hash))) + break + elsif (node_hash = node.hash) == MOVED + current_table = node.key + elsif (node_hash & HASH_BITS) != hash && !node.next # precheck + break # rules out possible existence + elsif Node.locked_hash?(node_hash) + try_await_lock(current_table, i, node) + else + succeeded, old_value = attempt_internal_replace(key, expected_old_value, hash, current_table, i, node, node_hash, &block) + return old_value if succeeded + end + end + NULL + end + + def attempt_internal_replace(key, expected_old_value, hash, current_table, i, node, node_hash) + current_table.try_lock_via_hash(i, node, node_hash) do + predecessor_node = nil + old_value = NULL + begin + if node.matches?(key, hash) && NULL != (current_value = node.value) + if NULL == expected_old_value || expected_old_value == current_value # NULL == expected_old_value means whatever value + old_value = current_value + if NULL == (node.value = yield(old_value)) + current_table.delete_node_at(i, node, predecessor_node) + decrement_size + end + end + break + end + + predecessor_node = node + end while node = node.next + + return true, old_value + end + end + + def find_value_in_node_list(node, key, hash, pure_hash) + do_check_for_resize = false + while true + if pure_hash == hash && node.key?(key) && NULL != (value = node.value) + return value + elsif node = node.next + do_check_for_resize = true # at least 2 nodes -> check for resize + pure_hash = node.pure_hash + else + return NULL + end + end + ensure + check_for_resize if do_check_for_resize + end + + def internal_compute(key, &block) + hash = key_hash(key) + current_table = table || initialize_table + while true + if !(node = current_table.volatile_get(i = current_table.hash_to_index(hash))) + succeeded, new_value = current_table.try_to_cas_in_computed(i, hash, key, &block) + if succeeded + if NULL == new_value + break nil + else + increment_size + break new_value + end + end + elsif (node_hash = node.hash) == MOVED + current_table = node.key + elsif Node.locked_hash?(node_hash) + try_await_lock(current_table, i, node) + else + succeeded, new_value = attempt_compute(key, hash, current_table, i, node, node_hash, &block) + break new_value if succeeded + end + end + end + + def attempt_internal_compute_if_absent(key, hash, current_table, i, node, node_hash) + added = false + current_table.try_lock_via_hash(i, node, node_hash) do + while true + if node.matches?(key, hash) && NULL != (value = node.value) + return true, value + end + last = node + unless node = node.next + last.next = Node.new(hash, key, value = yield) + added = true + increment_size + return true, value + end + end + end + ensure + check_for_resize if added + end + + def attempt_compute(key, hash, current_table, i, node, node_hash) + added = false + current_table.try_lock_via_hash(i, node, node_hash) do + predecessor_node = nil + while true + if node.matches?(key, hash) && NULL != (value = node.value) + if NULL == (node.value = value = yield(value)) + current_table.delete_node_at(i, node, predecessor_node) + decrement_size + value = nil + end + return true, value + end + predecessor_node = node + unless node = node.next + if NULL == (value = yield(NULL)) + value = nil + else + predecessor_node.next = Node.new(hash, key, value) + added = true + increment_size + end + return true, value + end + end + end + ensure + check_for_resize if added + end + + def attempt_get_and_set(key, value, hash, current_table, i, node, node_hash) + node_nesting = nil + current_table.try_lock_via_hash(i, node, node_hash) do + node_nesting = 1 + old_value = nil + found_old_value = false + while node + if node.matches?(key, hash) && NULL != (old_value = node.value) + found_old_value = true + node.value = value + break + end + last = node + unless node = node.next + last.next = Node.new(hash, key, value) + break + end + node_nesting += 1 + end + + return true, old_value if found_old_value + increment_size + true + end + ensure + check_for_resize if node_nesting && (node_nesting > 1 || current_table.size <= 64) + end + + def initialize_copy(other) + super + @counter = Concurrent::ThreadSafe::Util::Adder.new + self.table = nil + self.size_control = (other_table = other.table) ? other_table.size : DEFAULT_CAPACITY + self + end + + def try_await_lock(current_table, i, node) + check_for_resize # try resizing if can't get lock + node.try_await_lock(current_table, i) + end + + def key_hash(key) + key.hash & HASH_BITS + end + + # Returns a power of two table size for the given desired capacity. + def table_size_for(entry_count) + size = 2 + size <<= 1 while size < entry_count + size + end + + # Initializes table, using the size recorded in +size_control+. + def initialize_table + until current_table ||= table + if (size_ctrl = size_control) == NOW_RESIZING + Thread.pass # lost initialization race; just spin + else + try_in_resize_lock(current_table, size_ctrl) do + initial_size = size_ctrl > 0 ? size_ctrl : DEFAULT_CAPACITY + current_table = self.table = Table.new(initial_size) + initial_size - (initial_size >> 2) # 75% load factor + end + end + end + current_table + end + + # If table is too small and not already resizing, creates next table and + # transfers bins. Rechecks occupancy after a transfer to see if another + # resize is already needed because resizings are lagging additions. + def check_for_resize + while (current_table = table) && MAX_CAPACITY > (table_size = current_table.size) && NOW_RESIZING != (size_ctrl = size_control) && size_ctrl < @counter.sum + try_in_resize_lock(current_table, size_ctrl) do + self.table = rebuild(current_table) + (table_size << 1) - (table_size >> 1) # 75% load factor + end + end + end + + def try_in_resize_lock(current_table, size_ctrl) + if cas_size_control(size_ctrl, NOW_RESIZING) + begin + if current_table == table # recheck under lock + size_ctrl = yield # get new size_control + end + ensure + self.size_control = size_ctrl + end + end + end + + # Moves and/or copies the nodes in each bin to new table. See above for explanation. + def rebuild(table) + old_table_size = table.size + new_table = table.next_in_size_table + # puts "#{old_table_size} -> #{new_table.size}" + forwarder = Node.new(MOVED, new_table, NULL) + rev_forwarder = nil + locked_indexes = nil # holds bins to revisit; nil until needed + locked_arr_idx = 0 + bin = old_table_size - 1 + i = bin + while true + if !(node = table.volatile_get(i)) + # no lock needed (or available) if bin >= 0, because we're not popping values from locked_indexes until we've run through the whole table + redo unless (bin >= 0 ? table.cas(i, nil, forwarder) : lock_and_clean_up_reverse_forwarders(table, old_table_size, new_table, i, forwarder)) + elsif Node.locked_hash?(node_hash = node.hash) + locked_indexes ||= ::Array.new + if bin < 0 && locked_arr_idx > 0 + locked_arr_idx -= 1 + i, locked_indexes[locked_arr_idx] = locked_indexes[locked_arr_idx], i # swap with another bin + redo + end + if bin < 0 || locked_indexes.size >= TRANSFER_BUFFER_SIZE + node.try_await_lock(table, i) # no other options -- block + redo + end + rev_forwarder ||= Node.new(MOVED, table, NULL) + redo unless table.volatile_get(i) == node && node.locked? # recheck before adding to list + locked_indexes << i + new_table.volatile_set(i, rev_forwarder) + new_table.volatile_set(i + old_table_size, rev_forwarder) + else + redo unless split_old_bin(table, new_table, i, node, node_hash, forwarder) + end + + if bin > 0 + i = (bin -= 1) + elsif locked_indexes && !locked_indexes.empty? + bin = -1 + i = locked_indexes.pop + locked_arr_idx = locked_indexes.size - 1 + else + return new_table + end + end + end + + def lock_and_clean_up_reverse_forwarders(old_table, old_table_size, new_table, i, forwarder) + # transiently use a locked forwarding node + locked_forwarder = Node.new(moved_locked_hash = MOVED | LOCKED, new_table, NULL) + if old_table.cas(i, nil, locked_forwarder) + new_table.volatile_set(i, nil) # kill the potential reverse forwarders + new_table.volatile_set(i + old_table_size, nil) # kill the potential reverse forwarders + old_table.volatile_set(i, forwarder) + locked_forwarder.unlock_via_hash(moved_locked_hash, MOVED) + true + end + end + + # Splits a normal bin with list headed by e into lo and hi parts; installs in given table. + def split_old_bin(table, new_table, i, node, node_hash, forwarder) + table.try_lock_via_hash(i, node, node_hash) do + split_bin(new_table, i, node, node_hash) + table.volatile_set(i, forwarder) + end + end + + def split_bin(new_table, i, node, node_hash) + bit = new_table.size >> 1 # bit to split on + run_bit = node_hash & bit + last_run = nil + low = nil + high = nil + current_node = node + # this optimises for the lowest amount of volatile writes and objects created + while current_node = current_node.next + unless (b = current_node.hash & bit) == run_bit + run_bit = b + last_run = current_node + end + end + if run_bit == 0 + low = last_run + else + high = last_run + end + current_node = node + until current_node == last_run + pure_hash = current_node.pure_hash + if (pure_hash & bit) == 0 + low = Node.new(pure_hash, current_node.key, current_node.value, low) + else + high = Node.new(pure_hash, current_node.key, current_node.value, high) + end + current_node = current_node.next + end + new_table.volatile_set(i, low) + new_table.volatile_set(i + bit, high) + end + + def increment_size + @counter.increment + end + + def decrement_size(by = 1) + @counter.add(-by) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/mri_map_backend.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/mri_map_backend.rb new file mode 100644 index 0000000..903c1f2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/mri_map_backend.rb @@ -0,0 +1,66 @@ +require 'thread' +require 'concurrent/collection/map/non_concurrent_map_backend' + +module Concurrent + + # @!visibility private + module Collection + + # @!visibility private + class MriMapBackend < NonConcurrentMapBackend + + def initialize(options = nil) + super(options) + @write_lock = Mutex.new + end + + def []=(key, value) + @write_lock.synchronize { super } + end + + def compute_if_absent(key) + if NULL != (stored_value = @backend.fetch(key, NULL)) # fast non-blocking path for the most likely case + stored_value + else + @write_lock.synchronize { super } + end + end + + def compute_if_present(key) + @write_lock.synchronize { super } + end + + def compute(key) + @write_lock.synchronize { super } + end + + def merge_pair(key, value) + @write_lock.synchronize { super } + end + + def replace_pair(key, old_value, new_value) + @write_lock.synchronize { super } + end + + def replace_if_exists(key, new_value) + @write_lock.synchronize { super } + end + + def get_and_set(key, value) + @write_lock.synchronize { super } + end + + def delete(key) + @write_lock.synchronize { super } + end + + def delete_pair(key, value) + @write_lock.synchronize { super } + end + + def clear + @write_lock.synchronize { super } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/non_concurrent_map_backend.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/non_concurrent_map_backend.rb new file mode 100644 index 0000000..e7c62e6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/non_concurrent_map_backend.rb @@ -0,0 +1,140 @@ +require 'concurrent/constants' + +module Concurrent + + # @!visibility private + module Collection + + # @!visibility private + class NonConcurrentMapBackend + + # WARNING: all public methods of the class must operate on the @backend + # directly without calling each other. This is important because of the + # SynchronizedMapBackend which uses a non-reentrant mutex for performance + # reasons. + def initialize(options = nil) + @backend = {} + end + + def [](key) + @backend[key] + end + + def []=(key, value) + @backend[key] = value + end + + def compute_if_absent(key) + if NULL != (stored_value = @backend.fetch(key, NULL)) + stored_value + else + @backend[key] = yield + end + end + + def replace_pair(key, old_value, new_value) + if pair?(key, old_value) + @backend[key] = new_value + true + else + false + end + end + + def replace_if_exists(key, new_value) + if NULL != (stored_value = @backend.fetch(key, NULL)) + @backend[key] = new_value + stored_value + end + end + + def compute_if_present(key) + if NULL != (stored_value = @backend.fetch(key, NULL)) + store_computed_value(key, yield(stored_value)) + end + end + + def compute(key) + store_computed_value(key, yield(@backend[key])) + end + + def merge_pair(key, value) + if NULL == (stored_value = @backend.fetch(key, NULL)) + @backend[key] = value + else + store_computed_value(key, yield(stored_value)) + end + end + + def get_and_set(key, value) + stored_value = @backend[key] + @backend[key] = value + stored_value + end + + def key?(key) + @backend.key?(key) + end + + def delete(key) + @backend.delete(key) + end + + def delete_pair(key, value) + if pair?(key, value) + @backend.delete(key) + true + else + false + end + end + + def clear + @backend.clear + self + end + + def each_pair + dupped_backend.each_pair do |k, v| + yield k, v + end + self + end + + def size + @backend.size + end + + def get_or_default(key, default_value) + @backend.fetch(key, default_value) + end + + alias_method :_get, :[] + alias_method :_set, :[]= + private :_get, :_set + private + def initialize_copy(other) + super + @backend = {} + self + end + + def dupped_backend + @backend.dup + end + + def pair?(key, expected_value) + NULL != (stored_value = @backend.fetch(key, NULL)) && expected_value.equal?(stored_value) + end + + def store_computed_value(key, new_value) + if new_value.nil? + @backend.delete(key) + nil + else + @backend[key] = new_value + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/synchronized_map_backend.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/synchronized_map_backend.rb new file mode 100644 index 0000000..190c8d9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/synchronized_map_backend.rb @@ -0,0 +1,82 @@ +require 'concurrent/collection/map/non_concurrent_map_backend' + +module Concurrent + + # @!visibility private + module Collection + + # @!visibility private + class SynchronizedMapBackend < NonConcurrentMapBackend + + require 'mutex_m' + include Mutex_m + # WARNING: Mutex_m is a non-reentrant lock, so the synchronized methods are + # not allowed to call each other. + + def [](key) + synchronize { super } + end + + def []=(key, value) + synchronize { super } + end + + def compute_if_absent(key) + synchronize { super } + end + + def compute_if_present(key) + synchronize { super } + end + + def compute(key) + synchronize { super } + end + + def merge_pair(key, value) + synchronize { super } + end + + def replace_pair(key, old_value, new_value) + synchronize { super } + end + + def replace_if_exists(key, new_value) + synchronize { super } + end + + def get_and_set(key, value) + synchronize { super } + end + + def key?(key) + synchronize { super } + end + + def delete(key) + synchronize { super } + end + + def delete_pair(key, value) + synchronize { super } + end + + def clear + synchronize { super } + end + + def size + synchronize { super } + end + + def get_or_default(key, default_value) + synchronize { super } + end + + private + def dupped_backend + synchronize { super } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/truffleruby_map_backend.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/truffleruby_map_backend.rb new file mode 100644 index 0000000..68a1b38 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/map/truffleruby_map_backend.rb @@ -0,0 +1,14 @@ +module Concurrent + + # @!visibility private + module Collection + + # @!visibility private + class TruffleRubyMapBackend < TruffleRuby::ConcurrentMap + def initialize(options = nil) + options ||= {} + super(initial_capacity: options[:initial_capacity], load_factor: options[:load_factor]) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/non_concurrent_priority_queue.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/non_concurrent_priority_queue.rb new file mode 100644 index 0000000..694cd7a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/non_concurrent_priority_queue.rb @@ -0,0 +1,143 @@ +require 'concurrent/utility/engine' +require 'concurrent/collection/java_non_concurrent_priority_queue' +require 'concurrent/collection/ruby_non_concurrent_priority_queue' + +module Concurrent + module Collection + + # @!visibility private + # @!macro internal_implementation_note + NonConcurrentPriorityQueueImplementation = case + when Concurrent.on_jruby? + JavaNonConcurrentPriorityQueue + else + RubyNonConcurrentPriorityQueue + end + private_constant :NonConcurrentPriorityQueueImplementation + + # @!macro priority_queue + # + # A queue collection in which the elements are sorted based on their + # comparison (spaceship) operator `<=>`. Items are added to the queue + # at a position relative to their priority. On removal the element + # with the "highest" priority is removed. By default the sort order is + # from highest to lowest, but a lowest-to-highest sort order can be + # set on construction. + # + # The API is based on the `Queue` class from the Ruby standard library. + # + # The pure Ruby implementation, `RubyNonConcurrentPriorityQueue` uses a heap algorithm + # stored in an array. The algorithm is based on the work of Robert Sedgewick + # and Kevin Wayne. + # + # The JRuby native implementation is a thin wrapper around the standard + # library `java.util.NonConcurrentPriorityQueue`. + # + # When running under JRuby the class `NonConcurrentPriorityQueue` extends `JavaNonConcurrentPriorityQueue`. + # When running under all other interpreters it extends `RubyNonConcurrentPriorityQueue`. + # + # @note This implementation is *not* thread safe. + # + # @see http://en.wikipedia.org/wiki/Priority_queue + # @see http://ruby-doc.org/stdlib-2.0.0/libdoc/thread/rdoc/Queue.html + # + # @see http://algs4.cs.princeton.edu/24pq/index.php#2.6 + # @see http://algs4.cs.princeton.edu/24pq/MaxPQ.java.html + # + # @see http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html + # + # @!visibility private + class NonConcurrentPriorityQueue < NonConcurrentPriorityQueueImplementation + + alias_method :has_priority?, :include? + + alias_method :size, :length + + alias_method :deq, :pop + alias_method :shift, :pop + + alias_method :<<, :push + alias_method :enq, :push + + # @!method initialize(opts = {}) + # @!macro priority_queue_method_initialize + # + # Create a new priority queue with no items. + # + # @param [Hash] opts the options for creating the queue + # @option opts [Symbol] :order (:max) dictates the order in which items are + # stored: from highest to lowest when `:max` or `:high`; from lowest to + # highest when `:min` or `:low` + + # @!method clear + # @!macro priority_queue_method_clear + # + # Removes all of the elements from this priority queue. + + # @!method delete(item) + # @!macro priority_queue_method_delete + # + # Deletes all items from `self` that are equal to `item`. + # + # @param [Object] item the item to be removed from the queue + # @return [Object] true if the item is found else false + + # @!method empty? + # @!macro priority_queue_method_empty + # + # Returns `true` if `self` contains no elements. + # + # @return [Boolean] true if there are no items in the queue else false + + # @!method include?(item) + # @!macro priority_queue_method_include + # + # Returns `true` if the given item is present in `self` (that is, if any + # element == `item`), otherwise returns false. + # + # @param [Object] item the item to search for + # + # @return [Boolean] true if the item is found else false + + # @!method length + # @!macro priority_queue_method_length + # + # The current length of the queue. + # + # @return [Fixnum] the number of items in the queue + + # @!method peek + # @!macro priority_queue_method_peek + # + # Retrieves, but does not remove, the head of this queue, or returns `nil` + # if this queue is empty. + # + # @return [Object] the head of the queue or `nil` when empty + + # @!method pop + # @!macro priority_queue_method_pop + # + # Retrieves and removes the head of this queue, or returns `nil` if this + # queue is empty. + # + # @return [Object] the head of the queue or `nil` when empty + + # @!method push(item) + # @!macro priority_queue_method_push + # + # Inserts the specified element into this priority queue. + # + # @param [Object] item the item to insert onto the queue + + # @!method self.from_list(list, opts = {}) + # @!macro priority_queue_method_from_list + # + # Create a new priority queue from the given list. + # + # @param [Enumerable] list the list to build the queue from + # @param [Hash] opts the options for creating the queue + # + # @return [NonConcurrentPriorityQueue] the newly created and populated queue + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/ruby_non_concurrent_priority_queue.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/ruby_non_concurrent_priority_queue.rb new file mode 100644 index 0000000..322b4ac --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/collection/ruby_non_concurrent_priority_queue.rb @@ -0,0 +1,160 @@ +module Concurrent + module Collection + + # @!macro priority_queue + # + # @!visibility private + # @!macro internal_implementation_note + class RubyNonConcurrentPriorityQueue + + # @!macro priority_queue_method_initialize + def initialize(opts = {}) + order = opts.fetch(:order, :max) + @comparator = [:min, :low].include?(order) ? -1 : 1 + clear + end + + # @!macro priority_queue_method_clear + def clear + @queue = [nil] + @length = 0 + true + end + + # @!macro priority_queue_method_delete + def delete(item) + return false if empty? + original_length = @length + k = 1 + while k <= @length + if @queue[k] == item + swap(k, @length) + @length -= 1 + sink(k) || swim(k) + @queue.pop + else + k += 1 + end + end + @length != original_length + end + + # @!macro priority_queue_method_empty + def empty? + size == 0 + end + + # @!macro priority_queue_method_include + def include?(item) + @queue.include?(item) + end + alias_method :has_priority?, :include? + + # @!macro priority_queue_method_length + def length + @length + end + alias_method :size, :length + + # @!macro priority_queue_method_peek + def peek + empty? ? nil : @queue[1] + end + + # @!macro priority_queue_method_pop + def pop + return nil if empty? + max = @queue[1] + swap(1, @length) + @length -= 1 + sink(1) + @queue.pop + max + end + alias_method :deq, :pop + alias_method :shift, :pop + + # @!macro priority_queue_method_push + def push(item) + raise ArgumentError.new('cannot enqueue nil') if item.nil? + @length += 1 + @queue << item + swim(@length) + true + end + alias_method :<<, :push + alias_method :enq, :push + + # @!macro priority_queue_method_from_list + def self.from_list(list, opts = {}) + queue = new(opts) + list.each{|item| queue << item } + queue + end + + private + + # Exchange the values at the given indexes within the internal array. + # + # @param [Integer] x the first index to swap + # @param [Integer] y the second index to swap + # + # @!visibility private + def swap(x, y) + temp = @queue[x] + @queue[x] = @queue[y] + @queue[y] = temp + end + + # Are the items at the given indexes ordered based on the priority + # order specified at construction? + # + # @param [Integer] x the first index from which to retrieve a comparable value + # @param [Integer] y the second index from which to retrieve a comparable value + # + # @return [Boolean] true if the two elements are in the correct priority order + # else false + # + # @!visibility private + def ordered?(x, y) + (@queue[x] <=> @queue[y]) == @comparator + end + + # Percolate down to maintain heap invariant. + # + # @param [Integer] k the index at which to start the percolation + # + # @!visibility private + def sink(k) + success = false + + while (j = (2 * k)) <= @length do + j += 1 if j < @length && ! ordered?(j, j+1) + break if ordered?(k, j) + swap(k, j) + success = true + k = j + end + + success + end + + # Percolate up to maintain heap invariant. + # + # @param [Integer] k the index at which to start the percolation + # + # @!visibility private + def swim(k) + success = false + + while k > 1 && ! ordered?(k/2, k) do + swap(k, k/2) + k = k/2 + success = true + end + + success + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/deprecation.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/deprecation.rb new file mode 100644 index 0000000..35ae4b2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/deprecation.rb @@ -0,0 +1,34 @@ +require 'concurrent/concern/logging' + +module Concurrent + module Concern + + # @!visibility private + # @!macro internal_implementation_note + module Deprecation + # TODO require additional parameter: a version. Display when it'll be removed based on that. Error if not removed. + include Concern::Logging + + def deprecated(message, strip = 2) + caller_line = caller(strip).first if strip > 0 + klass = if Module === self + self + else + self.class + end + message = if strip > 0 + format("[DEPRECATED] %s\ncalled on: %s", message, caller_line) + else + format('[DEPRECATED] %s', message) + end + log WARN, klass.to_s, message + end + + def deprecated_method(old_name, new_name) + deprecated "`#{old_name}` is deprecated and it'll removed in next release, use `#{new_name}` instead", 3 + end + + extend self + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/dereferenceable.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/dereferenceable.rb new file mode 100644 index 0000000..dc172ba --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/dereferenceable.rb @@ -0,0 +1,73 @@ +module Concurrent + module Concern + + # Object references in Ruby are mutable. This can lead to serious problems when + # the `#value` of a concurrent object is a mutable reference. Which is always the + # case unless the value is a `Fixnum`, `Symbol`, or similar "primitive" data type. + # Most classes in this library that expose a `#value` getter method do so using the + # `Dereferenceable` mixin module. + # + # @!macro copy_options + module Dereferenceable + # NOTE: This module is going away in 2.0. In the mean time we need it to + # play nicely with the synchronization layer. This means that the + # including class SHOULD be synchronized and it MUST implement a + # `#synchronize` method. Not doing so will lead to runtime errors. + + # Return the value this object represents after applying the options specified + # by the `#set_deref_options` method. + # + # @return [Object] the current value of the object + def value + synchronize { apply_deref_options(@value) } + end + alias_method :deref, :value + + protected + + # Set the internal value of this object + # + # @param [Object] value the new value + def value=(value) + synchronize{ @value = value } + end + + # @!macro dereferenceable_set_deref_options + # Set the options which define the operations #value performs before + # returning data to the caller (dereferencing). + # + # @note Most classes that include this module will call `#set_deref_options` + # from within the constructor, thus allowing these options to be set at + # object creation. + # + # @param [Hash] opts the options defining dereference behavior. + # @option opts [String] :dup_on_deref (false) call `#dup` before returning the data + # @option opts [String] :freeze_on_deref (false) call `#freeze` before returning the data + # @option opts [String] :copy_on_deref (nil) call the given `Proc` passing + # the internal value and returning the value returned from the proc + def set_deref_options(opts = {}) + synchronize{ ns_set_deref_options(opts) } + end + + # @!macro dereferenceable_set_deref_options + # @!visibility private + def ns_set_deref_options(opts) + @dup_on_deref = opts[:dup_on_deref] || opts[:dup] + @freeze_on_deref = opts[:freeze_on_deref] || opts[:freeze] + @copy_on_deref = opts[:copy_on_deref] || opts[:copy] + @do_nothing_on_deref = !(@dup_on_deref || @freeze_on_deref || @copy_on_deref) + nil + end + + # @!visibility private + def apply_deref_options(value) + return nil if value.nil? + return value if @do_nothing_on_deref + value = @copy_on_deref.call(value) if @copy_on_deref + value = value.dup if @dup_on_deref + value = value.freeze if @freeze_on_deref + value + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/logging.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/logging.rb new file mode 100644 index 0000000..2c74999 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/logging.rb @@ -0,0 +1,32 @@ +require 'logger' + +module Concurrent + module Concern + + # Include where logging is needed + # + # @!visibility private + module Logging + include Logger::Severity + + # Logs through {Concurrent.global_logger}, it can be overridden by setting @logger + # @param [Integer] level one of Logger::Severity constants + # @param [String] progname e.g. a path of an Actor + # @param [String, nil] message when nil block is used to generate the message + # @yieldreturn [String] a message + def log(level, progname, message = nil, &block) + #NOTE: Cannot require 'concurrent/configuration' above due to circular references. + # Assume that the gem has been initialized if we've gotten this far. + logger = if defined?(@logger) && @logger + @logger + else + Concurrent.global_logger + end + logger.call level, progname, message, &block + rescue => error + $stderr.puts "`Concurrent.configuration.logger` failed to log #{[level, progname, message, block]}\n" + + "#{error.message} (#{error.class})\n#{error.backtrace.join "\n"}" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/obligation.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/obligation.rb new file mode 100644 index 0000000..2c9ac12 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/obligation.rb @@ -0,0 +1,220 @@ +require 'thread' +require 'timeout' + +require 'concurrent/atomic/event' +require 'concurrent/concern/dereferenceable' + +module Concurrent + module Concern + + module Obligation + include Concern::Dereferenceable + # NOTE: The Dereferenceable module is going away in 2.0. In the mean time + # we need it to place nicely with the synchronization layer. This means + # that the including class SHOULD be synchronized and it MUST implement a + # `#synchronize` method. Not doing so will lead to runtime errors. + + # Has the obligation been fulfilled? + # + # @return [Boolean] + def fulfilled? + state == :fulfilled + end + alias_method :realized?, :fulfilled? + + # Has the obligation been rejected? + # + # @return [Boolean] + def rejected? + state == :rejected + end + + # Is obligation completion still pending? + # + # @return [Boolean] + def pending? + state == :pending + end + + # Is the obligation still unscheduled? + # + # @return [Boolean] + def unscheduled? + state == :unscheduled + end + + # Has the obligation completed processing? + # + # @return [Boolean] + def complete? + [:fulfilled, :rejected].include? state + end + + # Is the obligation still awaiting completion of processing? + # + # @return [Boolean] + def incomplete? + ! complete? + end + + # The current value of the obligation. Will be `nil` while the state is + # pending or the operation has been rejected. + # + # @param [Numeric] timeout the maximum time in seconds to wait. + # @return [Object] see Dereferenceable#deref + def value(timeout = nil) + wait timeout + deref + end + + # Wait until obligation is complete or the timeout has been reached. + # + # @param [Numeric] timeout the maximum time in seconds to wait. + # @return [Obligation] self + def wait(timeout = nil) + event.wait(timeout) if timeout != 0 && incomplete? + self + end + + # Wait until obligation is complete or the timeout is reached. Will re-raise + # any exceptions raised during processing (but will not raise an exception + # on timeout). + # + # @param [Numeric] timeout the maximum time in seconds to wait. + # @return [Obligation] self + # @raise [Exception] raises the reason when rejected + def wait!(timeout = nil) + wait(timeout).tap { raise self if rejected? } + end + alias_method :no_error!, :wait! + + # The current value of the obligation. Will be `nil` while the state is + # pending or the operation has been rejected. Will re-raise any exceptions + # raised during processing (but will not raise an exception on timeout). + # + # @param [Numeric] timeout the maximum time in seconds to wait. + # @return [Object] see Dereferenceable#deref + # @raise [Exception] raises the reason when rejected + def value!(timeout = nil) + wait(timeout) + if rejected? + raise self + else + deref + end + end + + # The current state of the obligation. + # + # @return [Symbol] the current state + def state + synchronize { @state } + end + + # If an exception was raised during processing this will return the + # exception object. Will return `nil` when the state is pending or if + # the obligation has been successfully fulfilled. + # + # @return [Exception] the exception raised during processing or `nil` + def reason + synchronize { @reason } + end + + # @example allows Obligation to be risen + # rejected_ivar = Ivar.new.fail + # raise rejected_ivar + def exception(*args) + raise 'obligation is not rejected' unless rejected? + reason.exception(*args) + end + + protected + + # @!visibility private + def get_arguments_from(opts = {}) + [*opts.fetch(:args, [])] + end + + # @!visibility private + def init_obligation + @event = Event.new + @value = @reason = nil + end + + # @!visibility private + def event + @event + end + + # @!visibility private + def set_state(success, value, reason) + if success + @value = value + @state = :fulfilled + else + @reason = reason + @state = :rejected + end + end + + # @!visibility private + def state=(value) + synchronize { ns_set_state(value) } + end + + # Atomic compare and set operation + # State is set to `next_state` only if `current state == expected_current`. + # + # @param [Symbol] next_state + # @param [Symbol] expected_current + # + # @return [Boolean] true is state is changed, false otherwise + # + # @!visibility private + def compare_and_set_state(next_state, *expected_current) + synchronize do + if expected_current.include? @state + @state = next_state + true + else + false + end + end + end + + # Executes the block within mutex if current state is included in expected_states + # + # @return block value if executed, false otherwise + # + # @!visibility private + def if_state(*expected_states) + synchronize do + raise ArgumentError.new('no block given') unless block_given? + + if expected_states.include? @state + yield + else + false + end + end + end + + protected + + # Am I in the current state? + # + # @param [Symbol] expected The state to check against + # @return [Boolean] true if in the expected state else false + # + # @!visibility private + def ns_check_state?(expected) + @state == expected + end + + # @!visibility private + def ns_set_state(value) + @state = value + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/observable.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/observable.rb new file mode 100644 index 0000000..b513271 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concern/observable.rb @@ -0,0 +1,110 @@ +require 'concurrent/collection/copy_on_notify_observer_set' +require 'concurrent/collection/copy_on_write_observer_set' + +module Concurrent + module Concern + + # The [observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) is one + # of the most useful design patterns. + # + # The workflow is very simple: + # - an `observer` can register itself to a `subject` via a callback + # - many `observers` can be registered to the same `subject` + # - the `subject` notifies all registered observers when its status changes + # - an `observer` can deregister itself when is no more interested to receive + # event notifications + # + # In a single threaded environment the whole pattern is very easy: the + # `subject` can use a simple data structure to manage all its subscribed + # `observer`s and every `observer` can react directly to every event without + # caring about synchronization. + # + # In a multi threaded environment things are more complex. The `subject` must + # synchronize the access to its data structure and to do so currently we're + # using two specialized ObserverSet: {Concurrent::Concern::CopyOnWriteObserverSet} + # and {Concurrent::Concern::CopyOnNotifyObserverSet}. + # + # When implementing and `observer` there's a very important rule to remember: + # **there are no guarantees about the thread that will execute the callback** + # + # Let's take this example + # ``` + # class Observer + # def initialize + # @count = 0 + # end + # + # def update + # @count += 1 + # end + # end + # + # obs = Observer.new + # [obj1, obj2, obj3, obj4].each { |o| o.add_observer(obs) } + # # execute [obj1, obj2, obj3, obj4] + # ``` + # + # `obs` is wrong because the variable `@count` can be accessed by different + # threads at the same time, so it should be synchronized (using either a Mutex + # or an AtomicFixum) + module Observable + + # @!macro observable_add_observer + # + # Adds an observer to this set. If a block is passed, the observer will be + # created by this method and no other params should be passed. + # + # @param [Object] observer the observer to add + # @param [Symbol] func the function to call on the observer during notification. + # Default is :update + # @return [Object] the added observer + def add_observer(observer = nil, func = :update, &block) + observers.add_observer(observer, func, &block) + end + + # As `#add_observer` but can be used for chaining. + # + # @param [Object] observer the observer to add + # @param [Symbol] func the function to call on the observer during notification. + # @return [Observable] self + def with_observer(observer = nil, func = :update, &block) + add_observer(observer, func, &block) + self + end + + # @!macro observable_delete_observer + # + # Remove `observer` as an observer on this object so that it will no + # longer receive notifications. + # + # @param [Object] observer the observer to remove + # @return [Object] the deleted observer + def delete_observer(observer) + observers.delete_observer(observer) + end + + # @!macro observable_delete_observers + # + # Remove all observers associated with this object. + # + # @return [Observable] self + def delete_observers + observers.delete_observers + self + end + + # @!macro observable_count_observers + # + # Return the number of observers associated with this object. + # + # @return [Integer] the observers count + def count_observers + observers.count_observers + end + + protected + + attr_accessor :observers + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concurrent_ruby.jar b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concurrent_ruby.jar new file mode 100644 index 0000000..e0d30ec Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/concurrent_ruby.jar differ diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/configuration.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/configuration.rb new file mode 100644 index 0000000..a00dc84 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/configuration.rb @@ -0,0 +1,188 @@ +require 'thread' +require 'concurrent/delay' +require 'concurrent/errors' +require 'concurrent/atomic/atomic_reference' +require 'concurrent/concern/logging' +require 'concurrent/concern/deprecation' +require 'concurrent/executor/immediate_executor' +require 'concurrent/executor/cached_thread_pool' +require 'concurrent/utility/processor_counter' + +module Concurrent + extend Concern::Logging + extend Concern::Deprecation + + autoload :Options, 'concurrent/options' + autoload :TimerSet, 'concurrent/executor/timer_set' + autoload :ThreadPoolExecutor, 'concurrent/executor/thread_pool_executor' + + # @return [Logger] Logger with provided level and output. + def self.create_simple_logger(level = Logger::FATAL, output = $stderr) + # TODO (pitr-ch 24-Dec-2016): figure out why it had to be replaced, stdlogger was deadlocking + lambda do |severity, progname, message = nil, &block| + return false if severity < level + + message = block ? block.call : message + formatted_message = case message + when String + message + when Exception + format "%s (%s)\n%s", + message.message, message.class, (message.backtrace || []).join("\n") + else + message.inspect + end + + output.print format "[%s] %5s -- %s: %s\n", + Time.now.strftime('%Y-%m-%d %H:%M:%S.%L'), + Logger::SEV_LABEL[severity], + progname, + formatted_message + true + end + end + + # Use logger created by #create_simple_logger to log concurrent-ruby messages. + def self.use_simple_logger(level = Logger::FATAL, output = $stderr) + Concurrent.global_logger = create_simple_logger level, output + end + + # @return [Logger] Logger with provided level and output. + # @deprecated + def self.create_stdlib_logger(level = Logger::FATAL, output = $stderr) + logger = Logger.new(output) + logger.level = level + logger.formatter = lambda do |severity, datetime, progname, msg| + formatted_message = case msg + when String + msg + when Exception + format "%s (%s)\n%s", + msg.message, msg.class, (msg.backtrace || []).join("\n") + else + msg.inspect + end + format "[%s] %5s -- %s: %s\n", + datetime.strftime('%Y-%m-%d %H:%M:%S.%L'), + severity, + progname, + formatted_message + end + + lambda do |loglevel, progname, message = nil, &block| + logger.add loglevel, message, progname, &block + end + end + + # Use logger created by #create_stdlib_logger to log concurrent-ruby messages. + # @deprecated + def self.use_stdlib_logger(level = Logger::FATAL, output = $stderr) + Concurrent.global_logger = create_stdlib_logger level, output + end + + # TODO (pitr-ch 27-Dec-2016): remove deadlocking stdlib_logger methods + + # Suppresses all output when used for logging. + NULL_LOGGER = lambda { |level, progname, message = nil, &block| } + + # @!visibility private + GLOBAL_LOGGER = AtomicReference.new(create_simple_logger(Logger::WARN)) + private_constant :GLOBAL_LOGGER + + def self.global_logger + GLOBAL_LOGGER.value + end + + def self.global_logger=(value) + GLOBAL_LOGGER.value = value + end + + # @!visibility private + GLOBAL_FAST_EXECUTOR = Delay.new { Concurrent.new_fast_executor } + private_constant :GLOBAL_FAST_EXECUTOR + + # @!visibility private + GLOBAL_IO_EXECUTOR = Delay.new { Concurrent.new_io_executor } + private_constant :GLOBAL_IO_EXECUTOR + + # @!visibility private + GLOBAL_TIMER_SET = Delay.new { TimerSet.new } + private_constant :GLOBAL_TIMER_SET + + # @!visibility private + GLOBAL_IMMEDIATE_EXECUTOR = ImmediateExecutor.new + private_constant :GLOBAL_IMMEDIATE_EXECUTOR + + # Disables AtExit handlers including pool auto-termination handlers. + # When disabled it will be the application programmer's responsibility + # to ensure that the handlers are shutdown properly prior to application + # exit by calling `AtExit.run` method. + # + # @note this option should be needed only because of `at_exit` ordering + # issues which may arise when running some of the testing frameworks. + # E.g. Minitest's test-suite runs itself in `at_exit` callback which + # executes after the pools are already terminated. Then auto termination + # needs to be disabled and called manually after test-suite ends. + # @note This method should *never* be called + # from within a gem. It should *only* be used from within the main + # application and even then it should be used only when necessary. + # @deprecated Has no effect since it is no longer needed, see https://github.com/ruby-concurrency/concurrent-ruby/pull/841. + # + def self.disable_at_exit_handlers! + deprecated "Method #disable_at_exit_handlers! has no effect since it is no longer needed, see https://github.com/ruby-concurrency/concurrent-ruby/pull/841." + end + + # Global thread pool optimized for short, fast *operations*. + # + # @return [ThreadPoolExecutor] the thread pool + def self.global_fast_executor + GLOBAL_FAST_EXECUTOR.value + end + + # Global thread pool optimized for long, blocking (IO) *tasks*. + # + # @return [ThreadPoolExecutor] the thread pool + def self.global_io_executor + GLOBAL_IO_EXECUTOR.value + end + + def self.global_immediate_executor + GLOBAL_IMMEDIATE_EXECUTOR + end + + # Global thread pool user for global *timers*. + # + # @return [Concurrent::TimerSet] the thread pool + def self.global_timer_set + GLOBAL_TIMER_SET.value + end + + # General access point to global executors. + # @param [Symbol, Executor] executor_identifier symbols: + # - :fast - {Concurrent.global_fast_executor} + # - :io - {Concurrent.global_io_executor} + # - :immediate - {Concurrent.global_immediate_executor} + # @return [Executor] + def self.executor(executor_identifier) + Options.executor(executor_identifier) + end + + def self.new_fast_executor(opts = {}) + FixedThreadPool.new( + [2, Concurrent.processor_count].max, + auto_terminate: opts.fetch(:auto_terminate, true), + idletime: 60, # 1 minute + max_queue: 0, # unlimited + fallback_policy: :abort, # shouldn't matter -- 0 max queue + name: "fast" + ) + end + + def self.new_io_executor(opts = {}) + CachedThreadPool.new( + auto_terminate: opts.fetch(:auto_terminate, true), + fallback_policy: :abort, # shouldn't matter -- 0 max queue + name: "io" + ) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/constants.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/constants.rb new file mode 100644 index 0000000..676c2af --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/constants.rb @@ -0,0 +1,8 @@ +module Concurrent + + # Various classes within allows for +nil+ values to be stored, + # so a special +NULL+ token is required to indicate the "nil-ness". + # @!visibility private + NULL = ::Object.new + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/dataflow.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/dataflow.rb new file mode 100644 index 0000000..d55f19d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/dataflow.rb @@ -0,0 +1,81 @@ +require 'concurrent/future' +require 'concurrent/atomic/atomic_fixnum' + +module Concurrent + + # @!visibility private + class DependencyCounter # :nodoc: + + def initialize(count, &block) + @counter = AtomicFixnum.new(count) + @block = block + end + + def update(time, value, reason) + if @counter.decrement == 0 + @block.call + end + end + end + + # Dataflow allows you to create a task that will be scheduled when all of its data dependencies are available. + # {include:file:docs-source/dataflow.md} + # + # @param [Future] inputs zero or more `Future` operations that this dataflow depends upon + # + # @yield The operation to perform once all the dependencies are met + # @yieldparam [Future] inputs each of the `Future` inputs to the dataflow + # @yieldreturn [Object] the result of the block operation + # + # @return [Object] the result of all the operations + # + # @raise [ArgumentError] if no block is given + # @raise [ArgumentError] if any of the inputs are not `IVar`s + def dataflow(*inputs, &block) + dataflow_with(Concurrent.global_io_executor, *inputs, &block) + end + module_function :dataflow + + def dataflow_with(executor, *inputs, &block) + call_dataflow(:value, executor, *inputs, &block) + end + module_function :dataflow_with + + def dataflow!(*inputs, &block) + dataflow_with!(Concurrent.global_io_executor, *inputs, &block) + end + module_function :dataflow! + + def dataflow_with!(executor, *inputs, &block) + call_dataflow(:value!, executor, *inputs, &block) + end + module_function :dataflow_with! + + private + + def call_dataflow(method, executor, *inputs, &block) + raise ArgumentError.new('an executor must be provided') if executor.nil? + raise ArgumentError.new('no block given') unless block_given? + unless inputs.all? { |input| input.is_a? IVar } + raise ArgumentError.new("Not all dependencies are IVars.\nDependencies: #{ inputs.inspect }") + end + + result = Future.new(executor: executor) do + values = inputs.map { |input| input.send(method) } + block.call(*values) + end + + if inputs.empty? + result.execute + else + counter = DependencyCounter.new(inputs.size) { result.execute } + + inputs.each do |input| + input.add_observer counter + end + end + + result + end + module_function :call_dataflow +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/delay.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/delay.rb new file mode 100644 index 0000000..83799d0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/delay.rb @@ -0,0 +1,199 @@ +require 'thread' +require 'concurrent/concern/obligation' +require 'concurrent/executor/immediate_executor' +require 'concurrent/synchronization' + +module Concurrent + + # This file has circular require issues. It must be autoloaded here. + autoload :Options, 'concurrent/options' + + # Lazy evaluation of a block yielding an immutable result. Useful for + # expensive operations that may never be needed. It may be non-blocking, + # supports the `Concern::Obligation` interface, and accepts the injection of + # custom executor upon which to execute the block. Processing of + # block will be deferred until the first time `#value` is called. + # At that time the caller can choose to return immediately and let + # the block execute asynchronously, block indefinitely, or block + # with a timeout. + # + # When a `Delay` is created its state is set to `pending`. The value and + # reason are both `nil`. The first time the `#value` method is called the + # enclosed opration will be run and the calling thread will block. Other + # threads attempting to call `#value` will block as well. Once the operation + # is complete the *value* will be set to the result of the operation or the + # *reason* will be set to the raised exception, as appropriate. All threads + # blocked on `#value` will return. Subsequent calls to `#value` will immediately + # return the cached value. The operation will only be run once. This means that + # any side effects created by the operation will only happen once as well. + # + # `Delay` includes the `Concurrent::Concern::Dereferenceable` mixin to support thread + # safety of the reference returned by `#value`. + # + # @!macro copy_options + # + # @!macro delay_note_regarding_blocking + # @note The default behavior of `Delay` is to block indefinitely when + # calling either `value` or `wait`, executing the delayed operation on + # the current thread. This makes the `timeout` value completely + # irrelevant. To enable non-blocking behavior, use the `executor` + # constructor option. This will cause the delayed operation to be + # execute on the given executor, allowing the call to timeout. + # + # @see Concurrent::Concern::Dereferenceable + class Delay < Synchronization::LockableObject + include Concern::Obligation + + # NOTE: Because the global thread pools are lazy-loaded with these objects + # there is a performance hit every time we post a new task to one of these + # thread pools. Subsequently it is critical that `Delay` perform as fast + # as possible post-completion. This class has been highly optimized using + # the benchmark script `examples/lazy_and_delay.rb`. Do NOT attempt to + # DRY-up this class or perform other refactoring with running the + # benchmarks and ensuring that performance is not negatively impacted. + + # Create a new `Delay` in the `:pending` state. + # + # @!macro executor_and_deref_options + # + # @yield the delayed operation to perform + # + # @raise [ArgumentError] if no block is given + def initialize(opts = {}, &block) + raise ArgumentError.new('no block given') unless block_given? + super(&nil) + synchronize { ns_initialize(opts, &block) } + end + + # Return the value this object represents after applying the options + # specified by the `#set_deref_options` method. If the delayed operation + # raised an exception this method will return nil. The execption object + # can be accessed via the `#reason` method. + # + # @param [Numeric] timeout the maximum number of seconds to wait + # @return [Object] the current value of the object + # + # @!macro delay_note_regarding_blocking + def value(timeout = nil) + if @executor # TODO (pitr 12-Sep-2015): broken unsafe read? + super + else + # this function has been optimized for performance and + # should not be modified without running new benchmarks + synchronize do + execute = @evaluation_started = true unless @evaluation_started + if execute + begin + set_state(true, @task.call, nil) + rescue => ex + set_state(false, nil, ex) + end + elsif incomplete? + raise IllegalOperationError, 'Recursive call to #value during evaluation of the Delay' + end + end + if @do_nothing_on_deref + @value + else + apply_deref_options(@value) + end + end + end + + # Return the value this object represents after applying the options + # specified by the `#set_deref_options` method. If the delayed operation + # raised an exception, this method will raise that exception (even when) + # the operation has already been executed). + # + # @param [Numeric] timeout the maximum number of seconds to wait + # @return [Object] the current value of the object + # @raise [Exception] when `#rejected?` raises `#reason` + # + # @!macro delay_note_regarding_blocking + def value!(timeout = nil) + if @executor + super + else + result = value + raise @reason if @reason + result + end + end + + # Return the value this object represents after applying the options + # specified by the `#set_deref_options` method. + # + # @param [Integer] timeout (nil) the maximum number of seconds to wait for + # the value to be computed. When `nil` the caller will block indefinitely. + # + # @return [Object] self + # + # @!macro delay_note_regarding_blocking + def wait(timeout = nil) + if @executor + execute_task_once + super(timeout) + else + value + end + self + end + + # Reconfigures the block returning the value if still `#incomplete?` + # + # @yield the delayed operation to perform + # @return [true, false] if success + def reconfigure(&block) + synchronize do + raise ArgumentError.new('no block given') unless block_given? + unless @evaluation_started + @task = block + true + else + false + end + end + end + + protected + + def ns_initialize(opts, &block) + init_obligation + set_deref_options(opts) + @executor = opts[:executor] + + @task = block + @state = :pending + @evaluation_started = false + end + + private + + # @!visibility private + def execute_task_once # :nodoc: + # this function has been optimized for performance and + # should not be modified without running new benchmarks + execute = task = nil + synchronize do + execute = @evaluation_started = true unless @evaluation_started + task = @task + end + + if execute + executor = Options.executor_from_options(executor: @executor) + executor.post do + begin + result = task.call + success = true + rescue => ex + reason = ex + end + synchronize do + set_state(success, result, reason) + event.set + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/errors.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/errors.rb new file mode 100644 index 0000000..b69fec0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/errors.rb @@ -0,0 +1,69 @@ +module Concurrent + + Error = Class.new(StandardError) + + # Raised when errors occur during configuration. + ConfigurationError = Class.new(Error) + + # Raised when an asynchronous operation is cancelled before execution. + CancelledOperationError = Class.new(Error) + + # Raised when a lifecycle method (such as `stop`) is called in an improper + # sequence or when the object is in an inappropriate state. + LifecycleError = Class.new(Error) + + # Raised when an attempt is made to violate an immutability guarantee. + ImmutabilityError = Class.new(Error) + + # Raised when an operation is attempted which is not legal given the + # receiver's current state + IllegalOperationError = Class.new(Error) + + # Raised when an object's methods are called when it has not been + # properly initialized. + InitializationError = Class.new(Error) + + # Raised when an object with a start/stop lifecycle has been started an + # excessive number of times. Often used in conjunction with a restart + # policy or strategy. + MaxRestartFrequencyError = Class.new(Error) + + # Raised when an attempt is made to modify an immutable object + # (such as an `IVar`) after its final state has been set. + class MultipleAssignmentError < Error + attr_reader :inspection_data + + def initialize(message = nil, inspection_data = nil) + @inspection_data = inspection_data + super message + end + + def inspect + format '%s %s>', super[0..-2], @inspection_data.inspect + end + end + + # Raised by an `Executor` when it is unable to process a given task, + # possibly because of a reject policy or other internal error. + RejectedExecutionError = Class.new(Error) + + # Raised when any finite resource, such as a lock counter, exceeds its + # maximum limit/threshold. + ResourceLimitError = Class.new(Error) + + # Raised when an operation times out. + TimeoutError = Class.new(Error) + + # Aggregates multiple exceptions. + class MultipleErrors < Error + attr_reader :errors + + def initialize(errors, message = "#{errors.size} errors") + @errors = errors + super [*message, + *errors.map { |e| [format('%s (%s)', e.message, e.class), *e.backtrace] }.flatten(1) + ].join("\n") + end + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/exchanger.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/exchanger.rb new file mode 100644 index 0000000..5a99550 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/exchanger.rb @@ -0,0 +1,352 @@ +require 'concurrent/constants' +require 'concurrent/errors' +require 'concurrent/maybe' +require 'concurrent/atomic/atomic_reference' +require 'concurrent/atomic/count_down_latch' +require 'concurrent/utility/engine' +require 'concurrent/utility/monotonic_time' + +module Concurrent + + # @!macro exchanger + # + # A synchronization point at which threads can pair and swap elements within + # pairs. Each thread presents some object on entry to the exchange method, + # matches with a partner thread, and receives its partner's object on return. + # + # @!macro thread_safe_variable_comparison + # + # This implementation is very simple, using only a single slot for each + # exchanger (unlike more advanced implementations which use an "arena"). + # This approach will work perfectly fine when there are only a few threads + # accessing a single `Exchanger`. Beyond a handful of threads the performance + # will degrade rapidly due to contention on the single slot, but the algorithm + # will remain correct. + # + # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Exchanger.html java.util.concurrent.Exchanger + # @example + # + # exchanger = Concurrent::Exchanger.new + # + # threads = [ + # Thread.new { puts "first: " << exchanger.exchange('foo', 1) }, #=> "first: bar" + # Thread.new { puts "second: " << exchanger.exchange('bar', 1) } #=> "second: foo" + # ] + # threads.each {|t| t.join(2) } + + # @!visibility private + class AbstractExchanger < Synchronization::Object + + # @!visibility private + CANCEL = ::Object.new + private_constant :CANCEL + + def initialize + super + end + + # @!macro exchanger_method_do_exchange + # + # Waits for another thread to arrive at this exchange point (unless the + # current thread is interrupted), and then transfers the given object to + # it, receiving its object in return. The timeout value indicates the + # approximate number of seconds the method should block while waiting + # for the exchange. When the timeout value is `nil` the method will + # block indefinitely. + # + # @param [Object] value the value to exchange with another thread + # @param [Numeric, nil] timeout in seconds, `nil` blocks indefinitely + # + # @!macro exchanger_method_exchange + # + # In some edge cases when a `timeout` is given a return value of `nil` may be + # ambiguous. Specifically, if `nil` is a valid value in the exchange it will + # be impossible to tell whether `nil` is the actual return value or if it + # signifies timeout. When `nil` is a valid value in the exchange consider + # using {#exchange!} or {#try_exchange} instead. + # + # @return [Object] the value exchanged by the other thread or `nil` on timeout + def exchange(value, timeout = nil) + (value = do_exchange(value, timeout)) == CANCEL ? nil : value + end + + # @!macro exchanger_method_do_exchange + # @!macro exchanger_method_exchange_bang + # + # On timeout a {Concurrent::TimeoutError} exception will be raised. + # + # @return [Object] the value exchanged by the other thread + # @raise [Concurrent::TimeoutError] on timeout + def exchange!(value, timeout = nil) + if (value = do_exchange(value, timeout)) == CANCEL + raise Concurrent::TimeoutError + else + value + end + end + + # @!macro exchanger_method_do_exchange + # @!macro exchanger_method_try_exchange + # + # The return value will be a {Concurrent::Maybe} set to `Just` on success or + # `Nothing` on timeout. + # + # @return [Concurrent::Maybe] on success a `Just` maybe will be returned with + # the item exchanged by the other thread as `#value`; on timeout a + # `Nothing` maybe will be returned with {Concurrent::TimeoutError} as `#reason` + # + # @example + # + # exchanger = Concurrent::Exchanger.new + # + # result = exchanger.exchange(:foo, 0.5) + # + # if result.just? + # puts result.value #=> :bar + # else + # puts 'timeout' + # end + def try_exchange(value, timeout = nil) + if (value = do_exchange(value, timeout)) == CANCEL + Concurrent::Maybe.nothing(Concurrent::TimeoutError) + else + Concurrent::Maybe.just(value) + end + end + + private + + # @!macro exchanger_method_do_exchange + # + # @return [Object, CANCEL] the value exchanged by the other thread; {CANCEL} on timeout + def do_exchange(value, timeout) + raise NotImplementedError + end + end + + # @!macro internal_implementation_note + # @!visibility private + class RubyExchanger < AbstractExchanger + # A simplified version of java.util.concurrent.Exchanger written by + # Doug Lea, Bill Scherer, and Michael Scott with assistance from members + # of JCP JSR-166 Expert Group and released to the public domain. It does + # not include the arena or the multi-processor spin loops. + # http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/Exchanger.java + + safe_initialization! + + class Node < Concurrent::Synchronization::Object + attr_atomic :value + safe_initialization! + + def initialize(item) + super() + @Item = item + @Latch = Concurrent::CountDownLatch.new + self.value = nil + end + + def latch + @Latch + end + + def item + @Item + end + end + private_constant :Node + + def initialize + super + end + + private + + attr_atomic(:slot) + + # @!macro exchanger_method_do_exchange + # + # @return [Object, CANCEL] the value exchanged by the other thread; {CANCEL} on timeout + def do_exchange(value, timeout) + + # ALGORITHM + # + # From the original Java version: + # + # > The basic idea is to maintain a "slot", which is a reference to + # > a Node containing both an Item to offer and a "hole" waiting to + # > get filled in. If an incoming "occupying" thread sees that the + # > slot is null, it CAS'es (compareAndSets) a Node there and waits + # > for another to invoke exchange. That second "fulfilling" thread + # > sees that the slot is non-null, and so CASes it back to null, + # > also exchanging items by CASing the hole, plus waking up the + # > occupying thread if it is blocked. In each case CAS'es may + # > fail because a slot at first appears non-null but is null upon + # > CAS, or vice-versa. So threads may need to retry these + # > actions. + # + # This version: + # + # An exchange occurs between an "occupier" thread and a "fulfiller" thread. + # The "slot" is used to setup this interaction. The first thread in the + # exchange puts itself into the slot (occupies) and waits for a fulfiller. + # The second thread removes the occupier from the slot and attempts to + # perform the exchange. Removing the occupier also frees the slot for + # another occupier/fulfiller pair. + # + # Because the occupier and the fulfiller are operating independently and + # because there may be contention with other threads, any failed operation + # indicates contention. Both the occupier and the fulfiller operate within + # spin loops. Any failed actions along the happy path will cause the thread + # to repeat the loop and try again. + # + # When a timeout value is given the thread must be cognizant of time spent + # in the spin loop. The remaining time is checked every loop. When the time + # runs out the thread will exit. + # + # A "node" is the data structure used to perform the exchange. Only the + # occupier's node is necessary. It's the node used for the exchange. + # Each node has an "item," a "hole" (self), and a "latch." The item is the + # node's initial value. It never changes. It's what the fulfiller returns on + # success. The occupier's hole is where the fulfiller put its item. It's the + # item that the occupier returns on success. The latch is used for synchronization. + # Because a thread may act as either an occupier or fulfiller (or possibly + # both in periods of high contention) every thread creates a node when + # the exchange method is first called. + # + # The following steps occur within the spin loop. If any actions fail + # the thread will loop and try again, so long as there is time remaining. + # If time runs out the thread will return CANCEL. + # + # Check the slot for an occupier: + # + # * If the slot is empty try to occupy + # * If the slot is full try to fulfill + # + # Attempt to occupy: + # + # * Attempt to CAS myself into the slot + # * Go to sleep and wait to be woken by a fulfiller + # * If the sleep is successful then the fulfiller completed its happy path + # - Return the value from my hole (the value given by the fulfiller) + # * When the sleep fails (time ran out) attempt to cancel the operation + # - Attempt to CAS myself out of the hole + # - If successful there is no contention + # - Return CANCEL + # - On failure, I am competing with a fulfiller + # - Attempt to CAS my hole to CANCEL + # - On success + # - Let the fulfiller deal with my cancel + # - Return CANCEL + # - On failure the fulfiller has completed its happy path + # - Return th value from my hole (the fulfiller's value) + # + # Attempt to fulfill: + # + # * Attempt to CAS the occupier out of the slot + # - On failure loop again + # * Attempt to CAS my item into the occupier's hole + # - On failure the occupier is trying to cancel + # - Loop again + # - On success we are on the happy path + # - Wake the sleeping occupier + # - Return the occupier's item + + value = NULL if value.nil? # The sentinel allows nil to be a valid value + me = Node.new(value) # create my node in case I need to occupy + end_at = Concurrent.monotonic_time + timeout.to_f # The time to give up + + result = loop do + other = slot + if other && compare_and_set_slot(other, nil) + # try to fulfill + if other.compare_and_set_value(nil, value) + # happy path + other.latch.count_down + break other.item + end + elsif other.nil? && compare_and_set_slot(nil, me) + # try to occupy + timeout = end_at - Concurrent.monotonic_time if timeout + if me.latch.wait(timeout) + # happy path + break me.value + else + # attempt to remove myself from the slot + if compare_and_set_slot(me, nil) + break CANCEL + elsif !me.compare_and_set_value(nil, CANCEL) + # I've failed to block the fulfiller + break me.value + end + end + end + break CANCEL if timeout && Concurrent.monotonic_time >= end_at + end + + result == NULL ? nil : result + end + end + + if Concurrent.on_jruby? + + # @!macro internal_implementation_note + # @!visibility private + class JavaExchanger < AbstractExchanger + + def initialize + @exchanger = java.util.concurrent.Exchanger.new + end + + private + + # @!macro exchanger_method_do_exchange + # + # @return [Object, CANCEL] the value exchanged by the other thread; {CANCEL} on timeout + def do_exchange(value, timeout) + result = nil + if timeout.nil? + Synchronization::JRuby.sleep_interruptibly do + result = @exchanger.exchange(value) + end + else + Synchronization::JRuby.sleep_interruptibly do + result = @exchanger.exchange(value, 1000 * timeout, java.util.concurrent.TimeUnit::MILLISECONDS) + end + end + result + rescue java.util.concurrent.TimeoutException + CANCEL + end + end + end + + # @!visibility private + # @!macro internal_implementation_note + ExchangerImplementation = case + when Concurrent.on_jruby? + JavaExchanger + else + RubyExchanger + end + private_constant :ExchangerImplementation + + # @!macro exchanger + class Exchanger < ExchangerImplementation + + # @!method initialize + # Creates exchanger instance + + # @!method exchange(value, timeout = nil) + # @!macro exchanger_method_do_exchange + # @!macro exchanger_method_exchange + + # @!method exchange!(value, timeout = nil) + # @!macro exchanger_method_do_exchange + # @!macro exchanger_method_exchange_bang + + # @!method try_exchange(value, timeout = nil) + # @!macro exchanger_method_do_exchange + # @!macro exchanger_method_try_exchange + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/abstract_executor_service.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/abstract_executor_service.rb new file mode 100644 index 0000000..f3631bf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/abstract_executor_service.rb @@ -0,0 +1,131 @@ +require 'concurrent/errors' +require 'concurrent/concern/deprecation' +require 'concurrent/executor/executor_service' +require 'concurrent/synchronization' + +module Concurrent + + # @!macro abstract_executor_service_public_api + # @!visibility private + class AbstractExecutorService < Synchronization::LockableObject + include ExecutorService + include Concern::Deprecation + + # The set of possible fallback policies that may be set at thread pool creation. + FALLBACK_POLICIES = [:abort, :discard, :caller_runs].freeze + + # @!macro executor_service_attr_reader_fallback_policy + attr_reader :fallback_policy + + attr_reader :name + + # Create a new thread pool. + def initialize(opts = {}, &block) + super(&nil) + synchronize do + @auto_terminate = opts.fetch(:auto_terminate, true) + @name = opts.fetch(:name) if opts.key?(:name) + ns_initialize(opts, &block) + end + end + + def to_s + name ? "#{super[0..-2]} name: #{name}>" : super + end + + # @!macro executor_service_method_shutdown + def shutdown + raise NotImplementedError + end + + # @!macro executor_service_method_kill + def kill + raise NotImplementedError + end + + # @!macro executor_service_method_wait_for_termination + def wait_for_termination(timeout = nil) + raise NotImplementedError + end + + # @!macro executor_service_method_running_question + def running? + synchronize { ns_running? } + end + + # @!macro executor_service_method_shuttingdown_question + def shuttingdown? + synchronize { ns_shuttingdown? } + end + + # @!macro executor_service_method_shutdown_question + def shutdown? + synchronize { ns_shutdown? } + end + + # @!macro executor_service_method_auto_terminate_question + def auto_terminate? + synchronize { @auto_terminate } + end + + # @!macro executor_service_method_auto_terminate_setter + def auto_terminate=(value) + deprecated "Method #auto_terminate= has no effect. Set :auto_terminate option when executor is initialized." + end + + private + + # Returns an action which executes the `fallback_policy` once the queue + # size reaches `max_queue`. The reason for the indirection of an action + # is so that the work can be deferred outside of synchronization. + # + # @param [Array] args the arguments to the task which is being handled. + # + # @!visibility private + def fallback_action(*args) + case fallback_policy + when :abort + lambda { raise RejectedExecutionError } + when :discard + lambda { false } + when :caller_runs + lambda { + begin + yield(*args) + rescue => ex + # let it fail + log DEBUG, ex + end + true + } + else + lambda { fail "Unknown fallback policy #{fallback_policy}" } + end + end + + def ns_execute(*args, &task) + raise NotImplementedError + end + + # @!macro executor_service_method_ns_shutdown_execution + # + # Callback method called when an orderly shutdown has completed. + # The default behavior is to signal all waiting threads. + def ns_shutdown_execution + # do nothing + end + + # @!macro executor_service_method_ns_kill_execution + # + # Callback method called when the executor has been killed. + # The default behavior is to do nothing. + def ns_kill_execution + # do nothing + end + + def ns_auto_terminate? + @auto_terminate + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/cached_thread_pool.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/cached_thread_pool.rb new file mode 100644 index 0000000..de50ed1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/cached_thread_pool.rb @@ -0,0 +1,62 @@ +require 'concurrent/utility/engine' +require 'concurrent/executor/thread_pool_executor' + +module Concurrent + + # A thread pool that dynamically grows and shrinks to fit the current workload. + # New threads are created as needed, existing threads are reused, and threads + # that remain idle for too long are killed and removed from the pool. These + # pools are particularly suited to applications that perform a high volume of + # short-lived tasks. + # + # On creation a `CachedThreadPool` has zero running threads. New threads are + # created on the pool as new operations are `#post`. The size of the pool + # will grow until `#max_length` threads are in the pool or until the number + # of threads exceeds the number of running and pending operations. When a new + # operation is post to the pool the first available idle thread will be tasked + # with the new operation. + # + # Should a thread crash for any reason the thread will immediately be removed + # from the pool. Similarly, threads which remain idle for an extended period + # of time will be killed and reclaimed. Thus these thread pools are very + # efficient at reclaiming unused resources. + # + # The API and behavior of this class are based on Java's `CachedThreadPool` + # + # @!macro thread_pool_options + class CachedThreadPool < ThreadPoolExecutor + + # @!macro cached_thread_pool_method_initialize + # + # Create a new thread pool. + # + # @param [Hash] opts the options defining pool behavior. + # @option opts [Symbol] :fallback_policy (`:abort`) the fallback policy + # + # @raise [ArgumentError] if `fallback_policy` is not a known policy + # + # @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool-- + def initialize(opts = {}) + defaults = { idletime: DEFAULT_THREAD_IDLETIMEOUT } + overrides = { min_threads: 0, + max_threads: DEFAULT_MAX_POOL_SIZE, + max_queue: DEFAULT_MAX_QUEUE_SIZE } + super(defaults.merge(opts).merge(overrides)) + end + + private + + # @!macro cached_thread_pool_method_initialize + # @!visibility private + def ns_initialize(opts) + super(opts) + if Concurrent.on_jruby? + @max_queue = 0 + @executor = java.util.concurrent.Executors.newCachedThreadPool( + DaemonThreadFactory.new(ns_auto_terminate?)) + @executor.setRejectedExecutionHandler(FALLBACK_POLICY_CLASSES[@fallback_policy].new) + @executor.setKeepAliveTime(opts.fetch(:idletime, DEFAULT_THREAD_IDLETIMEOUT), java.util.concurrent.TimeUnit::SECONDS) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/executor_service.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/executor_service.rb new file mode 100644 index 0000000..7e34491 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/executor_service.rb @@ -0,0 +1,185 @@ +require 'concurrent/concern/logging' + +module Concurrent + + ################################################################### + + # @!macro executor_service_method_post + # + # Submit a task to the executor for asynchronous processing. + # + # @param [Array] args zero or more arguments to be passed to the task + # + # @yield the asynchronous task to perform + # + # @return [Boolean] `true` if the task is queued, `false` if the executor + # is not running + # + # @raise [ArgumentError] if no task is given + + # @!macro executor_service_method_left_shift + # + # Submit a task to the executor for asynchronous processing. + # + # @param [Proc] task the asynchronous task to perform + # + # @return [self] returns itself + + # @!macro executor_service_method_can_overflow_question + # + # Does the task queue have a maximum size? + # + # @return [Boolean] True if the task queue has a maximum size else false. + + # @!macro executor_service_method_serialized_question + # + # Does this executor guarantee serialization of its operations? + # + # @return [Boolean] True if the executor guarantees that all operations + # will be post in the order they are received and no two operations may + # occur simultaneously. Else false. + + ################################################################### + + # @!macro executor_service_public_api + # + # @!method post(*args, &task) + # @!macro executor_service_method_post + # + # @!method <<(task) + # @!macro executor_service_method_left_shift + # + # @!method can_overflow? + # @!macro executor_service_method_can_overflow_question + # + # @!method serialized? + # @!macro executor_service_method_serialized_question + + ################################################################### + + # @!macro executor_service_attr_reader_fallback_policy + # @return [Symbol] The fallback policy in effect. Either `:abort`, `:discard`, or `:caller_runs`. + + # @!macro executor_service_method_shutdown + # + # Begin an orderly shutdown. Tasks already in the queue will be executed, + # but no new tasks will be accepted. Has no additional effect if the + # thread pool is not running. + + # @!macro executor_service_method_kill + # + # Begin an immediate shutdown. In-progress tasks will be allowed to + # complete but enqueued tasks will be dismissed and no new tasks + # will be accepted. Has no additional effect if the thread pool is + # not running. + + # @!macro executor_service_method_wait_for_termination + # + # Block until executor shutdown is complete or until `timeout` seconds have + # passed. + # + # @note Does not initiate shutdown or termination. Either `shutdown` or `kill` + # must be called before this method (or on another thread). + # + # @param [Integer] timeout the maximum number of seconds to wait for shutdown to complete + # + # @return [Boolean] `true` if shutdown complete or false on `timeout` + + # @!macro executor_service_method_running_question + # + # Is the executor running? + # + # @return [Boolean] `true` when running, `false` when shutting down or shutdown + + # @!macro executor_service_method_shuttingdown_question + # + # Is the executor shuttingdown? + # + # @return [Boolean] `true` when not running and not shutdown, else `false` + + # @!macro executor_service_method_shutdown_question + # + # Is the executor shutdown? + # + # @return [Boolean] `true` when shutdown, `false` when shutting down or running + + # @!macro executor_service_method_auto_terminate_question + # + # Is the executor auto-terminate when the application exits? + # + # @return [Boolean] `true` when auto-termination is enabled else `false`. + + # @!macro executor_service_method_auto_terminate_setter + # + # + # Set the auto-terminate behavior for this executor. + # @deprecated Has no effect + # @param [Boolean] value The new auto-terminate value to set for this executor. + # @return [Boolean] `true` when auto-termination is enabled else `false`. + + ################################################################### + + # @!macro abstract_executor_service_public_api + # + # @!macro executor_service_public_api + # + # @!attribute [r] fallback_policy + # @!macro executor_service_attr_reader_fallback_policy + # + # @!method shutdown + # @!macro executor_service_method_shutdown + # + # @!method kill + # @!macro executor_service_method_kill + # + # @!method wait_for_termination(timeout = nil) + # @!macro executor_service_method_wait_for_termination + # + # @!method running? + # @!macro executor_service_method_running_question + # + # @!method shuttingdown? + # @!macro executor_service_method_shuttingdown_question + # + # @!method shutdown? + # @!macro executor_service_method_shutdown_question + # + # @!method auto_terminate? + # @!macro executor_service_method_auto_terminate_question + # + # @!method auto_terminate=(value) + # @!macro executor_service_method_auto_terminate_setter + + ################################################################### + + # @!macro executor_service_public_api + # @!visibility private + module ExecutorService + include Concern::Logging + + # @!macro executor_service_method_post + def post(*args, &task) + raise NotImplementedError + end + + # @!macro executor_service_method_left_shift + def <<(task) + post(&task) + self + end + + # @!macro executor_service_method_can_overflow_question + # + # @note Always returns `false` + def can_overflow? + false + end + + # @!macro executor_service_method_serialized_question + # + # @note Always returns `false` + def serialized? + false + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/fixed_thread_pool.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/fixed_thread_pool.rb new file mode 100644 index 0000000..4de512a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/fixed_thread_pool.rb @@ -0,0 +1,220 @@ +require 'concurrent/utility/engine' +require 'concurrent/executor/thread_pool_executor' + +module Concurrent + + # @!macro thread_pool_executor_constant_default_max_pool_size + # Default maximum number of threads that will be created in the pool. + + # @!macro thread_pool_executor_constant_default_min_pool_size + # Default minimum number of threads that will be retained in the pool. + + # @!macro thread_pool_executor_constant_default_max_queue_size + # Default maximum number of tasks that may be added to the task queue. + + # @!macro thread_pool_executor_constant_default_thread_timeout + # Default maximum number of seconds a thread in the pool may remain idle + # before being reclaimed. + + # @!macro thread_pool_executor_constant_default_synchronous + # Default value of the :synchronous option. + + # @!macro thread_pool_executor_attr_reader_max_length + # The maximum number of threads that may be created in the pool. + # @return [Integer] The maximum number of threads that may be created in the pool. + + # @!macro thread_pool_executor_attr_reader_min_length + # The minimum number of threads that may be retained in the pool. + # @return [Integer] The minimum number of threads that may be retained in the pool. + + # @!macro thread_pool_executor_attr_reader_largest_length + # The largest number of threads that have been created in the pool since construction. + # @return [Integer] The largest number of threads that have been created in the pool since construction. + + # @!macro thread_pool_executor_attr_reader_scheduled_task_count + # The number of tasks that have been scheduled for execution on the pool since construction. + # @return [Integer] The number of tasks that have been scheduled for execution on the pool since construction. + + # @!macro thread_pool_executor_attr_reader_completed_task_count + # The number of tasks that have been completed by the pool since construction. + # @return [Integer] The number of tasks that have been completed by the pool since construction. + + # @!macro thread_pool_executor_attr_reader_idletime + # The number of seconds that a thread may be idle before being reclaimed. + # @return [Integer] The number of seconds that a thread may be idle before being reclaimed. + + # @!macro thread_pool_executor_attr_reader_synchronous + # Whether or not a value of 0 for :max_queue option means the queue must perform direct hand-off or rather unbounded queue. + # @return [true, false] + + # @!macro thread_pool_executor_attr_reader_max_queue + # The maximum number of tasks that may be waiting in the work queue at any one time. + # When the queue size reaches `max_queue` subsequent tasks will be rejected in + # accordance with the configured `fallback_policy`. + # + # @return [Integer] The maximum number of tasks that may be waiting in the work queue at any one time. + # When the queue size reaches `max_queue` subsequent tasks will be rejected in + # accordance with the configured `fallback_policy`. + + # @!macro thread_pool_executor_attr_reader_length + # The number of threads currently in the pool. + # @return [Integer] The number of threads currently in the pool. + + # @!macro thread_pool_executor_attr_reader_queue_length + # The number of tasks in the queue awaiting execution. + # @return [Integer] The number of tasks in the queue awaiting execution. + + # @!macro thread_pool_executor_attr_reader_remaining_capacity + # Number of tasks that may be enqueued before reaching `max_queue` and rejecting + # new tasks. A value of -1 indicates that the queue may grow without bound. + # + # @return [Integer] Number of tasks that may be enqueued before reaching `max_queue` and rejecting + # new tasks. A value of -1 indicates that the queue may grow without bound. + + # @!macro thread_pool_executor_method_prune_pool + # Prune the thread pool of unneeded threads + # + # What is being pruned is controlled by the min_threads and idletime + # parameters passed at pool creation time + # + # This is a no-op on some pool implementation (e.g. the Java one). The Ruby + # pool will auto-prune each time a new job is posted. You will need to call + # this method explicitely in case your application post jobs in bursts (a + # lot of jobs and then nothing for long periods) + + # @!macro thread_pool_executor_public_api + # + # @!macro abstract_executor_service_public_api + # + # @!attribute [r] max_length + # @!macro thread_pool_executor_attr_reader_max_length + # + # @!attribute [r] min_length + # @!macro thread_pool_executor_attr_reader_min_length + # + # @!attribute [r] largest_length + # @!macro thread_pool_executor_attr_reader_largest_length + # + # @!attribute [r] scheduled_task_count + # @!macro thread_pool_executor_attr_reader_scheduled_task_count + # + # @!attribute [r] completed_task_count + # @!macro thread_pool_executor_attr_reader_completed_task_count + # + # @!attribute [r] idletime + # @!macro thread_pool_executor_attr_reader_idletime + # + # @!attribute [r] max_queue + # @!macro thread_pool_executor_attr_reader_max_queue + # + # @!attribute [r] length + # @!macro thread_pool_executor_attr_reader_length + # + # @!attribute [r] queue_length + # @!macro thread_pool_executor_attr_reader_queue_length + # + # @!attribute [r] remaining_capacity + # @!macro thread_pool_executor_attr_reader_remaining_capacity + # + # @!method can_overflow? + # @!macro executor_service_method_can_overflow_question + # + # @!method prune_pool + # @!macro thread_pool_executor_method_prune_pool + + + + + # @!macro thread_pool_options + # + # **Thread Pool Options** + # + # Thread pools support several configuration options: + # + # * `idletime`: The number of seconds that a thread may be idle before being reclaimed. + # * `name`: The name of the executor (optional). Printed in the executor's `#to_s` output and + # a `-worker-` name is given to its threads if supported by used Ruby + # implementation. `` is uniq for each thread. + # * `max_queue`: The maximum number of tasks that may be waiting in the work queue at + # any one time. When the queue size reaches `max_queue` and no new threads can be created, + # subsequent tasks will be rejected in accordance with the configured `fallback_policy`. + # * `auto_terminate`: When true (default), the threads started will be marked as daemon. + # * `fallback_policy`: The policy defining how rejected tasks are handled. + # + # Three fallback policies are supported: + # + # * `:abort`: Raise a `RejectedExecutionError` exception and discard the task. + # * `:discard`: Discard the task and return false. + # * `:caller_runs`: Execute the task on the calling thread. + # + # **Shutting Down Thread Pools** + # + # Killing a thread pool while tasks are still being processed, either by calling + # the `#kill` method or at application exit, will have unpredictable results. There + # is no way for the thread pool to know what resources are being used by the + # in-progress tasks. When those tasks are killed the impact on those resources + # cannot be predicted. The *best* practice is to explicitly shutdown all thread + # pools using the provided methods: + # + # * Call `#shutdown` to initiate an orderly termination of all in-progress tasks + # * Call `#wait_for_termination` with an appropriate timeout interval an allow + # the orderly shutdown to complete + # * Call `#kill` *only when* the thread pool fails to shutdown in the allotted time + # + # On some runtime platforms (most notably the JVM) the application will not + # exit until all thread pools have been shutdown. To prevent applications from + # "hanging" on exit, all threads can be marked as daemon according to the + # `:auto_terminate` option. + # + # ```ruby + # pool1 = Concurrent::FixedThreadPool.new(5) # threads will be marked as daemon + # pool2 = Concurrent::FixedThreadPool.new(5, auto_terminate: false) # mark threads as non-daemon + # ``` + # + # @note Failure to properly shutdown a thread pool can lead to unpredictable results. + # Please read *Shutting Down Thread Pools* for more information. + # + # @see http://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html Java Tutorials: Thread Pools + # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html Java Executors class + # @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html Java ExecutorService interface + # @see https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#setDaemon-boolean- + + + + + + # @!macro fixed_thread_pool + # + # A thread pool that reuses a fixed number of threads operating off an unbounded queue. + # At any point, at most `num_threads` will be active processing tasks. When all threads are busy new + # tasks `#post` to the thread pool are enqueued until a thread becomes available. + # Should a thread crash for any reason the thread will immediately be removed + # from the pool and replaced. + # + # The API and behavior of this class are based on Java's `FixedThreadPool` + # + # @!macro thread_pool_options + class FixedThreadPool < ThreadPoolExecutor + + # @!macro fixed_thread_pool_method_initialize + # + # Create a new thread pool. + # + # @param [Integer] num_threads the number of threads to allocate + # @param [Hash] opts the options defining pool behavior. + # @option opts [Symbol] :fallback_policy (`:abort`) the fallback policy + # + # @raise [ArgumentError] if `num_threads` is less than or equal to zero + # @raise [ArgumentError] if `fallback_policy` is not a known policy + # + # @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool-int- + def initialize(num_threads, opts = {}) + raise ArgumentError.new('number of threads must be greater than zero') if num_threads.to_i < 1 + defaults = { max_queue: DEFAULT_MAX_QUEUE_SIZE, + idletime: DEFAULT_THREAD_IDLETIMEOUT } + overrides = { min_threads: num_threads, + max_threads: num_threads } + super(defaults.merge(opts).merge(overrides)) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/immediate_executor.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/immediate_executor.rb new file mode 100644 index 0000000..282df7a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/immediate_executor.rb @@ -0,0 +1,66 @@ +require 'concurrent/atomic/event' +require 'concurrent/executor/abstract_executor_service' +require 'concurrent/executor/serial_executor_service' + +module Concurrent + + # An executor service which runs all operations on the current thread, + # blocking as necessary. Operations are performed in the order they are + # received and no two operations can be performed simultaneously. + # + # This executor service exists mainly for testing an debugging. When used + # it immediately runs every `#post` operation on the current thread, blocking + # that thread until the operation is complete. This can be very beneficial + # during testing because it makes all operations deterministic. + # + # @note Intended for use primarily in testing and debugging. + class ImmediateExecutor < AbstractExecutorService + include SerialExecutorService + + # Creates a new executor + def initialize + @stopped = Concurrent::Event.new + end + + # @!macro executor_service_method_post + def post(*args, &task) + raise ArgumentError.new('no block given') unless block_given? + return false unless running? + task.call(*args) + true + end + + # @!macro executor_service_method_left_shift + def <<(task) + post(&task) + self + end + + # @!macro executor_service_method_running_question + def running? + ! shutdown? + end + + # @!macro executor_service_method_shuttingdown_question + def shuttingdown? + false + end + + # @!macro executor_service_method_shutdown_question + def shutdown? + @stopped.set? + end + + # @!macro executor_service_method_shutdown + def shutdown + @stopped.set + true + end + alias_method :kill, :shutdown + + # @!macro executor_service_method_wait_for_termination + def wait_for_termination(timeout = nil) + @stopped.wait(timeout) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/indirect_immediate_executor.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/indirect_immediate_executor.rb new file mode 100644 index 0000000..4f9769f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/indirect_immediate_executor.rb @@ -0,0 +1,44 @@ +require 'concurrent/executor/immediate_executor' +require 'concurrent/executor/simple_executor_service' + +module Concurrent + # An executor service which runs all operations on a new thread, blocking + # until it completes. Operations are performed in the order they are received + # and no two operations can be performed simultaneously. + # + # This executor service exists mainly for testing an debugging. When used it + # immediately runs every `#post` operation on a new thread, blocking the + # current thread until the operation is complete. This is similar to how the + # ImmediateExecutor works, but the operation has the full stack of the new + # thread at its disposal. This can be helpful when the operations will spawn + # more operations on the same executor and so on - such a situation might + # overflow the single stack in case of an ImmediateExecutor, which is + # inconsistent with how it would behave for a threaded executor. + # + # @note Intended for use primarily in testing and debugging. + class IndirectImmediateExecutor < ImmediateExecutor + # Creates a new executor + def initialize + super + @internal_executor = SimpleExecutorService.new + end + + # @!macro executor_service_method_post + def post(*args, &task) + raise ArgumentError.new("no block given") unless block_given? + return false unless running? + + event = Concurrent::Event.new + @internal_executor.post do + begin + task.call(*args) + ensure + event.set + end + end + event.wait + + true + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/java_executor_service.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/java_executor_service.rb new file mode 100644 index 0000000..e63e898 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/java_executor_service.rb @@ -0,0 +1,103 @@ +if Concurrent.on_jruby? + + require 'concurrent/errors' + require 'concurrent/utility/engine' + require 'concurrent/executor/abstract_executor_service' + + module Concurrent + + # @!macro abstract_executor_service_public_api + # @!visibility private + class JavaExecutorService < AbstractExecutorService + java_import 'java.lang.Runnable' + + FALLBACK_POLICY_CLASSES = { + abort: java.util.concurrent.ThreadPoolExecutor::AbortPolicy, + discard: java.util.concurrent.ThreadPoolExecutor::DiscardPolicy, + caller_runs: java.util.concurrent.ThreadPoolExecutor::CallerRunsPolicy + }.freeze + private_constant :FALLBACK_POLICY_CLASSES + + def post(*args, &task) + raise ArgumentError.new('no block given') unless block_given? + return fallback_action(*args, &task).call unless running? + @executor.submit Job.new(args, task) + true + rescue Java::JavaUtilConcurrent::RejectedExecutionException + raise RejectedExecutionError + end + + def wait_for_termination(timeout = nil) + if timeout.nil? + ok = @executor.awaitTermination(60, java.util.concurrent.TimeUnit::SECONDS) until ok + true + else + @executor.awaitTermination(1000 * timeout, java.util.concurrent.TimeUnit::MILLISECONDS) + end + end + + def shutdown + synchronize do + @executor.shutdown + nil + end + end + + def kill + synchronize do + @executor.shutdownNow + nil + end + end + + private + + def ns_running? + !(ns_shuttingdown? || ns_shutdown?) + end + + def ns_shuttingdown? + if @executor.respond_to? :isTerminating + @executor.isTerminating + else + false + end + end + + def ns_shutdown? + @executor.isShutdown || @executor.isTerminated + end + + class Job + include Runnable + def initialize(args, block) + @args = args + @block = block + end + + def run + @block.call(*@args) + end + end + private_constant :Job + end + + class DaemonThreadFactory + # hide include from YARD + send :include, java.util.concurrent.ThreadFactory + + def initialize(daemonize = true) + @daemonize = daemonize + end + + def newThread(runnable) + thread = java.util.concurrent.Executors.defaultThreadFactory().newThread(runnable) + thread.setDaemon(@daemonize) + return thread + end + end + + private_constant :DaemonThreadFactory + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/java_single_thread_executor.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/java_single_thread_executor.rb new file mode 100644 index 0000000..7aa24f2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/java_single_thread_executor.rb @@ -0,0 +1,30 @@ +if Concurrent.on_jruby? + + require 'concurrent/executor/java_executor_service' + require 'concurrent/executor/serial_executor_service' + + module Concurrent + + # @!macro single_thread_executor + # @!macro abstract_executor_service_public_api + # @!visibility private + class JavaSingleThreadExecutor < JavaExecutorService + include SerialExecutorService + + # @!macro single_thread_executor_method_initialize + def initialize(opts = {}) + super(opts) + end + + private + + def ns_initialize(opts) + @executor = java.util.concurrent.Executors.newSingleThreadExecutor( + DaemonThreadFactory.new(ns_auto_terminate?) + ) + @fallback_policy = opts.fetch(:fallback_policy, :discard) + raise ArgumentError.new("#{@fallback_policy} is not a valid fallback policy") unless FALLBACK_POLICY_CLASSES.keys.include?(@fallback_policy) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/java_thread_pool_executor.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/java_thread_pool_executor.rb new file mode 100644 index 0000000..1213a95 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/java_thread_pool_executor.rb @@ -0,0 +1,140 @@ +if Concurrent.on_jruby? + + require 'concurrent/executor/java_executor_service' + + module Concurrent + + # @!macro thread_pool_executor + # @!macro thread_pool_options + # @!visibility private + class JavaThreadPoolExecutor < JavaExecutorService + + # @!macro thread_pool_executor_constant_default_max_pool_size + DEFAULT_MAX_POOL_SIZE = java.lang.Integer::MAX_VALUE # 2147483647 + + # @!macro thread_pool_executor_constant_default_min_pool_size + DEFAULT_MIN_POOL_SIZE = 0 + + # @!macro thread_pool_executor_constant_default_max_queue_size + DEFAULT_MAX_QUEUE_SIZE = 0 + + # @!macro thread_pool_executor_constant_default_thread_timeout + DEFAULT_THREAD_IDLETIMEOUT = 60 + + # @!macro thread_pool_executor_constant_default_synchronous + DEFAULT_SYNCHRONOUS = false + + # @!macro thread_pool_executor_attr_reader_max_length + attr_reader :max_length + + # @!macro thread_pool_executor_attr_reader_max_queue + attr_reader :max_queue + + # @!macro thread_pool_executor_attr_reader_synchronous + attr_reader :synchronous + + # @!macro thread_pool_executor_method_initialize + def initialize(opts = {}) + super(opts) + end + + # @!macro executor_service_method_can_overflow_question + def can_overflow? + @max_queue != 0 + end + + # @!macro thread_pool_executor_attr_reader_min_length + def min_length + @executor.getCorePoolSize + end + + # @!macro thread_pool_executor_attr_reader_max_length + def max_length + @executor.getMaximumPoolSize + end + + # @!macro thread_pool_executor_attr_reader_length + def length + @executor.getPoolSize + end + + # @!macro thread_pool_executor_attr_reader_largest_length + def largest_length + @executor.getLargestPoolSize + end + + # @!macro thread_pool_executor_attr_reader_scheduled_task_count + def scheduled_task_count + @executor.getTaskCount + end + + # @!macro thread_pool_executor_attr_reader_completed_task_count + def completed_task_count + @executor.getCompletedTaskCount + end + + # @!macro thread_pool_executor_attr_reader_idletime + def idletime + @executor.getKeepAliveTime(java.util.concurrent.TimeUnit::SECONDS) + end + + # @!macro thread_pool_executor_attr_reader_queue_length + def queue_length + @executor.getQueue.size + end + + # @!macro thread_pool_executor_attr_reader_remaining_capacity + def remaining_capacity + @max_queue == 0 ? -1 : @executor.getQueue.remainingCapacity + end + + # @!macro executor_service_method_running_question + def running? + super && !@executor.isTerminating + end + + # @!macro thread_pool_executor_method_prune_pool + def prune_pool + end + + private + + def ns_initialize(opts) + min_length = opts.fetch(:min_threads, DEFAULT_MIN_POOL_SIZE).to_i + max_length = opts.fetch(:max_threads, DEFAULT_MAX_POOL_SIZE).to_i + idletime = opts.fetch(:idletime, DEFAULT_THREAD_IDLETIMEOUT).to_i + @max_queue = opts.fetch(:max_queue, DEFAULT_MAX_QUEUE_SIZE).to_i + @synchronous = opts.fetch(:synchronous, DEFAULT_SYNCHRONOUS) + @fallback_policy = opts.fetch(:fallback_policy, :abort) + + raise ArgumentError.new("`synchronous` cannot be set unless `max_queue` is 0") if @synchronous && @max_queue > 0 + raise ArgumentError.new("`max_threads` cannot be less than #{DEFAULT_MIN_POOL_SIZE}") if max_length < DEFAULT_MIN_POOL_SIZE + raise ArgumentError.new("`max_threads` cannot be greater than #{DEFAULT_MAX_POOL_SIZE}") if max_length > DEFAULT_MAX_POOL_SIZE + raise ArgumentError.new("`min_threads` cannot be less than #{DEFAULT_MIN_POOL_SIZE}") if min_length < DEFAULT_MIN_POOL_SIZE + raise ArgumentError.new("`min_threads` cannot be more than `max_threads`") if min_length > max_length + raise ArgumentError.new("#{fallback_policy} is not a valid fallback policy") unless FALLBACK_POLICY_CLASSES.include?(@fallback_policy) + + if @max_queue == 0 + if @synchronous + queue = java.util.concurrent.SynchronousQueue.new + else + queue = java.util.concurrent.LinkedBlockingQueue.new + end + else + queue = java.util.concurrent.LinkedBlockingQueue.new(@max_queue) + end + + @executor = java.util.concurrent.ThreadPoolExecutor.new( + min_length, + max_length, + idletime, + java.util.concurrent.TimeUnit::SECONDS, + queue, + DaemonThreadFactory.new(ns_auto_terminate?), + FALLBACK_POLICY_CLASSES[@fallback_policy].new) + + end + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/ruby_executor_service.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/ruby_executor_service.rb new file mode 100644 index 0000000..1f7301b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/ruby_executor_service.rb @@ -0,0 +1,82 @@ +require 'concurrent/executor/abstract_executor_service' +require 'concurrent/atomic/event' + +module Concurrent + + # @!macro abstract_executor_service_public_api + # @!visibility private + class RubyExecutorService < AbstractExecutorService + safe_initialization! + + def initialize(*args, &block) + super + @StopEvent = Event.new + @StoppedEvent = Event.new + end + + def post(*args, &task) + raise ArgumentError.new('no block given') unless block_given? + deferred_action = synchronize { + if running? + ns_execute(*args, &task) + else + fallback_action(*args, &task) + end + } + if deferred_action + deferred_action.call + else + true + end + end + + def shutdown + synchronize do + break unless running? + stop_event.set + ns_shutdown_execution + end + true + end + + def kill + synchronize do + break if shutdown? + stop_event.set + ns_kill_execution + stopped_event.set + end + true + end + + def wait_for_termination(timeout = nil) + stopped_event.wait(timeout) + end + + private + + def stop_event + @StopEvent + end + + def stopped_event + @StoppedEvent + end + + def ns_shutdown_execution + stopped_event.set + end + + def ns_running? + !stop_event.set? + end + + def ns_shuttingdown? + !(ns_running? || ns_shutdown?) + end + + def ns_shutdown? + stopped_event.set? + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/ruby_single_thread_executor.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/ruby_single_thread_executor.rb new file mode 100644 index 0000000..916337d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/ruby_single_thread_executor.rb @@ -0,0 +1,21 @@ +require 'concurrent/executor/ruby_thread_pool_executor' + +module Concurrent + + # @!macro single_thread_executor + # @!macro abstract_executor_service_public_api + # @!visibility private + class RubySingleThreadExecutor < RubyThreadPoolExecutor + + # @!macro single_thread_executor_method_initialize + def initialize(opts = {}) + super( + min_threads: 1, + max_threads: 1, + max_queue: 0, + idletime: DEFAULT_THREAD_IDLETIMEOUT, + fallback_policy: opts.fetch(:fallback_policy, :discard), + ) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/ruby_thread_pool_executor.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/ruby_thread_pool_executor.rb new file mode 100644 index 0000000..298dd7f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/ruby_thread_pool_executor.rb @@ -0,0 +1,366 @@ +require 'thread' +require 'concurrent/atomic/event' +require 'concurrent/concern/logging' +require 'concurrent/executor/ruby_executor_service' +require 'concurrent/utility/monotonic_time' + +module Concurrent + + # @!macro thread_pool_executor + # @!macro thread_pool_options + # @!visibility private + class RubyThreadPoolExecutor < RubyExecutorService + + # @!macro thread_pool_executor_constant_default_max_pool_size + DEFAULT_MAX_POOL_SIZE = 2_147_483_647 # java.lang.Integer::MAX_VALUE + + # @!macro thread_pool_executor_constant_default_min_pool_size + DEFAULT_MIN_POOL_SIZE = 0 + + # @!macro thread_pool_executor_constant_default_max_queue_size + DEFAULT_MAX_QUEUE_SIZE = 0 + + # @!macro thread_pool_executor_constant_default_thread_timeout + DEFAULT_THREAD_IDLETIMEOUT = 60 + + # @!macro thread_pool_executor_constant_default_synchronous + DEFAULT_SYNCHRONOUS = false + + # @!macro thread_pool_executor_attr_reader_max_length + attr_reader :max_length + + # @!macro thread_pool_executor_attr_reader_min_length + attr_reader :min_length + + # @!macro thread_pool_executor_attr_reader_idletime + attr_reader :idletime + + # @!macro thread_pool_executor_attr_reader_max_queue + attr_reader :max_queue + + # @!macro thread_pool_executor_attr_reader_synchronous + attr_reader :synchronous + + # @!macro thread_pool_executor_method_initialize + def initialize(opts = {}) + super(opts) + end + + # @!macro thread_pool_executor_attr_reader_largest_length + def largest_length + synchronize { @largest_length } + end + + # @!macro thread_pool_executor_attr_reader_scheduled_task_count + def scheduled_task_count + synchronize { @scheduled_task_count } + end + + # @!macro thread_pool_executor_attr_reader_completed_task_count + def completed_task_count + synchronize { @completed_task_count } + end + + # @!macro executor_service_method_can_overflow_question + def can_overflow? + synchronize { ns_limited_queue? } + end + + # @!macro thread_pool_executor_attr_reader_length + def length + synchronize { @pool.length } + end + + # @!macro thread_pool_executor_attr_reader_queue_length + def queue_length + synchronize { @queue.length } + end + + # @!macro thread_pool_executor_attr_reader_remaining_capacity + def remaining_capacity + synchronize do + if ns_limited_queue? + @max_queue - @queue.length + else + -1 + end + end + end + + # @!visibility private + def remove_busy_worker(worker) + synchronize { ns_remove_busy_worker worker } + end + + # @!visibility private + def ready_worker(worker, last_message) + synchronize { ns_ready_worker worker, last_message } + end + + # @!visibility private + def worker_died(worker) + synchronize { ns_worker_died worker } + end + + # @!visibility private + def worker_task_completed + synchronize { @completed_task_count += 1 } + end + + # @!macro thread_pool_executor_method_prune_pool + def prune_pool + synchronize { ns_prune_pool } + end + + private + + # @!visibility private + def ns_initialize(opts) + @min_length = opts.fetch(:min_threads, DEFAULT_MIN_POOL_SIZE).to_i + @max_length = opts.fetch(:max_threads, DEFAULT_MAX_POOL_SIZE).to_i + @idletime = opts.fetch(:idletime, DEFAULT_THREAD_IDLETIMEOUT).to_i + @max_queue = opts.fetch(:max_queue, DEFAULT_MAX_QUEUE_SIZE).to_i + @synchronous = opts.fetch(:synchronous, DEFAULT_SYNCHRONOUS) + @fallback_policy = opts.fetch(:fallback_policy, :abort) + + raise ArgumentError.new("`synchronous` cannot be set unless `max_queue` is 0") if @synchronous && @max_queue > 0 + raise ArgumentError.new("#{@fallback_policy} is not a valid fallback policy") unless FALLBACK_POLICIES.include?(@fallback_policy) + raise ArgumentError.new("`max_threads` cannot be less than #{DEFAULT_MIN_POOL_SIZE}") if @max_length < DEFAULT_MIN_POOL_SIZE + raise ArgumentError.new("`max_threads` cannot be greater than #{DEFAULT_MAX_POOL_SIZE}") if @max_length > DEFAULT_MAX_POOL_SIZE + raise ArgumentError.new("`min_threads` cannot be less than #{DEFAULT_MIN_POOL_SIZE}") if @min_length < DEFAULT_MIN_POOL_SIZE + raise ArgumentError.new("`min_threads` cannot be more than `max_threads`") if min_length > max_length + + @pool = [] # all workers + @ready = [] # used as a stash (most idle worker is at the start) + @queue = [] # used as queue + # @ready or @queue is empty at all times + @scheduled_task_count = 0 + @completed_task_count = 0 + @largest_length = 0 + @workers_counter = 0 + @ruby_pid = $$ # detects if Ruby has forked + + @gc_interval = opts.fetch(:gc_interval, @idletime / 2.0).to_i # undocumented + @next_gc_time = Concurrent.monotonic_time + @gc_interval + end + + # @!visibility private + def ns_limited_queue? + @max_queue != 0 + end + + # @!visibility private + def ns_execute(*args, &task) + ns_reset_if_forked + + if ns_assign_worker(*args, &task) || ns_enqueue(*args, &task) + @scheduled_task_count += 1 + else + return fallback_action(*args, &task) + end + + ns_prune_pool if @next_gc_time < Concurrent.monotonic_time + nil + end + + # @!visibility private + def ns_shutdown_execution + ns_reset_if_forked + + if @pool.empty? + # nothing to do + stopped_event.set + end + + if @queue.empty? + # no more tasks will be accepted, just stop all workers + @pool.each(&:stop) + end + end + + # @!visibility private + def ns_kill_execution + # TODO log out unprocessed tasks in queue + # TODO try to shutdown first? + @pool.each(&:kill) + @pool.clear + @ready.clear + end + + # tries to assign task to a worker, tries to get one from @ready or to create new one + # @return [true, false] if task is assigned to a worker + # + # @!visibility private + def ns_assign_worker(*args, &task) + # keep growing if the pool is not at the minimum yet + worker, _ = (@ready.pop if @pool.size >= @min_length) || ns_add_busy_worker + if worker + worker << [task, args] + true + else + false + end + rescue ThreadError + # Raised when the operating system refuses to create the new thread + return false + end + + # tries to enqueue task + # @return [true, false] if enqueued + # + # @!visibility private + def ns_enqueue(*args, &task) + return false if @synchronous + + if !ns_limited_queue? || @queue.size < @max_queue + @queue << [task, args] + true + else + false + end + end + + # @!visibility private + def ns_worker_died(worker) + ns_remove_busy_worker worker + replacement_worker = ns_add_busy_worker + ns_ready_worker replacement_worker, Concurrent.monotonic_time, false if replacement_worker + end + + # creates new worker which has to receive work to do after it's added + # @return [nil, Worker] nil of max capacity is reached + # + # @!visibility private + def ns_add_busy_worker + return if @pool.size >= @max_length + + @workers_counter += 1 + @pool << (worker = Worker.new(self, @workers_counter)) + @largest_length = @pool.length if @pool.length > @largest_length + worker + end + + # handle ready worker, giving it new job or assigning back to @ready + # + # @!visibility private + def ns_ready_worker(worker, last_message, success = true) + task_and_args = @queue.shift + if task_and_args + worker << task_and_args + else + # stop workers when !running?, do not return them to @ready + if running? + raise unless last_message + @ready.push([worker, last_message]) + else + worker.stop + end + end + end + + # removes a worker which is not in not tracked in @ready + # + # @!visibility private + def ns_remove_busy_worker(worker) + @pool.delete(worker) + stopped_event.set if @pool.empty? && !running? + true + end + + # try oldest worker if it is idle for enough time, it's returned back at the start + # + # @!visibility private + def ns_prune_pool + now = Concurrent.monotonic_time + stopped_workers = 0 + while !@ready.empty? && (@pool.size - stopped_workers > @min_length) + worker, last_message = @ready.first + if now - last_message > self.idletime + stopped_workers += 1 + @ready.shift + worker << :stop + else break + end + end + + @next_gc_time = Concurrent.monotonic_time + @gc_interval + end + + def ns_reset_if_forked + if $$ != @ruby_pid + @queue.clear + @ready.clear + @pool.clear + @scheduled_task_count = 0 + @completed_task_count = 0 + @largest_length = 0 + @workers_counter = 0 + @ruby_pid = $$ + end + end + + # @!visibility private + class Worker + include Concern::Logging + + def initialize(pool, id) + # instance variables accessed only under pool's lock so no need to sync here again + @queue = Queue.new + @pool = pool + @thread = create_worker @queue, pool, pool.idletime + + if @thread.respond_to?(:name=) + @thread.name = [pool.name, 'worker', id].compact.join('-') + end + end + + def <<(message) + @queue << message + end + + def stop + @queue << :stop + end + + def kill + @thread.kill + end + + private + + def create_worker(queue, pool, idletime) + Thread.new(queue, pool, idletime) do |my_queue, my_pool, my_idletime| + catch(:stop) do + loop do + + case message = my_queue.pop + when :stop + my_pool.remove_busy_worker(self) + throw :stop + + else + task, args = message + run_task my_pool, task, args + my_pool.ready_worker(self, Concurrent.monotonic_time) + end + end + end + end + end + + def run_task(pool, task, args) + task.call(*args) + pool.worker_task_completed + rescue => ex + # let it fail + log DEBUG, ex + rescue Exception => ex + log ERROR, ex + pool.worker_died(self) + throw :stop + end + end + + private_constant :Worker + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/safe_task_executor.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/safe_task_executor.rb new file mode 100644 index 0000000..17acfd5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/safe_task_executor.rb @@ -0,0 +1,35 @@ +require 'concurrent/synchronization' + +module Concurrent + + # A simple utility class that executes a callable and returns and array of three elements: + # success - indicating if the callable has been executed without errors + # value - filled by the callable result if it has been executed without errors, nil otherwise + # reason - the error risen by the callable if it has been executed with errors, nil otherwise + class SafeTaskExecutor < Synchronization::LockableObject + + def initialize(task, opts = {}) + @task = task + @exception_class = opts.fetch(:rescue_exception, false) ? Exception : StandardError + super() # ensures visibility + end + + # @return [Array] + def execute(*args) + success = true + value = reason = nil + + synchronize do + begin + value = @task.call(*args) + success = true + rescue @exception_class => ex + reason = ex + success = false + end + end + + [success, value, reason] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/serial_executor_service.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/serial_executor_service.rb new file mode 100644 index 0000000..f1c38ec --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/serial_executor_service.rb @@ -0,0 +1,34 @@ +require 'concurrent/executor/executor_service' + +module Concurrent + + # Indicates that the including `ExecutorService` guarantees + # that all operations will occur in the order they are post and that no + # two operations may occur simultaneously. This module provides no + # functionality and provides no guarantees. That is the responsibility + # of the including class. This module exists solely to allow the including + # object to be interrogated for its serialization status. + # + # @example + # class Foo + # include Concurrent::SerialExecutor + # end + # + # foo = Foo.new + # + # foo.is_a? Concurrent::ExecutorService #=> true + # foo.is_a? Concurrent::SerialExecutor #=> true + # foo.serialized? #=> true + # + # @!visibility private + module SerialExecutorService + include ExecutorService + + # @!macro executor_service_method_serialized_question + # + # @note Always returns `true` + def serialized? + true + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/serialized_execution.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/serialized_execution.rb new file mode 100644 index 0000000..d314e90 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/serialized_execution.rb @@ -0,0 +1,107 @@ +require 'concurrent/errors' +require 'concurrent/concern/logging' +require 'concurrent/synchronization' + +module Concurrent + + # Ensures passed jobs in a serialized order never running at the same time. + class SerializedExecution < Synchronization::LockableObject + include Concern::Logging + + def initialize() + super() + synchronize { ns_initialize } + end + + Job = Struct.new(:executor, :args, :block) do + def call + block.call(*args) + end + end + + # Submit a task to the executor for asynchronous processing. + # + # @param [Executor] executor to be used for this job + # + # @param [Array] args zero or more arguments to be passed to the task + # + # @yield the asynchronous task to perform + # + # @return [Boolean] `true` if the task is queued, `false` if the executor + # is not running + # + # @raise [ArgumentError] if no task is given + def post(executor, *args, &task) + posts [[executor, args, task]] + true + end + + # As {#post} but allows to submit multiple tasks at once, it's guaranteed that they will not + # be interleaved by other tasks. + # + # @param [Array, Proc)>] posts array of triplets where + # first is a {ExecutorService}, second is array of args for task, third is a task (Proc) + def posts(posts) + # if can_overflow? + # raise ArgumentError, 'SerializedExecution does not support thread-pools which can overflow' + # end + + return nil if posts.empty? + + jobs = posts.map { |executor, args, task| Job.new executor, args, task } + + job_to_post = synchronize do + if @being_executed + @stash.push(*jobs) + nil + else + @being_executed = true + @stash.push(*jobs[1..-1]) + jobs.first + end + end + + call_job job_to_post if job_to_post + true + end + + private + + def ns_initialize + @being_executed = false + @stash = [] + end + + def call_job(job) + did_it_run = begin + job.executor.post { work(job) } + true + rescue RejectedExecutionError => ex + false + end + + # TODO not the best idea to run it myself + unless did_it_run + begin + work job + rescue => ex + # let it fail + log DEBUG, ex + end + end + end + + # ensures next job is executed if any is stashed + def work(job) + job.call + ensure + synchronize do + job = @stash.shift || (@being_executed = false) + end + + # TODO maybe be able to tell caching pool to just enqueue this job, because the current one end at the end + # of this block + call_job job if job + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/serialized_execution_delegator.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/serialized_execution_delegator.rb new file mode 100644 index 0000000..8197781 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/serialized_execution_delegator.rb @@ -0,0 +1,28 @@ +require 'delegate' +require 'concurrent/executor/serial_executor_service' +require 'concurrent/executor/serialized_execution' + +module Concurrent + + # A wrapper/delegator for any `ExecutorService` that + # guarantees serialized execution of tasks. + # + # @see [SimpleDelegator](http://www.ruby-doc.org/stdlib-2.1.2/libdoc/delegate/rdoc/SimpleDelegator.html) + # @see Concurrent::SerializedExecution + class SerializedExecutionDelegator < SimpleDelegator + include SerialExecutorService + + def initialize(executor) + @executor = executor + @serializer = SerializedExecution.new + super(executor) + end + + # @!macro executor_service_method_post + def post(*args, &task) + raise ArgumentError.new('no block given') unless block_given? + return false unless running? + @serializer.post(@executor, *args, &task) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/simple_executor_service.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/simple_executor_service.rb new file mode 100644 index 0000000..b87fed5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/simple_executor_service.rb @@ -0,0 +1,100 @@ +require 'concurrent/atomics' +require 'concurrent/executor/executor_service' + +module Concurrent + + # An executor service in which every operation spawns a new, + # independently operating thread. + # + # This is perhaps the most inefficient executor service in this + # library. It exists mainly for testing an debugging. Thread creation + # and management is expensive in Ruby and this executor performs no + # resource pooling. This can be very beneficial during testing and + # debugging because it decouples the using code from the underlying + # executor implementation. In production this executor will likely + # lead to suboptimal performance. + # + # @note Intended for use primarily in testing and debugging. + class SimpleExecutorService < RubyExecutorService + + # @!macro executor_service_method_post + def self.post(*args) + raise ArgumentError.new('no block given') unless block_given? + Thread.new(*args) do + Thread.current.abort_on_exception = false + yield(*args) + end + true + end + + # @!macro executor_service_method_left_shift + def self.<<(task) + post(&task) + self + end + + # @!macro executor_service_method_post + def post(*args, &task) + raise ArgumentError.new('no block given') unless block_given? + return false unless running? + @count.increment + Thread.new(*args) do + Thread.current.abort_on_exception = false + begin + yield(*args) + ensure + @count.decrement + @stopped.set if @running.false? && @count.value == 0 + end + end + end + + # @!macro executor_service_method_left_shift + def <<(task) + post(&task) + self + end + + # @!macro executor_service_method_running_question + def running? + @running.true? + end + + # @!macro executor_service_method_shuttingdown_question + def shuttingdown? + @running.false? && ! @stopped.set? + end + + # @!macro executor_service_method_shutdown_question + def shutdown? + @stopped.set? + end + + # @!macro executor_service_method_shutdown + def shutdown + @running.make_false + @stopped.set if @count.value == 0 + true + end + + # @!macro executor_service_method_kill + def kill + @running.make_false + @stopped.set + true + end + + # @!macro executor_service_method_wait_for_termination + def wait_for_termination(timeout = nil) + @stopped.wait(timeout) + end + + private + + def ns_initialize(*args) + @running = Concurrent::AtomicBoolean.new(true) + @stopped = Concurrent::Event.new + @count = Concurrent::AtomicFixnum.new(0) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/single_thread_executor.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/single_thread_executor.rb new file mode 100644 index 0000000..f1474ea --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/single_thread_executor.rb @@ -0,0 +1,57 @@ +require 'concurrent/utility/engine' +require 'concurrent/executor/ruby_single_thread_executor' + +module Concurrent + + if Concurrent.on_jruby? + require 'concurrent/executor/java_single_thread_executor' + end + + SingleThreadExecutorImplementation = case + when Concurrent.on_jruby? + JavaSingleThreadExecutor + else + RubySingleThreadExecutor + end + private_constant :SingleThreadExecutorImplementation + + # @!macro single_thread_executor + # + # A thread pool with a single thread an unlimited queue. Should the thread + # die for any reason it will be removed and replaced, thus ensuring that + # the executor will always remain viable and available to process jobs. + # + # A common pattern for background processing is to create a single thread + # on which an infinite loop is run. The thread's loop blocks on an input + # source (perhaps blocking I/O or a queue) and processes each input as it + # is received. This pattern has several issues. The thread itself is highly + # susceptible to errors during processing. Also, the thread itself must be + # constantly monitored and restarted should it die. `SingleThreadExecutor` + # encapsulates all these bahaviors. The task processor is highly resilient + # to errors from within tasks. Also, should the thread die it will + # automatically be restarted. + # + # The API and behavior of this class are based on Java's `SingleThreadExecutor`. + # + # @!macro abstract_executor_service_public_api + class SingleThreadExecutor < SingleThreadExecutorImplementation + + # @!macro single_thread_executor_method_initialize + # + # Create a new thread pool. + # + # @option opts [Symbol] :fallback_policy (:discard) the policy for handling new + # tasks that are received when the queue size has reached + # `max_queue` or the executor has shut down + # + # @raise [ArgumentError] if `:fallback_policy` is not one of the values specified + # in `FALLBACK_POLICIES` + # + # @see http://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html + # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html + # @see http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html + + # @!method initialize(opts = {}) + # @!macro single_thread_executor_method_initialize + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/thread_pool_executor.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/thread_pool_executor.rb new file mode 100644 index 0000000..253d46a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/thread_pool_executor.rb @@ -0,0 +1,88 @@ +require 'concurrent/utility/engine' +require 'concurrent/executor/ruby_thread_pool_executor' + +module Concurrent + + if Concurrent.on_jruby? + require 'concurrent/executor/java_thread_pool_executor' + end + + ThreadPoolExecutorImplementation = case + when Concurrent.on_jruby? + JavaThreadPoolExecutor + else + RubyThreadPoolExecutor + end + private_constant :ThreadPoolExecutorImplementation + + # @!macro thread_pool_executor + # + # An abstraction composed of one or more threads and a task queue. Tasks + # (blocks or `proc` objects) are submitted to the pool and added to the queue. + # The threads in the pool remove the tasks and execute them in the order + # they were received. + # + # A `ThreadPoolExecutor` will automatically adjust the pool size according + # to the bounds set by `min-threads` and `max-threads`. When a new task is + # submitted and fewer than `min-threads` threads are running, a new thread + # is created to handle the request, even if other worker threads are idle. + # If there are more than `min-threads` but less than `max-threads` threads + # running, a new thread will be created only if the queue is full. + # + # Threads that are idle for too long will be garbage collected, down to the + # configured minimum options. Should a thread crash it, too, will be garbage collected. + # + # `ThreadPoolExecutor` is based on the Java class of the same name. From + # the official Java documentation; + # + # > Thread pools address two different problems: they usually provide + # > improved performance when executing large numbers of asynchronous tasks, + # > due to reduced per-task invocation overhead, and they provide a means + # > of bounding and managing the resources, including threads, consumed + # > when executing a collection of tasks. Each ThreadPoolExecutor also + # > maintains some basic statistics, such as the number of completed tasks. + # > + # > To be useful across a wide range of contexts, this class provides many + # > adjustable parameters and extensibility hooks. However, programmers are + # > urged to use the more convenient Executors factory methods + # > [CachedThreadPool] (unbounded thread pool, with automatic thread reclamation), + # > [FixedThreadPool] (fixed size thread pool) and [SingleThreadExecutor] (single + # > background thread), that preconfigure settings for the most common usage + # > scenarios. + # + # @!macro thread_pool_options + # + # @!macro thread_pool_executor_public_api + class ThreadPoolExecutor < ThreadPoolExecutorImplementation + + # @!macro thread_pool_executor_method_initialize + # + # Create a new thread pool. + # + # @param [Hash] opts the options which configure the thread pool. + # + # @option opts [Integer] :max_threads (DEFAULT_MAX_POOL_SIZE) the maximum + # number of threads to be created + # @option opts [Integer] :min_threads (DEFAULT_MIN_POOL_SIZE) When a new task is submitted + # and fewer than `min_threads` are running, a new thread is created + # @option opts [Integer] :idletime (DEFAULT_THREAD_IDLETIMEOUT) the maximum + # number of seconds a thread may be idle before being reclaimed + # @option opts [Integer] :max_queue (DEFAULT_MAX_QUEUE_SIZE) the maximum + # number of tasks allowed in the work queue at any one time; a value of + # zero means the queue may grow without bound + # @option opts [Symbol] :fallback_policy (:abort) the policy for handling new + # tasks that are received when the queue size has reached + # `max_queue` or the executor has shut down + # @option opts [Boolean] :synchronous (DEFAULT_SYNCHRONOUS) whether or not a value of 0 + # for :max_queue means the queue must perform direct hand-off rather than unbounded. + # @raise [ArgumentError] if `:max_threads` is less than one + # @raise [ArgumentError] if `:min_threads` is less than zero + # @raise [ArgumentError] if `:fallback_policy` is not one of the values specified + # in `FALLBACK_POLICIES` + # + # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html + + # @!method initialize(opts = {}) + # @!macro thread_pool_executor_method_initialize + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/timer_set.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/timer_set.rb new file mode 100644 index 0000000..0dfaf12 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executor/timer_set.rb @@ -0,0 +1,172 @@ +require 'concurrent/scheduled_task' +require 'concurrent/atomic/event' +require 'concurrent/collection/non_concurrent_priority_queue' +require 'concurrent/executor/executor_service' +require 'concurrent/executor/single_thread_executor' + +require 'concurrent/options' + +module Concurrent + + # Executes a collection of tasks, each after a given delay. A master task + # monitors the set and schedules each task for execution at the appropriate + # time. Tasks are run on the global thread pool or on the supplied executor. + # Each task is represented as a `ScheduledTask`. + # + # @see Concurrent::ScheduledTask + # + # @!macro monotonic_clock_warning + class TimerSet < RubyExecutorService + + # Create a new set of timed tasks. + # + # @!macro executor_options + # + # @param [Hash] opts the options used to specify the executor on which to perform actions + # @option opts [Executor] :executor when set use the given `Executor` instance. + # Three special values are also supported: `:task` returns the global task pool, + # `:operation` returns the global operation pool, and `:immediate` returns a new + # `ImmediateExecutor` object. + def initialize(opts = {}) + super(opts) + end + + # Post a task to be execute run after a given delay (in seconds). If the + # delay is less than 1/100th of a second the task will be immediately post + # to the executor. + # + # @param [Float] delay the number of seconds to wait for before executing the task. + # @param [Array] args the arguments passed to the task on execution. + # + # @yield the task to be performed. + # + # @return [Concurrent::ScheduledTask, false] IVar representing the task if the post + # is successful; false after shutdown. + # + # @raise [ArgumentError] if the intended execution time is not in the future. + # @raise [ArgumentError] if no block is given. + def post(delay, *args, &task) + raise ArgumentError.new('no block given') unless block_given? + return false unless running? + opts = { executor: @task_executor, + args: args, + timer_set: self } + task = ScheduledTask.execute(delay, opts, &task) # may raise exception + task.unscheduled? ? false : task + end + + # Begin an immediate shutdown. In-progress tasks will be allowed to + # complete but enqueued tasks will be dismissed and no new tasks + # will be accepted. Has no additional effect if the thread pool is + # not running. + def kill + shutdown + end + + private :<< + + private + + # Initialize the object. + # + # @param [Hash] opts the options to create the object with. + # @!visibility private + def ns_initialize(opts) + @queue = Collection::NonConcurrentPriorityQueue.new(order: :min) + @task_executor = Options.executor_from_options(opts) || Concurrent.global_io_executor + @timer_executor = SingleThreadExecutor.new + @condition = Event.new + @ruby_pid = $$ # detects if Ruby has forked + end + + # Post the task to the internal queue. + # + # @note This is intended as a callback method from ScheduledTask + # only. It is not intended to be used directly. Post a task + # by using the `SchedulesTask#execute` method. + # + # @!visibility private + def post_task(task) + synchronize { ns_post_task(task) } + end + + # @!visibility private + def ns_post_task(task) + return false unless ns_running? + ns_reset_if_forked + if (task.initial_delay) <= 0.01 + task.executor.post { task.process_task } + else + @queue.push(task) + # only post the process method when the queue is empty + @timer_executor.post(&method(:process_tasks)) if @queue.length == 1 + @condition.set + end + true + end + + # Remove the given task from the queue. + # + # @note This is intended as a callback method from `ScheduledTask` + # only. It is not intended to be used directly. Cancel a task + # by using the `ScheduledTask#cancel` method. + # + # @!visibility private + def remove_task(task) + synchronize { @queue.delete(task) } + end + + # `ExecutorService` callback called during shutdown. + # + # @!visibility private + def ns_shutdown_execution + ns_reset_if_forked + @queue.clear + @timer_executor.kill + stopped_event.set + end + + def ns_reset_if_forked + if $$ != @ruby_pid + @queue.clear + @condition.reset + @ruby_pid = $$ + end + end + + # Run a loop and execute tasks in the scheduled order and at the approximate + # scheduled time. If no tasks remain the thread will exit gracefully so that + # garbage collection can occur. If there are no ready tasks it will sleep + # for up to 60 seconds waiting for the next scheduled task. + # + # @!visibility private + def process_tasks + loop do + task = synchronize { @condition.reset; @queue.peek } + break unless task + + now = Concurrent.monotonic_time + diff = task.schedule_time - now + + if diff <= 0 + # We need to remove the task from the queue before passing + # it to the executor, to avoid race conditions where we pass + # the peek'ed task to the executor and then pop a different + # one that's been added in the meantime. + # + # Note that there's no race condition between the peek and + # this pop - this pop could retrieve a different task from + # the peek, but that task would be due to fire now anyway + # (because @queue is a priority queue, and this thread is + # the only reader, so whatever timer is at the head of the + # queue now must have the same pop time, or a closer one, as + # when we peeked). + task = synchronize { @queue.pop } + task.executor.post { task.process_task } + else + @condition.wait([diff, 60].min) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executors.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executors.rb new file mode 100644 index 0000000..eb1972c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/executors.rb @@ -0,0 +1,20 @@ +require 'concurrent/executor/abstract_executor_service' +require 'concurrent/executor/cached_thread_pool' +require 'concurrent/executor/executor_service' +require 'concurrent/executor/fixed_thread_pool' +require 'concurrent/executor/immediate_executor' +require 'concurrent/executor/indirect_immediate_executor' +require 'concurrent/executor/java_executor_service' +require 'concurrent/executor/java_single_thread_executor' +require 'concurrent/executor/java_thread_pool_executor' +require 'concurrent/executor/ruby_executor_service' +require 'concurrent/executor/ruby_single_thread_executor' +require 'concurrent/executor/ruby_thread_pool_executor' +require 'concurrent/executor/cached_thread_pool' +require 'concurrent/executor/safe_task_executor' +require 'concurrent/executor/serial_executor_service' +require 'concurrent/executor/serialized_execution' +require 'concurrent/executor/serialized_execution_delegator' +require 'concurrent/executor/single_thread_executor' +require 'concurrent/executor/thread_pool_executor' +require 'concurrent/executor/timer_set' diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/future.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/future.rb new file mode 100644 index 0000000..1af182e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/future.rb @@ -0,0 +1,141 @@ +require 'thread' +require 'concurrent/constants' +require 'concurrent/errors' +require 'concurrent/ivar' +require 'concurrent/executor/safe_task_executor' + +require 'concurrent/options' + +# TODO (pitr-ch 14-Mar-2017): deprecate, Future, Promise, etc. + + +module Concurrent + + # {include:file:docs-source/future.md} + # + # @!macro copy_options + # + # @see http://ruby-doc.org/stdlib-2.1.1/libdoc/observer/rdoc/Observable.html Ruby Observable module + # @see http://clojuredocs.org/clojure_core/clojure.core/future Clojure's future function + # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html java.util.concurrent.Future + class Future < IVar + + # Create a new `Future` in the `:unscheduled` state. + # + # @yield the asynchronous operation to perform + # + # @!macro executor_and_deref_options + # + # @option opts [object, Array] :args zero or more arguments to be passed the task + # block on execution + # + # @raise [ArgumentError] if no block is given + def initialize(opts = {}, &block) + raise ArgumentError.new('no block given') unless block_given? + super(NULL, opts.merge(__task_from_block__: block), &nil) + end + + # Execute an `:unscheduled` `Future`. Immediately sets the state to `:pending` and + # passes the block to a new thread/thread pool for eventual execution. + # Does nothing if the `Future` is in any state other than `:unscheduled`. + # + # @return [Future] a reference to `self` + # + # @example Instance and execute in separate steps + # future = Concurrent::Future.new{ sleep(1); 42 } + # future.state #=> :unscheduled + # future.execute + # future.state #=> :pending + # + # @example Instance and execute in one line + # future = Concurrent::Future.new{ sleep(1); 42 }.execute + # future.state #=> :pending + def execute + if compare_and_set_state(:pending, :unscheduled) + @executor.post{ safe_execute(@task, @args) } + self + end + end + + # Create a new `Future` object with the given block, execute it, and return the + # `:pending` object. + # + # @yield the asynchronous operation to perform + # + # @!macro executor_and_deref_options + # + # @option opts [object, Array] :args zero or more arguments to be passed the task + # block on execution + # + # @raise [ArgumentError] if no block is given + # + # @return [Future] the newly created `Future` in the `:pending` state + # + # @example + # future = Concurrent::Future.execute{ sleep(1); 42 } + # future.state #=> :pending + def self.execute(opts = {}, &block) + Future.new(opts, &block).execute + end + + # @!macro ivar_set_method + def set(value = NULL, &block) + check_for_block_or_value!(block_given?, value) + synchronize do + if @state != :unscheduled + raise MultipleAssignmentError + else + @task = block || Proc.new { value } + end + end + execute + end + + # Attempt to cancel the operation if it has not already processed. + # The operation can only be cancelled while still `pending`. It cannot + # be cancelled once it has begun processing or has completed. + # + # @return [Boolean] was the operation successfully cancelled. + def cancel + if compare_and_set_state(:cancelled, :pending) + complete(false, nil, CancelledOperationError.new) + true + else + false + end + end + + # Has the operation been successfully cancelled? + # + # @return [Boolean] + def cancelled? + state == :cancelled + end + + # Wait the given number of seconds for the operation to complete. + # On timeout attempt to cancel the operation. + # + # @param [Numeric] timeout the maximum time in seconds to wait. + # @return [Boolean] true if the operation completed before the timeout + # else false + def wait_or_cancel(timeout) + wait(timeout) + if complete? + true + else + cancel + false + end + end + + protected + + def ns_initialize(value, opts) + super + @state = :unscheduled + @task = opts[:__task_from_block__] + @executor = Options.executor_from_options(opts) || Concurrent.global_io_executor + @args = get_arguments_from(opts) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/hash.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/hash.rb new file mode 100644 index 0000000..92df66b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/hash.rb @@ -0,0 +1,59 @@ +require 'concurrent/utility/engine' +require 'concurrent/thread_safe/util' + +module Concurrent + + # @!macro concurrent_hash + # + # A thread-safe subclass of Hash. This version locks against the object + # itself for every method call, ensuring only one thread can be reading + # or writing at a time. This includes iteration methods like `#each`, + # which takes the lock repeatedly when reading an item. + # + # @see http://ruby-doc.org/core/Hash.html Ruby standard library `Hash` + + # @!macro internal_implementation_note + HashImplementation = case + when Concurrent.on_cruby? + # Hash is thread-safe in practice because CRuby runs + # threads one at a time and does not do context + # switching during the execution of C functions. + ::Hash + + when Concurrent.on_jruby? + require 'jruby/synchronized' + + class JRubyHash < ::Hash + include JRuby::Synchronized + end + JRubyHash + + when Concurrent.on_rbx? + require 'monitor' + require 'concurrent/thread_safe/util/data_structures' + + class RbxHash < ::Hash + end + ThreadSafe::Util.make_synchronized_on_rbx RbxHash + RbxHash + + when Concurrent.on_truffleruby? + require 'concurrent/thread_safe/util/data_structures' + + class TruffleRubyHash < ::Hash + end + + ThreadSafe::Util.make_synchronized_on_truffleruby TruffleRubyHash + TruffleRubyHash + + else + warn 'Possibly unsupported Ruby implementation' + ::Hash + end + private_constant :HashImplementation + + # @!macro concurrent_hash + class Hash < HashImplementation + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/immutable_struct.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/immutable_struct.rb new file mode 100644 index 0000000..d275595 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/immutable_struct.rb @@ -0,0 +1,101 @@ +require 'concurrent/synchronization/abstract_struct' +require 'concurrent/synchronization' + +module Concurrent + + # A thread-safe, immutable variation of Ruby's standard `Struct`. + # + # @see http://ruby-doc.org/core/Struct.html Ruby standard library `Struct` + module ImmutableStruct + include Synchronization::AbstractStruct + + def self.included(base) + base.safe_initialization! + end + + # @!macro struct_values + def values + ns_values + end + + alias_method :to_a, :values + + # @!macro struct_values_at + def values_at(*indexes) + ns_values_at(indexes) + end + + # @!macro struct_inspect + def inspect + ns_inspect + end + + alias_method :to_s, :inspect + + # @!macro struct_merge + def merge(other, &block) + ns_merge(other, &block) + end + + # @!macro struct_to_h + def to_h + ns_to_h + end + + # @!macro struct_get + def [](member) + ns_get(member) + end + + # @!macro struct_equality + def ==(other) + ns_equality(other) + end + + # @!macro struct_each + def each(&block) + return enum_for(:each) unless block_given? + ns_each(&block) + end + + # @!macro struct_each_pair + def each_pair(&block) + return enum_for(:each_pair) unless block_given? + ns_each_pair(&block) + end + + # @!macro struct_select + def select(&block) + return enum_for(:select) unless block_given? + ns_select(&block) + end + + private + + # @!visibility private + def initialize_copy(original) + super(original) + ns_initialize_copy + end + + # @!macro struct_new + def self.new(*args, &block) + clazz_name = nil + if args.length == 0 + raise ArgumentError.new('wrong number of arguments (0 for 1+)') + elsif args.length > 0 && args.first.is_a?(String) + clazz_name = args.shift + end + FACTORY.define_struct(clazz_name, args, &block) + end + + FACTORY = Class.new(Synchronization::LockableObject) do + def define_struct(name, members, &block) + synchronize do + Synchronization::AbstractStruct.define_struct_class(ImmutableStruct, Synchronization::Object, name, members, &block) + end + end + end.new + private_constant :FACTORY + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/ivar.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/ivar.rb new file mode 100644 index 0000000..2a724db --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/ivar.rb @@ -0,0 +1,207 @@ +require 'concurrent/constants' +require 'concurrent/errors' +require 'concurrent/collection/copy_on_write_observer_set' +require 'concurrent/concern/obligation' +require 'concurrent/concern/observable' +require 'concurrent/synchronization' + +module Concurrent + + # An `IVar` is like a future that you can assign. As a future is a value that + # is being computed that you can wait on, an `IVar` is a value that is waiting + # to be assigned, that you can wait on. `IVars` are single assignment and + # deterministic. + # + # Then, express futures as an asynchronous computation that assigns an `IVar`. + # The `IVar` becomes the primitive on which [futures](Future) and + # [dataflow](Dataflow) are built. + # + # An `IVar` is a single-element container that is normally created empty, and + # can only be set once. The I in `IVar` stands for immutable. Reading an + # `IVar` normally blocks until it is set. It is safe to set and read an `IVar` + # from different threads. + # + # If you want to have some parallel task set the value in an `IVar`, you want + # a `Future`. If you want to create a graph of parallel tasks all executed + # when the values they depend on are ready you want `dataflow`. `IVar` is + # generally a low-level primitive. + # + # ## Examples + # + # Create, set and get an `IVar` + # + # ```ruby + # ivar = Concurrent::IVar.new + # ivar.set 14 + # ivar.value #=> 14 + # ivar.set 2 # would now be an error + # ``` + # + # ## See Also + # + # 1. For the theory: Arvind, R. Nikhil, and K. Pingali. + # [I-Structures: Data structures for parallel computing](http://dl.acm.org/citation.cfm?id=69562). + # In Proceedings of Workshop on Graph Reduction, 1986. + # 2. For recent application: + # [DataDrivenFuture in Habanero Java from Rice](http://www.cs.rice.edu/~vs3/hjlib/doc/edu/rice/hj/api/HjDataDrivenFuture.html). + class IVar < Synchronization::LockableObject + include Concern::Obligation + include Concern::Observable + + # Create a new `IVar` in the `:pending` state with the (optional) initial value. + # + # @param [Object] value the initial value + # @param [Hash] opts the options to create a message with + # @option opts [String] :dup_on_deref (false) call `#dup` before returning + # the data + # @option opts [String] :freeze_on_deref (false) call `#freeze` before + # returning the data + # @option opts [String] :copy_on_deref (nil) call the given `Proc` passing + # the internal value and returning the value returned from the proc + def initialize(value = NULL, opts = {}, &block) + if value != NULL && block_given? + raise ArgumentError.new('provide only a value or a block') + end + super(&nil) + synchronize { ns_initialize(value, opts, &block) } + end + + # Add an observer on this object that will receive notification on update. + # + # Upon completion the `IVar` will notify all observers in a thread-safe way. + # The `func` method of the observer will be called with three arguments: the + # `Time` at which the `Future` completed the asynchronous operation, the + # final `value` (or `nil` on rejection), and the final `reason` (or `nil` on + # fulfillment). + # + # @param [Object] observer the object that will be notified of changes + # @param [Symbol] func symbol naming the method to call when this + # `Observable` has changes` + def add_observer(observer = nil, func = :update, &block) + raise ArgumentError.new('cannot provide both an observer and a block') if observer && block + direct_notification = false + + if block + observer = block + func = :call + end + + synchronize do + if event.set? + direct_notification = true + else + observers.add_observer(observer, func) + end + end + + observer.send(func, Time.now, self.value, reason) if direct_notification + observer + end + + # @!macro ivar_set_method + # Set the `IVar` to a value and wake or notify all threads waiting on it. + # + # @!macro ivar_set_parameters_and_exceptions + # @param [Object] value the value to store in the `IVar` + # @yield A block operation to use for setting the value + # @raise [ArgumentError] if both a value and a block are given + # @raise [Concurrent::MultipleAssignmentError] if the `IVar` has already + # been set or otherwise completed + # + # @return [IVar] self + def set(value = NULL) + check_for_block_or_value!(block_given?, value) + raise MultipleAssignmentError unless compare_and_set_state(:processing, :pending) + + begin + value = yield if block_given? + complete_without_notification(true, value, nil) + rescue => ex + complete_without_notification(false, nil, ex) + end + + notify_observers(self.value, reason) + self + end + + # @!macro ivar_fail_method + # Set the `IVar` to failed due to some error and wake or notify all threads waiting on it. + # + # @param [Object] reason for the failure + # @raise [Concurrent::MultipleAssignmentError] if the `IVar` has already + # been set or otherwise completed + # @return [IVar] self + def fail(reason = StandardError.new) + complete(false, nil, reason) + end + + # Attempt to set the `IVar` with the given value or block. Return a + # boolean indicating the success or failure of the set operation. + # + # @!macro ivar_set_parameters_and_exceptions + # + # @return [Boolean] true if the value was set else false + def try_set(value = NULL, &block) + set(value, &block) + true + rescue MultipleAssignmentError + false + end + + protected + + # @!visibility private + def ns_initialize(value, opts) + value = yield if block_given? + init_obligation + self.observers = Collection::CopyOnWriteObserverSet.new + set_deref_options(opts) + + @state = :pending + if value != NULL + ns_complete_without_notification(true, value, nil) + end + end + + # @!visibility private + def safe_execute(task, args = []) + if compare_and_set_state(:processing, :pending) + success, val, reason = SafeTaskExecutor.new(task, rescue_exception: true).execute(*@args) + complete(success, val, reason) + yield(success, val, reason) if block_given? + end + end + + # @!visibility private + def complete(success, value, reason) + complete_without_notification(success, value, reason) + notify_observers(self.value, reason) + self + end + + # @!visibility private + def complete_without_notification(success, value, reason) + synchronize { ns_complete_without_notification(success, value, reason) } + self + end + + # @!visibility private + def notify_observers(value, reason) + observers.notify_and_delete_observers{ [Time.now, value, reason] } + end + + # @!visibility private + def ns_complete_without_notification(success, value, reason) + raise MultipleAssignmentError if [:fulfilled, :rejected].include? @state + set_state(success, value, reason) + event.set + end + + # @!visibility private + def check_for_block_or_value!(block_given, value) # :nodoc: + if (block_given && value != NULL) || (! block_given && value == NULL) + raise ArgumentError.new('must set with either a value or a block') + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/map.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/map.rb new file mode 100644 index 0000000..808757f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/map.rb @@ -0,0 +1,346 @@ +require 'thread' +require 'concurrent/constants' +require 'concurrent/synchronization' +require 'concurrent/utility/engine' + +module Concurrent + # @!visibility private + module Collection + + # @!visibility private + MapImplementation = case + when Concurrent.on_jruby? + # noinspection RubyResolve + JRubyMapBackend + when Concurrent.on_cruby? + require 'concurrent/collection/map/mri_map_backend' + MriMapBackend + when Concurrent.on_truffleruby? && defined?(::TruffleRuby::ConcurrentMap) + require 'concurrent/collection/map/truffleruby_map_backend' + TruffleRubyMapBackend + when Concurrent.on_truffleruby? || Concurrent.on_rbx? + require 'concurrent/collection/map/atomic_reference_map_backend' + AtomicReferenceMapBackend + else + warn 'Concurrent::Map: unsupported Ruby engine, using a fully synchronized Concurrent::Map implementation' + require 'concurrent/collection/map/synchronized_map_backend' + SynchronizedMapBackend + end + end + + # `Concurrent::Map` is a hash-like object and should have much better performance + # characteristics, especially under high concurrency, than `Concurrent::Hash`. + # However, `Concurrent::Map `is not strictly semantically equivalent to a ruby `Hash` + # -- for instance, it does not necessarily retain ordering by insertion time as `Hash` + # does. For most uses it should do fine though, and we recommend you consider + # `Concurrent::Map` instead of `Concurrent::Hash` for your concurrency-safe hash needs. + class Map < Collection::MapImplementation + + # @!macro map.atomic_method + # This method is atomic. + + # @!macro map.atomic_method_with_block + # This method is atomic. + # @note Atomic methods taking a block do not allow the `self` instance + # to be used within the block. Doing so will cause a deadlock. + + # @!method compute_if_absent(key) + # Compute and store new value for key if the key is absent. + # @param [Object] key + # @yield new value + # @yieldreturn [Object] new value + # @return [Object] new value or current value + # @!macro map.atomic_method_with_block + + # @!method compute_if_present(key) + # Compute and store new value for key if the key is present. + # @param [Object] key + # @yield new value + # @yieldparam old_value [Object] + # @yieldreturn [Object, nil] new value, when nil the key is removed + # @return [Object, nil] new value or nil + # @!macro map.atomic_method_with_block + + # @!method compute(key) + # Compute and store new value for key. + # @param [Object] key + # @yield compute new value from old one + # @yieldparam old_value [Object, nil] old_value, or nil when key is absent + # @yieldreturn [Object, nil] new value, when nil the key is removed + # @return [Object, nil] new value or nil + # @!macro map.atomic_method_with_block + + # @!method merge_pair(key, value) + # If the key is absent, the value is stored, otherwise new value is + # computed with a block. + # @param [Object] key + # @param [Object] value + # @yield compute new value from old one + # @yieldparam old_value [Object] old value + # @yieldreturn [Object, nil] new value, when nil the key is removed + # @return [Object, nil] new value or nil + # @!macro map.atomic_method_with_block + + # @!method replace_pair(key, old_value, new_value) + # Replaces old_value with new_value if key exists and current value + # matches old_value + # @param [Object] key + # @param [Object] old_value + # @param [Object] new_value + # @return [true, false] true if replaced + # @!macro map.atomic_method + + # @!method replace_if_exists(key, new_value) + # Replaces current value with new_value if key exists + # @param [Object] key + # @param [Object] new_value + # @return [Object, nil] old value or nil + # @!macro map.atomic_method + + # @!method get_and_set(key, value) + # Get the current value under key and set new value. + # @param [Object] key + # @param [Object] value + # @return [Object, nil] old value or nil when the key was absent + # @!macro map.atomic_method + + # @!method delete(key) + # Delete key and its value. + # @param [Object] key + # @return [Object, nil] old value or nil when the key was absent + # @!macro map.atomic_method + + # @!method delete_pair(key, value) + # Delete pair and its value if current value equals the provided value. + # @param [Object] key + # @param [Object] value + # @return [true, false] true if deleted + # @!macro map.atomic_method + + # + def initialize(options = nil, &block) + if options.kind_of?(::Hash) + validate_options_hash!(options) + else + options = nil + end + + super(options) + @default_proc = block + end + + # Get a value with key + # @param [Object] key + # @return [Object] the value + def [](key) + if value = super # non-falsy value is an existing mapping, return it right away + value + # re-check is done with get_or_default(key, NULL) instead of a simple !key?(key) in order to avoid a race condition, whereby by the time the current thread gets to the key?(key) call + # a key => value mapping might have already been created by a different thread (key?(key) would then return true, this elsif branch wouldn't be taken and an incorrent +nil+ value + # would be returned) + # note: nil == value check is not technically necessary + elsif @default_proc && nil == value && NULL == (value = get_or_default(key, NULL)) + @default_proc.call(self, key) + else + value + end + end + + # Set a value with key + # @param [Object] key + # @param [Object] value + # @return [Object] the new value + def []=(key, value) + super + end + + alias_method :get, :[] + alias_method :put, :[]= + + # Get a value with key, or default_value when key is absent, + # or fail when no default_value is given. + # @param [Object] key + # @param [Object] default_value + # @yield default value for a key + # @yieldparam key [Object] + # @yieldreturn [Object] default value + # @return [Object] the value or default value + # @raise [KeyError] when key is missing and no default_value is provided + # @!macro map_method_not_atomic + # @note The "fetch-then-act" methods of `Map` are not atomic. `Map` is intended + # to be use as a concurrency primitive with strong happens-before + # guarantees. It is not intended to be used as a high-level abstraction + # supporting complex operations. All read and write operations are + # thread safe, but no guarantees are made regarding race conditions + # between the fetch operation and yielding to the block. Additionally, + # this method does not support recursion. This is due to internal + # constraints that are very unlikely to change in the near future. + def fetch(key, default_value = NULL) + if NULL != (value = get_or_default(key, NULL)) + value + elsif block_given? + yield key + elsif NULL != default_value + default_value + else + raise_fetch_no_key + end + end + + # Fetch value with key, or store default value when key is absent, + # or fail when no default_value is given. This is a two step operation, + # therefore not atomic. The store can overwrite other concurrently + # stored value. + # @param [Object] key + # @param [Object] default_value + # @yield default value for a key + # @yieldparam key [Object] + # @yieldreturn [Object] default value + # @return [Object] the value or default value + # @!macro map.atomic_method_with_block + def fetch_or_store(key, default_value = NULL) + fetch(key) do + put(key, block_given? ? yield(key) : (NULL == default_value ? raise_fetch_no_key : default_value)) + end + end + + # Insert value into map with key if key is absent in one atomic step. + # @param [Object] key + # @param [Object] value + # @return [Object, nil] the previous value when key was present or nil when there was no key + def put_if_absent(key, value) + computed = false + result = compute_if_absent(key) do + computed = true + value + end + computed ? nil : result + end unless method_defined?(:put_if_absent) + + # Is the value stored in the map. Iterates over all values. + # @param [Object] value + # @return [true, false] + def value?(value) + each_value do |v| + return true if value.equal?(v) + end + false + end + + # All keys + # @return [::Array] keys + def keys + arr = [] + each_pair { |k, v| arr << k } + arr + end unless method_defined?(:keys) + + # All values + # @return [::Array] values + def values + arr = [] + each_pair { |k, v| arr << v } + arr + end unless method_defined?(:values) + + # Iterates over each key. + # @yield for each key in the map + # @yieldparam key [Object] + # @return [self] + # @!macro map.atomic_method_with_block + def each_key + each_pair { |k, v| yield k } + end unless method_defined?(:each_key) + + # Iterates over each value. + # @yield for each value in the map + # @yieldparam value [Object] + # @return [self] + # @!macro map.atomic_method_with_block + def each_value + each_pair { |k, v| yield v } + end unless method_defined?(:each_value) + + # Iterates over each key value pair. + # @yield for each key value pair in the map + # @yieldparam key [Object] + # @yieldparam value [Object] + # @return [self] + # @!macro map.atomic_method_with_block + def each_pair + return enum_for :each_pair unless block_given? + super + end + + alias_method :each, :each_pair unless method_defined?(:each) + + # Find key of a value. + # @param [Object] value + # @return [Object, nil] key or nil when not found + def key(value) + each_pair { |k, v| return k if v == value } + nil + end unless method_defined?(:key) + + # Is map empty? + # @return [true, false] + def empty? + each_pair { |k, v| return false } + true + end unless method_defined?(:empty?) + + # The size of map. + # @return [Integer] size + def size + count = 0 + each_pair { |k, v| count += 1 } + count + end unless method_defined?(:size) + + # @!visibility private + def marshal_dump + raise TypeError, "can't dump hash with default proc" if @default_proc + h = {} + each_pair { |k, v| h[k] = v } + h + end + + # @!visibility private + def marshal_load(hash) + initialize + populate_from(hash) + end + + undef :freeze + + # @!visibility private + def inspect + format '%s entries=%d default_proc=%s>', to_s[0..-2], size.to_s, @default_proc.inspect + end + + private + + def raise_fetch_no_key + raise KeyError, 'key not found' + end + + def initialize_copy(other) + super + populate_from(other) + end + + def populate_from(hash) + hash.each_pair { |k, v| self[k] = v } + self + end + + def validate_options_hash!(options) + if (initial_capacity = options[:initial_capacity]) && (!initial_capacity.kind_of?(Integer) || initial_capacity < 0) + raise ArgumentError, ":initial_capacity must be a positive Integer" + end + if (load_factor = options[:load_factor]) && (!load_factor.kind_of?(Numeric) || load_factor <= 0 || load_factor > 1) + raise ArgumentError, ":load_factor must be a number between 0 and 1" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/maybe.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/maybe.rb new file mode 100644 index 0000000..7ba3d3e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/maybe.rb @@ -0,0 +1,229 @@ +require 'concurrent/synchronization' + +module Concurrent + + # A `Maybe` encapsulates an optional value. A `Maybe` either contains a value + # of (represented as `Just`), or it is empty (represented as `Nothing`). Using + # `Maybe` is a good way to deal with errors or exceptional cases without + # resorting to drastic measures such as exceptions. + # + # `Maybe` is a replacement for the use of `nil` with better type checking. + # + # For compatibility with {Concurrent::Concern::Obligation} the predicate and + # accessor methods are aliased as `fulfilled?`, `rejected?`, `value`, and + # `reason`. + # + # ## Motivation + # + # A common pattern in languages with pattern matching, such as Erlang and + # Haskell, is to return *either* a value *or* an error from a function + # Consider this Erlang code: + # + # ```erlang + # case file:consult("data.dat") of + # {ok, Terms} -> do_something_useful(Terms); + # {error, Reason} -> lager:error(Reason) + # end. + # ``` + # + # In this example the standard library function `file:consult` returns a + # [tuple](http://erlang.org/doc/reference_manual/data_types.html#id69044) + # with two elements: an [atom](http://erlang.org/doc/reference_manual/data_types.html#id64134) + # (similar to a ruby symbol) and a variable containing ancillary data. On + # success it returns the atom `ok` and the data from the file. On failure it + # returns `error` and a string with an explanation of the problem. With this + # pattern there is no ambiguity regarding success or failure. If the file is + # empty the return value cannot be misinterpreted as an error. And when an + # error occurs the return value provides useful information. + # + # In Ruby we tend to return `nil` when an error occurs or else we raise an + # exception. Both of these idioms are problematic. Returning `nil` is + # ambiguous because `nil` may also be a valid value. It also lacks + # information pertaining to the nature of the error. Raising an exception + # is both expensive and usurps the normal flow of control. All of these + # problems can be solved with the use of a `Maybe`. + # + # A `Maybe` is unambiguous with regard to whether or not it contains a value. + # When `Just` it contains a value, when `Nothing` it does not. When `Just` + # the value it contains may be `nil`, which is perfectly valid. When + # `Nothing` the reason for the lack of a value is contained as well. The + # previous Erlang example can be duplicated in Ruby in a principled way by + # having functions return `Maybe` objects: + # + # ```ruby + # result = MyFileUtils.consult("data.dat") # returns a Maybe + # if result.just? + # do_something_useful(result.value) # or result.just + # else + # logger.error(result.reason) # or result.nothing + # end + # ``` + # + # @example Returning a Maybe from a Function + # module MyFileUtils + # def self.consult(path) + # file = File.open(path, 'r') + # Concurrent::Maybe.just(file.read) + # rescue => ex + # return Concurrent::Maybe.nothing(ex) + # ensure + # file.close if file + # end + # end + # + # maybe = MyFileUtils.consult('bogus.file') + # maybe.just? #=> false + # maybe.nothing? #=> true + # maybe.reason #=> # + # + # maybe = MyFileUtils.consult('README.md') + # maybe.just? #=> true + # maybe.nothing? #=> false + # maybe.value #=> "# Concurrent Ruby\n[![Gem Version..." + # + # @example Using Maybe with a Block + # result = Concurrent::Maybe.from do + # Client.find(10) # Client is an ActiveRecord model + # end + # + # # -- if the record was found + # result.just? #=> true + # result.value #=> # + # + # # -- if the record was not found + # result.just? #=> false + # result.reason #=> ActiveRecord::RecordNotFound + # + # @example Using Maybe with the Null Object Pattern + # # In a Rails controller... + # result = ClientService.new(10).find # returns a Maybe + # render json: result.or(NullClient.new) + # + # @see https://hackage.haskell.org/package/base-4.2.0.1/docs/Data-Maybe.html Haskell Data.Maybe + # @see https://github.com/purescript/purescript-maybe/blob/master/docs/Data.Maybe.md PureScript Data.Maybe + class Maybe < Synchronization::Object + include Comparable + safe_initialization! + + # Indicates that the given attribute has not been set. + # When `Just` the {#nothing} getter will return `NONE`. + # When `Nothing` the {#just} getter will return `NONE`. + NONE = ::Object.new.freeze + + # The value of a `Maybe` when `Just`. Will be `NONE` when `Nothing`. + attr_reader :just + + # The reason for the `Maybe` when `Nothing`. Will be `NONE` when `Just`. + attr_reader :nothing + + private_class_method :new + + # Create a new `Maybe` using the given block. + # + # Runs the given block passing all function arguments to the block as block + # arguments. If the block runs to completion without raising an exception + # a new `Just` is created with the value set to the return value of the + # block. If the block raises an exception a new `Nothing` is created with + # the reason being set to the raised exception. + # + # @param [Array] args Zero or more arguments to pass to the block. + # @yield The block from which to create a new `Maybe`. + # @yieldparam [Array] args Zero or more block arguments passed as + # arguments to the function. + # + # @return [Maybe] The newly created object. + # + # @raise [ArgumentError] when no block given. + def self.from(*args) + raise ArgumentError.new('no block given') unless block_given? + begin + value = yield(*args) + return new(value, NONE) + rescue => ex + return new(NONE, ex) + end + end + + # Create a new `Just` with the given value. + # + # @param [Object] value The value to set for the new `Maybe` object. + # + # @return [Maybe] The newly created object. + def self.just(value) + return new(value, NONE) + end + + # Create a new `Nothing` with the given (optional) reason. + # + # @param [Exception] error The reason to set for the new `Maybe` object. + # When given a string a new `StandardError` will be created with the + # argument as the message. When no argument is given a new + # `StandardError` with an empty message will be created. + # + # @return [Maybe] The newly created object. + def self.nothing(error = '') + if error.is_a?(Exception) + nothing = error + else + nothing = StandardError.new(error.to_s) + end + return new(NONE, nothing) + end + + # Is this `Maybe` a `Just` (successfully fulfilled with a value)? + # + # @return [Boolean] True if `Just` or false if `Nothing`. + def just? + ! nothing? + end + alias :fulfilled? :just? + + # Is this `Maybe` a `nothing` (rejected with an exception upon fulfillment)? + # + # @return [Boolean] True if `Nothing` or false if `Just`. + def nothing? + @nothing != NONE + end + alias :rejected? :nothing? + + alias :value :just + + alias :reason :nothing + + # Comparison operator. + # + # @return [Integer] 0 if self and other are both `Nothing`; + # -1 if self is `Nothing` and other is `Just`; + # 1 if self is `Just` and other is nothing; + # `self.just <=> other.just` if both self and other are `Just`. + def <=>(other) + if nothing? + other.nothing? ? 0 : -1 + else + other.nothing? ? 1 : just <=> other.just + end + end + + # Return either the value of self or the given default value. + # + # @return [Object] The value of self when `Just`; else the given default. + def or(other) + just? ? just : other + end + + private + + # Create a new `Maybe` with the given attributes. + # + # @param [Object] just The value when `Just` else `NONE`. + # @param [Exception, Object] nothing The exception when `Nothing` else `NONE`. + # + # @return [Maybe] The new `Maybe`. + # + # @!visibility private + def initialize(just, nothing) + @just = just + @nothing = nothing + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/mutable_struct.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/mutable_struct.rb new file mode 100644 index 0000000..55361e7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/mutable_struct.rb @@ -0,0 +1,239 @@ +require 'concurrent/synchronization/abstract_struct' +require 'concurrent/synchronization' + +module Concurrent + + # An thread-safe variation of Ruby's standard `Struct`. Values can be set at + # construction or safely changed at any time during the object's lifecycle. + # + # @see http://ruby-doc.org/core/Struct.html Ruby standard library `Struct` + module MutableStruct + include Synchronization::AbstractStruct + + # @!macro struct_new + # + # Factory for creating new struct classes. + # + # ``` + # new([class_name] [, member_name]+>) -> StructClass click to toggle source + # new([class_name] [, member_name]+>) {|StructClass| block } -> StructClass + # new(value, ...) -> obj + # StructClass[value, ...] -> obj + # ``` + # + # The first two forms are used to create a new struct subclass `class_name` + # that can contain a value for each member_name . This subclass can be + # used to create instances of the structure like any other Class . + # + # If the `class_name` is omitted an anonymous struct class will be created. + # Otherwise, the name of this struct will appear as a constant in the struct class, + # so it must be unique for all structs under this base class and must start with a + # capital letter. Assigning a struct class to a constant also gives the class + # the name of the constant. + # + # If a block is given it will be evaluated in the context of `StructClass`, passing + # the created class as a parameter. This is the recommended way to customize a struct. + # Subclassing an anonymous struct creates an extra anonymous class that will never be used. + # + # The last two forms create a new instance of a struct subclass. The number of value + # parameters must be less than or equal to the number of attributes defined for the + # struct. Unset parameters default to nil. Passing more parameters than number of attributes + # will raise an `ArgumentError`. + # + # @see http://ruby-doc.org/core/Struct.html#method-c-new Ruby standard library `Struct#new` + + # @!macro struct_values + # + # Returns the values for this struct as an Array. + # + # @return [Array] the values for this struct + # + def values + synchronize { ns_values } + end + alias_method :to_a, :values + + # @!macro struct_values_at + # + # Returns the struct member values for each selector as an Array. + # + # A selector may be either an Integer offset or a Range of offsets (as in `Array#values_at`). + # + # @param [Fixnum, Range] indexes the index(es) from which to obatin the values (in order) + def values_at(*indexes) + synchronize { ns_values_at(indexes) } + end + + # @!macro struct_inspect + # + # Describe the contents of this struct in a string. + # + # @return [String] the contents of this struct in a string + def inspect + synchronize { ns_inspect } + end + alias_method :to_s, :inspect + + # @!macro struct_merge + # + # Returns a new struct containing the contents of `other` and the contents + # of `self`. If no block is specified, the value for entries with duplicate + # keys will be that of `other`. Otherwise the value for each duplicate key + # is determined by calling the block with the key, its value in `self` and + # its value in `other`. + # + # @param [Hash] other the hash from which to set the new values + # @yield an options block for resolving duplicate keys + # @yieldparam [String, Symbol] member the name of the member which is duplicated + # @yieldparam [Object] selfvalue the value of the member in `self` + # @yieldparam [Object] othervalue the value of the member in `other` + # + # @return [Synchronization::AbstractStruct] a new struct with the new values + # + # @raise [ArgumentError] of given a member that is not defined in the struct + def merge(other, &block) + synchronize { ns_merge(other, &block) } + end + + # @!macro struct_to_h + # + # Returns a hash containing the names and values for the struct’s members. + # + # @return [Hash] the names and values for the struct’s members + def to_h + synchronize { ns_to_h } + end + + # @!macro struct_get + # + # Attribute Reference + # + # @param [Symbol, String, Integer] member the string or symbol name of the member + # for which to obtain the value or the member's index + # + # @return [Object] the value of the given struct member or the member at the given index. + # + # @raise [NameError] if the member does not exist + # @raise [IndexError] if the index is out of range. + def [](member) + synchronize { ns_get(member) } + end + + # @!macro struct_equality + # + # Equality + # + # @return [Boolean] true if other has the same struct subclass and has + # equal member values (according to `Object#==`) + def ==(other) + synchronize { ns_equality(other) } + end + + # @!macro struct_each + # + # Yields the value of each struct member in order. If no block is given + # an enumerator is returned. + # + # @yield the operation to be performed on each struct member + # @yieldparam [Object] value each struct value (in order) + def each(&block) + return enum_for(:each) unless block_given? + synchronize { ns_each(&block) } + end + + # @!macro struct_each_pair + # + # Yields the name and value of each struct member in order. If no block is + # given an enumerator is returned. + # + # @yield the operation to be performed on each struct member/value pair + # @yieldparam [Object] member each struct member (in order) + # @yieldparam [Object] value each struct value (in order) + def each_pair(&block) + return enum_for(:each_pair) unless block_given? + synchronize { ns_each_pair(&block) } + end + + # @!macro struct_select + # + # Yields each member value from the struct to the block and returns an Array + # containing the member values from the struct for which the given block + # returns a true value (equivalent to `Enumerable#select`). + # + # @yield the operation to be performed on each struct member + # @yieldparam [Object] value each struct value (in order) + # + # @return [Array] an array containing each value for which the block returns true + def select(&block) + return enum_for(:select) unless block_given? + synchronize { ns_select(&block) } + end + + # @!macro struct_set + # + # Attribute Assignment + # + # Sets the value of the given struct member or the member at the given index. + # + # @param [Symbol, String, Integer] member the string or symbol name of the member + # for which to obtain the value or the member's index + # + # @return [Object] the value of the given struct member or the member at the given index. + # + # @raise [NameError] if the name does not exist + # @raise [IndexError] if the index is out of range. + def []=(member, value) + if member.is_a? Integer + length = synchronize { @values.length } + if member >= length + raise IndexError.new("offset #{member} too large for struct(size:#{length})") + end + synchronize { @values[member] = value } + else + send("#{member}=", value) + end + rescue NoMethodError + raise NameError.new("no member '#{member}' in struct") + end + + private + + # @!visibility private + def initialize_copy(original) + synchronize do + super(original) + ns_initialize_copy + end + end + + # @!macro struct_new + def self.new(*args, &block) + clazz_name = nil + if args.length == 0 + raise ArgumentError.new('wrong number of arguments (0 for 1+)') + elsif args.length > 0 && args.first.is_a?(String) + clazz_name = args.shift + end + FACTORY.define_struct(clazz_name, args, &block) + end + + FACTORY = Class.new(Synchronization::LockableObject) do + def define_struct(name, members, &block) + synchronize do + clazz = Synchronization::AbstractStruct.define_struct_class(MutableStruct, Synchronization::LockableObject, name, members, &block) + members.each_with_index do |member, index| + clazz.send :remove_method, member + clazz.send(:define_method, member) do + synchronize { @values[index] } + end + clazz.send(:define_method, "#{member}=") do |value| + synchronize { @values[index] = value } + end + end + clazz + end + end + end.new + private_constant :FACTORY + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/mvar.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/mvar.rb new file mode 100644 index 0000000..9034711 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/mvar.rb @@ -0,0 +1,242 @@ +require 'concurrent/concern/dereferenceable' +require 'concurrent/synchronization' + +module Concurrent + + # An `MVar` is a synchronized single element container. They are empty or + # contain one item. Taking a value from an empty `MVar` blocks, as does + # putting a value into a full one. You can either think of them as blocking + # queue of length one, or a special kind of mutable variable. + # + # On top of the fundamental `#put` and `#take` operations, we also provide a + # `#mutate` that is atomic with respect to operations on the same instance. + # These operations all support timeouts. + # + # We also support non-blocking operations `#try_put!` and `#try_take!`, a + # `#set!` that ignores existing values, a `#value` that returns the value + # without removing it or returns `MVar::EMPTY`, and a `#modify!` that yields + # `MVar::EMPTY` if the `MVar` is empty and can be used to set `MVar::EMPTY`. + # You shouldn't use these operations in the first instance. + # + # `MVar` is a [Dereferenceable](Dereferenceable). + # + # `MVar` is related to M-structures in Id, `MVar` in Haskell and `SyncVar` in Scala. + # + # Note that unlike the original Haskell paper, our `#take` is blocking. This is how + # Haskell and Scala do it today. + # + # @!macro copy_options + # + # ## See Also + # + # 1. P. Barth, R. Nikhil, and Arvind. [M-Structures: Extending a parallel, non- strict, functional language with state](http://dl.acm.org/citation.cfm?id=652538). In Proceedings of the 5th + # ACM Conference on Functional Programming Languages and Computer Architecture (FPCA), 1991. + # + # 2. S. Peyton Jones, A. Gordon, and S. Finne. [Concurrent Haskell](http://dl.acm.org/citation.cfm?id=237794). + # In Proceedings of the 23rd Symposium on Principles of Programming Languages + # (PoPL), 1996. + class MVar < Synchronization::Object + include Concern::Dereferenceable + safe_initialization! + + # Unique value that represents that an `MVar` was empty + EMPTY = ::Object.new + + # Unique value that represents that an `MVar` timed out before it was able + # to produce a value. + TIMEOUT = ::Object.new + + # Create a new `MVar`, either empty or with an initial value. + # + # @param [Hash] opts the options controlling how the future will be processed + # + # @!macro deref_options + def initialize(value = EMPTY, opts = {}) + @value = value + @mutex = Mutex.new + @empty_condition = ConditionVariable.new + @full_condition = ConditionVariable.new + set_deref_options(opts) + end + + # Remove the value from an `MVar`, leaving it empty, and blocking if there + # isn't a value. A timeout can be set to limit the time spent blocked, in + # which case it returns `TIMEOUT` if the time is exceeded. + # @return [Object] the value that was taken, or `TIMEOUT` + def take(timeout = nil) + @mutex.synchronize do + wait_for_full(timeout) + + # If we timed out we'll still be empty + if unlocked_full? + value = @value + @value = EMPTY + @empty_condition.signal + apply_deref_options(value) + else + TIMEOUT + end + end + end + + # acquires lock on the from an `MVAR`, yields the value to provided block, + # and release lock. A timeout can be set to limit the time spent blocked, + # in which case it returns `TIMEOUT` if the time is exceeded. + # @return [Object] the value returned by the block, or `TIMEOUT` + def borrow(timeout = nil) + @mutex.synchronize do + wait_for_full(timeout) + + # if we timeoud out we'll still be empty + if unlocked_full? + yield @value + else + TIMEOUT + end + end + end + + # Put a value into an `MVar`, blocking if there is already a value until + # it is empty. A timeout can be set to limit the time spent blocked, in + # which case it returns `TIMEOUT` if the time is exceeded. + # @return [Object] the value that was put, or `TIMEOUT` + def put(value, timeout = nil) + @mutex.synchronize do + wait_for_empty(timeout) + + # If we timed out we won't be empty + if unlocked_empty? + @value = value + @full_condition.signal + apply_deref_options(value) + else + TIMEOUT + end + end + end + + # Atomically `take`, yield the value to a block for transformation, and then + # `put` the transformed value. Returns the transformed value. A timeout can + # be set to limit the time spent blocked, in which case it returns `TIMEOUT` + # if the time is exceeded. + # @return [Object] the transformed value, or `TIMEOUT` + def modify(timeout = nil) + raise ArgumentError.new('no block given') unless block_given? + + @mutex.synchronize do + wait_for_full(timeout) + + # If we timed out we'll still be empty + if unlocked_full? + value = @value + @value = yield value + @full_condition.signal + apply_deref_options(value) + else + TIMEOUT + end + end + end + + # Non-blocking version of `take`, that returns `EMPTY` instead of blocking. + def try_take! + @mutex.synchronize do + if unlocked_full? + value = @value + @value = EMPTY + @empty_condition.signal + apply_deref_options(value) + else + EMPTY + end + end + end + + # Non-blocking version of `put`, that returns whether or not it was successful. + def try_put!(value) + @mutex.synchronize do + if unlocked_empty? + @value = value + @full_condition.signal + true + else + false + end + end + end + + # Non-blocking version of `put` that will overwrite an existing value. + def set!(value) + @mutex.synchronize do + old_value = @value + @value = value + @full_condition.signal + apply_deref_options(old_value) + end + end + + # Non-blocking version of `modify` that will yield with `EMPTY` if there is no value yet. + def modify! + raise ArgumentError.new('no block given') unless block_given? + + @mutex.synchronize do + value = @value + @value = yield value + if unlocked_empty? + @empty_condition.signal + else + @full_condition.signal + end + apply_deref_options(value) + end + end + + # Returns if the `MVar` is currently empty. + def empty? + @mutex.synchronize { @value == EMPTY } + end + + # Returns if the `MVar` currently contains a value. + def full? + !empty? + end + + protected + + def synchronize(&block) + @mutex.synchronize(&block) + end + + private + + def unlocked_empty? + @value == EMPTY + end + + def unlocked_full? + ! unlocked_empty? + end + + def wait_for_full(timeout) + wait_while(@full_condition, timeout) { unlocked_empty? } + end + + def wait_for_empty(timeout) + wait_while(@empty_condition, timeout) { unlocked_full? } + end + + def wait_while(condition, timeout) + if timeout.nil? + while yield + condition.wait(@mutex) + end + else + stop = Concurrent.monotonic_time + timeout + while yield && timeout > 0.0 + condition.wait(@mutex, timeout) + timeout = stop - Concurrent.monotonic_time + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/options.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/options.rb new file mode 100644 index 0000000..bdd22a9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/options.rb @@ -0,0 +1,42 @@ +require 'concurrent/configuration' + +module Concurrent + + # @!visibility private + module Options + + # Get the requested `Executor` based on the values set in the options hash. + # + # @param [Hash] opts the options defining the requested executor + # @option opts [Executor] :executor when set use the given `Executor` instance. + # Three special values are also supported: `:fast` returns the global fast executor, + # `:io` returns the global io executor, and `:immediate` returns a new + # `ImmediateExecutor` object. + # + # @return [Executor, nil] the requested thread pool, or nil when no option specified + # + # @!visibility private + def self.executor_from_options(opts = {}) # :nodoc: + if identifier = opts.fetch(:executor, nil) + executor(identifier) + else + nil + end + end + + def self.executor(executor_identifier) + case executor_identifier + when :fast + Concurrent.global_fast_executor + when :io + Concurrent.global_io_executor + when :immediate + Concurrent.global_immediate_executor + when Concurrent::ExecutorService + executor_identifier + else + raise ArgumentError, "executor not recognized by '#{executor_identifier}'" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/promise.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/promise.rb new file mode 100644 index 0000000..e917791 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/promise.rb @@ -0,0 +1,580 @@ +require 'thread' +require 'concurrent/constants' +require 'concurrent/errors' +require 'concurrent/ivar' +require 'concurrent/executor/safe_task_executor' + +require 'concurrent/options' + +module Concurrent + + PromiseExecutionError = Class.new(StandardError) + + # Promises are inspired by the JavaScript [Promises/A](http://wiki.commonjs.org/wiki/Promises/A) + # and [Promises/A+](http://promises-aplus.github.io/promises-spec/) specifications. + # + # > A promise represents the eventual value returned from the single + # > completion of an operation. + # + # Promises are similar to futures and share many of the same behaviours. + # Promises are far more robust, however. Promises can be chained in a tree + # structure where each promise may have zero or more children. Promises are + # chained using the `then` method. The result of a call to `then` is always + # another promise. Promises are resolved asynchronously (with respect to the + # main thread) but in a strict order: parents are guaranteed to be resolved + # before their children, children before their younger siblings. The `then` + # method takes two parameters: an optional block to be executed upon parent + # resolution and an optional callable to be executed upon parent failure. The + # result of each promise is passed to each of its children upon resolution. + # When a promise is rejected all its children will be summarily rejected and + # will receive the reason. + # + # Promises have several possible states: *:unscheduled*, *:pending*, + # *:processing*, *:rejected*, or *:fulfilled*. These are also aggregated as + # `#incomplete?` and `#complete?`. When a Promise is created it is set to + # *:unscheduled*. Once the `#execute` method is called the state becomes + # *:pending*. Once a job is pulled from the thread pool's queue and is given + # to a thread for processing (often immediately upon `#post`) the state + # becomes *:processing*. The future will remain in this state until processing + # is complete. A future that is in the *:unscheduled*, *:pending*, or + # *:processing* is considered `#incomplete?`. A `#complete?` Promise is either + # *:rejected*, indicating that an exception was thrown during processing, or + # *:fulfilled*, indicating success. If a Promise is *:fulfilled* its `#value` + # will be updated to reflect the result of the operation. If *:rejected* the + # `reason` will be updated with a reference to the thrown exception. The + # predicate methods `#unscheduled?`, `#pending?`, `#rejected?`, and + # `#fulfilled?` can be called at any time to obtain the state of the Promise, + # as can the `#state` method, which returns a symbol. + # + # Retrieving the value of a promise is done through the `value` (alias: + # `deref`) method. Obtaining the value of a promise is a potentially blocking + # operation. When a promise is *rejected* a call to `value` will return `nil` + # immediately. When a promise is *fulfilled* a call to `value` will + # immediately return the current value. When a promise is *pending* a call to + # `value` will block until the promise is either *rejected* or *fulfilled*. A + # *timeout* value can be passed to `value` to limit how long the call will + # block. If `nil` the call will block indefinitely. If `0` the call will not + # block. Any other integer or float value will indicate the maximum number of + # seconds to block. + # + # Promises run on the global thread pool. + # + # @!macro copy_options + # + # ### Examples + # + # Start by requiring promises + # + # ```ruby + # require 'concurrent' + # ``` + # + # Then create one + # + # ```ruby + # p = Concurrent::Promise.execute do + # # do something + # 42 + # end + # ``` + # + # Promises can be chained using the `then` method. The `then` method accepts a + # block and an executor, to be executed on fulfillment, and a callable argument to be executed + # on rejection. The result of the each promise is passed as the block argument + # to chained promises. + # + # ```ruby + # p = Concurrent::Promise.new{10}.then{|x| x * 2}.then{|result| result - 10 }.execute + # ``` + # + # And so on, and so on, and so on... + # + # ```ruby + # p = Concurrent::Promise.fulfill(20). + # then{|result| result - 10 }. + # then{|result| result * 3 }. + # then(executor: different_executor){|result| result % 5 }.execute + # ``` + # + # The initial state of a newly created Promise depends on the state of its parent: + # - if parent is *unscheduled* the child will be *unscheduled* + # - if parent is *pending* the child will be *pending* + # - if parent is *fulfilled* the child will be *pending* + # - if parent is *rejected* the child will be *pending* (but will ultimately be *rejected*) + # + # Promises are executed asynchronously from the main thread. By the time a + # child Promise finishes intialization it may be in a different state than its + # parent (by the time a child is created its parent may have completed + # execution and changed state). Despite being asynchronous, however, the order + # of execution of Promise objects in a chain (or tree) is strictly defined. + # + # There are multiple ways to create and execute a new `Promise`. Both ways + # provide identical behavior: + # + # ```ruby + # # create, operate, then execute + # p1 = Concurrent::Promise.new{ "Hello World!" } + # p1.state #=> :unscheduled + # p1.execute + # + # # create and immediately execute + # p2 = Concurrent::Promise.new{ "Hello World!" }.execute + # + # # execute during creation + # p3 = Concurrent::Promise.execute{ "Hello World!" } + # ``` + # + # Once the `execute` method is called a `Promise` becomes `pending`: + # + # ```ruby + # p = Concurrent::Promise.execute{ "Hello, world!" } + # p.state #=> :pending + # p.pending? #=> true + # ``` + # + # Wait a little bit, and the promise will resolve and provide a value: + # + # ```ruby + # p = Concurrent::Promise.execute{ "Hello, world!" } + # sleep(0.1) + # + # p.state #=> :fulfilled + # p.fulfilled? #=> true + # p.value #=> "Hello, world!" + # ``` + # + # If an exception occurs, the promise will be rejected and will provide + # a reason for the rejection: + # + # ```ruby + # p = Concurrent::Promise.execute{ raise StandardError.new("Here comes the Boom!") } + # sleep(0.1) + # + # p.state #=> :rejected + # p.rejected? #=> true + # p.reason #=> "#" + # ``` + # + # #### Rejection + # + # When a promise is rejected all its children will be rejected and will + # receive the rejection `reason` as the rejection callable parameter: + # + # ```ruby + # p = Concurrent::Promise.execute { Thread.pass; raise StandardError } + # + # c1 = p.then(-> reason { 42 }) + # c2 = p.then(-> reason { raise 'Boom!' }) + # + # c1.wait.state #=> :fulfilled + # c1.value #=> 45 + # c2.wait.state #=> :rejected + # c2.reason #=> # + # ``` + # + # Once a promise is rejected it will continue to accept children that will + # receive immediately rejection (they will be executed asynchronously). + # + # #### Aliases + # + # The `then` method is the most generic alias: it accepts a block to be + # executed upon parent fulfillment and a callable to be executed upon parent + # rejection. At least one of them should be passed. The default block is `{ + # |result| result }` that fulfills the child with the parent value. The + # default callable is `{ |reason| raise reason }` that rejects the child with + # the parent reason. + # + # - `on_success { |result| ... }` is the same as `then {|result| ... }` + # - `rescue { |reason| ... }` is the same as `then(Proc.new { |reason| ... } )` + # - `rescue` is aliased by `catch` and `on_error` + class Promise < IVar + + # Initialize a new Promise with the provided options. + # + # @!macro executor_and_deref_options + # + # @!macro promise_init_options + # + # @option opts [Promise] :parent the parent `Promise` when building a chain/tree + # @option opts [Proc] :on_fulfill fulfillment handler + # @option opts [Proc] :on_reject rejection handler + # @option opts [object, Array] :args zero or more arguments to be passed + # the task block on execution + # + # @yield The block operation to be performed asynchronously. + # + # @raise [ArgumentError] if no block is given + # + # @see http://wiki.commonjs.org/wiki/Promises/A + # @see http://promises-aplus.github.io/promises-spec/ + def initialize(opts = {}, &block) + opts.delete_if { |k, v| v.nil? } + super(NULL, opts.merge(__promise_body_from_block__: block), &nil) + end + + # Create a new `Promise` and fulfill it immediately. + # + # @!macro executor_and_deref_options + # + # @!macro promise_init_options + # + # @raise [ArgumentError] if no block is given + # + # @return [Promise] the newly created `Promise` + def self.fulfill(value, opts = {}) + Promise.new(opts).tap { |p| p.send(:synchronized_set_state!, true, value, nil) } + end + + # Create a new `Promise` and reject it immediately. + # + # @!macro executor_and_deref_options + # + # @!macro promise_init_options + # + # @raise [ArgumentError] if no block is given + # + # @return [Promise] the newly created `Promise` + def self.reject(reason, opts = {}) + Promise.new(opts).tap { |p| p.send(:synchronized_set_state!, false, nil, reason) } + end + + # Execute an `:unscheduled` `Promise`. Immediately sets the state to `:pending` and + # passes the block to a new thread/thread pool for eventual execution. + # Does nothing if the `Promise` is in any state other than `:unscheduled`. + # + # @return [Promise] a reference to `self` + def execute + if root? + if compare_and_set_state(:pending, :unscheduled) + set_pending + realize(@promise_body) + end + else + compare_and_set_state(:pending, :unscheduled) + @parent.execute + end + self + end + + # @!macro ivar_set_method + # + # @raise [Concurrent::PromiseExecutionError] if not the root promise + def set(value = NULL, &block) + raise PromiseExecutionError.new('supported only on root promise') unless root? + check_for_block_or_value!(block_given?, value) + synchronize do + if @state != :unscheduled + raise MultipleAssignmentError + else + @promise_body = block || Proc.new { |result| value } + end + end + execute + end + + # @!macro ivar_fail_method + # + # @raise [Concurrent::PromiseExecutionError] if not the root promise + def fail(reason = StandardError.new) + set { raise reason } + end + + # Create a new `Promise` object with the given block, execute it, and return the + # `:pending` object. + # + # @!macro executor_and_deref_options + # + # @!macro promise_init_options + # + # @return [Promise] the newly created `Promise` in the `:pending` state + # + # @raise [ArgumentError] if no block is given + # + # @example + # promise = Concurrent::Promise.execute{ sleep(1); 42 } + # promise.state #=> :pending + def self.execute(opts = {}, &block) + new(opts, &block).execute + end + + # Chain a new promise off the current promise. + # + # @return [Promise] the new promise + # @yield The block operation to be performed asynchronously. + # @overload then(rescuer, executor, &block) + # @param [Proc] rescuer An optional rescue block to be executed if the + # promise is rejected. + # @param [ThreadPool] executor An optional thread pool executor to be used + # in the new Promise + # @overload then(rescuer, executor: executor, &block) + # @param [Proc] rescuer An optional rescue block to be executed if the + # promise is rejected. + # @param [ThreadPool] executor An optional thread pool executor to be used + # in the new Promise + def then(*args, &block) + if args.last.is_a?(::Hash) + executor = args.pop[:executor] + rescuer = args.first + else + rescuer, executor = args + end + + executor ||= @executor + + raise ArgumentError.new('rescuers and block are both missing') if rescuer.nil? && !block_given? + block = Proc.new { |result| result } unless block_given? + child = Promise.new( + parent: self, + executor: executor, + on_fulfill: block, + on_reject: rescuer + ) + + synchronize do + child.state = :pending if @state == :pending + child.on_fulfill(apply_deref_options(@value)) if @state == :fulfilled + child.on_reject(@reason) if @state == :rejected + @children << child + end + + child + end + + # Chain onto this promise an action to be undertaken on success + # (fulfillment). + # + # @yield The block to execute + # + # @return [Promise] self + def on_success(&block) + raise ArgumentError.new('no block given') unless block_given? + self.then(&block) + end + + # Chain onto this promise an action to be undertaken on failure + # (rejection). + # + # @yield The block to execute + # + # @return [Promise] self + def rescue(&block) + self.then(block) + end + + alias_method :catch, :rescue + alias_method :on_error, :rescue + + # Yield the successful result to the block that returns a promise. If that + # promise is also successful the result is the result of the yielded promise. + # If either part fails the whole also fails. + # + # @example + # Promise.execute { 1 }.flat_map { |v| Promise.execute { v + 2 } }.value! #=> 3 + # + # @return [Promise] + def flat_map(&block) + child = Promise.new( + parent: self, + executor: ImmediateExecutor.new, + ) + + on_error { |e| child.on_reject(e) } + on_success do |result1| + begin + inner = block.call(result1) + inner.execute + inner.on_success { |result2| child.on_fulfill(result2) } + inner.on_error { |e| child.on_reject(e) } + rescue => e + child.on_reject(e) + end + end + + child + end + + # Builds a promise that produces the result of promises in an Array + # and fails if any of them fails. + # + # @overload zip(*promises) + # @param [Array] promises + # + # @overload zip(*promises, opts) + # @param [Array] promises + # @param [Hash] opts the configuration options + # @option opts [Executor] :executor (ImmediateExecutor.new) when set use the given `Executor` instance. + # @option opts [Boolean] :execute (true) execute promise before returning + # + # @return [Promise] + def self.zip(*promises) + opts = promises.last.is_a?(::Hash) ? promises.pop.dup : {} + opts[:executor] ||= ImmediateExecutor.new + zero = if !opts.key?(:execute) || opts.delete(:execute) + fulfill([], opts) + else + Promise.new(opts) { [] } + end + + promises.reduce(zero) do |p1, p2| + p1.flat_map do |results| + p2.then do |next_result| + results << next_result + end + end + end + end + + # Builds a promise that produces the result of self and others in an Array + # and fails if any of them fails. + # + # @overload zip(*promises) + # @param [Array] others + # + # @overload zip(*promises, opts) + # @param [Array] others + # @param [Hash] opts the configuration options + # @option opts [Executor] :executor (ImmediateExecutor.new) when set use the given `Executor` instance. + # @option opts [Boolean] :execute (true) execute promise before returning + # + # @return [Promise] + def zip(*others) + self.class.zip(self, *others) + end + + # Aggregates a collection of promises and executes the `then` condition + # if all aggregated promises succeed. Executes the `rescue` handler with + # a `Concurrent::PromiseExecutionError` if any of the aggregated promises + # fail. Upon execution will execute any of the aggregate promises that + # were not already executed. + # + # @!macro promise_self_aggregate + # + # The returned promise will not yet have been executed. Additional `#then` + # and `#rescue` handlers may still be provided. Once the returned promise + # is execute the aggregate promises will be also be executed (if they have + # not been executed already). The results of the aggregate promises will + # be checked upon completion. The necessary `#then` and `#rescue` blocks + # on the aggregating promise will then be executed as appropriate. If the + # `#rescue` handlers are executed the raises exception will be + # `Concurrent::PromiseExecutionError`. + # + # @param [Array] promises Zero or more promises to aggregate + # @return [Promise] an unscheduled (not executed) promise that aggregates + # the promises given as arguments + def self.all?(*promises) + aggregate(:all?, *promises) + end + + # Aggregates a collection of promises and executes the `then` condition + # if any aggregated promises succeed. Executes the `rescue` handler with + # a `Concurrent::PromiseExecutionError` if any of the aggregated promises + # fail. Upon execution will execute any of the aggregate promises that + # were not already executed. + # + # @!macro promise_self_aggregate + def self.any?(*promises) + aggregate(:any?, *promises) + end + + protected + + def ns_initialize(value, opts) + super + + @executor = Options.executor_from_options(opts) || Concurrent.global_io_executor + @args = get_arguments_from(opts) + + @parent = opts.fetch(:parent) { nil } + @on_fulfill = opts.fetch(:on_fulfill) { Proc.new { |result| result } } + @on_reject = opts.fetch(:on_reject) { Proc.new { |reason| raise reason } } + + @promise_body = opts[:__promise_body_from_block__] || Proc.new { |result| result } + @state = :unscheduled + @children = [] + end + + # Aggregate a collection of zero or more promises under a composite promise, + # execute the aggregated promises and collect them into a standard Ruby array, + # call the given Ruby `Ennnumerable` predicate (such as `any?`, `all?`, `none?`, + # or `one?`) on the collection checking for the success or failure of each, + # then executing the composite's `#then` handlers if the predicate returns + # `true` or executing the composite's `#rescue` handlers if the predicate + # returns false. + # + # @!macro promise_self_aggregate + def self.aggregate(method, *promises) + composite = Promise.new do + completed = promises.collect do |promise| + promise.execute if promise.unscheduled? + promise.wait + promise + end + unless completed.empty? || completed.send(method){|promise| promise.fulfilled? } + raise PromiseExecutionError + end + end + composite + end + + # @!visibility private + def set_pending + synchronize do + @state = :pending + @children.each { |c| c.set_pending } + end + end + + # @!visibility private + def root? # :nodoc: + @parent.nil? + end + + # @!visibility private + def on_fulfill(result) + realize Proc.new { @on_fulfill.call(result) } + nil + end + + # @!visibility private + def on_reject(reason) + realize Proc.new { @on_reject.call(reason) } + nil + end + + # @!visibility private + def notify_child(child) + if_state(:fulfilled) { child.on_fulfill(apply_deref_options(@value)) } + if_state(:rejected) { child.on_reject(@reason) } + end + + # @!visibility private + def complete(success, value, reason) + children_to_notify = synchronize do + set_state!(success, value, reason) + @children.dup + end + + children_to_notify.each { |child| notify_child(child) } + observers.notify_and_delete_observers{ [Time.now, self.value, reason] } + end + + # @!visibility private + def realize(task) + @executor.post do + success, value, reason = SafeTaskExecutor.new(task, rescue_exception: true).execute(*@args) + complete(success, value, reason) + end + end + + # @!visibility private + def set_state!(success, value, reason) + set_state(success, value, reason) + event.set + end + + # @!visibility private + def synchronized_set_state!(success, value, reason) + synchronize { set_state!(success, value, reason) } + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/promises.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/promises.rb new file mode 100644 index 0000000..76af4d5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/promises.rb @@ -0,0 +1,2167 @@ +require 'concurrent/synchronization' +require 'concurrent/atomic/atomic_boolean' +require 'concurrent/atomic/atomic_fixnum' +require 'concurrent/collection/lock_free_stack' +require 'concurrent/errors' +require 'concurrent/re_include' + +module Concurrent + + # {include:file:docs-source/promises-main.md} + module Promises + + # @!macro promises.param.default_executor + # @param [Executor, :io, :fast] default_executor Instance of an executor or a name of the + # global executor. Default executor propagates to chained futures unless overridden with + # executor parameter or changed with {AbstractEventFuture#with_default_executor}. + # + # @!macro promises.param.executor + # @param [Executor, :io, :fast] executor Instance of an executor or a name of the + # global executor. The task is executed on it, default executor remains unchanged. + # + # @!macro promises.param.args + # @param [Object] args arguments which are passed to the task when it's executed. + # (It might be prepended with other arguments, see the @yeild section). + # + # @!macro promises.shortcut.on + # Shortcut of {#$0_on} with default `:io` executor supplied. + # @see #$0_on + # + # @!macro promises.shortcut.using + # Shortcut of {#$0_using} with default `:io` executor supplied. + # @see #$0_using + # + # @!macro promise.param.task-future + # @yieldreturn will become result of the returned Future. + # Its returned value becomes {Future#value} fulfilling it, + # raised exception becomes {Future#reason} rejecting it. + # + # @!macro promise.param.callback + # @yieldreturn is forgotten. + + # Container of all {Future}, {Event} factory methods. They are never constructed directly with + # new. + module FactoryMethods + extend ReInclude + extend self + + module Configuration + # @return [Executor, :io, :fast] the executor which is used when none is supplied + # to a factory method. The method can be overridden in the receivers of + # `include FactoryMethod` + def default_executor + :io + end + end + + include Configuration + + # @!macro promises.shortcut.on + # @return [ResolvableEvent] + def resolvable_event + resolvable_event_on default_executor + end + + # Created resolvable event, user is responsible for resolving the event once by + # {Promises::ResolvableEvent#resolve}. + # + # @!macro promises.param.default_executor + # @return [ResolvableEvent] + def resolvable_event_on(default_executor = self.default_executor) + ResolvableEventPromise.new(default_executor).future + end + + # @!macro promises.shortcut.on + # @return [ResolvableFuture] + def resolvable_future + resolvable_future_on default_executor + end + + # Creates resolvable future, user is responsible for resolving the future once by + # {Promises::ResolvableFuture#resolve}, {Promises::ResolvableFuture#fulfill}, + # or {Promises::ResolvableFuture#reject} + # + # @!macro promises.param.default_executor + # @return [ResolvableFuture] + def resolvable_future_on(default_executor = self.default_executor) + ResolvableFuturePromise.new(default_executor).future + end + + # @!macro promises.shortcut.on + # @return [Future] + def future(*args, &task) + future_on(default_executor, *args, &task) + end + + # Constructs new Future which will be resolved after block is evaluated on default executor. + # Evaluation begins immediately. + # + # @!macro promises.param.default_executor + # @!macro promises.param.args + # @yield [*args] to the task. + # @!macro promise.param.task-future + # @return [Future] + def future_on(default_executor, *args, &task) + ImmediateEventPromise.new(default_executor).future.then(*args, &task) + end + + # Creates resolved future with will be either fulfilled with the given value or rejection with + # the given reason. + # + # @param [true, false] fulfilled + # @param [Object] value + # @param [Object] reason + # @!macro promises.param.default_executor + # @return [Future] + def resolved_future(fulfilled, value, reason, default_executor = self.default_executor) + ImmediateFuturePromise.new(default_executor, fulfilled, value, reason).future + end + + # Creates resolved future with will be fulfilled with the given value. + # + # @!macro promises.param.default_executor + # @param [Object] value + # @return [Future] + def fulfilled_future(value, default_executor = self.default_executor) + resolved_future true, value, nil, default_executor + end + + # Creates resolved future with will be rejected with the given reason. + # + # @!macro promises.param.default_executor + # @param [Object] reason + # @return [Future] + def rejected_future(reason, default_executor = self.default_executor) + resolved_future false, nil, reason, default_executor + end + + # Creates resolved event. + # + # @!macro promises.param.default_executor + # @return [Event] + def resolved_event(default_executor = self.default_executor) + ImmediateEventPromise.new(default_executor).event + end + + # General constructor. Behaves differently based on the argument's type. It's provided for convenience + # but it's better to be explicit. + # + # @see rejected_future, resolved_event, fulfilled_future + # @!macro promises.param.default_executor + # @return [Event, Future] + # + # @overload make_future(nil, default_executor = self.default_executor) + # @param [nil] nil + # @return [Event] resolved event. + # + # @overload make_future(a_future, default_executor = self.default_executor) + # @param [Future] a_future + # @return [Future] a future which will be resolved when a_future is. + # + # @overload make_future(an_event, default_executor = self.default_executor) + # @param [Event] an_event + # @return [Event] an event which will be resolved when an_event is. + # + # @overload make_future(exception, default_executor = self.default_executor) + # @param [Exception] exception + # @return [Future] a rejected future with the exception as its reason. + # + # @overload make_future(value, default_executor = self.default_executor) + # @param [Object] value when none of the above overloads fits + # @return [Future] a fulfilled future with the value. + def make_future(argument = nil, default_executor = self.default_executor) + case argument + when AbstractEventFuture + # returning wrapper would change nothing + argument + when Exception + rejected_future argument, default_executor + when nil + resolved_event default_executor + else + fulfilled_future argument, default_executor + end + end + + # @!macro promises.shortcut.on + # @return [Future, Event] + def delay(*args, &task) + delay_on default_executor, *args, &task + end + + # Creates new event or future which is resolved only after it is touched, + # see {Concurrent::AbstractEventFuture#touch}. + # + # @!macro promises.param.default_executor + # @overload delay_on(default_executor, *args, &task) + # If task is provided it returns a {Future} representing the result of the task. + # @!macro promises.param.args + # @yield [*args] to the task. + # @!macro promise.param.task-future + # @return [Future] + # @overload delay_on(default_executor) + # If no task is provided, it returns an {Event} + # @return [Event] + def delay_on(default_executor, *args, &task) + event = DelayPromise.new(default_executor).event + task ? event.chain(*args, &task) : event + end + + # @!macro promises.shortcut.on + # @return [Future, Event] + def schedule(intended_time, *args, &task) + schedule_on default_executor, intended_time, *args, &task + end + + # Creates new event or future which is resolved in intended_time. + # + # @!macro promises.param.default_executor + # @!macro promises.param.intended_time + # @param [Numeric, Time] intended_time `Numeric` means to run in `intended_time` seconds. + # `Time` means to run on `intended_time`. + # @overload schedule_on(default_executor, intended_time, *args, &task) + # If task is provided it returns a {Future} representing the result of the task. + # @!macro promises.param.args + # @yield [*args] to the task. + # @!macro promise.param.task-future + # @return [Future] + # @overload schedule_on(default_executor, intended_time) + # If no task is provided, it returns an {Event} + # @return [Event] + def schedule_on(default_executor, intended_time, *args, &task) + event = ScheduledPromise.new(default_executor, intended_time).event + task ? event.chain(*args, &task) : event + end + + # @!macro promises.shortcut.on + # @return [Future] + def zip_futures(*futures_and_or_events) + zip_futures_on default_executor, *futures_and_or_events + end + + # Creates new future which is resolved after all futures_and_or_events are resolved. + # Its value is array of zipped future values. Its reason is array of reasons for rejection. + # If there is an error it rejects. + # @!macro promises.event-conversion + # If event is supplied, which does not have value and can be only resolved, it's + # represented as `:fulfilled` with value `nil`. + # + # @!macro promises.param.default_executor + # @param [AbstractEventFuture] futures_and_or_events + # @return [Future] + def zip_futures_on(default_executor, *futures_and_or_events) + ZipFuturesPromise.new_blocked_by(futures_and_or_events, default_executor).future + end + + alias_method :zip, :zip_futures + + # @!macro promises.shortcut.on + # @return [Event] + def zip_events(*futures_and_or_events) + zip_events_on default_executor, *futures_and_or_events + end + + # Creates new event which is resolved after all futures_and_or_events are resolved. + # (Future is resolved when fulfilled or rejected.) + # + # @!macro promises.param.default_executor + # @param [AbstractEventFuture] futures_and_or_events + # @return [Event] + def zip_events_on(default_executor, *futures_and_or_events) + ZipEventsPromise.new_blocked_by(futures_and_or_events, default_executor).event + end + + # @!macro promises.shortcut.on + # @return [Future] + def any_resolved_future(*futures_and_or_events) + any_resolved_future_on default_executor, *futures_and_or_events + end + + alias_method :any, :any_resolved_future + + # Creates new future which is resolved after first futures_and_or_events is resolved. + # Its result equals result of the first resolved future. + # @!macro promises.any-touch + # If resolved it does not propagate {Concurrent::AbstractEventFuture#touch}, leaving delayed + # futures un-executed if they are not required any more. + # @!macro promises.event-conversion + # + # @!macro promises.param.default_executor + # @param [AbstractEventFuture] futures_and_or_events + # @return [Future] + def any_resolved_future_on(default_executor, *futures_and_or_events) + AnyResolvedFuturePromise.new_blocked_by(futures_and_or_events, default_executor).future + end + + # @!macro promises.shortcut.on + # @return [Future] + def any_fulfilled_future(*futures_and_or_events) + any_fulfilled_future_on default_executor, *futures_and_or_events + end + + # Creates new future which is resolved after first of futures_and_or_events is fulfilled. + # Its result equals result of the first resolved future or if all futures_and_or_events reject, + # it has reason of the last resolved future. + # @!macro promises.any-touch + # @!macro promises.event-conversion + # + # @!macro promises.param.default_executor + # @param [AbstractEventFuture] futures_and_or_events + # @return [Future] + def any_fulfilled_future_on(default_executor, *futures_and_or_events) + AnyFulfilledFuturePromise.new_blocked_by(futures_and_or_events, default_executor).future + end + + # @!macro promises.shortcut.on + # @return [Future] + def any_event(*futures_and_or_events) + any_event_on default_executor, *futures_and_or_events + end + + # Creates new event which becomes resolved after first of the futures_and_or_events resolves. + # @!macro promises.any-touch + # + # @!macro promises.param.default_executor + # @param [AbstractEventFuture] futures_and_or_events + # @return [Event] + def any_event_on(default_executor, *futures_and_or_events) + AnyResolvedEventPromise.new_blocked_by(futures_and_or_events, default_executor).event + end + + # TODO consider adding first(count, *futures) + # TODO consider adding zip_by(slice, *futures) processing futures in slices + # TODO or rather a generic aggregator taking a function + end + + module InternalStates + # @!visibility private + class State + def resolved? + raise NotImplementedError + end + + def to_sym + raise NotImplementedError + end + end + + # @!visibility private + class Pending < State + def resolved? + false + end + + def to_sym + :pending + end + end + + # @!visibility private + class Reserved < Pending + end + + # @!visibility private + class ResolvedWithResult < State + def resolved? + true + end + + def to_sym + :resolved + end + + def result + [fulfilled?, value, reason] + end + + def fulfilled? + raise NotImplementedError + end + + def value + raise NotImplementedError + end + + def reason + raise NotImplementedError + end + + def apply + raise NotImplementedError + end + end + + # @!visibility private + class Fulfilled < ResolvedWithResult + + def initialize(value) + @Value = value + end + + def fulfilled? + true + end + + def apply(args, block) + block.call value, *args + end + + def value + @Value + end + + def reason + nil + end + + def to_sym + :fulfilled + end + end + + # @!visibility private + class FulfilledArray < Fulfilled + def apply(args, block) + block.call(*value, *args) + end + end + + # @!visibility private + class Rejected < ResolvedWithResult + def initialize(reason) + @Reason = reason + end + + def fulfilled? + false + end + + def value + nil + end + + def reason + @Reason + end + + def to_sym + :rejected + end + + def apply(args, block) + block.call reason, *args + end + end + + # @!visibility private + class PartiallyRejected < ResolvedWithResult + def initialize(value, reason) + super() + @Value = value + @Reason = reason + end + + def fulfilled? + false + end + + def to_sym + :rejected + end + + def value + @Value + end + + def reason + @Reason + end + + def apply(args, block) + block.call(*reason, *args) + end + end + + # @!visibility private + PENDING = Pending.new + # @!visibility private + RESERVED = Reserved.new + # @!visibility private + RESOLVED = Fulfilled.new(nil) + + def RESOLVED.to_sym + :resolved + end + end + + private_constant :InternalStates + + # @!macro promises.shortcut.event-future + # @see Event#$0 + # @see Future#$0 + + # @!macro promises.param.timeout + # @param [Numeric] timeout the maximum time in second to wait. + + # @!macro promises.warn.blocks + # @note This function potentially blocks current thread until the Future is resolved. + # Be careful it can deadlock. Try to chain instead. + + # Common ancestor of {Event} and {Future} classes, many shared methods are defined here. + class AbstractEventFuture < Synchronization::Object + safe_initialization! + attr_atomic(:internal_state) + private :internal_state=, :swap_internal_state, :compare_and_set_internal_state, :update_internal_state + # @!method internal_state + # @!visibility private + + include InternalStates + + def initialize(promise, default_executor) + super() + @Lock = Mutex.new + @Condition = ConditionVariable.new + @Promise = promise + @DefaultExecutor = default_executor + @Callbacks = LockFreeStack.new + @Waiters = AtomicFixnum.new 0 + self.internal_state = PENDING + end + + private :initialize + + # Returns its state. + # @return [Symbol] + # + # @overload an_event.state + # @return [:pending, :resolved] + # @overload a_future.state + # Both :fulfilled, :rejected implies :resolved. + # @return [:pending, :fulfilled, :rejected] + def state + internal_state.to_sym + end + + # Is it in pending state? + # @return [Boolean] + def pending? + !internal_state.resolved? + end + + # Is it in resolved state? + # @return [Boolean] + def resolved? + internal_state.resolved? + end + + # Propagates touch. Requests all the delayed futures, which it depends on, to be + # executed. This method is called by any other method requiring resolved state, like {#wait}. + # @return [self] + def touch + @Promise.touch + self + end + + # @!macro promises.touches + # Calls {Concurrent::AbstractEventFuture#touch}. + + # @!macro promises.method.wait + # Wait (block the Thread) until receiver is {#resolved?}. + # @!macro promises.touches + # + # @!macro promises.warn.blocks + # @!macro promises.param.timeout + # @return [self, true, false] self implies timeout was not used, true implies timeout was used + # and it was resolved, false implies it was not resolved within timeout. + def wait(timeout = nil) + result = wait_until_resolved(timeout) + timeout ? result : self + end + + # Returns default executor. + # @return [Executor] default executor + # @see #with_default_executor + # @see FactoryMethods#future_on + # @see FactoryMethods#resolvable_future + # @see FactoryMethods#any_fulfilled_future_on + # @see similar + def default_executor + @DefaultExecutor + end + + # @!macro promises.shortcut.on + # @return [Future] + def chain(*args, &task) + chain_on @DefaultExecutor, *args, &task + end + + # Chains the task to be executed asynchronously on executor after it is resolved. + # + # @!macro promises.param.executor + # @!macro promises.param.args + # @return [Future] + # @!macro promise.param.task-future + # + # @overload an_event.chain_on(executor, *args, &task) + # @yield [*args] to the task. + # @overload a_future.chain_on(executor, *args, &task) + # @yield [fulfilled, value, reason, *args] to the task. + # @yieldparam [true, false] fulfilled + # @yieldparam [Object] value + # @yieldparam [Object] reason + def chain_on(executor, *args, &task) + ChainPromise.new_blocked_by1(self, @DefaultExecutor, executor, args, &task).future + end + + # @return [String] Short string representation. + def to_s + format '%s %s>', super[0..-2], state + end + + alias_method :inspect, :to_s + + # Resolves the resolvable when receiver is resolved. + # + # @param [Resolvable] resolvable + # @return [self] + def chain_resolvable(resolvable) + on_resolution! { resolvable.resolve_with internal_state } + end + + alias_method :tangle, :chain_resolvable + + # @!macro promises.shortcut.using + # @return [self] + def on_resolution(*args, &callback) + on_resolution_using @DefaultExecutor, *args, &callback + end + + # Stores the callback to be executed synchronously on resolving thread after it is + # resolved. + # + # @!macro promises.param.args + # @!macro promise.param.callback + # @return [self] + # + # @overload an_event.on_resolution!(*args, &callback) + # @yield [*args] to the callback. + # @overload a_future.on_resolution!(*args, &callback) + # @yield [fulfilled, value, reason, *args] to the callback. + # @yieldparam [true, false] fulfilled + # @yieldparam [Object] value + # @yieldparam [Object] reason + def on_resolution!(*args, &callback) + add_callback :callback_on_resolution, args, callback + end + + # Stores the callback to be executed asynchronously on executor after it is resolved. + # + # @!macro promises.param.executor + # @!macro promises.param.args + # @!macro promise.param.callback + # @return [self] + # + # @overload an_event.on_resolution_using(executor, *args, &callback) + # @yield [*args] to the callback. + # @overload a_future.on_resolution_using(executor, *args, &callback) + # @yield [fulfilled, value, reason, *args] to the callback. + # @yieldparam [true, false] fulfilled + # @yieldparam [Object] value + # @yieldparam [Object] reason + def on_resolution_using(executor, *args, &callback) + add_callback :async_callback_on_resolution, executor, args, callback + end + + # @!macro promises.method.with_default_executor + # Crates new object with same class with the executor set as its new default executor. + # Any futures depending on it will use the new default executor. + # @!macro promises.shortcut.event-future + # @abstract + # @return [AbstractEventFuture] + def with_default_executor(executor) + raise NotImplementedError + end + + # @!visibility private + def resolve_with(state, raise_on_reassign = true, reserved = false) + if compare_and_set_internal_state(reserved ? RESERVED : PENDING, state) + # go to synchronized block only if there were waiting threads + @Lock.synchronize { @Condition.broadcast } unless @Waiters.value == 0 + call_callbacks state + else + return rejected_resolution(raise_on_reassign, state) + end + self + end + + # For inspection. + # @!visibility private + # @return [Array] + def blocks + @Callbacks.each_with_object([]) do |(method, args), promises| + promises.push(args[0]) if method == :callback_notify_blocked + end + end + + # For inspection. + # @!visibility private + def callbacks + @Callbacks.each.to_a + end + + # For inspection. + # @!visibility private + def promise + @Promise + end + + # For inspection. + # @!visibility private + def touched? + promise.touched? + end + + # For inspection. + # @!visibility private + def waiting_threads + @Waiters.each.to_a + end + + # @!visibility private + def add_callback_notify_blocked(promise, index) + add_callback :callback_notify_blocked, promise, index + end + + # @!visibility private + def add_callback_clear_delayed_node(node) + add_callback(:callback_clear_delayed_node, node) + end + + # @!visibility private + def with_hidden_resolvable + # TODO (pitr-ch 10-Dec-2018): documentation, better name if in edge + self + end + + private + + def add_callback(method, *args) + state = internal_state + if state.resolved? + call_callback method, state, args + else + @Callbacks.push [method, args] + state = internal_state + # take back if it was resolved in the meanwhile + call_callbacks state if state.resolved? + end + self + end + + def callback_clear_delayed_node(state, node) + node.value = nil + end + + # @return [Boolean] + def wait_until_resolved(timeout) + return true if resolved? + + touch + + @Lock.synchronize do + @Waiters.increment + begin + unless resolved? + @Condition.wait @Lock, timeout + end + ensure + # JRuby may raise ConcurrencyError + @Waiters.decrement + end + end + resolved? + end + + def call_callback(method, state, args) + self.send method, state, *args + end + + def call_callbacks(state) + method, args = @Callbacks.pop + while method + call_callback method, state, args + method, args = @Callbacks.pop + end + end + + def with_async(executor, *args, &block) + Concurrent.executor(executor).post(*args, &block) + end + + def async_callback_on_resolution(state, executor, args, callback) + with_async(executor, state, args, callback) do |st, ar, cb| + callback_on_resolution st, ar, cb + end + end + + def callback_notify_blocked(state, promise, index) + promise.on_blocker_resolution self, index + end + end + + # Represents an event which will happen in future (will be resolved). The event is either + # pending or resolved. It should be always resolved. Use {Future} to communicate rejections and + # cancellation. + class Event < AbstractEventFuture + + alias_method :then, :chain + + + # @!macro promises.method.zip + # Creates a new event or a future which will be resolved when receiver and other are. + # Returns an event if receiver and other are events, otherwise returns a future. + # If just one of the parties is Future then the result + # of the returned future is equal to the result of the supplied future. If both are futures + # then the result is as described in {FactoryMethods#zip_futures_on}. + # + # @return [Future, Event] + def zip(other) + if other.is_a?(Future) + ZipFutureEventPromise.new_blocked_by2(other, self, @DefaultExecutor).future + else + ZipEventEventPromise.new_blocked_by2(self, other, @DefaultExecutor).event + end + end + + alias_method :&, :zip + + # Creates a new event which will be resolved when the first of receiver, `event_or_future` + # resolves. + # + # @return [Event] + def any(event_or_future) + AnyResolvedEventPromise.new_blocked_by2(self, event_or_future, @DefaultExecutor).event + end + + alias_method :|, :any + + # Creates new event dependent on receiver which will not evaluate until touched, see {#touch}. + # In other words, it inserts delay into the chain of Futures making rest of it lazy evaluated. + # + # @return [Event] + def delay + event = DelayPromise.new(@DefaultExecutor).event + ZipEventEventPromise.new_blocked_by2(self, event, @DefaultExecutor).event + end + + # @!macro promise.method.schedule + # Creates new event dependent on receiver scheduled to execute on/in intended_time. + # In time is interpreted from the moment the receiver is resolved, therefore it inserts + # delay into the chain. + # + # @!macro promises.param.intended_time + # @return [Event] + def schedule(intended_time) + chain do + event = ScheduledPromise.new(@DefaultExecutor, intended_time).event + ZipEventEventPromise.new_blocked_by2(self, event, @DefaultExecutor).event + end.flat_event + end + + # Converts event to a future. The future is fulfilled when the event is resolved, the future may never fail. + # + # @return [Future] + def to_future + future = Promises.resolvable_future + ensure + chain_resolvable(future) + end + + # Returns self, since this is event + # @return [Event] + def to_event + self + end + + # @!macro promises.method.with_default_executor + # @return [Event] + def with_default_executor(executor) + EventWrapperPromise.new_blocked_by1(self, executor).event + end + + private + + def rejected_resolution(raise_on_reassign, state) + Concurrent::MultipleAssignmentError.new('Event can be resolved only once') if raise_on_reassign + return false + end + + def callback_on_resolution(state, args, callback) + callback.call(*args) + end + end + + # Represents a value which will become available in future. May reject with a reason instead, + # e.g. when the tasks raises an exception. + class Future < AbstractEventFuture + + # Is it in fulfilled state? + # @return [Boolean] + def fulfilled? + state = internal_state + state.resolved? && state.fulfilled? + end + + # Is it in rejected state? + # @return [Boolean] + def rejected? + state = internal_state + state.resolved? && !state.fulfilled? + end + + # @!macro promises.warn.nil + # @note Make sure returned `nil` is not confused with timeout, no value when rejected, + # no reason when fulfilled, etc. + # Use more exact methods if needed, like {#wait}, {#value!}, {#result}, etc. + + # @!macro promises.method.value + # Return value of the future. + # @!macro promises.touches + # + # @!macro promises.warn.blocks + # @!macro promises.warn.nil + # @!macro promises.param.timeout + # @!macro promises.param.timeout_value + # @param [Object] timeout_value a value returned by the method when it times out + # @return [Object, nil, timeout_value] the value of the Future when fulfilled, + # timeout_value on timeout, + # nil on rejection. + def value(timeout = nil, timeout_value = nil) + if wait_until_resolved timeout + internal_state.value + else + timeout_value + end + end + + # Returns reason of future's rejection. + # @!macro promises.touches + # + # @!macro promises.warn.blocks + # @!macro promises.warn.nil + # @!macro promises.param.timeout + # @!macro promises.param.timeout_value + # @return [Object, timeout_value] the reason, or timeout_value on timeout, or nil on fulfillment. + def reason(timeout = nil, timeout_value = nil) + if wait_until_resolved timeout + internal_state.reason + else + timeout_value + end + end + + # Returns triplet fulfilled?, value, reason. + # @!macro promises.touches + # + # @!macro promises.warn.blocks + # @!macro promises.param.timeout + # @return [Array(Boolean, Object, Object), nil] triplet of fulfilled?, value, reason, or nil + # on timeout. + def result(timeout = nil) + internal_state.result if wait_until_resolved timeout + end + + # @!macro promises.method.wait + # @raise [Exception] {#reason} on rejection + def wait!(timeout = nil) + result = wait_until_resolved!(timeout) + timeout ? result : self + end + + # @!macro promises.method.value + # @return [Object, nil, timeout_value] the value of the Future when fulfilled, + # or nil on rejection, + # or timeout_value on timeout. + # @raise [Exception] {#reason} on rejection + def value!(timeout = nil, timeout_value = nil) + if wait_until_resolved! timeout + internal_state.value + else + timeout_value + end + end + + # Allows rejected Future to be risen with `raise` method. + # If the reason is not an exception `Runtime.new(reason)` is returned. + # + # @example + # raise Promises.rejected_future(StandardError.new("boom")) + # raise Promises.rejected_future("or just boom") + # @raise [Concurrent::Error] when raising not rejected future + # @return [Exception] + def exception(*args) + raise Concurrent::Error, 'it is not rejected' unless rejected? + raise ArgumentError unless args.size <= 1 + reason = Array(internal_state.reason).flatten.compact + if reason.size > 1 + ex = Concurrent::MultipleErrors.new reason + ex.set_backtrace(caller) + ex + else + ex = if reason[0].respond_to? :exception + reason[0].exception(*args) + else + RuntimeError.new(reason[0]).exception(*args) + end + ex.set_backtrace Array(ex.backtrace) + caller + ex + end + end + + # @!macro promises.shortcut.on + # @return [Future] + def then(*args, &task) + then_on @DefaultExecutor, *args, &task + end + + # Chains the task to be executed asynchronously on executor after it fulfills. Does not run + # the task if it rejects. It will resolve though, triggering any dependent futures. + # + # @!macro promises.param.executor + # @!macro promises.param.args + # @!macro promise.param.task-future + # @return [Future] + # @yield [value, *args] to the task. + def then_on(executor, *args, &task) + ThenPromise.new_blocked_by1(self, @DefaultExecutor, executor, args, &task).future + end + + # @!macro promises.shortcut.on + # @return [Future] + def rescue(*args, &task) + rescue_on @DefaultExecutor, *args, &task + end + + # Chains the task to be executed asynchronously on executor after it rejects. Does not run + # the task if it fulfills. It will resolve though, triggering any dependent futures. + # + # @!macro promises.param.executor + # @!macro promises.param.args + # @!macro promise.param.task-future + # @return [Future] + # @yield [reason, *args] to the task. + def rescue_on(executor, *args, &task) + RescuePromise.new_blocked_by1(self, @DefaultExecutor, executor, args, &task).future + end + + # @!macro promises.method.zip + # @return [Future] + def zip(other) + if other.is_a?(Future) + ZipFuturesPromise.new_blocked_by2(self, other, @DefaultExecutor).future + else + ZipFutureEventPromise.new_blocked_by2(self, other, @DefaultExecutor).future + end + end + + alias_method :&, :zip + + # Creates a new event which will be resolved when the first of receiver, `event_or_future` + # resolves. Returning future will have value nil if event_or_future is event and resolves + # first. + # + # @return [Future] + def any(event_or_future) + AnyResolvedFuturePromise.new_blocked_by2(self, event_or_future, @DefaultExecutor).future + end + + alias_method :|, :any + + # Creates new future dependent on receiver which will not evaluate until touched, see {#touch}. + # In other words, it inserts delay into the chain of Futures making rest of it lazy evaluated. + # + # @return [Future] + def delay + event = DelayPromise.new(@DefaultExecutor).event + ZipFutureEventPromise.new_blocked_by2(self, event, @DefaultExecutor).future + end + + # @!macro promise.method.schedule + # @return [Future] + def schedule(intended_time) + chain do + event = ScheduledPromise.new(@DefaultExecutor, intended_time).event + ZipFutureEventPromise.new_blocked_by2(self, event, @DefaultExecutor).future + end.flat + end + + # @!macro promises.method.with_default_executor + # @return [Future] + def with_default_executor(executor) + FutureWrapperPromise.new_blocked_by1(self, executor).future + end + + # Creates new future which will have result of the future returned by receiver. If receiver + # rejects it will have its rejection. + # + # @param [Integer] level how many levels of futures should flatten + # @return [Future] + def flat_future(level = 1) + FlatFuturePromise.new_blocked_by1(self, level, @DefaultExecutor).future + end + + alias_method :flat, :flat_future + + # Creates new event which will be resolved when the returned event by receiver is. + # Be careful if the receiver rejects it will just resolve since Event does not hold reason. + # + # @return [Event] + def flat_event + FlatEventPromise.new_blocked_by1(self, @DefaultExecutor).event + end + + # @!macro promises.shortcut.using + # @return [self] + def on_fulfillment(*args, &callback) + on_fulfillment_using @DefaultExecutor, *args, &callback + end + + # Stores the callback to be executed synchronously on resolving thread after it is + # fulfilled. Does nothing on rejection. + # + # @!macro promises.param.args + # @!macro promise.param.callback + # @return [self] + # @yield [value, *args] to the callback. + def on_fulfillment!(*args, &callback) + add_callback :callback_on_fulfillment, args, callback + end + + # Stores the callback to be executed asynchronously on executor after it is + # fulfilled. Does nothing on rejection. + # + # @!macro promises.param.executor + # @!macro promises.param.args + # @!macro promise.param.callback + # @return [self] + # @yield [value, *args] to the callback. + def on_fulfillment_using(executor, *args, &callback) + add_callback :async_callback_on_fulfillment, executor, args, callback + end + + # @!macro promises.shortcut.using + # @return [self] + def on_rejection(*args, &callback) + on_rejection_using @DefaultExecutor, *args, &callback + end + + # Stores the callback to be executed synchronously on resolving thread after it is + # rejected. Does nothing on fulfillment. + # + # @!macro promises.param.args + # @!macro promise.param.callback + # @return [self] + # @yield [reason, *args] to the callback. + def on_rejection!(*args, &callback) + add_callback :callback_on_rejection, args, callback + end + + # Stores the callback to be executed asynchronously on executor after it is + # rejected. Does nothing on fulfillment. + # + # @!macro promises.param.executor + # @!macro promises.param.args + # @!macro promise.param.callback + # @return [self] + # @yield [reason, *args] to the callback. + def on_rejection_using(executor, *args, &callback) + add_callback :async_callback_on_rejection, executor, args, callback + end + + # Allows to use futures as green threads. The receiver has to evaluate to a future which + # represents what should be done next. It basically flattens indefinitely until non Future + # values is returned which becomes result of the returned future. Any encountered exception + # will become reason of the returned future. + # + # @return [Future] + # @param [#call(value)] run_test + # an object which when called returns either Future to keep running with + # or nil, then the run completes with the value. + # The run_test can be used to extract the Future from deeper structure, + # or to distinguish Future which is a resulting value from a future + # which is suppose to continue running. + # @example + # body = lambda do |v| + # v += 1 + # v < 5 ? Promises.future(v, &body) : v + # end + # Promises.future(0, &body).run.value! # => 5 + def run(run_test = method(:run_test)) + RunFuturePromise.new_blocked_by1(self, @DefaultExecutor, run_test).future + end + + # @!visibility private + def apply(args, block) + internal_state.apply args, block + end + + # Converts future to event which is resolved when future is resolved by fulfillment or rejection. + # + # @return [Event] + def to_event + event = Promises.resolvable_event + ensure + chain_resolvable(event) + end + + # Returns self, since this is a future + # @return [Future] + def to_future + self + end + + # @return [String] Short string representation. + def to_s + if resolved? + format '%s with %s>', super[0..-2], (fulfilled? ? value : reason).inspect + else + super + end + end + + alias_method :inspect, :to_s + + private + + def run_test(v) + v if v.is_a?(Future) + end + + def rejected_resolution(raise_on_reassign, state) + if raise_on_reassign + if internal_state == RESERVED + raise Concurrent::MultipleAssignmentError.new( + "Future can be resolved only once. It is already reserved.") + else + raise Concurrent::MultipleAssignmentError.new( + "Future can be resolved only once. It's #{result}, trying to set #{state.result}.", + current_result: result, + new_result: state.result) + end + end + return false + end + + def wait_until_resolved!(timeout = nil) + result = wait_until_resolved(timeout) + raise self if rejected? + result + end + + def async_callback_on_fulfillment(state, executor, args, callback) + with_async(executor, state, args, callback) do |st, ar, cb| + callback_on_fulfillment st, ar, cb + end + end + + def async_callback_on_rejection(state, executor, args, callback) + with_async(executor, state, args, callback) do |st, ar, cb| + callback_on_rejection st, ar, cb + end + end + + def callback_on_fulfillment(state, args, callback) + state.apply args, callback if state.fulfilled? + end + + def callback_on_rejection(state, args, callback) + state.apply args, callback unless state.fulfilled? + end + + def callback_on_resolution(state, args, callback) + callback.call(*state.result, *args) + end + + end + + # Marker module of Future, Event resolved manually. + module Resolvable + include InternalStates + end + + # A Event which can be resolved by user. + class ResolvableEvent < Event + include Resolvable + + # @!macro raise_on_reassign + # @raise [MultipleAssignmentError] when already resolved and raise_on_reassign is true. + + # @!macro promise.param.raise_on_reassign + # @param [Boolean] raise_on_reassign should method raise exception if already resolved + # @return [self, false] false is returner when raise_on_reassign is false and the receiver + # is already resolved. + # + + # Makes the event resolved, which triggers all dependent futures. + # + # @!macro promise.param.raise_on_reassign + # @!macro promise.param.reserved + # @param [true, false] reserved + # Set to true if the resolvable is {#reserve}d by you, + # marks resolution of reserved resolvable events and futures explicitly. + # Advanced feature, ignore unless you use {Resolvable#reserve} from edge. + def resolve(raise_on_reassign = true, reserved = false) + resolve_with RESOLVED, raise_on_reassign, reserved + end + + # Creates new event wrapping receiver, effectively hiding the resolve method. + # + # @return [Event] + def with_hidden_resolvable + @with_hidden_resolvable ||= EventWrapperPromise.new_blocked_by1(self, @DefaultExecutor).event + end + + # Behaves as {AbstractEventFuture#wait} but has one additional optional argument + # resolve_on_timeout. + # + # @param [true, false] resolve_on_timeout + # If it times out and the argument is true it will also resolve the event. + # @return [self, true, false] + # @see AbstractEventFuture#wait + def wait(timeout = nil, resolve_on_timeout = false) + super(timeout) or if resolve_on_timeout + # if it fails to resolve it was resolved in the meantime + # so return true as if there was no timeout + !resolve(false) + else + false + end + end + end + + # A Future which can be resolved by user. + class ResolvableFuture < Future + include Resolvable + + # Makes the future resolved with result of triplet `fulfilled?`, `value`, `reason`, + # which triggers all dependent futures. + # + # @param [true, false] fulfilled + # @param [Object] value + # @param [Object] reason + # @!macro promise.param.raise_on_reassign + # @!macro promise.param.reserved + def resolve(fulfilled = true, value = nil, reason = nil, raise_on_reassign = true, reserved = false) + resolve_with(fulfilled ? Fulfilled.new(value) : Rejected.new(reason), raise_on_reassign, reserved) + end + + # Makes the future fulfilled with `value`, + # which triggers all dependent futures. + # + # @param [Object] value + # @!macro promise.param.raise_on_reassign + # @!macro promise.param.reserved + def fulfill(value, raise_on_reassign = true, reserved = false) + resolve_with Fulfilled.new(value), raise_on_reassign, reserved + end + + # Makes the future rejected with `reason`, + # which triggers all dependent futures. + # + # @param [Object] reason + # @!macro promise.param.raise_on_reassign + # @!macro promise.param.reserved + def reject(reason, raise_on_reassign = true, reserved = false) + resolve_with Rejected.new(reason), raise_on_reassign, reserved + end + + # Evaluates the block and sets its result as future's value fulfilling, if the block raises + # an exception the future rejects with it. + # + # @yield [*args] to the block. + # @yieldreturn [Object] value + # @return [self] + def evaluate_to(*args, &block) + promise.evaluate_to(*args, block) + end + + # Evaluates the block and sets its result as future's value fulfilling, if the block raises + # an exception the future rejects with it. + # + # @yield [*args] to the block. + # @yieldreturn [Object] value + # @return [self] + # @raise [Exception] also raise reason on rejection. + def evaluate_to!(*args, &block) + promise.evaluate_to(*args, block).wait! + end + + # @!macro promises.resolvable.resolve_on_timeout + # @param [::Array(true, Object, nil), ::Array(false, nil, Exception), nil] resolve_on_timeout + # If it times out and the argument is not nil it will also resolve the future + # to the provided resolution. + + # Behaves as {AbstractEventFuture#wait} but has one additional optional argument + # resolve_on_timeout. + # + # @!macro promises.resolvable.resolve_on_timeout + # @return [self, true, false] + # @see AbstractEventFuture#wait + def wait(timeout = nil, resolve_on_timeout = nil) + super(timeout) or if resolve_on_timeout + # if it fails to resolve it was resolved in the meantime + # so return true as if there was no timeout + !resolve(*resolve_on_timeout, false) + else + false + end + end + + # Behaves as {Future#wait!} but has one additional optional argument + # resolve_on_timeout. + # + # @!macro promises.resolvable.resolve_on_timeout + # @return [self, true, false] + # @raise [Exception] {#reason} on rejection + # @see Future#wait! + def wait!(timeout = nil, resolve_on_timeout = nil) + super(timeout) or if resolve_on_timeout + if resolve(*resolve_on_timeout, false) + false + else + # if it fails to resolve it was resolved in the meantime + # so return true as if there was no timeout + raise self if rejected? + true + end + else + false + end + end + + # Behaves as {Future#value} but has one additional optional argument + # resolve_on_timeout. + # + # @!macro promises.resolvable.resolve_on_timeout + # @return [Object, timeout_value, nil] + # @see Future#value + def value(timeout = nil, timeout_value = nil, resolve_on_timeout = nil) + if wait_until_resolved timeout + internal_state.value + else + if resolve_on_timeout + unless resolve(*resolve_on_timeout, false) + # if it fails to resolve it was resolved in the meantime + # so return value as if there was no timeout + return internal_state.value + end + end + timeout_value + end + end + + # Behaves as {Future#value!} but has one additional optional argument + # resolve_on_timeout. + # + # @!macro promises.resolvable.resolve_on_timeout + # @return [Object, timeout_value, nil] + # @raise [Exception] {#reason} on rejection + # @see Future#value! + def value!(timeout = nil, timeout_value = nil, resolve_on_timeout = nil) + if wait_until_resolved! timeout + internal_state.value + else + if resolve_on_timeout + unless resolve(*resolve_on_timeout, false) + # if it fails to resolve it was resolved in the meantime + # so return value as if there was no timeout + raise self if rejected? + return internal_state.value + end + end + timeout_value + end + end + + # Behaves as {Future#reason} but has one additional optional argument + # resolve_on_timeout. + # + # @!macro promises.resolvable.resolve_on_timeout + # @return [Exception, timeout_value, nil] + # @see Future#reason + def reason(timeout = nil, timeout_value = nil, resolve_on_timeout = nil) + if wait_until_resolved timeout + internal_state.reason + else + if resolve_on_timeout + unless resolve(*resolve_on_timeout, false) + # if it fails to resolve it was resolved in the meantime + # so return value as if there was no timeout + return internal_state.reason + end + end + timeout_value + end + end + + # Behaves as {Future#result} but has one additional optional argument + # resolve_on_timeout. + # + # @!macro promises.resolvable.resolve_on_timeout + # @return [::Array(Boolean, Object, Exception), nil] + # @see Future#result + def result(timeout = nil, resolve_on_timeout = nil) + if wait_until_resolved timeout + internal_state.result + else + if resolve_on_timeout + unless resolve(*resolve_on_timeout, false) + # if it fails to resolve it was resolved in the meantime + # so return value as if there was no timeout + internal_state.result + end + end + # otherwise returns nil + end + end + + # Creates new future wrapping receiver, effectively hiding the resolve method and similar. + # + # @return [Future] + def with_hidden_resolvable + @with_hidden_resolvable ||= FutureWrapperPromise.new_blocked_by1(self, @DefaultExecutor).future + end + end + + # @abstract + # @private + class AbstractPromise < Synchronization::Object + safe_initialization! + include InternalStates + + def initialize(future) + super() + @Future = future + end + + def future + @Future + end + + alias_method :event, :future + + def default_executor + future.default_executor + end + + def state + future.state + end + + def touch + end + + def to_s + format '%s %s>', super[0..-2], @Future + end + + alias_method :inspect, :to_s + + def delayed_because + nil + end + + private + + def resolve_with(new_state, raise_on_reassign = true) + @Future.resolve_with(new_state, raise_on_reassign) + end + + # @return [Future] + def evaluate_to(*args, block) + resolve_with Fulfilled.new(block.call(*args)) + rescue Exception => error + resolve_with Rejected.new(error) + raise error unless error.is_a?(StandardError) + end + end + + class ResolvableEventPromise < AbstractPromise + def initialize(default_executor) + super ResolvableEvent.new(self, default_executor) + end + end + + class ResolvableFuturePromise < AbstractPromise + def initialize(default_executor) + super ResolvableFuture.new(self, default_executor) + end + + public :evaluate_to + end + + # @abstract + class InnerPromise < AbstractPromise + end + + # @abstract + class BlockedPromise < InnerPromise + + private_class_method :new + + def self.new_blocked_by1(blocker, *args, &block) + blocker_delayed = blocker.promise.delayed_because + promise = new(blocker_delayed, 1, *args, &block) + blocker.add_callback_notify_blocked promise, 0 + promise + end + + def self.new_blocked_by2(blocker1, blocker2, *args, &block) + blocker_delayed1 = blocker1.promise.delayed_because + blocker_delayed2 = blocker2.promise.delayed_because + delayed = if blocker_delayed1 && blocker_delayed2 + # TODO (pitr-ch 23-Dec-2016): use arrays when we know it will not grow (only flat adds delay) + LockFreeStack.of2(blocker_delayed1, blocker_delayed2) + else + blocker_delayed1 || blocker_delayed2 + end + promise = new(delayed, 2, *args, &block) + blocker1.add_callback_notify_blocked promise, 0 + blocker2.add_callback_notify_blocked promise, 1 + promise + end + + def self.new_blocked_by(blockers, *args, &block) + delayed = blockers.reduce(nil) { |d, f| add_delayed d, f.promise.delayed_because } + promise = new(delayed, blockers.size, *args, &block) + blockers.each_with_index { |f, i| f.add_callback_notify_blocked promise, i } + promise + end + + def self.add_delayed(delayed1, delayed2) + if delayed1 && delayed2 + delayed1.push delayed2 + delayed1 + else + delayed1 || delayed2 + end + end + + def initialize(delayed, blockers_count, future) + super(future) + @Delayed = delayed + @Countdown = AtomicFixnum.new blockers_count + end + + def on_blocker_resolution(future, index) + countdown = process_on_blocker_resolution(future, index) + resolvable = resolvable?(countdown, future, index) + + on_resolvable(future, index) if resolvable + end + + def delayed_because + @Delayed + end + + def touch + clear_and_propagate_touch + end + + # for inspection only + def blocked_by + blocked_by = [] + ObjectSpace.each_object(AbstractEventFuture) { |o| blocked_by.push o if o.blocks.include? self } + blocked_by + end + + private + + def clear_and_propagate_touch(stack_or_element = @Delayed) + return if stack_or_element.nil? + + if stack_or_element.is_a? LockFreeStack + stack_or_element.clear_each { |element| clear_and_propagate_touch element } + else + stack_or_element.touch unless stack_or_element.nil? # if still present + end + end + + # @return [true,false] if resolvable + def resolvable?(countdown, future, index) + countdown.zero? + end + + def process_on_blocker_resolution(future, index) + @Countdown.decrement + end + + def on_resolvable(resolved_future, index) + raise NotImplementedError + end + end + + # @abstract + class BlockedTaskPromise < BlockedPromise + def initialize(delayed, blockers_count, default_executor, executor, args, &task) + raise ArgumentError, 'no block given' unless block_given? + super delayed, 1, Future.new(self, default_executor) + @Executor = executor + @Task = task + @Args = args + end + + def executor + @Executor + end + end + + class ThenPromise < BlockedTaskPromise + private + + def initialize(delayed, blockers_count, default_executor, executor, args, &task) + super delayed, blockers_count, default_executor, executor, args, &task + end + + def on_resolvable(resolved_future, index) + if resolved_future.fulfilled? + Concurrent.executor(@Executor).post(resolved_future, @Args, @Task) do |future, args, task| + evaluate_to lambda { future.apply args, task } + end + else + resolve_with resolved_future.internal_state + end + end + end + + class RescuePromise < BlockedTaskPromise + private + + def initialize(delayed, blockers_count, default_executor, executor, args, &task) + super delayed, blockers_count, default_executor, executor, args, &task + end + + def on_resolvable(resolved_future, index) + if resolved_future.rejected? + Concurrent.executor(@Executor).post(resolved_future, @Args, @Task) do |future, args, task| + evaluate_to lambda { future.apply args, task } + end + else + resolve_with resolved_future.internal_state + end + end + end + + class ChainPromise < BlockedTaskPromise + private + + def on_resolvable(resolved_future, index) + if Future === resolved_future + Concurrent.executor(@Executor).post(resolved_future, @Args, @Task) do |future, args, task| + evaluate_to(*future.result, *args, task) + end + else + Concurrent.executor(@Executor).post(@Args, @Task) do |args, task| + evaluate_to(*args, task) + end + end + end + end + + # will be immediately resolved + class ImmediateEventPromise < InnerPromise + def initialize(default_executor) + super Event.new(self, default_executor).resolve_with(RESOLVED) + end + end + + class ImmediateFuturePromise < InnerPromise + def initialize(default_executor, fulfilled, value, reason) + super Future.new(self, default_executor). + resolve_with(fulfilled ? Fulfilled.new(value) : Rejected.new(reason)) + end + end + + class AbstractFlatPromise < BlockedPromise + + def initialize(delayed_because, blockers_count, event_or_future) + delayed = LockFreeStack.of1(self) + super(delayed, blockers_count, event_or_future) + # noinspection RubyArgCount + @Touched = AtomicBoolean.new false + @DelayedBecause = delayed_because || LockFreeStack.new + + event_or_future.add_callback_clear_delayed_node delayed.peek + end + + def touch + if @Touched.make_true + clear_and_propagate_touch @DelayedBecause + end + end + + private + + def touched? + @Touched.value + end + + def on_resolvable(resolved_future, index) + resolve_with resolved_future.internal_state + end + + def resolvable?(countdown, future, index) + !@Future.internal_state.resolved? && super(countdown, future, index) + end + + def add_delayed_of(future) + delayed = future.promise.delayed_because + if touched? + clear_and_propagate_touch delayed + else + BlockedPromise.add_delayed @DelayedBecause, delayed + clear_and_propagate_touch @DelayedBecause if touched? + end + end + + end + + class FlatEventPromise < AbstractFlatPromise + + private + + def initialize(delayed, blockers_count, default_executor) + super delayed, 2, Event.new(self, default_executor) + end + + def process_on_blocker_resolution(future, index) + countdown = super(future, index) + if countdown.nonzero? + internal_state = future.internal_state + + unless internal_state.fulfilled? + resolve_with RESOLVED + return countdown + end + + value = internal_state.value + case value + when AbstractEventFuture + add_delayed_of value + value.add_callback_notify_blocked self, nil + countdown + else + resolve_with RESOLVED + end + end + countdown + end + + end + + class FlatFuturePromise < AbstractFlatPromise + + private + + def initialize(delayed, blockers_count, levels, default_executor) + raise ArgumentError, 'levels has to be higher than 0' if levels < 1 + # flat promise may result to a future having delayed futures, therefore we have to have empty stack + # to be able to add new delayed futures + super delayed || LockFreeStack.new, 1 + levels, Future.new(self, default_executor) + end + + def process_on_blocker_resolution(future, index) + countdown = super(future, index) + if countdown.nonzero? + internal_state = future.internal_state + + unless internal_state.fulfilled? + resolve_with internal_state + return countdown + end + + value = internal_state.value + case value + when AbstractEventFuture + add_delayed_of value + value.add_callback_notify_blocked self, nil + countdown + else + evaluate_to(lambda { raise TypeError, "returned value #{value.inspect} is not a Future" }) + end + end + countdown + end + + end + + class RunFuturePromise < AbstractFlatPromise + + private + + def initialize(delayed, blockers_count, default_executor, run_test) + super delayed, 1, Future.new(self, default_executor) + @RunTest = run_test + end + + def process_on_blocker_resolution(future, index) + internal_state = future.internal_state + + unless internal_state.fulfilled? + resolve_with internal_state + return 0 + end + + value = internal_state.value + continuation_future = @RunTest.call value + + if continuation_future + add_delayed_of continuation_future + continuation_future.add_callback_notify_blocked self, nil + else + resolve_with internal_state + end + + 1 + end + end + + class ZipEventEventPromise < BlockedPromise + def initialize(delayed, blockers_count, default_executor) + super delayed, 2, Event.new(self, default_executor) + end + + private + + def on_resolvable(resolved_future, index) + resolve_with RESOLVED + end + end + + class ZipFutureEventPromise < BlockedPromise + def initialize(delayed, blockers_count, default_executor) + super delayed, 2, Future.new(self, default_executor) + @result = nil + end + + private + + def process_on_blocker_resolution(future, index) + # first blocking is future, take its result + @result = future.internal_state if index == 0 + # super has to be called after above to piggyback on volatile @Countdown + super future, index + end + + def on_resolvable(resolved_future, index) + resolve_with @result + end + end + + class EventWrapperPromise < BlockedPromise + def initialize(delayed, blockers_count, default_executor) + super delayed, 1, Event.new(self, default_executor) + end + + private + + def on_resolvable(resolved_future, index) + resolve_with RESOLVED + end + end + + class FutureWrapperPromise < BlockedPromise + def initialize(delayed, blockers_count, default_executor) + super delayed, 1, Future.new(self, default_executor) + end + + private + + def on_resolvable(resolved_future, index) + resolve_with resolved_future.internal_state + end + end + + class ZipFuturesPromise < BlockedPromise + + private + + def initialize(delayed, blockers_count, default_executor) + super(delayed, blockers_count, Future.new(self, default_executor)) + @Resolutions = ::Array.new(blockers_count, nil) + + on_resolvable nil, nil if blockers_count == 0 + end + + def process_on_blocker_resolution(future, index) + # TODO (pitr-ch 18-Dec-2016): Can we assume that array will never break under parallel access when never re-sized? + @Resolutions[index] = future.internal_state # has to be set before countdown in super + super future, index + end + + def on_resolvable(resolved_future, index) + all_fulfilled = true + values = ::Array.new(@Resolutions.size) + reasons = ::Array.new(@Resolutions.size) + + @Resolutions.each_with_index do |internal_state, i| + fulfilled, values[i], reasons[i] = internal_state.result + all_fulfilled &&= fulfilled + end + + if all_fulfilled + resolve_with FulfilledArray.new(values) + else + resolve_with PartiallyRejected.new(values, reasons) + end + end + end + + class ZipEventsPromise < BlockedPromise + + private + + def initialize(delayed, blockers_count, default_executor) + super delayed, blockers_count, Event.new(self, default_executor) + + on_resolvable nil, nil if blockers_count == 0 + end + + def on_resolvable(resolved_future, index) + resolve_with RESOLVED + end + end + + # @abstract + class AbstractAnyPromise < BlockedPromise + end + + class AnyResolvedEventPromise < AbstractAnyPromise + + private + + def initialize(delayed, blockers_count, default_executor) + super delayed, blockers_count, Event.new(self, default_executor) + end + + def resolvable?(countdown, future, index) + true + end + + def on_resolvable(resolved_future, index) + resolve_with RESOLVED, false + end + end + + class AnyResolvedFuturePromise < AbstractAnyPromise + + private + + def initialize(delayed, blockers_count, default_executor) + super delayed, blockers_count, Future.new(self, default_executor) + end + + def resolvable?(countdown, future, index) + true + end + + def on_resolvable(resolved_future, index) + resolve_with resolved_future.internal_state, false + end + end + + class AnyFulfilledFuturePromise < AnyResolvedFuturePromise + + private + + def resolvable?(countdown, future, index) + future.fulfilled? || + # inlined super from BlockedPromise + countdown.zero? + end + end + + class DelayPromise < InnerPromise + + def initialize(default_executor) + event = Event.new(self, default_executor) + @Delayed = LockFreeStack.of1(self) + super event + event.add_callback_clear_delayed_node @Delayed.peek + end + + def touch + @Future.resolve_with RESOLVED + end + + def delayed_because + @Delayed + end + + end + + class ScheduledPromise < InnerPromise + def intended_time + @IntendedTime + end + + def inspect + "#{to_s[0..-2]} intended_time: #{@IntendedTime}>" + end + + private + + def initialize(default_executor, intended_time) + super Event.new(self, default_executor) + + @IntendedTime = intended_time + + in_seconds = begin + now = Time.now + schedule_time = if @IntendedTime.is_a? Time + @IntendedTime + else + now + @IntendedTime + end + [0, schedule_time.to_f - now.to_f].max + end + + Concurrent.global_timer_set.post(in_seconds) do + @Future.resolve_with RESOLVED + end + end + end + + extend FactoryMethods + + private_constant :AbstractPromise, + :ResolvableEventPromise, + :ResolvableFuturePromise, + :InnerPromise, + :BlockedPromise, + :BlockedTaskPromise, + :ThenPromise, + :RescuePromise, + :ChainPromise, + :ImmediateEventPromise, + :ImmediateFuturePromise, + :AbstractFlatPromise, + :FlatFuturePromise, + :FlatEventPromise, + :RunFuturePromise, + :ZipEventEventPromise, + :ZipFutureEventPromise, + :EventWrapperPromise, + :FutureWrapperPromise, + :ZipFuturesPromise, + :ZipEventsPromise, + :AbstractAnyPromise, + :AnyResolvedFuturePromise, + :AnyFulfilledFuturePromise, + :AnyResolvedEventPromise, + :DelayPromise, + :ScheduledPromise + + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/re_include.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/re_include.rb new file mode 100644 index 0000000..516d58c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/re_include.rb @@ -0,0 +1,58 @@ +module Concurrent + + # Methods form module A included to a module B, which is already included into class C, + # will not be visible in the C class. If this module is extended to B then A's methods + # are correctly made visible to C. + # + # @example + # module A + # def a + # :a + # end + # end + # + # module B1 + # end + # + # class C1 + # include B1 + # end + # + # module B2 + # extend Concurrent::ReInclude + # end + # + # class C2 + # include B2 + # end + # + # B1.send :include, A + # B2.send :include, A + # + # C1.new.respond_to? :a # => false + # C2.new.respond_to? :a # => true + module ReInclude + # @!visibility private + def included(base) + (@re_include_to_bases ||= []) << [:include, base] + super(base) + end + + # @!visibility private + def extended(base) + (@re_include_to_bases ||= []) << [:extend, base] + super(base) + end + + # @!visibility private + def include(*modules) + result = super(*modules) + modules.reverse.each do |module_being_included| + (@re_include_to_bases ||= []).each do |method, mod| + mod.send method, module_being_included + end + end + result + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/scheduled_task.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/scheduled_task.rb new file mode 100644 index 0000000..96c8272 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/scheduled_task.rb @@ -0,0 +1,331 @@ +require 'concurrent/constants' +require 'concurrent/errors' +require 'concurrent/configuration' +require 'concurrent/ivar' +require 'concurrent/collection/copy_on_notify_observer_set' +require 'concurrent/utility/monotonic_time' + +require 'concurrent/options' + +module Concurrent + + # `ScheduledTask` is a close relative of `Concurrent::Future` but with one + # important difference: A `Future` is set to execute as soon as possible + # whereas a `ScheduledTask` is set to execute after a specified delay. This + # implementation is loosely based on Java's + # [ScheduledExecutorService](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html). + # It is a more feature-rich variant of {Concurrent.timer}. + # + # The *intended* schedule time of task execution is set on object construction + # with the `delay` argument. The delay is a numeric (floating point or integer) + # representing a number of seconds in the future. Any other value or a numeric + # equal to or less than zero will result in an exception. The *actual* schedule + # time of task execution is set when the `execute` method is called. + # + # The constructor can also be given zero or more processing options. Currently + # the only supported options are those recognized by the + # [Dereferenceable](Dereferenceable) module. + # + # The final constructor argument is a block representing the task to be performed. + # If no block is given an `ArgumentError` will be raised. + # + # **States** + # + # `ScheduledTask` mixes in the [Obligation](Obligation) module thus giving it + # "future" behavior. This includes the expected lifecycle states. `ScheduledTask` + # has one additional state, however. While the task (block) is being executed the + # state of the object will be `:processing`. This additional state is necessary + # because it has implications for task cancellation. + # + # **Cancellation** + # + # A `:pending` task can be cancelled using the `#cancel` method. A task in any + # other state, including `:processing`, cannot be cancelled. The `#cancel` + # method returns a boolean indicating the success of the cancellation attempt. + # A cancelled `ScheduledTask` cannot be restarted. It is immutable. + # + # **Obligation and Observation** + # + # The result of a `ScheduledTask` can be obtained either synchronously or + # asynchronously. `ScheduledTask` mixes in both the [Obligation](Obligation) + # module and the + # [Observable](http://ruby-doc.org/stdlib-2.0/libdoc/observer/rdoc/Observable.html) + # module from the Ruby standard library. With one exception `ScheduledTask` + # behaves identically to [Future](Observable) with regard to these modules. + # + # @!macro copy_options + # + # @example Basic usage + # + # require 'concurrent' + # require 'csv' + # require 'open-uri' + # + # class Ticker + # def get_year_end_closing(symbol, year, api_key) + # uri = "https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=#{symbol}&apikey=#{api_key}&datatype=csv" + # data = [] + # csv = URI.parse(uri).read + # if csv.include?('call frequency') + # return :rate_limit_exceeded + # end + # CSV.parse(csv, headers: true) do |row| + # data << row['close'].to_f if row['timestamp'].include?(year.to_s) + # end + # year_end = data.first + # year_end + # rescue => e + # p e + # end + # end + # + # api_key = ENV['ALPHAVANTAGE_KEY'] + # abort(error_message) unless api_key + # + # # Future + # price = Concurrent::Future.execute{ Ticker.new.get_year_end_closing('TWTR', 2013, api_key) } + # price.state #=> :pending + # price.pending? #=> true + # price.value(0) #=> nil (does not block) + # + # sleep(1) # do other stuff + # + # price.value #=> 63.65 (after blocking if necessary) + # price.state #=> :fulfilled + # price.fulfilled? #=> true + # price.value #=> 63.65 + # + # @example Successful task execution + # + # task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' } + # task.state #=> :unscheduled + # task.execute + # task.state #=> pending + # + # # wait for it... + # sleep(3) + # + # task.unscheduled? #=> false + # task.pending? #=> false + # task.fulfilled? #=> true + # task.rejected? #=> false + # task.value #=> 'What does the fox say?' + # + # @example One line creation and execution + # + # task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }.execute + # task.state #=> pending + # + # task = Concurrent::ScheduledTask.execute(2){ 'What do you get when you multiply 6 by 9?' } + # task.state #=> pending + # + # @example Failed task execution + # + # task = Concurrent::ScheduledTask.execute(2){ raise StandardError.new('Call me maybe?') } + # task.pending? #=> true + # + # # wait for it... + # sleep(3) + # + # task.unscheduled? #=> false + # task.pending? #=> false + # task.fulfilled? #=> false + # task.rejected? #=> true + # task.value #=> nil + # task.reason #=> # + # + # @example Task execution with observation + # + # observer = Class.new{ + # def update(time, value, reason) + # puts "The task completed at #{time} with value '#{value}'" + # end + # }.new + # + # task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' } + # task.add_observer(observer) + # task.execute + # task.pending? #=> true + # + # # wait for it... + # sleep(3) + # + # #>> The task completed at 2013-11-07 12:26:09 -0500 with value 'What does the fox say?' + # + # @!macro monotonic_clock_warning + # + # @see Concurrent.timer + class ScheduledTask < IVar + include Comparable + + # The executor on which to execute the task. + # @!visibility private + attr_reader :executor + + # Schedule a task for execution at a specified future time. + # + # @param [Float] delay the number of seconds to wait for before executing the task + # + # @yield the task to be performed + # + # @!macro executor_and_deref_options + # + # @option opts [object, Array] :args zero or more arguments to be passed the task + # block on execution + # + # @raise [ArgumentError] When no block is given + # @raise [ArgumentError] When given a time that is in the past + def initialize(delay, opts = {}, &task) + raise ArgumentError.new('no block given') unless block_given? + raise ArgumentError.new('seconds must be greater than zero') if delay.to_f < 0.0 + + super(NULL, opts, &nil) + + synchronize do + ns_set_state(:unscheduled) + @parent = opts.fetch(:timer_set, Concurrent.global_timer_set) + @args = get_arguments_from(opts) + @delay = delay.to_f + @task = task + @time = nil + @executor = Options.executor_from_options(opts) || Concurrent.global_io_executor + self.observers = Collection::CopyOnNotifyObserverSet.new + end + end + + # The `delay` value given at instanciation. + # + # @return [Float] the initial delay. + def initial_delay + synchronize { @delay } + end + + # The monotonic time at which the the task is scheduled to be executed. + # + # @return [Float] the schedule time or nil if `unscheduled` + def schedule_time + synchronize { @time } + end + + # Comparator which orders by schedule time. + # + # @!visibility private + def <=>(other) + schedule_time <=> other.schedule_time + end + + # Has the task been cancelled? + # + # @return [Boolean] true if the task is in the given state else false + def cancelled? + synchronize { ns_check_state?(:cancelled) } + end + + # In the task execution in progress? + # + # @return [Boolean] true if the task is in the given state else false + def processing? + synchronize { ns_check_state?(:processing) } + end + + # Cancel this task and prevent it from executing. A task can only be + # cancelled if it is pending or unscheduled. + # + # @return [Boolean] true if successfully cancelled else false + def cancel + if compare_and_set_state(:cancelled, :pending, :unscheduled) + complete(false, nil, CancelledOperationError.new) + # To avoid deadlocks this call must occur outside of #synchronize + # Changing the state above should prevent redundant calls + @parent.send(:remove_task, self) + else + false + end + end + + # Reschedule the task using the original delay and the current time. + # A task can only be reset while it is `:pending`. + # + # @return [Boolean] true if successfully rescheduled else false + def reset + synchronize{ ns_reschedule(@delay) } + end + + # Reschedule the task using the given delay and the current time. + # A task can only be reset while it is `:pending`. + # + # @param [Float] delay the number of seconds to wait for before executing the task + # + # @return [Boolean] true if successfully rescheduled else false + # + # @raise [ArgumentError] When given a time that is in the past + def reschedule(delay) + delay = delay.to_f + raise ArgumentError.new('seconds must be greater than zero') if delay < 0.0 + synchronize{ ns_reschedule(delay) } + end + + # Execute an `:unscheduled` `ScheduledTask`. Immediately sets the state to `:pending` + # and starts counting down toward execution. Does nothing if the `ScheduledTask` is + # in any state other than `:unscheduled`. + # + # @return [ScheduledTask] a reference to `self` + def execute + if compare_and_set_state(:pending, :unscheduled) + synchronize{ ns_schedule(@delay) } + end + self + end + + # Create a new `ScheduledTask` object with the given block, execute it, and return the + # `:pending` object. + # + # @param [Float] delay the number of seconds to wait for before executing the task + # + # @!macro executor_and_deref_options + # + # @return [ScheduledTask] the newly created `ScheduledTask` in the `:pending` state + # + # @raise [ArgumentError] if no block is given + def self.execute(delay, opts = {}, &task) + new(delay, opts, &task).execute + end + + # Execute the task. + # + # @!visibility private + def process_task + safe_execute(@task, @args) + end + + protected :set, :try_set, :fail, :complete + + protected + + # Schedule the task using the given delay and the current time. + # + # @param [Float] delay the number of seconds to wait for before executing the task + # + # @return [Boolean] true if successfully rescheduled else false + # + # @!visibility private + def ns_schedule(delay) + @delay = delay + @time = Concurrent.monotonic_time + @delay + @parent.send(:post_task, self) + end + + # Reschedule the task using the given delay and the current time. + # A task can only be reset while it is `:pending`. + # + # @param [Float] delay the number of seconds to wait for before executing the task + # + # @return [Boolean] true if successfully rescheduled else false + # + # @!visibility private + def ns_reschedule(delay) + return false unless ns_check_state?(:pending) + @parent.send(:remove_task, self) && ns_schedule(delay) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/set.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/set.rb new file mode 100644 index 0000000..3bf0c89 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/set.rb @@ -0,0 +1,74 @@ +require 'concurrent/utility/engine' +require 'concurrent/thread_safe/util' +require 'set' + +module Concurrent + + # @!macro concurrent_set + # + # A thread-safe subclass of Set. This version locks against the object + # itself for every method call, ensuring only one thread can be reading + # or writing at a time. This includes iteration methods like `#each`. + # + # @note `a += b` is **not** a **thread-safe** operation on + # `Concurrent::Set`. It reads Set `a`, then it creates new `Concurrent::Set` + # which is union of `a` and `b`, then it writes the union to `a`. + # The read and write are independent operations they do not form a single atomic + # operation therefore when two `+=` operations are executed concurrently updates + # may be lost. Use `#merge` instead. + # + # @see http://ruby-doc.org/stdlib-2.4.0/libdoc/set/rdoc/Set.html Ruby standard library `Set` + + # @!macro internal_implementation_note + SetImplementation = case + when Concurrent.on_cruby? + # The CRuby implementation of Set is written in Ruby itself and is + # not thread safe for certain methods. + require 'monitor' + require 'concurrent/thread_safe/util/data_structures' + + class CRubySet < ::Set + end + + ThreadSafe::Util.make_synchronized_on_cruby CRubySet + CRubySet + + when Concurrent.on_jruby? + require 'jruby/synchronized' + + class JRubySet < ::Set + include JRuby::Synchronized + end + + JRubySet + + when Concurrent.on_rbx? + require 'monitor' + require 'concurrent/thread_safe/util/data_structures' + + class RbxSet < ::Set + end + + ThreadSafe::Util.make_synchronized_on_rbx RbxSet + RbxSet + + when Concurrent.on_truffleruby? + require 'concurrent/thread_safe/util/data_structures' + + class TruffleRubySet < ::Set + end + + ThreadSafe::Util.make_synchronized_on_truffleruby TruffleRubySet + TruffleRubySet + + else + warn 'Possibly unsupported Ruby implementation' + ::Set + end + private_constant :SetImplementation + + # @!macro concurrent_set + class Set < SetImplementation + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/settable_struct.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/settable_struct.rb new file mode 100644 index 0000000..0012352 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/settable_struct.rb @@ -0,0 +1,139 @@ +require 'concurrent/synchronization/abstract_struct' +require 'concurrent/errors' +require 'concurrent/synchronization' + +module Concurrent + + # An thread-safe, write-once variation of Ruby's standard `Struct`. + # Each member can have its value set at most once, either at construction + # or any time thereafter. Attempting to assign a value to a member + # that has already been set will result in a `Concurrent::ImmutabilityError`. + # + # @see http://ruby-doc.org/core/Struct.html Ruby standard library `Struct` + # @see http://en.wikipedia.org/wiki/Final_(Java) Java `final` keyword + module SettableStruct + include Synchronization::AbstractStruct + + # @!macro struct_values + def values + synchronize { ns_values } + end + alias_method :to_a, :values + + # @!macro struct_values_at + def values_at(*indexes) + synchronize { ns_values_at(indexes) } + end + + # @!macro struct_inspect + def inspect + synchronize { ns_inspect } + end + alias_method :to_s, :inspect + + # @!macro struct_merge + def merge(other, &block) + synchronize { ns_merge(other, &block) } + end + + # @!macro struct_to_h + def to_h + synchronize { ns_to_h } + end + + # @!macro struct_get + def [](member) + synchronize { ns_get(member) } + end + + # @!macro struct_equality + def ==(other) + synchronize { ns_equality(other) } + end + + # @!macro struct_each + def each(&block) + return enum_for(:each) unless block_given? + synchronize { ns_each(&block) } + end + + # @!macro struct_each_pair + def each_pair(&block) + return enum_for(:each_pair) unless block_given? + synchronize { ns_each_pair(&block) } + end + + # @!macro struct_select + def select(&block) + return enum_for(:select) unless block_given? + synchronize { ns_select(&block) } + end + + # @!macro struct_set + # + # @raise [Concurrent::ImmutabilityError] if the given member has already been set + def []=(member, value) + if member.is_a? Integer + length = synchronize { @values.length } + if member >= length + raise IndexError.new("offset #{member} too large for struct(size:#{length})") + end + synchronize do + unless @values[member].nil? + raise Concurrent::ImmutabilityError.new('struct member has already been set') + end + @values[member] = value + end + else + send("#{member}=", value) + end + rescue NoMethodError + raise NameError.new("no member '#{member}' in struct") + end + + private + + # @!visibility private + def initialize_copy(original) + synchronize do + super(original) + ns_initialize_copy + end + end + + # @!macro struct_new + def self.new(*args, &block) + clazz_name = nil + if args.length == 0 + raise ArgumentError.new('wrong number of arguments (0 for 1+)') + elsif args.length > 0 && args.first.is_a?(String) + clazz_name = args.shift + end + FACTORY.define_struct(clazz_name, args, &block) + end + + FACTORY = Class.new(Synchronization::LockableObject) do + def define_struct(name, members, &block) + synchronize do + clazz = Synchronization::AbstractStruct.define_struct_class(SettableStruct, Synchronization::LockableObject, name, members, &block) + members.each_with_index do |member, index| + clazz.send :remove_method, member if clazz.instance_methods.include? member + clazz.send(:define_method, member) do + synchronize { @values[index] } + end + clazz.send(:define_method, "#{member}=") do |value| + synchronize do + unless @values[index].nil? + raise Concurrent::ImmutabilityError.new('struct member has already been set') + end + @values[index] = value + end + end + end + clazz + end + end + end.new + private_constant :FACTORY + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization.rb new file mode 100644 index 0000000..49c68eb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization.rb @@ -0,0 +1,30 @@ +require 'concurrent/utility/engine' + +require 'concurrent/synchronization/abstract_object' +require 'concurrent/utility/native_extension_loader' # load native parts first +Concurrent.load_native_extensions + +require 'concurrent/synchronization/mri_object' +require 'concurrent/synchronization/jruby_object' +require 'concurrent/synchronization/rbx_object' +require 'concurrent/synchronization/truffleruby_object' +require 'concurrent/synchronization/object' +require 'concurrent/synchronization/volatile' + +require 'concurrent/synchronization/abstract_lockable_object' +require 'concurrent/synchronization/mutex_lockable_object' +require 'concurrent/synchronization/jruby_lockable_object' +require 'concurrent/synchronization/rbx_lockable_object' + +require 'concurrent/synchronization/lockable_object' + +require 'concurrent/synchronization/condition' +require 'concurrent/synchronization/lock' + +module Concurrent + # {include:file:docs-source/synchronization.md} + # {include:file:docs-source/synchronization-notes.md} + module Synchronization + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb new file mode 100644 index 0000000..bc12603 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb @@ -0,0 +1,98 @@ +module Concurrent + module Synchronization + + # @!visibility private + class AbstractLockableObject < Synchronization::Object + + protected + + # @!macro synchronization_object_method_synchronize + # + # @yield runs the block synchronized against this object, + # equivalent of java's `synchronize(this) {}` + # @note can by made public in descendants if required by `public :synchronize` + def synchronize + raise NotImplementedError + end + + # @!macro synchronization_object_method_ns_wait_until + # + # Wait until condition is met or timeout passes, + # protects against spurious wake-ups. + # @param [Numeric, nil] timeout in seconds, `nil` means no timeout + # @yield condition to be met + # @yieldreturn [true, false] + # @return [true, false] if condition met + # @note only to be used inside synchronized block + # @note to provide direct access to this method in a descendant add method + # ``` + # def wait_until(timeout = nil, &condition) + # synchronize { ns_wait_until(timeout, &condition) } + # end + # ``` + def ns_wait_until(timeout = nil, &condition) + if timeout + wait_until = Concurrent.monotonic_time + timeout + loop do + now = Concurrent.monotonic_time + condition_result = condition.call + return condition_result if now >= wait_until || condition_result + ns_wait wait_until - now + end + else + ns_wait timeout until condition.call + true + end + end + + # @!macro synchronization_object_method_ns_wait + # + # Wait until another thread calls #signal or #broadcast, + # spurious wake-ups can happen. + # + # @param [Numeric, nil] timeout in seconds, `nil` means no timeout + # @return [self] + # @note only to be used inside synchronized block + # @note to provide direct access to this method in a descendant add method + # ``` + # def wait(timeout = nil) + # synchronize { ns_wait(timeout) } + # end + # ``` + def ns_wait(timeout = nil) + raise NotImplementedError + end + + # @!macro synchronization_object_method_ns_signal + # + # Signal one waiting thread. + # @return [self] + # @note only to be used inside synchronized block + # @note to provide direct access to this method in a descendant add method + # ``` + # def signal + # synchronize { ns_signal } + # end + # ``` + def ns_signal + raise NotImplementedError + end + + # @!macro synchronization_object_method_ns_broadcast + # + # Broadcast to all waiting threads. + # @return [self] + # @note only to be used inside synchronized block + # @note to provide direct access to this method in a descendant add method + # ``` + # def broadcast + # synchronize { ns_broadcast } + # end + # ``` + def ns_broadcast + raise NotImplementedError + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/abstract_object.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/abstract_object.rb new file mode 100644 index 0000000..532388b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/abstract_object.rb @@ -0,0 +1,24 @@ +module Concurrent + module Synchronization + + # @!visibility private + # @!macro internal_implementation_note + class AbstractObject + + # @abstract has to be implemented based on Ruby runtime + def initialize + raise NotImplementedError + end + + # @!visibility private + # @abstract + def full_memory_barrier + raise NotImplementedError + end + + def self.attr_volatile(*names) + raise NotImplementedError + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/abstract_struct.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/abstract_struct.rb new file mode 100644 index 0000000..1fe90c1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/abstract_struct.rb @@ -0,0 +1,171 @@ +module Concurrent + module Synchronization + + # @!visibility private + # @!macro internal_implementation_note + module AbstractStruct + + # @!visibility private + def initialize(*values) + super() + ns_initialize(*values) + end + + # @!macro struct_length + # + # Returns the number of struct members. + # + # @return [Fixnum] the number of struct members + def length + self.class::MEMBERS.length + end + alias_method :size, :length + + # @!macro struct_members + # + # Returns the struct members as an array of symbols. + # + # @return [Array] the struct members as an array of symbols + def members + self.class::MEMBERS.dup + end + + protected + + # @!macro struct_values + # + # @!visibility private + def ns_values + @values.dup + end + + # @!macro struct_values_at + # + # @!visibility private + def ns_values_at(indexes) + @values.values_at(*indexes) + end + + # @!macro struct_to_h + # + # @!visibility private + def ns_to_h + length.times.reduce({}){|memo, i| memo[self.class::MEMBERS[i]] = @values[i]; memo} + end + + # @!macro struct_get + # + # @!visibility private + def ns_get(member) + if member.is_a? Integer + if member >= @values.length + raise IndexError.new("offset #{member} too large for struct(size:#{@values.length})") + end + @values[member] + else + send(member) + end + rescue NoMethodError + raise NameError.new("no member '#{member}' in struct") + end + + # @!macro struct_equality + # + # @!visibility private + def ns_equality(other) + self.class == other.class && self.values == other.values + end + + # @!macro struct_each + # + # @!visibility private + def ns_each + values.each{|value| yield value } + end + + # @!macro struct_each_pair + # + # @!visibility private + def ns_each_pair + @values.length.times do |index| + yield self.class::MEMBERS[index], @values[index] + end + end + + # @!macro struct_select + # + # @!visibility private + def ns_select + values.select{|value| yield value } + end + + # @!macro struct_inspect + # + # @!visibility private + def ns_inspect + struct = pr_underscore(self.class.ancestors[1]) + clazz = ((self.class.to_s =~ /^#" + end + + # @!macro struct_merge + # + # @!visibility private + def ns_merge(other, &block) + self.class.new(*self.to_h.merge(other, &block).values) + end + + # @!visibility private + def ns_initialize_copy + @values = @values.map do |val| + begin + val.clone + rescue TypeError + val + end + end + end + + # @!visibility private + def pr_underscore(clazz) + word = clazz.to_s.dup # dup string to workaround JRuby 9.2.0.0 bug https://github.com/jruby/jruby/issues/5229 + word.gsub!(/::/, '/') + word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2') + word.gsub!(/([a-z\d])([A-Z])/,'\1_\2') + word.tr!("-", "_") + word.downcase! + word + end + + # @!visibility private + def self.define_struct_class(parent, base, name, members, &block) + clazz = Class.new(base || Object) do + include parent + self.const_set(:MEMBERS, members.collect{|member| member.to_s.to_sym}.freeze) + def ns_initialize(*values) + raise ArgumentError.new('struct size differs') if values.length > length + @values = values.fill(nil, values.length..length-1) + end + end + unless name.nil? + begin + parent.send :remove_const, name if parent.const_defined?(name, false) + parent.const_set(name, clazz) + clazz + rescue NameError + raise NameError.new("identifier #{name} needs to be constant") + end + end + members.each_with_index do |member, index| + clazz.send :remove_method, member if clazz.instance_methods.include? member + clazz.send(:define_method, member) do + @values[index] + end + end + clazz.class_exec(&block) unless block.nil? + clazz.singleton_class.send :alias_method, :[], :new + clazz + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/condition.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/condition.rb new file mode 100644 index 0000000..f704b81 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/condition.rb @@ -0,0 +1,60 @@ +module Concurrent + module Synchronization + + # @!visibility private + # TODO (pitr-ch 04-Dec-2016): should be in edge + class Condition < LockableObject + safe_initialization! + + # TODO (pitr 12-Sep-2015): locks two objects, improve + # TODO (pitr 26-Sep-2015): study + # http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/concurrent/locks/AbstractQueuedSynchronizer.java#AbstractQueuedSynchronizer.Node + + singleton_class.send :alias_method, :private_new, :new + private_class_method :new + + def initialize(lock) + super() + @Lock = lock + end + + def wait(timeout = nil) + @Lock.synchronize { ns_wait(timeout) } + end + + def ns_wait(timeout = nil) + synchronize { super(timeout) } + end + + def wait_until(timeout = nil, &condition) + @Lock.synchronize { ns_wait_until(timeout, &condition) } + end + + def ns_wait_until(timeout = nil, &condition) + synchronize { super(timeout, &condition) } + end + + def signal + @Lock.synchronize { ns_signal } + end + + def ns_signal + synchronize { super } + end + + def broadcast + @Lock.synchronize { ns_broadcast } + end + + def ns_broadcast + synchronize { super } + end + end + + class LockableObject < LockableObjectImplementation + def new_condition + Condition.private_new(self) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/jruby_lockable_object.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/jruby_lockable_object.rb new file mode 100644 index 0000000..359a032 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/jruby_lockable_object.rb @@ -0,0 +1,13 @@ +module Concurrent + module Synchronization + + if Concurrent.on_jruby? && Concurrent.java_extensions_loaded? + + # @!visibility private + # @!macro internal_implementation_note + class JRubyLockableObject < AbstractLockableObject + + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/jruby_object.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/jruby_object.rb new file mode 100644 index 0000000..da91ac5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/jruby_object.rb @@ -0,0 +1,45 @@ +module Concurrent + module Synchronization + + if Concurrent.on_jruby? && Concurrent.java_extensions_loaded? + + # @!visibility private + module JRubyAttrVolatile + def self.included(base) + base.extend(ClassMethods) + end + + module ClassMethods + def attr_volatile(*names) + names.each do |name| + + ivar = :"@volatile_#{name}" + + class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{name} + instance_variable_get_volatile(:#{ivar}) + end + + def #{name}=(value) + instance_variable_set_volatile(:#{ivar}, value) + end + RUBY + + end + names.map { |n| [n, :"#{n}="] }.flatten + end + end + end + + # @!visibility private + # @!macro internal_implementation_note + class JRubyObject < AbstractObject + include JRubyAttrVolatile + + def initialize + # nothing to do + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/lock.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/lock.rb new file mode 100644 index 0000000..0dbad2e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/lock.rb @@ -0,0 +1,36 @@ +module Concurrent + module Synchronization + + # @!visibility private + # TODO (pitr-ch 04-Dec-2016): should be in edge + class Lock < LockableObject + # TODO use JavaReentrantLock on JRuby + + public :synchronize + + def wait(timeout = nil) + synchronize { ns_wait(timeout) } + end + + public :ns_wait + + def wait_until(timeout = nil, &condition) + synchronize { ns_wait_until(timeout, &condition) } + end + + public :ns_wait_until + + def signal + synchronize { ns_signal } + end + + public :ns_signal + + def broadcast + synchronize { ns_broadcast } + end + + public :ns_broadcast + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/lockable_object.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/lockable_object.rb new file mode 100644 index 0000000..ae28e5b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/lockable_object.rb @@ -0,0 +1,72 @@ +module Concurrent + module Synchronization + + # @!visibility private + # @!macro internal_implementation_note + LockableObjectImplementation = case + when Concurrent.on_cruby? + MutexLockableObject + when Concurrent.on_jruby? + JRubyLockableObject + when Concurrent.on_rbx? + RbxLockableObject + when Concurrent.on_truffleruby? + MutexLockableObject + else + warn 'Possibly unsupported Ruby implementation' + MonitorLockableObject + end + private_constant :LockableObjectImplementation + + # Safe synchronization under any Ruby implementation. + # It provides methods like {#synchronize}, {#wait}, {#signal} and {#broadcast}. + # Provides a single layer which can improve its implementation over time without changes needed to + # the classes using it. Use {Synchronization::Object} not this abstract class. + # + # @note this object does not support usage together with + # [`Thread#wakeup`](http://ruby-doc.org/core/Thread.html#method-i-wakeup) + # and [`Thread#raise`](http://ruby-doc.org/core/Thread.html#method-i-raise). + # `Thread#sleep` and `Thread#wakeup` will work as expected but mixing `Synchronization::Object#wait` and + # `Thread#wakeup` will not work on all platforms. + # + # @see Event implementation as an example of this class use + # + # @example simple + # class AnClass < Synchronization::Object + # def initialize + # super + # synchronize { @value = 'asd' } + # end + # + # def value + # synchronize { @value } + # end + # end + # + # @!visibility private + class LockableObject < LockableObjectImplementation + + # TODO (pitr 12-Sep-2015): make private for c-r, prohibit subclassing + # TODO (pitr 12-Sep-2015): we inherit too much ourselves :/ + + # @!method initialize(*args, &block) + # @!macro synchronization_object_method_initialize + + # @!method synchronize + # @!macro synchronization_object_method_synchronize + + # @!method wait_until(timeout = nil, &condition) + # @!macro synchronization_object_method_ns_wait_until + + # @!method wait(timeout = nil) + # @!macro synchronization_object_method_ns_wait + + # @!method signal + # @!macro synchronization_object_method_ns_signal + + # @!method broadcast + # @!macro synchronization_object_method_ns_broadcast + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/mri_object.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/mri_object.rb new file mode 100644 index 0000000..4b1d6c2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/mri_object.rb @@ -0,0 +1,44 @@ +module Concurrent + module Synchronization + + # @!visibility private + module MriAttrVolatile + def self.included(base) + base.extend(ClassMethods) + end + + module ClassMethods + def attr_volatile(*names) + names.each do |name| + ivar = :"@volatile_#{name}" + class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{name} + #{ivar} + end + + def #{name}=(value) + #{ivar} = value + end + RUBY + end + names.map { |n| [n, :"#{n}="] }.flatten + end + end + + def full_memory_barrier + # relying on undocumented behavior of CRuby, GVL acquire has lock which ensures visibility of ivars + # https://github.com/ruby/ruby/blob/ruby_2_2/thread_pthread.c#L204-L211 + end + end + + # @!visibility private + # @!macro internal_implementation_note + class MriObject < AbstractObject + include MriAttrVolatile + + def initialize + # nothing to do + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/mutex_lockable_object.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/mutex_lockable_object.rb new file mode 100644 index 0000000..f17ea50 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/mutex_lockable_object.rb @@ -0,0 +1,88 @@ +module Concurrent + # noinspection RubyInstanceVariableNamingConvention + module Synchronization + + # @!visibility private + # @!macro internal_implementation_note + module ConditionSignalling + protected + + def ns_signal + @__Condition__.signal + self + end + + def ns_broadcast + @__Condition__.broadcast + self + end + end + + + # @!visibility private + # @!macro internal_implementation_note + class MutexLockableObject < AbstractLockableObject + include ConditionSignalling + + safe_initialization! + + def initialize(*defaults) + super(*defaults) + @__Lock__ = ::Mutex.new + @__Condition__ = ::ConditionVariable.new + end + + def initialize_copy(other) + super + @__Lock__ = ::Mutex.new + @__Condition__ = ::ConditionVariable.new + end + + protected + + def synchronize + if @__Lock__.owned? + yield + else + @__Lock__.synchronize { yield } + end + end + + def ns_wait(timeout = nil) + @__Condition__.wait @__Lock__, timeout + self + end + end + + # @!visibility private + # @!macro internal_implementation_note + class MonitorLockableObject < AbstractLockableObject + include ConditionSignalling + + safe_initialization! + + def initialize(*defaults) + super(*defaults) + @__Lock__ = ::Monitor.new + @__Condition__ = @__Lock__.new_cond + end + + def initialize_copy(other) + super + @__Lock__ = ::Monitor.new + @__Condition__ = @__Lock__.new_cond + end + + protected + + def synchronize # TODO may be a problem with lock.synchronize { lock.wait } + @__Lock__.synchronize { yield } + end + + def ns_wait(timeout = nil) + @__Condition__.wait timeout + self + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/object.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/object.rb new file mode 100644 index 0000000..0e62112 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/object.rb @@ -0,0 +1,183 @@ +module Concurrent + module Synchronization + + # @!visibility private + # @!macro internal_implementation_note + ObjectImplementation = case + when Concurrent.on_cruby? + MriObject + when Concurrent.on_jruby? + JRubyObject + when Concurrent.on_rbx? + RbxObject + when Concurrent.on_truffleruby? + TruffleRubyObject + else + warn 'Possibly unsupported Ruby implementation' + MriObject + end + private_constant :ObjectImplementation + + # Abstract object providing final, volatile, ans CAS extensions to build other concurrent abstractions. + # - final instance variables see {Object.safe_initialization!} + # - volatile instance variables see {Object.attr_volatile} + # - volatile instance variables see {Object.attr_atomic} + class Object < ObjectImplementation + # TODO make it a module if possible + + # @!method self.attr_volatile(*names) + # Creates methods for reading and writing (as `attr_accessor` does) to a instance variable with + # volatile (Java) semantic. The instance variable should be accessed only through generated methods. + # + # @param [::Array] names of the instance variables to be volatile + # @return [::Array] names of defined method names + + # Has to be called by children. + def initialize + super + __initialize_atomic_fields__ + end + + # By calling this method on a class, it and all its children are marked to be constructed safely. Meaning that + # all writes (ivar initializations) are made visible to all readers of newly constructed object. It ensures + # same behaviour as Java's final fields. + # @example + # class AClass < Concurrent::Synchronization::Object + # safe_initialization! + # + # def initialize + # @AFinalValue = 'value' # published safely, does not have to be synchronized + # end + # end + # @return [true] + def self.safe_initialization! + # define only once, and not again in children + return if safe_initialization? + + # @!visibility private + def self.new(*args, &block) + object = super(*args, &block) + ensure + object.full_memory_barrier if object + end + + @safe_initialization = true + end + + # @return [true, false] if this class is safely initialized. + def self.safe_initialization? + @safe_initialization = false unless defined? @safe_initialization + @safe_initialization || (superclass.respond_to?(:safe_initialization?) && superclass.safe_initialization?) + end + + # For testing purposes, quite slow. Injects assert code to new method which will raise if class instance contains + # any instance variables with CamelCase names and isn't {.safe_initialization?}. + # @raise when offend found + # @return [true] + def self.ensure_safe_initialization_when_final_fields_are_present + Object.class_eval do + def self.new(*args, &block) + object = super(*args, &block) + ensure + has_final_field = object.instance_variables.any? { |v| v.to_s =~ /^@[A-Z]/ } + if has_final_field && !safe_initialization? + raise "there was an instance of #{object.class} with final field but not marked with safe_initialization!" + end + end + end + true + end + + # Creates methods for reading and writing to a instance variable with + # volatile (Java) semantic as {.attr_volatile} does. + # The instance variable should be accessed oly through generated methods. + # This method generates following methods: `value`, `value=(new_value) #=> new_value`, + # `swap_value(new_value) #=> old_value`, + # `compare_and_set_value(expected, value) #=> true || false`, `update_value(&block)`. + # @param [::Array] names of the instance variables to be volatile with CAS. + # @return [::Array] names of defined method names. + # @!macro attr_atomic + # @!method $1 + # @return [Object] The $1. + # @!method $1=(new_$1) + # Set the $1. + # @return [Object] new_$1. + # @!method swap_$1(new_$1) + # Set the $1 to new_$1 and return the old $1. + # @return [Object] old $1 + # @!method compare_and_set_$1(expected_$1, new_$1) + # Sets the $1 to new_$1 if the current $1 is expected_$1 + # @return [true, false] + # @!method update_$1(&block) + # Updates the $1 using the block. + # @yield [Object] Calculate a new $1 using given (old) $1 + # @yieldparam [Object] old $1 + # @return [Object] new $1 + def self.attr_atomic(*names) + @__atomic_fields__ ||= [] + @__atomic_fields__ += names + safe_initialization! + define_initialize_atomic_fields + + names.each do |name| + ivar = :"@Atomic#{name.to_s.gsub(/(?:^|_)(.)/) { $1.upcase }}" + class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{name} + #{ivar}.get + end + + def #{name}=(value) + #{ivar}.set value + end + + def swap_#{name}(value) + #{ivar}.swap value + end + + def compare_and_set_#{name}(expected, value) + #{ivar}.compare_and_set expected, value + end + + def update_#{name}(&block) + #{ivar}.update(&block) + end + RUBY + end + names.flat_map { |n| [n, :"#{n}=", :"swap_#{n}", :"compare_and_set_#{n}", :"update_#{n}"] } + end + + # @param [true, false] inherited should inherited volatile with CAS fields be returned? + # @return [::Array] Returns defined volatile with CAS fields on this class. + def self.atomic_attributes(inherited = true) + @__atomic_fields__ ||= [] + ((superclass.atomic_attributes if superclass.respond_to?(:atomic_attributes) && inherited) || []) + @__atomic_fields__ + end + + # @return [true, false] is the attribute with name atomic? + def self.atomic_attribute?(name) + atomic_attributes.include? name + end + + private + + def self.define_initialize_atomic_fields + assignments = @__atomic_fields__.map do |name| + "@Atomic#{name.to_s.gsub(/(?:^|_)(.)/) { $1.upcase }} = Concurrent::AtomicReference.new(nil)" + end.join("\n") + + class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def __initialize_atomic_fields__ + super + #{assignments} + end + RUBY + end + + private_class_method :define_initialize_atomic_fields + + def __initialize_atomic_fields__ + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/rbx_lockable_object.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/rbx_lockable_object.rb new file mode 100644 index 0000000..1c4697c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/rbx_lockable_object.rb @@ -0,0 +1,71 @@ +module Concurrent + module Synchronization + + # @!visibility private + # @!macro internal_implementation_note + class RbxLockableObject < AbstractLockableObject + safe_initialization! + + def initialize(*defaults) + super(*defaults) + @__Waiters__ = [] + @__owner__ = nil + end + + def initialize_copy(other) + super + @__Waiters__ = [] + @__owner__ = nil + end + + protected + + def synchronize(&block) + if @__owner__ == Thread.current + yield + else + result = nil + Rubinius.synchronize(self) do + begin + @__owner__ = Thread.current + result = yield + ensure + @__owner__ = nil + end + end + result + end + end + + def ns_wait(timeout = nil) + wchan = Rubinius::Channel.new + + begin + @__Waiters__.push wchan + Rubinius.unlock(self) + signaled = wchan.receive_timeout timeout + ensure + Rubinius.lock(self) + + if !signaled && !@__Waiters__.delete(wchan) + # we timed out, but got signaled afterwards, + # so pass that signal on to the next waiter + @__Waiters__.shift << true unless @__Waiters__.empty? + end + end + + self + end + + def ns_signal + @__Waiters__.shift << true unless @__Waiters__.empty? + self + end + + def ns_broadcast + @__Waiters__.shift << true until @__Waiters__.empty? + self + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/rbx_object.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/rbx_object.rb new file mode 100644 index 0000000..4b23f2a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/rbx_object.rb @@ -0,0 +1,49 @@ +module Concurrent + module Synchronization + + # @!visibility private + module RbxAttrVolatile + def self.included(base) + base.extend(ClassMethods) + end + + module ClassMethods + + def attr_volatile(*names) + names.each do |name| + ivar = :"@volatile_#{name}" + class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{name} + Rubinius.memory_barrier + #{ivar} + end + + def #{name}=(value) + #{ivar} = value + Rubinius.memory_barrier + end + RUBY + end + names.map { |n| [n, :"#{n}="] }.flatten + end + + end + + def full_memory_barrier + # Rubinius instance variables are not volatile so we need to insert barrier + # TODO (pitr 26-Nov-2015): check comments like ^ + Rubinius.memory_barrier + end + end + + # @!visibility private + # @!macro internal_implementation_note + class RbxObject < AbstractObject + include RbxAttrVolatile + + def initialize + # nothing to do + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/truffleruby_object.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/truffleruby_object.rb new file mode 100644 index 0000000..3919c76 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/truffleruby_object.rb @@ -0,0 +1,47 @@ +module Concurrent + module Synchronization + + # @!visibility private + module TruffleRubyAttrVolatile + def self.included(base) + base.extend(ClassMethods) + end + + module ClassMethods + def attr_volatile(*names) + names.each do |name| + ivar = :"@volatile_#{name}" + + class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{name} + full_memory_barrier + #{ivar} + end + + def #{name}=(value) + #{ivar} = value + full_memory_barrier + end + RUBY + end + + names.map { |n| [n, :"#{n}="] }.flatten + end + end + + def full_memory_barrier + TruffleRuby.full_memory_barrier + end + end + + # @!visibility private + # @!macro internal_implementation_note + class TruffleRubyObject < AbstractObject + include TruffleRubyAttrVolatile + + def initialize + # nothing to do + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/volatile.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/volatile.rb new file mode 100644 index 0000000..9dffa91 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/synchronization/volatile.rb @@ -0,0 +1,36 @@ +module Concurrent + module Synchronization + + # Volatile adds the attr_volatile class method when included. + # + # @example + # class Foo + # include Concurrent::Synchronization::Volatile + # + # attr_volatile :bar + # + # def initialize + # self.bar = 1 + # end + # end + # + # foo = Foo.new + # foo.bar + # => 1 + # foo.bar = 2 + # => 2 + + Volatile = case + when Concurrent.on_cruby? + MriAttrVolatile + when Concurrent.on_jruby? + JRubyAttrVolatile + when Concurrent.on_rbx? + RbxAttrVolatile + when Concurrent.on_truffleruby? + TruffleRubyAttrVolatile + else + MriAttrVolatile + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/synchronized_delegator.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/synchronized_delegator.rb new file mode 100644 index 0000000..92e7c45 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/synchronized_delegator.rb @@ -0,0 +1,50 @@ +require 'delegate' +require 'monitor' + +module Concurrent + unless defined?(SynchronizedDelegator) + + # This class provides a trivial way to synchronize all calls to a given object + # by wrapping it with a `Delegator` that performs `Monitor#enter/exit` calls + # around the delegated `#send`. Example: + # + # array = [] # not thread-safe on many impls + # array = SynchronizedDelegator.new([]) # thread-safe + # + # A simple `Monitor` provides a very coarse-grained way to synchronize a given + # object, in that it will cause synchronization for methods that have no need + # for it, but this is a trivial way to get thread-safety where none may exist + # currently on some implementations. + # + # This class is currently being considered for inclusion into stdlib, via + # https://bugs.ruby-lang.org/issues/8556 + # + # @!visibility private + class SynchronizedDelegator < SimpleDelegator + def setup + @old_abort = Thread.abort_on_exception + Thread.abort_on_exception = true + end + + def teardown + Thread.abort_on_exception = @old_abort + end + + def initialize(obj) + __setobj__(obj) + @monitor = Monitor.new + end + + def method_missing(method, *args, &block) + monitor = @monitor + begin + monitor.enter + super + ensure + monitor.exit + end + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util.rb new file mode 100644 index 0000000..c67084a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util.rb @@ -0,0 +1,16 @@ +module Concurrent + + # @!visibility private + module ThreadSafe + + # @!visibility private + module Util + + # TODO (pitr-ch 15-Oct-2016): migrate to Utility::NativeInteger + FIXNUM_BIT_SIZE = (0.size * 8) - 2 + MAX_INT = (2 ** FIXNUM_BIT_SIZE) - 1 + # TODO (pitr-ch 15-Oct-2016): migrate to Utility::ProcessorCounter + CPU_COUNT = 16 # is there a way to determine this? + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/adder.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/adder.rb new file mode 100644 index 0000000..7a6e8d5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/adder.rb @@ -0,0 +1,74 @@ +require 'concurrent/thread_safe/util' +require 'concurrent/thread_safe/util/striped64' + +module Concurrent + + # @!visibility private + module ThreadSafe + + # @!visibility private + module Util + + # A Ruby port of the Doug Lea's jsr166e.LondAdder class version 1.8 + # available in public domain. + # + # Original source code available here: + # http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/LongAdder.java?revision=1.8 + # + # One or more variables that together maintain an initially zero + # sum. When updates (method +add+) are contended across threads, + # the set of variables may grow dynamically to reduce contention. + # Method +sum+ returns the current total combined across the + # variables maintaining the sum. + # + # This class is usually preferable to single +Atomic+ reference when + # multiple threads update a common sum that is used for purposes such + # as collecting statistics, not for fine-grained synchronization + # control. Under low update contention, the two classes have similar + # characteristics. But under high contention, expected throughput of + # this class is significantly higher, at the expense of higher space + # consumption. + # + # @!visibility private + class Adder < Striped64 + # Adds the given value. + def add(x) + if (current_cells = cells) || !cas_base_computed {|current_base| current_base + x} + was_uncontended = true + hash = hash_code + unless current_cells && (cell = current_cells.volatile_get_by_hash(hash)) && (was_uncontended = cell.cas_computed {|current_value| current_value + x}) + retry_update(x, hash, was_uncontended) {|current_value| current_value + x} + end + end + end + + def increment + add(1) + end + + def decrement + add(-1) + end + + # Returns the current sum. The returned value is _NOT_ an + # atomic snapshot: Invocation in the absence of concurrent + # updates returns an accurate result, but concurrent updates that + # occur while the sum is being calculated might not be + # incorporated. + def sum + x = base + if current_cells = cells + current_cells.each do |cell| + x += cell.value if cell + end + end + x + end + + def reset + internal_reset(0) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/cheap_lockable.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/cheap_lockable.rb new file mode 100644 index 0000000..d9b4c58 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/cheap_lockable.rb @@ -0,0 +1,118 @@ +require 'concurrent/thread_safe/util' +require 'concurrent/thread_safe/util/volatile' + +module Concurrent + + # @!visibility private + module ThreadSafe + + # @!visibility private + module Util + + # Provides a cheapest possible (mainly in terms of memory usage) +Mutex+ + # with the +ConditionVariable+ bundled in. + # + # Usage: + # class A + # include CheapLockable + # + # def do_exlusively + # cheap_synchronize { yield } + # end + # + # def wait_for_something + # cheap_synchronize do + # cheap_wait until resource_available? + # do_something + # cheap_broadcast # wake up others + # end + # end + # end + # + # @!visibility private + module CheapLockable + private + engine = defined?(RUBY_ENGINE) && RUBY_ENGINE + if engine == 'rbx' + # Making use of the Rubinius' ability to lock via object headers to avoid the overhead of the extra Mutex objects. + def cheap_synchronize + Rubinius.lock(self) + begin + yield + ensure + Rubinius.unlock(self) + end + end + + def cheap_wait + wchan = Rubinius::Channel.new + + begin + waiters = @waiters ||= [] + waiters.push wchan + Rubinius.unlock(self) + signaled = wchan.receive_timeout nil + ensure + Rubinius.lock(self) + + unless signaled or waiters.delete(wchan) + # we timed out, but got signaled afterwards (e.g. while waiting to + # acquire @lock), so pass that signal on to the next waiter + waiters.shift << true unless waiters.empty? + end + end + + self + end + + def cheap_broadcast + waiters = @waiters ||= [] + waiters.shift << true until waiters.empty? + self + end + elsif engine == 'jruby' + # Use Java's native synchronized (this) { wait(); notifyAll(); } to avoid the overhead of the extra Mutex objects + require 'jruby' + + def cheap_synchronize + JRuby.reference0(self).synchronized { yield } + end + + def cheap_wait + JRuby.reference0(self).wait + end + + def cheap_broadcast + JRuby.reference0(self).notify_all + end + else + require 'thread' + + extend Volatile + attr_volatile :mutex + + # Non-reentrant Mutex#syncrhonize + def cheap_synchronize + true until (my_mutex = mutex) || cas_mutex(nil, my_mutex = Mutex.new) + my_mutex.synchronize { yield } + end + + # Releases this object's +cheap_synchronize+ lock and goes to sleep waiting for other threads to +cheap_broadcast+, reacquires the lock on wakeup. + # Must only be called in +cheap_broadcast+'s block. + def cheap_wait + conditional_variable = @conditional_variable ||= ConditionVariable.new + conditional_variable.wait(mutex) + end + + # Wakes up all threads waiting for this object's +cheap_synchronize+ lock. + # Must only be called in +cheap_broadcast+'s block. + def cheap_broadcast + if conditional_variable = @conditional_variable + conditional_variable.broadcast + end + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/data_structures.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/data_structures.rb new file mode 100644 index 0000000..24d039b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/data_structures.rb @@ -0,0 +1,88 @@ +require 'concurrent/thread_safe/util' + +# Shim for TruffleRuby.synchronized +if Concurrent.on_truffleruby? && !TruffleRuby.respond_to?(:synchronized) + module TruffleRuby + def self.synchronized(object, &block) + Truffle::System.synchronized(object, &block) + end + end +end + +module Concurrent + module ThreadSafe + module Util + def self.make_synchronized_on_cruby(klass) + klass.class_eval do + def initialize(*args, &block) + @_monitor = Monitor.new + super + end + + def initialize_copy(other) + # make sure a copy is not sharing a monitor with the original object! + @_monitor = Monitor.new + super + end + end + + klass.superclass.instance_methods(false).each do |method| + klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{method}(*args) + monitor = @_monitor + monitor or raise("BUG: Internal monitor was not properly initialized. Please report this to the concurrent-ruby developers.") + monitor.synchronize { super } + end + RUBY + end + end + + def self.make_synchronized_on_rbx(klass) + klass.class_eval do + private + + def _mon_initialize + @_monitor ||= Monitor.new # avoid double initialisation + end + + def self.new(*args) + obj = super(*args) + obj.send(:_mon_initialize) + obj + end + end + + klass.superclass.instance_methods(false).each do |method| + case method + when :new_range, :new_reserved + klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{method}(*args) + obj = super + obj.send(:_mon_initialize) + obj + end + RUBY + else + klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{method}(*args) + monitor = @_monitor + monitor or raise("BUG: Internal monitor was not properly initialized. Please report this to the concurrent-ruby developers.") + monitor.synchronize { super } + end + RUBY + end + end + end + + def self.make_synchronized_on_truffleruby(klass) + klass.superclass.instance_methods(false).each do |method| + klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{method}(*args, &block) + TruffleRuby.synchronized(self) { super(*args, &block) } + end + RUBY + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/power_of_two_tuple.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/power_of_two_tuple.rb new file mode 100644 index 0000000..b54be39 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/power_of_two_tuple.rb @@ -0,0 +1,38 @@ +require 'concurrent/thread_safe/util' +require 'concurrent/tuple' + +module Concurrent + + # @!visibility private + module ThreadSafe + + # @!visibility private + module Util + + # @!visibility private + class PowerOfTwoTuple < Concurrent::Tuple + + def initialize(size) + raise ArgumentError, "size must be a power of 2 (#{size.inspect} provided)" unless size > 0 && size & (size - 1) == 0 + super(size) + end + + def hash_to_index(hash) + (size - 1) & hash + end + + def volatile_get_by_hash(hash) + volatile_get(hash_to_index(hash)) + end + + def volatile_set_by_hash(hash, value) + volatile_set(hash_to_index(hash), value) + end + + def next_in_size_table + self.class.new(size << 1) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/striped64.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/striped64.rb new file mode 100644 index 0000000..4169c3d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/striped64.rb @@ -0,0 +1,246 @@ +require 'concurrent/thread_safe/util' +require 'concurrent/thread_safe/util/power_of_two_tuple' +require 'concurrent/thread_safe/util/volatile' +require 'concurrent/thread_safe/util/xor_shift_random' + +module Concurrent + + # @!visibility private + module ThreadSafe + + # @!visibility private + module Util + + # A Ruby port of the Doug Lea's jsr166e.Striped64 class version 1.6 + # available in public domain. + # + # Original source code available here: + # http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/Striped64.java?revision=1.6 + # + # Class holding common representation and mechanics for classes supporting + # dynamic striping on 64bit values. + # + # This class maintains a lazily-initialized table of atomically updated + # variables, plus an extra +base+ field. The table size is a power of two. + # Indexing uses masked per-thread hash codes. Nearly all methods on this + # class are private, accessed directly by subclasses. + # + # Table entries are of class +Cell+; a variant of AtomicLong padded to + # reduce cache contention on most processors. Padding is overkill for most + # Atomics because they are usually irregularly scattered in memory and thus + # don't interfere much with each other. But Atomic objects residing in + # arrays will tend to be placed adjacent to each other, and so will most + # often share cache lines (with a huge negative performance impact) without + # this precaution. + # + # In part because +Cell+s are relatively large, we avoid creating them until + # they are needed. When there is no contention, all updates are made to the + # +base+ field. Upon first contention (a failed CAS on +base+ update), the + # table is initialized to size 2. The table size is doubled upon further + # contention until reaching the nearest power of two greater than or equal + # to the number of CPUS. Table slots remain empty (+nil+) until they are + # needed. + # + # A single spinlock (+busy+) is used for initializing and resizing the + # table, as well as populating slots with new +Cell+s. There is no need for + # a blocking lock: When the lock is not available, threads try other slots + # (or the base). During these retries, there is increased contention and + # reduced locality, which is still better than alternatives. + # + # Per-thread hash codes are initialized to random values. Contention and/or + # table collisions are indicated by failed CASes when performing an update + # operation (see method +retry_update+). Upon a collision, if the table size + # is less than the capacity, it is doubled in size unless some other thread + # holds the lock. If a hashed slot is empty, and lock is available, a new + # +Cell+ is created. Otherwise, if the slot exists, a CAS is tried. Retries + # proceed by "double hashing", using a secondary hash (XorShift) to try to + # find a free slot. + # + # The table size is capped because, when there are more threads than CPUs, + # supposing that each thread were bound to a CPU, there would exist a + # perfect hash function mapping threads to slots that eliminates collisions. + # When we reach capacity, we search for this mapping by randomly varying the + # hash codes of colliding threads. Because search is random, and collisions + # only become known via CAS failures, convergence can be slow, and because + # threads are typically not bound to CPUS forever, may not occur at all. + # However, despite these limitations, observed contention rates are + # typically low in these cases. + # + # It is possible for a +Cell+ to become unused when threads that once hashed + # to it terminate, as well as in the case where doubling the table causes no + # thread to hash to it under expanded mask. We do not try to detect or + # remove such cells, under the assumption that for long-running instances, + # observed contention levels will recur, so the cells will eventually be + # needed again; and for short-lived ones, it does not matter. + # + # @!visibility private + class Striped64 + + # Padded variant of AtomicLong supporting only raw accesses plus CAS. + # The +value+ field is placed between pads, hoping that the JVM doesn't + # reorder them. + # + # Optimisation note: It would be possible to use a release-only + # form of CAS here, if it were provided. + # + # @!visibility private + class Cell < Concurrent::AtomicReference + + alias_method :cas, :compare_and_set + + def cas_computed + cas(current_value = value, yield(current_value)) + end + + # @!visibility private + def self.padding + # TODO: this only adds padding after the :value slot, need to find a way to add padding before the slot + # TODO (pitr-ch 28-Jul-2018): the padding instance vars may not be created + # hide from yardoc in a method + attr_reader :padding_0, :padding_1, :padding_2, :padding_3, :padding_4, :padding_5, :padding_6, :padding_7, :padding_8, :padding_9, :padding_10, :padding_11 + end + padding + end + + extend Volatile + attr_volatile :cells, # Table of cells. When non-null, size is a power of 2. + :base, # Base value, used mainly when there is no contention, but also as a fallback during table initialization races. Updated via CAS. + :busy # Spinlock (locked via CAS) used when resizing and/or creating Cells. + + alias_method :busy?, :busy + + def initialize + super() + self.busy = false + self.base = 0 + end + + # Handles cases of updates involving initialization, resizing, + # creating new Cells, and/or contention. See above for + # explanation. This method suffers the usual non-modularity + # problems of optimistic retry code, relying on rechecked sets of + # reads. + # + # Arguments: + # [+x+] + # the value + # [+hash_code+] + # hash code used + # [+x+] + # false if CAS failed before call + def retry_update(x, hash_code, was_uncontended) # :yields: current_value + hash = hash_code + collided = false # True if last slot nonempty + while true + if current_cells = cells + if !(cell = current_cells.volatile_get_by_hash(hash)) + if busy? + collided = false + else # Try to attach new Cell + if try_to_install_new_cell(Cell.new(x), hash) # Optimistically create and try to insert new cell + break + else + redo # Slot is now non-empty + end + end + elsif !was_uncontended # CAS already known to fail + was_uncontended = true # Continue after rehash + elsif cell.cas_computed {|current_value| yield current_value} + break + elsif current_cells.size >= CPU_COUNT || cells != current_cells # At max size or stale + collided = false + elsif collided && expand_table_unless_stale(current_cells) + collided = false + redo # Retry with expanded table + else + collided = true + end + hash = XorShiftRandom.xorshift(hash) + + elsif try_initialize_cells(x, hash) || cas_base_computed {|current_base| yield current_base} + break + end + end + self.hash_code = hash + end + + private + # Static per-thread hash code key. Shared across all instances to + # reduce Thread locals pollution and because adjustments due to + # collisions in one table are likely to be appropriate for + # others. + THREAD_LOCAL_KEY = "#{name}.hash_code".to_sym + + # A thread-local hash code accessor. The code is initially + # random, but may be set to a different value upon collisions. + def hash_code + Thread.current[THREAD_LOCAL_KEY] ||= XorShiftRandom.get + end + + def hash_code=(hash) + Thread.current[THREAD_LOCAL_KEY] = hash + end + + # Sets base and all +cells+ to the given value. + def internal_reset(initial_value) + current_cells = cells + self.base = initial_value + if current_cells + current_cells.each do |cell| + cell.value = initial_value if cell + end + end + end + + def cas_base_computed + cas_base(current_base = base, yield(current_base)) + end + + def free? + !busy? + end + + def try_initialize_cells(x, hash) + if free? && !cells + try_in_busy do + unless cells # Recheck under lock + new_cells = PowerOfTwoTuple.new(2) + new_cells.volatile_set_by_hash(hash, Cell.new(x)) + self.cells = new_cells + end + end + end + end + + def expand_table_unless_stale(current_cells) + try_in_busy do + if current_cells == cells # Recheck under lock + new_cells = current_cells.next_in_size_table + current_cells.each_with_index {|x, i| new_cells.volatile_set(i, x)} + self.cells = new_cells + end + end + end + + def try_to_install_new_cell(new_cell, hash) + try_in_busy do + # Recheck under lock + if (current_cells = cells) && !current_cells.volatile_get(i = current_cells.hash_to_index(hash)) + current_cells.volatile_set(i, new_cell) + end + end + end + + def try_in_busy + if cas_busy(false, true) + begin + yield + ensure + self.busy = false + end + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/volatile.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/volatile.rb new file mode 100644 index 0000000..cdac2a3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/volatile.rb @@ -0,0 +1,75 @@ +require 'concurrent/thread_safe/util' + +module Concurrent + + # @!visibility private + module ThreadSafe + + # @!visibility private + module Util + + # @!visibility private + module Volatile + + # Provides +volatile+ (in the JVM's sense) attribute accessors implemented + # atop of +Concurrent::AtomicReference+. + # + # Usage: + # class Foo + # extend Concurrent::ThreadSafe::Util::Volatile + # attr_volatile :foo, :bar + # + # def initialize(bar) + # super() # must super() into parent initializers before using the volatile attribute accessors + # self.bar = bar + # end + # + # def hello + # my_foo = foo # volatile read + # self.foo = 1 # volatile write + # cas_foo(1, 2) # => true | a strong CAS + # end + # end + def attr_volatile(*attr_names) + return if attr_names.empty? + include(Module.new do + atomic_ref_setup = attr_names.map {|attr_name| "@__#{attr_name} = Concurrent::AtomicReference.new"} + initialize_copy_setup = attr_names.zip(atomic_ref_setup).map do |attr_name, ref_setup| + "#{ref_setup}(other.instance_variable_get(:@__#{attr_name}).get)" + end + class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 + def initialize(*) + super + #{atomic_ref_setup.join('; ')} + end + + def initialize_copy(other) + super + #{initialize_copy_setup.join('; ')} + end + RUBY_EVAL + + attr_names.each do |attr_name| + class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 + def #{attr_name} + @__#{attr_name}.get + end + + def #{attr_name}=(value) + @__#{attr_name}.set(value) + end + + def compare_and_set_#{attr_name}(old_value, new_value) + @__#{attr_name}.compare_and_set(old_value, new_value) + end + RUBY_EVAL + + alias_method :"cas_#{attr_name}", :"compare_and_set_#{attr_name}" + alias_method :"lazy_set_#{attr_name}", :"#{attr_name}=" + end + end) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/xor_shift_random.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/xor_shift_random.rb new file mode 100644 index 0000000..bdde2dd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/thread_safe/util/xor_shift_random.rb @@ -0,0 +1,50 @@ +require 'concurrent/thread_safe/util' + +module Concurrent + + # @!visibility private + module ThreadSafe + + # @!visibility private + module Util + + # A xorshift random number (positive +Fixnum+s) generator, provides + # reasonably cheap way to generate thread local random numbers without + # contending for the global +Kernel.rand+. + # + # Usage: + # x = XorShiftRandom.get # uses Kernel.rand to generate an initial seed + # while true + # if (x = XorShiftRandom.xorshift).odd? # thread-localy generate a next random number + # do_something_at_random + # end + # end + module XorShiftRandom + extend self + MAX_XOR_SHIFTABLE_INT = MAX_INT - 1 + + # Generates an initial non-zero positive +Fixnum+ via +Kernel.rand+. + def get + Kernel.rand(MAX_XOR_SHIFTABLE_INT) + 1 # 0 can't be xorshifted + end + + # xorshift based on: http://www.jstatsoft.org/v08/i14/paper + if 0.size == 4 + # using the "yˆ=y>>a; yˆ=y<>c;" transform with the (a,b,c) tuple with values (3,1,14) to minimise Bignum overflows + def xorshift(x) + x ^= x >> 3 + x ^= (x << 1) & MAX_INT # cut-off Bignum overflow + x ^= x >> 14 + end + else + # using the "yˆ=y>>a; yˆ=y<>c;" transform with the (a,b,c) tuple with values (1,1,54) to minimise Bignum overflows + def xorshift(x) + x ^= x >> 1 + x ^= (x << 1) & MAX_INT # cut-off Bignum overflow + x ^= x >> 54 + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/timer_task.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/timer_task.rb new file mode 100644 index 0000000..b69cfc8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/timer_task.rb @@ -0,0 +1,311 @@ +require 'concurrent/collection/copy_on_notify_observer_set' +require 'concurrent/concern/dereferenceable' +require 'concurrent/concern/observable' +require 'concurrent/atomic/atomic_boolean' +require 'concurrent/executor/executor_service' +require 'concurrent/executor/ruby_executor_service' +require 'concurrent/executor/safe_task_executor' +require 'concurrent/scheduled_task' + +module Concurrent + + # A very common concurrency pattern is to run a thread that performs a task at + # regular intervals. The thread that performs the task sleeps for the given + # interval then wakes up and performs the task. Lather, rinse, repeat... This + # pattern causes two problems. First, it is difficult to test the business + # logic of the task because the task itself is tightly coupled with the + # concurrency logic. Second, an exception raised while performing the task can + # cause the entire thread to abend. In a long-running application where the + # task thread is intended to run for days/weeks/years a crashed task thread + # can pose a significant problem. `TimerTask` alleviates both problems. + # + # When a `TimerTask` is launched it starts a thread for monitoring the + # execution interval. The `TimerTask` thread does not perform the task, + # however. Instead, the TimerTask launches the task on a separate thread. + # Should the task experience an unrecoverable crash only the task thread will + # crash. This makes the `TimerTask` very fault tolerant. Additionally, the + # `TimerTask` thread can respond to the success or failure of the task, + # performing logging or ancillary operations. + # + # One other advantage of `TimerTask` is that it forces the business logic to + # be completely decoupled from the concurrency logic. The business logic can + # be tested separately then passed to the `TimerTask` for scheduling and + # running. + # + # In some cases it may be necessary for a `TimerTask` to affect its own + # execution cycle. To facilitate this, a reference to the TimerTask instance + # is passed as an argument to the provided block every time the task is + # executed. + # + # The `TimerTask` class includes the `Dereferenceable` mixin module so the + # result of the last execution is always available via the `#value` method. + # Dereferencing options can be passed to the `TimerTask` during construction or + # at any later time using the `#set_deref_options` method. + # + # `TimerTask` supports notification through the Ruby standard library + # {http://ruby-doc.org/stdlib-2.0/libdoc/observer/rdoc/Observable.html + # Observable} module. On execution the `TimerTask` will notify the observers + # with three arguments: time of execution, the result of the block (or nil on + # failure), and any raised exceptions (or nil on success). + # + # @!macro copy_options + # + # @example Basic usage + # task = Concurrent::TimerTask.new{ puts 'Boom!' } + # task.execute + # + # task.execution_interval #=> 60 (default) + # + # # wait 60 seconds... + # #=> 'Boom!' + # + # task.shutdown #=> true + # + # @example Configuring `:execution_interval` + # task = Concurrent::TimerTask.new(execution_interval: 5) do + # puts 'Boom!' + # end + # + # task.execution_interval #=> 5 + # + # @example Immediate execution with `:run_now` + # task = Concurrent::TimerTask.new(run_now: true){ puts 'Boom!' } + # task.execute + # + # #=> 'Boom!' + # + # @example Last `#value` and `Dereferenceable` mixin + # task = Concurrent::TimerTask.new( + # dup_on_deref: true, + # execution_interval: 5 + # ){ Time.now } + # + # task.execute + # Time.now #=> 2013-11-07 18:06:50 -0500 + # sleep(10) + # task.value #=> 2013-11-07 18:06:55 -0500 + # + # @example Controlling execution from within the block + # timer_task = Concurrent::TimerTask.new(execution_interval: 1) do |task| + # task.execution_interval.times{ print 'Boom! ' } + # print "\n" + # task.execution_interval += 1 + # if task.execution_interval > 5 + # puts 'Stopping...' + # task.shutdown + # end + # end + # + # timer_task.execute # blocking call - this task will stop itself + # #=> Boom! + # #=> Boom! Boom! + # #=> Boom! Boom! Boom! + # #=> Boom! Boom! Boom! Boom! + # #=> Boom! Boom! Boom! Boom! Boom! + # #=> Stopping... + # + # @example Observation + # class TaskObserver + # def update(time, result, ex) + # if result + # print "(#{time}) Execution successfully returned #{result}\n" + # else + # print "(#{time}) Execution failed with error #{ex}\n" + # end + # end + # end + # + # task = Concurrent::TimerTask.new(execution_interval: 1){ 42 } + # task.add_observer(TaskObserver.new) + # task.execute + # sleep 4 + # + # #=> (2013-10-13 19:08:58 -0400) Execution successfully returned 42 + # #=> (2013-10-13 19:08:59 -0400) Execution successfully returned 42 + # #=> (2013-10-13 19:09:00 -0400) Execution successfully returned 42 + # task.shutdown + # + # task = Concurrent::TimerTask.new(execution_interval: 1){ sleep } + # task.add_observer(TaskObserver.new) + # task.execute + # + # #=> (2013-10-13 19:07:25 -0400) Execution timed out + # #=> (2013-10-13 19:07:27 -0400) Execution timed out + # #=> (2013-10-13 19:07:29 -0400) Execution timed out + # task.shutdown + # + # task = Concurrent::TimerTask.new(execution_interval: 1){ raise StandardError } + # task.add_observer(TaskObserver.new) + # task.execute + # + # #=> (2013-10-13 19:09:37 -0400) Execution failed with error StandardError + # #=> (2013-10-13 19:09:38 -0400) Execution failed with error StandardError + # #=> (2013-10-13 19:09:39 -0400) Execution failed with error StandardError + # task.shutdown + # + # @see http://ruby-doc.org/stdlib-2.0/libdoc/observer/rdoc/Observable.html + # @see http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html + class TimerTask < RubyExecutorService + include Concern::Dereferenceable + include Concern::Observable + + # Default `:execution_interval` in seconds. + EXECUTION_INTERVAL = 60 + + # Default `:timeout_interval` in seconds. + TIMEOUT_INTERVAL = 30 + + # Create a new TimerTask with the given task and configuration. + # + # @!macro timer_task_initialize + # @param [Hash] opts the options defining task execution. + # @option opts [Integer] :execution_interval number of seconds between + # task executions (default: EXECUTION_INTERVAL) + # @option opts [Boolean] :run_now Whether to run the task immediately + # upon instantiation or to wait until the first # execution_interval + # has passed (default: false) + # + # @!macro deref_options + # + # @raise ArgumentError when no block is given. + # + # @yield to the block after :execution_interval seconds have passed since + # the last yield + # @yieldparam task a reference to the `TimerTask` instance so that the + # block can control its own lifecycle. Necessary since `self` will + # refer to the execution context of the block rather than the running + # `TimerTask`. + # + # @return [TimerTask] the new `TimerTask` + def initialize(opts = {}, &task) + raise ArgumentError.new('no block given') unless block_given? + super + set_deref_options opts + end + + # Is the executor running? + # + # @return [Boolean] `true` when running, `false` when shutting down or shutdown + def running? + @running.true? + end + + # Execute a previously created `TimerTask`. + # + # @return [TimerTask] a reference to `self` + # + # @example Instance and execute in separate steps + # task = Concurrent::TimerTask.new(execution_interval: 10){ print "Hello World\n" } + # task.running? #=> false + # task.execute + # task.running? #=> true + # + # @example Instance and execute in one line + # task = Concurrent::TimerTask.new(execution_interval: 10){ print "Hello World\n" }.execute + # task.running? #=> true + def execute + synchronize do + if @running.false? + @running.make_true + schedule_next_task(@run_now ? 0 : @execution_interval) + end + end + self + end + + # Create and execute a new `TimerTask`. + # + # @!macro timer_task_initialize + # + # @example + # task = Concurrent::TimerTask.execute(execution_interval: 10){ print "Hello World\n" } + # task.running? #=> true + def self.execute(opts = {}, &task) + TimerTask.new(opts, &task).execute + end + + # @!attribute [rw] execution_interval + # @return [Fixnum] Number of seconds after the task completes before the + # task is performed again. + def execution_interval + synchronize { @execution_interval } + end + + # @!attribute [rw] execution_interval + # @return [Fixnum] Number of seconds after the task completes before the + # task is performed again. + def execution_interval=(value) + if (value = value.to_f) <= 0.0 + raise ArgumentError.new('must be greater than zero') + else + synchronize { @execution_interval = value } + end + end + + # @!attribute [rw] timeout_interval + # @return [Fixnum] Number of seconds the task can run before it is + # considered to have failed. + def timeout_interval + warn 'TimerTask timeouts are now ignored as these were not able to be implemented correctly' + end + + # @!attribute [rw] timeout_interval + # @return [Fixnum] Number of seconds the task can run before it is + # considered to have failed. + def timeout_interval=(value) + warn 'TimerTask timeouts are now ignored as these were not able to be implemented correctly' + end + + private :post, :<< + + private + + def ns_initialize(opts, &task) + set_deref_options(opts) + + self.execution_interval = opts[:execution] || opts[:execution_interval] || EXECUTION_INTERVAL + if opts[:timeout] || opts[:timeout_interval] + warn 'TimeTask timeouts are now ignored as these were not able to be implemented correctly' + end + @run_now = opts[:now] || opts[:run_now] + @executor = Concurrent::SafeTaskExecutor.new(task) + @running = Concurrent::AtomicBoolean.new(false) + @value = nil + + self.observers = Collection::CopyOnNotifyObserverSet.new + end + + # @!visibility private + def ns_shutdown_execution + @running.make_false + super + end + + # @!visibility private + def ns_kill_execution + @running.make_false + super + end + + # @!visibility private + def schedule_next_task(interval = execution_interval) + ScheduledTask.execute(interval, args: [Concurrent::Event.new], &method(:execute_task)) + nil + end + + # @!visibility private + def execute_task(completion) + return nil unless @running.true? + _success, value, reason = @executor.execute(self) + if completion.try? + self.value = value + schedule_next_task + time = Time.now + observers.notify_observers do + [time, self.value, reason] + end + end + nil + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/tuple.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/tuple.rb new file mode 100644 index 0000000..f8c4c25 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/tuple.rb @@ -0,0 +1,86 @@ +require 'concurrent/atomic/atomic_reference' + +module Concurrent + + # A fixed size array with volatile (synchronized, thread safe) getters/setters. + # Mixes in Ruby's `Enumerable` module for enhanced search, sort, and traversal. + # + # @example + # tuple = Concurrent::Tuple.new(16) + # + # tuple.set(0, :foo) #=> :foo | volatile write + # tuple.get(0) #=> :foo | volatile read + # tuple.compare_and_set(0, :foo, :bar) #=> true | strong CAS + # tuple.cas(0, :foo, :baz) #=> false | strong CAS + # tuple.get(0) #=> :bar | volatile read + # + # @see https://en.wikipedia.org/wiki/Tuple Tuple entry at Wikipedia + # @see http://www.erlang.org/doc/reference_manual/data_types.html#id70396 Erlang Tuple + # @see http://ruby-doc.org/core-2.2.2/Enumerable.html Enumerable + class Tuple + include Enumerable + + # The (fixed) size of the tuple. + attr_reader :size + + # @!visibility private + Tuple = defined?(Rubinius::Tuple) ? Rubinius::Tuple : ::Array + private_constant :Tuple + + # Create a new tuple of the given size. + # + # @param [Integer] size the number of elements in the tuple + def initialize(size) + @size = size + @tuple = tuple = Tuple.new(size) + i = 0 + while i < size + tuple[i] = Concurrent::AtomicReference.new + i += 1 + end + end + + # Get the value of the element at the given index. + # + # @param [Integer] i the index from which to retrieve the value + # @return [Object] the value at the given index or nil if the index is out of bounds + def get(i) + return nil if i >= @size || i < 0 + @tuple[i].get + end + alias_method :volatile_get, :get + + # Set the element at the given index to the given value + # + # @param [Integer] i the index for the element to set + # @param [Object] value the value to set at the given index + # + # @return [Object] the new value of the element at the given index or nil if the index is out of bounds + def set(i, value) + return nil if i >= @size || i < 0 + @tuple[i].set(value) + end + alias_method :volatile_set, :set + + # Set the value at the given index to the new value if and only if the current + # value matches the given old value. + # + # @param [Integer] i the index for the element to set + # @param [Object] old_value the value to compare against the current value + # @param [Object] new_value the value to set at the given index + # + # @return [Boolean] true if the value at the given element was set else false + def compare_and_set(i, old_value, new_value) + return false if i >= @size || i < 0 + @tuple[i].compare_and_set(old_value, new_value) + end + alias_method :cas, :compare_and_set + + # Calls the given block once for each element in self, passing that element as a parameter. + # + # @yieldparam [Object] ref the `Concurrent::AtomicReference` object at the current index + def each + @tuple.each {|ref| yield ref.get} + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/tvar.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/tvar.rb new file mode 100644 index 0000000..104761f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/tvar.rb @@ -0,0 +1,221 @@ +require 'set' +require 'concurrent/synchronization' + +module Concurrent + + # A `TVar` is a transactional variable - a single-element container that + # is used as part of a transaction - see `Concurrent::atomically`. + # + # @!macro thread_safe_variable_comparison + # + # {include:file:docs-source/tvar.md} + class TVar < Synchronization::Object + safe_initialization! + + # Create a new `TVar` with an initial value. + def initialize(value) + @value = value + @lock = Mutex.new + end + + # Get the value of a `TVar`. + def value + Concurrent::atomically do + Transaction::current.read(self) + end + end + + # Set the value of a `TVar`. + def value=(value) + Concurrent::atomically do + Transaction::current.write(self, value) + end + end + + # @!visibility private + def unsafe_value # :nodoc: + @value + end + + # @!visibility private + def unsafe_value=(value) # :nodoc: + @value = value + end + + # @!visibility private + def unsafe_lock # :nodoc: + @lock + end + + end + + # Run a block that reads and writes `TVar`s as a single atomic transaction. + # With respect to the value of `TVar` objects, the transaction is atomic, in + # that it either happens or it does not, consistent, in that the `TVar` + # objects involved will never enter an illegal state, and isolated, in that + # transactions never interfere with each other. You may recognise these + # properties from database transactions. + # + # There are some very important and unusual semantics that you must be aware of: + # + # * Most importantly, the block that you pass to atomically may be executed + # more than once. In most cases your code should be free of + # side-effects, except for via TVar. + # + # * If an exception escapes an atomically block it will abort the transaction. + # + # * It is undefined behaviour to use callcc or Fiber with atomically. + # + # * If you create a new thread within an atomically, it will not be part of + # the transaction. Creating a thread counts as a side-effect. + # + # Transactions within transactions are flattened to a single transaction. + # + # @example + # a = new TVar(100_000) + # b = new TVar(100) + # + # Concurrent::atomically do + # a.value -= 10 + # b.value += 10 + # end + def atomically + raise ArgumentError.new('no block given') unless block_given? + + # Get the current transaction + + transaction = Transaction::current + + # Are we not already in a transaction (not nested)? + + if transaction.nil? + # New transaction + + begin + # Retry loop + + loop do + + # Create a new transaction + + transaction = Transaction.new + Transaction::current = transaction + + # Run the block, aborting on exceptions + + begin + result = yield + rescue Transaction::AbortError => e + transaction.abort + result = Transaction::ABORTED + rescue Transaction::LeaveError => e + transaction.abort + break result + rescue => e + transaction.abort + raise e + end + # If we can commit, break out of the loop + + if result != Transaction::ABORTED + if transaction.commit + break result + end + end + end + ensure + # Clear the current transaction + + Transaction::current = nil + end + else + # Nested transaction - flatten it and just run the block + + yield + end + end + + # Abort a currently running transaction - see `Concurrent::atomically`. + def abort_transaction + raise Transaction::AbortError.new + end + + # Leave a transaction without committing or aborting - see `Concurrent::atomically`. + def leave_transaction + raise Transaction::LeaveError.new + end + + module_function :atomically, :abort_transaction, :leave_transaction + + private + + class Transaction + + ABORTED = ::Object.new + + OpenEntry = Struct.new(:value, :modified) + + AbortError = Class.new(StandardError) + LeaveError = Class.new(StandardError) + + def initialize + @open_tvars = {} + end + + def read(tvar) + entry = open(tvar) + entry.value + end + + def write(tvar, value) + entry = open(tvar) + entry.modified = true + entry.value = value + end + + def open(tvar) + entry = @open_tvars[tvar] + + unless entry + unless tvar.unsafe_lock.try_lock + Concurrent::abort_transaction + end + + entry = OpenEntry.new(tvar.unsafe_value, false) + @open_tvars[tvar] = entry + end + + entry + end + + def abort + unlock + end + + def commit + @open_tvars.each do |tvar, entry| + if entry.modified + tvar.unsafe_value = entry.value + end + end + + unlock + end + + def unlock + @open_tvars.each_key do |tvar| + tvar.unsafe_lock.unlock + end + end + + def self.current + Thread.current[:current_tvar_transaction] + end + + def self.current=(transaction) + Thread.current[:current_tvar_transaction] = transaction + end + + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/engine.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/engine.rb new file mode 100644 index 0000000..bc4173e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/engine.rb @@ -0,0 +1,56 @@ +module Concurrent + module Utility + + # @!visibility private + module EngineDetector + def on_jruby? + ruby_engine == 'jruby' + end + + def on_jruby_9000? + on_jruby? && ruby_version(JRUBY_VERSION, :>=, 9, 0, 0) + end + + def on_cruby? + ruby_engine == 'ruby' + end + + def on_rbx? + ruby_engine == 'rbx' + end + + def on_truffleruby? + ruby_engine == 'truffleruby' + end + + def on_windows? + !(RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/).nil? + end + + def on_osx? + !(RbConfig::CONFIG['host_os'] =~ /darwin|mac os/).nil? + end + + def on_linux? + !(RbConfig::CONFIG['host_os'] =~ /linux/).nil? + end + + def ruby_engine + defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby' + end + + def ruby_version(version = RUBY_VERSION, comparison, major, minor, patch) + result = (version.split('.').map(&:to_i) <=> [major, minor, patch]) + comparisons = { :== => [0], + :>= => [1, 0], + :<= => [-1, 0], + :> => [1], + :< => [-1] } + comparisons.fetch(comparison).include? result + end + end + end + + # @!visibility private + extend Utility::EngineDetector +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/monotonic_time.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/monotonic_time.rb new file mode 100644 index 0000000..0fa5c50 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/monotonic_time.rb @@ -0,0 +1,90 @@ +require 'concurrent/synchronization' + +module Concurrent + + # @!macro monotonic_get_time + # + # Returns the current time a tracked by the application monotonic clock. + # + # @param [Symbol] unit the time unit to be returned, can be either + # :float_second, :float_millisecond, :float_microsecond, :second, + # :millisecond, :microsecond, or :nanosecond default to :float_second. + # + # @return [Float] The current monotonic time since some unspecified + # starting point + # + # @!macro monotonic_clock_warning + if defined?(Process::CLOCK_MONOTONIC) + + def monotonic_time(unit = :float_second) + Process.clock_gettime(Process::CLOCK_MONOTONIC, unit) + end + + elsif Concurrent.on_jruby? + + # @!visibility private + TIME_UNITS = Hash.new { |_hash, key| raise ArgumentError, "unexpected unit: #{key}" }.compare_by_identity + TIME_UNITS.merge!( + second: 1_000_000_000, + millisecond: 1_000_000, + microsecond: 1_000, + nanosecond: 1, + float_second: 1_000_000_000.0, + float_millisecond: 1_000_000.0, + float_microsecond: 1_000.0, + ) + TIME_UNITS.freeze + private_constant :TIME_UNITS + + def monotonic_time(unit = :float_second) + java.lang.System.nanoTime() / TIME_UNITS[unit] + end + + else + + class_definition = Class.new(Synchronization::LockableObject) do + def initialize + @last_time = Time.now.to_f + @time_units = Hash.new { |_hash, key| raise ArgumentError, "unexpected unit: #{key}" }.compare_by_identity + @time_units.merge!( + second: [nil, true], + millisecond: [1_000, true], + microsecond: [1_000_000, true], + nanosecond: [1_000_000_000, true], + float_second: [nil, false], + float_millisecond: [1_000.0, false], + float_microsecond: [1_000_000.0, false], + ) + super() + end + + # @!visibility private + def get_time(unit) + synchronize do + now = Time.now.to_f + if @last_time < now + @last_time = now + else # clock has moved back in time + @last_time += 0.000_001 + end + scale, to_int = @time_units[unit] + now *= scale if scale + now = now.to_i if to_int + now + end + end + end + + # Clock that cannot be set and represents monotonic time since + # some unspecified starting point. + # + # @!visibility private + GLOBAL_MONOTONIC_CLOCK = class_definition.new + private_constant :GLOBAL_MONOTONIC_CLOCK + + def monotonic_time(unit = :float_second) + GLOBAL_MONOTONIC_CLOCK.get_time(unit) + end + end + module_function :monotonic_time +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/native_extension_loader.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/native_extension_loader.rb new file mode 100644 index 0000000..a944bd7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/native_extension_loader.rb @@ -0,0 +1,79 @@ +require 'concurrent/utility/engine' + +module Concurrent + + module Utility + + # @!visibility private + module NativeExtensionLoader + + def allow_c_extensions? + Concurrent.on_cruby? + end + + def c_extensions_loaded? + defined?(@c_extensions_loaded) && @c_extensions_loaded + end + + def java_extensions_loaded? + defined?(@java_extensions_loaded) && @java_extensions_loaded + end + + def load_native_extensions + unless defined? Synchronization::AbstractObject + raise 'native_extension_loader loaded before Synchronization::AbstractObject' + end + + if Concurrent.on_cruby? && !c_extensions_loaded? + ['concurrent/concurrent_ruby_ext', + "concurrent/#{RUBY_VERSION[0..2]}/concurrent_ruby_ext" + ].each { |p| try_load_c_extension p } + end + + if Concurrent.on_jruby? && !java_extensions_loaded? + begin + require 'concurrent/concurrent_ruby.jar' + set_java_extensions_loaded + rescue LoadError => e + raise e, "Java extensions are required for JRuby.\n" + e.message, e.backtrace + end + end + end + + private + + def load_error_path(error) + if error.respond_to? :path + error.path + else + error.message.split(' -- ').last + end + end + + def set_c_extensions_loaded + @c_extensions_loaded = true + end + + def set_java_extensions_loaded + @java_extensions_loaded = true + end + + def try_load_c_extension(path) + require path + set_c_extensions_loaded + rescue LoadError => e + if load_error_path(e) == path + # move on with pure-Ruby implementations + # TODO (pitr-ch 12-Jul-2018): warning on verbose? + else + raise e + end + end + + end + end + + # @!visibility private + extend Utility::NativeExtensionLoader +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/native_integer.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/native_integer.rb new file mode 100644 index 0000000..10719e7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/native_integer.rb @@ -0,0 +1,53 @@ +module Concurrent + module Utility + # @private + module NativeInteger + # http://stackoverflow.com/questions/535721/ruby-max-integer + MIN_VALUE = -(2**(0.size * 8 - 2)) + MAX_VALUE = (2**(0.size * 8 - 2) - 1) + + def ensure_upper_bound(value) + if value > MAX_VALUE + raise RangeError.new("#{value} is greater than the maximum value of #{MAX_VALUE}") + end + value + end + + def ensure_lower_bound(value) + if value < MIN_VALUE + raise RangeError.new("#{value} is less than the maximum value of #{MIN_VALUE}") + end + value + end + + def ensure_integer(value) + unless value.is_a?(Integer) + raise ArgumentError.new("#{value} is not an Integer") + end + value + end + + def ensure_integer_and_bounds(value) + ensure_integer value + ensure_upper_bound value + ensure_lower_bound value + end + + def ensure_positive(value) + if value < 0 + raise ArgumentError.new("#{value} cannot be negative") + end + value + end + + def ensure_positive_and_no_zero(value) + if value < 1 + raise ArgumentError.new("#{value} cannot be negative or zero") + end + value + end + + extend self + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/processor_counter.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/processor_counter.rb new file mode 100644 index 0000000..c59f981 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/utility/processor_counter.rb @@ -0,0 +1,130 @@ +require 'etc' +require 'rbconfig' +require 'concurrent/delay' + +module Concurrent + module Utility + + # @!visibility private + class ProcessorCounter + def initialize + @processor_count = Delay.new { compute_processor_count } + @physical_processor_count = Delay.new { compute_physical_processor_count } + end + + # Number of processors seen by the OS and used for process scheduling. For + # performance reasons the calculated value will be memoized on the first + # call. + # + # When running under JRuby the Java runtime call + # `java.lang.Runtime.getRuntime.availableProcessors` will be used. According + # to the Java documentation this "value may change during a particular + # invocation of the virtual machine... [applications] should therefore + # occasionally poll this property." Subsequently the result will NOT be + # memoized under JRuby. + # + # Ruby's Etc.nprocessors will be used if available (MRI 2.2+). + # + # On Windows the Win32 API will be queried for the + # `NumberOfLogicalProcessors from Win32_Processor`. This will return the + # total number "logical processors for the current instance of the + # processor", which taked into account hyperthreading. + # + # * AIX: /usr/sbin/pmcycles (AIX 5+), /usr/sbin/lsdev + # * Alpha: /usr/bin/nproc (/proc/cpuinfo exists but cannot be used) + # * BSD: /sbin/sysctl + # * Cygwin: /proc/cpuinfo + # * Darwin: /usr/bin/hwprefs, /usr/sbin/sysctl + # * HP-UX: /usr/sbin/ioscan + # * IRIX: /usr/sbin/sysconf + # * Linux: /proc/cpuinfo + # * Minix 3+: /proc/cpuinfo + # * Solaris: /usr/sbin/psrinfo + # * Tru64 UNIX: /usr/sbin/psrinfo + # * UnixWare: /usr/sbin/psrinfo + # + # @return [Integer] number of processors seen by the OS or Java runtime + # + # @see https://github.com/grosser/parallel/blob/4fc8b89d08c7091fe0419ca8fba1ec3ce5a8d185/lib/parallel.rb + # + # @see http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#availableProcessors() + # @see http://msdn.microsoft.com/en-us/library/aa394373(v=vs.85).aspx + def processor_count + @processor_count.value + end + + # Number of physical processor cores on the current system. For performance + # reasons the calculated value will be memoized on the first call. + # + # On Windows the Win32 API will be queried for the `NumberOfCores from + # Win32_Processor`. This will return the total number "of cores for the + # current instance of the processor." On Unix-like operating systems either + # the `hwprefs` or `sysctl` utility will be called in a subshell and the + # returned value will be used. In the rare case where none of these methods + # work or an exception is raised the function will simply return 1. + # + # @return [Integer] number physical processor cores on the current system + # + # @see https://github.com/grosser/parallel/blob/4fc8b89d08c7091fe0419ca8fba1ec3ce5a8d185/lib/parallel.rb + # + # @see http://msdn.microsoft.com/en-us/library/aa394373(v=vs.85).aspx + # @see http://www.unix.com/man-page/osx/1/HWPREFS/ + # @see http://linux.die.net/man/8/sysctl + def physical_processor_count + @physical_processor_count.value + end + + private + + def compute_processor_count + if Concurrent.on_jruby? + java.lang.Runtime.getRuntime.availableProcessors + else + Etc.nprocessors + end + end + + def compute_physical_processor_count + ppc = case RbConfig::CONFIG["target_os"] + when /darwin\d\d/ + IO.popen("/usr/sbin/sysctl -n hw.physicalcpu", &:read).to_i + when /linux/ + cores = {} # unique physical ID / core ID combinations + phy = 0 + IO.read("/proc/cpuinfo").scan(/^physical id.*|^core id.*/) do |ln| + if ln.start_with?("physical") + phy = ln[/\d+/] + elsif ln.start_with?("core") + cid = phy + ":" + ln[/\d+/] + cores[cid] = true if not cores[cid] + end + end + cores.count + when /mswin|mingw/ + require 'win32ole' + result_set = WIN32OLE.connect("winmgmts://").ExecQuery( + "select NumberOfCores from Win32_Processor") + result_set.to_enum.collect(&:NumberOfCores).reduce(:+) + else + processor_count + end + # fall back to logical count if physical info is invalid + ppc > 0 ? ppc : processor_count + rescue + return 1 + end + end + end + + # create the default ProcessorCounter on load + @processor_counter = Utility::ProcessorCounter.new + singleton_class.send :attr_reader, :processor_counter + + def self.processor_count + processor_counter.processor_count + end + + def self.physical_processor_count + processor_counter.physical_processor_count + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/version.rb b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/version.rb new file mode 100644 index 0000000..4372d0d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/concurrent-ruby-1.1.10/lib/concurrent-ruby/concurrent/version.rb @@ -0,0 +1,3 @@ +module Concurrent + VERSION = '1.1.10' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/CHANGELOG.md b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/CHANGELOG.md new file mode 100644 index 0000000..26b9ce7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/CHANGELOG.md @@ -0,0 +1,338 @@ +1.15.5 / 2022-01-10 +------------------- + +Fixed: +* Fix long double argument or return values on 32bit i686. #849 +* FFI::ConstGenerator: avoid usage of the same binary file simultaneously. #929 + +Added: +* Add Windows fat binary gem for Ruby-3.1 + +Removed: +* Remove Windows fat binary gem for Ruby < 2.4 + + +1.15.4 / 2021-09-01 +------------------- + +Fixed: +* Fix build for uClibc. #913 +* Correct module lookup when including `ffi-module` gem. #912 + +Changed: +* Use ruby code of the ffi gem in JRuby-9.2.20+. #915 + + +1.15.3 / 2021-06-16 +------------------- + +Fixed: +* Fix temporary packaging issue with libffi. #904 + + +1.15.2 / 2021-06-16 +------------------- + +Added: +* Add support for Windows MINGW-UCRT build. #903 +* Add `/opt/homebrew/lib/` to fallback search paths to improve homebrew support. #880 #882 + +Changed: +* Regenerate `types.conf` for FreeBSD12 aarch64. #902 + + +1.15.1 / 2021-05-22 +------------------- + +Fixed: +* Append -pthread to linker options. #893 +* Use arm or aarch64 to identify Apple ARM CPU arch. #899 +* Allow overriding `gcc` with the `CC` env var in `const_generator.rb` and `struct_generator.rb`. #897 + + +1.15.0 / 2021-03-05 +------------------- + +Fixed: +* Fix MSVC build +* Fix async callbacks in conjunction with fork(). #884 + +Added: +* Allow to pass callbacks in varargs. #885 +* Name the threads for FFI callback dispatcher and async thread calls for easier debugging. #883 + The name can be retrieved by Thread.name and is shown by Thread.list.inspect etc. + Even gdb shows the thread name on supported operating systems. +* Add types.conf for powerpc64le-linux +* Add types.conf for riscv64-linux +* More release automation of ffi gems + +Changed: +* Switch from rubygems-tasks to bundler/gem_helper + +Removed: +* Remove unused VariadicInvoker#init + + +1.14.2 / 2020-12-21 +------------------- + +Fixed: +* Fix builtin libffi on newer Ubuntu caused by an outdated Makefile.in . #863 + + +1.14.1 / 2020-12-19 +------------------- + +Changed: +* Revert changes to FFI::Pointer#write_string made in ffi-1.14.0. + It breaks compatibilty in a way that can cause hard to find errors. #857 + + +1.14.0 / 2020-12-18 +------------------- + +Added: +* Add types.conf for x86_64-msys, x86_64-haiku, aarch64-openbsd and aarch64-darwin (alias arm64-darwin) +* Add method AbstractMemory#size_limit? . #829 +* Add new extconf option --enable-libffi-alloc which is enabled per default on Apple M1 (arm64-darwin). + +Changed: +* Do NULL pointer check only when array length > 0 . #305 +* Raise an error on an unknown order argument. #830 +* Change FFI::Pointer#write_string to terminate with a NUL byte like other string methods. #805 +* Update bundled libffi to latest master. + +Removed: +* Remove win32/stdint.h and stdbool.h because of copyright issue. #693 + +Fixed: +* Fix possible UTF-8 load error in loader script interpretation. #792 +* Fix segfault on non-array argument to #write_array_of_* +* Fix memory leak in MethodHandle . #815 +* Fix possible segfault in combination with fiddle or other libffi using gems . #835 +* Fix possibility to use ffi ruby gem with JRuby-9.3 . #763 +* Fix a GC issue, when a callback Proc is used on more than 2 callback signatures. #820 + + +1.13.1 / 2020-06-09 +------------------- + +Changed: +* Revert use of `ucrtbase.dll` as default C library on Windows-MINGW. + `ucrtbase.dll` is still used on MSWIN target. #790 +* Test for `ffi_prep_closure_loc()` to make sure we can use this function. + This fixes incorrect use of system libffi on MacOS Mojave (10.14). #787 +* Update types.conf on x86_64-dragonflybsd + + +1.13.0 / 2020-06-01 +------------------- + +Added: +* Add TruffleRuby support. Almost all specs are running on TruffleRuby and succeed. #768 +* Add ruby source files to the java gem. This allows to ship the Ruby library code per platform java gem and add it as a default gem to JRuby. #763 +* Add FFI::Platform::LONG_DOUBLE_SIZE +* Add bounds checks for writing to an inline char[] . #756 +* Add long double as callback return value. #771 +* Update type definitions and add types from stdint.h and stddef.h on i386-windows, x86_64-windows, x86_64-darwin, x86_64-linux, arm-linux, powerpc-linux. #749 +* Add new type definitions for powerpc-openbsd and sparcv9-openbsd. #775, #778 + +Changed: +* Raise required ruby version to >= 2.3. +* Lots of cleanups and improvements in library, specs and benchmarks. +* Fix a lot of compiler warnings at the C-extension +* Fix several install issues on MacOS: + * Look for libffi in SDK paths, since recent versions of macOS removed it from `/usr/include` . #757 + * Fix error `ld: library not found for -lgcc_s.10.4` + * Don't built for i386 architecture as it is deprecated +* Several fixes for MSVC build on Windows. #779 +* Use `ucrtbase.dll` as default C library on Windows instead of old `msvcrt.dll`. #779 +* Update builtin libffi to fix a Powerpc issue with parameters of type long +* Allow unmodified sourcing of (the ruby code of) this gem in JRuby and TruffleRuby as a default gem. #747 +* Improve check to detect if a module has a #find_type method suitable for FFI. This fixes compatibility with stdlib `mkmf` . #776 + +Removed: +* Reject callback with `:string` return type at definition, because it didn't work so far and is not save to use. #751, #782 + + +1.12.2 / 2020-02-01 +------------------- + +* Fix possible segfault at FFI::Struct#[] and []= after GC.compact . #742 + + +1.12.1 / 2020-01-14 +------------------- + +Added: +* Add binary gem support for ruby-2.7 on Windows + + +1.12.0 / 2020-01-14 +------------------- + +Added: +* FFI::VERSION is defined as part of `require 'ffi'` now. + It is no longer necessary to `require 'ffi/version'` . + +Changed: +* Update libffi to latest master. + +Deprecated: +* Overwriting struct layouts is now warned and will be disallowed in ffi-2.0. #734, #735 + + +1.11.3 / 2019-11-25 +------------------- + +Removed: +* Remove support for tainted objects which cause deprecation warnings in ruby-2.7. #730 + + +1.11.2 / 2019-11-11 +------------------- + +Added: +* Add DragonFlyBSD as a platform. #724 + +Changed: +* Sort all types.conf files, so that files and changes are easier to compare. +* Regenerated type conf for freebsd12 and x86_64-linux targets. #722 +* Remove MACOSX_DEPLOYMENT_TARGET that was targeting very old version 10.4. #647 +* Fix library name mangling for non glibc Linux/UNIX. #727 +* Fix compiler warnings raised by ruby-2.7 +* Update libffi to latest master. + + +1.11.1 / 2019-05-20 +------------------- + +Changed: +* Raise required ruby version to >=2.0. #699, #700 +* Fix a possible linker error on ruby < 2.3 on Linux. + + +1.11.0 / 2019-05-17 +------------------- +This version was yanked on 2019-05-20 to fix an install issue on ruby-1.9.3. #700 + +Added: +* Add ability to disable or force use of system libffi. #669 + Use like `gem inst ffi -- --enable-system-libffi` . +* Add ability to call FFI callbacks from outside of FFI call frame. #584 +* Add proper documentation to FFI::Generator and ::Task +* Add gemspec metadata. #696, #698 + +Changed: +* Fix stdcall on Win32. #649, #669 +* Fix load paths for FFI::Generator::Task +* Fix FFI::Pointer#read_string(0) to return a binary String. #692 +* Fix benchmark suite so that it runs on ruby-2.x +* Move FFI::Platform::CPU from C to Ruby. #663 +* Move FFI::StructByReference to Ruby. #681 +* Move FFI::DataConverter to Ruby (#661) +* Various cleanups and improvements of specs and benchmarks + +Removed: +* Remove ruby-1.8 and 1.9 compatibility code. #683 +* Remove unused spec files. #684 + + +1.10.0 / 2019-01-06 +------------------- + +Added: +* Add /opt/local/lib/ to ffi's fallback library search path. #638 +* Add binary gem support for ruby-2.6 on Windows +* Add FreeBSD on AArch64 and ARM support. #644 +* Add FFI::LastError.winapi_error on Windows native or Cygwin. #633 + +Changed: +* Update to rake-compiler-dock-0.7.0 +* Use 64-bit inodes on FreeBSD >= 12. #644 +* Switch time_t and suseconds_t types to long on FreeBSD. #627 +* Make register_t long_long on 64-bit FreeBSD. #644 +* Fix Pointer#write_array_of_type #637 + +Removed: +* Drop binary gem support for ruby-2.0 and 2.1 on Windows + + +1.9.25 / 2018-06-03 +------------------- + +Changed: +* Revert closures via libffi. + This re-adds ClosurePool and fixes compat with SELinux enabled systems. #621 + + +1.9.24 / 2018-06-02 +------------------- + +Security Note: + +This update addresses vulnerability CVE-2018-1000201: DLL loading issue which can be hijacked on Windows OS, when a Symbol is used as DLL name instead of a String. Found by Matthew Bush. + +Added: +* Added a CHANGELOG file +* Add mips64(eb) support, and mips r6 support. (#601) + +Changed: +* Update libffi to latest changes on master. +* Don't search in hardcoded /usr paths on Windows. +* Don't treat Symbol args different to Strings in ffi_lib. +* Make sure size_t is defined in Thread.c. Fixes #609 + + +1.9.23 / 2018-02-25 +------------------- + +Changed: +* Fix unnecessary rebuild of configure in darwin multi arch. Fixes #605 + + +1.9.22 / 2018-02-22 +------------------- + +Changed: +* Update libffi to latest changes on master. +* Update detection of system libffi to match new requirements. Fixes #617 +* Prefer bundled libffi over system libffi on Mac OS. +* Do closures via libffi. This removes ClosurePool and fixes compat with PaX. #540 +* Use a more deterministic gem packaging. +* Fix unnecessary update of autoconf files at gem install. + + +1.9.21 / 2018-02-06 +------------------- + +Added: +* Ruby-2.5 support by Windows binary gems. Fixes #598 +* Add missing win64 types. +* Added support for Bitmask. (#573) +* Add support for MSYS2 (#572) and Sparc64 Linux. (#574) + +Changed: +* Fix read_string to not throw an error on length 0. +* Don't use absolute paths for sh and env. Fixes usage on Adroid #528 +* Use Ruby implementation for `which` for better compat with Windows. Fixes #315 +* Fix compatibility with PPC64LE platform. (#577) +* Normalize sparc64 to sparcv9. (#575) + +Removed: +* Drop Ruby 1.8.7 support (#480) + + +1.9.18 / 2017-03-03 +------------------- + +Added: +* Add compatibility with Ruby-2.4. + +Changed: +* Add missing shlwapi.h include to fix Windows build. +* Avoid undefined behaviour of LoadLibrary() on Windows. #553 + + +1.9.17 / 2017-01-13 +------------------- diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/COPYING b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/COPYING new file mode 100644 index 0000000..7622318 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/COPYING @@ -0,0 +1,49 @@ +Copyright (c) 2008-2013, Ruby FFI project contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the Ruby FFI project nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +libffi, used by this project, is licensed under the MIT license: + +libffi - Copyright (c) 1996-2011 Anthony Green, Red Hat, Inc and others. +See source files for details. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/Gemfile b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/Gemfile new file mode 100644 index 0000000..ad819ef --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/Gemfile @@ -0,0 +1,14 @@ +source 'https://rubygems.org' + +group :development do + gem 'rake', '~> 13.0' + gem 'rake-compiler', '~> 1.0.3' + gem 'rake-compiler-dock', '~> 1.0' + gem 'rspec', '~> 3.0' + gem 'bundler', '>= 1.16', '< 3' +end + +group :doc do + gem 'kramdown' + gem 'yard', '~> 0.9' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/LICENSE b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/LICENSE new file mode 100644 index 0000000..20185fd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2008-2016, Ruby FFI project contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the Ruby FFI project nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/LICENSE.SPECS b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/LICENSE.SPECS new file mode 100644 index 0000000..5c9ffce --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/LICENSE.SPECS @@ -0,0 +1,22 @@ +Copyright (c) 2008-2012 Ruby-FFI contributors + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/README.md b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/README.md new file mode 100644 index 0000000..5845f26 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/README.md @@ -0,0 +1,136 @@ +# Ruby-FFI https://github.com/ffi/ffi/wiki [![Build Status](https://travis-ci.com/ffi/ffi.svg?branch=master)](https://travis-ci.com/ffi/ffi) [![Build status Windows](https://ci.appveyor.com/api/projects/status/r8wxn1sd4s794gg1/branch/master?svg=true)](https://ci.appveyor.com/project/larskanis/ffi-aofqa/branch/master) + +## Description + +Ruby-FFI is a gem for programmatically loading dynamically-linked native +libraries, binding functions within them, and calling those functions +from Ruby code. Moreover, a Ruby-FFI extension works without changes +on CRuby (MRI), JRuby, Rubinius and TruffleRuby. [Discover why you should write your next extension +using Ruby-FFI](https://github.com/ffi/ffi/wiki/why-use-ffi). + +## Features + +* Intuitive DSL +* Supports all C native types +* C structs (also nested), enums and global variables +* Callbacks from C to Ruby +* Automatic garbage collection of native memory + +## Synopsis + +```ruby +require 'ffi' + +module MyLib + extend FFI::Library + ffi_lib 'c' + attach_function :puts, [ :string ], :int +end + +MyLib.puts 'Hello, World using libc!' +``` + +For less minimalistic and more examples you may look at: + +* the `samples/` folder +* the examples on the [wiki](https://github.com/ffi/ffi/wiki) +* the projects using FFI listed on the wiki: https://github.com/ffi/ffi/wiki/projects-using-ffi + +## Requirements + +When installing the gem on CRuby (MRI), you will need: +* A C compiler (e.g., Xcode on macOS, `gcc` or `clang` on everything else) +Optionally (speeds up installation): +* The `libffi` library and development headers - this is commonly in the `libffi-dev` or `libffi-devel` packages + +The ffi gem comes with a builtin libffi version, which is used, when the system libffi library is not available or too old. +Use of the system libffi can be enforced by: +``` +gem install ffi -- --enable-system-libffi # to install the gem manually +bundle config build.ffi --enable-system-libffi # for bundle install +``` +or prevented by `--disable-system-libffi`. + +On Linux systems running with [PaX](https://en.wikipedia.org/wiki/PaX) (Gentoo, Alpine, etc.), FFI may trigger `mprotect` errors. You may need to disable [mprotect](https://en.wikibooks.org/wiki/Grsecurity/Appendix/Grsecurity_and_PaX_Configuration_Options#Restrict_mprotect.28.29) for ruby (`paxctl -m [/path/to/ruby]`) for the time being until a solution is found. + +On FreeBSD systems pkgconf must be installed for the gem to be able to compile using clang. Install either via packages `pkg install pkgconf` or from ports via `devel/pkgconf`. + +On JRuby and TruffleRuby, there are no requirements to install the FFI gem, and `require 'ffi'` works even without installing the gem (i.e., the gem is preinstalled on these implementations). + +## Installation + +From rubygems: + + [sudo] gem install ffi + +From a Gemfile using git or GitHub + + gem 'ffi', github: 'ffi/ffi', submodules: true + +or from the git repository on github: + + git clone git://github.com/ffi/ffi.git + cd ffi + git submodule update --init --recursive + bundle install + rake install + +### Install options: + +* `--enable-system-libffi` : Force usage of system libffi +* `--disable-system-libffi` : Force usage of builtin libffi +* `--enable-libffi-alloc` : Force closure allocation by libffi +* `--disable-libffi-alloc` : Force closure allocation by builtin method + +## License + +The ffi library is covered by the BSD license, also see the LICENSE file. +The specs are covered by the same license as [ruby/spec](https://github.com/ruby/spec), the MIT license. + +## Credits + +The following people have submitted code, bug reports, or otherwise contributed to the success of this project: + +* Alban Peignier +* Aman Gupta +* Andrea Fazzi +* Andreas Niederl +* Andrew Cholakian +* Antonio Terceiro +* Benoit Daloze +* Brian Candler +* Brian D. Burns +* Bryan Kearney +* Charlie Savage +* Chikanaga Tomoyuki +* Hongli Lai +* Ian MacLeod +* Jake Douglas +* Jean-Dominique Morani +* Jeremy Hinegardner +* Jesús García Sáez +* Joe Khoobyar +* Jurij Smakov +* KISHIMOTO, Makoto +* Kim Burgestrand +* Lars Kanis +* Luc Heinrich +* Luis Lavena +* Matijs van Zuijlen +* Matthew King +* Mike Dalessio +* NARUSE, Yui +* Park Heesob +* Shin Yee +* Stephen Bannasch +* Suraj N. Kurapati +* Sylvain Daubert +* Victor Costan +* beoran@gmail.com +* ctide +* emboss +* hobophobe +* meh +* postmodern +* wycats@gmail.com +* Wayne Meissner diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/Rakefile b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/Rakefile new file mode 100644 index 0000000..7175060 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/Rakefile @@ -0,0 +1,191 @@ +require 'rbconfig' +require 'date' +require 'fileutils' +require 'rbconfig' +require 'rspec/core/rake_task' +require 'rubygems/package_task' +require 'rake/extensiontask' +require_relative "lib/ffi/version" +require_relative "rakelib/ffi_gem_helper" + +BUILD_DIR = "build" +BUILD_EXT_DIR = File.join(BUILD_DIR, "#{RbConfig::CONFIG['arch']}", 'ffi_c', RUBY_VERSION) + +gem_spec = Bundler.load_gemspec('ffi.gemspec') + +RSpec::Core::RakeTask.new(:spec => :compile) do |config| + config.rspec_opts = YAML.load_file 'spec/spec.opts' +end + +desc "Build all packages" +task :package => %w[ gem:java gem:native ] + +CLOBBER.include 'lib/ffi/types.conf' +CLOBBER.include 'pkg' +CLOBBER.include 'log' + +CLEAN.include 'build' +CLEAN.include 'conftest.dSYM' +CLEAN.include 'spec/ffi/fixtures/libtest.{dylib,so,dll}' +CLEAN.include 'spec/ffi/fixtures/*.o' +CLEAN.include 'spec/ffi/embed-test/ext/*.{o,def}' +CLEAN.include 'spec/ffi/embed-test/ext/Makefile' +CLEAN.include "pkg/ffi-*-{mingw32,java}" +CLEAN.include 'lib/1.*' +CLEAN.include 'lib/2.*' + +# clean all shipped files, that are not in git +CLEAN.include( + gem_spec.files - + `git --git-dir ext/ffi_c/libffi/.git ls-files -z`.split("\x0").map { |f| File.join("ext/ffi_c/libffi", f) } - + `git ls-files -z`.split("\x0") +) + +task :distclean => :clobber + +desc "Test the extension" +task :test => [ :spec ] + + +namespace :bench do + ITER = ENV['ITER'] ? ENV['ITER'].to_i : 100000 + bench_files = Dir["bench/bench_*.rb"].sort.reject { |f| f == "bench/bench_helper.rb" } + bench_files.each do |bench| + task File.basename(bench, ".rb")[6..-1] => :compile do + sh %{#{Gem.ruby} #{bench} #{ITER}} + end + end + task :all => :compile do + bench_files.each do |bench| + sh %{#{Gem.ruby} #{bench}} + end + end +end + +task 'spec:run' => :compile +task 'spec:specdoc' => :compile + +task :default => :spec + +namespace 'java' do + + java_gem_spec = gem_spec.dup.tap do |s| + s.files.reject! { |f| File.fnmatch?("ext/*", f) } + s.extensions = [] + s.platform = 'java' + end + + Gem::PackageTask.new(java_gem_spec) do |pkg| + pkg.need_zip = true + pkg.need_tar = true + pkg.package_dir = 'pkg' + end +end + +task 'gem:java' => 'java:gem' + +FfiGemHelper.install_tasks +# Register windows gems to be pushed to rubygems.org +Bundler::GemHelper.instance.cross_platforms = %w[x86-mingw32 x64-mingw-ucrt x64-mingw32] + +if RUBY_ENGINE == 'ruby' || RUBY_ENGINE == 'rbx' + require 'rake/extensiontask' + Rake::ExtensionTask.new('ffi_c', gem_spec) do |ext| + ext.name = 'ffi_c' # indicate the name of the extension. + # ext.lib_dir = BUILD_DIR # put binaries into this folder. + ext.tmp_dir = BUILD_DIR # temporary folder used during compilation. + ext.cross_compile = true # enable cross compilation (requires cross compile toolchain) + ext.cross_platform = Bundler::GemHelper.instance.cross_platforms + ext.cross_compiling do |spec| + spec.files.reject! { |path| File.fnmatch?('ext/*', path) } + end + + end +else + task :compile do + STDERR.puts "Nothing to compile on #{RUBY_ENGINE}" + end +end + + +namespace "gem" do + task 'prepare' do + require 'rake_compiler_dock' + sh "bundle package --all" + end + + Bundler::GemHelper.instance.cross_platforms.each do |plat| + desc "Build all native binary gems in parallel" + multitask 'native' => plat + + desc "Build the native gem for #{plat}" + task plat => ['prepare', 'build'] do + RakeCompilerDock.sh <<-EOT, platform: plat + sudo apt-get update && + sudo apt-get install -y libltdl-dev && bundle --local && + rake cross native gem MAKE='nice make -j`nproc`' RUBY_CC_VERSION=${RUBY_CC_VERSION/:2.2.2/} + EOT + end + end +end + +directory "ext/ffi_c/libffi" +file "ext/ffi_c/libffi/autogen.sh" => "ext/ffi_c/libffi" do + warn "Downloading libffi ..." + sh "git submodule update --init --recursive" +end +task :libffi => "ext/ffi_c/libffi/autogen.sh" + +LIBFFI_GIT_FILES = `git --git-dir ext/ffi_c/libffi/.git ls-files -z`.split("\x0") + +# Generate files which are in the gemspec but not in libffi's git repo by running autogen.sh +gem_spec.files.select do |f| + f =~ /ext\/ffi_c\/libffi\/(.*)/ && !LIBFFI_GIT_FILES.include?($1) +end.each do |f| + file f => "ext/ffi_c/libffi/autogen.sh" do + chdir "ext/ffi_c/libffi" do + sh "sh ./autogen.sh" + end + touch f + if gem_spec.files != Gem::Specification.load('./ffi.gemspec').files + warn "gemspec files have changed -> Please restart rake!" + exit 1 + end + end +end + +# Make sure we have all gemspec files before packaging +task :build => gem_spec.files +task :gem => :build + + +require_relative "lib/ffi/platform" +types_conf = File.expand_path(File.join(FFI::Platform::CONF_DIR, 'types.conf')) +logfile = File.join(File.dirname(__FILE__), 'types_log') + +task types_conf do |task| + require 'fileutils' + require_relative "lib/ffi/tools/types_generator" + options = {} + FileUtils.mkdir_p(File.dirname(task.name), mode: 0755 ) + File.open(task.name, File::CREAT|File::TRUNC|File::RDWR, 0644) do |f| + f.puts FFI::TypesGenerator.generate(options) + end + File.open(logfile, 'w') do |log| + log.puts(types_conf) + end +end + +desc "Create or update type information for platform #{FFI::Platform::NAME}" +task :types_conf => types_conf + +begin + require 'yard' + + namespace :doc do + YARD::Rake::YardocTask.new do |yard| + end + end +rescue LoadError + warn "[warn] YARD unavailable" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/.sitearchdir.time b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/.sitearchdir.time new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/AbstractMemory.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/AbstractMemory.c new file mode 100644 index 0000000..1a7fcde --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/AbstractMemory.c @@ -0,0 +1,1104 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * Copyright (C) 2009 Jake Douglas + * Copyright (C) 2008 Luc Heinrich + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#ifndef _MSC_VER +# include +#endif +#include +#include + +#include +#include + +#include "rbffi.h" +#include "compat.h" +#include "AbstractMemory.h" +#include "Pointer.h" +#include "Function.h" +#include "LongDouble.h" + +#ifdef PRIsVALUE +# define RB_OBJ_CLASSNAME(obj) rb_obj_class(obj) +# define RB_OBJ_STRING(obj) (obj) +#else +# define PRIsVALUE "s" +# define RB_OBJ_CLASSNAME(obj) rb_obj_classname(obj) +# define RB_OBJ_STRING(obj) StringValueCStr(obj) +#endif + +static inline char* memory_address(VALUE self); +VALUE rbffi_AbstractMemoryClass = Qnil; +static VALUE NullPointerErrorClass = Qnil; +static ID id_to_ptr = 0, id_plus = 0, id_call = 0; + +static VALUE +memory_allocate(VALUE klass) +{ + AbstractMemory* memory; + VALUE obj; + obj = Data_Make_Struct(klass, AbstractMemory, NULL, -1, memory); + memory->flags = MEM_RD | MEM_WR; + + return obj; +} +#define VAL(x, swap) (unlikely(((memory->flags & MEM_SWAP) != 0)) ? swap((x)) : (x)) + +#define NUM_OP(name, type, toNative, fromNative, swap) \ +static void memory_op_put_##name(AbstractMemory* memory, long off, VALUE value); \ +static void \ +memory_op_put_##name(AbstractMemory* memory, long off, VALUE value) \ +{ \ + type tmp = (type) VAL(toNative(value), swap); \ + checkWrite(memory); \ + checkBounds(memory, off, sizeof(type)); \ + memcpy(memory->address + off, &tmp, sizeof(tmp)); \ +} \ +static VALUE memory_put_##name(VALUE self, VALUE offset, VALUE value); \ +static VALUE \ +memory_put_##name(VALUE self, VALUE offset, VALUE value) \ +{ \ + AbstractMemory* memory; \ + Data_Get_Struct(self, AbstractMemory, memory); \ + memory_op_put_##name(memory, NUM2LONG(offset), value); \ + return self; \ +} \ +static VALUE memory_write_##name(VALUE self, VALUE value); \ +static VALUE \ +memory_write_##name(VALUE self, VALUE value) \ +{ \ + AbstractMemory* memory; \ + Data_Get_Struct(self, AbstractMemory, memory); \ + memory_op_put_##name(memory, 0, value); \ + return self; \ +} \ +static VALUE memory_op_get_##name(AbstractMemory* memory, long off); \ +static VALUE \ +memory_op_get_##name(AbstractMemory* memory, long off) \ +{ \ + type tmp; \ + checkRead(memory); \ + checkBounds(memory, off, sizeof(type)); \ + memcpy(&tmp, memory->address + off, sizeof(tmp)); \ + return fromNative(VAL(tmp, swap)); \ +} \ +static VALUE memory_get_##name(VALUE self, VALUE offset); \ +static VALUE \ +memory_get_##name(VALUE self, VALUE offset) \ +{ \ + AbstractMemory* memory; \ + Data_Get_Struct(self, AbstractMemory, memory); \ + return memory_op_get_##name(memory, NUM2LONG(offset)); \ +} \ +static VALUE memory_read_##name(VALUE self); \ +static VALUE \ +memory_read_##name(VALUE self) \ +{ \ + AbstractMemory* memory; \ + Data_Get_Struct(self, AbstractMemory, memory); \ + return memory_op_get_##name(memory, 0); \ +} \ +static MemoryOp memory_op_##name = { memory_op_get_##name, memory_op_put_##name }; \ +\ +static VALUE memory_put_array_of_##name(VALUE self, VALUE offset, VALUE ary); \ +static VALUE \ +memory_put_array_of_##name(VALUE self, VALUE offset, VALUE ary) \ +{ \ + long count; \ + long off = NUM2LONG(offset); \ + AbstractMemory* memory = MEMORY(self); \ + long i; \ + Check_Type(ary, T_ARRAY); \ + count = RARRAY_LEN(ary); \ + if (likely(count > 0)) checkWrite(memory); \ + checkBounds(memory, off, count * sizeof(type)); \ + for (i = 0; i < count; i++) { \ + type tmp = (type) VAL(toNative(RARRAY_PTR(ary)[i]), swap); \ + memcpy(memory->address + off + (i * sizeof(type)), &tmp, sizeof(tmp)); \ + } \ + return self; \ +} \ +static VALUE memory_write_array_of_##name(VALUE self, VALUE ary); \ +static VALUE \ +memory_write_array_of_##name(VALUE self, VALUE ary) \ +{ \ + return memory_put_array_of_##name(self, INT2FIX(0), ary); \ +} \ +static VALUE memory_get_array_of_##name(VALUE self, VALUE offset, VALUE length); \ +static VALUE \ +memory_get_array_of_##name(VALUE self, VALUE offset, VALUE length) \ +{ \ + long count = NUM2LONG(length); \ + long off = NUM2LONG(offset); \ + AbstractMemory* memory = MEMORY(self); \ + VALUE retVal = rb_ary_new2(count); \ + long i; \ + if (likely(count > 0)) checkRead(memory); \ + checkBounds(memory, off, count * sizeof(type)); \ + for (i = 0; i < count; ++i) { \ + type tmp; \ + memcpy(&tmp, memory->address + off + (i * sizeof(type)), sizeof(tmp)); \ + rb_ary_push(retVal, fromNative(VAL(tmp, swap))); \ + } \ + return retVal; \ +} \ +static VALUE memory_read_array_of_##name(VALUE self, VALUE length); \ +static VALUE \ +memory_read_array_of_##name(VALUE self, VALUE length) \ +{ \ + return memory_get_array_of_##name(self, INT2FIX(0), length); \ +} + +#define NOSWAP(x) (x) +#define bswap16(x) (((x) >> 8) & 0xff) | (((x) << 8) & 0xff00); +static inline int16_t +SWAPS16(int16_t x) +{ + return bswap16(x); +} + +static inline uint16_t +SWAPU16(uint16_t x) +{ + return bswap16(x); +} + +#if !defined(__GNUC__) || (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 3) +#define bswap32(x) \ + (((x << 24) & 0xff000000) | \ + ((x << 8) & 0x00ff0000) | \ + ((x >> 8) & 0x0000ff00) | \ + ((x >> 24) & 0x000000ff)) + +#define bswap64(x) \ + (((x << 56) & 0xff00000000000000ULL) | \ + ((x << 40) & 0x00ff000000000000ULL) | \ + ((x << 24) & 0x0000ff0000000000ULL) | \ + ((x << 8) & 0x000000ff00000000ULL) | \ + ((x >> 8) & 0x00000000ff000000ULL) | \ + ((x >> 24) & 0x0000000000ff0000ULL) | \ + ((x >> 40) & 0x000000000000ff00ULL) | \ + ((x >> 56) & 0x00000000000000ffULL)) + +static inline int32_t +SWAPS32(int32_t x) +{ + return bswap32(x); +} + +static inline uint32_t +SWAPU32(uint32_t x) +{ + return bswap32(x); +} + +static inline int64_t +SWAPS64(int64_t x) +{ + return bswap64(x); +} + +static inline uint64_t +SWAPU64(uint64_t x) +{ + return bswap64(x); +} + +#else +# define SWAPS32(x) ((int32_t) __builtin_bswap32(x)) +# define SWAPU32(x) ((uint32_t) __builtin_bswap32(x)) +# define SWAPS64(x) ((int64_t) __builtin_bswap64(x)) +# define SWAPU64(x) ((uint64_t) __builtin_bswap64(x)) +#endif + +#if LONG_MAX > INT_MAX +# define SWAPSLONG SWAPS64 +# define SWAPULONG SWAPU64 +#else +# define SWAPSLONG SWAPS32 +# define SWAPULONG SWAPU32 +#endif + +NUM_OP(int8, int8_t, NUM2INT, INT2NUM, NOSWAP); +NUM_OP(uint8, uint8_t, NUM2UINT, UINT2NUM, NOSWAP); +NUM_OP(int16, int16_t, NUM2INT, INT2NUM, SWAPS16); +NUM_OP(uint16, uint16_t, NUM2UINT, UINT2NUM, SWAPU16); +NUM_OP(int32, int32_t, NUM2INT, INT2NUM, SWAPS32); +NUM_OP(uint32, uint32_t, NUM2UINT, UINT2NUM, SWAPU32); +NUM_OP(int64, int64_t, NUM2LL, LL2NUM, SWAPS64); +NUM_OP(uint64, uint64_t, NUM2ULL, ULL2NUM, SWAPU64); +NUM_OP(long, long, NUM2LONG, LONG2NUM, SWAPSLONG); +NUM_OP(ulong, unsigned long, NUM2ULONG, ULONG2NUM, SWAPULONG); +NUM_OP(float32, float, NUM2DBL, rb_float_new, NOSWAP); +NUM_OP(float64, double, NUM2DBL, rb_float_new, NOSWAP); +NUM_OP(longdouble, long double, rbffi_num2longdouble, rbffi_longdouble_new, NOSWAP); + +static inline void* +get_pointer_value(VALUE value) +{ + const int type = TYPE(value); + if (type == T_DATA && rb_obj_is_kind_of(value, rbffi_PointerClass)) { + return memory_address(value); + } else if (type == T_NIL) { + return NULL; + } else if (type == T_FIXNUM) { + return (void *) (uintptr_t) FIX2ULONG(value); + } else if (type == T_BIGNUM) { + return (void *) (uintptr_t) NUM2ULL(value); + } else if (rb_respond_to(value, id_to_ptr)) { + return MEMORY_PTR(rb_funcall2(value, id_to_ptr, 0, NULL)); + } else { + rb_raise(rb_eArgError, "value is not a pointer"); + return NULL; + } +} + +NUM_OP(pointer, void *, get_pointer_value, rbffi_Pointer_NewInstance, NOSWAP); + +static inline uint8_t +rbffi_bool_value(VALUE value) +{ + return RTEST(value); +} + +static inline VALUE +rbffi_bool_new(uint8_t value) +{ + return (value & 1) != 0 ? Qtrue : Qfalse; +} + +NUM_OP(bool, unsigned char, rbffi_bool_value, rbffi_bool_new, NOSWAP); + + +/* + * call-seq: memory.clear + * Set the memory to all-zero. + * @return [self] + */ +static VALUE +memory_clear(VALUE self) +{ + AbstractMemory* ptr = MEMORY(self); + memset(ptr->address, 0, ptr->size); + return self; +} + +/* + * call-seq: memory.size + * Return memory size in bytes (alias: #total) + * @return [Numeric] + */ +static VALUE +memory_size(VALUE self) +{ + AbstractMemory* ptr; + + Data_Get_Struct(self, AbstractMemory, ptr); + + return LONG2NUM(ptr->size); +} + +/* + * call-seq: memory.get(type, offset) + * Return data of given type contained in memory. + * @param [Symbol, Type] type_name type of data to get + * @param [Numeric] offset point in buffer to start from + * @return [Object] + * @raise {ArgumentError} if type is not supported + */ +static VALUE +memory_get(VALUE self, VALUE type_name, VALUE offset) +{ + AbstractMemory* ptr; + VALUE nType; + Type *type; + + nType = rbffi_Type_Lookup(type_name); + if(NIL_P(nType)) goto undefined_type; + + Data_Get_Struct(self, AbstractMemory, ptr); + Data_Get_Struct(nType, Type, type); + + MemoryOp *op = get_memory_op(type); + if(op == NULL) goto undefined_type; + + return op->get(ptr, NUM2LONG(offset)); + +undefined_type: { + VALUE msg = rb_sprintf("undefined type '%" PRIsVALUE "'", type_name); + rb_exc_raise(rb_exc_new3(rb_eArgError, msg)); + return Qnil; + } +} + +/* + * call-seq: memory.put(type, offset, value) + * @param [Symbol, Type] type_name type of data to put + * @param [Numeric] offset point in buffer to start from + * @return [nil] + * @raise {ArgumentError} if type is not supported + */ +static VALUE +memory_put(VALUE self, VALUE type_name, VALUE offset, VALUE value) +{ + AbstractMemory* ptr; + VALUE nType; + Type *type; + + nType = rbffi_Type_Lookup(type_name); + if(NIL_P(nType)) goto undefined_type; + + Data_Get_Struct(self, AbstractMemory, ptr); + Data_Get_Struct(nType, Type, type); + + MemoryOp *op = get_memory_op(type); + if(op == NULL) goto undefined_type; + + op->put(ptr, NUM2LONG(offset), value); + return Qnil; + +undefined_type: { + VALUE msg = rb_sprintf("unsupported type '%" PRIsVALUE "'", type_name); + rb_exc_raise(rb_exc_new3(rb_eArgError, msg)); + return Qnil; + } +} + +/* + * call-seq: memory.get_string(offset, length=nil) + * Return string contained in memory. + * @param [Numeric] offset point in buffer to start from + * @param [Numeric] length string's length in bytes. If nil, a (memory size - offset) length string is returned). + * @return [String] + * @raise {IndexError} if +length+ is too great + * @raise {NullPointerError} if memory not initialized + */ +static VALUE +memory_get_string(int argc, VALUE* argv, VALUE self) +{ + VALUE length = Qnil, offset = Qnil; + AbstractMemory* ptr = MEMORY(self); + long off, len; + char* end; + int nargs = rb_scan_args(argc, argv, "11", &offset, &length); + + off = NUM2LONG(offset); + len = nargs > 1 && length != Qnil ? NUM2LONG(length) : (ptr->size - off); + checkRead(ptr); + checkBounds(ptr, off, len); + + end = memchr(ptr->address + off, 0, len); + return rb_str_new((char *) ptr->address + off, + (end != NULL ? end - ptr->address - off : len)); +} + +/* + * call-seq: memory.get_array_of_string(offset, count=nil) + * Return an array of strings contained in memory. + * @param [Numeric] offset point in memory to start from + * @param [Numeric] count number of strings to get. If nil, return all strings + * @return [Array] + * @raise {IndexError} if +offset+ is too great + * @raise {NullPointerError} if memory not initialized + */ +static VALUE +memory_get_array_of_string(int argc, VALUE* argv, VALUE self) +{ + VALUE offset = Qnil, countnum = Qnil, retVal = Qnil; + AbstractMemory* ptr; + long off; + int count; + + rb_scan_args(argc, argv, "11", &offset, &countnum); + off = NUM2LONG(offset); + count = (countnum == Qnil ? 0 : NUM2INT(countnum)); + retVal = rb_ary_new2(count); + + Data_Get_Struct(self, AbstractMemory, ptr); + checkRead(ptr); + + if (countnum != Qnil) { + int i; + + checkBounds(ptr, off, count * sizeof (char*)); + + for (i = 0; i < count; ++i) { + const char* strptr = *((const char**) (ptr->address + off) + i); + rb_ary_push(retVal, (strptr == NULL ? Qnil : rb_str_new2(strptr))); + } + + } else { + checkBounds(ptr, off, sizeof (char*)); + for ( ; off < ptr->size - (long) sizeof (void *); off += (long) sizeof (void *)) { + const char* strptr = *(const char**) (ptr->address + off); + if (strptr == NULL) { + break; + } + rb_ary_push(retVal, rb_str_new2(strptr)); + } + } + + return retVal; +} + +/* + * call-seq: memory.read_array_of_string(count=nil) + * Return an array of strings contained in memory. Same as: + * memory.get_array_of_string(0, count) + * @param [Numeric] count number of strings to get. If nil, return all strings + * @return [Array] + */ +static VALUE +memory_read_array_of_string(int argc, VALUE* argv, VALUE self) +{ + VALUE* rargv = ALLOCA_N(VALUE, argc + 1); + int i; + + rargv[0] = INT2FIX(0); + for (i = 0; i < argc; i++) { + rargv[i + 1] = argv[i]; + } + + return memory_get_array_of_string(argc + 1, rargv, self); +} + + +/* + * call-seq: memory.put_string(offset, str) + * @param [Numeric] offset + * @param [String] str + * @return [self] + * @raise {SecurityError} when writing unsafe string to memory + * @raise {IndexError} if +offset+ is too great + * @raise {NullPointerError} if memory not initialized + * Put a string in memory. + */ +static VALUE +memory_put_string(VALUE self, VALUE offset, VALUE str) +{ + AbstractMemory* ptr = MEMORY(self); + long off, len; + + Check_Type(str, T_STRING); + off = NUM2LONG(offset); + len = RSTRING_LEN(str); + + checkWrite(ptr); + checkBounds(ptr, off, len + 1); + + memcpy(ptr->address + off, RSTRING_PTR(str), len); + *((char *) ptr->address + off + len) = '\0'; + + return self; +} + +/* + * call-seq: memory.get_bytes(offset, length) + * Return string contained in memory. + * @param [Numeric] offset point in buffer to start from + * @param [Numeric] length string's length in bytes. + * @return [String] + * @raise {IndexError} if +length+ is too great + * @raise {NullPointerError} if memory not initialized + */ +static VALUE +memory_get_bytes(VALUE self, VALUE offset, VALUE length) +{ + AbstractMemory* ptr = MEMORY(self); + long off, len; + + off = NUM2LONG(offset); + len = NUM2LONG(length); + + checkRead(ptr); + checkBounds(ptr, off, len); + + return rb_str_new((char *) ptr->address + off, len); +} + +/* + * call-seq: memory.put_bytes(offset, str, index=0, length=nil) + * Put a string in memory. + * @param [Numeric] offset point in buffer to start from + * @param [String] str string to put to memory + * @param [Numeric] index + * @param [Numeric] length string's length in bytes. If nil, a (memory size - offset) length string is returned). + * @return [self] + * @raise {IndexError} if +length+ is too great + * @raise {NullPointerError} if memory not initialized + * @raise {RangeError} if +index+ is negative, or if index+length is greater than size of string + * @raise {SecurityError} when writing unsafe string to memory + */ +static VALUE +memory_put_bytes(int argc, VALUE* argv, VALUE self) +{ + AbstractMemory* ptr = MEMORY(self); + VALUE offset = Qnil, str = Qnil, rbIndex = Qnil, rbLength = Qnil; + long off, len, idx; + int nargs = rb_scan_args(argc, argv, "22", &offset, &str, &rbIndex, &rbLength); + + Check_Type(str, T_STRING); + + off = NUM2LONG(offset); + idx = nargs > 2 ? NUM2LONG(rbIndex) : 0; + if (idx < 0) { + rb_raise(rb_eRangeError, "index cannot be less than zero"); + return Qnil; + } + len = nargs > 3 ? NUM2LONG(rbLength) : (RSTRING_LEN(str) - idx); + if ((idx + len) > RSTRING_LEN(str)) { + rb_raise(rb_eRangeError, "index+length is greater than size of string"); + return Qnil; + } + + checkWrite(ptr); + checkBounds(ptr, off, len); + + memcpy(ptr->address + off, RSTRING_PTR(str) + idx, len); + + return self; +} + +/* + * call-seq: memory.read_bytes(length) + * @param [Numeric] length of string to return + * @return [String] + * equivalent to : + * memory.get_bytes(0, length) + */ +static VALUE +memory_read_bytes(VALUE self, VALUE length) +{ + return memory_get_bytes(self, INT2FIX(0), length); +} + +/* + * call-seq: memory.write_bytes(str, index=0, length=nil) + * @param [String] str string to put to memory + * @param [Numeric] index + * @param [Numeric] length string's length in bytes. If nil, a (memory size - offset) length string is returned). + * @return [self] + * equivalent to : + * memory.put_bytes(0, str, index, length) + */ +static VALUE +memory_write_bytes(int argc, VALUE* argv, VALUE self) +{ + VALUE* wargv = ALLOCA_N(VALUE, argc + 1); + int i; + + wargv[0] = INT2FIX(0); + for (i = 0; i < argc; i++) { + wargv[i + 1] = argv[i]; + } + + return memory_put_bytes(argc + 1, wargv, self); +} + +/* + * call-seq: memory.type_size + * @return [Numeric] type size in bytes + * Get the memory's type size. + */ +static VALUE +memory_type_size(VALUE self) +{ + AbstractMemory* ptr; + + Data_Get_Struct(self, AbstractMemory, ptr); + + return INT2NUM(ptr->typeSize); +} + +/* + * Document-method: [] + * call-seq: memory[idx] + * @param [Numeric] idx index to access in memory + * @return + * Memory read accessor. + */ +static VALUE +memory_aref(VALUE self, VALUE idx) +{ + AbstractMemory* ptr; + VALUE rbOffset = Qnil; + + Data_Get_Struct(self, AbstractMemory, ptr); + + rbOffset = ULONG2NUM(NUM2ULONG(idx) * ptr->typeSize); + + return rb_funcall2(self, id_plus, 1, &rbOffset); +} + +static inline char* +memory_address(VALUE obj) +{ + return ((AbstractMemory *) DATA_PTR(obj))->address; +} + +static VALUE +memory_copy_from(VALUE self, VALUE rbsrc, VALUE rblen) +{ + AbstractMemory* dst; + + Data_Get_Struct(self, AbstractMemory, dst); + + memcpy(dst->address, rbffi_AbstractMemory_Cast(rbsrc, rbffi_AbstractMemoryClass)->address, NUM2INT(rblen)); + + return self; +} + +AbstractMemory* +rbffi_AbstractMemory_Cast(VALUE obj, VALUE klass) +{ + if (rb_obj_is_kind_of(obj, klass)) { + AbstractMemory* memory; + Data_Get_Struct(obj, AbstractMemory, memory); + return memory; + } + + rb_raise(rb_eArgError, "Invalid Memory object"); + return NULL; +} + +void +rbffi_AbstractMemory_Error(AbstractMemory *mem, int op) +{ + VALUE rbErrorClass = mem->address == NULL ? NullPointerErrorClass : rb_eRuntimeError; + if (op == MEM_RD) { + rb_raise(rbErrorClass, "invalid memory read at address=%p", mem->address); + } else if (op == MEM_WR) { + rb_raise(rbErrorClass, "invalid memory write at address=%p", mem->address); + } else { + rb_raise(rbErrorClass, "invalid memory access at address=%p", mem->address); + } +} + +static VALUE +memory_op_get_strptr(AbstractMemory* ptr, long offset) +{ + void* tmp = NULL; + + if (ptr != NULL && ptr->address != NULL) { + checkRead(ptr); + checkBounds(ptr, offset, sizeof(tmp)); + memcpy(&tmp, ptr->address + offset, sizeof(tmp)); + } + + return tmp != NULL ? rb_str_new2(tmp) : Qnil; +} + +static void +memory_op_put_strptr(AbstractMemory* ptr, long offset, VALUE value) +{ + rb_raise(rb_eArgError, "Cannot set :string fields"); +} + +static MemoryOp memory_op_strptr = { memory_op_get_strptr, memory_op_put_strptr }; + + +MemoryOps rbffi_AbstractMemoryOps = { + &memory_op_int8, /*.int8 */ + &memory_op_uint8, /* .uint8 */ + &memory_op_int16, /* .int16 */ + &memory_op_uint16, /* .uint16 */ + &memory_op_int32, /* .int32 */ + &memory_op_uint32, /* .uint32 */ + &memory_op_int64, /* .int64 */ + &memory_op_uint64, /* .uint64 */ + &memory_op_long, /* .slong */ + &memory_op_ulong, /* .uslong */ + &memory_op_float32, /* .float32 */ + &memory_op_float64, /* .float64 */ + &memory_op_longdouble, /* .longdouble */ + &memory_op_pointer, /* .pointer */ + &memory_op_strptr, /* .strptr */ + &memory_op_bool /* .boolOp */ +}; + +void +rbffi_AbstractMemory_Init(VALUE moduleFFI) +{ + /* + * Document-class: FFI::AbstractMemory + * + * {AbstractMemory} is the base class for many memory management classes such as {Buffer}. + * + * This class has a lot of methods to work with integers : + * * put_intsize(offset, value) + * * get_intsize(offset) + * * put_uintsize(offset, value) + * * get_uintsize(offset) + * * writeuintsize(value) + * * read_intsize + * * write_uintsize(value) + * * read_uintsize + * * put_array_of_intsize(offset, ary) + * * get_array_of_intsize(offset, length) + * * put_array_of_uintsize(offset, ary) + * * get_array_of_uintsize(offset, length) + * * write_array_of_intsize(ary) + * * read_array_of_intsize(length) + * * write_array_of_uintsize(ary) + * * read_array_of_uintsize(length) + * where _size_ is 8, 16, 32 or 64. Same methods exist for long type. + * + * Aliases exist : _char_ for _int8_, _short_ for _int16_, _int_ for _int32_ and long_long for _int64_. + * + * Others methods are listed below. + */ + VALUE classMemory = rb_define_class_under(moduleFFI, "AbstractMemory", rb_cObject); + rbffi_AbstractMemoryClass = classMemory; + /* + * Document-variable: FFI::AbstractMemory + */ + rb_global_variable(&rbffi_AbstractMemoryClass); + rb_define_alloc_func(classMemory, memory_allocate); + + NullPointerErrorClass = rb_define_class_under(moduleFFI, "NullPointerError", rb_eRuntimeError); + /* Document-variable: NullPointerError */ + rb_global_variable(&NullPointerErrorClass); + + +#undef INT +#define INT(type) \ + rb_define_method(classMemory, "put_" #type, memory_put_##type, 2); \ + rb_define_method(classMemory, "get_" #type, memory_get_##type, 1); \ + rb_define_method(classMemory, "put_u" #type, memory_put_u##type, 2); \ + rb_define_method(classMemory, "get_u" #type, memory_get_u##type, 1); \ + rb_define_method(classMemory, "write_" #type, memory_write_##type, 1); \ + rb_define_method(classMemory, "read_" #type, memory_read_##type, 0); \ + rb_define_method(classMemory, "write_u" #type, memory_write_u##type, 1); \ + rb_define_method(classMemory, "read_u" #type, memory_read_u##type, 0); \ + rb_define_method(classMemory, "put_array_of_" #type, memory_put_array_of_##type, 2); \ + rb_define_method(classMemory, "get_array_of_" #type, memory_get_array_of_##type, 2); \ + rb_define_method(classMemory, "put_array_of_u" #type, memory_put_array_of_u##type, 2); \ + rb_define_method(classMemory, "get_array_of_u" #type, memory_get_array_of_u##type, 2); \ + rb_define_method(classMemory, "write_array_of_" #type, memory_write_array_of_##type, 1); \ + rb_define_method(classMemory, "read_array_of_" #type, memory_read_array_of_##type, 1); \ + rb_define_method(classMemory, "write_array_of_u" #type, memory_write_array_of_u##type, 1); \ + rb_define_method(classMemory, "read_array_of_u" #type, memory_read_array_of_u##type, 1); + + INT(int8); + INT(int16); + INT(int32); + INT(int64); + INT(long); + +#define ALIAS(name, old) \ + rb_define_alias(classMemory, "put_" #name, "put_" #old); \ + rb_define_alias(classMemory, "get_" #name, "get_" #old); \ + rb_define_alias(classMemory, "put_u" #name, "put_u" #old); \ + rb_define_alias(classMemory, "get_u" #name, "get_u" #old); \ + rb_define_alias(classMemory, "write_" #name, "write_" #old); \ + rb_define_alias(classMemory, "read_" #name, "read_" #old); \ + rb_define_alias(classMemory, "write_u" #name, "write_u" #old); \ + rb_define_alias(classMemory, "read_u" #name, "read_u" #old); \ + rb_define_alias(classMemory, "put_array_of_" #name, "put_array_of_" #old); \ + rb_define_alias(classMemory, "get_array_of_" #name, "get_array_of_" #old); \ + rb_define_alias(classMemory, "put_array_of_u" #name, "put_array_of_u" #old); \ + rb_define_alias(classMemory, "get_array_of_u" #name, "get_array_of_u" #old); \ + rb_define_alias(classMemory, "write_array_of_" #name, "write_array_of_" #old); \ + rb_define_alias(classMemory, "read_array_of_" #name, "read_array_of_" #old); \ + rb_define_alias(classMemory, "write_array_of_u" #name, "write_array_of_u" #old); \ + rb_define_alias(classMemory, "read_array_of_u" #name, "read_array_of_u" #old); + + ALIAS(char, int8); + ALIAS(short, int16); + ALIAS(int, int32); + ALIAS(long_long, int64); + + /* + * Document-method: put_float32 + * call-seq: memory.put_float32offset, value) + * @param [Numeric] offset + * @param [Numeric] value + * @return [self] + * Put +value+ as a 32-bit float in memory at offset +offset+ (alias: #put_float). + */ + rb_define_method(classMemory, "put_float32", memory_put_float32, 2); + /* + * Document-method: get_float32 + * call-seq: memory.get_float32(offset) + * @param [Numeric] offset + * @return [Float] + * Get a 32-bit float from memory at offset +offset+ (alias: #get_float). + */ + rb_define_method(classMemory, "get_float32", memory_get_float32, 1); + rb_define_alias(classMemory, "put_float", "put_float32"); + rb_define_alias(classMemory, "get_float", "get_float32"); + /* + * Document-method: write_float + * call-seq: memory.write_float(value) + * @param [Numeric] value + * @return [self] + * Write +value+ as a 32-bit float in memory. + * + * Same as: + * memory.put_float(0, value) + */ + rb_define_method(classMemory, "write_float", memory_write_float32, 1); + /* + * Document-method: read_float + * call-seq: memory.read_float + * @return [Float] + * Read a 32-bit float from memory. + * + * Same as: + * memory.get_float(0) + */ + rb_define_method(classMemory, "read_float", memory_read_float32, 0); + /* + * Document-method: put_array_of_float32 + * call-seq: memory.put_array_of_float32(offset, ary) + * @param [Numeric] offset + * @param [Array] ary + * @return [self] + * Put values from +ary+ as 32-bit floats in memory from offset +offset+ (alias: #put_array_of_float). + */ + rb_define_method(classMemory, "put_array_of_float32", memory_put_array_of_float32, 2); + /* + * Document-method: get_array_of_float32 + * call-seq: memory.get_array_of_float32(offset, length) + * @param [Numeric] offset + * @param [Numeric] length number of Float to get + * @return [Array] + * Get 32-bit floats in memory from offset +offset+ (alias: #get_array_of_float). + */ + rb_define_method(classMemory, "get_array_of_float32", memory_get_array_of_float32, 2); + /* + * Document-method: write_array_of_float + * call-seq: memory.write_array_of_float(ary) + * @param [Array] ary + * @return [self] + * Write values from +ary+ as 32-bit floats in memory. + * + * Same as: + * memory.put_array_of_float(0, ary) + */ + rb_define_method(classMemory, "write_array_of_float", memory_write_array_of_float32, 1); + /* + * Document-method: read_array_of_float + * call-seq: memory.read_array_of_float(length) + * @param [Numeric] length number of Float to read + * @return [Array] + * Read 32-bit floats from memory. + * + * Same as: + * memory.get_array_of_float(0, ary) + */ + rb_define_method(classMemory, "read_array_of_float", memory_read_array_of_float32, 1); + rb_define_alias(classMemory, "put_array_of_float", "put_array_of_float32"); + rb_define_alias(classMemory, "get_array_of_float", "get_array_of_float32"); + /* + * Document-method: put_float64 + * call-seq: memory.put_float64(offset, value) + * @param [Numeric] offset + * @param [Numeric] value + * @return [self] + * Put +value+ as a 64-bit float (double) in memory at offset +offset+ (alias: #put_double). + */ + rb_define_method(classMemory, "put_float64", memory_put_float64, 2); + /* + * Document-method: get_float64 + * call-seq: memory.get_float64(offset) + * @param [Numeric] offset + * @return [Float] + * Get a 64-bit float (double) from memory at offset +offset+ (alias: #get_double). + */ + rb_define_method(classMemory, "get_float64", memory_get_float64, 1); + rb_define_alias(classMemory, "put_double", "put_float64"); + rb_define_alias(classMemory, "get_double", "get_float64"); + /* + * Document-method: write_double + * call-seq: memory.write_double(value) + * @param [Numeric] value + * @return [self] + * Write +value+ as a 64-bit float (double) in memory. + * + * Same as: + * memory.put_double(0, value) + */ + rb_define_method(classMemory, "write_double", memory_write_float64, 1); + /* + * Document-method: read_double + * call-seq: memory.read_double + * @return [Float] + * Read a 64-bit float (double) from memory. + * + * Same as: + * memory.get_double(0) + */ + rb_define_method(classMemory, "read_double", memory_read_float64, 0); + /* + * Document-method: put_array_of_float64 + * call-seq: memory.put_array_of_float64(offset, ary) + * @param [Numeric] offset + * @param [Array] ary + * @return [self] + * Put values from +ary+ as 64-bit floats (doubles) in memory from offset +offset+ (alias: #put_array_of_double). + */ + rb_define_method(classMemory, "put_array_of_float64", memory_put_array_of_float64, 2); + /* + * Document-method: get_array_of_float64 + * call-seq: memory.get_array_of_float64(offset, length) + * @param [Numeric] offset + * @param [Numeric] length number of Float to get + * @return [Array] + * Get 64-bit floats (doubles) in memory from offset +offset+ (alias: #get_array_of_double). + */ + rb_define_method(classMemory, "get_array_of_float64", memory_get_array_of_float64, 2); + /* + * Document-method: write_array_of_double + * call-seq: memory.write_array_of_double(ary) + * @param [Array] ary + * @return [self] + * Write values from +ary+ as 64-bit floats (doubles) in memory. + * + * Same as: + * memory.put_array_of_double(0, ary) + */ + rb_define_method(classMemory, "write_array_of_double", memory_write_array_of_float64, 1); + /* + * Document-method: read_array_of_double + * call-seq: memory.read_array_of_double(length) + * @param [Numeric] length number of Float to read + * @return [Array] + * Read 64-bit floats (doubles) from memory. + * + * Same as: + * memory.get_array_of_double(0, ary) + */ + rb_define_method(classMemory, "read_array_of_double", memory_read_array_of_float64, 1); + rb_define_alias(classMemory, "put_array_of_double", "put_array_of_float64"); + rb_define_alias(classMemory, "get_array_of_double", "get_array_of_float64"); + /* + * Document-method: put_pointer + * call-seq: memory.put_pointer(offset, value) + * @param [Numeric] offset + * @param [nil,Pointer, Integer, #to_ptr] value + * @return [self] + * Put +value+ in memory from +offset+.. + */ + rb_define_method(classMemory, "put_pointer", memory_put_pointer, 2); + /* + * Document-method: get_pointer + * call-seq: memory.get_pointer(offset) + * @param [Numeric] offset + * @return [Pointer] + * Get a {Pointer} to the memory from +offset+. + */ + rb_define_method(classMemory, "get_pointer", memory_get_pointer, 1); + /* + * Document-method: write_pointer + * call-seq: memory.write_pointer(value) + * @param [nil,Pointer, Integer, #to_ptr] value + * @return [self] + * Write +value+ in memory. + * + * Equivalent to: + * memory.put_pointer(0, value) + */ + rb_define_method(classMemory, "write_pointer", memory_write_pointer, 1); + /* + * Document-method: read_pointer + * call-seq: memory.read_pointer + * @return [Pointer] + * Get a {Pointer} to the memory from base address. + * + * Equivalent to: + * memory.get_pointer(0) + */ + rb_define_method(classMemory, "read_pointer", memory_read_pointer, 0); + /* + * Document-method: put_array_of_pointer + * call-seq: memory.put_array_of_pointer(offset, ary) + * @param [Numeric] offset + * @param [Array<#to_ptr>] ary + * @return [self] + * Put an array of {Pointer} into memory from +offset+. + */ + rb_define_method(classMemory, "put_array_of_pointer", memory_put_array_of_pointer, 2); + /* + * Document-method: get_array_of_pointer + * call-seq: memory.get_array_of_pointer(offset, length) + * @param [Numeric] offset + * @param [Numeric] length + * @return [Array] + * Get an array of {Pointer} of length +length+ from +offset+. + */ + rb_define_method(classMemory, "get_array_of_pointer", memory_get_array_of_pointer, 2); + /* + * Document-method: write_array_of_pointer + * call-seq: memory.write_array_of_pointer(ary) + * @param [Array<#to_ptr>] ary + * @return [self] + * Write an array of {Pointer} into memory from +offset+. + * + * Same as : + * memory.put_array_of_pointer(0, ary) + */ + rb_define_method(classMemory, "write_array_of_pointer", memory_write_array_of_pointer, 1); + /* + * Document-method: read_array_of_pointer + * call-seq: memory.read_array_of_pointer(length) + * @param [Numeric] length + * @return [Array] + * Read an array of {Pointer} of length +length+. + * + * Same as: + * memory.get_array_of_pointer(0, length) + */ + rb_define_method(classMemory, "read_array_of_pointer", memory_read_array_of_pointer, 1); + + rb_define_method(classMemory, "get_string", memory_get_string, -1); + rb_define_method(classMemory, "put_string", memory_put_string, 2); + rb_define_method(classMemory, "get_bytes", memory_get_bytes, 2); + rb_define_method(classMemory, "put_bytes", memory_put_bytes, -1); + rb_define_method(classMemory, "read_bytes", memory_read_bytes, 1); + rb_define_method(classMemory, "write_bytes", memory_write_bytes, -1); + rb_define_method(classMemory, "get_array_of_string", memory_get_array_of_string, -1); + + rb_define_method(classMemory, "get", memory_get, 2); + rb_define_method(classMemory, "put", memory_put, 3); + + rb_define_method(classMemory, "clear", memory_clear, 0); + rb_define_method(classMemory, "total", memory_size, 0); + rb_define_alias(classMemory, "size", "total"); + rb_define_method(classMemory, "type_size", memory_type_size, 0); + rb_define_method(classMemory, "[]", memory_aref, 1); + rb_define_method(classMemory, "__copy_from__", memory_copy_from, 2); + + id_to_ptr = rb_intern("to_ptr"); + id_call = rb_intern("call"); + id_plus = rb_intern("+"); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/AbstractMemory.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/AbstractMemory.h new file mode 100644 index 0000000..1119288 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/AbstractMemory.h @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_ABSTRACTMEMORY_H +#define RBFFI_ABSTRACTMEMORY_H + +#ifndef _MSC_VER +#include +#endif +#include +#ifndef _MSC_VER +#include +#endif + +#include "compat.h" +#include "Types.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +#define MEM_RD 0x01 +#define MEM_WR 0x02 +#define MEM_CODE 0x04 +#define MEM_SWAP 0x08 +#define MEM_EMBED 0x10 + +typedef struct AbstractMemory_ AbstractMemory; + +typedef struct { + VALUE (*get)(AbstractMemory* ptr, long offset); + void (*put)(AbstractMemory* ptr, long offset, VALUE value); +} MemoryOp; + +typedef struct { + MemoryOp* int8; + MemoryOp* uint8; + MemoryOp* int16; + MemoryOp* uint16; + MemoryOp* int32; + MemoryOp* uint32; + MemoryOp* int64; + MemoryOp* uint64; + MemoryOp* slong; + MemoryOp* uslong; + MemoryOp* float32; + MemoryOp* float64; + MemoryOp* longdouble; + MemoryOp* pointer; + MemoryOp* strptr; + MemoryOp* boolOp; +} MemoryOps; + +struct AbstractMemory_ { + char* address; /* Use char* instead of void* to ensure adding to it works correctly */ + long size; + int flags; + int typeSize; +}; + + +extern VALUE rbffi_AbstractMemoryClass; +extern MemoryOps rbffi_AbstractMemoryOps; + +extern void rbffi_AbstractMemory_Init(VALUE ffiModule); + +extern AbstractMemory* rbffi_AbstractMemory_Cast(VALUE obj, VALUE klass); + +extern void rbffi_AbstractMemory_Error(AbstractMemory *, int op); + +static inline void +checkBounds(AbstractMemory* mem, long off, long len) +{ + if (unlikely((off | len | (off + len) | (mem->size - (off + len))) < 0)) { + rb_raise(rb_eIndexError, "Memory access offset=%ld size=%ld is out of bounds", + off, len); + } +} + +static inline void +checkRead(AbstractMemory* mem) +{ + if (unlikely((mem->flags & MEM_RD) == 0)) { + rbffi_AbstractMemory_Error(mem, MEM_RD); + } +} + +static inline void +checkWrite(AbstractMemory* mem) +{ + if (unlikely((mem->flags & MEM_WR) == 0)) { + rbffi_AbstractMemory_Error(mem, MEM_WR); + } +} + +static inline MemoryOp* +get_memory_op(Type* type) +{ + switch (type->nativeType) { + case NATIVE_INT8: + return rbffi_AbstractMemoryOps.int8; + case NATIVE_UINT8: + return rbffi_AbstractMemoryOps.uint8; + case NATIVE_INT16: + return rbffi_AbstractMemoryOps.int16; + case NATIVE_UINT16: + return rbffi_AbstractMemoryOps.uint16; + case NATIVE_INT32: + return rbffi_AbstractMemoryOps.int32; + case NATIVE_UINT32: + return rbffi_AbstractMemoryOps.uint32; + case NATIVE_INT64: + return rbffi_AbstractMemoryOps.int64; + case NATIVE_UINT64: + return rbffi_AbstractMemoryOps.uint64; + case NATIVE_LONG: + return rbffi_AbstractMemoryOps.slong; + case NATIVE_ULONG: + return rbffi_AbstractMemoryOps.uslong; + case NATIVE_FLOAT32: + return rbffi_AbstractMemoryOps.float32; + case NATIVE_FLOAT64: + return rbffi_AbstractMemoryOps.float64; + case NATIVE_LONGDOUBLE: + return rbffi_AbstractMemoryOps.longdouble; + case NATIVE_POINTER: + return rbffi_AbstractMemoryOps.pointer; + case NATIVE_STRING: + return rbffi_AbstractMemoryOps.strptr; + case NATIVE_BOOL: + return rbffi_AbstractMemoryOps.boolOp; + default: + return NULL; + } +} + +#define MEMORY(obj) rbffi_AbstractMemory_Cast((obj), rbffi_AbstractMemoryClass) +#define MEMORY_PTR(obj) MEMORY((obj))->address +#define MEMORY_LEN(obj) MEMORY((obj))->size + + + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_ABSTRACTMEMORY_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/AbstractMemory.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/AbstractMemory.o new file mode 100644 index 0000000..54ae5fb Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/AbstractMemory.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ArrayType.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ArrayType.c new file mode 100644 index 0000000..bfd666a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ArrayType.c @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include "ArrayType.h" + +static VALUE array_type_s_allocate(VALUE klass); +static VALUE array_type_initialize(VALUE self, VALUE rbComponentType, VALUE rbLength); +static void array_type_mark(ArrayType *); +static void array_type_free(ArrayType *); + +VALUE rbffi_ArrayTypeClass = Qnil; + +static VALUE +array_type_s_allocate(VALUE klass) +{ + ArrayType* array; + VALUE obj; + + obj = Data_Make_Struct(klass, ArrayType, array_type_mark, array_type_free, array); + + array->base.nativeType = NATIVE_ARRAY; + array->base.ffiType = xcalloc(1, sizeof(*array->base.ffiType)); + array->base.ffiType->type = FFI_TYPE_STRUCT; + array->base.ffiType->size = 0; + array->base.ffiType->alignment = 0; + array->rbComponentType = Qnil; + + return obj; +} + +static void +array_type_mark(ArrayType *array) +{ + rb_gc_mark(array->rbComponentType); +} + +static void +array_type_free(ArrayType *array) +{ + xfree(array->base.ffiType); + xfree(array->ffiTypes); + xfree(array); +} + + +/* + * call-seq: initialize(component_type, length) + * @param [Type] component_type + * @param [Numeric] length + * @return [self] + * A new instance of ArrayType. + */ +static VALUE +array_type_initialize(VALUE self, VALUE rbComponentType, VALUE rbLength) +{ + ArrayType* array; + int i; + + Data_Get_Struct(self, ArrayType, array); + + array->length = NUM2UINT(rbLength); + array->rbComponentType = rbComponentType; + Data_Get_Struct(rbComponentType, Type, array->componentType); + + array->ffiTypes = xcalloc(array->length + 1, sizeof(*array->ffiTypes)); + array->base.ffiType->elements = array->ffiTypes; + array->base.ffiType->size = array->componentType->ffiType->size * array->length; + array->base.ffiType->alignment = array->componentType->ffiType->alignment; + + for (i = 0; i < array->length; ++i) { + array->ffiTypes[i] = array->componentType->ffiType; + } + + return self; +} + +/* + * call-seq: length + * @return [Numeric] + * Get array's length + */ +static VALUE +array_type_length(VALUE self) +{ + ArrayType* array; + + Data_Get_Struct(self, ArrayType, array); + + return UINT2NUM(array->length); +} + +/* + * call-seq: element_type + * @return [Type] + * Get element type. + */ +static VALUE +array_type_element_type(VALUE self) +{ + ArrayType* array; + + Data_Get_Struct(self, ArrayType, array); + + return array->rbComponentType; +} + +void +rbffi_ArrayType_Init(VALUE moduleFFI) +{ + VALUE ffi_Type; + + ffi_Type = rbffi_TypeClass; + + /* + * Document-class: FFI::ArrayType < FFI::Type + * + * This is a typed array. The type is a {NativeType native type}. + */ + rbffi_ArrayTypeClass = rb_define_class_under(moduleFFI, "ArrayType", ffi_Type); + /* + * Document-variable: FFI::ArrayType + */ + rb_global_variable(&rbffi_ArrayTypeClass); + /* + * Document-constant: FFI::Type::Array + */ + rb_define_const(ffi_Type, "Array", rbffi_ArrayTypeClass); + + rb_define_alloc_func(rbffi_ArrayTypeClass, array_type_s_allocate); + rb_define_method(rbffi_ArrayTypeClass, "initialize", array_type_initialize, 2); + rb_define_method(rbffi_ArrayTypeClass, "length", array_type_length, 0); + rb_define_method(rbffi_ArrayTypeClass, "elem_type", array_type_element_type, 0); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ArrayType.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ArrayType.h new file mode 100644 index 0000000..356ffb1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ArrayType.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_ARRAYTYPE_H +#define RBFFI_ARRAYTYPE_H + +#include +#include +#include "Type.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct ArrayType_ { + Type base; + int length; + ffi_type** ffiTypes; + Type* componentType; + VALUE rbComponentType; +} ArrayType; + +extern void rbffi_ArrayType_Init(VALUE moduleFFI); +extern VALUE rbffi_ArrayTypeClass; + + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_ARRAYTYPE_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ArrayType.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ArrayType.o new file mode 100644 index 0000000..e8dece2 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ArrayType.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Buffer.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Buffer.c new file mode 100644 index 0000000..b5f39a4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Buffer.c @@ -0,0 +1,360 @@ +/* + * Copyright (c) 2008-2010 Wayne Meissner + * Copyright (C) 2009 Aman Gupta + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include "rbffi.h" +#include "rbffi_endian.h" +#include "AbstractMemory.h" + +#define BUFFER_EMBED_MAXLEN (8) +typedef struct Buffer { + AbstractMemory memory; + + union { + VALUE rbParent; /* link to parent buffer */ + char* storage; /* start of malloc area */ + long embed[BUFFER_EMBED_MAXLEN / sizeof(long)]; /* storage for tiny allocations */ + } data; +} Buffer; + +static VALUE buffer_allocate(VALUE klass); +static VALUE buffer_initialize(int argc, VALUE* argv, VALUE self); +static void buffer_release(Buffer* ptr); +static void buffer_mark(Buffer* ptr); +static VALUE buffer_free(VALUE self); + +static VALUE BufferClass = Qnil; + +static VALUE +buffer_allocate(VALUE klass) +{ + Buffer* buffer; + VALUE obj; + + obj = Data_Make_Struct(klass, Buffer, NULL, buffer_release, buffer); + buffer->data.rbParent = Qnil; + buffer->memory.flags = MEM_RD | MEM_WR; + + return obj; +} + +static void +buffer_release(Buffer* ptr) +{ + if ((ptr->memory.flags & MEM_EMBED) == 0 && ptr->data.storage != NULL) { + xfree(ptr->data.storage); + ptr->data.storage = NULL; + } + + xfree(ptr); +} + +/* + * call-seq: initialize(size, count=1, clear=false) + * @param [Integer, Symbol, #size] Type or size in bytes of a buffer cell + * @param [Fixnum] count number of cell in the Buffer + * @param [Boolean] clear if true, set the buffer to all-zero + * @return [self] + * @raise {NoMemoryError} if failed to allocate memory for Buffer + * A new instance of Buffer. + */ +static VALUE +buffer_initialize(int argc, VALUE* argv, VALUE self) +{ + VALUE rbSize = Qnil, rbCount = Qnil, rbClear = Qnil; + Buffer* p; + int nargs; + + Data_Get_Struct(self, Buffer, p); + + nargs = rb_scan_args(argc, argv, "12", &rbSize, &rbCount, &rbClear); + p->memory.typeSize = rbffi_type_size(rbSize); + p->memory.size = p->memory.typeSize * (nargs > 1 ? NUM2LONG(rbCount) : 1); + + if (p->memory.size > BUFFER_EMBED_MAXLEN) { + p->data.storage = xmalloc(p->memory.size + 7); + if (p->data.storage == NULL) { + rb_raise(rb_eNoMemError, "Failed to allocate memory size=%lu bytes", p->memory.size); + return Qnil; + } + + /* ensure the memory is aligned on at least a 8 byte boundary */ + p->memory.address = (void *) (((uintptr_t) p->data.storage + 0x7) & (uintptr_t) ~0x7ULL); + + if (p->memory.size > 0 && (nargs < 3 || RTEST(rbClear))) { + memset(p->memory.address, 0, p->memory.size); + } + + } else { + p->memory.flags |= MEM_EMBED; + p->memory.address = (void *) &p->data.embed[0]; + } + + if (rb_block_given_p()) { + return rb_ensure(rb_yield, self, buffer_free, self); + } + + return self; +} + +/* + * call-seq: initialize_copy(other) + * @return [self] + * DO NOT CALL THIS METHOD. + */ +static VALUE +buffer_initialize_copy(VALUE self, VALUE other) +{ + AbstractMemory* src; + Buffer* dst; + + Data_Get_Struct(self, Buffer, dst); + src = rbffi_AbstractMemory_Cast(other, BufferClass); + if ((dst->memory.flags & MEM_EMBED) == 0 && dst->data.storage != NULL) { + xfree(dst->data.storage); + } + dst->data.storage = xmalloc(src->size + 7); + if (dst->data.storage == NULL) { + rb_raise(rb_eNoMemError, "failed to allocate memory size=%lu bytes", src->size); + return Qnil; + } + + dst->memory.address = (void *) (((uintptr_t) dst->data.storage + 0x7) & (uintptr_t) ~0x7ULL); + dst->memory.size = src->size; + dst->memory.typeSize = src->typeSize; + + /* finally, copy the actual buffer contents */ + memcpy(dst->memory.address, src->address, src->size); + + return self; +} + +static VALUE +buffer_alloc_inout(int argc, VALUE* argv, VALUE klass) +{ + return buffer_initialize(argc, argv, buffer_allocate(klass)); +} + +static VALUE +slice(VALUE self, long offset, long len) +{ + Buffer* ptr; + Buffer* result; + VALUE obj = Qnil; + + Data_Get_Struct(self, Buffer, ptr); + checkBounds(&ptr->memory, offset, len); + + obj = Data_Make_Struct(BufferClass, Buffer, buffer_mark, -1, result); + result->memory.address = ptr->memory.address + offset; + result->memory.size = len; + result->memory.flags = ptr->memory.flags; + result->memory.typeSize = ptr->memory.typeSize; + result->data.rbParent = self; + + return obj; +} + +/* + * call-seq: + offset + * @param [Numeric] offset + * @return [Buffer] a new instance of Buffer pointing from offset until end of previous buffer. + * Add a Buffer with an offset + */ +static VALUE +buffer_plus(VALUE self, VALUE rbOffset) +{ + Buffer* ptr; + long offset = NUM2LONG(rbOffset); + + Data_Get_Struct(self, Buffer, ptr); + + return slice(self, offset, ptr->memory.size - offset); +} + +/* + * call-seq: slice(offset, length) + * @param [Numeric] offset + * @param [Numeric] length + * @return [Buffer] a new instance of Buffer + * Slice an existing Buffer. + */ +static VALUE +buffer_slice(VALUE self, VALUE rbOffset, VALUE rbLength) +{ + return slice(self, NUM2LONG(rbOffset), NUM2LONG(rbLength)); +} + +/* + * call-seq: inspect + * @return [String] + * Inspect a Buffer. + */ +static VALUE +buffer_inspect(VALUE self) +{ + char tmp[100]; + Buffer* ptr; + + Data_Get_Struct(self, Buffer, ptr); + + snprintf(tmp, sizeof(tmp), "#", ptr, ptr->memory.address, ptr->memory.size); + + return rb_str_new2(tmp); +} + + +#if BYTE_ORDER == LITTLE_ENDIAN +# define SWAPPED_ORDER BIG_ENDIAN +#else +# define SWAPPED_ORDER LITTLE_ENDIAN +#endif + +/* + * Set or get endianness of Buffer. + * @overload order + * @return [:big, :little] + * Get endianness of Buffer. + * @overload order(order) + * @param [:big, :little, :network] order + * @return [self] + * Set endianness of Buffer (+:network+ is an alias for +:big+). + */ +static VALUE +buffer_order(int argc, VALUE* argv, VALUE self) +{ + Buffer* ptr; + + Data_Get_Struct(self, Buffer, ptr); + if (argc == 0) { + int order = (ptr->memory.flags & MEM_SWAP) == 0 ? BYTE_ORDER : SWAPPED_ORDER; + return order == BIG_ENDIAN ? ID2SYM(rb_intern("big")) : ID2SYM(rb_intern("little")); + } else { + VALUE rbOrder = Qnil; + int order = BYTE_ORDER; + + if (rb_scan_args(argc, argv, "1", &rbOrder) < 1) { + rb_raise(rb_eArgError, "need byte order"); + } + if (SYMBOL_P(rbOrder)) { + ID id = SYM2ID(rbOrder); + if (id == rb_intern("little")) { + order = LITTLE_ENDIAN; + + } else if (id == rb_intern("big") || id == rb_intern("network")) { + order = BIG_ENDIAN; + } + } + if (order != BYTE_ORDER) { + Buffer* p2; + VALUE retval = slice(self, 0, ptr->memory.size); + + Data_Get_Struct(retval, Buffer, p2); + p2->memory.flags |= MEM_SWAP; + return retval; + } + + return self; + } +} + +/* Only used to free the buffer if the yield in the initializer throws an exception */ +static VALUE +buffer_free(VALUE self) +{ + Buffer* ptr; + + Data_Get_Struct(self, Buffer, ptr); + if ((ptr->memory.flags & MEM_EMBED) == 0 && ptr->data.storage != NULL) { + xfree(ptr->data.storage); + ptr->data.storage = NULL; + } + + return self; +} + +static void +buffer_mark(Buffer* ptr) +{ + rb_gc_mark(ptr->data.rbParent); +} + +void +rbffi_Buffer_Init(VALUE moduleFFI) +{ + VALUE ffi_AbstractMemory = rbffi_AbstractMemoryClass; + + /* + * Document-class: FFI::Buffer < FFI::AbstractMemory + * + * A Buffer is a function argument type. It should be use with functions playing with C arrays. + */ + BufferClass = rb_define_class_under(moduleFFI, "Buffer", ffi_AbstractMemory); + + /* + * Document-variable: FFI::Buffer + */ + rb_global_variable(&BufferClass); + rb_define_alloc_func(BufferClass, buffer_allocate); + + /* + * Document-method: alloc_inout + * call-seq: alloc_inout(*args) + * Create a new Buffer for in and out arguments (alias : new_inout). + */ + rb_define_singleton_method(BufferClass, "alloc_inout", buffer_alloc_inout, -1); + /* + * Document-method: alloc_out + * call-seq: alloc_out(*args) + * Create a new Buffer for out arguments (alias : new_out). + */ + rb_define_singleton_method(BufferClass, "alloc_out", buffer_alloc_inout, -1); + /* + * Document-method: alloc_in + * call-seq: alloc_in(*args) + * Create a new Buffer for in arguments (alias : new_in). + */ + rb_define_singleton_method(BufferClass, "alloc_in", buffer_alloc_inout, -1); + rb_define_alias(rb_singleton_class(BufferClass), "new_in", "alloc_in"); + rb_define_alias(rb_singleton_class(BufferClass), "new_out", "alloc_out"); + rb_define_alias(rb_singleton_class(BufferClass), "new_inout", "alloc_inout"); + + rb_define_method(BufferClass, "initialize", buffer_initialize, -1); + rb_define_method(BufferClass, "initialize_copy", buffer_initialize_copy, 1); + rb_define_method(BufferClass, "order", buffer_order, -1); + rb_define_method(BufferClass, "inspect", buffer_inspect, 0); + rb_define_alias(BufferClass, "length", "total"); + rb_define_method(BufferClass, "+", buffer_plus, 1); + rb_define_method(BufferClass, "slice", buffer_slice, 2); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Buffer.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Buffer.o new file mode 100644 index 0000000..8a330c0 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Buffer.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Call.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Call.c new file mode 100644 index 0000000..bd6c277 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Call.c @@ -0,0 +1,487 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * Copyright (c) 2009, Luc Heinrich + * Copyright (c) 2009, Mike Dalessio + * Copyright (c) 2009, Aman Gupta. + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MSC_VER +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#if defined(HAVE_NATIVETHREAD) && !defined(_WIN32) +# include +# include +#endif +#include +#include "extconf.h" +#include "rbffi.h" +#include "compat.h" +#include "AbstractMemory.h" +#include "Pointer.h" +#include "Struct.h" +#include "Function.h" +#include "Type.h" +#include "LastError.h" +#include "Call.h" +#include "MappedType.h" +#include "Thread.h" +#include "LongDouble.h" + +#ifdef USE_RAW +# ifndef __i386__ +# error "RAW argument packing only supported on i386" +# endif + +#define INT8_ADJ (4) +#define INT16_ADJ (4) +#define INT32_ADJ (4) +#define INT64_ADJ (8) +#define LONG_ADJ (sizeof(long)) +#define FLOAT32_ADJ (4) +#define FLOAT64_ADJ (8) +#define ADDRESS_ADJ (sizeof(void *)) +#define LONGDOUBLE_ADJ (ffi_type_longdouble.alignment > sizeof(long double) ? ffi_type_longdouble.alignment : sizeof(long double)) + +#endif /* USE_RAW */ + +#ifdef USE_RAW +# define ADJ(p, a) ((p) = (FFIStorage*) (((char *) p) + a##_ADJ)) +#else +# define ADJ(p, a) (++(p)) +#endif + +static void* callback_param(VALUE proc, VALUE cbinfo); +static inline void* getPointer(VALUE value, int type); + +static ID id_to_ptr, id_map_symbol, id_to_native; + +void +rbffi_SetupCallParams(int argc, VALUE* argv, int paramCount, Type** paramTypes, + FFIStorage* paramStorage, void** ffiValues, + VALUE* callbackParameters, int callbackCount, VALUE enums) +{ + VALUE callbackProc = Qnil; + FFIStorage* param = ¶mStorage[0]; + int i, argidx, cbidx, argCount; + + if (unlikely(paramCount != -1 && paramCount != argc)) { + if (argc == (paramCount - 1) && callbackCount == 1 && rb_block_given_p()) { + callbackProc = rb_block_proc(); + } else { + rb_raise(rb_eArgError, "wrong number of arguments (%d for %d)", argc, paramCount); + } + } + + argCount = paramCount != -1 ? paramCount : argc; + + for (i = 0, argidx = 0, cbidx = 0; i < argCount; ++i) { + Type* paramType = paramTypes[i]; + int type; + + + if (unlikely(paramType->nativeType == NATIVE_MAPPED)) { + VALUE values[] = { argv[argidx], Qnil }; + argv[argidx] = rb_funcall2(((MappedType *) paramType)->rbConverter, id_to_native, 2, values); + paramType = ((MappedType *) paramType)->type; + } + + type = argidx < argc ? TYPE(argv[argidx]) : T_NONE; + ffiValues[i] = param; + + switch (paramType->nativeType) { + + case NATIVE_INT8: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + param->s8 = NUM2INT(value); + } else { + param->s8 = NUM2INT(argv[argidx]); + } + + ++argidx; + ADJ(param, INT8); + break; + + case NATIVE_INT16: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + param->s16 = NUM2INT(value); + + } else { + param->s16 = NUM2INT(argv[argidx]); + } + + ++argidx; + ADJ(param, INT16); + break; + + case NATIVE_INT32: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + param->s32 = NUM2INT(value); + + } else { + param->s32 = NUM2INT(argv[argidx]); + } + + ++argidx; + ADJ(param, INT32); + break; + + case NATIVE_BOOL: + if (type != T_TRUE && type != T_FALSE) { + rb_raise(rb_eTypeError, "wrong argument type (expected a boolean parameter)"); + } + param->s8 = argv[argidx++] == Qtrue; + ADJ(param, INT8); + break; + + case NATIVE_UINT8: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + param->u8 = NUM2UINT(value); + } else { + param->u8 = NUM2UINT(argv[argidx]); + } + + ADJ(param, INT8); + ++argidx; + break; + + case NATIVE_UINT16: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + param->u16 = NUM2UINT(value); + } else { + param->u16 = NUM2UINT(argv[argidx]); + } + + ADJ(param, INT16); + ++argidx; + break; + + case NATIVE_UINT32: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + param->u32 = NUM2UINT(value); + } else { + param->u32 = NUM2UINT(argv[argidx]); + } + + ADJ(param, INT32); + ++argidx; + break; + + case NATIVE_INT64: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + param->i64 = NUM2LL(value); + } else { + param->i64 = NUM2LL(argv[argidx]); + } + + ADJ(param, INT64); + ++argidx; + break; + + case NATIVE_UINT64: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + param->u64 = NUM2ULL(value); + } else { + param->u64 = NUM2ULL(argv[argidx]); + } + + ADJ(param, INT64); + ++argidx; + break; + + case NATIVE_LONG: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + *(ffi_sarg *) param = NUM2LONG(value); + } else { + *(ffi_sarg *) param = NUM2LONG(argv[argidx]); + } + + ADJ(param, LONG); + ++argidx; + break; + + case NATIVE_ULONG: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + *(ffi_arg *) param = NUM2ULONG(value); + } else { + *(ffi_arg *) param = NUM2ULONG(argv[argidx]); + } + + ADJ(param, LONG); + ++argidx; + break; + + case NATIVE_FLOAT32: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + param->f32 = (float) NUM2DBL(value); + } else { + param->f32 = (float) NUM2DBL(argv[argidx]); + } + + ADJ(param, FLOAT32); + ++argidx; + break; + + case NATIVE_FLOAT64: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + param->f64 = NUM2DBL(value); + } else { + param->f64 = NUM2DBL(argv[argidx]); + } + + ADJ(param, FLOAT64); + ++argidx; + break; + + case NATIVE_LONGDOUBLE: + if (unlikely(type == T_SYMBOL && enums != Qnil)) { + VALUE value = rb_funcall(enums, id_map_symbol, 1, argv[argidx]); + param->ld = rbffi_num2longdouble(value); + } else { + param->ld = rbffi_num2longdouble(argv[argidx]); + } + + ADJ(param, LONGDOUBLE); + ++argidx; + break; + + + case NATIVE_STRING: + if (type == T_NIL) { + param->ptr = NULL; + + } else { + param->ptr = StringValueCStr(argv[argidx]); + } + + ADJ(param, ADDRESS); + ++argidx; + break; + + case NATIVE_POINTER: + case NATIVE_BUFFER_IN: + case NATIVE_BUFFER_OUT: + case NATIVE_BUFFER_INOUT: + param->ptr = getPointer(argv[argidx++], type); + ADJ(param, ADDRESS); + break; + + + case NATIVE_FUNCTION: + if (callbackProc != Qnil) { + param->ptr = callback_param(callbackProc, callbackParameters[cbidx++]); + } else { + param->ptr = callback_param(argv[argidx], callbackParameters[cbidx++]); + ++argidx; + } + ADJ(param, ADDRESS); + break; + + case NATIVE_STRUCT: + ffiValues[i] = getPointer(argv[argidx++], type); + break; + + default: + rb_raise(rb_eArgError, "Invalid parameter type: %d", paramType->nativeType); + } + } +} + +static void * +call_blocking_function(void* data) +{ + rbffi_blocking_call_t* b = (rbffi_blocking_call_t *) data; + ffi_call(&b->cif, FFI_FN(b->function), b->retval, b->ffiValues); + + return NULL; +} + +VALUE +rbffi_do_blocking_call(VALUE data) +{ + rb_thread_call_without_gvl(call_blocking_function, (void*)data, (rb_unblock_function_t *) -1, NULL); + + return Qnil; +} + +VALUE +rbffi_save_frame_exception(VALUE data, VALUE exc) +{ + rbffi_frame_t* frame = (rbffi_frame_t *) data; + frame->exc = exc; + return Qnil; +} + +VALUE +rbffi_CallFunction(int argc, VALUE* argv, void* function, FunctionType* fnInfo) +{ + void* retval; + void** ffiValues; + FFIStorage* params; + VALUE rbReturnValue; + rbffi_frame_t frame = { 0 }; + + retval = alloca(MAX(fnInfo->ffi_cif.rtype->size, FFI_SIZEOF_ARG)); + + if (unlikely(fnInfo->blocking)) { + rbffi_blocking_call_t* bc; + + /* allocate information passed to the blocking function on the stack */ + ffiValues = ALLOCA_N(void *, fnInfo->parameterCount); + params = ALLOCA_N(FFIStorage, fnInfo->parameterCount); + bc = ALLOCA_N(rbffi_blocking_call_t, 1); + bc->retval = retval; + bc->cif = fnInfo->ffi_cif; + bc->function = function; + bc->ffiValues = ffiValues; + bc->params = params; + bc->frame = &frame; + + rbffi_SetupCallParams(argc, argv, + fnInfo->parameterCount, fnInfo->parameterTypes, params, ffiValues, + fnInfo->callbackParameters, fnInfo->callbackCount, fnInfo->rbEnums); + + rbffi_frame_push(&frame); + rb_rescue2(rbffi_do_blocking_call, (VALUE) bc, rbffi_save_frame_exception, (VALUE) &frame, rb_eException, (VALUE) 0); + rbffi_frame_pop(&frame); + + } else { + + ffiValues = ALLOCA_N(void *, fnInfo->parameterCount); + params = ALLOCA_N(FFIStorage, fnInfo->parameterCount); + + rbffi_SetupCallParams(argc, argv, + fnInfo->parameterCount, fnInfo->parameterTypes, params, ffiValues, + fnInfo->callbackParameters, fnInfo->callbackCount, fnInfo->rbEnums); + + rbffi_frame_push(&frame); + ffi_call(&fnInfo->ffi_cif, FFI_FN(function), retval, ffiValues); + rbffi_frame_pop(&frame); + } + + if (unlikely(!fnInfo->ignoreErrno)) { + rbffi_save_errno(); + } + + if (RTEST(frame.exc) && frame.exc != Qnil) { + rb_exc_raise(frame.exc); + } + + RB_GC_GUARD(rbReturnValue) = rbffi_NativeValue_ToRuby(fnInfo->returnType, fnInfo->rbReturnType, retval); + RB_GC_GUARD(fnInfo->rbReturnType); + + return rbReturnValue; +} + +static inline void* +getPointer(VALUE value, int type) +{ + if (likely(type == T_DATA && rb_obj_is_kind_of(value, rbffi_AbstractMemoryClass))) { + + return ((AbstractMemory *) DATA_PTR(value))->address; + + } else if (type == T_DATA && rb_obj_is_kind_of(value, rbffi_StructClass)) { + + AbstractMemory* memory = ((Struct *) DATA_PTR(value))->pointer; + return memory != NULL ? memory->address : NULL; + + } else if (type == T_STRING) { + + return StringValuePtr(value); + + } else if (type == T_NIL) { + + return NULL; + + } else if (rb_respond_to(value, id_to_ptr)) { + + VALUE ptr = rb_funcall2(value, id_to_ptr, 0, NULL); + if (rb_obj_is_kind_of(ptr, rbffi_AbstractMemoryClass) && TYPE(ptr) == T_DATA) { + return ((AbstractMemory *) DATA_PTR(ptr))->address; + } + rb_raise(rb_eArgError, "to_ptr returned an invalid pointer"); + } + + rb_raise(rb_eArgError, ":pointer argument is not a valid pointer"); + return NULL; +} + +Invoker +rbffi_GetInvoker(FunctionType *fnInfo) +{ + return rbffi_CallFunction; +} + + +static void* +callback_param(VALUE proc, VALUE cbInfo) +{ + VALUE callback ; + if (unlikely(proc == Qnil)) { + return NULL ; + } + + /* Handle Function pointers here */ + if (rb_obj_is_kind_of(proc, rbffi_FunctionClass)) { + AbstractMemory* ptr; + Data_Get_Struct(proc, AbstractMemory, ptr); + return ptr->address; + } + + callback = rbffi_Function_ForProc(cbInfo, proc); + RB_GC_GUARD(callback); + + return ((AbstractMemory *) DATA_PTR(callback))->address; +} + + +void +rbffi_Call_Init(VALUE moduleFFI) +{ + id_to_ptr = rb_intern("to_ptr"); + id_to_native = rb_intern("to_native"); + id_map_symbol = rb_intern("__map_symbol"); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Call.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Call.h new file mode 100644 index 0000000..b892d85 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Call.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * Copyright (c) 2009, Luc Heinrich + * Copyright (c) 2009, Mike Dalessio + * Copyright (c) 2009, Aman Gupta. + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_CALL_H +#define RBFFI_CALL_H + +#include "Thread.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(__i386__) && \ + (defined(HAVE_RAW_API) || defined(USE_INTERNAL_LIBFFI)) && \ + !defined(_WIN32) && !defined(__WIN32__) +# define USE_RAW +#endif + +#if (defined(__i386__) || defined(__x86_64__)) && !(defined(_WIN32) || defined(__WIN32__)) +# define BYPASS_FFI 1 +#endif + +typedef union { +#ifdef USE_RAW + signed int s8, s16, s32; + unsigned int u8, u16, u32; +#else + signed char s8; + unsigned char u8; + signed short s16; + unsigned short u16; + signed int s32; + unsigned int u32; +#endif + signed long long i64; + unsigned long long u64; + signed long sl; + unsigned long ul; + void* ptr; + float f32; + double f64; + long double ld; +} FFIStorage; + +extern void rbffi_Call_Init(VALUE moduleFFI); + +extern void rbffi_SetupCallParams(int argc, VALUE* argv, int paramCount, Type** paramTypes, + FFIStorage* paramStorage, void** ffiValues, + VALUE* callbackParameters, int callbackCount, VALUE enums); + +struct FunctionType_; +extern VALUE rbffi_CallFunction(int argc, VALUE* argv, void* function, struct FunctionType_* fnInfo); + +typedef VALUE (*Invoker)(int argc, VALUE* argv, void* function, struct FunctionType_* fnInfo); + +Invoker rbffi_GetInvoker(struct FunctionType_* fnInfo); + +extern VALUE rbffi_GetEnumValue(VALUE enums, VALUE value); +extern int rbffi_GetSignedIntValue(VALUE value, int type, int minValue, int maxValue, const char* typeName, VALUE enums); + +typedef struct rbffi_blocking_call { + rbffi_frame_t* frame; + void* function; + ffi_cif cif; + void **ffiValues; + void* retval; + void* params; +} rbffi_blocking_call_t; + +VALUE rbffi_do_blocking_call(VALUE data); +VALUE rbffi_save_frame_exception(VALUE data, VALUE exc); + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_CALL_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Call.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Call.o new file mode 100644 index 0000000..b2263d8 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Call.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ClosurePool.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ClosurePool.c new file mode 100644 index 0000000..cfdcf6c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ClosurePool.c @@ -0,0 +1,333 @@ +/* + * Copyright (c) 2009, 2010 Wayne Meissner + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MSC_VER +#include +#endif +#include +#if defined(__CYGWIN__) || !defined(_WIN32) +# include +#endif +#include +#include +#include +#if defined(__CYGWIN__) || !defined(_WIN32) +# include +#else +# include +# define _WINSOCKAPI_ +# include +#endif +#include +#include + +#include +#include "rbffi.h" +#include "compat.h" + +#include "Function.h" +#include "Types.h" +#include "Type.h" +#include "LastError.h" +#include "Call.h" + +#include "ClosurePool.h" + +#ifndef roundup +# define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) +#endif + +typedef struct Memory { + void* code; + void* data; + struct Memory* next; +} Memory; + +struct ClosurePool_ { + void* ctx; + int closureSize; + bool (*prep)(void* ctx, void *code, Closure* closure, char* errbuf, size_t errbufsize); + struct Memory* blocks; /* Keeps track of all the allocated memory for this pool */ + Closure* list; + long refcnt; +}; + +static long pageSize; + +static void* allocatePage(void); +static bool freePage(void *); +static bool protectPage(void *); + +ClosurePool* +rbffi_ClosurePool_New(int closureSize, + bool (*prep)(void* ctx, void *code, Closure* closure, char* errbuf, size_t errbufsize), + void* ctx) +{ + ClosurePool* pool; + + pool = xcalloc(1, sizeof(*pool)); + pool->closureSize = closureSize; + pool->ctx = ctx; + pool->prep = prep; + pool->refcnt = 1; + + return pool; +} + +void +cleanup_closure_pool(ClosurePool* pool) +{ + Memory* memory; + + for (memory = pool->blocks; memory != NULL; ) { + Memory* next = memory->next; +#if !USE_FFI_ALLOC + freePage(memory->code); +#else + ffi_closure_free(memory->code); +#endif + free(memory->data); + free(memory); + memory = next; + } + xfree(pool); +} + +void +rbffi_ClosurePool_Free(ClosurePool* pool) +{ + if (pool != NULL) { + long refcnt = --(pool->refcnt); + if (refcnt == 0) { + cleanup_closure_pool(pool); + } + } +} + +#if !USE_FFI_ALLOC + +Closure* +rbffi_Closure_Alloc(ClosurePool* pool) +{ + Closure *list = NULL; + Memory* block = NULL; + void *code = NULL; + char errmsg[256]; + int nclosures; + long trampolineSize; + int i; + + if (pool->list != NULL) { + Closure* closure = pool->list; + pool->list = pool->list->next; + pool->refcnt++; + + return closure; + } + + trampolineSize = roundup(pool->closureSize, 8); + nclosures = (int) (pageSize / trampolineSize); + block = calloc(1, sizeof(*block)); + list = calloc(nclosures, sizeof(*list)); + code = allocatePage(); + + if (block == NULL || list == NULL || code == NULL) { + snprintf(errmsg, sizeof(errmsg), "failed to allocate a page. errno=%d (%s)", errno, strerror(errno)); + goto error; + } + + for (i = 0; i < nclosures; ++i) { + Closure* closure = &list[i]; + closure->next = &list[i + 1]; + closure->pool = pool; + closure->code = ((char *)code + (i * trampolineSize)); + closure->pcl = closure->code; + + if (!(*pool->prep)(pool->ctx, closure->code, closure, errmsg, sizeof(errmsg))) { + goto error; + } + } + + if (!protectPage(code)) { + goto error; + } + + /* Track the allocated page + Closure memory area */ + block->data = list; + block->code = code; + block->next = pool->blocks; + pool->blocks = block; + + /* Thread the new block onto the free list, apart from the first one. */ + list[nclosures - 1].next = pool->list; + pool->list = list->next; + pool->refcnt++; + + /* Use the first one as the new handle */ + return list; + +error: + free(block); + free(list); + if (code != NULL) { + freePage(code); + } + + + rb_raise(rb_eRuntimeError, "%s", errmsg); + return NULL; +} + +#else + +Closure* +rbffi_Closure_Alloc(ClosurePool* pool) +{ + Closure *closure = NULL; + Memory* block = NULL; + void *code = NULL; + void *pcl = NULL; + char errmsg[256]; + + block = calloc(1, sizeof(*block)); + closure = calloc(1, sizeof(*closure)); + pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + + if (block == NULL || closure == NULL || pcl == NULL) { + snprintf(errmsg, sizeof(errmsg), "failed to allocate a page. errno=%d (%s)", errno, strerror(errno)); + goto error; + } + + closure->pool = pool; + closure->code = code; + closure->pcl = pcl; + + if (!(*pool->prep)(pool->ctx, closure->code, closure, errmsg, sizeof(errmsg))) { + goto error; + } + + /* Track the allocated page + Closure memory area */ + block->data = closure; + block->code = pcl; + pool->blocks = block; + + /* Thread the new block onto the free list, apart from the first one. */ + pool->refcnt++; + + return closure; + +error: + free(block); + free(closure); + if (pcl != NULL) { + ffi_closure_free(pcl); + } + + rb_raise(rb_eRuntimeError, "%s", errmsg); + return NULL; +} + +#endif /* !USE_FFI_ALLOC */ + +void +rbffi_Closure_Free(Closure* closure) +{ + if (closure != NULL) { + ClosurePool* pool = closure->pool; + long refcnt; + /* Just push it on the front of the free list */ + closure->next = pool->list; + pool->list = closure; + refcnt = --(pool->refcnt); + if (refcnt == 0) { + cleanup_closure_pool(pool); + } + } +} + +void* +rbffi_Closure_CodeAddress(Closure* handle) +{ + return handle->code; +} + + +static long +getPageSize() +{ +#if !defined(__CYGWIN__) && (defined(_WIN32) || defined(__WIN32__)) + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwPageSize; +#else + return sysconf(_SC_PAGESIZE); +#endif +} + +#if !USE_FFI_ALLOC + +static void* +allocatePage(void) +{ +#if !defined(__CYGWIN__) && (defined(_WIN32) || defined(__WIN32__)) + return VirtualAlloc(NULL, pageSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); +#else + void *page = mmap(NULL, pageSize, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); + return (page != (void *) -1) ? page : NULL; +#endif +} + +static bool +freePage(void *addr) +{ +#if !defined(__CYGWIN__) && (defined(_WIN32) || defined(__WIN32__)) + return VirtualFree(addr, 0, MEM_RELEASE); +#else + return munmap(addr, pageSize) == 0; +#endif +} + +static bool +protectPage(void* page) +{ +#if !defined(__CYGWIN__) && (defined(_WIN32) || defined(__WIN32__)) + DWORD oldProtect; + return VirtualProtect(page, pageSize, PAGE_EXECUTE_READ, &oldProtect); +#else + return mprotect(page, pageSize, PROT_READ | PROT_EXEC) == 0; +#endif +} + +#endif /* !USE_FFI_ALLOC */ + +void +rbffi_ClosurePool_Init(VALUE module) +{ + pageSize = getPageSize(); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ClosurePool.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ClosurePool.h new file mode 100644 index 0000000..99e3a47 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ClosurePool.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2009, 2010 Wayne Meissner + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RUBYFFI_CLOSUREPOOL_H +#define RUBYFFI_CLOSUREPOOL_H + +typedef struct ClosurePool_ ClosurePool; +typedef struct Closure_ Closure; + +struct Closure_ { + void* info; /* opaque handle for storing closure-instance specific data */ + void* function; /* closure-instance specific function, called by custom trampoline */ + void* code; /* Executable address for the native trampoline code location */ + void* pcl; /* Writeable address for the native trampoline code location */ + + struct ClosurePool_* pool; + Closure* next; +}; + +void rbffi_ClosurePool_Init(VALUE module); + +ClosurePool* rbffi_ClosurePool_New(int closureSize, + bool (*prep)(void* ctx, void *code, Closure* closure, char* errbuf, size_t errbufsize), + void* ctx); + +void rbffi_ClosurePool_Free(ClosurePool *); + +Closure* rbffi_Closure_Alloc(ClosurePool *); +void rbffi_Closure_Free(Closure *); + +void* rbffi_Closure_GetCodeAddress(Closure *); + +#endif /* RUBYFFI_CLOSUREPOOL_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ClosurePool.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ClosurePool.o new file mode 100644 index 0000000..760e940 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ClosurePool.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/DynamicLibrary.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/DynamicLibrary.c new file mode 100644 index 0000000..78b3de6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/DynamicLibrary.c @@ -0,0 +1,334 @@ +/* + * Copyright (c) 2008-2010 Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#if (defined(_WIN32) || defined(__WIN32__)) && !defined(__CYGWIN__) +# include +# define _WINSOCKAPI_ +# include +# include +#else +# include +#endif +#include + +#include + +#include "rbffi.h" +#include "compat.h" +#include "AbstractMemory.h" +#include "Pointer.h" +#include "DynamicLibrary.h" + +typedef struct LibrarySymbol_ { + Pointer base; + VALUE library; + VALUE name; +} LibrarySymbol; + +static VALUE library_initialize(VALUE self, VALUE libname, VALUE libflags); +static void library_free(Library* lib); + + +static VALUE symbol_allocate(VALUE klass); +static VALUE symbol_new(VALUE library, void* address, VALUE name); +static void symbol_mark(LibrarySymbol* sym); + +static VALUE LibraryClass = Qnil, SymbolClass = Qnil; + +#if (defined(_WIN32) || defined(__WIN32__)) && !defined(__CYGWIN__) +static void* dl_open(const char* name, int flags); +static void dl_error(char* buf, int size); +#define dl_sym(handle, name) GetProcAddress(handle, name) +#define dl_close(handle) FreeLibrary(handle) +#else +# define dl_open(name, flags) dlopen(name, flags != 0 ? flags : RTLD_LAZY) +# define dl_error(buf, size) do { snprintf(buf, size, "%s", dlerror()); } while(0) +# define dl_sym(handle, name) dlsym(handle, name) +# define dl_close(handle) dlclose(handle) +#endif + +static VALUE +library_allocate(VALUE klass) +{ + Library* library; + return Data_Make_Struct(klass, Library, NULL, library_free, library); +} + +/* + * call-seq: DynamicLibrary.open(libname, libflags) + * @param libname (see #initialize) + * @param libflags (see #initialize) + * @return [FFI::DynamicLibrary] + * @raise {LoadError} if +libname+ cannot be opened + * Open a library. + */ +static VALUE +library_open(VALUE klass, VALUE libname, VALUE libflags) +{ + return library_initialize(library_allocate(klass), libname, libflags); +} + +/* + * call-seq: initialize(libname, libflags) + * @param [String] libname name of library to open + * @param [Fixnum] libflags flags for library to open + * @return [FFI::DynamicLibrary] + * @raise {LoadError} if +libname+ cannot be opened + * A new DynamicLibrary instance. + */ +static VALUE +library_initialize(VALUE self, VALUE libname, VALUE libflags) +{ + Library* library; + int flags; + + Check_Type(libflags, T_FIXNUM); + + Data_Get_Struct(self, Library, library); + flags = libflags != Qnil ? NUM2UINT(libflags) : 0; + + library->handle = dl_open(libname != Qnil ? StringValueCStr(libname) : NULL, flags); + if (library->handle == NULL) { + char errmsg[1024]; + dl_error(errmsg, sizeof(errmsg)); + rb_raise(rb_eLoadError, "Could not open library '%s': %s", + libname != Qnil ? StringValueCStr(libname) : "[current process]", + errmsg); + } +#ifdef __CYGWIN__ + // On Cygwin 1.7.17 "dlsym(dlopen(0,0), 'getpid')" fails. (dlerror: "No such process") + // As a workaround we can use "dlsym(RTLD_DEFAULT, 'getpid')" instead. + // Since 0 == RTLD_DEFAULT we won't call dl_close later. + if (libname == Qnil) { + dl_close(library->handle); + library->handle = RTLD_DEFAULT; + } +#endif + rb_iv_set(self, "@name", libname != Qnil ? libname : rb_str_new2("[current process]")); + return self; +} + +static VALUE +library_dlsym(VALUE self, VALUE name) +{ + Library* library; + void* address = NULL; + Check_Type(name, T_STRING); + + Data_Get_Struct(self, Library, library); + address = dl_sym(library->handle, StringValueCStr(name)); + + return address != NULL ? symbol_new(self, address, name) : Qnil; +} + +/* + * call-seq: last_error + * @return [String] library's last error string + */ +static VALUE +library_dlerror(VALUE self) +{ + char errmsg[1024]; + dl_error(errmsg, sizeof(errmsg)); + return rb_str_new2(errmsg); +} + +static void +library_free(Library* library) +{ + /* dlclose() on MacOS tends to segfault - avoid it */ +#ifndef __APPLE__ + if (library->handle != NULL) { + dl_close(library->handle); + } +#endif + xfree(library); +} + +#if (defined(_WIN32) || defined(__WIN32__)) && !defined(__CYGWIN__) +static void* +dl_open(const char* name, int flags) +{ + if (name == NULL) { + return GetModuleHandle(NULL); + } else { + DWORD dwFlags = PathIsRelativeA(name) ? 0 : LOAD_WITH_ALTERED_SEARCH_PATH; + return LoadLibraryExA(name, NULL, dwFlags); + } +} + +static void +dl_error(char* buf, int size) +{ + FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), + 0, buf, size, NULL); +} +#endif + +static VALUE +symbol_allocate(VALUE klass) +{ + LibrarySymbol* sym; + VALUE obj = Data_Make_Struct(klass, LibrarySymbol, NULL, -1, sym); + sym->name = Qnil; + sym->library = Qnil; + sym->base.rbParent = Qnil; + + return obj; +} + + +/* + * call-seq: initialize_copy(other) + * @param [Object] other + * @return [nil] + * DO NOT CALL THIS METHOD + */ +static VALUE +symbol_initialize_copy(VALUE self, VALUE other) +{ + rb_raise(rb_eRuntimeError, "cannot duplicate symbol"); + return Qnil; +} + +static VALUE +symbol_new(VALUE library, void* address, VALUE name) +{ + LibrarySymbol* sym; + VALUE obj = Data_Make_Struct(SymbolClass, LibrarySymbol, symbol_mark, -1, sym); + + sym->base.memory.address = address; + sym->base.memory.size = LONG_MAX; + sym->base.memory.typeSize = 1; + sym->base.memory.flags = MEM_RD | MEM_WR; + sym->library = library; + sym->name = name; + + return obj; +} + +static void +symbol_mark(LibrarySymbol* sym) +{ + rb_gc_mark(sym->library); + rb_gc_mark(sym->name); +} + +/* + * call-seq: inspect + * @return [String] + * Inspect. + */ +static VALUE +symbol_inspect(VALUE self) +{ + LibrarySymbol* sym; + char buf[256]; + + Data_Get_Struct(self, LibrarySymbol, sym); + snprintf(buf, sizeof(buf), "#", + StringValueCStr(sym->name), sym->base.memory.address); + return rb_str_new2(buf); +} + +void +rbffi_DynamicLibrary_Init(VALUE moduleFFI) +{ + /* + * Document-class: FFI::DynamicLibrary + */ + LibraryClass = rb_define_class_under(moduleFFI, "DynamicLibrary", rb_cObject); + rb_global_variable(&LibraryClass); + /* + * Document-class: FFI::DynamicLibrary::Symbol < FFI::Pointer + * + * An instance of this class represents a library symbol. It may be a {Pointer pointer} to + * a function or to a variable. + */ + SymbolClass = rb_define_class_under(LibraryClass, "Symbol", rbffi_PointerClass); + rb_global_variable(&SymbolClass); + + /* + * Document-const: FFI::NativeLibrary + * Backward compatibility for FFI::DynamicLibrary + */ + rb_define_const(moduleFFI, "NativeLibrary", LibraryClass); /* backwards compat library */ + rb_define_alloc_func(LibraryClass, library_allocate); + rb_define_singleton_method(LibraryClass, "open", library_open, 2); + rb_define_singleton_method(LibraryClass, "last_error", library_dlerror, 0); + rb_define_method(LibraryClass, "initialize", library_initialize, 2); + /* + * Document-method: find_symbol + * call-seq: find_symbol(name) + * @param [String] name library symbol's name + * @return [FFI::DynamicLibrary::Symbol] library symbol + */ + rb_define_method(LibraryClass, "find_symbol", library_dlsym, 1); + /* + * Document-method: find_function + * call-seq: find_function(name) + * @param [String] name library function's name + * @return [FFI::DynamicLibrary::Symbol] library function symbol + */ + rb_define_method(LibraryClass, "find_function", library_dlsym, 1); + /* + * Document-method: find_variable + * call-seq: find_variable(name) + * @param [String] name library variable's name + * @return [FFI::DynamicLibrary::Symbol] library variable symbol + */ + rb_define_method(LibraryClass, "find_variable", library_dlsym, 1); + rb_define_method(LibraryClass, "last_error", library_dlerror, 0); + rb_define_attr(LibraryClass, "name", 1, 0); + + rb_define_alloc_func(SymbolClass, symbol_allocate); + rb_undef_method(SymbolClass, "new"); + rb_define_method(SymbolClass, "inspect", symbol_inspect, 0); + rb_define_method(SymbolClass, "initialize_copy", symbol_initialize_copy, 1); + +#define DEF(x) rb_define_const(LibraryClass, "RTLD_" #x, UINT2NUM(RTLD_##x)) + DEF(LAZY); + DEF(NOW); + DEF(GLOBAL); + DEF(LOCAL); + DEF(NOLOAD); + DEF(NODELETE); + DEF(FIRST); + DEF(DEEPBIND); + DEF(MEMBER); + DEF(BINDING_MASK); + DEF(LOCATION_MASK); + DEF(ALL_MASK); +#undef DEF + +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/DynamicLibrary.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/DynamicLibrary.h new file mode 100644 index 0000000..97bf7bc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/DynamicLibrary.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2008-2010 Wayne Meissner + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _LIBRARY_H +#define _LIBRARY_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* if these aren't defined (eg. windows), we need sensible defaults */ +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif + +#ifndef RTLD_NOW +#define RTLD_NOW 2 +#endif + +#ifndef RTLD_LOCAL +#define RTLD_LOCAL 4 +#endif + +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 8 +#endif + +/* If these aren't defined, they're not supported so define as 0 */ +#ifndef RTLD_NOLOAD +#define RTLD_NOLOAD 0 +#endif + +#ifndef RTLD_NODELETE +#define RTLD_NODELETE 0 +#endif + +#ifndef RTLD_FIRST +#define RTLD_FIRST 0 +#endif + +#ifndef RTLD_DEEPBIND +#define RTLD_DEEPBIND 0 +#endif + +#ifndef RTLD_MEMBER +#define RTLD_MEMBER 0 +#endif + +/* convenience */ +#ifndef RTLD_BINDING_MASK +#define RTLD_BINDING_MASK (RTLD_LAZY | RTLD_NOW) +#endif + +#ifndef RTLD_LOCATION_MASK +#define RTLD_LOCATION_MASK (RTLD_LOCAL | RTLD_GLOBAL) +#endif + +#ifndef RTLD_ALL_MASK +#define RTLD_ALL_MASK (RTLD_BINDING_MASK | RTLD_LOCATION_MASK | RTLD_NOLOAD | RTLD_NODELETE | RTLD_FIRST | RTLD_DEEPBIND | RTLD_MEMBER) +#endif + +typedef struct Library { + void* handle; +} Library; + +extern void rbffi_DynamicLibrary_Init(VALUE ffiModule); + +#ifdef __cplusplus +} +#endif + +#endif /* _LIBRARY_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/DynamicLibrary.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/DynamicLibrary.o new file mode 100644 index 0000000..710e84c Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/DynamicLibrary.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Function.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Function.c new file mode 100644 index 0000000..1a57591 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Function.c @@ -0,0 +1,917 @@ +/* + * Copyright (c) 2009-2011 Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MSC_VER +#include +#endif +#include +#ifndef _WIN32 +# include +# include +#endif + +#include +#include +#include +#include +#include + +#include +#if defined(HAVE_NATIVETHREAD) && !defined(_WIN32) +#include +#endif +#include + +#include "rbffi.h" +#include "compat.h" + +#include "AbstractMemory.h" +#include "Pointer.h" +#include "Struct.h" +#include "Platform.h" +#include "Type.h" +#include "LastError.h" +#include "Call.h" +#include "ClosurePool.h" +#include "MappedType.h" +#include "Thread.h" +#include "LongDouble.h" +#include "MethodHandle.h" +#include "Function.h" + +typedef struct Function_ { + Pointer base; + FunctionType* info; + MethodHandle* methodHandle; + bool autorelease; + Closure* closure; + VALUE rbProc; + VALUE rbFunctionInfo; +} Function; + +static void function_mark(Function *); +static void function_free(Function *); +static VALUE function_init(VALUE self, VALUE rbFunctionInfo, VALUE rbProc); +static void callback_invoke(ffi_cif* cif, void* retval, void** parameters, void* user_data); +static bool callback_prep(void* ctx, void* code, Closure* closure, char* errmsg, size_t errmsgsize); +static void* callback_with_gvl(void* data); +static VALUE invoke_callback(VALUE data); +static VALUE save_callback_exception(VALUE data, VALUE exc); + +#define DEFER_ASYNC_CALLBACK 1 + + +#if defined(DEFER_ASYNC_CALLBACK) +static VALUE async_cb_event(void *); +static VALUE async_cb_call(void *); +#endif + +extern int ruby_thread_has_gvl_p(void); +extern int ruby_native_thread_p(void); + +VALUE rbffi_FunctionClass = Qnil; + +#if defined(DEFER_ASYNC_CALLBACK) +static VALUE async_cb_thread = Qnil; +#endif + +static ID id_call = 0, id_to_native = 0, id_from_native = 0, id_cbtable = 0, id_cb_ref = 0; + +struct gvl_callback { + Closure* closure; + void* retval; + void** parameters; + bool done; + rbffi_frame_t *frame; +#if defined(DEFER_ASYNC_CALLBACK) + struct gvl_callback* next; +# ifndef _WIN32 + pthread_cond_t async_cond; + pthread_mutex_t async_mutex; +# else + HANDLE async_event; +# endif +#endif +}; + + +#if defined(DEFER_ASYNC_CALLBACK) +static struct gvl_callback* async_cb_list = NULL; +# ifndef _WIN32 + static pthread_mutex_t async_cb_mutex = PTHREAD_MUTEX_INITIALIZER; + static pthread_cond_t async_cb_cond = PTHREAD_COND_INITIALIZER; +# else + static HANDLE async_cb_cond; + static CRITICAL_SECTION async_cb_lock; +# endif +#endif + + +static VALUE +function_allocate(VALUE klass) +{ + Function *fn; + VALUE obj; + + obj = Data_Make_Struct(klass, Function, function_mark, function_free, fn); + + fn->base.memory.flags = MEM_RD; + fn->base.rbParent = Qnil; + fn->rbProc = Qnil; + fn->rbFunctionInfo = Qnil; + fn->autorelease = true; + + return obj; +} + +static void +function_mark(Function *fn) +{ + rb_gc_mark(fn->base.rbParent); + rb_gc_mark(fn->rbProc); + rb_gc_mark(fn->rbFunctionInfo); +} + +static void +function_free(Function *fn) +{ + if (fn->methodHandle != NULL) { + rbffi_MethodHandle_Free(fn->methodHandle); + } + + if (fn->closure != NULL && fn->autorelease) { + rbffi_Closure_Free(fn->closure); + } + + xfree(fn); +} + +/* + * @param [Type, Symbol] return_type return type for the function + * @param [Array] param_types array of parameters types + * @param [Hash] options see {FFI::FunctionType} for available options + * @return [self] + * A new Function instance. + * + * Define a function from a Proc or a block. + * + * @overload initialize(return_type, param_types, options = {}) { |i| ... } + * @yieldparam i parameters for the function + * @overload initialize(return_type, param_types, proc, options = {}) + * @param [Proc] proc + */ +static VALUE +function_initialize(int argc, VALUE* argv, VALUE self) +{ + + VALUE rbReturnType = Qnil, rbParamTypes = Qnil, rbProc = Qnil, rbOptions = Qnil; + VALUE rbFunctionInfo = Qnil; + VALUE infoArgv[3]; + int nargs; + + nargs = rb_scan_args(argc, argv, "22", &rbReturnType, &rbParamTypes, &rbProc, &rbOptions); + + /* + * Callback with block, + * e.g. Function.new(:int, [ :int ]) { |i| blah } + * or Function.new(:int, [ :int ], { :convention => :stdcall }) { |i| blah } + */ + if (rb_block_given_p()) { + if (nargs > 3) { + rb_raise(rb_eArgError, "cannot create function with both proc/address and block"); + } + rbOptions = rbProc; + rbProc = rb_block_proc(); + } else { + /* Callback with proc, or Function with address + * e.g. Function.new(:int, [ :int ], Proc.new { |i| }) + * Function.new(:int, [ :int ], Proc.new { |i| }, { :convention => :stdcall }) + * Function.new(:int, [ :int ], addr) + * Function.new(:int, [ :int ], addr, { :convention => :stdcall }) + */ + } + + infoArgv[0] = rbReturnType; + infoArgv[1] = rbParamTypes; + infoArgv[2] = rbOptions; + rbFunctionInfo = rb_class_new_instance(rbOptions != Qnil ? 3 : 2, infoArgv, rbffi_FunctionTypeClass); + + function_init(self, rbFunctionInfo, rbProc); + + return self; +} + +/* + * call-seq: initialize_copy(other) + * @return [nil] + * DO NOT CALL THIS METHOD + */ +static VALUE +function_initialize_copy(VALUE self, VALUE other) +{ + rb_raise(rb_eRuntimeError, "cannot duplicate function instances"); + return Qnil; +} + +VALUE +rbffi_Function_NewInstance(VALUE rbFunctionInfo, VALUE rbProc) +{ + return function_init(function_allocate(rbffi_FunctionClass), rbFunctionInfo, rbProc); +} + +VALUE +rbffi_Function_ForProc(VALUE rbFunctionInfo, VALUE proc) +{ + VALUE callback, cbref, cbTable; + + cbref = RTEST(rb_ivar_defined(proc, id_cb_ref)) ? rb_ivar_get(proc, id_cb_ref) : Qnil; + /* If the first callback reference has the same function function signature, use it */ + if (cbref != Qnil && CLASS_OF(cbref) == rbffi_FunctionClass) { + Function* fp; + Data_Get_Struct(cbref, Function, fp); + if (fp->rbFunctionInfo == rbFunctionInfo) { + return cbref; + } + } + + cbTable = RTEST(rb_ivar_defined(proc, id_cbtable)) ? rb_ivar_get(proc, id_cbtable) : Qnil; + if (cbTable != Qnil && (callback = rb_hash_aref(cbTable, rbFunctionInfo)) != Qnil) { + return callback; + } + + /* No existing function for the proc with that signature, create a new one and cache it */ + callback = rbffi_Function_NewInstance(rbFunctionInfo, proc); + if (cbref == Qnil) { + /* If there is no other cb already cached for this proc, we can use the ivar slot */ + rb_ivar_set(proc, id_cb_ref, callback); + } else { + /* The proc instance has been used as more than one type of callback, store extras in a hash */ + if(cbTable == Qnil) { + cbTable = rb_hash_new(); + rb_ivar_set(proc, id_cbtable, cbTable); + } + rb_hash_aset(cbTable, rbFunctionInfo, callback); + } + + return callback; +} + +#if !defined(_WIN32) && defined(DEFER_ASYNC_CALLBACK) +static void +after_fork_callback(void) +{ + /* Ensure that a new dispatcher thread is started in a forked process */ + async_cb_thread = Qnil; + pthread_mutex_init(&async_cb_mutex, NULL); + pthread_cond_init(&async_cb_cond, NULL); +} +#endif + +static VALUE +function_init(VALUE self, VALUE rbFunctionInfo, VALUE rbProc) +{ + Function* fn = NULL; + + Data_Get_Struct(self, Function, fn); + + fn->rbFunctionInfo = rbFunctionInfo; + + Data_Get_Struct(fn->rbFunctionInfo, FunctionType, fn->info); + + if (rb_obj_is_kind_of(rbProc, rbffi_PointerClass)) { + Pointer* orig; + Data_Get_Struct(rbProc, Pointer, orig); + fn->base.memory = orig->memory; + fn->base.rbParent = rbProc; + + } else if (rb_obj_is_kind_of(rbProc, rb_cProc) || rb_respond_to(rbProc, id_call)) { + if (fn->info->closurePool == NULL) { + fn->info->closurePool = rbffi_ClosurePool_New(sizeof(ffi_closure), callback_prep, fn->info); + if (fn->info->closurePool == NULL) { + rb_raise(rb_eNoMemError, "failed to create closure pool"); + } + } + +#if defined(DEFER_ASYNC_CALLBACK) + if (async_cb_thread == Qnil) { + +#if !defined(_WIN32) + if( pthread_atfork(NULL, NULL, after_fork_callback) ){ + rb_warn("FFI: unable to register fork callback"); + } +#endif + + async_cb_thread = rb_thread_create(async_cb_event, NULL); + /* Name thread, for better debugging */ + rb_funcall(async_cb_thread, rb_intern("name="), 1, rb_str_new2("FFI Callback Dispatcher")); + } +#endif + + fn->closure = rbffi_Closure_Alloc(fn->info->closurePool); + fn->closure->info = fn; + fn->base.memory.address = fn->closure->code; + fn->base.memory.size = sizeof(*fn->closure); + fn->autorelease = true; + + } else { + rb_raise(rb_eTypeError, "wrong argument type %s, expected pointer or proc", + rb_obj_classname(rbProc)); + } + + fn->rbProc = rbProc; + + return self; +} + +/* + * call-seq: call(*args) + * @param [Array] args function arguments + * @return [FFI::Type] + * Call the function + */ +static VALUE +function_call(int argc, VALUE* argv, VALUE self) +{ + Function* fn; + + Data_Get_Struct(self, Function, fn); + + return (*fn->info->invoke)(argc, argv, fn->base.memory.address, fn->info); +} + +/* + * call-seq: attach(m, name) + * @param [Module] m + * @param [String] name + * @return [self] + * Attach a Function to the Module +m+ as +name+. + */ +static VALUE +function_attach(VALUE self, VALUE module, VALUE name) +{ + Function* fn; + char var[1024]; + + Data_Get_Struct(self, Function, fn); + + if (fn->info->parameterCount == -1) { + rb_raise(rb_eRuntimeError, "cannot attach variadic functions"); + return Qnil; + } + + if (!rb_obj_is_kind_of(module, rb_cModule)) { + rb_raise(rb_eRuntimeError, "trying to attach function to non-module"); + return Qnil; + } + + if (fn->methodHandle == NULL) { + fn->methodHandle = rbffi_MethodHandle_Alloc(fn->info, fn->base.memory.address); + } + + /* + * Stash the Function in a module variable so it does not get garbage collected + */ + snprintf(var, sizeof(var), "@@%s", StringValueCStr(name)); + rb_cv_set(module, var, self); + + rb_define_singleton_method(module, StringValueCStr(name), + rbffi_MethodHandle_CodeAddress(fn->methodHandle), -1); + + + rb_define_method(module, StringValueCStr(name), + rbffi_MethodHandle_CodeAddress(fn->methodHandle), -1); + + return self; +} + +/* + * call-seq: autorelease = autorelease + * @param [Boolean] autorelease + * @return [self] + * Set +autorelease+ attribute (See {Pointer}). + */ +static VALUE +function_set_autorelease(VALUE self, VALUE autorelease) +{ + Function* fn; + + Data_Get_Struct(self, Function, fn); + + fn->autorelease = RTEST(autorelease); + + return self; +} + +static VALUE +function_autorelease_p(VALUE self) +{ + Function* fn; + + Data_Get_Struct(self, Function, fn); + + return fn->autorelease ? Qtrue : Qfalse; +} + +/* + * call-seq: free + * @return [self] + * Free memory allocated by Function. + */ +static VALUE +function_release(VALUE self) +{ + Function* fn; + + Data_Get_Struct(self, Function, fn); + + if (fn->closure == NULL) { + rb_raise(rb_eRuntimeError, "cannot free function which was not allocated"); + } + + rbffi_Closure_Free(fn->closure); + fn->closure = NULL; + + return self; +} + +static void +callback_invoke(ffi_cif* cif, void* retval, void** parameters, void* user_data) +{ + struct gvl_callback cb = { 0 }; + + cb.closure = (Closure *) user_data; + cb.retval = retval; + cb.parameters = parameters; + cb.done = false; + cb.frame = rbffi_frame_current(); + + if (cb.frame != NULL) cb.frame->exc = Qnil; + + if (ruby_native_thread_p()) { + if(ruby_thread_has_gvl_p()) { + callback_with_gvl(&cb); + } else { + rb_thread_call_with_gvl(callback_with_gvl, &cb); + } +#if defined(DEFER_ASYNC_CALLBACK) && !defined(_WIN32) + } else { + bool empty = false; + + pthread_mutex_init(&cb.async_mutex, NULL); + pthread_cond_init(&cb.async_cond, NULL); + + /* Now signal the async callback thread */ + pthread_mutex_lock(&async_cb_mutex); + empty = async_cb_list == NULL; + cb.next = async_cb_list; + async_cb_list = &cb; + + pthread_cond_signal(&async_cb_cond); + pthread_mutex_unlock(&async_cb_mutex); + + /* Wait for the thread executing the ruby callback to signal it is done */ + pthread_mutex_lock(&cb.async_mutex); + while (!cb.done) { + pthread_cond_wait(&cb.async_cond, &cb.async_mutex); + } + pthread_mutex_unlock(&cb.async_mutex); + pthread_cond_destroy(&cb.async_cond); + pthread_mutex_destroy(&cb.async_mutex); + +#elif defined(DEFER_ASYNC_CALLBACK) && defined(_WIN32) + } else { + bool empty = false; + + cb.async_event = CreateEvent(NULL, FALSE, FALSE, NULL); + + /* Now signal the async callback thread */ + EnterCriticalSection(&async_cb_lock); + empty = async_cb_list == NULL; + cb.next = async_cb_list; + async_cb_list = &cb; + LeaveCriticalSection(&async_cb_lock); + + SetEvent(async_cb_cond); + + /* Wait for the thread executing the ruby callback to signal it is done */ + WaitForSingleObject(cb.async_event, INFINITE); + CloseHandle(cb.async_event); +#endif + } +} + +#if defined(DEFER_ASYNC_CALLBACK) +struct async_wait { + void* cb; + bool stop; +}; + +static void * async_cb_wait(void *); +static void async_cb_stop(void *); + +static VALUE +async_cb_event(void* unused) +{ + struct async_wait w = { 0 }; + + w.stop = false; + while (!w.stop) { + rb_thread_call_without_gvl(async_cb_wait, &w, async_cb_stop, &w); + if (w.cb != NULL) { + /* Start up a new ruby thread to run the ruby callback */ + VALUE new_thread = rb_thread_create(async_cb_call, w.cb); + /* Name thread, for better debugging */ + rb_funcall(new_thread, rb_intern("name="), 1, rb_str_new2("FFI Callback Runner")); + } + } + + return Qnil; +} + +#ifdef _WIN32 +static void * +async_cb_wait(void *data) +{ + struct async_wait* w = (struct async_wait *) data; + + w->cb = NULL; + + EnterCriticalSection(&async_cb_lock); + + while (!w->stop && async_cb_list == NULL) { + LeaveCriticalSection(&async_cb_lock); + WaitForSingleObject(async_cb_cond, INFINITE); + EnterCriticalSection(&async_cb_lock); + } + + if (async_cb_list != NULL) { + w->cb = async_cb_list; + async_cb_list = async_cb_list->next; + } + + LeaveCriticalSection(&async_cb_lock); + + return NULL; +} + +static void +async_cb_stop(void *data) +{ + struct async_wait* w = (struct async_wait *) data; + + EnterCriticalSection(&async_cb_lock); + w->stop = true; + LeaveCriticalSection(&async_cb_lock); + SetEvent(async_cb_cond); +} + +#else +static void * +async_cb_wait(void *data) +{ + struct async_wait* w = (struct async_wait *) data; + + w->cb = NULL; + + pthread_mutex_lock(&async_cb_mutex); + + while (!w->stop && async_cb_list == NULL) { + pthread_cond_wait(&async_cb_cond, &async_cb_mutex); + } + + if (async_cb_list != NULL) { + w->cb = async_cb_list; + async_cb_list = async_cb_list->next; + } + + pthread_mutex_unlock(&async_cb_mutex); + + return NULL; +} + +static void +async_cb_stop(void *data) +{ + struct async_wait* w = (struct async_wait *) data; + + pthread_mutex_lock(&async_cb_mutex); + w->stop = true; + pthread_cond_signal(&async_cb_cond); + pthread_mutex_unlock(&async_cb_mutex); +} +#endif + +static VALUE +async_cb_call(void *data) +{ + struct gvl_callback* cb = (struct gvl_callback *) data; + + callback_with_gvl(data); + + /* Signal the original native thread that the ruby code has completed */ +#ifdef _WIN32 + SetEvent(cb->async_event); +#else + pthread_mutex_lock(&cb->async_mutex); + cb->done = true; + pthread_cond_signal(&cb->async_cond); + pthread_mutex_unlock(&cb->async_mutex); +#endif + + return Qnil; +} + +#endif + +static void * +callback_with_gvl(void* data) +{ + rb_rescue2(invoke_callback, (VALUE) data, save_callback_exception, (VALUE) data, rb_eException, (VALUE) 0); + return NULL; +} + +static VALUE +invoke_callback(VALUE data) +{ + struct gvl_callback* cb = (struct gvl_callback *) data; + + Function* fn = (Function *) cb->closure->info; + FunctionType *cbInfo = fn->info; + Type* returnType = cbInfo->returnType; + void* retval = cb->retval; + void** parameters = cb->parameters; + VALUE* rbParams; + VALUE rbReturnType = cbInfo->rbReturnType; + VALUE rbReturnValue; + int i; + + rbParams = ALLOCA_N(VALUE, cbInfo->parameterCount); + for (i = 0; i < cbInfo->parameterCount; ++i) { + VALUE param; + Type* paramType = cbInfo->parameterTypes[i]; + VALUE rbParamType = rb_ary_entry(cbInfo->rbParameterTypes, i); + + if (unlikely(paramType->nativeType == NATIVE_MAPPED)) { + rbParamType = ((MappedType *) paramType)->rbType; + paramType = ((MappedType *) paramType)->type; + } + + switch (paramType->nativeType) { + case NATIVE_INT8: + param = INT2NUM(*(int8_t *) parameters[i]); + break; + case NATIVE_UINT8: + param = UINT2NUM(*(uint8_t *) parameters[i]); + break; + case NATIVE_INT16: + param = INT2NUM(*(int16_t *) parameters[i]); + break; + case NATIVE_UINT16: + param = UINT2NUM(*(uint16_t *) parameters[i]); + break; + case NATIVE_INT32: + param = INT2NUM(*(int32_t *) parameters[i]); + break; + case NATIVE_UINT32: + param = UINT2NUM(*(uint32_t *) parameters[i]); + break; + case NATIVE_INT64: + param = LL2NUM(*(int64_t *) parameters[i]); + break; + case NATIVE_UINT64: + param = ULL2NUM(*(uint64_t *) parameters[i]); + break; + case NATIVE_LONG: + param = LONG2NUM(*(long *) parameters[i]); + break; + case NATIVE_ULONG: + param = ULONG2NUM(*(unsigned long *) parameters[i]); + break; + case NATIVE_FLOAT32: + param = rb_float_new(*(float *) parameters[i]); + break; + case NATIVE_FLOAT64: + param = rb_float_new(*(double *) parameters[i]); + break; + case NATIVE_LONGDOUBLE: + param = rbffi_longdouble_new(*(long double *) parameters[i]); + break; + case NATIVE_STRING: + param = (*(void **) parameters[i] != NULL) ? rb_str_new2(*(char **) parameters[i]) : Qnil; + break; + case NATIVE_POINTER: + param = rbffi_Pointer_NewInstance(*(void **) parameters[i]); + break; + case NATIVE_BOOL: + param = (*(uint8_t *) parameters[i]) ? Qtrue : Qfalse; + break; + + case NATIVE_FUNCTION: + case NATIVE_STRUCT: + param = rbffi_NativeValue_ToRuby(paramType, rbParamType, parameters[i]); + break; + + default: + param = Qnil; + break; + } + + /* Convert the native value into a custom ruby value */ + if (unlikely(cbInfo->parameterTypes[i]->nativeType == NATIVE_MAPPED)) { + VALUE values[] = { param, Qnil }; + param = rb_funcall2(((MappedType *) cbInfo->parameterTypes[i])->rbConverter, id_from_native, 2, values); + } + + rbParams[i] = param; + } + + rbReturnValue = rb_funcall2(fn->rbProc, id_call, cbInfo->parameterCount, rbParams); + + if (unlikely(returnType->nativeType == NATIVE_MAPPED)) { + VALUE values[] = { rbReturnValue, Qnil }; + rbReturnValue = rb_funcall2(((MappedType *) returnType)->rbConverter, id_to_native, 2, values); + rbReturnType = ((MappedType *) returnType)->rbType; + returnType = ((MappedType* ) returnType)->type; + } + + if (rbReturnValue == Qnil || TYPE(rbReturnValue) == T_NIL) { + memset(retval, 0, returnType->ffiType->size); + } else switch (returnType->nativeType) { + case NATIVE_INT8: + case NATIVE_INT16: + case NATIVE_INT32: + *((ffi_sarg *) retval) = NUM2INT(rbReturnValue); + break; + case NATIVE_UINT8: + case NATIVE_UINT16: + case NATIVE_UINT32: + *((ffi_arg *) retval) = NUM2UINT(rbReturnValue); + break; + case NATIVE_INT64: + *((int64_t *) retval) = NUM2LL(rbReturnValue); + break; + case NATIVE_UINT64: + *((uint64_t *) retval) = NUM2ULL(rbReturnValue); + break; + case NATIVE_LONG: + *((ffi_sarg *) retval) = NUM2LONG(rbReturnValue); + break; + case NATIVE_ULONG: + *((ffi_arg *) retval) = NUM2ULONG(rbReturnValue); + break; + case NATIVE_FLOAT32: + *((float *) retval) = (float) NUM2DBL(rbReturnValue); + break; + case NATIVE_FLOAT64: + *((double *) retval) = NUM2DBL(rbReturnValue); + break; + case NATIVE_LONGDOUBLE: + *((long double *) retval) = rbffi_num2longdouble(rbReturnValue); + break; + case NATIVE_POINTER: + if (TYPE(rbReturnValue) == T_DATA && rb_obj_is_kind_of(rbReturnValue, rbffi_PointerClass)) { + *((void **) retval) = ((AbstractMemory *) DATA_PTR(rbReturnValue))->address; + } else { + /* Default to returning NULL if not a value pointer object. handles nil case as well */ + *((void **) retval) = NULL; + } + break; + + case NATIVE_BOOL: + *((ffi_arg *) retval) = rbReturnValue == Qtrue; + break; + + case NATIVE_FUNCTION: + if (TYPE(rbReturnValue) == T_DATA && rb_obj_is_kind_of(rbReturnValue, rbffi_PointerClass)) { + + *((void **) retval) = ((AbstractMemory *) DATA_PTR(rbReturnValue))->address; + + } else if (rb_obj_is_kind_of(rbReturnValue, rb_cProc) || rb_respond_to(rbReturnValue, id_call)) { + VALUE function; + + function = rbffi_Function_ForProc(rbReturnType, rbReturnValue); + + *((void **) retval) = ((AbstractMemory *) DATA_PTR(function))->address; + } else { + *((void **) retval) = NULL; + } + break; + + case NATIVE_STRUCT: + if (TYPE(rbReturnValue) == T_DATA && rb_obj_is_kind_of(rbReturnValue, rbffi_StructClass)) { + AbstractMemory* memory = ((Struct *) DATA_PTR(rbReturnValue))->pointer; + + if (memory->address != NULL) { + memcpy(retval, memory->address, returnType->ffiType->size); + + } else { + memset(retval, 0, returnType->ffiType->size); + } + + } else { + memset(retval, 0, returnType->ffiType->size); + } + break; + + default: + *((ffi_arg *) retval) = 0; + break; + } + + return Qnil; +} + +static VALUE +save_callback_exception(VALUE data, VALUE exc) +{ + struct gvl_callback* cb = (struct gvl_callback *) data; + + memset(cb->retval, 0, ((Function *) cb->closure->info)->info->returnType->ffiType->size); + if (cb->frame != NULL) cb->frame->exc = exc; + + return Qnil; +} + +static bool +callback_prep(void* ctx, void* code, Closure* closure, char* errmsg, size_t errmsgsize) +{ + FunctionType* fnInfo = (FunctionType *) ctx; + ffi_status ffiStatus; + + ffiStatus = ffi_prep_closure_loc(closure->pcl, &fnInfo->ffi_cif, callback_invoke, closure, code); + if (ffiStatus != FFI_OK) { + snprintf(errmsg, errmsgsize, "ffi_prep_closure_loc failed. status=%#x", ffiStatus); + return false; + } + + return true; +} + +void +rbffi_Function_Init(VALUE moduleFFI) +{ + rbffi_FunctionInfo_Init(moduleFFI); + /* + * Document-class: FFI::Function < FFI::Pointer + */ + rbffi_FunctionClass = rb_define_class_under(moduleFFI, "Function", rbffi_PointerClass); + + rb_global_variable(&rbffi_FunctionClass); + rb_define_alloc_func(rbffi_FunctionClass, function_allocate); + + rb_define_method(rbffi_FunctionClass, "initialize", function_initialize, -1); + rb_define_method(rbffi_FunctionClass, "initialize_copy", function_initialize_copy, 1); + rb_define_method(rbffi_FunctionClass, "call", function_call, -1); + rb_define_method(rbffi_FunctionClass, "attach", function_attach, 2); + rb_define_method(rbffi_FunctionClass, "free", function_release, 0); + rb_define_method(rbffi_FunctionClass, "autorelease=", function_set_autorelease, 1); + /* + * call-seq: autorelease + * @return [Boolean] + * Get +autorelease+ attribute. + * Synonymous for {#autorelease?}. + */ + rb_define_method(rbffi_FunctionClass, "autorelease", function_autorelease_p, 0); + /* + * call-seq: autorelease? + * @return [Boolean] +autorelease+ attribute + * Get +autorelease+ attribute. + */ + rb_define_method(rbffi_FunctionClass, "autorelease?", function_autorelease_p, 0); + + id_call = rb_intern("call"); + id_cbtable = rb_intern("@__ffi_callback_table__"); + id_cb_ref = rb_intern("@__ffi_callback__"); + id_to_native = rb_intern("to_native"); + id_from_native = rb_intern("from_native"); +#if defined(_WIN32) + InitializeCriticalSection(&async_cb_lock); + async_cb_cond = CreateEvent(NULL, FALSE, FALSE, NULL); +#endif +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Function.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Function.h new file mode 100644 index 0000000..406b4d8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Function.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_FUNCTION_H +#define RBFFI_FUNCTION_H + +#ifdef __cplusplus +extern "C" { +#endif + +# include + +#include + +typedef struct FunctionType_ FunctionType; + +#include "Type.h" +#include "Call.h" +#include "ClosurePool.h" + +struct FunctionType_ { + Type type; /* The native type of a FunctionInfo object */ + VALUE rbReturnType; + VALUE rbParameterTypes; + + Type* returnType; + Type** parameterTypes; + NativeType* nativeParameterTypes; + ffi_type* ffiReturnType; + ffi_type** ffiParameterTypes; + ffi_cif ffi_cif; + Invoker invoke; + ClosurePool* closurePool; + int parameterCount; + int flags; + ffi_abi abi; + int callbackCount; + VALUE* callbackParameters; + VALUE rbEnums; + bool ignoreErrno; + bool blocking; + bool hasStruct; +}; + +extern VALUE rbffi_FunctionTypeClass, rbffi_FunctionClass; + +void rbffi_Function_Init(VALUE moduleFFI); +VALUE rbffi_Function_NewInstance(VALUE functionInfo, VALUE proc); +VALUE rbffi_Function_ForProc(VALUE cbInfo, VALUE proc); +void rbffi_FunctionInfo_Init(VALUE moduleFFI); + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_FUNCTION_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Function.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Function.o new file mode 100644 index 0000000..c58cb8b Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Function.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/FunctionInfo.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/FunctionInfo.c new file mode 100644 index 0000000..64e9874 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/FunctionInfo.c @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * Copyright (C) 2009 Andrea Fazzi + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MSC_VER +# include +#endif +#include +#include + +#include +#include + +#include +#include + +#include +#include "rbffi.h" +#include "compat.h" + +#include "AbstractMemory.h" +#include "Types.h" +#include "Type.h" +#include "StructByValue.h" +#include "Function.h" + +static VALUE fntype_allocate(VALUE klass); +static VALUE fntype_initialize(int argc, VALUE* argv, VALUE self); +static void fntype_mark(FunctionType*); +static void fntype_free(FunctionType *); + +VALUE rbffi_FunctionTypeClass = Qnil; + +static VALUE +fntype_allocate(VALUE klass) +{ + FunctionType* fnInfo; + VALUE obj = Data_Make_Struct(klass, FunctionType, fntype_mark, fntype_free, fnInfo); + + fnInfo->type.ffiType = &ffi_type_pointer; + fnInfo->type.nativeType = NATIVE_FUNCTION; + fnInfo->rbReturnType = Qnil; + fnInfo->rbParameterTypes = Qnil; + fnInfo->rbEnums = Qnil; + fnInfo->invoke = rbffi_CallFunction; + fnInfo->closurePool = NULL; + + return obj; +} + +static void +fntype_mark(FunctionType* fnInfo) +{ + rb_gc_mark(fnInfo->rbReturnType); + rb_gc_mark(fnInfo->rbParameterTypes); + rb_gc_mark(fnInfo->rbEnums); + if (fnInfo->callbackCount > 0 && fnInfo->callbackParameters != NULL) { + rb_gc_mark_locations(&fnInfo->callbackParameters[0], &fnInfo->callbackParameters[fnInfo->callbackCount]); + } +} + +static void +fntype_free(FunctionType* fnInfo) +{ + xfree(fnInfo->parameterTypes); + xfree(fnInfo->ffiParameterTypes); + xfree(fnInfo->nativeParameterTypes); + xfree(fnInfo->callbackParameters); + if (fnInfo->closurePool != NULL) { + rbffi_ClosurePool_Free(fnInfo->closurePool); + } + xfree(fnInfo); +} + +/* + * call-seq: initialize(return_type, param_types, options={}) + * @param [Type, Symbol] return_type return type for the function + * @param [Array] param_types array of parameters types + * @param [Hash] options + * @option options [Boolean] :blocking set to true if the C function is a blocking call + * @option options [Symbol] :convention calling convention see {FFI::Library#calling_convention} + * @option options [FFI::Enums] :enums + * @return [self] + * A new FunctionType instance. + */ +static VALUE +fntype_initialize(int argc, VALUE* argv, VALUE self) +{ + FunctionType *fnInfo; + ffi_status status; + VALUE rbReturnType = Qnil, rbParamTypes = Qnil, rbOptions = Qnil; + VALUE rbEnums = Qnil, rbConvention = Qnil, rbBlocking = Qnil; +#if defined(X86_WIN32) + VALUE rbConventionStr; +#endif + int i, nargs; + + nargs = rb_scan_args(argc, argv, "21", &rbReturnType, &rbParamTypes, &rbOptions); + if (nargs >= 3 && rbOptions != Qnil) { + rbConvention = rb_hash_aref(rbOptions, ID2SYM(rb_intern("convention"))); + rbEnums = rb_hash_aref(rbOptions, ID2SYM(rb_intern("enums"))); + rbBlocking = rb_hash_aref(rbOptions, ID2SYM(rb_intern("blocking"))); + } + + Check_Type(rbParamTypes, T_ARRAY); + + Data_Get_Struct(self, FunctionType, fnInfo); + fnInfo->parameterCount = (int) RARRAY_LEN(rbParamTypes); + fnInfo->parameterTypes = xcalloc(fnInfo->parameterCount, sizeof(*fnInfo->parameterTypes)); + fnInfo->ffiParameterTypes = xcalloc(fnInfo->parameterCount, sizeof(ffi_type *)); + fnInfo->nativeParameterTypes = xcalloc(fnInfo->parameterCount, sizeof(*fnInfo->nativeParameterTypes)); + fnInfo->rbParameterTypes = rb_ary_new2(fnInfo->parameterCount); + fnInfo->rbEnums = rbEnums; + fnInfo->blocking = RTEST(rbBlocking); + fnInfo->hasStruct = false; + + for (i = 0; i < fnInfo->parameterCount; ++i) { + VALUE entry = rb_ary_entry(rbParamTypes, i); + VALUE type = rbffi_Type_Lookup(entry); + + if (!RTEST(type)) { + VALUE typeName = rb_funcall2(entry, rb_intern("inspect"), 0, NULL); + rb_raise(rb_eTypeError, "Invalid parameter type (%s)", RSTRING_PTR(typeName)); + } + + if (rb_obj_is_kind_of(type, rbffi_FunctionTypeClass)) { + REALLOC_N(fnInfo->callbackParameters, VALUE, fnInfo->callbackCount + 1); + fnInfo->callbackParameters[fnInfo->callbackCount++] = type; + } + + if (rb_obj_is_kind_of(type, rbffi_StructByValueClass)) { + fnInfo->hasStruct = true; + } + + rb_ary_push(fnInfo->rbParameterTypes, type); + Data_Get_Struct(type, Type, fnInfo->parameterTypes[i]); + fnInfo->ffiParameterTypes[i] = fnInfo->parameterTypes[i]->ffiType; + fnInfo->nativeParameterTypes[i] = fnInfo->parameterTypes[i]->nativeType; + } + + fnInfo->rbReturnType = rbffi_Type_Lookup(rbReturnType); + if (!RTEST(fnInfo->rbReturnType)) { + VALUE typeName = rb_funcall2(rbReturnType, rb_intern("inspect"), 0, NULL); + rb_raise(rb_eTypeError, "Invalid return type (%s)", RSTRING_PTR(typeName)); + } + + if (rb_obj_is_kind_of(fnInfo->rbReturnType, rbffi_StructByValueClass)) { + fnInfo->hasStruct = true; + } + + Data_Get_Struct(fnInfo->rbReturnType, Type, fnInfo->returnType); + fnInfo->ffiReturnType = fnInfo->returnType->ffiType; + +#if defined(X86_WIN32) + rbConventionStr = (rbConvention != Qnil) ? rb_funcall2(rbConvention, rb_intern("to_s"), 0, NULL) : Qnil; + fnInfo->abi = (rbConventionStr != Qnil && strcmp(StringValueCStr(rbConventionStr), "stdcall") == 0) + ? FFI_STDCALL : FFI_DEFAULT_ABI; +#else + fnInfo->abi = FFI_DEFAULT_ABI; +#endif + + status = ffi_prep_cif(&fnInfo->ffi_cif, fnInfo->abi, fnInfo->parameterCount, + fnInfo->ffiReturnType, fnInfo->ffiParameterTypes); + switch (status) { + case FFI_BAD_ABI: + rb_raise(rb_eArgError, "Invalid ABI specified"); + case FFI_BAD_TYPEDEF: + rb_raise(rb_eArgError, "Invalid argument type specified"); + case FFI_OK: + break; + default: + rb_raise(rb_eArgError, "Unknown FFI error"); + } + + fnInfo->invoke = rbffi_GetInvoker(fnInfo); + + return self; +} + +/* + * call-seq: result_type + * @return [Type] + * Get the return type of the function type + */ +static VALUE +fntype_result_type(VALUE self) +{ + FunctionType* ft; + + Data_Get_Struct(self, FunctionType, ft); + + return ft->rbReturnType; +} + +/* + * call-seq: param_types + * @return [Array] + * Get parameters types. + */ +static VALUE +fntype_param_types(VALUE self) +{ + FunctionType* ft; + + Data_Get_Struct(self, FunctionType, ft); + + return rb_ary_dup(ft->rbParameterTypes); +} + +void +rbffi_FunctionInfo_Init(VALUE moduleFFI) +{ + VALUE ffi_Type; + + ffi_Type = rbffi_TypeClass; + + /* + * Document-class: FFI::FunctionType < FFI::Type + */ + rbffi_FunctionTypeClass = rb_define_class_under(moduleFFI, "FunctionType",ffi_Type); + rb_global_variable(&rbffi_FunctionTypeClass); + /* + * Document-const: FFI::CallbackInfo = FFI::FunctionType + */ + rb_define_const(moduleFFI, "CallbackInfo", rbffi_FunctionTypeClass); + /* + * Document-const: FFI::FunctionInfo = FFI::FunctionType + */ + rb_define_const(moduleFFI, "FunctionInfo", rbffi_FunctionTypeClass); + /* + * Document-const: FFI::Type::Function = FFI::FunctionType + */ + rb_define_const(ffi_Type, "Function", rbffi_FunctionTypeClass); + + rb_define_alloc_func(rbffi_FunctionTypeClass, fntype_allocate); + rb_define_method(rbffi_FunctionTypeClass, "initialize", fntype_initialize, -1); + rb_define_method(rbffi_FunctionTypeClass, "result_type", fntype_result_type, 0); + rb_define_method(rbffi_FunctionTypeClass, "param_types", fntype_param_types, 0); + +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/FunctionInfo.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/FunctionInfo.o new file mode 100644 index 0000000..78119d4 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/FunctionInfo.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LastError.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LastError.c new file mode 100644 index 0000000..6beecef --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LastError.c @@ -0,0 +1,225 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * Copyright (C) 2009 Aman Gupta + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MSC_VER +# include +#endif +#include +#include +#include +#include +#include +#include + +#include "LastError.h" + +#if defined(HAVE_NATIVETHREAD) && !defined(_WIN32) && !defined(__WIN32__) +# include +# define USE_PTHREAD_LOCAL +#endif + +#if defined(__CYGWIN__) +typedef uint32_t DWORD; +DWORD __stdcall GetLastError(void); +void __stdcall SetLastError(DWORD); +#endif + +typedef struct ThreadData { + int td_errno; +#if defined(_WIN32) || defined(__CYGWIN__) + DWORD td_winapi_errno; +#endif +} ThreadData; + +#if defined(USE_PTHREAD_LOCAL) +static pthread_key_t threadDataKey; +#endif + +static inline ThreadData* thread_data_get(void); + +#if defined(USE_PTHREAD_LOCAL) + +static ThreadData* +thread_data_init(void) +{ + ThreadData* td = xcalloc(1, sizeof(ThreadData)); + + pthread_setspecific(threadDataKey, td); + + return td; +} + + +static inline ThreadData* +thread_data_get(void) +{ + ThreadData* td = pthread_getspecific(threadDataKey); + return td != NULL ? td : thread_data_init(); +} + +static void +thread_data_free(void *ptr) +{ + xfree(ptr); +} + +#else +static ID id_thread_data; + +static ThreadData* +thread_data_init(void) +{ + ThreadData* td; + VALUE obj; + + obj = Data_Make_Struct(rb_cObject, ThreadData, NULL, -1, td); + rb_thread_local_aset(rb_thread_current(), id_thread_data, obj); + + return td; +} + +static inline ThreadData* +thread_data_get() +{ + VALUE obj = rb_thread_local_aref(rb_thread_current(), id_thread_data); + + if (obj != Qnil && TYPE(obj) == T_DATA) { + return (ThreadData *) DATA_PTR(obj); + } + + return thread_data_init(); +} + +#endif + + +/* + * call-seq: error + * @return [Numeric] + * Get +errno+ value. + */ +static VALUE +get_last_error(VALUE self) +{ + return INT2NUM(thread_data_get()->td_errno); +} + +#if defined(_WIN32) || defined(__CYGWIN__) +/* + * call-seq: winapi_error + * @return [Numeric] + * Get +GetLastError()+ value. Only Windows or Cygwin. + */ +static VALUE +get_last_winapi_error(VALUE self) +{ + return INT2NUM(thread_data_get()->td_winapi_errno); +} +#endif + + +/* + * call-seq: error(error) + * @param [Numeric] error + * @return [nil] + * Set +errno+ value. + */ +static VALUE +set_last_error(VALUE self, VALUE error) +{ + +#ifdef _WIN32 + SetLastError(NUM2INT(error)); +#else + errno = NUM2INT(error); +#endif + + return Qnil; +} + +#if defined(_WIN32) || defined(__CYGWIN__) +/* + * call-seq: error(error) + * @param [Numeric] error + * @return [nil] + * Set +GetLastError()+ value. Only on Windows and Cygwin. + */ +static VALUE +set_last_winapi_error(VALUE self, VALUE error) +{ + SetLastError(NUM2INT(error)); + return Qnil; +} +#endif + + +void +rbffi_save_errno(void) +{ + int error = 0; +#ifdef _WIN32 + error = GetLastError(); +#else + error = errno; +#endif + +#if defined(_WIN32) || defined(__CYGWIN__) + DWORD winapi_error = GetLastError(); + thread_data_get()->td_winapi_errno = winapi_error; +#endif + + thread_data_get()->td_errno = error; +} + +void +rbffi_LastError_Init(VALUE moduleFFI) +{ + /* + * Document-module: FFI::LastError + * This module defines a couple of method to set and get +errno+ + * for current thread. + */ + VALUE moduleError = rb_define_module_under(moduleFFI, "LastError"); + + rb_define_module_function(moduleError, "error", get_last_error, 0); + rb_define_module_function(moduleError, "error=", set_last_error, 1); + +#if defined(_WIN32) || defined(__CYGWIN__) + rb_define_module_function(moduleError, "winapi_error", get_last_winapi_error, 0); + rb_define_module_function(moduleError, "winapi_error=", set_last_winapi_error, 1); +#endif + +#if defined(USE_PTHREAD_LOCAL) + pthread_key_create(&threadDataKey, thread_data_free); +#else + id_thread_data = rb_intern("ffi_thread_local_data"); +#endif /* USE_PTHREAD_LOCAL */ +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LastError.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LastError.h new file mode 100644 index 0000000..ee1dfbb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LastError.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_LASTERROR_H +#define RBFFI_LASTERROR_H + +#ifdef __cplusplus +extern "C" { +#endif + + +void rbffi_LastError_Init(VALUE moduleFFI); + +void rbffi_save_errno(void); + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_LASTERROR_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LastError.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LastError.o new file mode 100644 index 0000000..c86d649 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LastError.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LongDouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LongDouble.c new file mode 100644 index 0000000..c95f2fd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LongDouble.c @@ -0,0 +1,65 @@ +#include "LongDouble.h" +#include +#include +#include + +#if defined (__CYGWIN__) || defined(__INTERIX) || defined(_MSC_VER) +# define strtold(str, endptr) ((long double) strtod((str), (endptr))) +#endif /* defined (__CYGWIN__) */ + +static VALUE rb_cBigDecimal = Qnil; +static VALUE bigdecimal_load(VALUE unused); +static VALUE bigdecimal_failed(VALUE value, VALUE exc); + +VALUE +rbffi_longdouble_new(long double ld) +{ + if (!RTEST(rb_cBigDecimal)) { + /* allow fallback if the bigdecimal library is unavailable in future ruby versions */ + rb_cBigDecimal = rb_rescue(bigdecimal_load, Qnil, bigdecimal_failed, rb_cObject); + } + + if (RTEST(rb_cBigDecimal) && rb_cBigDecimal != rb_cObject) { + char buf[128]; + return rb_funcall(rb_mKernel, rb_intern("BigDecimal"), 1, rb_str_new(buf, sprintf(buf, "%.35Le", ld))); + } + + /* Fall through to handling as a float */ + return rb_float_new(ld); +} + +long double +rbffi_num2longdouble(VALUE value) +{ + if (TYPE(value) == T_FLOAT) { + return rb_num2dbl(value); + } + + if (!RTEST(rb_cBigDecimal) && rb_const_defined(rb_cObject, rb_intern("BigDecimal"))) { + rb_cBigDecimal = rb_const_get(rb_cObject, rb_intern("BigDecimal")); + } + + if (RTEST(rb_cBigDecimal) && rb_cBigDecimal != rb_cObject && RTEST(rb_obj_is_kind_of(value, rb_cBigDecimal))) { + VALUE s = rb_funcall(value, rb_intern("to_s"), 1, rb_str_new2("E")); + long double ret = strtold(RSTRING_PTR(s), NULL); + RB_GC_GUARD(s); + return ret; + } + + /* Fall through to handling as a float */ + return rb_num2dbl(value); +} + + +static VALUE +bigdecimal_load(VALUE unused) +{ + rb_require("bigdecimal"); + return rb_const_get(rb_cObject, rb_intern("BigDecimal")); +} + +static VALUE +bigdecimal_failed(VALUE value, VALUE exc) +{ + return value; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LongDouble.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LongDouble.h new file mode 100644 index 0000000..079e890 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LongDouble.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2012, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_LONGDOUBLE_H +#define RBFFI_LONGDOUBLE_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +extern VALUE rbffi_longdouble_new(long double ld); +extern long double rbffi_num2longdouble(VALUE value); + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_LONGDOUBLE_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LongDouble.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LongDouble.o new file mode 100644 index 0000000..596213b Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/LongDouble.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Makefile b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Makefile new file mode 100644 index 0000000..73b7240 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Makefile @@ -0,0 +1,266 @@ + +SHELL = /bin/sh + +# V=0 quiet, V=1 verbose. other values don't work. +V = 0 +Q1 = $(V:1=) +Q = $(Q1:0=@) +ECHO1 = $(V:1=@ :) +ECHO = $(ECHO1:0=@ echo) +NULLCMD = : + +#### Start of system configuration section. #### + +srcdir = . +topdir = /usr/include/ruby-3.0.0 +hdrdir = $(topdir) +arch_hdrdir = /usr/include/ruby-3.0.0/x86_64-linux +PATH_SEPARATOR = : +VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby +prefix = $(DESTDIR)/usr +rubysitearchprefix = $(rubylibprefix)/$(sitearch) +rubyarchprefix = $(rubylibprefix)/$(arch) +rubylibprefix = $(libdir)/$(RUBY_BASE_NAME) +exec_prefix = $(prefix) +vendorarchhdrdir = $(vendorhdrdir)/$(sitearch) +sitearchhdrdir = $(sitehdrdir)/$(sitearch) +rubyarchhdrdir = $(rubyhdrdir)/$(arch) +vendorhdrdir = $(rubyhdrdir)/vendor_ruby +sitehdrdir = $(rubyhdrdir)/site_ruby +rubyhdrdir = $(includedir)/$(RUBY_VERSION_NAME) +vendorarchdir = $(vendorlibdir)/$(sitearch) +vendorlibdir = $(vendordir)/$(ruby_version) +vendordir = $(rubylibprefix)/vendor_ruby +sitearchdir = $(DESTDIR)./.gem.20220424-672384-3l4xqm +sitelibdir = $(DESTDIR)./.gem.20220424-672384-3l4xqm +sitedir = $(rubylibprefix)/site_ruby +rubyarchdir = $(rubylibdir)/$(arch) +rubylibdir = $(rubylibprefix)/$(ruby_version) +sitearchincludedir = $(includedir)/$(sitearch) +archincludedir = $(includedir)/$(arch) +sitearchlibdir = $(libdir)/$(sitearch) +archlibdir = $(libdir)/$(arch) +ridir = $(datarootdir)/$(RI_BASE_NAME) +mandir = $(datarootdir)/man +localedir = $(datarootdir)/locale +libdir = $(exec_prefix)/lib +psdir = $(docdir) +pdfdir = $(docdir) +dvidir = $(docdir) +htmldir = $(docdir) +infodir = $(datarootdir)/info +docdir = $(datarootdir)/doc/$(PACKAGE) +oldincludedir = $(DESTDIR)/usr/include +includedir = $(prefix)/include +runstatedir = $(localstatedir)/run +localstatedir = $(DESTDIR)/var +sharedstatedir = $(DESTDIR)/var/lib +sysconfdir = $(DESTDIR)/etc +datadir = $(datarootdir) +datarootdir = $(prefix)/share +libexecdir = $(DESTDIR)/usr/lib/ruby +sbindir = $(exec_prefix)/sbin +bindir = $(exec_prefix)/bin +archdir = $(rubyarchdir) + + +CC_WRAPPER = +CC = gcc +CXX = g++ +LIBRUBY = $(LIBRUBY_SO) +LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a +LIBRUBYARG_SHARED = -l$(RUBY_SO_NAME) +LIBRUBYARG_STATIC = -l$(RUBY_SO_NAME)-static $(MAINLIBS) +empty = +OUTFLAG = -o $(empty) +COUTFLAG = -o $(empty) +CSRCFLAG = $(empty) + +RUBY_EXTCONF_H = extconf.h +cflags = $(optflags) $(debugflags) $(warnflags) +cxxflags = +optflags = -O3 +debugflags = -ggdb3 +warnflags = +cppflags = +CCDLFLAGS = -fPIC +CFLAGS = $(CCDLFLAGS) -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC $(ARCH_FLAG) +INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir) +DEFS = +CPPFLAGS = -DRUBY_EXTCONF_H=\"$(RUBY_EXTCONF_H)\" $(DEFS) $(cppflags) +CXXFLAGS = $(CCDLFLAGS) -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -Wp,-D_GLIBCXX_ASSERTIONS $(ARCH_FLAG) +ldflags = -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed -pthread +dldflags = -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -Wl,--compress-debug-sections=zlib +ARCH_FLAG = +DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG) +LDSHARED = $(CC) -shared +LDSHAREDXX = $(CXX) -shared +AR = gcc-ar +EXEEXT = + +RUBY_INSTALL_NAME = $(RUBY_BASE_NAME) +RUBY_SO_NAME = ruby +RUBYW_INSTALL_NAME = +RUBY_VERSION_NAME = $(RUBY_BASE_NAME)-$(ruby_version) +RUBYW_BASE_NAME = rubyw +RUBY_BASE_NAME = ruby + +arch = x86_64-linux +sitearch = $(arch) +ruby_version = 3.0.0 +ruby = $(bindir)/$(RUBY_BASE_NAME) +RUBY = $(ruby) +ruby_headers = $(hdrdir)/ruby.h $(hdrdir)/ruby/backward.h $(hdrdir)/ruby/ruby.h $(hdrdir)/ruby/defines.h $(hdrdir)/ruby/missing.h $(hdrdir)/ruby/intern.h $(hdrdir)/ruby/st.h $(hdrdir)/ruby/subst.h $(arch_hdrdir)/ruby/config.h $(RUBY_EXTCONF_H) + +RM = rm -f +RM_RF = $(RUBY) -run -e rm -- -rf +RMDIRS = rmdir --ignore-fail-on-non-empty -p +MAKEDIRS = /usr/bin/mkdir -p +INSTALL = /usr/bin/install -c +INSTALL_PROG = $(INSTALL) -m 0755 +INSTALL_DATA = $(INSTALL) -m 644 +COPY = cp +TOUCH = exit > + +#### End of system configuration section. #### + +preload = +libpath = . $(libdir) +LIBPATH = -L. -L$(libdir) +DEFFILE = + +CLEANFILES = mkmf.log +DISTCLEANFILES = +DISTCLEANDIRS = + +extout = +extout_prefix = +target_prefix = +LOCAL_LIBS = +LIBS = $(LIBRUBYARG_SHARED) -lffi -lffi -lm -lc +ORIG_SRCS = AbstractMemory.c ArrayType.c Buffer.c Call.c ClosurePool.c DynamicLibrary.c Function.c FunctionInfo.c LastError.c LongDouble.c MappedType.c MemoryPointer.c MethodHandle.c Platform.c Pointer.c Struct.c StructByValue.c StructLayout.c Thread.c Type.c Types.c Variadic.c ffi.c +SRCS = $(ORIG_SRCS) +OBJS = AbstractMemory.o ArrayType.o Buffer.o Call.o ClosurePool.o DynamicLibrary.o Function.o FunctionInfo.o LastError.o LongDouble.o MappedType.o MemoryPointer.o MethodHandle.o Platform.o Pointer.o Struct.o StructByValue.o StructLayout.o Thread.o Type.o Types.o Variadic.o ffi.o +HDRS = $(srcdir)/AbstractMemory.h $(srcdir)/ArrayType.h $(srcdir)/Call.h $(srcdir)/ClosurePool.h $(srcdir)/DynamicLibrary.h $(srcdir)/Function.h $(srcdir)/LastError.h $(srcdir)/LongDouble.h $(srcdir)/MappedType.h $(srcdir)/MemoryPointer.h $(srcdir)/MethodHandle.h $(srcdir)/Platform.h $(srcdir)/Pointer.h $(srcdir)/Struct.h $(srcdir)/StructByValue.h $(srcdir)/Thread.h $(srcdir)/Type.h $(srcdir)/Types.h $(srcdir)/compat.h $(srcdir)/extconf.h $(srcdir)/rbffi.h $(srcdir)/rbffi_endian.h +LOCAL_HDRS = +TARGET = ffi_c +TARGET_NAME = ffi_c +TARGET_ENTRY = Init_$(TARGET_NAME) +DLLIB = $(TARGET).so +EXTSTATIC = +STATIC_LIB = + +TIMESTAMP_DIR = . +BINDIR = $(bindir) +RUBYCOMMONDIR = $(sitedir)$(target_prefix) +RUBYLIBDIR = $(sitelibdir)$(target_prefix) +RUBYARCHDIR = $(sitearchdir)$(target_prefix) +HDRDIR = $(sitehdrdir)$(target_prefix) +ARCHHDRDIR = $(sitearchhdrdir)$(target_prefix) +TARGET_SO_DIR = +TARGET_SO = $(TARGET_SO_DIR)$(DLLIB) +CLEANLIBS = $(TARGET_SO) +CLEANOBJS = *.o *.bak + +all: $(DLLIB) +static: $(STATIC_LIB) +.PHONY: all install static install-so install-rb +.PHONY: clean clean-so clean-static clean-rb + +clean-static:: +clean-rb-default:: +clean-rb:: +clean-so:: +clean: clean-so clean-static clean-rb-default clean-rb + -$(Q)$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES) .*.time + +distclean-rb-default:: +distclean-rb:: +distclean-so:: +distclean-static:: +distclean: clean distclean-so distclean-static distclean-rb-default distclean-rb + -$(Q)$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log + -$(Q)$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES) + -$(Q)$(RMDIRS) $(DISTCLEANDIRS) 2> /dev/null || true + +realclean: distclean +install: install-so install-rb + +install-so: $(DLLIB) $(TIMESTAMP_DIR)/.sitearchdir.time + $(INSTALL_PROG) $(DLLIB) $(RUBYARCHDIR) +clean-static:: + -$(Q)$(RM) $(STATIC_LIB) +install-rb: pre-install-rb do-install-rb install-rb-default +install-rb-default: pre-install-rb-default do-install-rb-default +pre-install-rb: Makefile +pre-install-rb-default: Makefile +do-install-rb: +do-install-rb-default: +pre-install-rb-default: + @$(NULLCMD) +$(TIMESTAMP_DIR)/.sitearchdir.time: + $(Q) $(MAKEDIRS) $(@D) $(RUBYARCHDIR) + $(Q) $(TOUCH) $@ + +site-install: site-install-so site-install-rb +site-install-so: install-so +site-install-rb: install-rb + +.SUFFIXES: .c .m .cc .mm .cxx .cpp .o .S + +.cc.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cc.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.mm.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.mm.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.cxx.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cxx.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.cpp.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cpp.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.c.o: + $(ECHO) compiling $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.c.S: + $(ECHO) translating $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.m.o: + $(ECHO) compiling $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.m.S: + $(ECHO) translating $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +$(TARGET_SO): $(OBJS) Makefile + $(ECHO) linking shared-object $(DLLIB) + -$(Q)$(RM) $(@) + $(Q) $(LDSHARED) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS) + + + +$(OBJS): $(HDRS) $(ruby_headers) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MappedType.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MappedType.c new file mode 100644 index 0000000..d1a4189 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MappedType.c @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2010, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include + +#include +#include "rbffi.h" + +#include "Type.h" +#include "MappedType.h" + + +static VALUE mapped_allocate(VALUE); +static VALUE mapped_initialize(VALUE, VALUE); +static void mapped_mark(MappedType *); +static ID id_native_type, id_to_native, id_from_native; + +VALUE rbffi_MappedTypeClass = Qnil; + +static VALUE +mapped_allocate(VALUE klass) +{ + MappedType* m; + + VALUE obj = Data_Make_Struct(klass, MappedType, mapped_mark, -1, m); + + m->rbConverter = Qnil; + m->rbType = Qnil; + m->type = NULL; + m->base.nativeType = NATIVE_MAPPED; + m->base.ffiType = &ffi_type_void; + + return obj; +} + +/* + * call-seq: initialize(converter) + * @param [#native_type, #to_native, #from_native] converter +converter+ must respond to + * all these methods + * @return [self] + */ +static VALUE +mapped_initialize(VALUE self, VALUE rbConverter) +{ + MappedType* m = NULL; + + if (!rb_respond_to(rbConverter, id_native_type)) { + rb_raise(rb_eNoMethodError, "native_type method not implemented"); + } + + if (!rb_respond_to(rbConverter, id_to_native)) { + rb_raise(rb_eNoMethodError, "to_native method not implemented"); + } + + if (!rb_respond_to(rbConverter, id_from_native)) { + rb_raise(rb_eNoMethodError, "from_native method not implemented"); + } + + Data_Get_Struct(self, MappedType, m); + m->rbType = rb_funcall2(rbConverter, id_native_type, 0, NULL); + if (!(rb_obj_is_kind_of(m->rbType, rbffi_TypeClass))) { + rb_raise(rb_eTypeError, "native_type did not return instance of FFI::Type"); + } + + m->rbConverter = rbConverter; + Data_Get_Struct(m->rbType, Type, m->type); + m->base.ffiType = m->type->ffiType; + + return self; +} + +static void +mapped_mark(MappedType* m) +{ + rb_gc_mark(m->rbType); + rb_gc_mark(m->rbConverter); +} + +/* + * call-seq: mapped_type.native_type + * @return [Type] + * Get native type of mapped type. + */ +static VALUE +mapped_native_type(VALUE self) +{ + MappedType*m = NULL; + Data_Get_Struct(self, MappedType, m); + + return m->rbType; +} + +/* + * call-seq: mapped_type.to_native(*args) + * @param args depends on {FFI::DataConverter} used to initialize +self+ + */ +static VALUE +mapped_to_native(int argc, VALUE* argv, VALUE self) +{ + MappedType*m = NULL; + + Data_Get_Struct(self, MappedType, m); + + return rb_funcall2(m->rbConverter, id_to_native, argc, argv); +} + +/* + * call-seq: mapped_type.from_native(*args) + * @param args depends on {FFI::DataConverter} used to initialize +self+ + */ +static VALUE +mapped_from_native(int argc, VALUE* argv, VALUE self) +{ + MappedType*m = NULL; + + Data_Get_Struct(self, MappedType, m); + + return rb_funcall2(m->rbConverter, id_from_native, argc, argv); +} + +void +rbffi_MappedType_Init(VALUE moduleFFI) +{ + /* + * Document-class: FFI::Type::Mapped < FFI::Type + */ + rbffi_MappedTypeClass = rb_define_class_under(rbffi_TypeClass, "Mapped", rbffi_TypeClass); + + rb_global_variable(&rbffi_MappedTypeClass); + + id_native_type = rb_intern("native_type"); + id_to_native = rb_intern("to_native"); + id_from_native = rb_intern("from_native"); + + rb_define_alloc_func(rbffi_MappedTypeClass, mapped_allocate); + rb_define_method(rbffi_MappedTypeClass, "initialize", mapped_initialize, 1); + rb_define_method(rbffi_MappedTypeClass, "type", mapped_native_type, 0); + rb_define_method(rbffi_MappedTypeClass, "native_type", mapped_native_type, 0); + rb_define_method(rbffi_MappedTypeClass, "to_native", mapped_to_native, -1); + rb_define_method(rbffi_MappedTypeClass, "from_native", mapped_from_native, -1); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MappedType.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MappedType.h new file mode 100644 index 0000000..4b26cc1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MappedType.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2010, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_MAPPEDTYPE_H +#define RBFFI_MAPPEDTYPE_H + + +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct MappedType_ { + Type base; + Type* type; + VALUE rbConverter; + VALUE rbType; + +} MappedType; + +void rbffi_MappedType_Init(VALUE moduleFFI); + +extern VALUE rbffi_MappedTypeClass; + + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_MAPPEDTYPE_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MappedType.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MappedType.o new file mode 100644 index 0000000..a821e0d Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MappedType.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MemoryPointer.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MemoryPointer.c new file mode 100644 index 0000000..1a64f2e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MemoryPointer.c @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * Copyright (C) 2009 Luc Heinrich + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include "rbffi.h" +#include "AbstractMemory.h" +#include "Pointer.h" +#include "MemoryPointer.h" + + +static VALUE memptr_allocate(VALUE klass); +static void memptr_release(Pointer* ptr); +static VALUE memptr_malloc(VALUE self, long size, long count, bool clear); +static VALUE memptr_free(VALUE self); + +VALUE rbffi_MemoryPointerClass; + +#define MEMPTR(obj) ((MemoryPointer *) rbffi_AbstractMemory_Cast(obj, rbffi_MemoryPointerClass)) + +VALUE +rbffi_MemoryPointer_NewInstance(long size, long count, bool clear) +{ + return memptr_malloc(memptr_allocate(rbffi_MemoryPointerClass), size, count, clear); +} + +static VALUE +memptr_allocate(VALUE klass) +{ + Pointer* p; + VALUE obj = Data_Make_Struct(klass, Pointer, NULL, memptr_release, p); + p->rbParent = Qnil; + p->memory.flags = MEM_RD | MEM_WR; + + return obj; +} + +/* + * call-seq: initialize(size, count=1, clear=true) + * @param [Fixnum, Bignum, Symbol, FFI::Type] size size of a memory cell (in bytes, or type whom size will be used) + * @param [Numeric] count number of cells in memory + * @param [Boolean] clear set memory to all-zero if +true+ + * @return [self] + * A new instance of FFI::MemoryPointer. + */ +static VALUE +memptr_initialize(int argc, VALUE* argv, VALUE self) +{ + VALUE size = Qnil, count = Qnil, clear = Qnil; + int nargs = rb_scan_args(argc, argv, "12", &size, &count, &clear); + + memptr_malloc(self, rbffi_type_size(size), nargs > 1 ? NUM2LONG(count) : 1, + RTEST(clear) || clear == Qnil); + + if (rb_block_given_p()) { + return rb_ensure(rb_yield, self, memptr_free, self); + } + + return self; +} + +static VALUE +memptr_malloc(VALUE self, long size, long count, bool clear) +{ + Pointer* p; + unsigned long msize; + + Data_Get_Struct(self, Pointer, p); + + msize = size * count; + + p->storage = xmalloc(msize + 7); + if (p->storage == NULL) { + rb_raise(rb_eNoMemError, "Failed to allocate memory size=%ld bytes", msize); + return Qnil; + } + p->autorelease = true; + p->memory.typeSize = (int) size; + p->memory.size = msize; + /* ensure the memory is aligned on at least a 8 byte boundary */ + p->memory.address = (char *) (((uintptr_t) p->storage + 0x7) & (uintptr_t) ~0x7ULL); + p->allocated = true; + + if (clear && p->memory.size > 0) { + memset(p->memory.address, 0, p->memory.size); + } + + return self; +} + +static VALUE +memptr_free(VALUE self) +{ + Pointer* ptr; + + Data_Get_Struct(self, Pointer, ptr); + + if (ptr->allocated) { + if (ptr->storage != NULL) { + xfree(ptr->storage); + ptr->storage = NULL; + } + ptr->allocated = false; + } + + return self; +} + +static void +memptr_release(Pointer* ptr) +{ + if (ptr->autorelease && ptr->allocated && ptr->storage != NULL) { + xfree(ptr->storage); + ptr->storage = NULL; + } + xfree(ptr); +} + +/* + * call-seq: from_string(s) + * @param [String] s string + * @return [MemoryPointer] + * Create a {MemoryPointer} with +s+ inside. + */ +static VALUE +memptr_s_from_string(VALUE klass, VALUE to_str) +{ + VALUE s = StringValue(to_str); + VALUE args[] = { INT2FIX(1), LONG2NUM(RSTRING_LEN(s) + 1), Qfalse }; + VALUE obj = rb_class_new_instance(3, args, klass); + rb_funcall(obj, rb_intern("put_string"), 2, INT2FIX(0), s); + + return obj; +} + +void +rbffi_MemoryPointer_Init(VALUE moduleFFI) +{ + VALUE ffi_Pointer; + + ffi_Pointer = rbffi_PointerClass; + + /* + * Document-class: FFI::MemoryPointer < FFI::Pointer + * A MemoryPointer is a specific {Pointer}. It points to a memory composed of cells. All cells have the + * same size. + * + * @example Create a new MemoryPointer + * mp = FFI::MemoryPointer.new(:long, 16) # Create a pointer on a memory of 16 long ints. + * @example Create a new MemoryPointer from a String + * mp1 = FFI::MemoryPointer.from_string("this is a string") + * # same as: + * mp2 = FFI::MemoryPointer.new(:char,16) + * mp2.put_string("this is a string") + */ + rbffi_MemoryPointerClass = rb_define_class_under(moduleFFI, "MemoryPointer", ffi_Pointer); + rb_global_variable(&rbffi_MemoryPointerClass); + + rb_define_alloc_func(rbffi_MemoryPointerClass, memptr_allocate); + rb_define_method(rbffi_MemoryPointerClass, "initialize", memptr_initialize, -1); + rb_define_singleton_method(rbffi_MemoryPointerClass, "from_string", memptr_s_from_string, 1); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MemoryPointer.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MemoryPointer.h new file mode 100644 index 0000000..8106030 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MemoryPointer.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * Copyright (c) 2008, Luc Heinrich + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_MEMORYPOINTER_H +#define RBFFI_MEMORYPOINTER_H + +# include +#include + +#ifdef __cplusplus +extern "C" { +#endif + + extern void rbffi_MemoryPointer_Init(VALUE moduleFFI); + extern VALUE rbffi_MemoryPointerClass; + extern VALUE rbffi_MemoryPointer_NewInstance(long size, long count, bool clear); +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_MEMORYPOINTER_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MemoryPointer.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MemoryPointer.o new file mode 100644 index 0000000..d148b1e Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MemoryPointer.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MethodHandle.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MethodHandle.c new file mode 100644 index 0000000..d047e10 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MethodHandle.c @@ -0,0 +1,348 @@ +/* + * Copyright (c) 2009, 2010 Wayne Meissner + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MSC_VER +#include +#endif +#include +#ifndef _WIN32 +# include +#endif +#include +#include +#include +#ifndef _WIN32 +# include +#endif +#include +#include +#if defined(HAVE_NATIVETHREAD) && !defined(_WIN32) && !defined(__WIN32__) +# include +#endif + +#include +#include "rbffi.h" +#include "compat.h" + +#include "Function.h" +#include "Types.h" +#include "Type.h" +#include "LastError.h" +#include "Call.h" +#include "ClosurePool.h" +#include "MethodHandle.h" + + +#define MAX_METHOD_FIXED_ARITY (6) + +#ifndef roundup +# define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) +#endif + +#ifdef USE_RAW +# define METHOD_CLOSURE ffi_raw_closure +# define METHOD_PARAMS ffi_raw* +#else +# define METHOD_CLOSURE ffi_closure +# define METHOD_PARAMS void** +#endif + + + +static bool prep_trampoline(void* ctx, void* code, Closure* closure, char* errmsg, size_t errmsgsize); +static long trampoline_size(void); + +#if defined(__x86_64__) && (defined(__linux__) || defined(__APPLE__)) +# define CUSTOM_TRAMPOLINE 1 +#endif + + +struct MethodHandle { + Closure* closure; +}; + +static ClosurePool* defaultClosurePool; + + +MethodHandle* +rbffi_MethodHandle_Alloc(FunctionType* fnInfo, void* function) +{ + MethodHandle* handle; + Closure* closure = rbffi_Closure_Alloc(defaultClosurePool); + if (closure == NULL) { + rb_raise(rb_eNoMemError, "failed to allocate closure from pool"); + return NULL; + } + + handle = xcalloc(1, sizeof(*handle)); + handle->closure = closure; + closure->info = fnInfo; + closure->function = function; + + return handle; +} + +void +rbffi_MethodHandle_Free(MethodHandle* handle) +{ + if (handle != NULL) { + rbffi_Closure_Free(handle->closure); + xfree(handle); + } +} + +rbffi_function_anyargs rbffi_MethodHandle_CodeAddress(MethodHandle* handle) +{ + return (rbffi_function_anyargs) handle->closure->code; +} + +#ifndef CUSTOM_TRAMPOLINE +static void attached_method_invoke(ffi_cif* cif, void* retval, METHOD_PARAMS parameters, void* user_data); + +static ffi_type* methodHandleParamTypes[3]; + +static ffi_cif mh_cif; + +static bool +prep_trampoline(void* ctx, void* code, Closure* closure, char* errmsg, size_t errmsgsize) +{ + ffi_status ffiStatus; + +#if defined(USE_RAW) + ffiStatus = ffi_prep_raw_closure(code, &mh_cif, attached_method_invoke, closure); +#else + ffiStatus = ffi_prep_closure_loc(closure->pcl, &mh_cif, attached_method_invoke, closure, code); +#endif + if (ffiStatus != FFI_OK) { + snprintf(errmsg, errmsgsize, "ffi_prep_closure_loc failed. status=%#x", ffiStatus); + return false; + } + + return true; +} + + +static long +trampoline_size(void) +{ + return sizeof(METHOD_CLOSURE); +} + +/* + * attached_method_invoke is used functions with more than 6 parameters, or + * with struct param or return values + */ +static void +attached_method_invoke(ffi_cif* cif, void* mretval, METHOD_PARAMS parameters, void* user_data) +{ + Closure* handle = (Closure *) user_data; + FunctionType* fnInfo = (FunctionType *) handle->info; + +#ifdef USE_RAW + int argc = parameters[0].sint; + VALUE* argv = *(VALUE **) ¶meters[1]; +#else + int argc = *(int *) parameters[0]; + VALUE* argv = *(VALUE **) parameters[1]; +#endif + + *(VALUE *) mretval = (*fnInfo->invoke)(argc, argv, handle->function, fnInfo); +} + +#endif + + + +#if defined(CUSTOM_TRAMPOLINE) +#if defined(__x86_64__) + +static VALUE custom_trampoline(int argc, VALUE* argv, VALUE self, Closure*); + +#define TRAMPOLINE_CTX_MAGIC (0xfee1deadcafebabe) +#define TRAMPOLINE_FUN_MAGIC (0xfeedfacebeeff00d) + +/* + * This is a hand-coded trampoline to speedup entry from ruby to the FFI translation + * layer for x86_64 arches. + * + * Since a ruby function has exactly 3 arguments, and the first 6 arguments are + * passed in registers for x86_64, we can tack on a context pointer by simply + * putting a value in %rcx, then jumping to the C trampoline code. + * + * This results in approx a 30% speedup for x86_64 FFI dispatch + */ +__asm__( + ".text\n\t" + ".globl ffi_trampoline\n\t" + ".globl _ffi_trampoline\n\t" + "ffi_trampoline:\n\t" + "_ffi_trampoline:\n\t" + "movabsq $0xfee1deadcafebabe, %rcx\n\t" + "movabsq $0xfeedfacebeeff00d, %r11\n\t" + "jmpq *%r11\n\t" + ".globl ffi_trampoline_end\n\t" + "ffi_trampoline_end:\n\t" + ".globl _ffi_trampoline_end\n\t" + "_ffi_trampoline_end:\n\t" +); + +static VALUE +custom_trampoline(int argc, VALUE* argv, VALUE self, Closure* handle) +{ + FunctionType* fnInfo = (FunctionType *) handle->info; + VALUE rbReturnValue; + + RB_GC_GUARD(rbReturnValue) = (*fnInfo->invoke)(argc, argv, handle->function, fnInfo); + RB_GC_GUARD(self); + + return rbReturnValue; +} + +#elif defined(__i386__) && 0 + +static VALUE custom_trampoline(void *args, Closure*); +#define TRAMPOLINE_CTX_MAGIC (0xfee1dead) +#define TRAMPOLINE_FUN_MAGIC (0xbeefcafe) + +/* + * This is a hand-coded trampoline to speed-up entry from ruby to the FFI translation + * layer for i386 arches. + * + * This does not make a discernible difference vs a raw closure, so for now, + * it is not enabled. + */ +__asm__( + ".text\n\t" + ".globl ffi_trampoline\n\t" + ".globl _ffi_trampoline\n\t" + "ffi_trampoline:\n\t" + "_ffi_trampoline:\n\t" + "subl $12, %esp\n\t" + "leal 16(%esp), %eax\n\t" + "movl %eax, (%esp)\n\t" + "movl $0xfee1dead, 4(%esp)\n\t" + "movl $0xbeefcafe, %eax\n\t" + "call *%eax\n\t" + "addl $12, %esp\n\t" + "ret\n\t" + ".globl ffi_trampoline_end\n\t" + "ffi_trampoline_end:\n\t" + ".globl _ffi_trampoline_end\n\t" + "_ffi_trampoline_end:\n\t" +); + +static VALUE +custom_trampoline(void *args, Closure* handle) +{ + FunctionType* fnInfo = (FunctionType *) handle->info; + return (*fnInfo->invoke)(*(int *) args, *(VALUE **) (args + 4), handle->function, fnInfo); +} + +#endif /* __x86_64__ else __i386__ */ + +extern void ffi_trampoline(int argc, VALUE* argv, VALUE self); +extern void ffi_trampoline_end(void); +static int trampoline_offsets(long *, long *); + +static long trampoline_ctx_offset, trampoline_func_offset; + +static long +trampoline_offset(int off, const long value) +{ + char *ptr; + for (ptr = (char *) &ffi_trampoline + off; ptr < (char *) &ffi_trampoline_end; ++ptr) { + if (*(long *) ptr == value) { + return ptr - (char *) &ffi_trampoline; + } + } + + return -1; +} + +static int +trampoline_offsets(long* ctxOffset, long* fnOffset) +{ + *ctxOffset = trampoline_offset(0, TRAMPOLINE_CTX_MAGIC); + if (*ctxOffset == -1) { + return -1; + } + + *fnOffset = trampoline_offset(0, TRAMPOLINE_FUN_MAGIC); + if (*fnOffset == -1) { + return -1; + } + + return 0; +} + +static bool +prep_trampoline(void* ctx, void* code, Closure* closure, char* errmsg, size_t errmsgsize) +{ + memcpy(code, (void*) &ffi_trampoline, trampoline_size()); + /* Patch the context and function addresses into the stub code */ + *(intptr_t *)((char*)code + trampoline_ctx_offset) = (intptr_t) closure; + *(intptr_t *)((char*)code + trampoline_func_offset) = (intptr_t) custom_trampoline; + + return true; +} + +static long +trampoline_size(void) +{ + return (char *) &ffi_trampoline_end - (char *) &ffi_trampoline; +} + +#endif /* CUSTOM_TRAMPOLINE */ + + +void +rbffi_MethodHandle_Init(VALUE module) +{ +#ifndef CUSTOM_TRAMPOLINE + ffi_status ffiStatus; +#endif + + defaultClosurePool = rbffi_ClosurePool_New((int) trampoline_size(), prep_trampoline, NULL); + +#if defined(CUSTOM_TRAMPOLINE) + if (trampoline_offsets(&trampoline_ctx_offset, &trampoline_func_offset) != 0) { + rb_raise(rb_eFatal, "Could not locate offsets in trampoline code"); + } +#else + methodHandleParamTypes[0] = &ffi_type_sint; + methodHandleParamTypes[1] = &ffi_type_pointer; + methodHandleParamTypes[2] = &ffi_type_ulong; + + ffiStatus = ffi_prep_cif(&mh_cif, FFI_DEFAULT_ABI, 3, &ffi_type_ulong, + methodHandleParamTypes); + if (ffiStatus != FFI_OK) { + rb_raise(rb_eFatal, "ffi_prep_cif failed. status=%#x", ffiStatus); + } + +#endif +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MethodHandle.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MethodHandle.h new file mode 100644 index 0000000..0dcc058 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MethodHandle.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_METHODHANDLE_H +#define RBFFI_METHODHANDLE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "Function.h" + + +typedef struct MethodHandlePool MethodHandlePool; +typedef struct MethodHandle MethodHandle; +typedef VALUE (*rbffi_function_anyargs)(int argc, VALUE* argv, VALUE self); + + +MethodHandle* rbffi_MethodHandle_Alloc(FunctionType* fnInfo, void* function); +void rbffi_MethodHandle_Free(MethodHandle* handle); +rbffi_function_anyargs rbffi_MethodHandle_CodeAddress(MethodHandle* handle); +void rbffi_MethodHandle_Init(VALUE module); + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_METHODHANDLE_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MethodHandle.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MethodHandle.o new file mode 100644 index 0000000..c6803e4 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/MethodHandle.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Platform.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Platform.c new file mode 100644 index 0000000..57f3219 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Platform.c @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2008-2010 Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MSC_VER +# include +#endif +# include +#include +#include +#include +#include +#include "rbffi_endian.h" +#include "Platform.h" + +#if defined(__GNU__) || (defined(__GLIBC__) && !defined(__UCLIBC__)) +# include +#endif + +static VALUE PlatformModule = Qnil; + +static void +export_primitive_types(VALUE module) +{ +#define S(name, T) do { \ + typedef struct { char c; T v; } s; \ + rb_define_const(module, #name "_ALIGN", INT2NUM((sizeof(s) - sizeof(T)) * 8)); \ + rb_define_const(module, #name "_SIZE", INT2NUM(sizeof(T)* 8)); \ +} while(0) + S(INT8, char); + S(INT16, short); + S(INT32, int); + S(INT64, long long); + S(LONG, long); + S(FLOAT, float); + S(DOUBLE, double); + S(LONG_DOUBLE, long double); + S(ADDRESS, void*); +#undef S +} + +void +rbffi_Platform_Init(VALUE moduleFFI) +{ + PlatformModule = rb_define_module_under(moduleFFI, "Platform"); + rb_define_const(PlatformModule, "BYTE_ORDER", INT2FIX(BYTE_ORDER)); + rb_define_const(PlatformModule, "LITTLE_ENDIAN", INT2FIX(LITTLE_ENDIAN)); + rb_define_const(PlatformModule, "BIG_ENDIAN", INT2FIX(BIG_ENDIAN)); +#if defined(__GNU__) || (defined(__GLIBC__) && !defined(__UCLIBC__)) + rb_define_const(PlatformModule, "GNU_LIBC", rb_str_new2(LIBC_SO)); +#endif + export_primitive_types(PlatformModule); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Platform.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Platform.h new file mode 100644 index 0000000..5575e34 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Platform.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2008-2010 Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_PLATFORM_H +#define RBFFI_PLATFORM_H + +#ifdef __cplusplus +extern "C" { +#endif + + extern void rbffi_Platform_Init(VALUE moduleFFI); + + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_PLATFORM_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Platform.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Platform.o new file mode 100644 index 0000000..0778322 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Platform.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Pointer.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Pointer.c new file mode 100644 index 0000000..153fff1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Pointer.c @@ -0,0 +1,507 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include "rbffi.h" +#include "rbffi_endian.h" +#include "AbstractMemory.h" +#include "Pointer.h" + +#define POINTER(obj) rbffi_AbstractMemory_Cast((obj), rbffi_PointerClass) + +VALUE rbffi_PointerClass = Qnil; +VALUE rbffi_NullPointerSingleton = Qnil; + +static void ptr_release(Pointer* ptr); +static void ptr_mark(Pointer* ptr); + +VALUE +rbffi_Pointer_NewInstance(void* addr) +{ + Pointer* p; + VALUE obj; + + if (addr == NULL) { + return rbffi_NullPointerSingleton; + } + + obj = Data_Make_Struct(rbffi_PointerClass, Pointer, NULL, -1, p); + p->memory.address = addr; + p->memory.size = LONG_MAX; + p->memory.flags = (addr == NULL) ? 0 : (MEM_RD | MEM_WR); + p->memory.typeSize = 1; + p->rbParent = Qnil; + + return obj; +} + +static VALUE +ptr_allocate(VALUE klass) +{ + Pointer* p; + VALUE obj; + + obj = Data_Make_Struct(klass, Pointer, ptr_mark, ptr_release, p); + p->rbParent = Qnil; + p->memory.flags = MEM_RD | MEM_WR; + + return obj; +} + +/* + * @overload initialize(pointer) + * @param [Pointer] pointer another pointer to initialize from + * Create a new pointer from another {Pointer}. + * @overload initialize(type, address) + * @param [Type] type type for pointer + * @param [Integer] address base address for pointer + * Create a new pointer from a {Type} and a base address + * @return [self] + * A new instance of Pointer. + */ +static VALUE +ptr_initialize(int argc, VALUE* argv, VALUE self) +{ + Pointer* p; + VALUE rbType = Qnil, rbAddress = Qnil; + int typeSize = 1; + + Data_Get_Struct(self, Pointer, p); + + switch (rb_scan_args(argc, argv, "11", &rbType, &rbAddress)) { + case 1: + rbAddress = rbType; + typeSize = 1; + break; + case 2: + typeSize = rbffi_type_size(rbType); + break; + default: + rb_raise(rb_eArgError, "Invalid arguments"); + } + + switch (TYPE(rbAddress)) { + case T_FIXNUM: + case T_BIGNUM: + p->memory.address = (void*) (uintptr_t) NUM2LL(rbAddress); + p->memory.size = LONG_MAX; + if (p->memory.address == NULL) { + p->memory.flags = 0; + } + break; + + default: + if (rb_obj_is_kind_of(rbAddress, rbffi_PointerClass)) { + Pointer* orig; + + p->rbParent = rbAddress; + Data_Get_Struct(rbAddress, Pointer, orig); + p->memory = orig->memory; + } else { + rb_raise(rb_eTypeError, "wrong argument type, expected Integer or FFI::Pointer"); + } + break; + } + + p->memory.typeSize = typeSize; + + return self; +} + +/* + * call-seq: ptr.initialize_copy(other) + * @param [Pointer] other source for cloning or dupping + * @return [self] + * @raise {RuntimeError} if +other+ is an unbounded memory area, or is unreadable/unwritable + * @raise {NoMemError} if failed to allocate memory for new object + * DO NOT CALL THIS METHOD. + * + * This method is internally used by #dup and #clone. Memory content is copied from +other+. + */ +static VALUE +ptr_initialize_copy(VALUE self, VALUE other) +{ + AbstractMemory* src; + Pointer* dst; + + Data_Get_Struct(self, Pointer, dst); + src = POINTER(other); + if (src->size == LONG_MAX) { + rb_raise(rb_eRuntimeError, "cannot duplicate unbounded memory area"); + return Qnil; + } + + if ((dst->memory.flags & (MEM_RD | MEM_WR)) != (MEM_RD | MEM_WR)) { + rb_raise(rb_eRuntimeError, "cannot duplicate unreadable/unwritable memory area"); + return Qnil; + } + + if (dst->storage != NULL) { + xfree(dst->storage); + dst->storage = NULL; + } + + dst->storage = xmalloc(src->size + 7); + if (dst->storage == NULL) { + rb_raise(rb_eNoMemError, "failed to allocate memory size=%lu bytes", src->size); + return Qnil; + } + + dst->allocated = true; + dst->autorelease = true; + dst->memory.address = (void *) (((uintptr_t) dst->storage + 0x7) & (uintptr_t) ~0x7ULL); + dst->memory.size = src->size; + dst->memory.typeSize = src->typeSize; + + /* finally, copy the actual memory contents */ + memcpy(dst->memory.address, src->address, src->size); + + return self; +} + +static VALUE +slice(VALUE self, long offset, long size) +{ + AbstractMemory* ptr; + Pointer* p; + VALUE retval; + + Data_Get_Struct(self, AbstractMemory, ptr); + checkBounds(ptr, offset, size == LONG_MAX ? 1 : size); + + retval = Data_Make_Struct(rbffi_PointerClass, Pointer, ptr_mark, -1, p); + + p->memory.address = ptr->address + offset; + p->memory.size = size; + p->memory.flags = ptr->flags; + p->memory.typeSize = ptr->typeSize; + p->rbParent = self; + + return retval; +} + +/* + * Document-method: + + * call-seq: ptr + offset + * @param [Numeric] offset + * @return [Pointer] + * Return a new {Pointer} from an existing pointer and an +offset+. + */ +static VALUE +ptr_plus(VALUE self, VALUE offset) +{ + AbstractMemory* ptr; + long off = NUM2LONG(offset); + + Data_Get_Struct(self, AbstractMemory, ptr); + + return slice(self, off, ptr->size == LONG_MAX ? LONG_MAX : ptr->size - off); +} + +/* + * call-seq: ptr.slice(offset, length) + * @param [Numeric] offset + * @param [Numeric] length + * @return [Pointer] + * Return a new {Pointer} from an existing one. This pointer points on same contents + * from +offset+ for a length +length+. + */ +static VALUE +ptr_slice(VALUE self, VALUE rbOffset, VALUE rbLength) +{ + return slice(self, NUM2LONG(rbOffset), NUM2LONG(rbLength)); +} + +/* + * call-seq: ptr.inspect + * @return [String] + * Inspect pointer object. + */ +static VALUE +ptr_inspect(VALUE self) +{ + char buf[100]; + Pointer* ptr; + + Data_Get_Struct(self, Pointer, ptr); + + if (ptr->memory.size != LONG_MAX) { + snprintf(buf, sizeof(buf), "#<%s address=%p size=%lu>", + rb_obj_classname(self), ptr->memory.address, ptr->memory.size); + } else { + snprintf(buf, sizeof(buf), "#<%s address=%p>", rb_obj_classname(self), ptr->memory.address); + } + + return rb_str_new2(buf); +} + +/* + * Document-method: null? + * call-seq: ptr.null? + * @return [Boolean] + * Return +true+ if +self+ is a {NULL} pointer. + */ +static VALUE +ptr_null_p(VALUE self) +{ + Pointer* ptr; + + Data_Get_Struct(self, Pointer, ptr); + + return ptr->memory.address == NULL ? Qtrue : Qfalse; +} + +/* + * Document-method: == + * call-seq: ptr == other + * @param [Pointer] other + * Check equality between +self+ and +other+. Equality is tested on {#address}. + */ +static VALUE +ptr_equals(VALUE self, VALUE other) +{ + Pointer* ptr; + + Data_Get_Struct(self, Pointer, ptr); + + if (NIL_P(other)) { + return ptr->memory.address == NULL ? Qtrue : Qfalse; + } + + return ptr->memory.address == POINTER(other)->address ? Qtrue : Qfalse; +} + +/* + * call-seq: ptr.address + * @return [Numeric] pointer's base address + * Return +self+'s base address (alias: #to_i). + */ +static VALUE +ptr_address(VALUE self) +{ + Pointer* ptr; + + Data_Get_Struct(self, Pointer, ptr); + + return ULL2NUM((uintptr_t) ptr->memory.address); +} + +#if BYTE_ORDER == LITTLE_ENDIAN +# define SWAPPED_ORDER BIG_ENDIAN +#else +# define SWAPPED_ORDER LITTLE_ENDIAN +#endif + +/* + * Get or set +self+'s endianness + * @overload order + * @return [:big, :little] endianness of +self+ + * @overload order(order) + * @param [Symbol] order endianness to set (+:little+, +:big+ or +:network+). +:big+ and +:network+ + * are synonymous. + * @return a new pointer with the new order + */ +static VALUE +ptr_order(int argc, VALUE* argv, VALUE self) +{ + Pointer* ptr; + + Data_Get_Struct(self, Pointer, ptr); + if (argc == 0) { + int order = (ptr->memory.flags & MEM_SWAP) == 0 ? BYTE_ORDER : SWAPPED_ORDER; + return order == BIG_ENDIAN ? ID2SYM(rb_intern("big")) : ID2SYM(rb_intern("little")); + } else { + VALUE rbOrder = Qnil; + int order = BYTE_ORDER; + + if (rb_scan_args(argc, argv, "1", &rbOrder) < 1) { + rb_raise(rb_eArgError, "need byte order"); + } + if (SYMBOL_P(rbOrder)) { + ID id = SYM2ID(rbOrder); + if (id == rb_intern("little")) { + order = LITTLE_ENDIAN; + + } else if (id == rb_intern("big") || id == rb_intern("network")) { + order = BIG_ENDIAN; + } else { + rb_raise(rb_eArgError, "unknown byte order"); + } + } + if (order != BYTE_ORDER) { + Pointer* p2; + VALUE retval = slice(self, 0, ptr->memory.size); + + Data_Get_Struct(retval, Pointer, p2); + p2->memory.flags |= MEM_SWAP; + return retval; + } + + return self; + } +} + + +/* + * call-seq: ptr.free + * @return [self] + * Free memory pointed by +self+. + */ +static VALUE +ptr_free(VALUE self) +{ + Pointer* ptr; + + Data_Get_Struct(self, Pointer, ptr); + + if (ptr->allocated) { + if (ptr->storage != NULL) { + xfree(ptr->storage); + ptr->storage = NULL; + } + ptr->allocated = false; + + } else { + VALUE caller = rb_funcall(rb_funcall(Qnil, rb_intern("caller"), 0), rb_intern("first"), 0); + + rb_warn("calling free on non allocated pointer %s from %s", RSTRING_PTR(ptr_inspect(self)), RSTRING_PTR(rb_str_to_str(caller))); + } + + return self; +} + +static VALUE +ptr_type_size(VALUE self) +{ + Pointer* ptr; + + Data_Get_Struct(self, Pointer, ptr); + + return INT2NUM(ptr->memory.typeSize); +} + +/* + * call-seq: ptr.autorelease = autorelease + * @param [Boolean] autorelease + * @return [Boolean] +autorelease+ + * Set +autorelease+ attribute. See also Autorelease section. + */ +static VALUE +ptr_autorelease(VALUE self, VALUE autorelease) +{ + Pointer* ptr; + + Data_Get_Struct(self, Pointer, ptr); + ptr->autorelease = autorelease == Qtrue; + + return autorelease; +} + +/* + * call-seq: ptr.autorelease? + * @return [Boolean] + * Get +autorelease+ attribute. See also Autorelease section. + */ +static VALUE +ptr_autorelease_p(VALUE self) +{ + Pointer* ptr; + + Data_Get_Struct(self, Pointer, ptr); + + return ptr->autorelease ? Qtrue : Qfalse; +} + + +static void +ptr_release(Pointer* ptr) +{ + if (ptr->autorelease && ptr->allocated && ptr->storage != NULL) { + xfree(ptr->storage); + ptr->storage = NULL; + } + xfree(ptr); +} + +static void +ptr_mark(Pointer* ptr) +{ + rb_gc_mark(ptr->rbParent); +} + +void +rbffi_Pointer_Init(VALUE moduleFFI) +{ + VALUE rbNullAddress = ULL2NUM(0); + VALUE ffi_AbstractMemory = rbffi_AbstractMemoryClass; + + /* + * Document-class: FFI::Pointer < FFI::AbstractMemory + * Pointer class is used to manage C pointers with ease. A {Pointer} object is defined by his + * {#address} (as a C pointer). It permits additions with an integer for pointer arithmetic. + * + * == Autorelease + * By default a pointer object frees its content when it's garbage collected. + * Therefore it's usually not necessary to call {#free} explicit. + * This behaviour may be changed with {#autorelease=} method. + * If it's set to +false+, the memory isn't freed by the garbage collector, but stays valid until +free()+ is called on C level or when the process terminates. + */ + rbffi_PointerClass = rb_define_class_under(moduleFFI, "Pointer", ffi_AbstractMemory); + /* + * Document-variable: Pointer + */ + rb_global_variable(&rbffi_PointerClass); + + rb_define_alloc_func(rbffi_PointerClass, ptr_allocate); + rb_define_method(rbffi_PointerClass, "initialize", ptr_initialize, -1); + rb_define_method(rbffi_PointerClass, "initialize_copy", ptr_initialize_copy, 1); + rb_define_method(rbffi_PointerClass, "inspect", ptr_inspect, 0); + rb_define_method(rbffi_PointerClass, "to_s", ptr_inspect, 0); + rb_define_method(rbffi_PointerClass, "+", ptr_plus, 1); + rb_define_method(rbffi_PointerClass, "slice", ptr_slice, 2); + rb_define_method(rbffi_PointerClass, "null?", ptr_null_p, 0); + rb_define_method(rbffi_PointerClass, "address", ptr_address, 0); + rb_define_alias(rbffi_PointerClass, "to_i", "address"); + rb_define_method(rbffi_PointerClass, "==", ptr_equals, 1); + rb_define_method(rbffi_PointerClass, "order", ptr_order, -1); + rb_define_method(rbffi_PointerClass, "autorelease=", ptr_autorelease, 1); + rb_define_method(rbffi_PointerClass, "autorelease?", ptr_autorelease_p, 0); + rb_define_method(rbffi_PointerClass, "free", ptr_free, 0); + rb_define_method(rbffi_PointerClass, "type_size", ptr_type_size, 0); + + rbffi_NullPointerSingleton = rb_class_new_instance(1, &rbNullAddress, rbffi_PointerClass); + /* + * NULL pointer + */ + rb_define_const(rbffi_PointerClass, "NULL", rbffi_NullPointerSingleton); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Pointer.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Pointer.h new file mode 100644 index 0000000..b3d6c85 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Pointer.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_POINTER_H +#define RBFFI_POINTER_H + +# include + +#ifdef __cplusplus +extern "C" { +#endif + +#include "AbstractMemory.h" + +extern void rbffi_Pointer_Init(VALUE moduleFFI); +extern VALUE rbffi_Pointer_NewInstance(void* addr); +extern VALUE rbffi_PointerClass; +extern VALUE rbffi_NullPointerSingleton; + +typedef struct Pointer { + AbstractMemory memory; + VALUE rbParent; + char* storage; /* start of malloc area */ + bool autorelease; + bool allocated; +} Pointer; + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_POINTER_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Pointer.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Pointer.o new file mode 100644 index 0000000..eae4e1c Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Pointer.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Struct.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Struct.c new file mode 100644 index 0000000..92731c8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Struct.c @@ -0,0 +1,822 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * Copyright (C) 2009 Luc Heinrich + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#ifndef _MSC_VER +# include +#endif +#include +#include +#include +#include "rbffi.h" +#include "compat.h" +#include "AbstractMemory.h" +#include "Pointer.h" +#include "MemoryPointer.h" +#include "Function.h" +#include "Types.h" +#include "Function.h" +#include "StructByValue.h" +#include "ArrayType.h" +#include "MappedType.h" +#include "Struct.h" + +typedef struct InlineArray_ { + VALUE rbMemory; + VALUE rbField; + + AbstractMemory* memory; + StructField* field; + MemoryOp *op; + Type* componentType; + ArrayType* arrayType; + int length; +} InlineArray; + + +static void struct_mark(Struct *); +static void struct_free(Struct *); +static VALUE struct_class_layout(VALUE klass); +static void struct_malloc(Struct* s); +static void inline_array_mark(InlineArray *); +static void store_reference_value(StructField* f, Struct* s, VALUE value); + +VALUE rbffi_StructClass = Qnil; + +VALUE rbffi_StructInlineArrayClass = Qnil; +VALUE rbffi_StructLayoutCharArrayClass = Qnil; + +static ID id_pointer_ivar = 0, id_layout_ivar = 0; +static ID id_get = 0, id_put = 0, id_to_ptr = 0, id_to_s = 0, id_layout = 0; + +static inline char* +memory_address(VALUE self) +{ + return ((AbstractMemory *)DATA_PTR((self)))->address; +} + +static VALUE +struct_allocate(VALUE klass) +{ + Struct* s; + VALUE obj = Data_Make_Struct(klass, Struct, struct_mark, struct_free, s); + + s->rbPointer = Qnil; + s->rbLayout = Qnil; + + return obj; +} + +/* + * call-seq: initialize + * @overload initialize(pointer, *args) + * @param [AbstractMemory] pointer + * @param [Array] args + * @return [self] + */ +static VALUE +struct_initialize(int argc, VALUE* argv, VALUE self) +{ + Struct* s; + VALUE rbPointer = Qnil, rest = Qnil, klass = CLASS_OF(self); + int nargs; + + Data_Get_Struct(self, Struct, s); + + nargs = rb_scan_args(argc, argv, "01*", &rbPointer, &rest); + + /* Call up into ruby code to adjust the layout */ + if (nargs > 1) { + s->rbLayout = rb_funcall2(CLASS_OF(self), id_layout, (int) RARRAY_LEN(rest), RARRAY_PTR(rest)); + } else { + s->rbLayout = struct_class_layout(klass); + } + + if (!rb_obj_is_kind_of(s->rbLayout, rbffi_StructLayoutClass)) { + rb_raise(rb_eRuntimeError, "Invalid Struct layout"); + } + + Data_Get_Struct(s->rbLayout, StructLayout, s->layout); + + if (rbPointer != Qnil) { + s->pointer = MEMORY(rbPointer); + s->rbPointer = rbPointer; + } else { + struct_malloc(s); + } + + return self; +} + +/* + * call-seq: initialize_copy(other) + * @return [nil] + * DO NOT CALL THIS METHOD + */ +static VALUE +struct_initialize_copy(VALUE self, VALUE other) +{ + Struct* src; + Struct* dst; + + Data_Get_Struct(self, Struct, dst); + Data_Get_Struct(other, Struct, src); + if (dst == src) { + return self; + } + + dst->rbLayout = src->rbLayout; + dst->layout = src->layout; + + /* + * A new MemoryPointer instance is allocated here instead of just calling + * #dup on rbPointer, since the Pointer may not know its length, or may + * be longer than just this struct. + */ + if (src->pointer->address != NULL) { + dst->rbPointer = rbffi_MemoryPointer_NewInstance(1, src->layout->size, false); + dst->pointer = MEMORY(dst->rbPointer); + memcpy(dst->pointer->address, src->pointer->address, src->layout->size); + } else { + dst->rbPointer = src->rbPointer; + dst->pointer = src->pointer; + } + + if (src->layout->referenceFieldCount > 0) { + dst->rbReferences = ALLOC_N(VALUE, dst->layout->referenceFieldCount); + memcpy(dst->rbReferences, src->rbReferences, dst->layout->referenceFieldCount * sizeof(VALUE)); + } + + return self; +} + +static VALUE +struct_class_layout(VALUE klass) +{ + VALUE layout; + if (!rb_ivar_defined(klass, id_layout_ivar)) { + rb_raise(rb_eRuntimeError, "no Struct layout configured for %s", rb_class2name(klass)); + } + + layout = rb_ivar_get(klass, id_layout_ivar); + if (!rb_obj_is_kind_of(layout, rbffi_StructLayoutClass)) { + rb_raise(rb_eRuntimeError, "invalid Struct layout for %s", rb_class2name(klass)); + } + + return layout; +} + +static StructLayout* +struct_layout(VALUE self) +{ + Struct* s = (Struct *) DATA_PTR(self); + if (s->layout != NULL) { + return s->layout; + } + + if (s->layout == NULL) { + s->rbLayout = struct_class_layout(CLASS_OF(self)); + Data_Get_Struct(s->rbLayout, StructLayout, s->layout); + } + + return s->layout; +} + +static Struct* +struct_validate(VALUE self) +{ + Struct* s; + Data_Get_Struct(self, Struct, s); + + if (struct_layout(self) == NULL) { + rb_raise(rb_eRuntimeError, "struct layout == null"); + } + + if (s->pointer == NULL) { + struct_malloc(s); + } + + return s; +} + +static void +struct_malloc(Struct* s) +{ + if (s->rbPointer == Qnil) { + s->rbPointer = rbffi_MemoryPointer_NewInstance(s->layout->size, 1, true); + + } else if (!rb_obj_is_kind_of(s->rbPointer, rbffi_AbstractMemoryClass)) { + rb_raise(rb_eRuntimeError, "invalid pointer in struct"); + } + + s->pointer = (AbstractMemory *) DATA_PTR(s->rbPointer); +} + +static void +struct_mark(Struct *s) +{ + rb_gc_mark(s->rbPointer); + rb_gc_mark(s->rbLayout); + if (s->rbReferences != NULL) { + rb_gc_mark_locations(&s->rbReferences[0], &s->rbReferences[s->layout->referenceFieldCount]); + } +} + +static void +struct_free(Struct* s) +{ + xfree(s->rbReferences); + xfree(s); +} + + +static void +store_reference_value(StructField* f, Struct* s, VALUE value) +{ + if (unlikely(f->referenceIndex == -1)) { + rb_raise(rb_eRuntimeError, "put_reference_value called for non-reference type"); + return; + } + if (s->rbReferences == NULL) { + int i; + s->rbReferences = ALLOC_N(VALUE, s->layout->referenceFieldCount); + for (i = 0; i < s->layout->referenceFieldCount; ++i) { + s->rbReferences[i] = Qnil; + } + } + + s->rbReferences[f->referenceIndex] = value; +} + + +static StructField * +struct_field(Struct* s, VALUE fieldName) +{ + StructLayout* layout = s->layout; + struct field_cache_entry *p_ce = FIELD_CACHE_LOOKUP(layout, fieldName); + + /* Do a hash lookup only if cache entry is empty or fieldName is unexpected? */ + if (unlikely(!SYMBOL_P(fieldName) || !p_ce->fieldName || p_ce->fieldName != fieldName)) { + VALUE rbField = rb_hash_aref(layout->rbFieldMap, fieldName); + if (unlikely(NIL_P(rbField))) { + VALUE str = rb_funcall2(fieldName, id_to_s, 0, NULL); + rb_raise(rb_eArgError, "No such field '%s'", StringValueCStr(str)); + } + /* Write the retrieved coder to the cache */ + p_ce->fieldName = fieldName; + p_ce->field = (StructField *) DATA_PTR(rbField); + } + + return p_ce->field; +} + +/* + * call-seq: struct[field_name] + * @param field_name field to access + * Acces to a Struct field. + */ +static VALUE +struct_aref(VALUE self, VALUE fieldName) +{ + Struct* s; + StructField* f; + + s = struct_validate(self); + + f = struct_field(s, fieldName); + if (f->get != NULL) { + return (*f->get)(f, s); + + } else if (f->memoryOp != NULL) { + return (*f->memoryOp->get)(s->pointer, f->offset); + + } else { + VALUE rbField = rb_hash_aref(s->layout->rbFieldMap, fieldName); + /* call up to the ruby code to fetch the value */ + return rb_funcall2(rbField, id_get, 1, &s->rbPointer); + } +} + +/* + * call-seq: []=(field_name, value) + * @param field_name field to access + * @param value value to set to +field_name+ + * @return [value] + * Set a field in Struct. + */ +static VALUE +struct_aset(VALUE self, VALUE fieldName, VALUE value) +{ + Struct* s; + StructField* f; + + s = struct_validate(self); + + f = struct_field(s, fieldName); + if (f->put != NULL) { + (*f->put)(f, s, value); + + } else if (f->memoryOp != NULL) { + + (*f->memoryOp->put)(s->pointer, f->offset, value); + + } else { + VALUE rbField = rb_hash_aref(s->layout->rbFieldMap, fieldName); + /* call up to the ruby code to set the value */ + VALUE argv[2]; + argv[0] = s->rbPointer; + argv[1] = value; + rb_funcall2(rbField, id_put, 2, argv); + } + + if (f->referenceRequired) { + store_reference_value(f, s, value); + } + + return value; +} + +/* + * call-seq: pointer= pointer + * @param [AbstractMemory] pointer + * @return [self] + * Make Struct point to +pointer+. + */ +static VALUE +struct_set_pointer(VALUE self, VALUE pointer) +{ + Struct* s; + StructLayout* layout; + AbstractMemory* memory; + + if (!rb_obj_is_kind_of(pointer, rbffi_AbstractMemoryClass)) { + rb_raise(rb_eTypeError, "wrong argument type %s (expected Pointer or Buffer)", + rb_obj_classname(pointer)); + return Qnil; + } + + + Data_Get_Struct(self, Struct, s); + Data_Get_Struct(pointer, AbstractMemory, memory); + layout = struct_layout(self); + + if ((int) layout->base.ffiType->size > memory->size) { + rb_raise(rb_eArgError, "memory of %ld bytes too small for struct %s (expected at least %ld)", + memory->size, rb_obj_classname(self), (long) layout->base.ffiType->size); + } + + s->pointer = MEMORY(pointer); + s->rbPointer = pointer; + rb_ivar_set(self, id_pointer_ivar, pointer); + + return self; +} + +/* + * call-seq: pointer + * @return [AbstractMemory] + * Get pointer to Struct contents. + */ +static VALUE +struct_get_pointer(VALUE self) +{ + Struct* s; + + Data_Get_Struct(self, Struct, s); + + return s->rbPointer; +} + +/* + * call-seq: layout= layout + * @param [StructLayout] layout + * @return [self] + * Set the Struct's layout. + */ +static VALUE +struct_set_layout(VALUE self, VALUE layout) +{ + Struct* s; + Data_Get_Struct(self, Struct, s); + + if (!rb_obj_is_kind_of(layout, rbffi_StructLayoutClass)) { + rb_raise(rb_eTypeError, "wrong argument type %s (expected %s)", + rb_obj_classname(layout), rb_class2name(rbffi_StructLayoutClass)); + return Qnil; + } + + Data_Get_Struct(layout, StructLayout, s->layout); + rb_ivar_set(self, id_layout_ivar, layout); + + return self; +} + +/* + * call-seq: layout + * @return [StructLayout] + * Get the Struct's layout. + */ +static VALUE +struct_get_layout(VALUE self) +{ + Struct* s; + + Data_Get_Struct(self, Struct, s); + + return s->rbLayout; +} + +/* + * call-seq: null? + * @return [Boolean] + * Test if Struct's pointer is NULL + */ +static VALUE +struct_null_p(VALUE self) +{ + Struct* s; + + Data_Get_Struct(self, Struct, s); + + return s->pointer->address == NULL ? Qtrue : Qfalse; +} + +/* + * (see Pointer#order) + */ +static VALUE +struct_order(int argc, VALUE* argv, VALUE self) +{ + Struct* s; + + Data_Get_Struct(self, Struct, s); + if (argc == 0) { + return rb_funcall(s->rbPointer, rb_intern("order"), 0); + + } else { + VALUE retval = rb_obj_dup(self); + VALUE rbPointer = rb_funcall2(s->rbPointer, rb_intern("order"), argc, argv); + struct_set_pointer(retval, rbPointer); + + return retval; + } +} + +static VALUE +inline_array_allocate(VALUE klass) +{ + InlineArray* array; + VALUE obj; + + obj = Data_Make_Struct(klass, InlineArray, inline_array_mark, -1, array); + array->rbField = Qnil; + array->rbMemory = Qnil; + + return obj; +} + +static void +inline_array_mark(InlineArray* array) +{ + rb_gc_mark(array->rbField); + rb_gc_mark(array->rbMemory); +} + +/* + * Document-method: FFI::Struct::InlineArray#initialize + * call-seq: initialize(memory, field) + * @param [AbstractMemory] memory + * @param [StructField] field + * @return [self] + */ +static VALUE +inline_array_initialize(VALUE self, VALUE rbMemory, VALUE rbField) +{ + InlineArray* array; + + Data_Get_Struct(self, InlineArray, array); + array->rbMemory = rbMemory; + array->rbField = rbField; + + Data_Get_Struct(rbMemory, AbstractMemory, array->memory); + Data_Get_Struct(rbField, StructField, array->field); + Data_Get_Struct(array->field->rbType, ArrayType, array->arrayType); + Data_Get_Struct(array->arrayType->rbComponentType, Type, array->componentType); + + array->op = get_memory_op(array->componentType); + if (array->op == NULL && array->componentType->nativeType == NATIVE_MAPPED) { + array->op = get_memory_op(((MappedType *) array->componentType)->type); + } + + array->length = array->arrayType->length; + + return self; +} + +/* + * call-seq: size + * @return [Numeric] + * Get size + */ +static VALUE +inline_array_size(VALUE self) +{ + InlineArray* array; + + Data_Get_Struct(self, InlineArray, array); + + return UINT2NUM(((ArrayType *) array->field->type)->length); +} + +static int +inline_array_offset(InlineArray* array, int index) +{ + if (index < 0 || (index >= array->length && array->length > 0)) { + rb_raise(rb_eIndexError, "index %d out of bounds", index); + } + + return (int) array->field->offset + (index * (int) array->componentType->ffiType->size); +} + +/* + * call-seq: [](index) + * @param [Numeric] index + * @return [Type, Struct] + */ +static VALUE +inline_array_aref(VALUE self, VALUE rbIndex) +{ + InlineArray* array; + + Data_Get_Struct(self, InlineArray, array); + + if (array->op != NULL) { + VALUE rbNativeValue = array->op->get(array->memory, + inline_array_offset(array, NUM2INT(rbIndex))); + if (unlikely(array->componentType->nativeType == NATIVE_MAPPED)) { + return rb_funcall(((MappedType *) array->componentType)->rbConverter, + rb_intern("from_native"), 2, rbNativeValue, Qnil); + } else { + return rbNativeValue; + } + + } else if (array->componentType->nativeType == NATIVE_STRUCT) { + VALUE rbOffset = INT2NUM(inline_array_offset(array, NUM2INT(rbIndex))); + VALUE rbLength = INT2NUM(array->componentType->ffiType->size); + VALUE rbPointer = rb_funcall(array->rbMemory, rb_intern("slice"), 2, rbOffset, rbLength); + + return rb_class_new_instance(1, &rbPointer, ((StructByValue *) array->componentType)->rbStructClass); + } else { + + rb_raise(rb_eArgError, "get not supported for %s", rb_obj_classname(array->arrayType->rbComponentType)); + return Qnil; + } +} + +/* + * call-seq: []=(index, value) + * @param [Numeric] index + * @param [Type, Struct] + * @return [value] + */ +static VALUE +inline_array_aset(VALUE self, VALUE rbIndex, VALUE rbValue) +{ + InlineArray* array; + + Data_Get_Struct(self, InlineArray, array); + + if (array->op != NULL) { + if (unlikely(array->componentType->nativeType == NATIVE_MAPPED)) { + rbValue = rb_funcall(((MappedType *) array->componentType)->rbConverter, + rb_intern("to_native"), 2, rbValue, Qnil); + } + array->op->put(array->memory, inline_array_offset(array, NUM2INT(rbIndex)), + rbValue); + + } else if (array->componentType->nativeType == NATIVE_STRUCT) { + int offset = inline_array_offset(array, NUM2INT(rbIndex)); + Struct* s; + + if (!rb_obj_is_kind_of(rbValue, rbffi_StructClass)) { + rb_raise(rb_eTypeError, "argument not an instance of struct"); + return Qnil; + } + + checkWrite(array->memory); + checkBounds(array->memory, offset, array->componentType->ffiType->size); + + Data_Get_Struct(rbValue, Struct, s); + checkRead(s->pointer); + checkBounds(s->pointer, 0, array->componentType->ffiType->size); + + memcpy(array->memory->address + offset, s->pointer->address, array->componentType->ffiType->size); + + } else { + ArrayType* arrayType; + Data_Get_Struct(array->field->rbType, ArrayType, arrayType); + + rb_raise(rb_eArgError, "set not supported for %s", rb_obj_classname(arrayType->rbComponentType)); + return Qnil; + } + + return rbValue; +} + +/* + * call-seq: each + * Yield block for each element of +self+. + */ +static VALUE +inline_array_each(VALUE self) +{ + InlineArray* array; + + int i; + + Data_Get_Struct(self, InlineArray, array); + + for (i = 0; i < array->length; ++i) { + rb_yield(inline_array_aref(self, INT2FIX(i))); + } + + return self; +} + +/* + * call-seq: to_a + * @return [Array] + * Convert +self+ to an array. + */ +static VALUE +inline_array_to_a(VALUE self) +{ + InlineArray* array; + VALUE obj; + int i; + + Data_Get_Struct(self, InlineArray, array); + obj = rb_ary_new2(array->length); + + + for (i = 0; i < array->length; ++i) { + rb_ary_push(obj, inline_array_aref(self, INT2FIX(i))); + } + + return obj; +} + +/* + * Document-method: FFI::StructLayout::CharArray#to_s + * call-seq: to_s + * @return [String] + * Convert +self+ to a string. + */ +static VALUE +inline_array_to_s(VALUE self) +{ + InlineArray* array; + VALUE argv[2]; + + Data_Get_Struct(self, InlineArray, array); + + if (array->componentType->nativeType != NATIVE_INT8 && array->componentType->nativeType != NATIVE_UINT8) { + VALUE dummy = Qnil; + return rb_call_super(0, &dummy); + } + + argv[0] = UINT2NUM(array->field->offset); + argv[1] = UINT2NUM(array->length); + + return rb_funcall2(array->rbMemory, rb_intern("get_string"), 2, argv); +} + +/* + * call-seq: to_ptr + * @return [AbstractMemory] + * Get pointer to +self+ content. + */ +static VALUE +inline_array_to_ptr(VALUE self) +{ + InlineArray* array; + + Data_Get_Struct(self, InlineArray, array); + + return rb_funcall(array->rbMemory, rb_intern("slice"), 2, + UINT2NUM(array->field->offset), UINT2NUM(array->arrayType->base.ffiType->size)); +} + + +void +rbffi_Struct_Init(VALUE moduleFFI) +{ + VALUE StructClass; + + rbffi_StructLayout_Init(moduleFFI); + + /* + * Document-class: FFI::Struct + * + * A FFI::Struct means to mirror a C struct. + * + * A Struct is defined as: + * class MyStruct < FFI::Struct + * layout :value1, :int, + * :value2, :double + * end + * and is used as: + * my_struct = MyStruct.new + * my_struct[:value1] = 12 + * + * For more information, see http://github.com/ffi/ffi/wiki/Structs + */ + rbffi_StructClass = rb_define_class_under(moduleFFI, "Struct", rb_cObject); + StructClass = rbffi_StructClass; // put on a line alone to help RDoc + rb_global_variable(&rbffi_StructClass); + + /* + * Document-class: FFI::Struct::InlineArray + */ + rbffi_StructInlineArrayClass = rb_define_class_under(rbffi_StructClass, "InlineArray", rb_cObject); + rb_global_variable(&rbffi_StructInlineArrayClass); + + /* + * Document-class: FFI::StructLayout::CharArray < FFI::Struct::InlineArray + */ + rbffi_StructLayoutCharArrayClass = rb_define_class_under(rbffi_StructLayoutClass, "CharArray", + rbffi_StructInlineArrayClass); + rb_global_variable(&rbffi_StructLayoutCharArrayClass); + + + rb_define_alloc_func(StructClass, struct_allocate); + rb_define_method(StructClass, "initialize", struct_initialize, -1); + rb_define_method(StructClass, "initialize_copy", struct_initialize_copy, 1); + rb_define_method(StructClass, "order", struct_order, -1); + + rb_define_alias(rb_singleton_class(StructClass), "alloc_in", "new"); + rb_define_alias(rb_singleton_class(StructClass), "alloc_out", "new"); + rb_define_alias(rb_singleton_class(StructClass), "alloc_inout", "new"); + rb_define_alias(rb_singleton_class(StructClass), "new_in", "new"); + rb_define_alias(rb_singleton_class(StructClass), "new_out", "new"); + rb_define_alias(rb_singleton_class(StructClass), "new_inout", "new"); + + rb_define_method(StructClass, "pointer", struct_get_pointer, 0); + rb_define_private_method(StructClass, "pointer=", struct_set_pointer, 1); + + rb_define_method(StructClass, "layout", struct_get_layout, 0); + rb_define_private_method(StructClass, "layout=", struct_set_layout, 1); + + rb_define_method(StructClass, "[]", struct_aref, 1); + rb_define_method(StructClass, "[]=", struct_aset, 2); + rb_define_method(StructClass, "null?", struct_null_p, 0); + + rb_include_module(rbffi_StructInlineArrayClass, rb_mEnumerable); + rb_define_alloc_func(rbffi_StructInlineArrayClass, inline_array_allocate); + rb_define_method(rbffi_StructInlineArrayClass, "initialize", inline_array_initialize, 2); + rb_define_method(rbffi_StructInlineArrayClass, "[]", inline_array_aref, 1); + rb_define_method(rbffi_StructInlineArrayClass, "[]=", inline_array_aset, 2); + rb_define_method(rbffi_StructInlineArrayClass, "each", inline_array_each, 0); + rb_define_method(rbffi_StructInlineArrayClass, "size", inline_array_size, 0); + rb_define_method(rbffi_StructInlineArrayClass, "to_a", inline_array_to_a, 0); + rb_define_method(rbffi_StructInlineArrayClass, "to_ptr", inline_array_to_ptr, 0); + + rb_define_method(rbffi_StructLayoutCharArrayClass, "to_s", inline_array_to_s, 0); + rb_define_alias(rbffi_StructLayoutCharArrayClass, "to_str", "to_s"); + + id_pointer_ivar = rb_intern("@pointer"); + id_layout_ivar = rb_intern("@layout"); + id_layout = rb_intern("layout"); + id_get = rb_intern("get"); + id_put = rb_intern("put"); + id_to_ptr = rb_intern("to_ptr"); + id_to_s = rb_intern("to_s"); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Struct.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Struct.h new file mode 100644 index 0000000..eb6edf2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Struct.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * Copyright (c) 2009, Luc Heinrich + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_STRUCT_H +#define RBFFI_STRUCT_H + +#include "extconf.h" +#include "AbstractMemory.h" +#include "Type.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + + extern void rbffi_Struct_Init(VALUE ffiModule); + extern void rbffi_StructLayout_Init(VALUE ffiModule); + typedef struct StructField_ StructField; + typedef struct StructLayout_ StructLayout; + typedef struct Struct_ Struct; + + struct StructField_ { + Type* type; + unsigned int offset; + + int referenceIndex; + + bool referenceRequired; + VALUE rbType; + VALUE rbName; + + VALUE (*get)(StructField* field, Struct* s); + void (*put)(StructField* field, Struct* s, VALUE value); + + MemoryOp* memoryOp; + }; + + struct StructLayout_ { + Type base; + StructField** fields; + int fieldCount; + int size; + int align; + ffi_type** ffiTypes; + + /* + * We use the fieldName's minor 8 Bits as index to a 256 entry cache. + * This avoids full ruby hash lookups for repeated lookups. + */ + #define FIELD_CACHE_LOOKUP(this, sym) ( &(this)->cache_row[((sym) >> 8) & 0xff] ) + + struct field_cache_entry { + VALUE fieldName; + StructField *field; + } cache_row[0x100]; + + /** The number of reference tracking fields in this struct */ + int referenceFieldCount; + + VALUE rbFieldNames; + VALUE rbFieldMap; + VALUE rbFields; + }; + + struct Struct_ { + StructLayout* layout; + AbstractMemory* pointer; + VALUE* rbReferences; + + VALUE rbLayout; + VALUE rbPointer; + }; + + extern VALUE rbffi_StructClass, rbffi_StructLayoutClass; + extern VALUE rbffi_StructLayoutFieldClass, rbffi_StructLayoutFunctionFieldClass; + extern VALUE rbffi_StructLayoutArrayFieldClass; + extern VALUE rbffi_StructInlineArrayClass; + extern VALUE rbffi_StructLayoutCharArrayClass; + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_STRUCT_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Struct.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Struct.o new file mode 100644 index 0000000..a08f609 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Struct.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructByValue.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructByValue.c new file mode 100644 index 0000000..a3255f4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructByValue.c @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MSC_VER +#include +#endif +#include +#include +#include +#include +#include +#include + +#include +#include "rbffi.h" +#include "compat.h" + +#include "Type.h" +#include "StructByValue.h" +#include "Struct.h" + +#define FFI_ALIGN(v, a) (((((size_t) (v))-1) | ((a)-1))+1) + +static VALUE sbv_allocate(VALUE); +static VALUE sbv_initialize(VALUE, VALUE); +static void sbv_mark(StructByValue *); +static void sbv_free(StructByValue *); + +VALUE rbffi_StructByValueClass = Qnil; + +static VALUE +sbv_allocate(VALUE klass) +{ + StructByValue* sbv; + + VALUE obj = Data_Make_Struct(klass, StructByValue, sbv_mark, sbv_free, sbv); + + sbv->rbStructClass = Qnil; + sbv->rbStructLayout = Qnil; + sbv->base.nativeType = NATIVE_STRUCT; + + sbv->base.ffiType = xcalloc(1, sizeof(*sbv->base.ffiType)); + sbv->base.ffiType->size = 0; + sbv->base.ffiType->alignment = 1; + sbv->base.ffiType->type = FFI_TYPE_STRUCT; + + return obj; +} + +static VALUE +sbv_initialize(VALUE self, VALUE rbStructClass) +{ + StructByValue* sbv = NULL; + StructLayout* layout = NULL; + VALUE rbLayout = Qnil; + + rbLayout = rb_ivar_get(rbStructClass, rb_intern("@layout")); + if (!rb_obj_is_instance_of(rbLayout, rbffi_StructLayoutClass)) { + rb_raise(rb_eTypeError, "wrong type in @layout ivar (expected FFI::StructLayout)"); + } + + Data_Get_Struct(rbLayout, StructLayout, layout); + Data_Get_Struct(self, StructByValue, sbv); + sbv->rbStructClass = rbStructClass; + sbv->rbStructLayout = rbLayout; + + /* We can just use everything from the ffi_type directly */ + *sbv->base.ffiType = *layout->base.ffiType; + + return self; +} + +static void +sbv_mark(StructByValue *sbv) +{ + rb_gc_mark(sbv->rbStructClass); + rb_gc_mark(sbv->rbStructLayout); +} + +static void +sbv_free(StructByValue *sbv) +{ + xfree(sbv->base.ffiType); + xfree(sbv); +} + + +static VALUE +sbv_layout(VALUE self) +{ + StructByValue* sbv; + + Data_Get_Struct(self, StructByValue, sbv); + return sbv->rbStructLayout; +} + +static VALUE +sbv_struct_class(VALUE self) +{ + StructByValue* sbv; + + Data_Get_Struct(self, StructByValue, sbv); + + return sbv->rbStructClass; +} + +void +rbffi_StructByValue_Init(VALUE moduleFFI) +{ + rbffi_StructByValueClass = rb_define_class_under(moduleFFI, "StructByValue", rbffi_TypeClass); + rb_global_variable(&rbffi_StructByValueClass); + rb_define_const(rbffi_TypeClass, "Struct", rbffi_StructByValueClass); + + rb_define_alloc_func(rbffi_StructByValueClass, sbv_allocate); + rb_define_method(rbffi_StructByValueClass, "initialize", sbv_initialize, 1); + rb_define_method(rbffi_StructByValueClass, "layout", sbv_layout, 0); + rb_define_method(rbffi_StructByValueClass, "struct_class", sbv_struct_class, 0); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructByValue.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructByValue.h new file mode 100644 index 0000000..07b2763 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructByValue.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_STRUCTBYVALUE_H +#define RBFFI_STRUCTBYVALUE_H + +#include +#include "Type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct StructByValue_ { + Type base; + VALUE rbStructClass; + VALUE rbStructLayout; +} StructByValue; + +void rbffi_StructByValue_Init(VALUE moduleFFI); + +extern VALUE rbffi_StructByValueClass; + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_STRUCTBYVALUE_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructByValue.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructByValue.o new file mode 100644 index 0000000..bd12004 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructByValue.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructLayout.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructLayout.c new file mode 100644 index 0000000..d318b8c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructLayout.c @@ -0,0 +1,700 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * Copyright (c) 2009, Luc Heinrich + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include + +#ifndef _MSC_VER +# include +#endif +#include +#include +#include +#include "rbffi.h" +#include "compat.h" +#include "AbstractMemory.h" +#include "Pointer.h" +#include "MemoryPointer.h" +#include "Function.h" +#include "Types.h" +#include "StructByValue.h" +#include "ArrayType.h" +#include "Function.h" +#include "MappedType.h" +#include "Struct.h" + +#define FFI_ALIGN(v, a) (((((size_t) (v))-1) | ((a)-1))+1) + +static void struct_layout_mark(StructLayout *); +static void struct_layout_free(StructLayout *); +static void struct_field_mark(StructField* ); + +VALUE rbffi_StructLayoutFieldClass = Qnil; +VALUE rbffi_StructLayoutNumberFieldClass = Qnil, rbffi_StructLayoutPointerFieldClass = Qnil; +VALUE rbffi_StructLayoutStringFieldClass = Qnil; +VALUE rbffi_StructLayoutFunctionFieldClass = Qnil, rbffi_StructLayoutArrayFieldClass = Qnil; + +VALUE rbffi_StructLayoutClass = Qnil; + + +static VALUE +struct_field_allocate(VALUE klass) +{ + StructField* field; + VALUE obj; + + obj = Data_Make_Struct(klass, StructField, struct_field_mark, -1, field); + field->rbType = Qnil; + field->rbName = Qnil; + + return obj; +} + +static void +struct_field_mark(StructField* f) +{ + rb_gc_mark(f->rbType); + rb_gc_mark(f->rbName); +} + +/* + * call-seq: initialize(name, offset, type) + * @param [String,Symbol] name + * @param [Fixnum] offset + * @param [FFI::Type] type + * @return [self] + * A new FFI::StructLayout::Field instance. + */ +static VALUE +struct_field_initialize(int argc, VALUE* argv, VALUE self) +{ + VALUE rbOffset = Qnil, rbName = Qnil, rbType = Qnil; + StructField* field; + int nargs; + + Data_Get_Struct(self, StructField, field); + + nargs = rb_scan_args(argc, argv, "3", &rbName, &rbOffset, &rbType); + + if (TYPE(rbName) != T_SYMBOL && TYPE(rbName) != T_STRING) { + rb_raise(rb_eTypeError, "wrong argument type %s (expected Symbol/String)", + rb_obj_classname(rbName)); + } + + Check_Type(rbOffset, T_FIXNUM); + + if (!rb_obj_is_kind_of(rbType, rbffi_TypeClass)) { + rb_raise(rb_eTypeError, "wrong argument type %s (expected FFI::Type)", + rb_obj_classname(rbType)); + } + + field->offset = NUM2UINT(rbOffset); + field->rbName = (TYPE(rbName) == T_SYMBOL) ? rbName : rb_str_intern(rbName); + field->rbType = rbType; + Data_Get_Struct(field->rbType, Type, field->type); + field->memoryOp = get_memory_op(field->type); + field->referenceIndex = -1; + + switch (field->type->nativeType == NATIVE_MAPPED ? ((MappedType *) field->type)->type->nativeType : field->type->nativeType) { + case NATIVE_FUNCTION: + case NATIVE_POINTER: + field->referenceRequired = true; + break; + + default: + field->referenceRequired = (rb_respond_to(self, rb_intern("reference_required?")) + && RTEST(rb_funcall2(self, rb_intern("reference_required?"), 0, NULL))) + || (rb_respond_to(rbType, rb_intern("reference_required?")) + && RTEST(rb_funcall2(rbType, rb_intern("reference_required?"), 0, NULL))); + break; + } + + return self; +} + +/* + * call-seq: offset + * @return [Numeric] + * Get the field offset. + */ +static VALUE +struct_field_offset(VALUE self) +{ + StructField* field; + Data_Get_Struct(self, StructField, field); + return UINT2NUM(field->offset); +} + +/* + * call-seq: size + * @return [Numeric] + * Get the field size. + */ +static VALUE +struct_field_size(VALUE self) +{ + StructField* field; + Data_Get_Struct(self, StructField, field); + return UINT2NUM(field->type->ffiType->size); +} + +/* + * call-seq: alignment + * @return [Numeric] + * Get the field alignment. + */ +static VALUE +struct_field_alignment(VALUE self) +{ + StructField* field; + Data_Get_Struct(self, StructField, field); + return UINT2NUM(field->type->ffiType->alignment); +} + +/* + * call-seq: type + * @return [Type] + * Get the field type. + */ +static VALUE +struct_field_type(VALUE self) +{ + StructField* field; + Data_Get_Struct(self, StructField, field); + + return field->rbType; +} + +/* + * call-seq: name + * @return [Symbol] + * Get the field name. + */ +static VALUE +struct_field_name(VALUE self) +{ + StructField* field; + Data_Get_Struct(self, StructField, field); + return field->rbName; +} + +/* + * call-seq: get(pointer) + * @param [AbstractMemory] pointer pointer on a {Struct} + * @return [Object] + * Get an object of type {#type} from memory pointed by +pointer+. + */ +static VALUE +struct_field_get(VALUE self, VALUE pointer) +{ + StructField* f; + + Data_Get_Struct(self, StructField, f); + if (f->memoryOp == NULL) { + rb_raise(rb_eArgError, "get not supported for %s", rb_obj_classname(f->rbType)); + return Qnil; + } + + return (*f->memoryOp->get)(MEMORY(pointer), f->offset); +} + +/* + * call-seq: put(pointer, value) + * @param [AbstractMemory] pointer pointer on a {Struct} + * @param [Object] value this object must be a kind of {#type} + * @return [self] + * Put an object to memory pointed by +pointer+. + */ +static VALUE +struct_field_put(VALUE self, VALUE pointer, VALUE value) +{ + StructField* f; + + Data_Get_Struct(self, StructField, f); + if (f->memoryOp == NULL) { + rb_raise(rb_eArgError, "put not supported for %s", rb_obj_classname(f->rbType)); + return self; + } + + (*f->memoryOp->put)(MEMORY(pointer), f->offset, value); + + return self; +} + +/* + * call-seq: get(pointer) + * @param [AbstractMemory] pointer pointer on a {Struct} + * @return [Function] + * Get a {Function} from memory pointed by +pointer+. + */ +static VALUE +function_field_get(VALUE self, VALUE pointer) +{ + StructField* f; + + Data_Get_Struct(self, StructField, f); + + return rbffi_Function_NewInstance(f->rbType, (*rbffi_AbstractMemoryOps.pointer->get)(MEMORY(pointer), f->offset)); +} + +/* + * call-seq: put(pointer, proc) + * @param [AbstractMemory] pointer pointer to a {Struct} + * @param [Function, Proc] proc + * @return [Function] + * Set a {Function} to memory pointed by +pointer+ as a function. + * + * If a Proc is submitted as +proc+, it is automatically transformed to a {Function}. + */ +static VALUE +function_field_put(VALUE self, VALUE pointer, VALUE proc) +{ + StructField* f; + VALUE value = Qnil; + + Data_Get_Struct(self, StructField, f); + + if (NIL_P(proc) || rb_obj_is_kind_of(proc, rbffi_FunctionClass)) { + value = proc; + } else if (rb_obj_is_kind_of(proc, rb_cProc) || rb_respond_to(proc, rb_intern("call"))) { + value = rbffi_Function_ForProc(f->rbType, proc); + } else { + rb_raise(rb_eTypeError, "wrong type (expected Proc or Function)"); + } + + (*rbffi_AbstractMemoryOps.pointer->put)(MEMORY(pointer), f->offset, value); + + return self; +} + +static inline bool +isCharArray(ArrayType* arrayType) +{ + return arrayType->componentType->nativeType == NATIVE_INT8 + || arrayType->componentType->nativeType == NATIVE_UINT8; +} + +/* + * call-seq: get(pointer) + * @param [AbstractMemory] pointer pointer on a {Struct} + * @return [FFI::StructLayout::CharArray, FFI::Struct::InlineArray] + * Get an array from a {Struct}. + */ +static VALUE +array_field_get(VALUE self, VALUE pointer) +{ + StructField* f; + ArrayType* array; + VALUE argv[2]; + + Data_Get_Struct(self, StructField, f); + Data_Get_Struct(f->rbType, ArrayType, array); + + argv[0] = pointer; + argv[1] = self; + + return rb_class_new_instance(2, argv, isCharArray(array) + ? rbffi_StructLayoutCharArrayClass : rbffi_StructInlineArrayClass); +} + +/* + * call-seq: put(pointer, value) + * @param [AbstractMemory] pointer pointer on a {Struct} + * @param [String, Array] value +value+ may be a String only if array's type is a kind of +int8+ + * @return [value] + * Set an array in a {Struct}. + */ +static VALUE +array_field_put(VALUE self, VALUE pointer, VALUE value) +{ + StructField* f; + ArrayType* array; + + + Data_Get_Struct(self, StructField, f); + Data_Get_Struct(f->rbType, ArrayType, array); + + if (isCharArray(array) && rb_obj_is_instance_of(value, rb_cString)) { + VALUE argv[2]; + + argv[0] = INT2FIX(f->offset); + argv[1] = value; + + if (RSTRING_LEN(value) < array->length) { + rb_funcall2(pointer, rb_intern("put_string"), 2, argv); + } else if (RSTRING_LEN(value) == array->length) { + rb_funcall2(pointer, rb_intern("put_bytes"), 2, argv); + } else { + rb_raise(rb_eIndexError, "String is longer (%ld bytes) than the char array (%d bytes)", RSTRING_LEN(value), array->length); + } + } else { +#ifdef notyet + MemoryOp* op; + int count = RARRAY_LEN(value); + int i; + AbstractMemory* memory = MEMORY(pointer); + + if (count > array->length) { + rb_raise(rb_eIndexError, "array too large"); + } + + /* clear the contents in case of a short write */ + checkWrite(memory); + checkBounds(memory, f->offset, f->type->ffiType->size); + if (count < array->length) { + memset(memory->address + f->offset + (count * array->componentType->ffiType->size), + 0, (array->length - count) * array->componentType->ffiType->size); + } + + /* now copy each element in */ + if ((op = get_memory_op(array->componentType)) != NULL) { + + for (i = 0; i < count; ++i) { + (*op->put)(memory, f->offset + (i * array->componentType->ffiType->size), rb_ary_entry(value, i)); + } + + } else if (array->componentType->nativeType == NATIVE_STRUCT) { + + for (i = 0; i < count; ++i) { + VALUE entry = rb_ary_entry(value, i); + Struct* s; + + if (!rb_obj_is_kind_of(entry, rbffi_StructClass)) { + rb_raise(rb_eTypeError, "array element not an instance of FFI::Struct"); + break; + } + + Data_Get_Struct(entry, Struct, s); + checkRead(s->pointer); + checkBounds(s->pointer, 0, array->componentType->ffiType->size); + + memcpy(memory->address + f->offset + (i * array->componentType->ffiType->size), + s->pointer->address, array->componentType->ffiType->size); + } + + } else { + rb_raise(rb_eNotImpError, "put not supported for arrays of type %s", rb_obj_classname(array->rbComponentType)); + } +#else + rb_raise(rb_eNotImpError, "cannot set array field"); +#endif + } + + return value; +} + + +static VALUE +struct_layout_allocate(VALUE klass) +{ + StructLayout* layout; + VALUE obj; + + obj = Data_Make_Struct(klass, StructLayout, struct_layout_mark, struct_layout_free, layout); + layout->rbFieldMap = Qnil; + layout->rbFieldNames = Qnil; + layout->rbFields = Qnil; + layout->base.ffiType = xcalloc(1, sizeof(*layout->base.ffiType)); + layout->base.ffiType->size = 0; + layout->base.ffiType->alignment = 0; + layout->base.ffiType->type = FFI_TYPE_STRUCT; + + return obj; +} + +/* + * call-seq: initialize(fields, size, align) + * @param [Array] fields + * @param [Numeric] size + * @param [Numeric] align + * @return [self] + * A new StructLayout instance. + */ +static VALUE +struct_layout_initialize(VALUE self, VALUE fields, VALUE size, VALUE align) +{ + StructLayout* layout; + ffi_type* ltype; + int i; + + Data_Get_Struct(self, StructLayout, layout); + layout->fieldCount = (int) RARRAY_LEN(fields); + layout->rbFieldMap = rb_hash_new(); + layout->rbFieldNames = rb_ary_new2(layout->fieldCount); + layout->size = (int) FFI_ALIGN(NUM2INT(size), NUM2INT(align)); + layout->align = NUM2INT(align); + layout->fields = xcalloc(layout->fieldCount, sizeof(StructField *)); + layout->ffiTypes = xcalloc(layout->fieldCount + 1, sizeof(ffi_type *)); + layout->rbFields = rb_ary_new2(layout->fieldCount); + layout->referenceFieldCount = 0; + layout->base.ffiType->elements = layout->ffiTypes; + layout->base.ffiType->size = layout->size; + layout->base.ffiType->alignment = layout->align; + + ltype = layout->base.ffiType; + for (i = 0; i < (int) layout->fieldCount; ++i) { + VALUE rbField = rb_ary_entry(fields, i); + VALUE rbName; + StructField* field; + ffi_type* ftype; + + + if (!rb_obj_is_kind_of(rbField, rbffi_StructLayoutFieldClass)) { + rb_raise(rb_eTypeError, "wrong type for field %d.", i); + } + rbName = rb_funcall2(rbField, rb_intern("name"), 0, NULL); + + Data_Get_Struct(rbField, StructField, field); + layout->fields[i] = field; + + if (field->type == NULL || field->type->ffiType == NULL) { + rb_raise(rb_eRuntimeError, "type of field %d not supported", i); + } + + ftype = field->type->ffiType; + if (ftype->size == 0 && i < ((int) layout->fieldCount - 1)) { + rb_raise(rb_eTypeError, "type of field %d has zero size", i); + } + + if (field->referenceRequired) { + field->referenceIndex = layout->referenceFieldCount++; + } + + + layout->ffiTypes[i] = ftype->size > 0 ? ftype : NULL; + rb_hash_aset(layout->rbFieldMap, rbName, rbField); + rb_ary_push(layout->rbFields, rbField); + rb_ary_push(layout->rbFieldNames, rbName); + } + + if (ltype->size == 0) { + rb_raise(rb_eRuntimeError, "Struct size is zero"); + } + + return self; +} + +/* + * call-seq: [](field) + * @param [Symbol] field + * @return [StructLayout::Field] + * Get a field from the layout. + */ +static VALUE +struct_layout_union_bang(VALUE self) +{ + const ffi_type *alignment_types[] = { &ffi_type_sint8, &ffi_type_sint16, &ffi_type_sint32, &ffi_type_sint64, + &ffi_type_float, &ffi_type_double, &ffi_type_longdouble, NULL }; + StructLayout* layout; + ffi_type *t = NULL; + int count, i; + + Data_Get_Struct(self, StructLayout, layout); + + for (i = 0; alignment_types[i] != NULL; ++i) { + if (alignment_types[i]->alignment == layout->align) { + t = (ffi_type *) alignment_types[i]; + break; + } + } + if (t == NULL) { + rb_raise(rb_eRuntimeError, "cannot create libffi union representation for alignment %d", layout->align); + return Qnil; + } + + count = (int) layout->size / (int) t->size; + xfree(layout->ffiTypes); + layout->ffiTypes = xcalloc(count + 1, sizeof(ffi_type *)); + layout->base.ffiType->elements = layout->ffiTypes; + + for (i = 0; i < count; ++i) { + layout->ffiTypes[i] = t; + } + + return self; +} + +static VALUE +struct_layout_aref(VALUE self, VALUE field) +{ + StructLayout* layout; + + Data_Get_Struct(self, StructLayout, layout); + + return rb_hash_aref(layout->rbFieldMap, field); +} + +/* + * call-seq: fields + * @return [Array] + * Get fields list. + */ +static VALUE +struct_layout_fields(VALUE self) +{ + StructLayout* layout; + + Data_Get_Struct(self, StructLayout, layout); + + return rb_ary_dup(layout->rbFields); +} + +/* + * call-seq: members + * @return [Array] + * Get list of field names. + */ +static VALUE +struct_layout_members(VALUE self) +{ + StructLayout* layout; + + Data_Get_Struct(self, StructLayout, layout); + + return rb_ary_dup(layout->rbFieldNames); +} + +/* + * call-seq: to_a + * @return [Array] + * Get an array of fields. + */ +static VALUE +struct_layout_to_a(VALUE self) +{ + StructLayout* layout; + + Data_Get_Struct(self, StructLayout, layout); + + return rb_ary_dup(layout->rbFields); +} + +static void +struct_layout_mark(StructLayout *layout) +{ + rb_gc_mark(layout->rbFieldMap); + rb_gc_mark(layout->rbFieldNames); + rb_gc_mark(layout->rbFields); + /* Clear the cache, to be safe from changes of fieldName VALUE by GC.compact. + * TODO: Move cache clearing to compactation callback provided by Ruby-2.7+. + */ + memset(&layout->cache_row, 0, sizeof(layout->cache_row)); +} + +static void +struct_layout_free(StructLayout *layout) +{ + xfree(layout->ffiTypes); + xfree(layout->base.ffiType); + xfree(layout->fields); + xfree(layout); +} + + +void +rbffi_StructLayout_Init(VALUE moduleFFI) +{ + VALUE ffi_Type = rbffi_TypeClass; + + /* + * Document-class: FFI::StructLayout < FFI::Type + * + * This class aims at defining a struct layout. + */ + rbffi_StructLayoutClass = rb_define_class_under(moduleFFI, "StructLayout", ffi_Type); + rb_global_variable(&rbffi_StructLayoutClass); + + /* + * Document-class: FFI::StructLayout::Field + * A field in a {StructLayout}. + */ + rbffi_StructLayoutFieldClass = rb_define_class_under(rbffi_StructLayoutClass, "Field", rb_cObject); + rb_global_variable(&rbffi_StructLayoutFieldClass); + + /* + * Document-class: FFI::StructLayout::Number + * A numeric {Field} in a {StructLayout}. + */ + rbffi_StructLayoutNumberFieldClass = rb_define_class_under(rbffi_StructLayoutClass, "Number", rbffi_StructLayoutFieldClass); + rb_global_variable(&rbffi_StructLayoutNumberFieldClass); + + /* + * Document-class: FFI::StructLayout::String + * A string {Field} in a {StructLayout}. + */ + rbffi_StructLayoutStringFieldClass = rb_define_class_under(rbffi_StructLayoutClass, "String", rbffi_StructLayoutFieldClass); + rb_global_variable(&rbffi_StructLayoutStringFieldClass); + + /* + * Document-class: FFI::StructLayout::Pointer + * A pointer {Field} in a {StructLayout}. + */ + rbffi_StructLayoutPointerFieldClass = rb_define_class_under(rbffi_StructLayoutClass, "Pointer", rbffi_StructLayoutFieldClass); + rb_global_variable(&rbffi_StructLayoutPointerFieldClass); + + /* + * Document-class: FFI::StructLayout::Function + * A function pointer {Field} in a {StructLayout}. + */ + rbffi_StructLayoutFunctionFieldClass = rb_define_class_under(rbffi_StructLayoutClass, "Function", rbffi_StructLayoutFieldClass); + rb_global_variable(&rbffi_StructLayoutFunctionFieldClass); + + /* + * Document-class: FFI::StructLayout::Array + * An array {Field} in a {StructLayout}. + */ + rbffi_StructLayoutArrayFieldClass = rb_define_class_under(rbffi_StructLayoutClass, "Array", rbffi_StructLayoutFieldClass); + rb_global_variable(&rbffi_StructLayoutArrayFieldClass); + + rb_define_alloc_func(rbffi_StructLayoutFieldClass, struct_field_allocate); + rb_define_method(rbffi_StructLayoutFieldClass, "initialize", struct_field_initialize, -1); + rb_define_method(rbffi_StructLayoutFieldClass, "offset", struct_field_offset, 0); + rb_define_method(rbffi_StructLayoutFieldClass, "size", struct_field_size, 0); + rb_define_method(rbffi_StructLayoutFieldClass, "alignment", struct_field_alignment, 0); + rb_define_method(rbffi_StructLayoutFieldClass, "name", struct_field_name, 0); + rb_define_method(rbffi_StructLayoutFieldClass, "type", struct_field_type, 0); + rb_define_method(rbffi_StructLayoutFieldClass, "put", struct_field_put, 2); + rb_define_method(rbffi_StructLayoutFieldClass, "get", struct_field_get, 1); + + rb_define_method(rbffi_StructLayoutFunctionFieldClass, "put", function_field_put, 2); + rb_define_method(rbffi_StructLayoutFunctionFieldClass, "get", function_field_get, 1); + + rb_define_method(rbffi_StructLayoutArrayFieldClass, "get", array_field_get, 1); + rb_define_method(rbffi_StructLayoutArrayFieldClass, "put", array_field_put, 2); + + rb_define_alloc_func(rbffi_StructLayoutClass, struct_layout_allocate); + rb_define_method(rbffi_StructLayoutClass, "initialize", struct_layout_initialize, 3); + rb_define_method(rbffi_StructLayoutClass, "[]", struct_layout_aref, 1); + rb_define_method(rbffi_StructLayoutClass, "fields", struct_layout_fields, 0); + rb_define_method(rbffi_StructLayoutClass, "members", struct_layout_members, 0); + rb_define_method(rbffi_StructLayoutClass, "to_a", struct_layout_to_a, 0); + rb_define_method(rbffi_StructLayoutClass, "__union!", struct_layout_union_bang, 0); + +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructLayout.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructLayout.o new file mode 100644 index 0000000..e94186a Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/StructLayout.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Thread.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Thread.c new file mode 100644 index 0000000..f6a8387 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Thread.c @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2010 Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include + +#if defined(__CYGWIN__) || !defined(_WIN32) +# include +# include +# include +# include +#else +# include +# define _WINSOCKAPI_ +# include +#endif +#include +#include "Thread.h" + +#ifdef _WIN32 +static volatile DWORD frame_thread_key = TLS_OUT_OF_INDEXES; +#else +static pthread_key_t thread_data_key; +struct thread_data { + rbffi_frame_t* frame; +}; +static inline struct thread_data* thread_data_get(void); + +#endif + +rbffi_frame_t* +rbffi_frame_current(void) +{ +#ifdef _WIN32 + return (rbffi_frame_t *) TlsGetValue(frame_thread_key); +#else + struct thread_data* td = (struct thread_data *) pthread_getspecific(thread_data_key); + return td != NULL ? td->frame : NULL; +#endif +} + +void +rbffi_frame_push(rbffi_frame_t* frame) +{ + memset(frame, 0, sizeof(*frame)); + frame->exc = Qnil; + +#ifdef _WIN32 + frame->prev = TlsGetValue(frame_thread_key); + TlsSetValue(frame_thread_key, frame); +#else + frame->td = thread_data_get(); + frame->prev = frame->td->frame; + frame->td->frame = frame; +#endif +} + +void +rbffi_frame_pop(rbffi_frame_t* frame) +{ +#ifdef _WIN32 + TlsSetValue(frame_thread_key, frame->prev); +#else + frame->td->frame = frame->prev; +#endif +} + +#ifndef _WIN32 +static struct thread_data* thread_data_init(void); + +static inline struct thread_data* +thread_data_get(void) +{ + struct thread_data* td = (struct thread_data *) pthread_getspecific(thread_data_key); + return td != NULL ? td : thread_data_init(); +} + +static struct thread_data* +thread_data_init(void) +{ + struct thread_data* td = calloc(1, sizeof(struct thread_data)); + + pthread_setspecific(thread_data_key, td); + + return td; +} + +static void +thread_data_free(void *ptr) +{ + free(ptr); +} +#endif + +void +rbffi_Thread_Init(VALUE moduleFFI) +{ +#ifdef _WIN32 + frame_thread_key = TlsAlloc(); +#else + pthread_key_create(&thread_data_key, thread_data_free); +#endif +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Thread.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Thread.h new file mode 100644 index 0000000..8c335e4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Thread.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2010 Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_THREAD_H +#define RBFFI_THREAD_H + +#include +#include +#include "extconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +#ifdef _WIN32 +# include +#else +# include +#endif + +typedef struct { +#ifdef _WIN32 + DWORD id; +#else + pthread_t id; +#endif + bool valid; + bool has_gvl; + VALUE exc; +} rbffi_thread_t; + +typedef struct rbffi_frame { +#ifndef _WIN32 + struct thread_data* td; +#endif + struct rbffi_frame* prev; + VALUE exc; +} rbffi_frame_t; + +rbffi_frame_t* rbffi_frame_current(void); +void rbffi_frame_push(rbffi_frame_t* frame); +void rbffi_frame_pop(rbffi_frame_t* frame); + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_THREAD_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Thread.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Thread.o new file mode 100644 index 0000000..3068c3c Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Thread.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Type.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Type.c new file mode 100644 index 0000000..7776bb0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Type.c @@ -0,0 +1,379 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MSC_VER +# include +#endif + +#include +#include +#include +#include "rbffi.h" +#include "compat.h" +#include "Types.h" +#include "Type.h" + + +typedef struct BuiltinType_ { + Type type; + char* name; +} BuiltinType; + +static void builtin_type_free(BuiltinType *); + +VALUE rbffi_TypeClass = Qnil; + +static VALUE classBuiltinType = Qnil; +static VALUE moduleNativeType = Qnil; +static VALUE typeMap = Qnil, sizeMap = Qnil; +static ID id_find_type = 0, id_type_size = 0, id_size = 0; + +static VALUE +type_allocate(VALUE klass) +{ + Type* type; + VALUE obj = Data_Make_Struct(klass, Type, NULL, -1, type); + + type->nativeType = -1; + type->ffiType = &ffi_type_void; + + return obj; +} + +/* + * Document-method: initialize + * call-seq: initialize(value) + * @param [Fixnum,Type] value + * @return [self] + */ +static VALUE +type_initialize(VALUE self, VALUE value) +{ + Type* type; + Type* other; + + Data_Get_Struct(self, Type, type); + + if (FIXNUM_P(value)) { + type->nativeType = FIX2INT(value); + } else if (rb_obj_is_kind_of(value, rbffi_TypeClass)) { + Data_Get_Struct(value, Type, other); + type->nativeType = other->nativeType; + type->ffiType = other->ffiType; + } else { + rb_raise(rb_eArgError, "wrong type"); + } + + return self; +} + +/* + * call-seq: type.size + * @return [Fixnum] + * Return type's size, in bytes. + */ +static VALUE +type_size(VALUE self) +{ + Type *type; + + Data_Get_Struct(self, Type, type); + + return INT2FIX(type->ffiType->size); +} + +/* + * call-seq: type.alignment + * @return [Fixnum] + * Get Type alignment. + */ +static VALUE +type_alignment(VALUE self) +{ + Type *type; + + Data_Get_Struct(self, Type, type); + + return INT2FIX(type->ffiType->alignment); +} + +/* + * call-seq: type.inspect + * @return [String] + * Inspect {Type} object. + */ +static VALUE +type_inspect(VALUE self) +{ + char buf[100]; + Type *type; + + Data_Get_Struct(self, Type, type); + + snprintf(buf, sizeof(buf), "#<%s:%p size=%d alignment=%d>", + rb_obj_classname(self), type, (int) type->ffiType->size, (int) type->ffiType->alignment); + + return rb_str_new2(buf); +} + +static VALUE +builtin_type_new(VALUE klass, int nativeType, ffi_type* ffiType, const char* name) +{ + BuiltinType* type; + VALUE obj = Qnil; + + obj = Data_Make_Struct(klass, BuiltinType, NULL, builtin_type_free, type); + + type->name = strdup(name); + type->type.nativeType = nativeType; + type->type.ffiType = ffiType; + + return obj; +} + +static void +builtin_type_free(BuiltinType *type) +{ + free(type->name); + xfree(type); +} + +/* + * call-seq: type.inspect + * @return [String] + * Inspect {Type::Builtin} object. + */ +static VALUE +builtin_type_inspect(VALUE self) +{ + char buf[100]; + BuiltinType *type; + + Data_Get_Struct(self, BuiltinType, type); + snprintf(buf, sizeof(buf), "#<%s:%s size=%d alignment=%d>", + rb_obj_classname(self), type->name, (int) type->type.ffiType->size, type->type.ffiType->alignment); + + return rb_str_new2(buf); +} + +int +rbffi_type_size(VALUE type) +{ + int t = TYPE(type); + + if (t == T_FIXNUM || t == T_BIGNUM) { + return NUM2INT(type); + + } else if (t == T_SYMBOL) { + /* + * Try looking up directly in the type and size maps + */ + VALUE nType; + if ((nType = rb_hash_lookup(typeMap, type)) != Qnil) { + if (rb_obj_is_kind_of(nType, rbffi_TypeClass)) { + Type* type; + Data_Get_Struct(nType, Type, type); + return (int) type->ffiType->size; + + } else if (rb_respond_to(nType, id_size)) { + return NUM2INT(rb_funcall2(nType, id_size, 0, NULL)); + } + } + + /* Not found - call up to the ruby version to resolve */ + return NUM2INT(rb_funcall2(rbffi_FFIModule, id_type_size, 1, &type)); + + } else { + return NUM2INT(rb_funcall2(type, id_size, 0, NULL)); + } +} + +VALUE +rbffi_Type_Lookup(VALUE name) +{ + int t = TYPE(name); + if (t == T_SYMBOL || t == T_STRING) { + /* + * Try looking up directly in the type Map + */ + VALUE nType; + if ((nType = rb_hash_lookup(typeMap, name)) != Qnil && rb_obj_is_kind_of(nType, rbffi_TypeClass)) { + return nType; + } + } else if (rb_obj_is_kind_of(name, rbffi_TypeClass)) { + + return name; + } + + /* Nothing found - let caller handle raising exceptions */ + return Qnil; +} + +void +rbffi_Type_Init(VALUE moduleFFI) +{ + /* + * Document-class: FFI::Type + * This class manages C types. + * + * It embbed {FFI::Type::Builtin} objects as constants (for names, + * see {FFI::NativeType}). + */ + rbffi_TypeClass = rb_define_class_under(moduleFFI, "Type", rb_cObject); + + /* + * Document-constant: FFI::TypeDefs + */ + rb_define_const(moduleFFI, "TypeDefs", typeMap = rb_hash_new()); + rb_define_const(moduleFFI, "SizeTypes", sizeMap = rb_hash_new()); + rb_global_variable(&typeMap); + rb_global_variable(&sizeMap); + id_find_type = rb_intern("find_type"); + id_type_size = rb_intern("type_size"); + id_size = rb_intern("size"); + + /* + * Document-class: FFI::Type::Builtin + * Class for Built-in types. + */ + classBuiltinType = rb_define_class_under(rbffi_TypeClass, "Builtin", rbffi_TypeClass); + /* + * Document-module: FFI::NativeType + * This module defines constants for native (C) types. + * + * ==Native type constants + * Native types are defined by constants : + * * INT8, SCHAR, CHAR + * * UINT8, UCHAR + * * INT16, SHORT, SSHORT + * * UINT16, USHORT + * * INT32,, INT, SINT + * * UINT32, UINT + * * INT64, LONG_LONG, SLONG_LONG + * * UINT64, ULONG_LONG + * * LONG, SLONG + * * ULONG + * * FLOAT32, FLOAT + * * FLOAT64, DOUBLE + * * POINTER + * * CALLBACK + * * FUNCTION + * * CHAR_ARRAY + * * BOOL + * * STRING (immutable string, nul terminated) + * * STRUCT (struct-b-value param or result) + * * ARRAY (array type definition) + * * MAPPED (custom native type) + * For function return type only : + * * VOID + * For function argument type only : + * * BUFFER_IN + * * BUFFER_OUT + * * VARARGS (function takes a variable number of arguments) + * + * All these constants are exported to {FFI} module prefixed with "TYPE_". + * They are objets from {FFI::Type::Builtin} class. + */ + moduleNativeType = rb_define_module_under(moduleFFI, "NativeType"); + + /* + * Document-global: FFI::Type + */ + rb_global_variable(&rbffi_TypeClass); + rb_global_variable(&classBuiltinType); + rb_global_variable(&moduleNativeType); + + rb_define_alloc_func(rbffi_TypeClass, type_allocate); + rb_define_method(rbffi_TypeClass, "initialize", type_initialize, 1); + rb_define_method(rbffi_TypeClass, "size", type_size, 0); + rb_define_method(rbffi_TypeClass, "alignment", type_alignment, 0); + rb_define_method(rbffi_TypeClass, "inspect", type_inspect, 0); + + /* Make Type::Builtin non-allocatable */ + rb_undef_method(CLASS_OF(classBuiltinType), "new"); + rb_define_method(classBuiltinType, "inspect", builtin_type_inspect, 0); + + rb_global_variable(&rbffi_TypeClass); + rb_global_variable(&classBuiltinType); + + /* Define all the builtin types */ + #define T(x, ffiType) do { \ + VALUE t = Qnil; \ + rb_define_const(rbffi_TypeClass, #x, t = builtin_type_new(classBuiltinType, NATIVE_##x, ffiType, #x)); \ + rb_define_const(moduleNativeType, #x, t); \ + rb_define_const(moduleFFI, "TYPE_" #x, t); \ + } while(0) + + #define A(old_type, new_type) do { \ + VALUE t = rb_const_get(rbffi_TypeClass, rb_intern(#old_type)); \ + rb_const_set(rbffi_TypeClass, rb_intern(#new_type), t); \ + } while(0) + + /* + * Document-constant: FFI::Type::Builtin::VOID + */ + T(VOID, &ffi_type_void); + T(INT8, &ffi_type_sint8); + A(INT8, SCHAR); + A(INT8, CHAR); + T(UINT8, &ffi_type_uint8); + A(UINT8, UCHAR); + + T(INT16, &ffi_type_sint16); + A(INT16, SHORT); + A(INT16, SSHORT); + T(UINT16, &ffi_type_uint16); + A(UINT16, USHORT); + T(INT32, &ffi_type_sint32); + A(INT32, INT); + A(INT32, SINT); + T(UINT32, &ffi_type_uint32); + A(UINT32, UINT); + T(INT64, &ffi_type_sint64); + A(INT64, LONG_LONG); + A(INT64, SLONG_LONG); + T(UINT64, &ffi_type_uint64); + A(UINT64, ULONG_LONG); + T(LONG, &ffi_type_slong); + A(LONG, SLONG); + T(ULONG, &ffi_type_ulong); + T(FLOAT32, &ffi_type_float); + A(FLOAT32, FLOAT); + T(FLOAT64, &ffi_type_double); + A(FLOAT64, DOUBLE); + T(LONGDOUBLE, &ffi_type_longdouble); + T(POINTER, &ffi_type_pointer); + T(STRING, &ffi_type_pointer); + T(BUFFER_IN, &ffi_type_pointer); + T(BUFFER_OUT, &ffi_type_pointer); + T(BUFFER_INOUT, &ffi_type_pointer); + T(BOOL, &ffi_type_uchar); + T(VARARGS, &ffi_type_void); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Type.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Type.h new file mode 100644 index 0000000..b81995a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Type.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * Copyright (C) 2009 Luc Heinrich + * + * This file is part of ruby-ffi. + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the Evan Phoenix nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef RBFFI_TYPE_H +#define RBFFI_TYPE_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Type_ Type; + +#include "Types.h" + +struct Type_ { + NativeType nativeType; + ffi_type* ffiType; +}; + +extern VALUE rbffi_TypeClass; +extern VALUE rbffi_Type_Lookup(VALUE type); + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_TYPE_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Type.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Type.o new file mode 100644 index 0000000..ae3cad7 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Type.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Types.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Types.c new file mode 100644 index 0000000..77741e0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Types.c @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2009, Wayne Meissner + * Copyright (c) 2009, Luc Heinrich + * Copyright (c) 2009, Aman Gupta. + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "Pointer.h" +#include "rbffi.h" +#include "Function.h" +#include "StructByValue.h" +#include "Types.h" +#include "Struct.h" +#include "MappedType.h" +#include "MemoryPointer.h" +#include "LongDouble.h" + +static ID id_from_native = 0; + + +VALUE +rbffi_NativeValue_ToRuby(Type* type, VALUE rbType, const void* ptr) +{ + switch (type->nativeType) { + case NATIVE_VOID: + return Qnil; + case NATIVE_INT8: + return INT2NUM((signed char) *(ffi_sarg *) ptr); + case NATIVE_INT16: + return INT2NUM((signed short) *(ffi_sarg *) ptr); + case NATIVE_INT32: + return INT2NUM((signed int) *(ffi_sarg *) ptr); + case NATIVE_LONG: + return LONG2NUM((signed long) *(ffi_sarg *) ptr); + case NATIVE_INT64: + return LL2NUM(*(signed long long *) ptr); + + case NATIVE_UINT8: + return UINT2NUM((unsigned char) *(ffi_arg *) ptr); + case NATIVE_UINT16: + return UINT2NUM((unsigned short) *(ffi_arg *) ptr); + case NATIVE_UINT32: + return UINT2NUM((unsigned int) *(ffi_arg *) ptr); + case NATIVE_ULONG: + return ULONG2NUM((unsigned long) *(ffi_arg *) ptr); + case NATIVE_UINT64: + return ULL2NUM(*(unsigned long long *) ptr); + + case NATIVE_FLOAT32: + return rb_float_new(*(float *) ptr); + case NATIVE_FLOAT64: + return rb_float_new(*(double *) ptr); + + case NATIVE_LONGDOUBLE: + return rbffi_longdouble_new(*(long double *) ptr); + + case NATIVE_STRING: + return (*(void **) ptr != NULL) ? rb_str_new2(*(char **) ptr) : Qnil; + case NATIVE_POINTER: + return rbffi_Pointer_NewInstance(*(void **) ptr); + case NATIVE_BOOL: + return ((unsigned char) *(ffi_arg *) ptr) ? Qtrue : Qfalse; + + case NATIVE_FUNCTION: { + return *(void **) ptr != NULL + ? rbffi_Function_NewInstance(rbType, rbffi_Pointer_NewInstance(*(void **) ptr)) + : Qnil; + } + + case NATIVE_STRUCT: { + StructByValue* sbv = (StructByValue *)type; + AbstractMemory* mem; + VALUE rbMemory = rbffi_MemoryPointer_NewInstance(1, sbv->base.ffiType->size, false); + + Data_Get_Struct(rbMemory, AbstractMemory, mem); + memcpy(mem->address, ptr, sbv->base.ffiType->size); + RB_GC_GUARD(rbMemory); + RB_GC_GUARD(rbType); + + return rb_class_new_instance(1, &rbMemory, sbv->rbStructClass); + } + + case NATIVE_MAPPED: { + /* + * For mapped types, first convert to the real native type, then upcall to + * ruby to convert to the expected return type + */ + MappedType* m = (MappedType *) type; + VALUE values[2], rbReturnValue; + + values[0] = rbffi_NativeValue_ToRuby(m->type, m->rbType, ptr); + values[1] = Qnil; + + + rbReturnValue = rb_funcall2(m->rbConverter, id_from_native, 2, values); + RB_GC_GUARD(values[0]); + RB_GC_GUARD(rbType); + + return rbReturnValue; + } + + default: + rb_raise(rb_eRuntimeError, "Unknown type: %d", type->nativeType); + return Qnil; + } +} + +void +rbffi_Types_Init(VALUE moduleFFI) +{ + id_from_native = rb_intern("from_native"); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Types.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Types.h new file mode 100644 index 0000000..4b72320 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Types.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * Copyright (c) 2009, Luc Heinrich + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_TYPES_H +#define RBFFI_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + NATIVE_VOID, + NATIVE_INT8, + NATIVE_UINT8, + NATIVE_INT16, + NATIVE_UINT16, + NATIVE_INT32, + NATIVE_UINT32, + NATIVE_INT64, + NATIVE_UINT64, + NATIVE_LONG, + NATIVE_ULONG, + NATIVE_FLOAT32, + NATIVE_FLOAT64, + NATIVE_LONGDOUBLE, + NATIVE_POINTER, + NATIVE_FUNCTION, + NATIVE_BUFFER_IN, + NATIVE_BUFFER_OUT, + NATIVE_BUFFER_INOUT, + NATIVE_CHAR_ARRAY, + NATIVE_BOOL, + + /** An immutable string. Nul terminated, but only copies in to the native function */ + NATIVE_STRING, + + /** The function takes a variable number of arguments */ + NATIVE_VARARGS, + + /** Struct-by-value param or result */ + NATIVE_STRUCT, + + /** An array type definition */ + NATIVE_ARRAY, + + /** Custom native type */ + NATIVE_MAPPED, +} NativeType; + +#include +#include "Type.h" + +VALUE rbffi_NativeValue_ToRuby(Type* type, VALUE rbType, const void* ptr); +void rbffi_Types_Init(VALUE moduleFFI); + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_TYPES_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Types.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Types.o new file mode 100644 index 0000000..f8c46ca Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Types.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Variadic.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Variadic.c new file mode 100644 index 0000000..8ad38b1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Variadic.c @@ -0,0 +1,303 @@ +/* + * Copyright (c) 2008-2010 Wayne Meissner + * Copyright (C) 2009 Andrea Fazzi + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MSC_VER +#include +#endif +#include + +#include +#include +#include +#include + +#include +#include "rbffi.h" +#include "compat.h" + +#include "AbstractMemory.h" +#include "Pointer.h" +#include "Types.h" +#include "Type.h" +#include "LastError.h" +#include "MethodHandle.h" +#include "Call.h" +#include "Thread.h" + +typedef struct VariadicInvoker_ { + VALUE rbAddress; + VALUE rbReturnType; + VALUE rbEnums; + + Type* returnType; + ffi_abi abi; + void* function; + int paramCount; + bool blocking; +} VariadicInvoker; + + +static VALUE variadic_allocate(VALUE klass); +static VALUE variadic_initialize(VALUE self, VALUE rbFunction, VALUE rbParameterTypes, + VALUE rbReturnType, VALUE options); +static void variadic_mark(VariadicInvoker *); + +static VALUE classVariadicInvoker = Qnil; + + +static VALUE +variadic_allocate(VALUE klass) +{ + VariadicInvoker *invoker; + VALUE obj = Data_Make_Struct(klass, VariadicInvoker, variadic_mark, -1, invoker); + + invoker->rbAddress = Qnil; + invoker->rbEnums = Qnil; + invoker->rbReturnType = Qnil; + invoker->blocking = false; + + return obj; +} + +static void +variadic_mark(VariadicInvoker *invoker) +{ + rb_gc_mark(invoker->rbEnums); + rb_gc_mark(invoker->rbAddress); + rb_gc_mark(invoker->rbReturnType); +} + +static VALUE +variadic_initialize(VALUE self, VALUE rbFunction, VALUE rbParameterTypes, VALUE rbReturnType, VALUE options) +{ + VariadicInvoker* invoker = NULL; + VALUE retval = Qnil; + VALUE convention = Qnil; + VALUE fixed = Qnil; +#if defined(X86_WIN32) + VALUE rbConventionStr; +#endif + int i; + + Check_Type(options, T_HASH); + convention = rb_hash_aref(options, ID2SYM(rb_intern("convention"))); + + Data_Get_Struct(self, VariadicInvoker, invoker); + invoker->rbEnums = rb_hash_aref(options, ID2SYM(rb_intern("enums"))); + invoker->rbAddress = rbFunction; + invoker->function = rbffi_AbstractMemory_Cast(rbFunction, rbffi_PointerClass)->address; + invoker->blocking = RTEST(rb_hash_aref(options, ID2SYM(rb_intern("blocking")))); + +#if defined(X86_WIN32) + rbConventionStr = rb_funcall2(convention, rb_intern("to_s"), 0, NULL); + invoker->abi = (RTEST(convention) && strcmp(StringValueCStr(rbConventionStr), "stdcall") == 0) + ? FFI_STDCALL : FFI_DEFAULT_ABI; +#else + invoker->abi = FFI_DEFAULT_ABI; +#endif + + invoker->rbReturnType = rbffi_Type_Lookup(rbReturnType); + if (!RTEST(invoker->rbReturnType)) { + VALUE typeName = rb_funcall2(rbReturnType, rb_intern("inspect"), 0, NULL); + rb_raise(rb_eTypeError, "Invalid return type (%s)", RSTRING_PTR(typeName)); + } + + Data_Get_Struct(rbReturnType, Type, invoker->returnType); + + invoker->paramCount = -1; + + fixed = rb_ary_new2(RARRAY_LEN(rbParameterTypes) - 1); + for (i = 0; i < RARRAY_LEN(rbParameterTypes); ++i) { + VALUE entry = rb_ary_entry(rbParameterTypes, i); + VALUE rbType = rbffi_Type_Lookup(entry); + Type* type; + + if (!RTEST(rbType)) { + VALUE typeName = rb_funcall2(entry, rb_intern("inspect"), 0, NULL); + rb_raise(rb_eTypeError, "Invalid parameter type (%s)", RSTRING_PTR(typeName)); + } + Data_Get_Struct(rbType, Type, type); + if (type->nativeType != NATIVE_VARARGS) { + rb_ary_push(fixed, entry); + } + } + /* + * @fixed and @type_map are used by the parameter mangling ruby code + */ + rb_iv_set(self, "@fixed", fixed); + rb_iv_set(self, "@type_map", rb_hash_aref(options, ID2SYM(rb_intern("type_map")))); + + return retval; +} + +static VALUE +variadic_invoke(VALUE self, VALUE parameterTypes, VALUE parameterValues) +{ + VariadicInvoker* invoker; + FFIStorage* params; + void* retval; + ffi_cif cif; + void** ffiValues; + ffi_type** ffiParamTypes; + ffi_type* ffiReturnType; + Type** paramTypes; + VALUE* argv; + VALUE* callbackParameters; + int paramCount = 0, fixedCount = 0, callbackCount = 0, i; + ffi_status ffiStatus; + rbffi_frame_t frame = { 0 }; + + Check_Type(parameterTypes, T_ARRAY); + Check_Type(parameterValues, T_ARRAY); + + Data_Get_Struct(self, VariadicInvoker, invoker); + paramCount = (int) RARRAY_LEN(parameterTypes); + paramTypes = ALLOCA_N(Type *, paramCount); + ffiParamTypes = ALLOCA_N(ffi_type *, paramCount); + params = ALLOCA_N(FFIStorage, paramCount); + ffiValues = ALLOCA_N(void*, paramCount); + argv = ALLOCA_N(VALUE, paramCount); + callbackParameters = ALLOCA_N(VALUE, paramCount); + retval = alloca(MAX(invoker->returnType->ffiType->size, FFI_SIZEOF_ARG)); + + for (i = 0; i < paramCount; ++i) { + VALUE rbType = rb_ary_entry(parameterTypes, i); + + if (!rb_obj_is_kind_of(rbType, rbffi_TypeClass)) { + rb_raise(rb_eTypeError, "wrong type. Expected (FFI::Type)"); + } + Data_Get_Struct(rbType, Type, paramTypes[i]); + + switch (paramTypes[i]->nativeType) { + case NATIVE_INT8: + case NATIVE_INT16: + case NATIVE_INT32: + rbType = rb_const_get(rbffi_TypeClass, rb_intern("INT32")); + Data_Get_Struct(rbType, Type, paramTypes[i]); + break; + case NATIVE_UINT8: + case NATIVE_UINT16: + case NATIVE_UINT32: + rbType = rb_const_get(rbffi_TypeClass, rb_intern("UINT32")); + Data_Get_Struct(rbType, Type, paramTypes[i]); + break; + + case NATIVE_FLOAT32: + rbType = rb_const_get(rbffi_TypeClass, rb_intern("DOUBLE")); + Data_Get_Struct(rbType, Type, paramTypes[i]); + break; + + case NATIVE_FUNCTION: + if (!rb_obj_is_kind_of(rbType, rbffi_FunctionTypeClass)) { + VALUE typeName = rb_funcall2(rbType, rb_intern("inspect"), 0, NULL); + rb_raise(rb_eTypeError, "Incorrect parameter type (%s)", RSTRING_PTR(typeName)); + } + callbackParameters[callbackCount++] = rbType; + break; + + default: + break; + } + + + ffiParamTypes[i] = paramTypes[i]->ffiType; + if (ffiParamTypes[i] == NULL) { + rb_raise(rb_eArgError, "Invalid parameter type #%x", paramTypes[i]->nativeType); + } + argv[i] = rb_ary_entry(parameterValues, i); + } + + ffiReturnType = invoker->returnType->ffiType; + if (ffiReturnType == NULL) { + rb_raise(rb_eArgError, "Invalid return type"); + } + + /*Get the number of fixed args from @fixed array*/ + fixedCount = RARRAY_LEN(rb_iv_get(self, "@fixed")); + +#ifdef HAVE_FFI_PREP_CIF_VAR + ffiStatus = ffi_prep_cif_var(&cif, invoker->abi, fixedCount, paramCount, ffiReturnType, ffiParamTypes); +#else + ffiStatus = ffi_prep_cif(&cif, invoker->abi, paramCount, ffiReturnType, ffiParamTypes); +#endif + switch (ffiStatus) { + case FFI_BAD_ABI: + rb_raise(rb_eArgError, "Invalid ABI specified"); + case FFI_BAD_TYPEDEF: + rb_raise(rb_eArgError, "Invalid argument type specified"); + case FFI_OK: + break; + default: + rb_raise(rb_eArgError, "Unknown FFI error"); + } + + rbffi_SetupCallParams(paramCount, argv, -1, paramTypes, params, + ffiValues, callbackParameters, callbackCount, invoker->rbEnums); + + rbffi_frame_push(&frame); + + if(unlikely(invoker->blocking)) { + rbffi_blocking_call_t* bc; + bc = ALLOCA_N(rbffi_blocking_call_t, 1); + bc->retval = retval; + bc->function = invoker->function; + bc->ffiValues = ffiValues; + bc->params = params; + bc->frame = &frame; + bc->cif = cif; + + rb_rescue2(rbffi_do_blocking_call, (VALUE) bc, rbffi_save_frame_exception, (VALUE) &frame, rb_eException, (VALUE) 0); + } else { + ffi_call(&cif, FFI_FN(invoker->function), retval, ffiValues); + } + + rbffi_frame_pop(&frame); + + rbffi_save_errno(); + + if (RTEST(frame.exc) && frame.exc != Qnil) { + rb_exc_raise(frame.exc); + } + + return rbffi_NativeValue_ToRuby(invoker->returnType, invoker->rbReturnType, retval); +} + + +void +rbffi_Variadic_Init(VALUE moduleFFI) +{ + classVariadicInvoker = rb_define_class_under(moduleFFI, "VariadicInvoker", rb_cObject); + rb_global_variable(&classVariadicInvoker); + + rb_define_alloc_func(classVariadicInvoker, variadic_allocate); + + rb_define_method(classVariadicInvoker, "initialize", variadic_initialize, 4); + rb_define_method(classVariadicInvoker, "invoke", variadic_invoke, 2); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Variadic.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Variadic.o new file mode 100644 index 0000000..9b481ff Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/Variadic.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/compat.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/compat.h new file mode 100644 index 0000000..3f7bbae --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/compat.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_COMPAT_H +#define RBFFI_COMPAT_H + +#include + +#ifndef RARRAY_LEN +# define RARRAY_LEN(ary) RARRAY(ary)->len +#endif + +#ifndef RARRAY_PTR +# define RARRAY_PTR(ary) RARRAY(ary)->ptr +#endif + +#ifndef RSTRING_LEN +# define RSTRING_LEN(s) RSTRING(s)->len +#endif + +#ifndef RSTRING_PTR +# define RSTRING_PTR(s) RSTRING(s)->ptr +#endif + +#ifndef NUM2ULL +# define NUM2ULL(x) rb_num2ull((VALUE)x) +#endif + +#ifndef roundup +# define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) +#endif + +#ifdef __GNUC__ +# define likely(x) __builtin_expect((x), 1) +# define unlikely(x) __builtin_expect((x), 0) +#else +# define likely(x) (x) +# define unlikely(x) (x) +#endif + +#ifdef _MSC_VER +#define ffi_type_longdouble ffi_type_double +#endif + +#ifndef MAX +# define MAX(a, b) ((a) < (b) ? (b) : (a)) +#endif +#ifndef MIN +# define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +#ifndef RB_GC_GUARD +# define RB_GC_GUARD(x) (x) +#endif + +#endif /* RBFFI_COMPAT_H */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/extconf.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/extconf.h new file mode 100644 index 0000000..a2e81a1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/extconf.h @@ -0,0 +1,7 @@ +#ifndef EXTCONF_H +#define EXTCONF_H +#define HAVE_FFI_PREP_CIF_VAR 1 +#define HAVE_FFI_RAW_CALL 1 +#define HAVE_FFI_PREP_RAW_CLOSURE 1 +#define HAVE_RAW_API 1 +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/extconf.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/extconf.rb new file mode 100644 index 0000000..720fb06 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/extconf.rb @@ -0,0 +1,98 @@ +#!/usr/bin/env ruby + +if RUBY_ENGINE == 'ruby' || RUBY_ENGINE == 'rbx' + require 'mkmf' + require 'rbconfig' + + def system_libffi_usable? + # We need pkg_config or ffi.h + libffi_ok = pkg_config("libffi") || + have_header("ffi.h") || + find_header("ffi.h", "/usr/local/include", "/usr/include/ffi", + "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/ffi", + "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/ffi") || + (find_header("ffi.h", `xcrun --sdk macosx --show-sdk-path`.strip + "/usr/include/ffi") rescue false) + + # Ensure we can link to ffi_prep_closure_loc + libffi_ok &&= have_library("ffi", "ffi_prep_closure_loc", [ "ffi.h" ]) || + have_library("libffi", "ffi_prep_closure_loc", [ "ffi.h" ]) || + have_library("libffi-8", "ffi_prep_closure_loc", [ "ffi.h" ]) + + if RbConfig::CONFIG['host_os'] =~ /mswin/ + have_library('libffi_convenience') + have_library('shlwapi') + end + + libffi_ok + end + + dir_config("ffi_c") + + # recent versions of ruby add restrictive ansi and warning flags on a whim - kill them all + $warnflags = '' + $CFLAGS.gsub!(/[\s+]-ansi/, '') + $CFLAGS.gsub!(/[\s+]-std=[^\s]+/, '') + # solaris 10 needs -c99 for + $CFLAGS << " -std=c99" if RbConfig::CONFIG['host_os'] =~ /solaris(!?2\.11)/ + + # Check whether we use system libffi + system_libffi = enable_config('system-libffi', :try) + + if system_libffi == :try + system_libffi = ENV['RUBY_CC_VERSION'].nil? && system_libffi_usable? + elsif system_libffi + abort "system libffi is not usable" unless system_libffi_usable? + end + + if system_libffi + have_func('ffi_prep_cif_var') + $defs << "-DHAVE_RAW_API" if have_func("ffi_raw_call") && have_func("ffi_prep_raw_closure") + else + $defs << "-DHAVE_FFI_PREP_CIF_VAR" + $defs << "-DUSE_INTERNAL_LIBFFI" + + # Ensure libffi symbols aren't exported when using static libffi. + # This is to avoid interference with other gems like fiddle. + # See https://github.com/ffi/ffi/issues/835 + append_ldflags "-Wl,--exclude-libs,ALL" + end + + # Some linux archs need explicit linking to pthread, see https://github.com/ffi/ffi/issues/893 + append_ldflags "-pthread" + + ffi_alloc_default = RbConfig::CONFIG['host_os'] =~ /darwin/i && RbConfig::CONFIG['host'] =~ /arm|aarch64/i + if enable_config('libffi-alloc', ffi_alloc_default) + $defs << "-DUSE_FFI_ALLOC" + end + + $defs << "-DHAVE_EXTCONF_H" if $defs.empty? # needed so create_header works + + create_header + create_makefile("ffi_c") + + unless system_libffi + File.open("Makefile", "a") do |mf| + mf.puts "LIBFFI_HOST=--host=#{RbConfig::CONFIG['host_alias']}" if RbConfig::CONFIG.has_key?("host_alias") + if RbConfig::CONFIG['host_os'] =~ /darwin/i + if RbConfig::CONFIG['host'] =~ /arm|aarch64/i + mf.puts "LIBFFI_HOST=--host=aarch64-apple-#{RbConfig::CONFIG['host_os']}" + end + mf.puts "include ${srcdir}/libffi.darwin.mk" + elsif RbConfig::CONFIG['host_os'] =~ /bsd/i + mf.puts '.include "${srcdir}/libffi.bsd.mk"' + elsif RbConfig::CONFIG['host_os'] =~ /mswin64/i + mf.puts '!include $(srcdir)/libffi.vc64.mk' + elsif RbConfig::CONFIG['host_os'] =~ /mswin32/i + mf.puts '!include $(srcdir)/libffi.vc.mk' + else + mf.puts "include ${srcdir}/libffi.mk" + end + end + end + +else + File.open("Makefile", "w") do |mf| + mf.puts "# Dummy makefile for non-mri rubies" + mf.puts "all install::\n" + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ffi.c new file mode 100644 index 0000000..22ea3bf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ffi.c @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * Copyright (C) 2009 Luc Heinrich + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include + +#include + +#include "rbffi.h" +#include "AbstractMemory.h" +#include "Pointer.h" +#include "MemoryPointer.h" +#include "Struct.h" +#include "StructByValue.h" +#include "DynamicLibrary.h" +#include "Platform.h" +#include "Types.h" +#include "LastError.h" +#include "Function.h" +#include "ClosurePool.h" +#include "MethodHandle.h" +#include "Call.h" +#include "ArrayType.h" +#include "MappedType.h" + +void Init_ffi_c(void); + +VALUE rbffi_FFIModule = Qnil; + +static VALUE moduleFFI = Qnil; + +void +Init_ffi_c(void) +{ + /* + * Document-module: FFI + * + * This module embbed type constants from {FFI::NativeType}. + */ + rbffi_FFIModule = moduleFFI = rb_define_module("FFI"); + rb_global_variable(&rbffi_FFIModule); + + rbffi_Thread_Init(rbffi_FFIModule); + + /* FFI::Type needs to be initialized before most other classes */ + rbffi_Type_Init(moduleFFI); + + rbffi_ArrayType_Init(moduleFFI); + rbffi_LastError_Init(moduleFFI); + rbffi_Call_Init(moduleFFI); + rbffi_ClosurePool_Init(moduleFFI); + rbffi_MethodHandle_Init(moduleFFI); + rbffi_Platform_Init(moduleFFI); + rbffi_AbstractMemory_Init(moduleFFI); + rbffi_Pointer_Init(moduleFFI); + rbffi_Function_Init(moduleFFI); + rbffi_MemoryPointer_Init(moduleFFI); + rbffi_Buffer_Init(moduleFFI); + rbffi_StructByValue_Init(moduleFFI); + rbffi_Struct_Init(moduleFFI); + rbffi_DynamicLibrary_Init(moduleFFI); + rbffi_Variadic_Init(moduleFFI); + rbffi_Types_Init(moduleFFI); + rbffi_MappedType_Init(moduleFFI); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ffi.o b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ffi.o new file mode 100644 index 0000000..a502748 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ffi.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ffi_c.so b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ffi_c.so new file mode 100755 index 0000000..196f6ad Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/ffi_c.so differ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.bsd.mk b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.bsd.mk new file mode 100644 index 0000000..ab66256 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.bsd.mk @@ -0,0 +1,40 @@ +# -*- makefile -*- +# +# Makefile for BSD systems +# + +LOCAL_LIBS += ${LIBFFI} -lpthread + +LIBFFI_CFLAGS = ${FFI_MMAP_EXEC} -pthread +LIBFFI_BUILD_DIR = ${.CURDIR}/libffi-${arch} +INCFLAGS := -I${LIBFFI_BUILD_DIR}/include -I${INCFLAGS} + +.if ${srcdir} == "." + LIBFFI_SRC_DIR := ${.CURDIR}/libffi +.else + LIBFFI_SRC_DIR := ${srcdir}/libffi +.endif + + +LIBFFI = ${LIBFFI_BUILD_DIR}/.libs/libffi_convenience.a +LIBFFI_AUTOGEN = ${LIBFFI_SRC_DIR}/autogen.sh +LIBFFI_CONFIGURE = ${LIBFFI_SRC_DIR}/configure --disable-static \ + --with-pic=yes --disable-dependency-tracking --disable-docs + +$(OBJS): ${LIBFFI} + +$(LIBFFI): + @mkdir -p ${LIBFFI_BUILD_DIR} + @if [ ! -f $(LIBFFI_SRC_DIR)/configure ]; then \ + echo "Running autoreconf for libffi"; \ + cd "$(LIBFFI_SRC_DIR)" && \ + /bin/sh $(LIBFFI_AUTOGEN) > /dev/null; \ + fi + @if [ ! -f ${LIBFFI_BUILD_DIR}/Makefile ]; then \ + echo "Configuring libffi"; \ + cd ${LIBFFI_BUILD_DIR} && \ + /usr/bin/env CC="${CC}" LD="${LD}" CFLAGS="${LIBFFI_CFLAGS}" GREP_OPTIONS="" \ + /bin/sh ${LIBFFI_CONFIGURE} ${LIBFFI_HOST} > /dev/null; \ + fi + @cd ${LIBFFI_BUILD_DIR} && ${MAKE} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.darwin.mk b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.darwin.mk new file mode 100644 index 0000000..893a8e1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.darwin.mk @@ -0,0 +1,105 @@ +# -*- makefile -*- + +include ${srcdir}/libffi.gnu.mk + +CCACHE := $(shell type -p ccache) +BUILD_DIR := $(shell pwd) + +INCFLAGS += -I"$(BUILD_DIR)" + +# Work out which arches we need to compile the lib for +ARCHES := +ARCHFLAGS ?= $(filter -arch %, $(CFLAGS)) + +ifneq ($(findstring -arch ppc,$(ARCHFLAGS)),) + ARCHES += ppc +endif + +ifneq ($(findstring -arch i386,$(ARCHFLAGS)),) + ARCHES += i386 +endif + +ifneq ($(findstring -arch x86_64,$(ARCHFLAGS)),) + ARCHES += x86_64 +endif + +ifeq ($(strip $(ARCHES)),) +LIBFFI_BUILD_DIR = $(BUILD_DIR)/libffi-$(arch) +# Just build the one (default) architecture +$(LIBFFI): + @mkdir -p "$(LIBFFI_BUILD_DIR)" "$(@D)" + @if [ ! -f "$(LIBFFI_SRC_DIR)"/configure ]; then \ + echo "Running autoreconf for libffi"; \ + cd "$(LIBFFI_SRC_DIR)" && \ + /bin/sh $(LIBFFI_AUTOGEN) > /dev/null; \ + fi + @if [ ! -f "$(LIBFFI_BUILD_DIR)"/Makefile ]; then \ + echo "Configuring libffi"; \ + cd "$(LIBFFI_BUILD_DIR)" && \ + /usr/bin/env CC="$(CC)" LD="$(LD)" CFLAGS="$(LIBFFI_CFLAGS)" GREP_OPTIONS="" \ + /bin/sh $(LIBFFI_CONFIGURE) $(LIBFFI_HOST) > /dev/null; \ + fi + cd "$(LIBFFI_BUILD_DIR)" && $(MAKE) + +else +LIBTARGETS = $(foreach arch,$(ARCHES),"$(BUILD_DIR)"/libffi-$(arch)/.libs/libffi_convenience.a) + +# Build a fat binary and assemble +build_ffi = \ + mkdir -p "$(BUILD_DIR)"/libffi-$(1); \ + (if [ ! -f "$(LIBFFI_SRC_DIR)"/configure ]; then \ + echo "Running autoreconf for libffi"; \ + cd "$(LIBFFI_SRC_DIR)" && \ + /bin/sh $(LIBFFI_AUTOGEN) > /dev/null; \ + fi); \ + (if [ ! -f "$(BUILD_DIR)"/libffi-$(1)/Makefile ]; then \ + echo "Configuring libffi for $(1)"; \ + cd "$(BUILD_DIR)"/libffi-$(1) && \ + env CC="$(CCACHE) $(CC)" CFLAGS="-arch $(1) $(LIBFFI_CFLAGS)" LDFLAGS="-arch $(1)" \ + $(LIBFFI_CONFIGURE) --host=$(1)-apple-darwin > /dev/null; \ + fi); \ + $(MAKE) -C "$(BUILD_DIR)"/libffi-$(1) + +target_ffi = "$(BUILD_DIR)"/libffi-$(1)/.libs/libffi_convenience.a:; $(call build_ffi,$(1)) + +# Work out which arches we need to compile the lib for +ifneq ($(findstring ppc,$(ARCHES)),) + $(call target_ffi,ppc) +endif + +ifneq ($(findstring i386,$(ARCHES)),) + $(call target_ffi,i386) +endif + +ifneq ($(findstring x86_64,$(ARCHES)),) + $(call target_ffi,x86_64) +endif + + +$(LIBFFI): $(LIBTARGETS) + # Assemble into a FAT (x86_64, i386, ppc) library + @mkdir -p "$(@D)" + /usr/bin/libtool -static -o $@ \ + $(foreach arch, $(ARCHES),"$(BUILD_DIR)"/libffi-$(arch)/.libs/libffi_convenience.a) + @mkdir -p "$(LIBFFI_BUILD_DIR)"/include + $(RM) "$(LIBFFI_BUILD_DIR)"/include/ffi.h + @( \ + printf "#if defined(__i386__)\n"; \ + printf "#include \"libffi-i386/include/ffi.h\"\n"; \ + printf "#elif defined(__x86_64__)\n"; \ + printf "#include \"libffi-x86_64/include/ffi.h\"\n";\ + printf "#elif defined(__ppc__)\n"; \ + printf "#include \"libffi-ppc/include/ffi.h\"\n";\ + printf "#endif\n";\ + ) > "$(LIBFFI_BUILD_DIR)"/include/ffi.h + @( \ + printf "#if defined(__i386__)\n"; \ + printf "#include \"libffi-i386/include/ffitarget.h\"\n"; \ + printf "#elif defined(__x86_64__)\n"; \ + printf "#include \"libffi-x86_64/include/ffitarget.h\"\n";\ + printf "#elif defined(__ppc__)\n"; \ + printf "#include \"libffi-ppc/include/ffitarget.h\"\n";\ + printf "#endif\n";\ + ) > "$(LIBFFI_BUILD_DIR)"/include/ffitarget.h + +endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.gnu.mk b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.gnu.mk new file mode 100644 index 0000000..473b8fb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.gnu.mk @@ -0,0 +1,32 @@ +# -*- makefile -*- +# +# Common definitions for all systems that use GNU make +# + + +# Tack the extra deps onto the autogenerated variables +LOCAL_LIBS += $(LIBFFI) +BUILD_DIR = $(shell pwd) +LIBFFI_CFLAGS = $(FFI_MMAP_EXEC) +LIBFFI_BUILD_DIR = $(BUILD_DIR)/libffi-$(arch) +INCFLAGS := -I"$(LIBFFI_BUILD_DIR)"/include $(INCFLAGS) + +ifeq ($(srcdir),.) + LIBFFI_SRC_DIR := $(shell pwd)/libffi +else ifeq ($(srcdir),..) + LIBFFI_SRC_DIR := $(shell pwd)/../libffi +else + LIBFFI_SRC_DIR := $(realpath $(srcdir)/libffi) +endif + +LIBFFI = "$(LIBFFI_BUILD_DIR)"/.libs/libffi_convenience.a +LIBFFI_AUTOGEN = ${LIBFFI_SRC_DIR}/autogen.sh +LIBFFI_CONFIGURE = "$(LIBFFI_SRC_DIR)"/configure --disable-static \ + --with-pic=yes --disable-dependency-tracking --disable-docs + +$(OBJS): $(LIBFFI) + +# +# libffi.mk or libffi.darwin.mk contains rules for building the actual library +# + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.mk b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.mk new file mode 100644 index 0000000..3b58227 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.mk @@ -0,0 +1,18 @@ +# -*- makefile -*- + +include ${srcdir}/libffi.gnu.mk + +$(LIBFFI): + @mkdir -p "$(LIBFFI_BUILD_DIR)" "$@(D)" + @if [ ! -f "$(LIBFFI_SRC_DIR)"/configure ]; then \ + echo "Running autoreconf for libffi"; \ + cd "$(LIBFFI_SRC_DIR)" && \ + /bin/sh $(LIBFFI_AUTOGEN) > /dev/null; \ + fi + @if [ ! -f "$(LIBFFI_BUILD_DIR)"/Makefile ]; then \ + echo "Configuring libffi"; \ + cd "$(LIBFFI_BUILD_DIR)" && \ + env CFLAGS="$(LIBFFI_CFLAGS)" GREP_OPTIONS="" \ + sh $(LIBFFI_CONFIGURE) $(LIBFFI_HOST) > /dev/null; \ + fi + $(MAKE) -C "$(LIBFFI_BUILD_DIR)" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.vc.mk b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.vc.mk new file mode 100644 index 0000000..8cd4603 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.vc.mk @@ -0,0 +1,26 @@ +# -*- makefile -*- +# +# Makefile for msvc +# + +# Tack the extra deps onto the autogenerated variables +INCFLAGS = -I$(LIBFFI_BUILD_DIR)/include -I$(LIBFFI_BUILD_DIR)/src/x86 $(INCFLAGS) +LOCAL_LIBS = $(LOCAL_LIBS) $(LIBFFI) +BUILD_DIR = $(MAKEDIR) +LIBFFI_BUILD_DIR = $(BUILD_DIR)/libffi + +!IF "$(srcdir)" == "." +LIBFFI_SRC_DIR = $(MAKEDIR)/libffi +!ELSE +LIBFFI_SRC_DIR = $(srcdir)/libffi +!ENDIF + +LIBFFI = $(LIBFFI_BUILD_DIR)/.libs/libffi_convenience.lib + +$(OBJS): $(LIBFFI) + +$(LIBFFI): + @$(MAKEDIRS) $(LIBFFI_BUILD_DIR) + @cd $(LIBFFI_BUILD_DIR) && $(MAKE) -f Makefile.vc + + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.vc64.mk b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.vc64.mk new file mode 100644 index 0000000..6f3dbbc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi.vc64.mk @@ -0,0 +1,26 @@ +# -*- makefile -*- +# +# Makefile for msvc +# + +# Tack the extra deps onto the autogenerated variables +INCFLAGS = -I$(LIBFFI_BUILD_DIR)/include -I$(LIBFFI_BUILD_DIR)/src/x86 $(INCFLAGS) +LOCAL_LIBS = $(LOCAL_LIBS) $(LIBFFI) +BUILD_DIR = $(MAKEDIR) +LIBFFI_BUILD_DIR = $(BUILD_DIR)/libffi + +!IF "$(srcdir)" == "." +LIBFFI_SRC_DIR = $(MAKEDIR)/libffi +!ELSE +LIBFFI_SRC_DIR = $(srcdir)/libffi +!ENDIF + +LIBFFI = $(LIBFFI_BUILD_DIR)/.libs/libffi_convenience.lib + +$(OBJS): $(LIBFFI) + +$(LIBFFI): + @$(MAKEDIRS) $(LIBFFI_BUILD_DIR) + @cd $(LIBFFI_BUILD_DIR) && $(MAKE) -f Makefile.vc64 + + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.appveyor.yml b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.appveyor.yml new file mode 100644 index 0000000..ece8a94 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.appveyor.yml @@ -0,0 +1,66 @@ +shallow_clone: true + +# We're currently only testing libffi built with Microsoft's +# tools. +# This matrix should be expanded to include at least: +# 32- and 64-bit gcc/cygwin +# 32- and 64-bit gcc/mingw +# 32- and 64-bit clang/mingw +# and perhaps more. + +image: Visual Studio 2017 +platform: + - x64 + - x86 + - arm + - arm64 + +environment: + global: + CYG_ROOT: C:/cygwin + CYG_CACHE: C:/cygwin/var/cache/setup + CYG_MIRROR: http://mirrors.kernel.org/sourceware/cygwin/ + matrix: + - VSVER: 15 + +install: + - ps: >- + If ($env:Platform -Match "x86") { + $env:VCVARS_PLATFORM="x86" + $env:BUILD="i686-pc-cygwin" + $env:HOST="i686-pc-cygwin" + $env:MSVCC="/cygdrive/c/projects/libffi/msvcc.sh" + $env:SRC_ARCHITECTURE="x86" + } ElseIf ($env:Platform -Match "arm64") { + $env:VCVARS_PLATFORM="x86_arm64" + $env:BUILD="i686-pc-cygwin" + $env:HOST="aarch64-w64-cygwin" + $env:MSVCC="/cygdrive/c/projects/libffi/msvcc.sh -marm64" + $env:SRC_ARCHITECTURE="aarch64" + } ElseIf ($env:Platform -Match "arm") { + $env:VCVARS_PLATFORM="x86_arm" + $env:BUILD="i686-pc-cygwin" + $env:HOST="arm-w32-cygwin" + $env:MSVCC="/cygdrive/c/projects/libffi/msvcc.sh -marm" + $env:SRC_ARCHITECTURE="arm" + } Else { + $env:VCVARS_PLATFORM="amd64" + $env:BUILD="x86_64-w64-cygwin" + $env:HOST="x86_64-w64-cygwin" + $env:MSVCC="/cygdrive/c/projects/libffi/msvcc.sh -m64" + $env:SRC_ARCHITECTURE="x86" + } + - 'appveyor DownloadFile https://cygwin.com/setup-x86.exe -FileName setup.exe' + - 'setup.exe -qnNdO -R "%CYG_ROOT%" -s "%CYG_MIRROR%" -l "%CYG_CACHE%" -P dejagnu >NUL' + - '%CYG_ROOT%/bin/bash -lc "cygcheck -dc cygwin"' + - echo call VsDevCmd to set VS150COMNTOOLS + - call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\Tools\VsDevCmd.bat" + - ps: $env:VSCOMNTOOLS=(Get-Content ("env:VS" + "$env:VSVER" + "0COMNTOOLS")) + - echo "Using Visual Studio %VSVER%.0 at %VSCOMNTOOLS%" + - call "%VSCOMNTOOLS%..\..\vc\Auxiliary\Build\vcvarsall.bat" %VCVARS_PLATFORM% + +build_script: + - c:\cygwin\bin\sh -lc "(cd $OLDPWD; ./autogen.sh;)" + - c:\cygwin\bin\sh -lc "(cd $OLDPWD; ./configure CC='%MSVCC%' CXX='%MSVCC%' LD='link' CPP='cl -nologo -EP' CXXCPP='cl -nologo -EP' CPPFLAGS='-DFFI_BUILDING_DLL' AR='/cygdrive/c/projects/libffi/.travis/ar-lib lib' NM='dumpbin -symbols' STRIP=':' --build=$BUILD --host=$HOST;)" + - c:\cygwin\bin\sh -lc "(cd $OLDPWD; cp src/%SRC_ARCHITECTURE%/ffitarget.h include; make; find .;)" + - c:\cygwin\bin\sh -lc "(cd $OLDPWD; cp `find . -name 'libffi-?.dll'` $HOST/testsuite/; make check; cat `find ./ -name libffi.log`)" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.gitattributes b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.gitattributes new file mode 100644 index 0000000..f7d3833 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.gitattributes @@ -0,0 +1,4 @@ +* text=auto + +*.sln text eol=crlf +*.vcxproj* text eol=crlf diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.github/issue_template.md b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.github/issue_template.md new file mode 100644 index 0000000..e197e2c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.github/issue_template.md @@ -0,0 +1,10 @@ +## System Details + + + + +## Problems Description + + + + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.gitignore b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.gitignore new file mode 100644 index 0000000..5d39689 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.gitignore @@ -0,0 +1,38 @@ +.libs +.deps +*.o +*.lo +.dirstamp +*.la +Makefile +!testsuite/libffi.bhaible/Makefile +Makefile.in +aclocal.m4 +compile +!.travis/compile +configure +depcomp +doc/libffi.info +*~ +fficonfig.h.in +fficonfig.h +include/ffi.h +include/ffitarget.h +install-sh +libffi.pc +libtool +libtool-ldflags +ltmain.sh +m4/libtool.m4 +m4/lt*.m4 +mdate-sh +missing +stamp-h1 +libffi*gz +autom4te.cache +libffi.xcodeproj/xcuserdata +libffi.xcodeproj/project.xcworkspace +build_*/ +darwin_*/ +src/arm/trampoline.S +**/texinfo.tex diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis.yml b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis.yml new file mode 100644 index 0000000..8db2ddf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis.yml @@ -0,0 +1,83 @@ +--- +sudo: required + +language: cpp + +# For qemu-powered targets, get the list of supported processors from +# travis by setting QEMU_CPU=help, then set -mcpu= for the compilers +# accordingly. + +matrix: + include: + - os: linux + env: HOST=powerpc-eabisim RUNTESTFLAGS="--target_board powerpc-eabisim" DEJAGNU="/opt/.travis/site.exp" + - os: linux + env: HOST=or1k-elf RUNTESTFLAGS="--target_board or1k-sim" DEJAGNU="/opt/.travis/site.exp" + - os: linux + env: HOST=m32r-elf RUNTESTFLAGS="--target_board m32r-sim" DEJAGNU="/opt/.travis/site.exp" + - os: linux + env: HOST=bfin-elf RUNTESTFLAGS="--target_board bfin-sim" DEJAGNU="/opt/.travis/site.exp" +# This configuration is still using the native x86 toolchain? +# - os: osx +# env: HOST=aarch64-apple-darwin13 + - os: osx + env: HOST=x86_64-apple-darwin10 + - os: linux + env: HOST=x86_64-w64-mingw32 MEVAL='export CC="x86_64-w64-mingw32-gcc" && CXX="x86_64-w64-mingw32-g++" RUNTESTFLAGS="--target_board wine-sim" DEJAGNU="$TRAVIS_BUILD_DIR/.travis/site.exp" CONFIGURE_OPTIONS=--disable-shared LIBFFI_TEST_OPTIMIZATION="-O2" + - os: linux + env: HOST=sh4-linux-gnu CONFIGURE_OPTIONS=--disable-shared QEMU_LD_PREFIX=/usr/sh4-linux-gnu + - os: linux + env: HOST=alpha-linux-gnu CONFIGURE_OPTIONS=--disable-shared QEMU_LD_PREFIX=/usr/alpha-linux-gnu + - os: linux + env: HOST=m68k-linux-gnu MEVAL='export CC="m68k-linux-gnu-gcc-8 -mcpu=547x" && CXX="m68k-linux-gnu-g++-8 -mcpu=547x"' CONFIGURE_OPTIONS=--disable-shared QEMU_LD_PREFIX=/usr/m68k-linux-gnu QEMU_CPU=cfv4e + - os: linux + arch: s390x + env: HOST=s390x-linux-gnu + - os: linux + arch: ppc64le + env: HOST=ppc64le-linux-gnu + - os: linux + arch: arm64 + env: HOST=aarch64-linux-gnu + - os: linux + arch: arm64 + env: HOST=aarch64-linux-gnu + compiler: clang + - os: linux + env: HOST=arm32v7-linux-gnu LIBFFI_TEST_OPTIMIZATION="-O0" + - os: linux + env: HOST=arm32v7-linux-gnu LIBFFI_TEST_OPTIMIZATION="-O2" + - os: linux + env: HOST=arm32v7-linux-gnu LIBFFI_TEST_OPTIMIZATION="-O2 -fomit-frame-pointer" +# The sparc64 linux system in the GCC compile farm is non-responsive. +# - os: linux +# env: HOST=sparc64-linux-gnu +# The mips64 linux system in the GCC compile farm is not allowing logins +# - os: linux +# env: HOST=mips64el-linux-gnu + - os: linux + compiler: gcc + env: HOST=i386-pc-linux-gnu MEVAL='export CC="$CC -m32" && CXX="$CXX -m32"' + - os: linux + compiler: gcc + - os: linux + compiler: gcc + env: CONFIGURE_OPTIONS=--disable-shared + - os: linux + compiler: clang + - os: linux + compiler: clang + env: CONFIGURE_OPTIONS=--disable-shared + - os: linux + env: HOST=moxie-elf MEVAL='export PATH=/opt/moxielogic/bin:$PATH && CC=moxie-elf-gcc && CXX=moxie-elf-g++' LDFLAGS=-Tsim.ld RUNTESTFLAGS="--target_board moxie-sim" DEJAGNU="$TRAVIS_BUILD_DIR/.travis/site.exp" + +before_install: + - if test x"$MEVAL" != x; then eval ${MEVAL}; fi + +install: + - travis_wait 30 ./.travis/install.sh + +script: + - if ! test x"$MEVAL" = x; then eval ${MEVAL}; fi + - travis_wait 115 sleep infinity & + - ./.travis/build.sh diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/ar-lib b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/ar-lib new file mode 100755 index 0000000..0baa4f6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/ar-lib @@ -0,0 +1,270 @@ +#! /bin/sh +# Wrapper for Microsoft lib.exe + +me=ar-lib +scriptversion=2012-03-01.08; # UTC + +# Copyright (C) 2010-2018 Free Software Foundation, Inc. +# Written by Peter Rosin . +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# This file is maintained in Automake, please report +# bugs to or send patches to +# . + + +# func_error message +func_error () +{ + echo "$me: $1" 1>&2 + exit 1 +} + +file_conv= + +# func_file_conv build_file +# Convert a $build file to $host form and store it in $file +# Currently only supports Windows hosts. +func_file_conv () +{ + file=$1 + case $file in + / | /[!/]*) # absolute file, and not a UNC file + if test -z "$file_conv"; then + # lazily determine how to convert abs files + case `uname -s` in + MINGW*) + file_conv=mingw + ;; + CYGWIN*) + file_conv=cygwin + ;; + *) + file_conv=wine + ;; + esac + fi + case $file_conv in + mingw) + file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` + ;; + cygwin) + file=`cygpath -m "$file" || echo "$file"` + ;; + wine) + file=`winepath -w "$file" || echo "$file"` + ;; + esac + ;; + esac +} + +# func_at_file at_file operation archive +# Iterate over all members in AT_FILE performing OPERATION on ARCHIVE +# for each of them. +# When interpreting the content of the @FILE, do NOT use func_file_conv, +# since the user would need to supply preconverted file names to +# binutils ar, at least for MinGW. +func_at_file () +{ + operation=$2 + archive=$3 + at_file_contents=`cat "$1"` + eval set x "$at_file_contents" + shift + + for member + do + $AR -NOLOGO $operation:"$member" "$archive" || exit $? + done +} + +case $1 in + '') + func_error "no command. Try '$0 --help' for more information." + ;; + -h | --h*) + cat < libffi.log + + ./rlgl l --key=${RLGL_KEY} https://rl.gl + ID=$(./rlgl start) + ./rlgl e --id=$ID --policy=https://github.com/libffi/rlgl-policy.git libffi.log + exit $? +} + +function build_linux() +{ + ./autogen.sh + ./configure ${HOST+--host=$HOST} ${CONFIGURE_OPTIONS} || cat */config.log + make + make dist + make check RUNTESTFLAGS="-a $RUNTESTFLAGS" + + ./rlgl l --key=${RLGL_KEY} https://rl.gl + ID=$(./rlgl start) + ./rlgl e --id=$ID --policy=https://github.com/libffi/rlgl-policy.git */testsuite/libffi.log + exit $? +} + +function build_foreign_linux() +{ + ${DOCKER} run --rm -t -i -v $(pwd):/opt ${SET_QEMU_CPU} -e LIBFFI_TEST_OPTIMIZATION="${LIBFFI_TEST_OPTIMIZATION}" $2 bash -c /opt/.travis/build-in-container.sh + + ./rlgl l --key=${RLGL_KEY} https://rl.gl + ID=$(./rlgl start) + ./rlgl e --id=$ID --policy=https://github.com/libffi/rlgl-policy.git */testsuite/libffi.log + exit $? +} + +function build_cross_linux() +{ + ${DOCKER} run --rm -t -i -v $(pwd):/opt ${SET_QEMU_CPU} -e HOST="${HOST}" -e CC="${HOST}-gcc-8 ${GCC_OPTIONS}" -e CXX="${HOST}-g++-8 ${GCC_OPTIONS}" -e LIBFFI_TEST_OPTIMIZATION="${LIBFFI_TEST_OPTIMIZATION}" moxielogic/cross-ci-build-container:latest bash -c /opt/.travis/build-in-container.sh + + ./rlgl l --key=${RLGL_KEY} https://rl.gl + ID=$(./rlgl start) + ./rlgl e --id=$ID --policy=https://github.com/libffi/rlgl-policy.git */testsuite/libffi.log + exit $? +} + +function build_cross() +{ + ${DOCKER} pull quay.io/moxielogic/libffi-ci-${HOST} + ${DOCKER} run --rm -t -i -v $(pwd):/opt -e HOST="${HOST}" -e CC="${HOST}-gcc ${GCC_OPTIONS}" -e CXX="${HOST}-g++ ${GCC_OPTIONS}" -e TRAVIS_BUILD_DIR=/opt -e DEJAGNU="${DEJAGNU}" -e RUNTESTFLAGS="${RUNTESTFLAGS}" -e LIBFFI_TEST_OPTIMIZATION="${LIBFFI_TEST_OPTIMIZATION}" quay.io/moxielogic/libffi-ci-${HOST} bash -c /opt/.travis/build-cross-in-container.sh + + ./rlgl l --key=${RLGL_KEY} https://rl.gl + ID=$(./rlgl start) + ./rlgl e --id=$ID --policy=https://github.com/libffi/rlgl-policy.git */testsuite/libffi.log + exit $? +} + +function build_ios() +{ + which python +# export PYTHON_BIN=/usr/local/bin/python + ./generate-darwin-source-and-headers.py --only-ios + xcodebuild -showsdks + xcodebuild -project libffi.xcodeproj -target "libffi-iOS" -configuration Release -sdk iphoneos11.4 + exit $? +} + +function build_macosx() +{ + which python +# export PYTHON_BIN=/usr/local/bin/python + ./generate-darwin-source-and-headers.py --only-osx + xcodebuild -showsdks + xcodebuild -project libffi.xcodeproj -target "libffi-Mac" -configuration Release -sdk macosx10.13 + echo "Finished build" + exit $? +} + +case "$HOST" in + arm-apple-darwin*) + ./autogen.sh + build_ios + ;; + x86_64-apple-darwin*) + ./autogen.sh + build_macosx + ;; + arm32v7-linux-gnu) + ./autogen.sh + build_foreign_linux arm moxielogic/arm32v7-ci-build-container:latest + ;; + mips64el-linux-gnu | sparc64-linux-gnu) + build_cfarm + ;; + bfin-elf ) + ./autogen.sh + GCC_OPTIONS=-msim build_cross + ;; + m32r-elf ) + ./autogen.sh + build_cross + ;; + or1k-elf ) + ./autogen.sh + build_cross + ;; + powerpc-eabisim ) + ./autogen.sh + build_cross + ;; + m68k-linux-gnu ) + ./autogen.sh + GCC_OPTIONS=-mcpu=547x build_cross_linux + ;; + alpha-linux-gnu | sh4-linux-gnu ) + ./autogen.sh + build_cross_linux + ;; + *) + ./autogen.sh + build_linux + ;; +esac diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/compile b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/compile new file mode 100755 index 0000000..655932a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/compile @@ -0,0 +1,351 @@ +#! /bin/sh +# Wrapper for compilers which do not understand '-c -o'. + +scriptversion=2018-03-27.18; # UTC + +# Copyright (C) 1999-2018 Free Software Foundation, Inc. +# Written by Tom Tromey . +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# This file is maintained in Automake, please report +# bugs to or send patches to +# . + +nl=' +' + +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent tools from complaining about whitespace usage. +IFS=" "" $nl" + +file_conv= + +# func_file_conv build_file lazy +# Convert a $build file to $host form and store it in $file +# Currently only supports Windows hosts. If the determined conversion +# type is listed in (the comma separated) LAZY, no conversion will +# take place. +func_file_conv () +{ + file=$1 + case $file in + / | /[!/]*) # absolute file, and not a UNC file + if test -z "$file_conv"; then + # lazily determine how to convert abs files + case `uname -s` in + MINGW*) + file_conv=mingw + ;; + CYGWIN*) + file_conv=cygwin + ;; + *) + file_conv=wine + ;; + esac + fi + case $file_conv/,$2, in + *,$file_conv,*) + ;; + mingw/*) + file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` + ;; + cygwin/*) + file=`cygpath -m "$file" || echo "$file"` + ;; + wine/*) + file=`winepath -w "$file" || echo "$file"` + ;; + esac + ;; + esac +} + +# func_cl_dashL linkdir +# Make cl look for libraries in LINKDIR +func_cl_dashL () +{ + func_file_conv "$1" + if test -z "$lib_path"; then + lib_path=$file + else + lib_path="$lib_path;$file" + fi + linker_opts="$linker_opts -LIBPATH:$file" +} + +# func_cl_dashl library +# Do a library search-path lookup for cl +func_cl_dashl () +{ + lib=$1 + found=no + save_IFS=$IFS + IFS=';' + for dir in $lib_path $LIB + do + IFS=$save_IFS + if $shared && test -f "$dir/$lib.dll.lib"; then + found=yes + lib=$dir/$lib.dll.lib + break + fi + if test -f "$dir/$lib.lib"; then + found=yes + lib=$dir/$lib.lib + break + fi + if test -f "$dir/lib$lib.a"; then + found=yes + lib=$dir/lib$lib.a + break + fi + done + IFS=$save_IFS + + if test "$found" != yes; then + lib=$lib.lib + fi +} + +# func_cl_wrapper cl arg... +# Adjust compile command to suit cl +func_cl_wrapper () +{ + # Assume a capable shell + lib_path= + shared=: + linker_opts= + for arg + do + if test -n "$eat"; then + eat= + else + case $1 in + -o) + # configure might choose to run compile as 'compile cc -o foo foo.c'. + eat=1 + case $2 in + *.o | *.[oO][bB][jJ]) + func_file_conv "$2" + set x "$@" -Fo"$file" + shift + ;; + *) + func_file_conv "$2" + set x "$@" -Fe"$file" + shift + ;; + esac + ;; + -I) + eat=1 + func_file_conv "$2" mingw + set x "$@" -I"$file" + shift + ;; + -I*) + func_file_conv "${1#-I}" mingw + set x "$@" -I"$file" + shift + ;; + -l) + eat=1 + func_cl_dashl "$2" + set x "$@" "$lib" + shift + ;; + -l*) + func_cl_dashl "${1#-l}" + set x "$@" "$lib" + shift + ;; + -L) + eat=1 + func_cl_dashL "$2" + ;; + -L*) + func_cl_dashL "${1#-L}" + ;; + -static) + shared=false + ;; + -warn) + eat=1 + ;; + -Wl,*) + arg=${1#-Wl,} + save_ifs="$IFS"; IFS=',' + for flag in $arg; do + IFS="$save_ifs" + linker_opts="$linker_opts $flag" + done + IFS="$save_ifs" + ;; + -Xlinker) + eat=1 + linker_opts="$linker_opts $2" + ;; + -*) + set x "$@" "$1" + shift + ;; + *.cc | *.CC | *.cxx | *.CXX | *.[cC]++) + func_file_conv "$1" + set x "$@" -Tp"$file" + shift + ;; + *.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO]) + func_file_conv "$1" mingw + set x "$@" "$file" + shift + ;; + *) + set x "$@" "$1" + shift + ;; + esac + fi + shift + done + if test -n "$linker_opts"; then + linker_opts="-link$linker_opts" + fi + exec "$@" $linker_opts + exit 1 +} + +eat= + +case $1 in + '') + echo "$0: No command. Try '$0 --help' for more information." 1>&2 + exit 1; + ;; + -h | --h*) + cat <<\EOF +Usage: compile [--help] [--version] PROGRAM [ARGS] + +Wrapper for compilers which do not understand '-c -o'. +Remove '-o dest.o' from ARGS, run PROGRAM with the remaining +arguments, and rename the output as expected. + +If you are trying to build a whole package this is not the +right script to run: please start by reading the file 'INSTALL'. + +Report bugs to . +EOF + exit $? + ;; + -v | --v*) + echo "compile $scriptversion" + exit $? + ;; + cl | *[/\\]cl | cl.exe | *[/\\]cl.exe | \ + icl | *[/\\]icl | icl.exe | *[/\\]icl.exe ) + func_cl_wrapper "$@" # Doesn't return... + ;; +esac + +ofile= +cfile= + +for arg +do + if test -n "$eat"; then + eat= + else + case $1 in + -o) + # configure might choose to run compile as 'compile cc -o foo foo.c'. + # So we strip '-o arg' only if arg is an object. + eat=1 + case $2 in + *.o | *.obj) + ofile=$2 + ;; + *) + set x "$@" -o "$2" + shift + ;; + esac + ;; + *.c) + cfile=$1 + set x "$@" "$1" + shift + ;; + *) + set x "$@" "$1" + shift + ;; + esac + fi + shift +done + +if test -z "$ofile" || test -z "$cfile"; then + # If no '-o' option was seen then we might have been invoked from a + # pattern rule where we don't need one. That is ok -- this is a + # normal compilation that the losing compiler can handle. If no + # '.c' file was seen then we are probably linking. That is also + # ok. + exec "$@" +fi + +# Name of file we expect compiler to create. +cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'` + +# Create the lock directory. +# Note: use '[/\\:.-]' here to ensure that we don't use the same name +# that we are using for the .o file. Also, base the name on the expected +# object file name, since that is what matters with a parallel build. +lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d +while true; do + if mkdir "$lockdir" >/dev/null 2>&1; then + break + fi + sleep 1 +done +# FIXME: race condition here if user kills between mkdir and trap. +trap "rmdir '$lockdir'; exit 1" 1 2 15 + +# Run the compile. +"$@" +ret=$? + +if test -f "$cofile"; then + test "$cofile" = "$ofile" || mv "$cofile" "$ofile" +elif test -f "${cofile}bj"; then + test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile" +fi + +rmdir "$lockdir" +exit $ret + +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'before-save-hook 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-time-zone: "UTC0" +# time-stamp-end: "; # UTC" +# End: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/install.sh b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/install.sh new file mode 100755 index 0000000..2420245 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/install.sh @@ -0,0 +1,71 @@ +#!/bin/bash +set -x + +if [[ $TRAVIS_OS_NAME != 'linux' ]]; then + brew update > brew-update.log 2>&1 + # fix an issue with libtool on travis by reinstalling it + brew uninstall libtool; + brew install libtool dejagnu; + + # Download and extract the rlgl client + wget -qO - https://rl.gl/cli/rlgl-darwin-amd64.tgz | \ + tar --strip-components=2 -xvzf - ./rlgl/rlgl; + +else + # Download and extract the rlgl client + case $HOST in + aarch64-linux-gnu) + wget -qO - https://rl.gl/cli/rlgl-linux-arm.tgz | \ + tar --strip-components=2 -xvzf - ./rlgl/rlgl; + ;; + ppc64le-linux-gnu) + wget -qO - https://rl.gl/cli/rlgl-linux-ppc64le.tgz | \ + tar --strip-components=2 -xvzf - ./rlgl/rlgl; + ;; + s390x-linux-gnu) + wget -qO - https://rl.gl/cli/rlgl-linux-s390x.tgz | \ + tar --strip-components=2 -xvzf - ./rlgl/rlgl; + ;; + *) + wget -qO - https://rl.gl/cli/rlgl-linux-amd64.tgz | \ + tar --strip-components=2 -xvzf - ./rlgl/rlgl; + ;; + esac + + sudo apt-get clean # clear the cache + sudo apt-get update + case $HOST in + mips64el-linux-gnu | sparc64-linux-gnu) + ;; + alpha-linux-gnu | arm32v7-linux-gnu | m68k-linux-gnu | sh4-linux-gnu) + sudo apt-get install qemu-user-static + ;; + hppa-linux-gnu ) + sudo apt-get install -y qemu-user-static g++-5-hppa-linux-gnu + ;; + i386-pc-linux-gnu) + sudo apt-get install gcc-multilib g++-multilib; + ;; + moxie-elf) + echo 'deb https://repos.moxielogic.org:7114/MoxieLogic moxiedev main' | sudo tee -a /etc/apt/sources.list + sudo apt-get clean # clear the cache + sudo apt-get update ## -qq + sudo apt-get update + sudo apt-get install -y --allow-unauthenticated moxielogic-moxie-elf-gcc moxielogic-moxie-elf-gcc-c++ moxielogic-moxie-elf-gcc-libstdc++ moxielogic-moxie-elf-gdb-sim + ;; + x86_64-w64-mingw32) + sudo apt-get install gcc-mingw-w64-x86-64 g++-mingw-w64-x86-64 wine; + ;; + i686-w32-mingw32) + sudo apt-get install gcc-mingw-w64-i686 g++-mingw-w64-i686 wine; + ;; + esac + case $HOST in + arm32v7-linux-gnu) + # don't install host tools + ;; + *) + sudo apt-get install dejagnu texinfo sharutils + ;; + esac +fi diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/m32r-sim.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/m32r-sim.exp new file mode 100644 index 0000000..c18123f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/m32r-sim.exp @@ -0,0 +1,58 @@ +# Copyright (C) 2010, 2019 Free Software Foundation, Inc. +# +# This file is part of DejaGnu. +# +# DejaGnu is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# DejaGnu is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with DejaGnu; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, MA 02110, USA. + +# This is a list of toolchains that are supported on this board. +set_board_info target_install {m32r-elf} + +# Load the generic configuration for this board. This will define a basic set +# of routines needed by the tool to communicate with the board. +load_generic_config "sim" + +# basic-sim.exp is a basic description for the standard Cygnus simulator. +load_base_board_description "basic-sim" + +# "m32r" is the name of the sim subdir in devo/sim. +setup_sim m32r + +# No multilib options needed by default. +process_multilib_options "" + +# We only support newlib on this target. We assume that all multilib +# options have been specified before we get here. + +set_board_info compiler "[find_gcc]" +set_board_info cflags "[libgloss_include_flags] [newlib_include_flags]" +set_board_info ldflags "[libgloss_link_flags] [newlib_link_flags]" + +# Configuration settings for testsuites +set_board_info noargs 1 +set_board_info gdb,nosignals 1 +set_board_info gdb,noresults 1 +set_board_info gdb,cannot_call_functions 1 +set_board_info gdb,skip_float_tests 1 +set_board_info gdb,can_reverse 1 +set_board_info gdb,use_precord 1 + +# More time is needed +set_board_info gcc,timeout 800 +set_board_info gdb,timeout 60 + +# Used by a few gcc.c-torture testcases to delimit how large the stack can +# be. +set_board_info gcc,stack_size 5000 + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/moxie-sim.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/moxie-sim.exp new file mode 100644 index 0000000..32979ea --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/moxie-sim.exp @@ -0,0 +1,60 @@ +# Copyright (C) 2010 Free Software Foundation, Inc. +# +# This file is part of DejaGnu. +# +# DejaGnu is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# DejaGnu is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with DejaGnu; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, MA 02110, USA. + +# This is a list of toolchains that are supported on this board. +set_board_info target_install {moxie-elf} + +# Load the generic configuration for this board. This will define a basic set +# of routines needed by the tool to communicate with the board. +load_generic_config "sim" + +# basic-sim.exp is a basic description for the standard Cygnus simulator. +load_base_board_description "basic-sim" + +# "moxie" is the name of the sim subdir in devo/sim. +setup_sim moxie + +# No multilib options needed by default. +process_multilib_options "" + +# We only support newlib on this target. We assume that all multilib +# options have been specified before we get here. + +set_board_info compiler "[find_gcc]" +set_board_info cflags "[libgloss_include_flags] [newlib_include_flags]" +set_board_info ldflags "[libgloss_link_flags] [newlib_link_flags]" +# No linker script needed. +set_board_info ldscript "-Tsim.ld" + +# Configuration settings for testsuites +set_board_info noargs 1 +set_board_info gdb,nosignals 1 +set_board_info gdb,noresults 1 +set_board_info gdb,cannot_call_functions 1 +set_board_info gdb,skip_float_tests 1 +set_board_info gdb,can_reverse 1 +set_board_info gdb,use_precord 1 + +# More time is needed +set_board_info gcc,timeout 800 +set_board_info gdb,timeout 60 + +# Used by a few gcc.c-torture testcases to delimit how large the stack can +# be. +set_board_info gcc,stack_size 5000 + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/or1k-sim.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/or1k-sim.exp new file mode 100644 index 0000000..3920413 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/or1k-sim.exp @@ -0,0 +1,58 @@ +# Copyright (C) 2010, 2019 Free Software Foundation, Inc. +# +# This file is part of DejaGnu. +# +# DejaGnu is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# DejaGnu is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with DejaGnu; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, MA 02110, USA. + +# This is a list of toolchains that are supported on this board. +set_board_info target_install {or1k-elf} + +# Load the generic configuration for this board. This will define a basic set +# of routines needed by the tool to communicate with the board. +load_generic_config "sim" + +# basic-sim.exp is a basic description for the standard Cygnus simulator. +load_base_board_description "basic-sim" + +# "or1k" is the name of the sim subdir in devo/sim. +setup_sim or1k + +# No multilib options needed by default. +process_multilib_options "" + +# We only support newlib on this target. We assume that all multilib +# options have been specified before we get here. + +set_board_info compiler "[find_gcc]" +set_board_info cflags "[libgloss_include_flags] [newlib_include_flags]" +set_board_info ldflags "[libgloss_link_flags] [newlib_link_flags]" + +# Configuration settings for testsuites +set_board_info noargs 1 +set_board_info gdb,nosignals 1 +set_board_info gdb,noresults 1 +set_board_info gdb,cannot_call_functions 1 +set_board_info gdb,skip_float_tests 1 +set_board_info gdb,can_reverse 1 +set_board_info gdb,use_precord 1 + +# More time is needed +set_board_info gcc,timeout 800 +set_board_info gdb,timeout 60 + +# Used by a few gcc.c-torture testcases to delimit how large the stack can +# be. +set_board_info gcc,stack_size 5000 + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/powerpc-eabisim.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/powerpc-eabisim.exp new file mode 100644 index 0000000..285fd4f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/powerpc-eabisim.exp @@ -0,0 +1,58 @@ +# Copyright (C) 2010, 2019 Free Software Foundation, Inc. +# +# This file is part of DejaGnu. +# +# DejaGnu is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# DejaGnu is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with DejaGnu; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, MA 02110, USA. + +# This is a list of toolchains that are supported on this board. +set_board_info target_install {powerpc-eabisim} + +# Load the generic configuration for this board. This will define a basic set +# of routines needed by the tool to communicate with the board. +load_generic_config "sim" + +# basic-sim.exp is a basic description for the standard Cygnus simulator. +load_base_board_description "basic-sim" + +# "powerpc" is the name of the sim subdir in devo/sim. +setup_sim powerpc + +# No multilib options needed by default. +process_multilib_options "" + +# We only support newlib on this target. We assume that all multilib +# options have been specified before we get here. + +set_board_info compiler "[find_gcc]" +set_board_info cflags "[libgloss_include_flags] [newlib_include_flags]" +set_board_info ldflags "[libgloss_link_flags] [newlib_link_flags]" + +# Configuration settings for testsuites +set_board_info noargs 1 +set_board_info gdb,nosignals 1 +set_board_info gdb,noresults 1 +set_board_info gdb,cannot_call_functions 1 +set_board_info gdb,skip_float_tests 1 +set_board_info gdb,can_reverse 1 +set_board_info gdb,use_precord 1 + +# More time is needed +set_board_info gcc,timeout 800 +set_board_info gdb,timeout 60 + +# Used by a few gcc.c-torture testcases to delimit how large the stack can +# be. +set_board_info gcc,stack_size 5000 + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/site.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/site.exp new file mode 100644 index 0000000..644ec63 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/site.exp @@ -0,0 +1,27 @@ +# Copyright (C) 2008, 2010, 2018, 2019 Anthony Green + +# Make sure we look in the right place for the board description files. +if ![info exists boards_dir] { + set boards_dir {} +} + +lappend boards_dir $::env(TRAVIS_BUILD_DIR)/.travis + +verbose "Global Config File: target_triplet is $target_triplet" 2 +global target_list + +case "$target_triplet" in { + { "bfin-elf" } { + set target_list "bfin-sim" + } + { "m32r-elf" } { + set target_list "m32r-sim" + } + { "moxie-elf" } { + set target_list "moxie-sim" + } + { "or1k-elf" } { + set target_list "or1k-sim" + } +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/wine-sim.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/wine-sim.exp new file mode 100644 index 0000000..1ad6038 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/.travis/wine-sim.exp @@ -0,0 +1,55 @@ +# Copyright (C) 2010, 2019 Free Software Foundation, Inc. +# +# This file is part of DejaGnu. +# +# DejaGnu is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# DejaGnu is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with DejaGnu; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, MA 02110, USA. + +# This is a list of toolchains that are supported on this board. +set_board_info target_install {i686-w64-mingw32} + +# Load the generic configuration for this board. This will define a basic set +# of routines needed by the tool to communicate with the board. +load_generic_config "sim" + +set_board_info sim "wineconsole --backend=curses" +set_board_info is_simulator 1 + +# No multilib options needed by default. +process_multilib_options "" + +# We only support newlib on this target. We assume that all multilib +# options have been specified before we get here. + +set_board_info compiler "[find_gcc]" +set_board_info cflags "[libgloss_include_flags] [newlib_include_flags]" +set_board_info ldflags "[libgloss_link_flags] [newlib_link_flags]" + +# Configuration settings for testsuites +set_board_info noargs 1 +set_board_info gdb,nosignals 1 +set_board_info gdb,noresults 1 +set_board_info gdb,cannot_call_functions 1 +set_board_info gdb,skip_float_tests 1 +set_board_info gdb,can_reverse 1 +set_board_info gdb,use_precord 1 + +# More time is needed +set_board_info gcc,timeout 800 +set_board_info gdb,timeout 60 + +# Used by a few gcc.c-torture testcases to delimit how large the stack can +# be. +set_board_info gcc,stack_size 5000 + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/ChangeLog.old b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/ChangeLog.old new file mode 100644 index 0000000..8de1ca7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/ChangeLog.old @@ -0,0 +1,7407 @@ +Libffi change logs used to be maintained in separate ChangeLog files. +These days we generate them directly from the git commit messages. +The old ChangeLog files are saved here in order to maintain the historical +record. + +============================================================================= +From the old ChangeLog.libffi-3.1 file... + +2014-03-16 Josh Triplett + + * ChangeLog: Archive to ChangeLog.libffi-3.1 and delete. Future + changelogs will come from git, with autogenerated snapshots shipped in + distributed tarballs. + +2014-03-16 Josh Triplett + + Add support for stdcall, thiscall, and fastcall on non-Windows + x86-32. + + Linux supports the stdcall calling convention, either via + functions explicitly declared with the stdcall attribute, or via + code compiled with -mrtd which effectively makes stdcall the + default. + + This introduces FFI_STDCALL, FFI_THISCALL, and FFI_FASTCALL on + non-Windows x86-32 platforms, as non-default calling conventions. + + * Makefile.am: Compile in src/x86/win32.S on non-Windows x86-32. + * src/x86/ffitarget.h: Add FFI_STDCALL, FFI_THISCALL, and + FFI_FASTCALL on non-Windows x86-32. Increase trampoline size to + accomodate these calling conventions, and unify some ifdeffery. + * src/x86/ffi.c: Add support for FFI_STDCALL, FFI_THISCALL, and + FFI_FASTCALL on non-Windows x86-32 platforms; update ifdeffery. + * src/x86/win32.S: Support compiling on non-Windows x86-32 + platforms. On those platforms, avoid redefining the SYSV symbols + already provided by src/x86/sysv.S. + * testsuite/libffi.call/closure_stdcall.c: Run on non-Windows. + #define __stdcall if needed. + * testsuite/libffi.call/closure_thiscall.c: Run on non-Windows. + #define __fastcall if needed. + * testsuite/libffi.call/fastthis1_win32.c: Run on non-Windows. + * testsuite/libffi.call/fastthis2_win32.c: Ditto. + * testsuite/libffi.call/fastthis3_win32.c: Ditto. + * testsuite/libffi.call/many2_win32.c: Ditto. + * testsuite/libffi.call/many_win32.c: Ditto. + * testsuite/libffi.call/strlen2_win32.c: Ditto. + * testsuite/libffi.call/strlen_win32.c: Ditto. + * testsuite/libffi.call/struct1_win32.c: Ditto. + * testsuite/libffi.call/struct2_win32.c: Ditto. + +2014-03-16 Josh Triplett + + * prep_cif.c: Remove unnecessary ifdef for X86_WIN32. + ffi_prep_cif_core had a special case for X86_WIN32, checking for + FFI_THISCALL in addition to the FFI_FIRST_ABI-to-FFI_LAST_ABI + range before returning FFI_BAD_ABI. However, on X86_WIN32, + FFI_THISCALL already falls in that range, making the special case + unnecessary. Remove it. + +2014-03-16 Josh Triplett + + * testsuite/libffi.call/closure_stdcall.c, + testsuite/libffi.call/closure_thiscall.c: Remove fragile stack + pointer checks. These files included inline assembly to save the + stack pointer before and after the call, and compare the values. + However, compilers can and do leave the stack in different states + for these two pieces of inline assembly, such as by saving a + temporary value on the stack across the call; observed with gcc + -Os, and verified as spurious through careful inspection of + disassembly. + +2014-03-16 Josh Triplett + + * testsuite/libffi.call/many.c: Avoid spurious failure due to + excess floating-point precision. + * testsuite/libffi.call/many_win32.c: Ditto. + +2014-03-16 Josh Triplett + + * libtool-ldflags: Re-add. + +2014-03-16 Josh Triplett + + * Makefile.in, aclocal.m4, compile, config.guess, config.sub, + configure, depcomp, include/Makefile.in, install-sh, + libtool-ldflags, ltmain.sh, m4/libtool.m4, m4/ltoptions.m4, + m4/ltsugar.m4, m4/ltversion.m4, m4/lt~obsolete.m4, + man/Makefile.in, mdate-sh, missing, testsuite/Makefile.in: Delete + autogenerated files from version control. + * .gitignore: Add autogenerated files. + * autogen.sh: New script to generate the autogenerated files. + * README: Document requirement to run autogen.sh when building + directly from version control. + * .travis.yml: Run autogen.sh + +2014-03-14 Anthony Green + + * configure, Makefile.in: Rebuilt. + +2014-03-10 Mike Hommey + + * configure.ac: Allow building for mipsel with Android NDK r8. + * Makefile.am (AM_MAKEFLAGS): Replace double quotes with single + quotes. + +2014-03-10 Landry Breuil + + * configure.ac: Ensure the linker supports @unwind sections in libffi. + +2014-03-01 Anthony Green + + * Makefile.am (EXTRA_DIST): Replace old scripts with + generate-darwin-source-and-headers.py. + * Makefile.in: Rebuilt. + +2014-02-28 Anthony Green + + * Makefile.am (AM_CFLAGS): Reintroduce missing -DFFI_DEBUG for + --enable-debug builds. + * Makefile.in: Rebuilt. + +2014-02-28 Makoto Kato + + * src/closures.c: Fix build failure when using clang for Android. + +2014-02-28 Marcin Wojdyr + + * libffi.pc.in (toolexeclibdir): use -L${toolexeclibdir} instead + of -L${libdir}. + +2014-02-28 Paulo Pizarro + + * src/bfin/sysv.S: Calling functions in shared libraries requires + considering the GOT. + +2014-02-28 Josh Triplett + + * src/x86/ffi64.c (classify_argument): Handle case where + FFI_TYPE_LONGDOUBLE == FFI_TYPE_DOUBLE. + +2014-02-28 Anthony Green + + * ltmain.sh: Generate with libtool-2.4.2.418. + * m4/libtool.m4, m4/ltoptions.m4, m4/ltversion.m4: Ditto. + * configure: Rebuilt. + +2014-02-28 Dominik Vogt + + * configure.ac (AC_ARG_ENABLE struct): Fix typo in help + message. + (AC_ARG_ENABLE raw_api): Ditto. + * configure, fficonfig.h.in: Rebuilt. + +2014-02-28 Will Newton + + * src/arm/sysv.S: Initialize IP register with FP. + +2014-02-28 Yufeng Zhang + + * src/aarch64/sysv.S (ffi_closure_SYSV): Use x29 as the + main CFA reg; update cfi_rel_offset. + +2014-02-15 Marcus Comstedt + + * src/powerpc/ffi_linux64.c, src/powerpc/linux64_closure.S: Remove + assumption on contents of r11 in closure. + +2014-02-09 Heiher + + * src/mips/n32.S: Fix call floating point va function. + +2014-01-21 Zachary Waldowski + + * src/aarch64/ffi.c: Fix missing semicolons on assertions under + debug mode. + +2013-12-30 Zachary Waldowski + + * .gitignore: Exclude darwin_* generated source and build_* trees. + * src/aarch64/ffi.c, src/arm/ffi.c, src/x86/ffi.c: Inhibit Clang + previous prototype warnings. + * src/arm/ffi.c: Prevent NULL dereference, fix short type warning + * src/dlmalloc.c: Fix warnings from set_segment_flags return type, + and the native use of size_t for malloc on platforms + * src/arm/sysv.S: Use unified syntax. Clang clean-ups for + ARM_FUNC_START. + * generate-osx-source-and-headers.py: Remove. + * build-ios.sh: Remove. + * libffi.xcodeproj/project.pbxproj: Rebuild targets. Include + x86_64+aarch64 pieces in library. Export headers properly. + * src/x86/ffi64.c: More Clang warning clean-ups. + * src/closures.c (open_temp_exec_file_dir): Use size_t. + * src/prep_cif.c (ffi_prep_cif_core): Cast ALIGN result. + * src/aarch64/sysv.S: Use CNAME for global symbols. Only use + .size for ELF targets. + * src/aarch64/ffi.c: Clean up for double == long double. Clean up + from Clang warnings. Use Clang cache invalidation builtin. Use + size_t in place of unsigned in many places. Accommodate for + differences in Apple AArch64 ABI. + +2013-12-02 Daniel Rodríguez Troitiño + + * generate-darwin-source-and-headers.py: Clean up, modernize, + merged version of previous scripts. + +2013-11-21 Anthony Green + + * configure, Makefile.in, include/Makefile.in, include/ffi.h.in, + man/Makefile.in, testsuite/Makefile.in, fficonfig.h.in: Rebuilt. + +2013-11-21 Alan Modra + + * Makefile.am (EXTRA_DIST): Add new src/powerpc files. + (nodist_libffi_la_SOURCES ): Likewise. + * configure.ac (HAVE_LONG_DOUBLE_VARIANT): Define for powerpc. + * include/ffi.h.in (ffi_prep_types): Declare. + * src/prep_cif.c (ffi_prep_cif_core): Call ffi_prep_types. + * src/types.c (FFI_NONCONST_TYPEDEF): Define and use for + HAVE_LONG_DOUBLE_VARIANT. + * src/powerpc/ffi_powerpc.h: New file. + * src/powerpc/ffi.c: Split into.. + * src/powerpc/ffi_sysv.c: ..new file, and.. + * src/powerpc/ffi_linux64.c: ..new file, rewriting parts. + * src/powerpc/ffitarget.h (enum ffi_abi): Rewrite powerpc ABI + selection as bits controlling features. + * src/powerpc/linux64.S: For consistency, use POWERPC64 rather + than __powerpc64__. + * src/powerpc/linux64_closure.S: Likewise. + * src/powerpc/ppc_closure.S: Likewise. Move .note.FNU-stack + inside guard. + * src/powerpc/sysv.S: Likewise. + * configure: Regenerate. + * fficonfig.h.in: Regenerate. + * Makefile.in: Regenerate. + +2013-11-20 Alan Modra + + * src/powerpc/ffi.c (ffi_prep_cif_machdep_core): Use + NUM_FPR_ARG_REGISTERS64 and NUM_GPR_ARG_REGISTERS64 not their + 32-bit versions for 64-bit code. + * src/powerpc/linux64_closure.S: Don't use the return value area + as a parameter save area on ELFv2. + +2013-11-18 Iain Sandoe + + * src/powerpc/darwin.S (EH): Correct use of pcrel FDE encoding. + * src/powerpc/darwin_closure.S (EH): Likewise. Modernise picbase + labels. + +2013-11-18 Anthony Green + + * src/arm/ffi.c (ffi_call): Hoist declaration of temp to top of + function. + * src/arm/ffi.c (ffi_closure_inner): Moderize function declaration + to appease compiler. + Thanks for Gregory P. Smith . + +2013-11-18 Anthony Green + + * README (tested): Mention PowerPC ELFv2. + +2013-11-16 Alan Modra + + * src/powerpc/ppc_closure.S: Move errant #endif to where it belongs. + Don't bl .Luint128. + +2013-11-16 Alan Modra + + * src/powerpc/ffi.c (ffi_prep_cif_machdep_core): Use #if _CALL_ELF + test to select parameter save sizing for ELFv2 vs. ELFv1. + * src/powerpc/ffitarget.h (FFI_V2_TYPE_FLOAT_HOMOG, + FFI_V2_TYPE_DOUBLE_HOMOG, FFI_V2_TYPE_SMALL_STRUCT): Define. + (FFI_TRAMPOLINE_SIZE): Define variant for ELFv2. + * src/powerpc/ffi.c (FLAG_ARG_NEEDS_PSAVE): Define. + (discover_homogeneous_aggregate): New function. + (ffi_prep_args64): Adjust start of param save area for ELFv2. + Handle homogenous floating point struct parms. + (ffi_prep_cif_machdep_core): Adjust space calculation for ELFv2. + Handle ELFv2 return values. Set FLAG_ARG_NEEDS_PSAVE. Handle + homogenous floating point structs. + (ffi_call): Increase size of smst_buffer for ELFv2. Handle ELFv2. + (flush_icache): Compile for ELFv2. + (ffi_prep_closure_loc): Set up ELFv2 trampoline. + (ffi_closure_helper_LINUX64): Don't return all structs directly + to caller. Handle homogenous floating point structs. Handle + ELFv2 struct return values. + * src/powerpc/linux64.S (ffi_call_LINUX64): Set up r2 for + ELFv2. Adjust toc save location. Call function pointer using + r12. Handle FLAG_RETURNS_SMST. Don't predict branches. + * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Set up r2 + for ELFv2. Define ELFv2 versions of STACKFRAME, PARMSAVE, and + RETVAL. Handle possibly missing parameter save area. Handle + ELFv2 return values. + (.note.GNU-stack): Move inside outer #ifdef. + +2013-11-16 Alan Modra + + * src/powerpc/ffi.c (ffi_prep_cif_machdep): Revert 2013-02-08 + change. Do not consume an int arg when returning a small struct + for FFI_SYSV ABI. + (ffi_call): Only use bounce buffer when FLAG_RETURNS_SMST. + Properly copy bounce buffer to destination. + * src/powerpc/sysv.S: Revert 2013-02-08 change. + * src/powerpc/ppc_closure.S: Remove stray '+'. + +2013-11-16 Alan Modra + + * src/powerpc/ffi.c (ffi_prep_args64): Align struct parameters + according to __STRUCT_PARM_ALIGN__. + (ffi_prep_cif_machdep_core): Likewise. + (ffi_closure_helper_LINUX64): Likewise. + +2013-11-16 Alan Modra + + * src/powerpc/linux64.S (ffi_call_LINUX64): Tweak restore of r28. + (.note.GNU-stack): Move inside outer #ifdef. + * src/powerpc/linux64_closure.S (STACKFRAME, PARMSAVE, + RETVAL): Define and use throughout. + (ffi_closure_LINUX64): Save fprs before buying stack. + (.note.GNU-stack): Move inside outer #ifdef. + +2013-11-16 Alan Modra + + * src/powerpc/ffitarget.h (FFI_TARGET_SPECIFIC_VARIADIC): Define. + (FFI_EXTRA_CIF_FIELDS): Define. + * src/powerpc/ffi.c (ffi_prep_args64): Save fprs as per the + ABI, not to both fpr and param save area. + (ffi_prep_cif_machdep_core): Renamed from ffi_prep_cif_machdep. + Keep initial flags. Formatting. Remove dead FFI_LINUX_SOFT_FLOAT + code. + (ffi_prep_cif_machdep, ffi_prep_cif_machdep_var): New functions. + (ffi_closure_helper_LINUX64): Pass floating point as per ABI, + not to both fpr and parameter save areas. + + * libffi/testsuite/libffi.call/cls_double_va.c (main): Correct + function cast and don't call ffi_prep_cif. + * libffi/testsuite/libffi.call/cls_longdouble_va.c (main): Likewise. + +2013-11-15 Andrew Haley + + * doc/libffi.texi (Closure Example): Fix the sample code. + * doc/libffi.info, doc/stamp-vti, doc/version.texi: Rebuilt. + +2013-11-15 Andrew Haley + + * testsuite/libffi.call/va_struct1.c (main): Fix broken test. + * testsuite/libffi.call/cls_uint_va.c (cls_ret_T_fn): Likewise + * testsuite/libffi.call/cls_struct_va1.c (test_fn): Likewise. + * testsuite/libffi.call/va_1.c (main): Likewise. + +2013-11-14 David Schneider + + * src/arm/ffi.c: Fix register allocation for mixed float and + doubles. + * testsuite/libffi.call/cls_many_mixed_float_double.c: Testcase + for many mixed float and double arguments. + +2013-11-13 Alan Modra + + * doc/libffi.texi (Simple Example): Correct example code. + * doc/libffi.info, doc/stamp-vti, doc/version.texi: Rebuilt. + +2013-11-13 Anthony Green + + * include/ffi_common.h: Respect HAVE_ALLOCA_H for GNU compiler + based build. (Thanks to tmr111116 on github) + +2013-11-09 Anthony Green + + * m4/libtool.m4: Refresh. + * configure, Makefile.in: Rebuilt. + * README: Add more notes about next release. + +2013-11-09 Shigeharu TAKENO + + * m4/ax_gcc_archflag.m4 (ax_gcc_arch): Don't recognize + UltraSPARC-IIi as ultrasparc3. + +2013-11-06 Mark Kettenis + + * src/x86/freebsd.S (ffi_call_SYSV): Align the stack pointer to + 16-bytes. + +2013-11-06 Konstantin Belousov + + * src/x86/freebsd.S (ffi_closure_raw_SYSV): Mark the assembler + source as not requiring executable stack. + +2013-11-02 Anthony Green + + * doc/libffi.texi (The Basics): Clarify return value buffer size + requirements. Also, NULL result buffer pointers are no longer + supported. + * doc/libffi.info: Rebuilt. + +2013-11-02 Mischa Jonker + + * Makefile.am (nodist_libffi_la_SOURCES): Fix build error. + * Makefile.in: Rebuilt. + +2013-11-02 David Schneider + + * src/arm/ffi.c: more robust argument handling for closures on arm hardfloat + * testsuite/libffi.call/many_mixed.c: New file. + * testsuite/libffi.call/cls_many_mixed_args.c: More tests. + +2013-11-02 Vitaly Budovski + + * src/x86/ffi.c (ffi_prep_cif_machdep): Don't align stack for win32. + +2013-10-23 Mark H Weaver + + * src/mips/ffi.c: Fix handling of uint32_t arguments on the + MIPS N32 ABI. + +2013-10-13 Sandra Loosemore + + * README: Add Nios II to table of supported platforms. + * Makefile.am (EXTRA_DIST): Add nios2 files. + (nodist_libffi_la_SOURCES): Likewise. + * Makefile.in: Regenerated. + * configure.ac (nios2*-linux*): New host. + (NIOS2): Add AM_CONDITIONAL. + * configure: Regenerated. + * src/nios2/ffi.c: New. + * src/nios2/ffitarget.h: New. + * src/nios2/sysv.S: New. + * src/prep_cif.c (initialize_aggregate): Handle extra structure + alignment via FFI_AGGREGATE_ALIGNMENT. + (ffi_prep_cif_core): Conditionalize structure return for NIOS2. + +2013-10-10 Sandra Loosemore + + * testsuite/libffi.call/cls_many_mixed_args.c (cls_ret_double_fn): + Fix uninitialized variable. + +2013-10-11 Marcus Shawcroft + + * testsuite/libffi.call/many.c (many): Replace * with +. + +2013-10-08 Ondřej Bílka + + * src/aarch64/ffi.c, src/aarch64/sysv.S, src/arm/ffi.c, + src/arm/gentramp.sh, src/bfin/sysv.S, src/closures.c, + src/dlmalloc.c, src/ia64/ffi.c, src/microblaze/ffi.c, + src/microblaze/sysv.S, src/powerpc/darwin_closure.S, + src/powerpc/ffi.c, src/powerpc/ffi_darwin.c, src/sh/ffi.c, + src/tile/tile.S, testsuite/libffi.call/nested_struct11.c: Fix + spelling errors. + +2013-10-08 Anthony Green + + * aclocal.m4, compile, config.guess, config.sub, depcomp, + install-sh, mdate-sh, missing, texinfo.tex: Update from upstream. + * configure.ac: Update version to 3.0.14-rc0. + * Makefile.in, configure, Makefile.in, include/Makefile.in, + man/Makefile.in, testsuite/Makefile.in: Rebuilt. + * README: Mention M88K and VAX. + +2013-07-15 Miod Vallat + + * Makefile.am, + configure.ac, + src/m88k/ffi.c, + src/m88k/ffitarget.h, + src/m88k/obsd.S, + src/vax/elfbsd.S, + src/vax/ffi.c, + src/vax/ffitarget.h: Add m88k and vax support. + +2013-06-24 Alan Modra + + * src/powerpc/ffi.c (ffi_prep_args_SYSV): Move var declaration + before statements. + (ffi_prep_args64): Support little-endian. + (ffi_closure_helper_SYSV, ffi_closure_helper_LINUX64): Likewise. + * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Likewise. + * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Likewise. + +2013-06-12 Mischa Jonker + + * configure.ac: Add support for ARC. + * Makefile.am: Likewise. + * README: Add ARC details. + * src/arc/arcompact.S: New. + * src/arc/ffi.c: Likewise. + * src/arc/ffitarget.h: Likewise. + +2013-03-28 David Schneider + + * src/arm/ffi.c: Fix support for ARM hard-float calling convention. + * src/arm/sysv.S: call different methods for SYSV and VFP ABIs. + * testsuite/libffi.call/cls_many_mixed_args.c: testcase for a closure with + mixed arguments, many doubles. + * testsuite/libffi.call/many_double.c: testcase for calling a function using + more than 8 doubles. + * testcase/libffi.call/many.c: use absolute value to check result against an + epsilon + +2013-03-17 Anthony Green + + * README: Update for 3.0.13. + * configure.ac: Ditto. + * configure: Rebuilt. + * doc/*: Update version. + +2013-03-17 Dave Korn + + * src/closures.c (is_emutramp_enabled + [!FFI_MMAP_EXEC_EMUTRAMP_PAX]): Move default definition outside + enclosing #if scope. + +2013-03-17 Anthony Green + + * configure.ac: Only modify toolexecdir in certain cases. + * configure: Rebuilt. + +2013-03-16 Gilles Talis + + * src/powerpc/ffi.c (ffi_prep_args_SYSV): Don't use + fparg_count,etc on __NO_FPRS__ targets. + +2013-03-16 Alan Hourihane + + * src/m68k/sysv.S (epilogue): Don't use extb instruction on + m680000 machines. + +2013-03-16 Alex Gaynor + + * src/x86/ffi.c (ffi_prep_cif_machdep): Always align stack. + +2013-03-13 Markos Chandras + + * configure.ac: Add support for Imagination Technologies Meta. + * Makefile.am: Likewise. + * README: Add Imagination Technologies Meta details. + * src/metag/ffi.c: New. + * src/metag/ffitarget.h: Likewise. + * src/metag/sysv.S: Likewise. + +2013-02-24 Andreas Schwab + + * doc/libffi.texi (Structures): Fix missing category argument of + @deftp. + +2013-02-11 Anthony Green + + * configure.ac: Update release number to 3.0.12. + * configure: Rebuilt. + * README: Update release info. + +2013-02-10 Anthony Green + + * README: Add Moxie. + * src/moxie/ffi.c: Created. + * src/moxie/eabi.S: Created. + * src/moxie/ffitarget.h: Created. + * Makefile.am (nodist_libffi_la_SOURCES): Add Moxie. + * Makefile.in: Rebuilt. + * configure.ac: Add Moxie. + * configure: Rebuilt. + * testsuite/libffi.call/huge_struct.c: Disable format string + warnings for moxie*-*-elf tests. + +2013-02-10 Anthony Green + + * Makefile.am (LTLDFLAGS): Fix reference. + * Makefile.in: Rebuilt. + +2013-02-10 Anthony Green + + * README: Update supported platforms. Update test results link. + +2013-02-09 Anthony Green + + * testsuite/libffi.call/negint.c: Remove forced -O2. + * testsuite/libffi.call/many2.c (foo): Remove GCCism. + * testsuite/libffi.call/ffitest.h: Add default PRIuPTR definition. + + * src/sparc/v8.S (ffi_closure_v8): Import ancient ulonglong + closure return type fix developed by Martin v. Löwis for cpython + fork. + +2013-02-08 Andreas Tobler + + * src/powerpc/ffi.c (ffi_prep_cif_machdep): Fix small struct + support. + * src/powerpc/sysv.S: Ditto. + +2013-02-08 Anthony Green + + * testsuite/libffi.call/cls_longdouble.c: Remove xfail for + arm*-*-*. + +2013-02-08 Anthony Green + + * src/sparc/ffi.c (ffi_prep_closure_loc): Fix cache flushing for GCC. + +2013-02-08 Matthias Klose + + * man/ffi_prep_cif.3: Clean up for debian linter. + +2013-02-08 Peter Bergner + + * src/powerpc/ffi.c (ffi_prep_args_SYSV): Account for FP args pushed + on the stack. + +2013-02-08 Anthony Green + + * Makefile.am (EXTRA_DIST): Add missing files. + * testsuite/Makefile.am (EXTRA_DIST): Ditto. + * Makefile.in: Rebuilt. + +2013-02-08 Anthony Green + + * configure.ac: Move sparc asm config checks to within functions + for compatibility with sun tools. + * configure: Rebuilt. + * src/sparc/ffi.c (ffi_prep_closure_loc): Flush cache on v9 + systems. + * src/sparc/v8.S (ffi_flush_icache): Implement a sparc v9 cache + flusher. + +2013-02-08 Nathan Rossi + + * src/microblaze/ffi.c (ffi_closure_call_SYSV): Fix handling of + small big-endian structures. + (ffi_prep_args): Ditto. + +2013-02-07 Anthony Green + + * src/sparc/v8.S (ffi_call_v8): Fix typo from last patch + (effectively hiding ffi_call_v8). + +2013-02-07 Anthony Green + + * configure.ac: Update bug reporting address. + * configure.in: Rebuild. + + * src/sparc/v8.S (ffi_flush_icache): Out-of-line cache flusher for + Sun compiler. + * src/sparc/ffi.c (ffi_call): Remove warning. + Call ffi_flush_icache for non-GCC builds. + (ffi_prep_closure_loc): Use ffi_flush_icache. + + * Makefile.am (EXTRA_DIST): Add libtool-ldflags. + * Makefile.in: Rebuilt. + * libtool-ldflags: New file. + +2013-02-07 Daniel Schepler + + * configure.ac: Correctly identify x32 systems as 64-bit. + * m4/libtool.m4: Remove libtool expr error. + * aclocal.m4, configure: Rebuilt. + +2013-02-07 Anthony Green + + * configure.ac: Fix GCC usage test. + * configure: Rebuilt. + * README: Mention LLVM/GCC x86_64 issue. + * testsuite/Makefile.in: Rebuilt. + +2013-02-07 Anthony Green + + * testsuite/libffi.call/cls_double_va.c (main): Replace // style + comments with /* */ for xlc compiler. + * testsuite/libffi.call/stret_large.c (main): Ditto. + * testsuite/libffi.call/stret_large2.c (main): Ditto. + * testsuite/libffi.call/nested_struct1.c (main): Ditto. + * testsuite/libffi.call/huge_struct.c (main): Ditto. + * testsuite/libffi.call/float_va.c (main): Ditto. + * testsuite/libffi.call/cls_struct_va1.c (main): Ditto. + * testsuite/libffi.call/cls_pointer_stack.c (main): Ditto. + * testsuite/libffi.call/cls_pointer.c (main): Ditto. + * testsuite/libffi.call/cls_longdouble_va.c (main): Ditto. + +2013-02-06 Anthony Green + + * man/ffi_prep_cif.3: Clean up for debian lintian checker. + +2013-02-06 Anthony Green + + * Makefile.am (pkgconfigdir): Add missing pkgconfig install bits. + * Makefile.in: Rebuild. + +2013-02-02 Mark H Weaver + + * src/x86/ffi64.c (ffi_call): Sign-extend integer arguments passed + via general purpose registers. + +2013-01-21 Nathan Rossi + + * README: Add MicroBlaze details. + * Makefile.am: Add MicroBlaze support. + * configure.ac: Likewise. + * src/microblaze/ffi.c: New. + * src/microblaze/ffitarget.h: Likewise. + * src/microblaze/sysv.S: Likewise. + +2013-01-21 Nathan Rossi + * testsuite/libffi.call/return_uc.c: Fixed issue. + +2013-01-21 Chris Zankel + + * README: Add Xtensa support. + * Makefile.am: Likewise. + * configure.ac: Likewise. + * Makefile.in Regenerate. + * configure: Likewise. + * src/prep_cif.c: Handle Xtensa. + * src/xtensa: New directory. + * src/xtensa/ffi.c: New file. + * src/xtensa/ffitarget.h: Ditto. + * src/xtensa/sysv.S: Ditto. + +2013-01-11 Anthony Green + + * src/powerpc/ffi_darwin.c (ffi_prep_args): Replace // style + comments with /* */ for xlc compiler. + * src/powerpc/aix.S (ffi_call_AIX): Ditto. + * testsuite/libffi.call/ffitest.h (allocate_mmap): Delete + deprecated inline function. + * testsuite/libffi.special/ffitestcxx.h: Ditto. + * README: Add update for AIX support. + +2013-01-11 Anthony Green + + * configure.ac: Robustify pc relative reloc check. + * m4/ax_cc_maxopt.m4: Don't -malign-double. This is an ABI + changing option for 32-bit x86. + * aclocal.m4, configure: Rebuilt. + * README: Update supported target list. + +2013-01-10 Anthony Green + + * README (tested): Add Compiler column to table. + +2013-01-10 Anthony Green + + * src/x86/ffi64.c (struct register_args): Make sse array and array + of unions for sunpro compiler compatibility. + +2013-01-10 Anthony Green + + * configure.ac: Test target platform size_t size. Handle both 32 + and 64-bit builds for x86_64-* and i?86-* targets (allowing for + CFLAG option to change default settings). + * configure, aclocal.m4: Rebuilt. + +2013-01-10 Anthony Green + + * testsuite/libffi.special/special.exp: Only run exception + handling tests when using GNU compiler. + + * m4/ax_compiler_vendor.m4: New file. + * configure.ac: Test for compiler vendor and don't use + AX_CFLAGS_WARN_ALL with the sun compiler. + * aclocal.m4, configure: Rebuilt. + +2013-01-10 Anthony Green + + * include/ffi_common.h: Don't use GCCisms to define types when + building with the SUNPRO compiler. + +2013-01-10 Anthony Green + + * configure.ac: Put local.exp in the right place. + * configure: Rebuilt. + + * src/x86/ffi.c: Update comment about regparm function attributes. + * src/x86/sysv.S (ffi_closure_SYSV): The SUNPRO compiler requires + that all function arguments be passed on the stack (no regparm + support). + +2013-01-08 Anthony Green + + * configure.ac: Generate local.exp. This sets CC_FOR_TARGET + when we are using the vendor compiler. + * testsuite/Makefile.am (EXTRA_DEJAGNU_SITE_CONFIG): Point to + ../local.exp. + * configure, testsuite/Makefile.in: Rebuilt. + + * testsuite/libffi.call/call.exp: Run tests with different + options, depending on whether or not we are using gcc or the + vendor compiler. + * testsuite/lib/libffi.exp (libffi-init): Set using_gcc based on + whether or not we are building/testing with gcc. + +2013-01-08 Anthony Green + + * configure.ac: Switch x86 solaris target to X86 by default. + * configure: Rebuilt. + +2013-01-08 Anthony Green + + * configure.ac: Fix test for read-only eh_frame. + * configure: Rebuilt. + +2013-01-08 Anthony Green + + * src/x86/sysv.S, src/x86/unix64.S: Only emit DWARF unwind info + when building with the GNU toolchain. + * testsuite/libffi.call/ffitest.h (CHECK): Fix for Solaris vendor + compiler. + +2013-01-07 Thorsten Glaser + + * testsuite/libffi.call/cls_uchar_va.c, + testsuite/libffi.call/cls_ushort_va.c, + testsuite/libffi.call/va_1.c: Testsuite fixes. + +2013-01-07 Thorsten Glaser + + * src/m68k/ffi.c (CIF_FLAGS_SINT8, CIF_FLAGS_SINT16): Define. + (ffi_prep_cif_machdep): Fix 8-bit and 16-bit signed calls. + * src/m68k/sysv.S (ffi_call_SYSV, ffi_closure_SYSV): Ditto. + +2013-01-04 Anthony Green + + * Makefile.am (AM_CFLAGS): Don't automatically add -fexceptions + and -Wall. This is set in the configure script after testing for + GCC. + * Makefile.in: Rebuilt. + +2013-01-02 rofl0r + + * src/powerpc/ffi.c (ffi_prep_cif_machdep): Fix build error on ppc + when long double == double. + +2013-01-02 Reini Urban + + * Makefile.am (libffi_la_LDFLAGS): Add -no-undefined to LDFLAGS + (required for shared libs on cygwin/mingw). + * Makefile.in: Rebuilt. + +2012-10-31 Alan Modra + + * src/powerpc/linux64_closure.S: Add new ABI support. + * src/powerpc/linux64.S: Likewise. + +2012-10-30 Magnus Granberg + Pavel Labushev + + * configure.ac: New options pax_emutramp + * configure, fficonfig.h.in: Regenerated + * src/closures.c: New function emutramp_enabled_check() and + checks. + +2012-10-30 Frederick Cheung + + * configure.ac: Enable FFI_MAP_EXEC_WRIT for Darwin 12 (mountain + lion) and future version. + * configure: Rebuild. + +2012-10-30 James Greenhalgh + Marcus Shawcroft + + * README: Add details of aarch64 port. + * src/aarch64/ffi.c: New. + * src/aarch64/ffitarget.h: Likewise. + * src/aarch64/sysv.S: Likewise. + * Makefile.am: Support aarch64. + * configure.ac: Support aarch64. + * Makefile.in, configure: Rebuilt. + +2012-10-30 James Greenhalgh + Marcus Shawcroft + + * testsuite/lib/libffi.exp: Add support for aarch64. + * testsuite/libffi.call/cls_struct_va1.c: New. + * testsuite/libffi.call/cls_uchar_va.c: Likewise. + * testsuite/libffi.call/cls_uint_va.c: Likewise. + * testsuite/libffi.call/cls_ulong_va.c: Likewise. + * testsuite/libffi.call/cls_ushort_va.c: Likewise. + * testsuite/libffi.call/nested_struct11.c: Likewise. + * testsuite/libffi.call/uninitialized.c: Likewise. + * testsuite/libffi.call/va_1.c: Likewise. + * testsuite/libffi.call/va_struct1.c: Likewise. + * testsuite/libffi.call/va_struct2.c: Likewise. + * testsuite/libffi.call/va_struct3.c: Likewise. + +2012-10-12 Walter Lee + + * Makefile.am: Add TILE-Gx/TILEPro support. + * configure.ac: Likewise. + * Makefile.in: Regenerate. + * configure: Likewise. + * src/prep_cif.c (ffi_prep_cif_core): Handle TILE-Gx/TILEPro. + * src/tile: New directory. + * src/tile/ffi.c: New file. + * src/tile/ffitarget.h: Ditto. + * src/tile/tile.S: Ditto. + +2012-10-12 Matthias Klose + + * generate-osx-source-and-headers.py: Normalize whitespace. + +2012-09-14 David Edelsohn + + * configure: Regenerated. + +2012-08-26 Andrew Pinski + + PR libffi/53014 + * src/mips/ffi.c (ffi_prep_closure_loc): Allow n32 with soft-float and n64 with + soft-float. + +2012-08-08 Uros Bizjak + + * src/s390/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test, + just return FFI_BAD_ABI when things are wrong. + +2012-07-18 H.J. Lu + + PR libffi/53982 + PR libffi/53973 + * src/x86/ffitarget.h: Check __ILP32__ instead of __LP64__ for x32. + (FFI_SIZEOF_JAVA_RAW): Defined to 4 for x32. + +2012-05-16 H.J. Lu + + * configure: Regenerated. + +2012-05-05 Nicolas Lelong + + * libffi.xcodeproj/project.pbxproj: Fixes. + * README: Update for iOS builds. + +2012-04-23 Alexandre Keunecke I. de Mendonca + + * configure.ac: Add Blackfin/sysv support + * Makefile.am: Add Blackfin/sysv support + * src/bfin/ffi.c: Add Blackfin/sysv support + * src/bfin/ffitarget.h: Add Blackfin/sysv support + +2012-04-11 Anthony Green + + * Makefile.am (EXTRA_DIST): Add new script. + * Makefile.in: Rebuilt. + +2012-04-11 Zachary Waldowski + + * generate-ios-source-and-headers.py, + libffi.xcodeproj/project.pbxproj: Support a Mac static library via + Xcode. Set iOS compatibility to 4.0. Move iOS trampoline + generation into an Xcode "run script" phase. Include both as + Xcode build scripts. Don't always regenerate config files. + +2012-04-10 Anthony Green + + * src/powerpc/ffi_darwin.c (ffi_prep_args): Add missing semicolon. + +2012-04-06 Anthony Green + + * Makefile.am (EXTRA_DIST): Add new iOS/xcode files. + * Makefile.in: Rebuilt. + +2012-04-06 Mike Lewis + + * generate-ios-source-and-headers.py: New file. + * libffi.xcodeproj/project.pbxproj: New file. + * README: Update instructions on building iOS binary. + * build-ios.sh: Delete. + +2012-04-06 Anthony Green + + * src/x86/ffi64.c (UINT128): Define differently for Intel and GNU + compilers, then use it. + +2012-04-06 H.J. Lu + + * m4/libtool.m4 (_LT_ENABLE_LOCK): Support x32. + +2012-04-06 Anthony Green + + * testsuite/Makefile.am (EXTRA_DIST): Add missing test cases. + * testsuite/Makefile.in: Rebuilt. + +2012-04-05 Zachary Waldowski + + * include/ffi.h.in: Add missing trampoline table fields. + * src/arm/sysv.S: Fix ENTRY definition, and wrap symbol references + in CNAME. + * src/x86/ffi.c: Wrap Windows specific code in ifdefs. + +2012-04-02 Peter Bergner + + * src/powerpc/ffi.c (ffi_prep_args_SYSV): Declare double_tmp. + Silence casting pointer to integer of different size warning. + Delete goto to previously deleted label. + (ffi_call): Silence possibly undefined warning. + (ffi_closure_helper_SYSV): Declare variable type. + +2012-04-02 Peter Rosin + + * src/x86/win32.S (ffi_call_win32): Sign/zero extend the return + value in the Intel version as is already done for the AT&T version. + (ffi_closure_SYSV): Likewise. + (ffi_closure_raw_SYSV): Likewise. + (ffi_closure_STDCALL): Likewise. + +2012-03-29 Peter Rosin + + * src/x86/win32.S (ffi_closure_raw_THISCALL): Unify the frame + generation, fix the ENDP label and remove the surplus third arg + from the 'lea' insn. + +2012-03-29 Peter Rosin + + * src/x86/win32.S (ffi_closure_raw_SYSV): Make the 'stubraw' label + visible outside the PROC, so that ffi_closure_raw_THISCALL can see + it. Also instruct the assembler to add a frame to the function. + +2012-03-23 Peter Rosin + + * Makefile.am (AM_CPPFLAGS): Add -DFFI_BUILDING. + * Makefile.in: Rebuilt. + * include/ffi.h.in [MSVC]: Add __declspec(dllimport) decorations + to all data exports, when compiling libffi clients using MSVC. + +2012-03-29 Peter Rosin + + * src/x86/ffitarget.h (ffi_abi): Add new ABI FFI_MS_CDECL and + make it the default for MSVC. + (FFI_TYPE_MS_STRUCT): New structure return convention. + * src/x86/ffi.c (ffi_prep_cif_machdep): Tweak the structure + return convention for FFI_MS_CDECL to be FFI_TYPE_MS_STRUCT + instead of an ordinary FFI_TYPE_STRUCT. + (ffi_prep_args): Treat FFI_TYPE_MS_STRUCT as FFI_TYPE_STRUCT. + (ffi_call): Likewise. + (ffi_prep_incoming_args_SYSV): Likewise. + (ffi_raw_call): Likewise. + (ffi_prep_closure_loc): Treat FFI_MS_CDECL as FFI_SYSV. + * src/x86/win32.S (ffi_closure_SYSV): For FFI_TYPE_MS_STRUCT, + return a pointer to the result structure in eax and don't pop + that pointer from the stack, the caller takes care of it. + (ffi_call_win32): Treat FFI_TYPE_MS_STRUCT as FFI_TYPE_STRUCT. + (ffi_closure_raw_SYSV): Likewise. + +2012-03-22 Peter Rosin + + * testsuite/libffi.call/closure_stdcall.c [MSVC]: Add inline + assembly version with Intel syntax. + * testsuite/libffi.call/closure_thiscall.c [MSVC]: Likewise. + +2012-03-23 Peter Rosin + + * testsuite/libffi.call/ffitest.h: Provide abstration of + __attribute__((fastcall)) in the form of a __FASTCALL__ + define. Define it to __fastcall for MSVC. + * testsuite/libffi.call/fastthis1_win32.c: Use the above. + * testsuite/libffi.call/fastthis2_win32.c: Likewise. + * testsuite/libffi.call/fastthis3_win32.c: Likewise. + * testsuite/libffi.call/strlen2_win32.c: Likewise. + * testsuite/libffi.call/struct1_win32.c: Likewise. + * testsuite/libffi.call/struct2_win32.c: Likewise. + +2012-03-22 Peter Rosin + + * src/x86/win32.S [MSVC] (ffi_closure_THISCALL): Remove the manual + frame on function entry, MASM adds one automatically. + +2012-03-22 Peter Rosin + + * testsuite/libffi.call/ffitest.h [MSVC]: Add kludge for missing + bits in the MSVC headers. + +2012-03-22 Peter Rosin + + * testsuite/libffi.call/cls_12byte.c: Adjust to the C89 style + with no declarations after statements. + * testsuite/libffi.call/cls_16byte.c: Likewise. + * testsuite/libffi.call/cls_18byte.c: Likewise. + * testsuite/libffi.call/cls_19byte.c: Likewise. + * testsuite/libffi.call/cls_1_1byte.c: Likewise. + * testsuite/libffi.call/cls_20byte.c: Likewise. + * testsuite/libffi.call/cls_20byte1.c: Likewise. + * testsuite/libffi.call/cls_24byte.c: Likewise. + * testsuite/libffi.call/cls_2byte.c: Likewise. + * testsuite/libffi.call/cls_3_1byte.c: Likewise. + * testsuite/libffi.call/cls_3byte1.c: Likewise. + * testsuite/libffi.call/cls_3byte2.c: Likewise. + * testsuite/libffi.call/cls_4_1byte.c: Likewise. + * testsuite/libffi.call/cls_4byte.c: Likewise. + * testsuite/libffi.call/cls_5_1_byte.c: Likewise. + * testsuite/libffi.call/cls_5byte.c: Likewise. + * testsuite/libffi.call/cls_64byte.c: Likewise. + * testsuite/libffi.call/cls_6_1_byte.c: Likewise. + * testsuite/libffi.call/cls_6byte.c: Likewise. + * testsuite/libffi.call/cls_7_1_byte.c: Likewise. + * testsuite/libffi.call/cls_7byte.c: Likewise. + * testsuite/libffi.call/cls_8byte.c: Likewise. + * testsuite/libffi.call/cls_9byte1.c: Likewise. + * testsuite/libffi.call/cls_9byte2.c: Likewise. + * testsuite/libffi.call/cls_align_double.c: Likewise. + * testsuite/libffi.call/cls_align_float.c: Likewise. + * testsuite/libffi.call/cls_align_longdouble.c: Likewise. + * testsuite/libffi.call/cls_align_longdouble_split.c: Likewise. + * testsuite/libffi.call/cls_align_longdouble_split2.c: Likewise. + * testsuite/libffi.call/cls_align_pointer.c: Likewise. + * testsuite/libffi.call/cls_align_sint16.c: Likewise. + * testsuite/libffi.call/cls_align_sint32.c: Likewise. + * testsuite/libffi.call/cls_align_sint64.c: Likewise. + * testsuite/libffi.call/cls_align_uint16.c: Likewise. + * testsuite/libffi.call/cls_align_uint32.c: Likewise. + * testsuite/libffi.call/cls_align_uint64.c: Likewise. + * testsuite/libffi.call/cls_dbls_struct.c: Likewise. + * testsuite/libffi.call/cls_pointer_stack.c: Likewise. + * testsuite/libffi.call/err_bad_typedef.c: Likewise. + * testsuite/libffi.call/huge_struct.c: Likewise. + * testsuite/libffi.call/nested_struct.c: Likewise. + * testsuite/libffi.call/nested_struct1.c: Likewise. + * testsuite/libffi.call/nested_struct10.c: Likewise. + * testsuite/libffi.call/nested_struct2.c: Likewise. + * testsuite/libffi.call/nested_struct3.c: Likewise. + * testsuite/libffi.call/nested_struct4.c: Likewise. + * testsuite/libffi.call/nested_struct5.c: Likewise. + * testsuite/libffi.call/nested_struct6.c: Likewise. + * testsuite/libffi.call/nested_struct7.c: Likewise. + * testsuite/libffi.call/nested_struct8.c: Likewise. + * testsuite/libffi.call/nested_struct9.c: Likewise. + * testsuite/libffi.call/stret_large.c: Likewise. + * testsuite/libffi.call/stret_large2.c: Likewise. + * testsuite/libffi.call/stret_medium.c: Likewise. + * testsuite/libffi.call/stret_medium2.c: Likewise. + * testsuite/libffi.call/struct1.c: Likewise. + * testsuite/libffi.call/struct1_win32.c: Likewise. + * testsuite/libffi.call/struct2.c: Likewise. + * testsuite/libffi.call/struct2_win32.c: Likewise. + * testsuite/libffi.call/struct3.c: Likewise. + * testsuite/libffi.call/struct4.c: Likewise. + * testsuite/libffi.call/struct5.c: Likewise. + * testsuite/libffi.call/struct6.c: Likewise. + * testsuite/libffi.call/struct7.c: Likewise. + * testsuite/libffi.call/struct8.c: Likewise. + * testsuite/libffi.call/struct9.c: Likewise. + * testsuite/libffi.call/testclosure.c: Likewise. + +2012-03-21 Peter Rosin + + * testsuite/libffi.call/float_va.c (float_va_fn): Use %f when + printing doubles (%lf is for long doubles). + (main): Likewise. + +2012-03-21 Peter Rosin + + * testsuite/lib/target-libpath.exp [*-*-cygwin*, *-*-mingw*] + (set_ld_library_path_env_vars): Add the library search dir to PATH + (and save PATH for later). + (restore_ld_library_path_env_vars): Restore PATH. + +2012-03-21 Peter Rosin + + * testsuite/lib/target-libpath.exp [*-*-cygwin*, *-*-mingw*] + (set_ld_library_path_env_vars): Add the library search dir to PATH + (and save PATH for later). + (restore_ld_library_path_env_vars): Restore PATH. + +2012-03-20 Peter Rosin + + * testsuite/libffi.call/strlen2_win32.c (main): Remove bug. + * src/x86/win32.S [MSVC] (ffi_closure_SYSV): Make the 'stub' label + visible outside the PROC, so that ffi_closure_THISCALL can see it. + +2012-03-20 Peter Rosin + + * testsuite/libffi.call/strlen2_win32.c (main): Remove bug. + * src/x86/win32.S [MSVC] (ffi_closure_SYSV): Make the 'stub' label + visible outside the PROC, so that ffi_closure_THISCALL can see it. + +2012-03-19 Alan Hourihane + + * src/m68k/ffi.c: Add MINT support. + * src/m68k/sysv.S: Ditto. + +2012-03-06 Chung-Lin Tang + + * src/arm/ffi.c (ffi_call): Add __ARM_EABI__ guard around call to + ffi_call_VFP(). + (ffi_prep_closure_loc): Add __ARM_EABI__ guard around use of + ffi_closure_VFP. + * src/arm/sysv.S: Add __ARM_EABI__ guard around VFP code. + +2012-03-19 chennam + + * src/powerpc/ffi_darwin.c (ffi_prep_closure_loc): Fix AIX closure + support. + +2012-03-13 Kaz Kojima + + * src/sh/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test, + just return FFI_BAD_ABI when things are wrong. + * src/sh64/ffi.c (ffi_prep_closure_loc): Ditto. + +2012-03-09 David Edelsohn + + * src/powerpc/aix_closure.S (ffi_closure_ASM): Adjust for Darwin64 + change to return value of ffi_closure_helper_DARWIN and load type + from return type. + +2012-03-03 H.J. Lu + + * src/x86/ffi64.c (ffi_call): Cast the return value to unsigned + long. + (ffi_prep_closure_loc): Cast to 64bit address in trampoline. + (ffi_closure_unix64_inner): Cast return pointer to unsigned long + first. + + * src/x86/ffitarget.h (FFI_SIZEOF_ARG): Defined to 8 for x32. + (ffi_arg): Set to unsigned long long for x32. + (ffi_sarg): Set to long long for x32. + +2012-03-03 H.J. Lu + + * src/prep_cif.c (ffi_prep_cif_core): Properly check bad ABI. + +2012-03-03 Andoni Morales Alastruey + + * configure.ac: Add -no-undefined for both 32- and 64-bit x86 + windows-like hosts. + * configure: Rebuilt. + +2012-02-27 Mikael Pettersson + + PR libffi/52223 + * Makefile.am (FLAGS_TO_PASS): Define. + * Makefile.in: Regenerate. + +2012-02-23 Anthony Green + + * src/*/ffitarget.h: Ensure that users never include ffitarget.h + directly. + +2012-02-23 Kai Tietz + + PR libffi/52221 + * src/x86/ffi.c (ffi_closure_raw_THISCALL): New + prototype. + (ffi_prep_raw_closure_loc): Use ffi_closure_raw_THISCALL for + thiscall-convention. + (ffi_raw_call): Use ffi_prep_args_raw. + * src/x86/win32.S (ffi_closure_raw_THISCALL): Add + implementation for stub. + +2012-02-10 Kai Tietz + + * configure.ac (AM_LTLDFLAGS): Add -no-undefine for x64 + windows target. + * configure: Regenerated. + +2012-02-08 Kai Tietz + + * src/prep_cif.c (ffi_prep_cif): Allow for X86_WIN32 + also FFI_THISCALL. + * src/x86/ffi.c (ffi_closure_THISCALL): Add prototype. + (FFI_INIT_TRAMPOLINE_THISCALL): New trampoline code. + (ffi_prep_closure_loc): Add FFI_THISCALL support. + * src/x86/ffitarget.h (FFI_TRAMPOLINE_SIZE): Adjust size. + * src/x86/win32.S (ffi_closure_THISCALL): New closure code + for thiscall-calling convention. + * testsuite/libffi.call/closure_thiscall.c: New test. + +2012-01-28 Kai Tietz + + * src/libffi/src/x86/ffi.c (ffi_call_win32): Add new + argument to prototype for specify calling-convention. + (ffi_call): Add support for stdcall/thiscall convention. + (ffi_prep_args): Likewise. + (ffi_raw_call): Likewise. + * src/x86/ffitarget.h (ffi_abi): Add FFI_THISCALL and + FFI_FASTCALL. + * src/x86/win32.S (_ffi_call_win32): Add support for + fastcall/thiscall calling-convention calls. + * testsuite/libffi.call/fastthis1_win32.c: New test. + * testsuite/libffi.call/fastthis2_win32.c: New test. + * testsuite/libffi.call/fastthis3_win32.c: New test. + * testsuite/libffi.call/strlen2_win32.c: New test. + * testsuite/libffi.call/many2_win32.c: New test. + * testsuite/libffi.call/struct1_win32.c: New test. + * testsuite/libffi.call/struct2_win32.c: New test. + +2012-01-23 Uros Bizjak + + * src/alpha/ffi.c (ffi_prep_closure_loc): Check for bad ABI. + +2012-01-23 Anthony Green + Chris Young + + * configure.ac: Add Amiga support. + * configure: Rebuilt. + +2012-01-23 Dmitry Nadezhin + + * include/ffi_common.h (LIKELY, UNLIKELY): Fix definitions. + +2012-01-23 Andreas Schwab + + * src/m68k/sysv.S (ffi_call_SYSV): Properly test for plain + mc68000. Test for __HAVE_68881__ in addition to __MC68881__. + +2012-01-19 Jakub Jelinek + + PR rtl-optimization/48496 + * src/ia64/ffi.c (ffi_call): Fix up aliasing violations. + +2012-01-09 Rainer Orth + + * configure.ac (i?86-*-*): Set TARGET to X86_64. + * configure: Regenerate. + +2011-12-07 Andrew Pinski + + PR libffi/50051 + * src/mips/n32.S: Add ".set mips4". + +2011-11-21 Andreas Tobler + + * configure: Regenerate. + +2011-11-12 David Gilbert + + * doc/libffi.texi, include/ffi.h.in, include/ffi_common.h, + man/Makefile.am, man/ffi.3, man/ffi_prep_cif.3, + man/ffi_prep_cif_var.3, src/arm/ffi.c, src/arm/ffitarget.h, + src/cris/ffi.c, src/prep_cif.c, + testsuite/libffi.call/cls_double_va.c, + testsuite/libffi.call/cls_longdouble_va.c, + testsuite/libffi.call/float_va.c: Many changes to support variadic + function calls. + +2011-11-12 Kyle Moffett + + * src/powerpc/ffi.c, src/powerpc/ffitarget.h, + src/powerpc/ppc_closure.S, src/powerpc/sysv.S: Many changes for + softfloat powerpc variants. + +2011-11-12 Petr Salinger + + * configure.ac (FFI_EXEC_TRAMPOLINE_TABLE): Fix kfreebsd support. + * configure: Rebuilt. + +2011-11-12 Timothy Wall + + * src/arm/ffi.c (ffi_prep_args, ffi_prep_incoming_args_SYSV): Max + alignment of 4 for wince on ARM. + +2011-11-12 Kyle Moffett + Anthony Green + + * src/ppc/sysv.S, src/ppc/ffi.c: Remove use of ppc string + instructions (not available on some cores, like the PPC440). + +2011-11-12 Kimura Wataru + + * m4/ax_enable_builddir: Change from string comparison to numeric + comparison for wc output. + * configure.ac: Enable FFI_MMAP_EXEC_WRIT for darwin11 aka Mac OS + X 10.7. + * configure: Rebuilt. + +2011-11-12 Anthony Green + + * Makefile.am (AM_CCASFLAGS): Add -g option to build assembly + files with debug info. + * Makefile.in: Rebuilt. + +2011-11-12 Jasper Lievisse Adriaanse + + * README: Update list of supported OpenBSD systems. + +2011-11-12 Anthony Green + + * libtool-version: Update. + * Makefile.am (nodist_libffi_la_SOURCES): Add src/debug.c if + FFI_DEBUG. + (libffi_la_SOURCES): Remove src/debug.c + (EXTRA_DIST): Add src/debug.c + * Makefile.in: Rebuilt. + * README: Update for 3.0.11. + +2011-11-10 Richard Henderson + + * configure.ac (GCC_AS_CFI_PSEUDO_OP): Use it instead of inline check. + * configure, aclocal.m4: Rebuild. + +2011-09-04 Iain Sandoe + + PR libffi/49594 + * src/powerpc/darwin_closure.S (stubs): Make the stub binding + helper reference track the architecture pointer size. + +2011-08-25 Andrew Haley + + * src/arm/ffi.c (FFI_INIT_TRAMPOLINE): Remove hard-coded assembly + instructions. + * src/arm/sysv.S (ffi_arm_trampoline): Put them here instead. + +2011-07-11 Andrew Haley + + * src/arm/ffi.c (FFI_INIT_TRAMPOLINE): Clear icache. + +2011-06-29 Rainer Orth + + * testsuite/libffi.call/cls_double_va.c: Move PR number to comment. + * testsuite/libffi.call/cls_longdouble_va.c: Likewise. + +2011-06-29 Rainer Orth + + PR libffi/46660 + * testsuite/libffi.call/cls_double_va.c: xfail dg-output on + mips-sgi-irix6*. + * testsuite/libffi.call/cls_longdouble_va.c: Likewise. + +2011-06-14 Rainer Orth + + * testsuite/libffi.call/huge_struct.c (test_large_fn): Use PRIu8, + PRId8 instead of %hhu, %hhd. + * testsuite/libffi.call/ffitest.h [__alpha__ && __osf__] (PRId8, + PRIu8): Define. + [__sgi__] (PRId8, PRIu8): Define. + +2011-04-29 Rainer Orth + + * src/alpha/osf.S (UA_SI, FDE_ENCODING, FDE_ENCODE, FDE_ARANGE): + Define. + Use them to handle ELF vs. ECOFF differences. + [__osf__] (_GLOBAL__F_ffi_call_osf): Define. + +2011-03-30 Timothy Wall + + * src/powerpc/darwin.S: Fix unknown FDE encoding. + * src/powerpc/darwin_closure.S: ditto. + +2011-02-25 Anthony Green + + * src/powerpc/ffi.c (ffi_prep_closure_loc): Allow for more + 32-bit ABIs. + +2011-02-15 Anthony Green + + * m4/ax_cc_maxopt.m4: Don't -malign-double or use -ffast-math. + * configure: Rebuilt. + +2011-02-13 Ralf Wildenhues + + * configure: Regenerate. + +2011-02-13 Anthony Green + + * include/ffi_common.h (UNLIKELY, LIKELY): Define. + * src/x86/ffi64.c (UNLIKELY, LIKELY): Remove definition. + * src/prep_cif.c (UNLIKELY, LIKELY): Remove definition. + + * src/prep_cif.c (initialize_aggregate): Convert assertion into + FFI_BAD_TYPEDEF return. Initialize arg size and alignment to 0. + + * src/pa/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test, + just return FFI_BAD_ABI when things are wrong. + * src/arm/ffi.c (ffi_prep_closure_loc): Ditto. + * src/powerpc/ffi.c (ffi_prep_closure_loc): Ditto. + * src/mips/ffi.c (ffi_prep_closure_loc): Ditto. + * src/ia64/ffi.c (ffi_prep_closure_loc): Ditto. + * src/avr32/ffi.c (ffi_prep_closure_loc): Ditto. + +2011-02-11 Anthony Green + + * src/sparc/ffi.c (ffi_prep_closure_loc): Don't ASSERT ABI test, + just return FFI_BAD_ABI when things are wrong. + +2012-02-11 Eric Botcazou + + * src/sparc/v9.S (STACKFRAME): Bump to 176. + +2011-02-09 Stuart Shelton + + http://bugs.gentoo.org/show_bug.cgi?id=286911 + * src/mips/ffitarget.h: Clean up error messages. + * src/java_raw_api.c (ffi_java_translate_args): Cast raw arg to + ffi_raw*. + * include/ffi.h.in: Add pragma for SGI compiler. + +2011-02-09 Anthony Green + + * configure.ac: Add powerpc64-*-darwin* support. + +2011-02-09 Anthony Green + + * README: Mention Interix. + +2011-02-09 Jonathan Callen + + * configure.ac: Add Interix to win32/cygwin/mingw case. + * configure: Ditto. + * src/closures.c: Treat Interix like Cygwin, instead of as a + generic win32. + +2011-02-09 Anthony Green + + * testsuite/libffi.call/err_bad_typedef.c: Remove xfail. + * testsuite/libffi.call/err_bad_abi.c: Remove xfail. + * src/x86/ffi64.c (UNLIKELY, LIKELY): Define. + (ffi_prep_closure_loc): Check for bad ABI. + * src/prep_cif.c (UNLIKELY, LIKELY): Define. + (initialize_aggregate): Check for bad types. + +2011-02-09 Landon Fuller + + * Makefile.am (EXTRA_DIST): Add build-ios.sh, src/arm/gentramp.sh, + src/arm/trampoline.S. + (nodist_libffi_la_SOURCES): Add src/arc/trampoline.S. + * configure.ac (FFI_EXEC_TRAMPOLINE_TABLE): Define. + * src/arm/ffi.c (ffi_trampoline_table) + (ffi_closure_trampoline_table_page, ffi_trampoline_table_entry) + (FFI_TRAMPOLINE_CODELOC_CONFIG, FFI_TRAMPOLINE_CONFIG_PAGE_OFFSET) + (FFI_TRAMPOLINE_COUNT, ffi_trampoline_lock, ffi_trampoline_tables) + (ffi_trampoline_table_alloc, ffi_closure_alloc, ffi_closure_free): + Define for FFI_EXEC_TRAMPOLINE_TABLE case (iOS). + (ffi_prep_closure_loc): Handl FFI_EXEC_TRAMPOLINE_TABLE case + separately. + * src/arm/sysv.S: Handle Apple iOS host. + * src/closures.c: Handle FFI_EXEC_TRAMPOLINE_TABLE case. + * build-ios.sh: New file. + * fficonfig.h.in, configure, Makefile.in: Rebuilt. + * README: Mention ARM iOS. + +2011-02-08 Oren Held + + * src/dlmalloc.c (_STRUCT_MALLINFO): Define in order to avoid + redefinition of mallinfo on HP-UX. + +2011-02-08 Ginn Chen + + * src/sparc/ffi.c (ffi_call): Make compatible with Solaris Studio + aggregate return ABI. Flush cache. + (ffi_prep_closure_loc): Flush cache. + +2011-02-11 Anthony Green + + From Tom Honermann : + * src/powerpc/aix.S (ffi_call_AIX): Support for xlc toolchain on + AIX. Declare .ffi_prep_args. Insert nops after branch + instructions so that the AIX linker can insert TOC reload + instructions. + * src/powerpc/aix_closure.S: Declare .ffi_closure_helper_DARWIN. + +2011-02-08 Ed + + * src/powerpc/asm.h: Fix grammar nit in comment. + +2011-02-08 Uli Link + + * include/ffi.h.in (FFI_64_BIT_MAX): Define and use. + +2011-02-09 Rainer Orth + + PR libffi/46661 + * testsuite/libffi.call/cls_pointer.c (main): Cast void * to + uintptr_t first. + * testsuite/libffi.call/cls_pointer_stack.c (main): Likewise. + +2011-02-08 Rafael Avila de Espindola + + * configure.ac: Fix x86 test for pc related relocs. + * configure: Rebuilt. + +2011-02-07 Joel Sherrill + + * libffi/src/m68k/ffi.c: Add RTEMS support for cache flushing. + Handle case when CPU variant does not have long double support. + * libffi/src/m68k/sysv.S: Add support for mc68000, Coldfire, + and cores with soft floating point. + +2011-02-07 Joel Sherrill + + * configure.ac: Add mips*-*-rtems* support. + * configure: Regenerate. + * src/mips/ffitarget.h: Ensure needed constants are available + for targets which do not have sgidefs.h. + +2011-01-26 Dave Korn + + PR target/40125 + * configure.ac (AM_LTLDFLAGS): Add -bindir option for windows DLLs. + * configure: Regenerate. + +2010-12-18 Iain Sandoe + + PR libffi/29152 + PR libffi/42378 + * src/powerpc/darwin_closure.S: Provide Darwin64 implementation, + update comments. + * src/powerpc/ffitarget.h (POWERPC_DARWIN64): New, + (FFI_TRAMPOLINE_SIZE): Update for Darwin64. + * src/powerpc/darwin.S: Provide Darwin64 implementation, + update comments. + * src/powerpc/ffi_darwin.c: Likewise. + +2010-12-06 Rainer Orth + + * configure.ac (libffi_cv_as_ascii_pseudo_op): Use double + backslashes. + (libffi_cv_as_string_pseudo_op): Likewise. + * configure: Regenerate. + +2010-12-03 Chung-Lin Tang + + * src/arm/sysv.S (ffi_closure_SYSV): Add UNWIND to .pad directive. + (ffi_closure_VFP): Same. + (ffi_call_VFP): Move down to before ffi_closure_VFP. Add '.fpu vfp' + directive. + +2010-12-01 Rainer Orth + + * testsuite/libffi.call/ffitest.h [__sgi] (PRId64, PRIu64): Define. + (PRIuPTR): Define. + +2010-11-29 Richard Henderson + Rainer Orth + + * src/x86/sysv.S (FDE_ENCODING, FDE_ENCODE): Define. + (.eh_frame): Use FDE_ENCODING. + (.LASFDE1, .LASFDE2, LASFDE3): Simplify with FDE_ENCODE. + +2010-11-22 Jacek Caban + + * configure.ac: Check for symbol underscores on mingw-w64. + * configure: Rebuilt. + * src/x86/win64.S: Correctly access extern symbols in respect to + underscores. + +2010-11-15 Rainer Orth + + * testsuite/lib/libffi-dg.exp: Rename ... + * testsuite/lib/libffi.exp: ... to this. + * libffi/testsuite/libffi.call/call.exp: Don't load libffi-dg.exp. + * libffi/testsuite/libffi.special/special.exp: Likewise. + +2010-10-28 Chung-Lin Tang + + * src/arm/ffi.c (ffi_prep_args): Add VFP register argument handling + code, new parameter, and return value. Update comments. + (ffi_prep_cif_machdep): Add case for VFP struct return values. Add + call to layout_vfp_args(). + (ffi_call_SYSV): Update declaration. + (ffi_call_VFP): New declaration. + (ffi_call): Add VFP struct return conditions. Call ffi_call_VFP() + when ABI is FFI_VFP. + (ffi_closure_VFP): New declaration. + (ffi_closure_SYSV_inner): Add new vfp_args parameter, update call to + ffi_prep_incoming_args_SYSV(). + (ffi_prep_incoming_args_SYSV): Update parameters. Add VFP argument + case handling. + (ffi_prep_closure_loc): Pass ffi_closure_VFP to trampoline + construction under VFP hard-float. + (rec_vfp_type_p): New function. + (vfp_type_p): Same. + (place_vfp_arg): Same. + (layout_vfp_args): Same. + * src/arm/ffitarget.h (ffi_abi): Add FFI_VFP. Define FFI_DEFAULT_ABI + based on __ARM_PCS_VFP. + (FFI_EXTRA_CIF_FIELDS): Define for adding VFP hard-float specific + fields. + (FFI_TYPE_STRUCT_VFP_FLOAT): Define internally used type code. + (FFI_TYPE_STRUCT_VFP_DOUBLE): Same. + * src/arm/sysv.S (ffi_call_SYSV): Change call of ffi_prep_args() to + direct call. Move function pointer load upwards. + (ffi_call_VFP): New function. + (ffi_closure_VFP): Same. + + * testsuite/lib/libffi-dg.exp (check-flags): New function. + (dg-skip-if): New function. + * testsuite/libffi.call/cls_double_va.c: Skip if target is arm*-*-* + and compiler options include -mfloat-abi=hard. + * testsuite/libffi.call/cls_longdouble_va.c: Same. + +2010-10-01 Jakub Jelinek + + PR libffi/45677 + * src/x86/ffi64.c (ffi_prep_cif_machdep): Ensure cif->bytes is + a multiple of 8. + * testsuite/libffi.call/many2.c: New test. + +2010-08-20 Mark Wielaard + + * src/closures.c (open_temp_exec_file_mnt): Check if getmntent_r + returns NULL. + +2010-08-09 Andreas Tobler + + * configure.ac: Add target powerpc64-*-freebsd*. + * configure: Regenerate. + * testsuite/libffi.call/cls_align_longdouble_split.c: Pass + -mlong-double-128 only to linux targets. + * testsuite/libffi.call/cls_align_longdouble_split2.c: Likewise. + * testsuite/libffi.call/cls_longdouble.c: Likewise. + * testsuite/libffi.call/huge_struct.c: Likewise. + +2010-08-05 Dan Witte + + * Makefile.am: Pass FFI_DEBUG define to msvcc.sh for linking to the + debug CRT when --enable-debug is given. + * configure.ac: Define it. + * msvcc.sh: Translate -g and -DFFI_DEBUG appropriately. + +2010-08-04 Dan Witte + + * src/x86/ffitarget.h: Add X86_ANY define for all x86/x86_64 + platforms. + * src/x86/ffi.c: Remove redundant ifdef checks. + * src/prep_cif.c: Push stack space computation into src/x86/ffi.c + for X86_ANY so return value space doesn't get added twice. + +2010-08-03 Neil Rashbrooke + + * msvcc.sh: Don't pass -safeseh to ml64 because behavior is buggy. + +2010-07-22 Dan Witte + + * src/*/ffitarget.h: Make FFI_LAST_ABI one past the last valid ABI. + * src/prep_cif.c: Fix ABI assertion. + * src/cris/ffi.c: Ditto. + +2010-07-10 Evan Phoenix + + * src/closures.c (selinux_enabled_check): Fix strncmp usage bug. + +2010-07-07 Dan Horák + + * include/ffi.h.in: Protect #define with #ifndef. + * src/powerpc/ffitarget.h: Ditto. + * src/s390/ffitarget.h: Ditto. + * src/sparc/ffitarget.h: Ditto. + +2010-07-07 Neil Roberts + + * src/x86/sysv.S (ffi_call_SYSV): Align the stack pointer to + 16-bytes. + +2010-07-02 Jakub Jelinek + + * Makefile.am (AM_MAKEFLAGS): Pass also mandir to submakes. + * Makefile.in: Regenerated. + +2010-05-19 Rainer Orth + + * configure.ac (libffi_cv_as_x86_pcrel): Check for illegal in as + output, too. + (libffi_cv_as_ascii_pseudo_op): Check for .ascii. + (libffi_cv_as_string_pseudo_op): Check for .string. + * configure: Regenerate. + * fficonfig.h.in: Regenerate. + * src/x86/sysv.S (.eh_frame): Use .ascii, .string or error. + +2010-05-11 Dan Witte + + * doc/libffi.tex: Document previous change. + +2010-05-11 Makoto Kato + + * src/x86/ffi.c (ffi_call): Don't copy structs passed by value. + +2010-05-05 Michael Kohler + + * src/dlmalloc.c (dlfree): Fix spelling. + * src/ia64/ffi.c (ffi_prep_cif_machdep): Ditto. + * configure.ac: Ditto. + * configure: Rebuilt. + +2010-04-13 Dan Witte + + * msvcc.sh: Build with -W3 instead of -Wall. + * src/powerpc/ffi_darwin.c: Remove build warnings. + * src/x86/ffi.c: Ditto. + * src/x86/ffitarget.h: Ditto. + +2010-04-12 Dan Witte + Walter Meinl + + * configure.ac: Add OS/2 support. + * configure: Rebuilt. + * src/closures.c: Ditto. + * src/dlmalloc.c: Ditto. + * src/x86/win32.S: Ditto. + +2010-04-07 Jakub Jelinek + + * testsuite/libffi.call/err_bad_abi.c: Remove unused args variable. + +2010-04-02 Ralf Wildenhues + + * Makefile.in: Regenerate. + * aclocal.m4: Regenerate. + * include/Makefile.in: Regenerate. + * man/Makefile.in: Regenerate. + * testsuite/Makefile.in: Regenerate. + +2010-03-30 Dan Witte + + * msvcc.sh: Disable build warnings. + * README (tested): Clarify windows build procedure. + +2010-03-15 Rainer Orth + + * configure.ac (libffi_cv_as_x86_64_unwind_section_type): New test. + * configure: Regenerate. + * fficonfig.h.in: Regenerate. + * libffi/src/x86/unix64.S (.eh_frame) + [HAVE_AS_X86_64_UNWIND_SECTION_TYPE]: Use @unwind section type. + +2010-03-14 Matthias Klose + + * src/x86/ffi64.c: Fix typo in comment. + * src/x86/ffi.c: Use /* ... */ comment style. + +2010-02-24 Rainer Orth + + * doc/libffi.texi (The Closure API): Fix typo. + * doc/libffi.info: Remove. + +2010-02-15 Matthias Klose + + * src/arm/sysv.S (__ARM_ARCH__): Define for processor + __ARM_ARCH_7EM__. + +2010-01-15 Anthony Green + + * README: Add notes on building with Microsoft Visual C++. + +2010-01-15 Daniel Witte + + * msvcc.sh: New file. + + * src/x86/win32.S: Port assembly routines to MSVC and #ifdef. + * src/x86/ffi.c: Tweak function declaration and remove excess + parens. + * include/ffi.h.in: Add __declspec(align(8)) to typedef struct + ffi_closure. + + * src/x86/ffi.c: Merge ffi_call_SYSV and ffi_call_STDCALL into new + function ffi_call_win32 on X86_WIN32. + * src/x86/win32.S (ffi_call_SYSV): Rename to ffi_call_win32. + (ffi_call_STDCALL): Remove. + + * src/prep_cif.c (ffi_prep_cif): Move stack space allocation code + to ffi_prep_cif_machdep for x86. + * src/x86/ffi.c (ffi_prep_cif_machdep): To here. + +2010-01-15 Oliver Kiddle + + * src/x86/ffitarget.h (ffi_abi): Check for __i386 and __amd64 for + Sun Studio compiler compatibility. + +2010-01-12 Conrad Irwin + + * doc/libffi.texi: Add closure example. + +2010-01-07 Rainer Orth + + PR libffi/40701 + * testsuite/libffi.call/ffitest.h [__alpha__ && __osf__] (PRIdLL, + PRIuLL, PRId64, PRIu64, PRIuPTR): Define. + * testsuite/libffi.call/cls_align_sint64.c: Add -Wno-format on + alpha*-dec-osf*. + * testsuite/libffi.call/cls_align_uint64.c: Likewise. + * testsuite/libffi.call/cls_ulonglong.c: Likewise. + * testsuite/libffi.call/return_ll1.c: Likewise. + * testsuite/libffi.call/stret_medium2.c: Likewise. + * testsuite/libffi.special/ffitestcxx.h (allocate_mmap): Cast + MAP_FAILED to char *. + +2010-01-06 Rainer Orth + + * src/mips/n32.S: Use .abicalls and .eh_frame with __GNUC__. + +2009-12-31 Anthony Green + + * README: Update for libffi 3.0.9. + +2009-12-27 Matthias Klose + + * configure.ac (HAVE_LONG_DOUBLE): Define for mips when + appropriate. + * configure: Rebuilt. + +2009-12-26 Anthony Green + + * testsuite/libffi.call/cls_longdouble_va.c: Mark as xfail for + avr32*-*-*. + * testsuite/libffi.call/cls_double_va.c: Ditto. + +2009-12-26 Andreas Tobler + + * testsuite/libffi.call/ffitest.h: Conditionally include stdint.h + and inttypes.h. + * testsuite/libffi.special/unwindtest.cc: Ditto. + +2009-12-26 Andreas Tobler + + * configure.ac: Add amd64-*-openbsd*. + * configure: Rebuilt. + * testsuite/lib/libffi-dg.exp (libffi_target_compile): Link + openbsd programs with -lpthread. + +2009-12-26 Anthony Green + + * testsuite/libffi.call/cls_double_va.c, + testsuite/libffi.call/cls_longdouble.c, + testsuite/libffi.call/cls_longdouble_va.c, + testsuite/libffi.call/cls_pointer.c, + testsuite/libffi.call/cls_pointer_stack.c: Remove xfail for + mips*-*-* and arm*-*-*. + * testsuite/libffi.call/cls_align_longdouble_split.c, + testsuite/libffi.call/cls_align_longdouble_split2.c, + testsuite/libffi.call/stret_medium2.c, + testsuite/libffi.call/stret_medium.c, + testsuite/libffi.call/stret_large.c, + testsuite/libffi.call/stret_large2.c: Remove xfail for arm*-*-*. + +2009-12-31 Kay Tietz + + * testsuite/libffi.call/ffitest.h, + testsuite/libffi.special/ffitestcxx.h (PRIdLL, PRuLL): Fix + definitions. + +2009-12-31 Carlo Bramini + + * configure.ac (AM_LTLDFLAGS): Define for windows hosts. + * Makefile.am (libffi_la_LDFLAGS): Add AM_LTLDFLAGS. + * configure: Rebuilt. + * Makefile.in: Rebuilt. + +2009-12-31 Anthony Green + Blake Chaffin. + + * testsuite/libffi.call/huge_struct.c: New test case from Blake + Chaffin @ Apple. + +2009-12-28 David Edelsohn + + * src/powerpc/ffi_darwin.c (ffi_prep_args): Copy abi and nargs to + local variables. + (aix_adjust_aggregate_sizes): New function. + (ffi_prep_cif_machdep): Call it. + +2009-12-26 Andreas Tobler + + * configure.ac: Define FFI_MMAP_EXEC_WRIT for the given targets. + * configure: Regenerate. + * fficonfig.h.in: Likewise. + * src/closures.c: Remove the FFI_MMAP_EXEC_WRIT definition for + Solaris/x86. + +2009-12-26 Andreas Schwab + + * src/powerpc/ffi.c (ffi_prep_args_SYSV): Advance intarg_count + when a float arguments is passed in memory. + (ffi_closure_helper_SYSV): Mark general registers as used up when + a 64bit or soft-float long double argument is passed in memory. + +2009-12-25 Matthias Klose + + * man/ffi_call.3: Fix #include in examples. + * doc/libffi.texi: Add dircategory. + +2009-12-25 Frank Everdij + + * include/ffi.h.in: Placed '__GNUC__' ifdef around + '__attribute__((aligned(8)))' in ffi_closure, fixes compile for + IRIX MIPSPro c99. + * include/ffi_common.h: Added '__sgi' define to non + '__attribute__((__mode__()))' integer typedefs. + * src/mips/ffi.c (ffi_call, ffi_closure_mips_inner_O32, + ffi_closure_mips_inner_N32): Added 'defined(_MIPSEB)' to BE check. + (ffi_closure_mips_inner_O32, ffi_closure_mips_inner_N32): Added + FFI_LONGDOUBLE support and alignment(N32 only). + * src/mips/ffitarget.h: Corrected '#include ' for IRIX and + fixed non '__attribute__((__mode__()))' integer typedefs. + * src/mips/n32.S: Put '#ifdef linux' around '.abicalls' and '.eh_frame' + since they are Linux/GNU Assembler specific. + +2009-12-25 Bradley Smith + + * configure.ac, Makefile.am, src/avr32/ffi.c, + src/avr32/ffitarget.h, + src/avr32/sysv.S: Add AVR32 port. + * configure, Makefile.in: Rebuilt. + +2009-12-21 Andreas Tobler + + * configure.ac: Make i?86 build on FreeBSD and OpenBSD. + * configure: Regenerate. + +2009-12-15 John David Anglin + + * testsuite/libffi.call/ffitest.h: Define PRIuPTR on PA HP-UX. + +2009-12-13 John David Anglin + + * src/pa/ffi.c (ffi_closure_inner_pa32): Handle FFI_TYPE_LONGDOUBLE + type on HP-UX. + +2012-02-13 Kai Tietz + + PR libffi/52221 + * src/x86/ffi.c (ffi_prep_raw_closure_loc): Add thiscall + support for X86_WIN32. + (FFI_INIT_TRAMPOLINE_THISCALL): Fix displacement. + +2009-12-11 Eric Botcazou + + * src/sparc/ffi.c (ffi_closure_sparc_inner_v9): Properly align 'long + double' arguments. + +2009-12-11 Eric Botcazou + + * testsuite/libffi.call/ffitest.h: Define PRIuPTR on Solaris < 10. + +2009-12-10 Rainer Orth + + PR libffi/40700 + * src/closures.c [X86_64 && __sun__ && __svr4__] + (FFI_MMAP_EXEC_WRIT): Define. + +2009-12-08 David Daney + + * testsuite/libffi.call/stret_medium.c: Remove xfail for mips*-*-* + * testsuite/libffi.call/cls_align_longdouble_split2.c: Same. + * testsuite/libffi.call/stret_large.c: Same. + * testsuite/libffi.call/cls_align_longdouble_split.c: Same. + * testsuite/libffi.call/stret_large2.c: Same. + * testsuite/libffi.call/stret_medium2.c: Same. + +2009-12-07 David Edelsohn + + * src/powerpc/aix_closure.S (libffi_closure_ASM): Fix tablejump + typo. + +2009-12-05 David Edelsohn + + * src/powerpc/aix.S: Update AIX32 code to be consistent with AIX64 + code. + * src/powerpc/aix_closure.S: Same. + +2009-12-05 Ralf Wildenhues + + * Makefile.in: Regenerate. + * configure: Regenerate. + * include/Makefile.in: Regenerate. + * man/Makefile.in: Regenerate. + * testsuite/Makefile.in: Regenerate. + +2009-12-04 David Edelsohn + + * src/powerpc/aix_closure.S: Reorganize 64-bit code to match + linux64_closure.S. + +2009-12-04 Uros Bizjak + + PR libffi/41908 + * src/x86/ffi64.c (classify_argument): Update from + gcc/config/i386/i386.c. + (ffi_closure_unix64_inner): Do not use the address of two consecutive + SSE registers directly. + * testsuite/libffi.call/cls_dbls_struct.c (main): Remove xfail + for x86_64 linux targets. + +2009-12-04 David Edelsohn + + * src/powerpc/ffi_darwin.c (ffi_closure_helper_DARWIN): Increment + pfr for long double split between fpr13 and stack. + +2009-12-03 David Edelsohn + + * src/powerpc/ffi_darwin.c (ffi_prep_args): Increment next_arg and + fparg_count twice for long double. + +2009-12-03 David Edelsohn + + PR libffi/42243 + * src/powerpc/ffi_darwin.c (ffi_prep_args): Remove extra parentheses. + +2009-12-03 Uros Bizjak + + * testsuite/libffi.call/cls_longdouble_va.c (main): Fix format string. + Remove xfails for x86 linux targets. + +2009-12-02 David Edelsohn + + * src/powerpc/ffi_darwin.c (ffi_prep_args): Fix typo in INT64 + case. + +2009-12-01 David Edelsohn + + * src/powerpc/aix.S (ffi_call_AIX): Convert to more standard + register usage. Call ffi_prep_args directly. Add long double + return value support. + * src/powerpc/ffi_darwin.c (ffi_prep_args): Double arg increment + applies to FFI_TYPE_DOUBLE. Correct fpr_base increment typo. + Separate FFI_TYPE_SINT32 and FFI_TYPE_UINT32 cases. + (ffi_prep_cif_machdep): Only 16 byte stack alignment in 64 bit + mode. + (ffi_closure_helper_DARWIN): Remove nf and ng counters. Move temp + into case. + * src/powerpc/aix_closure.S: Maintain 16 byte stack alignment. + Allocate result area between params and FPRs. + +2009-11-30 David Edelsohn + + PR target/35484 + * src/powerpc/ffitarget.h (POWERPC64): Define for PPC64 Linux and + AIX64. + * src/powerpc/aix.S: Implement AIX64 version. + * src/powerpc/aix_closure.S: Implement AIX64 version. + (ffi_closure_ASM): Use extsb, lha and displament addresses. + * src/powerpc/ffi_darwin.c (ffi_prep_args): Implement AIX64 + support. + (ffi_prep_cif_machdep): Same. + (ffi_call): Same. + (ffi_closure_helper_DARWIN): Same. + +2009-11-02 Andreas Tobler + + PR libffi/41908 + * testsuite/libffi.call/testclosure.c: New test. + +2009-09-28 Kai Tietz + + * src/x86/win64.S (_ffi_call_win64 stack): Remove for gnu + assembly version use of ___chkstk. + +2009-09-23 Matthias Klose + + PR libffi/40242, PR libffi/41443 + * src/arm/sysv.S (__ARM_ARCH__): Define for processors + __ARM_ARCH_6T2__, __ARM_ARCH_6M__, __ARM_ARCH_7__, + __ARM_ARCH_7A__, __ARM_ARCH_7R__, __ARM_ARCH_7M__. + Change the conditionals to __SOFTFP__ || __ARM_EABI__ + for -mfloat-abi=softfp to work. + +2009-09-17 Loren J. Rittle + + PR testsuite/32843 (strikes again) + * src/x86/ffi.c (ffi_prep_cif_machdep): Add X86_FREEBSD to + enable proper extension on char and short. + +2009-09-15 David Daney + + * src/java_raw_api.c (ffi_java_raw_to_rvalue): Remove special + handling for FFI_TYPE_POINTER. + * src/mips/ffitarget.h (FFI_TYPE_STRUCT_D_SOFT, + FFI_TYPE_STRUCT_F_SOFT, FFI_TYPE_STRUCT_DD_SOFT, + FFI_TYPE_STRUCT_FF_SOFT, FFI_TYPE_STRUCT_FD_SOFT, + FFI_TYPE_STRUCT_DF_SOFT, FFI_TYPE_STRUCT_SOFT): New defines. + (FFI_N32_SOFT_FLOAT, FFI_N64_SOFT_FLOAT): New ffi_abi enumerations. + (enum ffi_abi): Set FFI_DEFAULT_ABI for soft-float. + * src/mips/n32.S (ffi_call_N32): Add handling for soft-float + structure and pointer returns. + (ffi_closure_N32): Add handling for pointer returns. + * src/mips/ffi.c (ffi_prep_args, calc_n32_struct_flags, + calc_n32_return_struct_flags): Handle soft-float. + (ffi_prep_cif_machdep): Handle soft-float, fix pointer handling. + (ffi_call_N32): Declare proper argument types. + (ffi_call, copy_struct_N32, ffi_closure_mips_inner_N32): Handle + soft-float. + +2009-08-24 Ralf Wildenhues + + * configure.ac (AC_PREREQ): Bump to 2.64. + +2009-08-22 Ralf Wildenhues + + * Makefile.am (install-html, install-pdf): Remove. + * Makefile.in: Regenerate. + + * Makefile.in: Regenerate. + * aclocal.m4: Regenerate. + * configure: Regenerate. + * fficonfig.h.in: Regenerate. + * include/Makefile.in: Regenerate. + * man/Makefile.in: Regenerate. + * testsuite/Makefile.in: Regenerate. + +2011-08-22 Jasper Lievisse Adriaanse + + * configure.ac: Add OpenBSD/hppa and OpenBSD/powerpc support. + * configure: Rebuilt. + +2009-07-30 Ralf Wildenhues + + * configure.ac (_AC_ARG_VAR_PRECIOUS): Use m4_rename_force. + +2009-07-24 Dave Korn + + PR libffi/40807 + * src/x86/ffi.c (ffi_prep_cif_machdep): Also use sign/zero-extending + return types for X86_WIN32. + * src/x86/win32.S (_ffi_call_SYSV): Handle omitted return types. + (_ffi_call_STDCALL, _ffi_closure_SYSV, _ffi_closure_raw_SYSV, + _ffi_closure_STDCALL): Likewise. + + * src/closures.c (is_selinux_enabled): Define to const 0 for Cygwin. + (dlmmap, dlmunmap): Also use these functions on Cygwin. + +2009-07-11 Richard Sandiford + + PR testsuite/40699 + PR testsuite/40707 + PR testsuite/40709 + * testsuite/lib/libffi-dg.exp: Revert 2009-07-02, 2009-07-01 and + 2009-06-30 commits. + +2009-07-01 Richard Sandiford + + * testsuite/lib/libffi-dg.exp (libffi-init): Set ld_library_path + to "" before adding paths. (This reinstates an assignment that + was removed by my 2009-06-30 commit, but changes the initial + value from "." to "".) + +2009-07-01 H.J. Lu + + PR testsuite/40601 + * testsuite/lib/libffi-dg.exp (libffi-init): Properly set + gccdir. Adjust ld_library_path for gcc only if gccdir isn't + empty. + +2009-06-30 Richard Sandiford + + * testsuite/lib/libffi-dg.exp (libffi-init): Don't add "." + to ld_library_path. Use add_path. Add just find_libgcc_s + to ld_library_path, not every libgcc multilib directory. + +2009-06-16 Wim Lewis + + * src/powerpc/ffi.c: Avoid clobbering cr3 and cr4, which are + supposed to be callee-saved. + * src/powerpc/sysv.S (small_struct_return_value): Fix overrun of + return buffer for odd-size structs. + +2009-06-16 Andreas Tobler + + PR libffi/40444 + * testsuite/lib/libffi-dg.exp (libffi_target_compile): Add + allow_stack_execute for Darwin. + +2009-06-16 Andrew Haley + + * configure.ac (TARGETDIR): Add missing blank lines. + * configure: Regenerate. + +2009-06-16 Andrew Haley + + * testsuite/libffi.call/cls_align_sint64.c, + testsuite/libffi.call/cls_align_uint64.c, + testsuite/libffi.call/cls_longdouble_va.c, + testsuite/libffi.call/cls_ulonglong.c, + testsuite/libffi.call/return_ll1.c, + testsuite/libffi.call/stret_medium2.c: Fix printf format + specifiers. + * testsuite/libffi.call/ffitest.h, + testsuite/libffi.special/ffitestcxx.h (PRIdLL, PRIuLL): Define. + +2009-06-15 Andrew Haley + + * testsuite/libffi.call/err_bad_typedef.c: xfail everywhere. + * testsuite/libffi.call/err_bad_abi.c: Likewise. + +2009-06-12 Andrew Haley + + * Makefile.am: Remove info_TEXINFOS. + +2009-06-12 Andrew Haley + + * ChangeLog.libffi: testsuite/libffi.call/cls_align_sint64.c, + testsuite/libffi.call/cls_align_uint64.c, + testsuite/libffi.call/cls_ulonglong.c, + testsuite/libffi.call/return_ll1.c, + testsuite/libffi.call/stret_medium2.c: Fix printf format + specifiers. + testsuite/libffi.special/unwindtest.cc: include stdint.h. + +2009-06-11 Timothy Wall + + * Makefile.am, + configure.ac, + include/ffi.h.in, + include/ffi_common.h, + src/closures.c, + src/dlmalloc.c, + src/x86/ffi.c, + src/x86/ffitarget.h, + src/x86/win64.S (new), + README: Added win64 support (mingw or MSVC) + * Makefile.in, + include/Makefile.in, + man/Makefile.in, + testsuite/Makefile.in, + configure, + aclocal.m4: Regenerated + * ltcf-c.sh: properly escape cygwin/w32 path + * man/ffi_call.3: Clarify size requirements for return value. + * src/x86/ffi64.c: Fix filename in comment. + * src/x86/win32.S: Remove unused extern. + + * testsuite/libffi.call/closure_fn0.c, + testsuite/libffi.call/closure_fn1.c, + testsuite/libffi.call/closure_fn2.c, + testsuite/libffi.call/closure_fn3.c, + testsuite/libffi.call/closure_fn4.c, + testsuite/libffi.call/closure_fn5.c, + testsuite/libffi.call/closure_fn6.c, + testsuite/libffi.call/closure_stdcall.c, + testsuite/libffi.call/cls_12byte.c, + testsuite/libffi.call/cls_16byte.c, + testsuite/libffi.call/cls_18byte.c, + testsuite/libffi.call/cls_19byte.c, + testsuite/libffi.call/cls_1_1byte.c, + testsuite/libffi.call/cls_20byte.c, + testsuite/libffi.call/cls_20byte1.c, + testsuite/libffi.call/cls_24byte.c, + testsuite/libffi.call/cls_2byte.c, + testsuite/libffi.call/cls_3_1byte.c, + testsuite/libffi.call/cls_3byte1.c, + testsuite/libffi.call/cls_3byte2.c, + testsuite/libffi.call/cls_4_1byte.c, + testsuite/libffi.call/cls_4byte.c, + testsuite/libffi.call/cls_5_1_byte.c, + testsuite/libffi.call/cls_5byte.c, + testsuite/libffi.call/cls_64byte.c, + testsuite/libffi.call/cls_6_1_byte.c, + testsuite/libffi.call/cls_6byte.c, + testsuite/libffi.call/cls_7_1_byte.c, + testsuite/libffi.call/cls_7byte.c, + testsuite/libffi.call/cls_8byte.c, + testsuite/libffi.call/cls_9byte1.c, + testsuite/libffi.call/cls_9byte2.c, + testsuite/libffi.call/cls_align_double.c, + testsuite/libffi.call/cls_align_float.c, + testsuite/libffi.call/cls_align_longdouble.c, + testsuite/libffi.call/cls_align_longdouble_split.c, + testsuite/libffi.call/cls_align_longdouble_split2.c, + testsuite/libffi.call/cls_align_pointer.c, + testsuite/libffi.call/cls_align_sint16.c, + testsuite/libffi.call/cls_align_sint32.c, + testsuite/libffi.call/cls_align_sint64.c, + testsuite/libffi.call/cls_align_uint16.c, + testsuite/libffi.call/cls_align_uint32.c, + testsuite/libffi.call/cls_align_uint64.c, + testsuite/libffi.call/cls_dbls_struct.c, + testsuite/libffi.call/cls_double.c, + testsuite/libffi.call/cls_double_va.c, + testsuite/libffi.call/cls_float.c, + testsuite/libffi.call/cls_longdouble.c, + testsuite/libffi.call/cls_longdouble_va.c, + testsuite/libffi.call/cls_multi_schar.c, + testsuite/libffi.call/cls_multi_sshort.c, + testsuite/libffi.call/cls_multi_sshortchar.c, + testsuite/libffi.call/cls_multi_uchar.c, + testsuite/libffi.call/cls_multi_ushort.c, + testsuite/libffi.call/cls_multi_ushortchar.c, + testsuite/libffi.call/cls_pointer.c, + testsuite/libffi.call/cls_pointer_stack.c, + testsuite/libffi.call/cls_schar.c, + testsuite/libffi.call/cls_sint.c, + testsuite/libffi.call/cls_sshort.c, + testsuite/libffi.call/cls_uchar.c, + testsuite/libffi.call/cls_uint.c, + testsuite/libffi.call/cls_ulonglong.c, + testsuite/libffi.call/cls_ushort.c, + testsuite/libffi.call/err_bad_abi.c, + testsuite/libffi.call/err_bad_typedef.c, + testsuite/libffi.call/float2.c, + testsuite/libffi.call/huge_struct.c, + testsuite/libffi.call/nested_struct.c, + testsuite/libffi.call/nested_struct1.c, + testsuite/libffi.call/nested_struct10.c, + testsuite/libffi.call/nested_struct2.c, + testsuite/libffi.call/nested_struct3.c, + testsuite/libffi.call/nested_struct4.c, + testsuite/libffi.call/nested_struct5.c, + testsuite/libffi.call/nested_struct6.c, + testsuite/libffi.call/nested_struct7.c, + testsuite/libffi.call/nested_struct8.c, + testsuite/libffi.call/nested_struct9.c, + testsuite/libffi.call/problem1.c, + testsuite/libffi.call/return_ldl.c, + testsuite/libffi.call/return_ll1.c, + testsuite/libffi.call/stret_large.c, + testsuite/libffi.call/stret_large2.c, + testsuite/libffi.call/stret_medium.c, + testsuite/libffi.call/stret_medium2.c, + testsuite/libffi.special/unwindtest.cc: use ffi_closure_alloc instead + of checking for MMAP. Use intptr_t instead of long casts. + +2009-06-11 Kaz Kojima + + * testsuite/libffi.call/cls_longdouble_va.c: Add xfail sh*-*-linux-*. + * testsuite/libffi.call/err_bad_abi.c: Add xfail sh*-*-*. + * testsuite/libffi.call/err_bad_typedef.c: Likewise. + +2009-06-09 Andrew Haley + + * src/x86/freebsd.S: Add missing file. + +2009-06-08 Andrew Haley + + Import from libffi 3.0.8: + + * doc/libffi.texi: New file. + * doc/libffi.info: Likewise. + * doc/stamp-vti: Likewise. + * man/Makefile.am: New file. + * man/ffi_call.3: New file. + + * Makefile.am (EXTRA_DIST): Add src/x86/darwin64.S, + src/dlmalloc.c. + (nodist_libffi_la_SOURCES): Add X86_FREEBSD. + + * configure.ac: Bump version to 3.0.8. + parisc*-*-linux*: Add. + i386-*-freebsd* | i386-*-openbsd*: Add. + powerpc-*-beos*: Add. + AM_CONDITIONAL X86_FREEBSD: Add. + AC_CONFIG_FILES: Add man/Makefile. + + * include/ffi.h.in (FFI_FN): Change void (*)() to void (*)(void). + +2009-06-08 Andrew Haley + + * README: Import from libffi 3.0.8. + +2009-06-08 Andrew Haley + + * testsuite/libffi.call/err_bad_abi.c: Add xfails. + * testsuite/libffi.call/cls_longdouble_va.c: Add xfails. + * testsuite/libffi.call/cls_dbls_struct.c: Add xfail x86_64-*-linux-*. + * testsuite/libffi.call/err_bad_typedef.c: Add xfails. + + * testsuite/libffi.call/stret_medium2.c: Add __UNUSED__ to args. + * testsuite/libffi.call/stret_medium.c: Likewise. + * testsuite/libffi.call/stret_large2.c: Likewise. + * testsuite/libffi.call/stret_large.c: Likewise. + +2008-12-26 Timothy Wall + + * testsuite/libffi.call/cls_longdouble.c, + testsuite/libffi.call/cls_longdouble_va.c, + testsuite/libffi.call/cls_align_longdouble.c, + testsuite/libffi.call/cls_align_longdouble_split.c, + testsuite/libffi.call/cls_align_longdouble_split2.c: mark expected + failures on x86_64 cygwin/mingw. + +2008-12-22 Timothy Wall + + * testsuite/libffi.call/closure_fn0.c, + testsuite/libffi.call/closure_fn1.c, + testsuite/libffi.call/closure_fn2.c, + testsuite/libffi.call/closure_fn3.c, + testsuite/libffi.call/closure_fn4.c, + testsuite/libffi.call/closure_fn5.c, + testsuite/libffi.call/closure_fn6.c, + testsuite/libffi.call/closure_loc_fn0.c, + testsuite/libffi.call/closure_stdcall.c, + testsuite/libffi.call/cls_align_pointer.c, + testsuite/libffi.call/cls_pointer.c, + testsuite/libffi.call/cls_pointer_stack.c: use portable cast from + pointer to integer (intptr_t). + * testsuite/libffi.call/cls_longdouble.c: disable for win64. + +2008-07-24 Anthony Green + + * testsuite/libffi.call/cls_dbls_struct.c, + testsuite/libffi.call/cls_double_va.c, + testsuite/libffi.call/cls_longdouble.c, + testsuite/libffi.call/cls_longdouble_va.c, + testsuite/libffi.call/cls_pointer.c, + testsuite/libffi.call/cls_pointer_stack.c, + testsuite/libffi.call/err_bad_abi.c: Clean up failures from + compiler warnings. + +2008-03-04 Anthony Green + Blake Chaffin + hos@tamanegi.org + + * testsuite/libffi.call/cls_align_longdouble_split2.c + testsuite/libffi.call/cls_align_longdouble_split.c + testsuite/libffi.call/cls_dbls_struct.c + testsuite/libffi.call/cls_double_va.c + testsuite/libffi.call/cls_longdouble.c + testsuite/libffi.call/cls_longdouble_va.c + testsuite/libffi.call/cls_pointer.c + testsuite/libffi.call/cls_pointer_stack.c + testsuite/libffi.call/err_bad_abi.c + testsuite/libffi.call/err_bad_typedef.c + testsuite/libffi.call/stret_large2.c + testsuite/libffi.call/stret_large.c + testsuite/libffi.call/stret_medium2.c + testsuite/libffi.call/stret_medium.c: New tests from Apple. + +2009-06-05 Andrew Haley + + * src/x86/ffitarget.h, src/x86/ffi.c: Merge stdcall changes from + libffi. + +2009-06-04 Andrew Haley + + * src/x86/ffitarget.h, src/x86/win32.S, src/x86/ffi.c: Back out + stdcall changes. + +2008-02-26 Anthony Green + Thomas Heller + + * src/x86/ffi.c (ffi_closure_SYSV_inner): Change C++ comment to C + comment. + +2008-02-03 Timothy Wall + + * src/x86/ffi.c (FFI_INIT_TRAMPOLINE_STDCALL): Calculate jump return + offset based on code pointer, not data pointer. + +2008-01-31 Timothy Wall + + * testsuite/libffi.call/closure_stdcall.c: Add test for stdcall + closures. + * src/x86/ffitarget.h: Increase size of trampoline for stdcall + closures. + * src/x86/win32.S: Add assembly for stdcall closure. + * src/x86/ffi.c: Initialize stdcall closure trampoline. + +2009-06-04 Andrew Haley + + * include/ffi.h.in: Change void (*)() to void (*)(void). + * src/x86/ffi.c: Likewise. + +2009-06-04 Andrew Haley + + * src/powerpc/ppc_closure.S: Insert licence header. + * src/powerpc/linux64_closure.S: Likewise. + * src/m68k/sysv.S: Likewise. + + * src/sh64/ffi.c: Change void (*)() to void (*)(void). + * src/powerpc/ffi.c: Likewise. + * src/powerpc/ffi_darwin.c: Likewise. + * src/m32r/ffi.c: Likewise. + * src/sh64/ffi.c: Likewise. + * src/x86/ffi64.c: Likewise. + * src/alpha/ffi.c: Likewise. + * src/alpha/osf.S: Likewise. + * src/frv/ffi.c: Likewise. + * src/s390/ffi.c: Likewise. + * src/pa/ffi.c: Likewise. + * src/pa/hpux32.S: Likewise. + * src/ia64/unix.S: Likewise. + * src/ia64/ffi.c: Likewise. + * src/sparc/ffi.c: Likewise. + * src/mips/ffi.c: Likewise. + * src/sh/ffi.c: Likewise. + +2008-02-15 David Daney + + * src/mips/ffi.c (USE__BUILTIN___CLEAR_CACHE): + Define (conditionally), and use it to include cachectl.h. + (ffi_prep_closure_loc): Fix cache flushing. + * src/mips/ffitarget.h (_ABIN32, _ABI64, _ABIO32): Define. + +2009-06-04 Andrew Haley + + include/ffi.h.in, + src/arm/ffitarget.h, + src/arm/ffi.c, + src/arm/sysv.S, + src/powerpc/ffitarget.h, + src/closures.c, + src/sh64/ffitarget.h, + src/sh64/ffi.c, + src/sh64/sysv.S, + src/types.c, + src/x86/ffi64.c, + src/x86/ffitarget.h, + src/x86/win32.S, + src/x86/darwin.S, + src/x86/ffi.c, + src/x86/sysv.S, + src/x86/unix64.S, + src/alpha/ffitarget.h, + src/alpha/ffi.c, + src/alpha/osf.S, + src/m68k/ffitarget.h, + src/frv/ffitarget.h, + src/frv/ffi.c, + src/s390/ffitarget.h, + src/s390/sysv.S, + src/cris/ffitarget.h, + src/pa/linux.S, + src/pa/ffitarget.h, + src/pa/ffi.c, + src/raw_api.c, + src/ia64/ffitarget.h, + src/ia64/unix.S, + src/ia64/ffi.c, + src/ia64/ia64_flags.h, + src/java_raw_api.c, + src/debug.c, + src/sparc/v9.S, + src/sparc/ffitarget.h, + src/sparc/ffi.c, + src/sparc/v8.S, + src/mips/ffitarget.h, + src/mips/n32.S, + src/mips/o32.S, + src/mips/ffi.c, + src/prep_cif.c, + src/sh/ffitarget.h, + src/sh/ffi.c, + src/sh/sysv.S: Update license text. + +2009-05-22 Dave Korn + + * src/x86/win32.S (_ffi_closure_STDCALL): New function. + (.eh_frame): Add FDE for it. + +2009-05-22 Dave Korn + + * configure.ac: Also check if assembler supports pc-relative + relocs on X86_WIN32 targets. + * configure: Regenerate. + * src/x86/win32.S (ffi_prep_args): Declare extern, not global. + (_ffi_call_SYSV): Add missing function type symbol .def and + add EH markup labels. + (_ffi_call_STDCALL): Likewise. + (_ffi_closure_SYSV): Likewise. + (_ffi_closure_raw_SYSV): Likewise. + (.eh_frame): Add hand-crafted EH data. + +2009-04-09 Jakub Jelinek + + * testsuite/lib/libffi-dg.exp: Change copyright header to refer to + version 3 of the GNU General Public License and to point readers + at the COPYING3 file and the FSF's license web page. + * testsuite/libffi.call/call.exp: Likewise. + * testsuite/libffi.special/special.exp: Likewise. + +2009-03-01 Ralf Wildenhues + + * configure: Regenerate. + +2008-12-18 Rainer Orth + + PR libffi/26048 + * configure.ac (HAVE_AS_X86_PCREL): New test. + * configure: Regenerate. + * fficonfig.h.in: Regenerate. + * src/x86/sysv.S [!FFI_NO_RAW_API]: Precalculate + RAW_CLOSURE_CIF_OFFSET, RAW_CLOSURE_FUN_OFFSET, + RAW_CLOSURE_USER_DATA_OFFSET for the Solaris 10/x86 assembler. + (.eh_frame): Only use SYMBOL-. iff HAVE_AS_X86_PCREL. + * src/x86/unix64.S (.Lstore_table): Move to .text section. + (.Lload_table): Likewise. + (.eh_frame): Only use SYMBOL-. iff HAVE_AS_X86_PCREL. + +2008-12-18 Ralf Wildenhues + + * configure: Regenerate. + +2008-11-21 Eric Botcazou + + * src/sparc/ffi.c (ffi_prep_cif_machdep): Add support for + signed/unsigned int8/16 return values. + * src/sparc/v8.S (ffi_call_v8): Likewise. + (ffi_closure_v8): Likewise. + +2008-09-26 Peter O'Gorman + Steve Ellcey + + * configure: Regenerate for new libtool. + * Makefile.in: Ditto. + * include/Makefile.in: Ditto. + * aclocal.m4: Ditto. + +2008-08-25 Andreas Tobler + + * src/powerpc/ffitarget.h (ffi_abi): Add FFI_LINUX and + FFI_LINUX_SOFT_FLOAT to the POWERPC_FREEBSD enum. + Add note about flag bits used for FFI_SYSV_TYPE_SMALL_STRUCT. + Adjust copyright notice. + * src/powerpc/ffi.c: Add two new flags to indicate if we have one + register or two register to use for FFI_SYSV structs. + (ffi_prep_cif_machdep): Pass the right register flag introduced above. + (ffi_closure_helper_SYSV): Fix the return type for + FFI_SYSV_TYPE_SMALL_STRUCT. Comment. + Adjust copyright notice. + +2008-07-16 Kaz Kojima + + * src/sh/ffi.c (ffi_prep_closure_loc): Turn INSN into an unsigned + int. + +2008-06-17 Ralf Wildenhues + + * configure: Regenerate. + * include/Makefile.in: Regenerate. + * testsuite/Makefile.in: Regenerate. + +2008-06-07 Joseph Myers + + * configure.ac (parisc*-*-linux*, powerpc-*-sysv*, + powerpc-*-beos*): Remove. + * configure: Regenerate. + +2008-05-09 Julian Brown + + * Makefile.am (LTLDFLAGS): New. + (libffi_la_LDFLAGS): Use above. + * Makefile.in: Regenerate. + +2008-04-18 Paolo Bonzini + + PR bootstrap/35457 + * aclocal.m4: Regenerate. + * configure: Regenerate. + +2008-03-26 Kaz Kojima + + * src/sh/sysv.S: Add .note.GNU-stack on Linux. + * src/sh64/sysv.S: Likewise. + +2008-03-26 Daniel Jacobowitz + + * src/arm/sysv.S: Fix ARM comment marker. + +2008-03-26 Jakub Jelinek + + * src/alpha/osf.S: Add .note.GNU-stack on Linux. + * src/s390/sysv.S: Likewise. + * src/powerpc/ppc_closure.S: Likewise. + * src/powerpc/sysv.S: Likewise. + * src/x86/unix64.S: Likewise. + * src/x86/sysv.S: Likewise. + * src/sparc/v8.S: Likewise. + * src/sparc/v9.S: Likewise. + * src/m68k/sysv.S: Likewise. + * src/arm/sysv.S: Likewise. + +2008-03-16 Ralf Wildenhues + + * aclocal.m4: Regenerate. + * configure: Likewise. + * Makefile.in: Likewise. + * include/Makefile.in: Likewise. + * testsuite/Makefile.in: Likewise. + +2008-02-12 Bjoern Koenig + Andreas Tobler + + * configure.ac: Add amd64-*-freebsd* target. + * configure: Regenerate. + +2008-01-30 H.J. Lu + + PR libffi/34612 + * src/x86/sysv.S (ffi_closure_SYSV): Pop 4 byte from stack when + returning struct. + + * testsuite/libffi.call/call.exp: Add "-O2 -fomit-frame-pointer" + tests. + +2008-01-24 David Edelsohn + + * configure: Regenerate. + +2008-01-06 Andreas Tobler + + * src/x86/ffi.c (ffi_prep_cif_machdep): Fix thinko. + +2008-01-05 Andreas Tobler + + PR testsuite/32843 + * src/x86/ffi.c (ffi_prep_cif_machdep): Add code for + signed/unsigned int8/16 for X86_DARWIN. + Updated copyright info. + Handle one and two byte structs with special cif->flags. + * src/x86/ffitarget.h: Add special types for one and two byte structs. + Updated copyright info. + * src/x86/darwin.S (ffi_call_SYSV): Rewrite to use a jump table like + sysv.S + Remove code to pop args from the stack after call. + Special-case signed/unsigned for int8/16, one and two byte structs. + (ffi_closure_raw_SYSV): Handle FFI_TYPE_UINT8, + FFI_TYPE_SINT8, FFI_TYPE_UINT16, FFI_TYPE_SINT16, FFI_TYPE_UINT32, + FFI_TYPE_SINT32. + Updated copyright info. + +2007-12-08 David Daney + + * src/mips/n32.S (ffi_call_N32): Replace dadd with ADDU, dsub with + SUBU, add with ADDU and use smaller code sequences. + +2007-12-07 David Daney + + * src/mips/ffi.c (ffi_prep_cif_machdep): Handle long double return + type. + +2007-12-06 David Daney + + * include/ffi.h.in (FFI_SIZEOF_JAVA_RAW): Define if not already + defined. + (ffi_java_raw): New typedef. + (ffi_java_raw_call, ffi_java_ptrarray_to_raw, + ffi_java_raw_to_ptrarray): Change parameter types from ffi_raw to + ffi_java_raw. + (ffi_java_raw_closure) : Same. + (ffi_prep_java_raw_closure, ffi_prep_java_raw_closure_loc): Change + parameter types. + * src/java_raw_api.c (ffi_java_raw_size): Replace FFI_SIZEOF_ARG with + FFI_SIZEOF_JAVA_RAW. + (ffi_java_raw_to_ptrarray): Change type of raw to ffi_java_raw. + Replace FFI_SIZEOF_ARG with FFI_SIZEOF_JAVA_RAW. Use + sizeof(ffi_java_raw) for alignment calculations. + (ffi_java_ptrarray_to_raw): Same. + (ffi_java_rvalue_to_raw): Add special handling for FFI_TYPE_POINTER + if FFI_SIZEOF_JAVA_RAW == 4. + (ffi_java_raw_to_rvalue): Same. + (ffi_java_raw_call): Change type of raw to ffi_java_raw. + (ffi_java_translate_args): Same. + (ffi_prep_java_raw_closure_loc, ffi_prep_java_raw_closure): Change + parameter types. + * src/mips/ffitarget.h (FFI_SIZEOF_JAVA_RAW): Define for N32 ABI. + +2007-12-06 David Daney + + * src/mips/n32.S (ffi_closure_N32): Use 64-bit add instruction on + pointer values. + +2007-12-01 Andreas Tobler + + PR libffi/31937 + * src/powerpc/ffitarget.h: Introduce new ABI FFI_LINUX_SOFT_FLOAT. + Add local FFI_TYPE_UINT128 to handle soft-float long-double-128. + * src/powerpc/ffi.c: Distinguish between __NO_FPRS__ and not and + set the NUM_FPR_ARG_REGISTERS according to. + Add support for potential soft-float support under hard-float + architecture. + (ffi_prep_args_SYSV): Set NUM_FPR_ARG_REGISTERS to 0 in case of + FFI_LINUX_SOFT_FLOAT, handle float, doubles and long-doubles according + to the FFI_LINUX_SOFT_FLOAT ABI. + (ffi_prep_cif_machdep): Likewise. + (ffi_closure_helper_SYSV): Likewise. + * src/powerpc/ppc_closure.S: Make sure not to store float/double + on archs where __NO_FPRS__ is true. + Add FFI_TYPE_UINT128 support. + * src/powerpc/sysv.S: Add support for soft-float long-double-128. + Adjust copyright notice. + +2007-11-25 Andreas Tobler + + * src/closures.c: Move defintion of MAYBE_UNUSED from here to ... + * include/ffi_common.h: ... here. + Update copyright. + +2007-11-17 Andreas Tobler + + * src/powerpc/sysv.S: Load correct cr to compare if we have long double. + * src/powerpc/linux64.S: Likewise. + * src/powerpc/ffi.c: Add a comment to show which part goes into cr6. + * testsuite/libffi.call/return_ldl.c: New test. + +2007-09-04 + + * src/arm/sysv.S (UNWIND): New. + (Whole file): Conditionally compile unwinder directives. + * src/arm/sysv.S: Add unwinder directives. + + * src/arm/ffi.c (ffi_prep_args): Align structs by at least 4 bytes. + Only treat r0 as a struct address if we're actually returning a + struct by address. + Only copy the bytes that are actually within a struct. + (ffi_prep_cif_machdep): A Composite Type not larger than 4 bytes + is returned in r0, not passed by address. + (ffi_call): Allocate a word-sized temporary for the case where + a composite is returned in r0. + (ffi_prep_incoming_args_SYSV): Align as necessary. + +2007-08-05 Steven Newbury + + * src/arm/ffi.c (FFI_INIT_TRAMPOLINE): Use __clear_cache instead of + directly using the sys_cacheflush syscall. + +2007-07-27 Andrew Haley + + * src/arm/sysv.S (ffi_closure_SYSV): Add soft-float. + +2007-09-03 Maciej W. Rozycki + + * Makefile.am: Unify MIPS_IRIX and MIPS_LINUX into MIPS. + * configure.ac: Likewise. + * Makefile.in: Regenerate. + * include/Makefile.in: Likewise. + * testsuite/Makefile.in: Likewise. + * configure: Likewise. + +2007-08-24 David Daney + + * testsuite/libffi.call/return_sl.c: New test. + +2007-08-10 David Daney + + * testsuite/libffi.call/cls_multi_ushort.c, + testsuite/libffi.call/cls_align_uint16.c, + testsuite/libffi.call/nested_struct1.c, + testsuite/libffi.call/nested_struct3.c, + testsuite/libffi.call/cls_7_1_byte.c, + testsuite/libffi.call/nested_struct5.c, + testsuite/libffi.call/cls_double.c, + testsuite/libffi.call/nested_struct7.c, + testsuite/libffi.call/cls_sint.c, + testsuite/libffi.call/nested_struct9.c, + testsuite/libffi.call/cls_20byte1.c, + testsuite/libffi.call/cls_multi_sshortchar.c, + testsuite/libffi.call/cls_align_sint64.c, + testsuite/libffi.call/cls_3byte2.c, + testsuite/libffi.call/cls_multi_schar.c, + testsuite/libffi.call/cls_multi_uchar.c, + testsuite/libffi.call/cls_19byte.c, + testsuite/libffi.call/cls_9byte1.c, + testsuite/libffi.call/cls_align_float.c, + testsuite/libffi.call/closure_fn1.c, + testsuite/libffi.call/problem1.c, + testsuite/libffi.call/closure_fn3.c, + testsuite/libffi.call/cls_sshort.c, + testsuite/libffi.call/closure_fn5.c, + testsuite/libffi.call/cls_align_double.c, + testsuite/libffi.call/nested_struct.c, + testsuite/libffi.call/cls_2byte.c, + testsuite/libffi.call/nested_struct10.c, + testsuite/libffi.call/cls_4byte.c, + testsuite/libffi.call/cls_6byte.c, + testsuite/libffi.call/cls_8byte.c, + testsuite/libffi.call/cls_multi_sshort.c, + testsuite/libffi.call/cls_align_sint16.c, + testsuite/libffi.call/cls_align_uint32.c, + testsuite/libffi.call/cls_20byte.c, + testsuite/libffi.call/cls_float.c, + testsuite/libffi.call/nested_struct2.c, + testsuite/libffi.call/cls_5_1_byte.c, + testsuite/libffi.call/nested_struct4.c, + testsuite/libffi.call/cls_24byte.c, + testsuite/libffi.call/nested_struct6.c, + testsuite/libffi.call/cls_64byte.c, + testsuite/libffi.call/nested_struct8.c, + testsuite/libffi.call/cls_uint.c, + testsuite/libffi.call/cls_multi_ushortchar.c, + testsuite/libffi.call/cls_schar.c, + testsuite/libffi.call/cls_uchar.c, + testsuite/libffi.call/cls_align_uint64.c, + testsuite/libffi.call/cls_ulonglong.c, + testsuite/libffi.call/cls_align_longdouble.c, + testsuite/libffi.call/cls_1_1byte.c, + testsuite/libffi.call/cls_12byte.c, + testsuite/libffi.call/cls_3_1byte.c, + testsuite/libffi.call/cls_3byte1.c, + testsuite/libffi.call/cls_4_1byte.c, + testsuite/libffi.call/cls_6_1_byte.c, + testsuite/libffi.call/cls_16byte.c, + testsuite/libffi.call/cls_18byte.c, + testsuite/libffi.call/closure_fn0.c, + testsuite/libffi.call/cls_9byte2.c, + testsuite/libffi.call/closure_fn2.c, + testsuite/libffi.call/closure_fn4.c, + testsuite/libffi.call/cls_ushort.c, + testsuite/libffi.call/closure_fn6.c, + testsuite/libffi.call/cls_5byte.c, + testsuite/libffi.call/cls_align_pointer.c, + testsuite/libffi.call/cls_7byte.c, + testsuite/libffi.call/cls_align_sint32.c, + testsuite/libffi.special/unwindtest_ffi_call.cc, + testsuite/libffi.special/unwindtest.cc: Remove xfail for mips64*-*-*. + +2007-08-10 David Daney + + PR libffi/28313 + * configure.ac: Don't treat mips64 as a special case. + * Makefile.am (nodist_libffi_la_SOURCES): Add n32.S. + * configure: Regenerate + * Makefile.in: Ditto. + * fficonfig.h.in: Ditto. + * src/mips/ffitarget.h (REG_L, REG_S, SUBU, ADDU, SRL, LI): Indent. + (LA, EH_FRAME_ALIGN, FDE_ADDR_BYTES): New preprocessor macros. + (FFI_DEFAULT_ABI): Set for n64 case. + (FFI_CLOSURES, FFI_TRAMPOLINE_SIZE): Define for n32 and n64 cases. + * src/mips/n32.S (ffi_call_N32): Add debug macros and labels for FDE. + (ffi_closure_N32): New function. + (.eh_frame): New section + * src/mips/o32.S: Clean up comments. + (ffi_closure_O32): Pass ffi_closure parameter in $12. + * src/mips/ffi.c: Use FFI_MIPS_N32 instead of + _MIPS_SIM == _ABIN32 throughout. + (FFI_MIPS_STOP_HERE): New, use in place of + ffi_stop_here. + (ffi_prep_args): Use unsigned long to hold pointer values. Rewrite + to support n32/n64 ABIs. + (calc_n32_struct_flags): Rewrite. + (calc_n32_return_struct_flags): Remove unused variable. Reverse + position of flag bits. + (ffi_prep_cif_machdep): Rewrite n32 portion. + (ffi_call): Enable for n64. Add special handling for small structure + return values. + (ffi_prep_closure_loc): Add n32 and n64 support. + (ffi_closure_mips_inner_O32): Add cast to silence warning. + (copy_struct_N32, ffi_closure_mips_inner_N32): New functions. + +2007-08-08 David Daney + + * testsuite/libffi.call/ffitest.h (ffi_type_mylong): Remove definition. + * testsuite/libffi.call/cls_align_uint16.c (main): Use correct type + specifiers. + * testsuite/libffi.call/nested_struct1.c (main): Ditto. + * testsuite/libffi.call/cls_sint.c (main): Ditto. + * testsuite/libffi.call/nested_struct9.c (main): Ditto. + * testsuite/libffi.call/cls_20byte1.c (main): Ditto. + * testsuite/libffi.call/cls_9byte1.c (main): Ditto. + * testsuite/libffi.call/closure_fn1.c (main): Ditto. + * testsuite/libffi.call/closure_fn3.c (main): Ditto. + * testsuite/libffi.call/return_dbl2.c (main): Ditto. + * testsuite/libffi.call/cls_sshort.c (main): Ditto. + * testsuite/libffi.call/return_fl3.c (main): Ditto. + * testsuite/libffi.call/closure_fn5.c (main): Ditto. + * testsuite/libffi.call/nested_struct.c (main): Ditto. + * testsuite/libffi.call/nested_struct10.c (main): Ditto. + * testsuite/libffi.call/return_ll1.c (main): Ditto. + * testsuite/libffi.call/cls_8byte.c (main): Ditto. + * testsuite/libffi.call/cls_align_uint32.c (main): Ditto. + * testsuite/libffi.call/cls_align_sint16.c (main): Ditto. + * testsuite/libffi.call/cls_20byte.c (main): Ditto. + * testsuite/libffi.call/nested_struct2.c (main): Ditto. + * testsuite/libffi.call/cls_24byte.c (main): Ditto. + * testsuite/libffi.call/nested_struct6.c (main): Ditto. + * testsuite/libffi.call/cls_uint.c (main): Ditto. + * testsuite/libffi.call/cls_12byte.c (main): Ditto. + * testsuite/libffi.call/cls_16byte.c (main): Ditto. + * testsuite/libffi.call/closure_fn0.c (main): Ditto. + * testsuite/libffi.call/cls_9byte2.c (main): Ditto. + * testsuite/libffi.call/closure_fn2.c (main): Ditto. + * testsuite/libffi.call/return_dbl1.c (main): Ditto. + * testsuite/libffi.call/closure_fn4.c (main): Ditto. + * testsuite/libffi.call/closure_fn6.c (main): Ditto. + * testsuite/libffi.call/cls_align_sint32.c (main): Ditto. + +2007-08-07 Andrew Haley + + * src/x86/sysv.S (ffi_closure_raw_SYSV): Fix typo in previous + checkin. + +2007-08-06 Andrew Haley + + PR testsuite/32843 + * src/x86/sysv.S (ffi_closure_raw_SYSV): Handle FFI_TYPE_UINT8, + FFI_TYPE_SINT8, FFI_TYPE_UINT16, FFI_TYPE_SINT16, FFI_TYPE_UINT32, + FFI_TYPE_SINT32. + +2007-08-02 David Daney + + * testsuite/libffi.call/return_ul.c (main): Define return type as + ffi_arg. Use proper printf conversion specifier. + +2007-07-30 Andrew Haley + + PR testsuite/32843 + * src/x86/ffi.c (ffi_prep_cif_machdep): in x86 case, add code for + signed/unsigned int8/16. + * src/x86/sysv.S (ffi_call_SYSV): Rewrite to: + Use a jump table. + Remove code to pop args from the stack after call. + Special-case signed/unsigned int8/16. + * testsuite/libffi.call/return_sc.c (main): Revert. + +2007-07-26 Richard Guenther + + PR testsuite/32843 + * testsuite/libffi.call/return_sc.c (main): Verify call + result as signed char, not ffi_arg. + +2007-07-16 Rainer Orth + + * configure.ac (i?86-*-solaris2.1[0-9]): Set TARGET to X86_64. + * configure: Regenerate. + +2007-07-11 David Daney + + * src/mips/ffi.c: Don't include sys/cachectl.h. + (ffi_prep_closure_loc): Use __builtin___clear_cache() instead of + cacheflush(). + +2007-05-18 Aurelien Jarno + + * src/arm/ffi.c (ffi_prep_closure_loc): Renamed and ajusted + from (ffi_prep_closure): ... this. + (FFI_INIT_TRAMPOLINE): Adjust. + +2005-12-31 Phil Blundell + + * src/arm/ffi.c (ffi_prep_incoming_args_SYSV, + ffi_closure_SYSV_inner, ffi_prep_closure): New, add closure support. + * src/arm/sysv.S(ffi_closure_SYSV): Likewise. + * src/arm/ffitarget.h (FFI_TRAMPOLINE_SIZE): Likewise. + (FFI_CLOSURES): Enable closure support. + +2007-07-03 Andrew Haley + + * testsuite/libffi.call/cls_multi_ushort.c, + testsuite/libffi.call/cls_align_uint16.c, + testsuite/libffi.call/nested_struct1.c, + testsuite/libffi.call/nested_struct3.c, + testsuite/libffi.call/cls_7_1_byte.c, + testsuite/libffi.call/cls_double.c, + testsuite/libffi.call/nested_struct5.c, + testsuite/libffi.call/nested_struct7.c, + testsuite/libffi.call/cls_sint.c, + testsuite/libffi.call/nested_struct9.c, + testsuite/libffi.call/cls_20byte1.c, + testsuite/libffi.call/cls_multi_sshortchar.c, + testsuite/libffi.call/cls_align_sint64.c, + testsuite/libffi.call/cls_3byte2.c, + testsuite/libffi.call/cls_multi_schar.c, + testsuite/libffi.call/cls_multi_uchar.c, + testsuite/libffi.call/cls_19byte.c, + testsuite/libffi.call/cls_9byte1.c, + testsuite/libffi.call/cls_align_float.c, + testsuite/libffi.call/closure_fn1.c, + testsuite/libffi.call/problem1.c, + testsuite/libffi.call/closure_fn3.c, + testsuite/libffi.call/cls_sshort.c, + testsuite/libffi.call/closure_fn5.c, + testsuite/libffi.call/cls_align_double.c, + testsuite/libffi.call/cls_2byte.c, + testsuite/libffi.call/nested_struct.c, + testsuite/libffi.call/nested_struct10.c, + testsuite/libffi.call/cls_4byte.c, + testsuite/libffi.call/cls_6byte.c, + testsuite/libffi.call/cls_8byte.c, + testsuite/libffi.call/cls_multi_sshort.c, + testsuite/libffi.call/cls_align_uint32.c, + testsuite/libffi.call/cls_align_sint16.c, + testsuite/libffi.call/cls_float.c, + testsuite/libffi.call/cls_20byte.c, + testsuite/libffi.call/cls_5_1_byte.c, + testsuite/libffi.call/nested_struct2.c, + testsuite/libffi.call/cls_24byte.c, + testsuite/libffi.call/nested_struct4.c, + testsuite/libffi.call/nested_struct6.c, + testsuite/libffi.call/cls_64byte.c, + testsuite/libffi.call/nested_struct8.c, + testsuite/libffi.call/cls_uint.c, + testsuite/libffi.call/cls_multi_ushortchar.c, + testsuite/libffi.call/cls_schar.c, + testsuite/libffi.call/cls_uchar.c, + testsuite/libffi.call/cls_align_uint64.c, + testsuite/libffi.call/cls_ulonglong.c, + testsuite/libffi.call/cls_align_longdouble.c, + testsuite/libffi.call/cls_1_1byte.c, + testsuite/libffi.call/cls_12byte.c, + testsuite/libffi.call/cls_3_1byte.c, + testsuite/libffi.call/cls_3byte1.c, + testsuite/libffi.call/cls_4_1byte.c, + testsuite/libffi.call/cls_6_1_byte.c, + testsuite/libffi.call/cls_16byte.c, + testsuite/libffi.call/cls_18byte.c, + testsuite/libffi.call/closure_fn0.c, + testsuite/libffi.call/cls_9byte2.c, + testsuite/libffi.call/closure_fn2.c, + testsuite/libffi.call/closure_fn4.c, + testsuite/libffi.call/cls_ushort.c, + testsuite/libffi.call/closure_fn6.c, + testsuite/libffi.call/cls_5byte.c, + testsuite/libffi.call/cls_align_pointer.c, + testsuite/libffi.call/cls_7byte.c, + testsuite/libffi.call/cls_align_sint32.c, + testsuite/libffi.special/unwindtest_ffi_call.cc, + testsuite/libffi.special/unwindtest.cc: Enable for ARM. + +2007-07-05 H.J. Lu + + * aclocal.m4: Regenerated. + +2007-06-02 Paolo Bonzini + + * configure: Regenerate. + +2007-05-23 Steve Ellcey + + * Makefile.in: Regenerate. + * configure: Regenerate. + * aclocal.m4: Regenerate. + * include/Makefile.in: Regenerate. + * testsuite/Makefile.in: Regenerate. + +2007-05-10 Roman Zippel + + * src/m68k/ffi.c (ffi_prep_incoming_args_SYSV, + ffi_closure_SYSV_inner,ffi_prep_closure): New, add closure support. + * src/m68k/sysv.S(ffi_closure_SYSV,ffi_closure_struct_SYSV): Likewise. + * src/m68k/ffitarget.h (FFI_TRAMPOLINE_SIZE): Likewise. + (FFI_CLOSURES): Enable closure support. + +2007-05-10 Roman Zippel + + * configure.ac (HAVE_AS_CFI_PSEUDO_OP): New test. + * configure: Regenerate. + * fficonfig.h.in: Regenerate. + * src/m68k/sysv.S (CFI_STARTPROC,CFI_ENDPROC, + CFI_OFFSET,CFI_DEF_CFA): New macros. + (ffi_call_SYSV): Add callframe annotation. + +2007-05-10 Roman Zippel + + * src/m68k/ffi.c (ffi_prep_args,ffi_prep_cif_machdep): Fix + numerous test suite failures. + * src/m68k/sysv.S (ffi_call_SYSV): Likewise. + +2007-04-11 Paolo Bonzini + + * Makefile.am (EXTRA_DIST): Bring up to date. + * Makefile.in: Regenerate. + * src/frv/eabi.S: Remove RCS keyword. + +2007-04-06 Richard Henderson + + * configure.ac: Tidy target case. + (HAVE_LONG_DOUBLE): Allow the target to override. + * configure: Regenerate. + * include/ffi.h.in: Don't define ffi_type_foo if + LIBFFI_HIDE_BASIC_TYPES is defined. + (ffi_type_longdouble): If not HAVE_LONG_DOUBLE, define + to ffi_type_double. + * types.c (LIBFFI_HIDE_BASIC_TYPES): Define. + (FFI_TYPEDEF, ffi_type_void): Mark the data const. + (ffi_type_longdouble): Special case for Alpha. Don't define + if long double == double. + + * src/alpha/ffi.c (FFI_TYPE_LONGDOUBLE): Assert unique value. + (ffi_prep_cif_machdep): Handle it as the 128-bit type. + (ffi_call, ffi_closure_osf_inner): Likewise. + (ffi_closure_osf_inner): Likewise. Mark hidden. + (ffi_call_osf, ffi_closure_osf): Mark hidden. + * src/alpha/ffitarget.h (FFI_LAST_ABI): Tidy definition. + * src/alpha/osf.S (ffi_call_osf, ffi_closure_osf): Mark hidden. + (load_table): Handle 128-bit long double. + + * testsuite/libffi.call/float4.c: Add -mieee for alpha. + +2007-04-06 Tom Tromey + + PR libffi/31491: + * README: Fixed bug in example. + +2007-04-03 Jakub Jelinek + + * src/closures.c: Include sys/statfs.h. + (_GNU_SOURCE): Define on Linux. + (FFI_MMAP_EXEC_SELINUX): Define. + (selinux_enabled): New variable. + (selinux_enabled_check): New function. + (is_selinux_enabled): Define. + (dlmmap): Use it. + +2007-03-24 Uros Bizjak + + * testsuite/libffi.call/return_fl2.c (return_fl): Mark as static. + Use 'volatile float sum' to create sum of floats to avoid false + negative due to excess precision on ix86 targets. + (main): Ditto. + +2007-03-08 Alexandre Oliva + + * src/powerpc/ffi.c (flush_icache): Fix left-over from previous + patch. + (ffi_prep_closure_loc): Remove unneeded casts. Add needed ones. + +2007-03-07 Alexandre Oliva + + * include/ffi.h.in (ffi_closure_alloc, ffi_closure_free): New. + (ffi_prep_closure_loc): New. + (ffi_prep_raw_closure_loc): New. + (ffi_prep_java_raw_closure_loc): New. + * src/closures.c: New file. + * src/dlmalloc.c [FFI_MMAP_EXEC_WRIT] (struct malloc_segment): + Replace sflags with exec_offset. + [FFI_MMAP_EXEC_WRIT] (mmap_exec_offset, add_segment_exec_offset, + sub_segment_exec_offset): New macros. + (get_segment_flags, set_segment_flags, check_segment_merge): New + macros. + (is_mmapped_segment, is_extern_segment): Use get_segment_flags. + (add_segment, sys_alloc, create_mspace, create_mspace_with_base, + destroy_mspace): Use new macros. + (sys_alloc): Silence warning. + * Makefile.am (libffi_la_SOURCES): Add src/closures.c. + * Makefile.in: Rebuilt. + * src/prep_cif [FFI_CLOSURES] (ffi_prep_closure): Implement in + terms of ffi_prep_closure_loc. + * src/raw_api.c (ffi_prep_raw_closure_loc): Renamed and adjusted + from... + (ffi_prep_raw_closure): ... this. Re-implement in terms of the + renamed version. + * src/java_raw_api (ffi_prep_java_raw_closure_loc): Renamed and + adjusted from... + (ffi_prep_java_raw_closure): ... this. Re-implement in terms of + the renamed version. + * src/alpha/ffi.c (ffi_prep_closure_loc): Renamed from + (ffi_prep_closure): ... this. + * src/pa/ffi.c: Likewise. + * src/cris/ffi.c: Likewise. Adjust. + * src/frv/ffi.c: Likewise. + * src/ia64/ffi.c: Likewise. + * src/mips/ffi.c: Likewise. + * src/powerpc/ffi_darwin.c: Likewise. + * src/s390/ffi.c: Likewise. + * src/sh/ffi.c: Likewise. + * src/sh64/ffi.c: Likewise. + * src/sparc/ffi.c: Likewise. + * src/x86/ffi64.c: Likewise. + * src/x86/ffi.c: Likewise. + (FFI_INIT_TRAMPOLINE): Adjust. + (ffi_prep_raw_closure_loc): Renamed and adjusted from... + (ffi_prep_raw_closure): ... this. + * src/powerpc/ffi.c (ffi_prep_closure_loc): Renamed from + (ffi_prep_closure): ... this. + (flush_icache): Adjust. + +2007-03-07 Alexandre Oliva + + * src/dlmalloc.c: New file, imported version 2.8.3 of Doug + Lea's malloc. + +2007-03-01 Brooks Moses + + * Makefile.am: Add dummy install-pdf target. + * Makefile.in: Regenerate + +2007-02-13 Andreas Krebbel + + * src/s390/ffi.c (ffi_prep_args, ffi_prep_cif_machdep, + ffi_closure_helper_SYSV): Add long double handling. + +2007-02-02 Jakub Jelinek + + * src/powerpc/linux64.S (ffi_call_LINUX64): Move restore of r2 + immediately after bctrl instruction. + +2007-01-18 Alexandre Oliva + + * Makefile.am (all-recursive, install-recursive, + mostlyclean-recursive, clean-recursive, distclean-recursive, + maintainer-clean-recursive): Add missing targets. + * Makefile.in: Rebuilt. + +2006-12-14 Andreas Tobler + + * configure.ac: Add TARGET for x86_64-*-darwin*. + * Makefile.am (nodist_libffi_la_SOURCES): Add rules for 64-bit sources + for X86_DARWIN. + * src/x86/ffitarget.h: Set trampoline size for x86_64-*-darwin*. + * src/x86/darwin64.S: New file for x86_64-*-darwin* support. + * configure: Regenerate. + * Makefile.in: Regenerate. + * include/Makefile.in: Regenerate. + * testsuite/Makefile.in: Regenerate. + * testsuite/libffi.special/unwindtest_ffi_call.cc: New test case for + ffi_call only. + +2006-12-13 Andreas Tobler + + * aclocal.m4: Regenerate with aclocal -I .. as written in the + Makefile.am. + +2006-10-31 Geoffrey Keating + + * src/powerpc/ffi_darwin.c (darwin_adjust_aggregate_sizes): New. + (ffi_prep_cif_machdep): Call darwin_adjust_aggregate_sizes for + Darwin. + * testsuite/libffi.call/nested_struct4.c: Remove Darwin XFAIL. + * testsuite/libffi.call/nested_struct6.c: Remove Darwin XFAIL. + +2006-10-10 Paolo Bonzini + Sandro Tolaini + + * configure.ac [i*86-*-darwin*]: Set X86_DARWIN symbol and + conditional. + * configure: Regenerated. + * Makefile.am (nodist_libffi_la_SOURCES) [X86_DARWIN]: New case. + (EXTRA_DIST): Add src/x86/darwin.S. + * Makefile.in: Regenerated. + * include/Makefile.in: Regenerated. + * testsuite/Makefile.in: Regenerated. + + * src/x86/ffi.c (ffi_prep_cif_machdep) [X86_DARWIN]: Treat like + X86_WIN32, and additionally align stack to 16 bytes. + * src/x86/darwin.S: New, based on sysv.S. + * src/prep_cif.c (ffi_prep_cif) [X86_DARWIN]: Align > 8-byte structs. + +2006-09-12 David Daney + + PR libffi/23935 + * include/Makefile.am: Install both ffi.h and ffitarget.h in + $(libdir)/gcc/$(target_alias)/$(gcc_version)/include. + * aclocal.m4: Regenerated for automake 1.9.6. + * Makefile.in: Regenerated. + * include/Makefile.in: Regenerated. + * testsuite/Makefile.in: Regenerated. + +2006-08-17 Andreas Tobler + + * include/ffi_common.h (struct): Revert accidental commit. + +2006-08-15 Andreas Tobler + + * include/ffi_common.h: Remove lint directives. + * include/ffi.h.in: Likewise. + +2006-07-25 Torsten Schoenfeld + + * include/ffi.h.in (ffi_type_ulong, ffi_type_slong): Define correctly + for 32-bit architectures. + * testsuite/libffi.call/return_ul.c: New test case. + +2006-07-19 David Daney + + * testsuite/libffi.call/closure_fn6.c: Remove xfail for mips, + xfail remains for mips64. + +2006-05-23 Carlos O'Donell + + * Makefile.am: Add install-html target. Add install-html to .PHONY + * Makefile.in: Regenerate. + * aclocal.m4: Regenerate. + * include/Makefile.in: Regenerate. + * testsuite/Makefile.in: Regenerate. + +2006-05-18 John David Anglin + + * pa/ffi.c (ffi_prep_args_pa32): Load floating point arguments from + stack slot. + +2006-04-22 Andreas Tobler + + * README: Remove notice about 'Crazy Comments'. + * src/debug.c: Remove lint directives. Cleanup white spaces. + * src/java_raw_api.c: Likewise. + * src/prep_cif.c: Likewise. + * src/raw_api.c: Likewise. + * src/ffitest.c: Delete. No longer needed, all test cases migrated + to the testsuite. + * src/arm/ffi.c: Remove lint directives. + * src/m32r/ffi.c: Likewise. + * src/pa/ffi.c: Likewise. + * src/powerpc/ffi.c: Likewise. + * src/powerpc/ffi_darwin.c: Likewise. + * src/sh/ffi.c: Likewise. + * src/sh64/ffi.c: Likewise. + * src/x86/ffi.c: Likewise. + * testsuite/libffi.call/float2.c: Likewise. + * testsuite/libffi.call/promotion.c: Likewise. + * testsuite/libffi.call/struct1.c: Likewise. + +2006-04-13 Andreas Tobler + + * src/pa/hpux32.S: Correct unwind offset calculation for + ffi_closure_pa32. + * src/pa/linux.S: Likewise. + +2006-04-12 James E Wilson + + PR libgcj/26483 + * src/ia64/ffi.c (stf_spill, ldf_fill): Rewrite as macros. + (hfa_type_load): Call stf_spill. + (hfa_type_store): Call ldf_fill. + (ffi_call): Adjust calls to above routines. Add local temps for + macro result. + +2006-04-10 Matthias Klose + + * testsuite/lib/libffi-dg.exp (libffi-init): Recognize multilib + directory names containing underscores. + +2006-04-07 James E Wilson + + * testsuite/libffi.call/float4.c: New testcase. + +2006-04-05 John David Anglin + Andreas Tobler + + * Makefile.am: Add PA_HPUX port. + * Makefile.in: Regenerate. + * include/Makefile.in: Likewise. + * testsuite/Makefile.in: Likewise. + * configure.ac: Add PA_HPUX rules. + * configure: Regenerate. + * src/pa/ffitarget.h: Rename linux target to PA_LINUX. + Add PA_HPUX and PA64_HPUX. + Rename FFI_LINUX ABI to FFI_PA32 ABI. + (FFI_TRAMPOLINE_SIZE): Define for 32-bit HP-UX targets. + (FFI_TYPE_SMALL_STRUCT2): Define. + (FFI_TYPE_SMALL_STRUCT4): Likewise. + (FFI_TYPE_SMALL_STRUCT8): Likewise. + (FFI_TYPE_SMALL_STRUCT3): Redefine. + (FFI_TYPE_SMALL_STRUCT5): Likewise. + (FFI_TYPE_SMALL_STRUCT6): Likewise. + (FFI_TYPE_SMALL_STRUCT7): Likewise. + * src/pa/ffi.c (ROUND_DOWN): Delete. + (fldw, fstw, fldd, fstd): Use '__asm__'. + (ffi_struct_type): Add support for FFI_TYPE_SMALL_STRUCT2, + FFI_TYPE_SMALL_STRUCT4 and FFI_TYPE_SMALL_STRUCT8. + (ffi_prep_args_LINUX): Rename to ffi_prep_args_pa32. Update comment. + Simplify incrementing of stack slot variable. Change type of local + 'n' to unsigned int. + (ffi_size_stack_LINUX): Rename to ffi_size_stack_pa32. Handle long + double on PA_HPUX. + (ffi_prep_cif_machdep): Likewise. + (ffi_call): Likewise. + (ffi_closure_inner_LINUX): Rename to ffi_closure_inner_pa32. Change + return type to ffi_status. Simplify incrementing of stack slot + variable. Only copy floating point argument registers when PA_LINUX + is true. Reformat debug statement. + Add support for FFI_TYPE_SMALL_STRUCT2, FFI_TYPE_SMALL_STRUCT4 and + FFI_TYPE_SMALL_STRUCT8. + (ffi_closure_LINUX): Rename to ffi_closure_pa32. Add 'extern' to + declaration. + (ffi_prep_closure): Make linux trampoline conditional on PA_LINUX. + Add nops to cache flush. Add trampoline for PA_HPUX. + * src/pa/hpux32.S: New file. + * src/pa/linux.S (ffi_call_LINUX): Rename to ffi_call_pa32. Rename + ffi_prep_args_LINUX to ffi_prep_args_pa32. + Localize labels. Add support for 2, 4 and 8-byte small structs. Handle + unaligned destinations in 3, 5, 6 and 7-byte small structs. Order + argument type checks so that common argument types appear first. + (ffi_closure_LINUX): Rename to ffi_closure_pa32. Rename + ffi_closure_inner_LINUX to ffi_closure_inner_pa32. + +2006-03-24 Alan Modra + + * src/powerpc/ffitarget.h (enum ffi_abi): Add FFI_LINUX. Default + for 32-bit using IBM extended double format. Fix FFI_LAST_ABI. + * src/powerpc/ffi.c (ffi_prep_args_SYSV): Handle linux variant of + FFI_TYPE_LONGDOUBLE. + (ffi_prep_args64): Assert using IBM extended double. + (ffi_prep_cif_machdep): Don't munge FFI_TYPE_LONGDOUBLE type. + Handle FFI_LINUX FFI_TYPE_LONGDOUBLE return and args. + (ffi_call): Handle FFI_LINUX. + (ffi_closure_helper_SYSV): Non FFI_LINUX long double return needs + gpr3 return pointer as for struct return. Handle FFI_LINUX + FFI_TYPE_LONGDOUBLE return and args. Don't increment "nf" + unnecessarily. + * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Load both f1 and f2 + for FFI_TYPE_LONGDOUBLE. Move epilogue insns into case table. + Don't use r6 as pointer to results, instead use sp offset. Don't + make a special call to load lr with case table address, instead + use offset from previous call. + * src/powerpc/sysv.S (ffi_call_SYSV): Save long double return. + * src/powerpc/linux64.S (ffi_call_LINUX64): Simplify long double + return. + +2006-03-15 Kaz Kojima + + * src/sh64/ffi.c (ffi_prep_cif_machdep): Handle float arguments + passed with FP registers correctly. + (ffi_closure_helper_SYSV): Likewise. + * src/sh64/sysv.S: Likewise. + +2006-03-01 Andreas Tobler + + * testsuite/libffi.special/unwindtest.cc (closure_test_fn): Mark cif, + args and userdata unused. + (closure_test_fn1): Mark cif and userdata unused. + (main): Remove unused res. + +2006-02-28 Andreas Tobler + + * testsuite/libffi.call/call.exp: Adjust FSF address. Add test runs for + -O2, -O3, -Os and the warning flags -W -Wall. + * testsuite/libffi.special/special.exp: Likewise. + * testsuite/libffi.call/ffitest.h: Add an __UNUSED__ macro to mark + unused parameter unused for gcc or else do nothing. + * testsuite/libffi.special/ffitestcxx.h: Likewise. + * testsuite/libffi.call/cls_12byte.c (cls_struct_12byte_gn): Mark cif + and userdata unused. + * testsuite/libffi.call/cls_16byte.c (cls_struct_16byte_gn): Likewise. + * testsuite/libffi.call/cls_18byte.c (cls_struct_18byte_gn): Likewise. + * testsuite/libffi.call/cls_19byte.c (cls_struct_19byte_gn): Likewise. + * testsuite/libffi.call/cls_1_1byte.c (cls_struct_1_1byte_gn): Likewise. + * testsuite/libffi.call/cls_20byte.c (cls_struct_20byte_gn): Likewise. + * testsuite/libffi.call/cls_20byte1.c (cls_struct_20byte_gn): Likewise. + * testsuite/libffi.call/cls_24byte.c (cls_struct_24byte_gn): Likewise. + * testsuite/libffi.call/cls_2byte.c (cls_struct_2byte_gn): Likewise. + * testsuite/libffi.call/cls_3_1byte.c (cls_struct_3_1byte_gn): Likewise. + * testsuite/libffi.call/cls_3byte1.c (cls_struct_3byte_gn): Likewise. + * testsuite/libffi.call/cls_3byte2.c (cls_struct_3byte_gn1): Likewise. + * testsuite/libffi.call/cls_4_1byte.c (cls_struct_4_1byte_gn): Likewise. + * testsuite/libffi.call/cls_4byte.c (cls_struct_4byte_gn): Likewise. + * testsuite/libffi.call/cls_5_1_byte.c (cls_struct_5byte_gn): Likewise. + * testsuite/libffi.call/cls_5byte.c (cls_struct_5byte_gn): Likewise. + * testsuite/libffi.call/cls_64byte.c (cls_struct_64byte_gn): Likewise. + * testsuite/libffi.call/cls_6_1_byte.c (cls_struct_6byte_gn): Likewise. + * testsuite/libffi.call/cls_6byte.c (cls_struct_6byte_gn): Likewise. + * testsuite/libffi.call/cls_7_1_byte.c (cls_struct_7byte_gn): Likewise. + * testsuite/libffi.call/cls_7byte.c (cls_struct_7byte_gn): Likewise. + * testsuite/libffi.call/cls_8byte.c (cls_struct_8byte_gn): Likewise. + * testsuite/libffi.call/cls_9byte1.c (cls_struct_9byte_gn): Likewise. + * testsuite/libffi.call/cls_9byte2.c (cls_struct_9byte_gn): Likewise. + * testsuite/libffi.call/cls_align_double.c (cls_struct_align_gn): + Likewise. + * testsuite/libffi.call/cls_align_float.c (cls_struct_align_gn): + Likewise. + * testsuite/libffi.call/cls_align_longdouble.c (cls_struct_align_gn): + Likewise. + * testsuite/libffi.call/cls_align_pointer.c (cls_struct_align_fn): Cast + void* to avoid compiler warning. + (main): Likewise. + (cls_struct_align_gn): Mark cif and userdata unused. + * testsuite/libffi.call/cls_align_sint16.c (cls_struct_align_gn): + Likewise. + * testsuite/libffi.call/cls_align_sint32.c (cls_struct_align_gn): + Likewise. + * testsuite/libffi.call/cls_align_sint64.c (cls_struct_align_gn): + Likewise. + * testsuite/libffi.call/cls_align_uint16.c (cls_struct_align_gn): + Likewise. + * testsuite/libffi.call/cls_align_uint32.c (cls_struct_align_gn): + Likewise. + * testsuite/libffi.call/cls_double.c (cls_ret_double_fn): Likewise. + * testsuite/libffi.call/cls_float.c (cls_ret_float_fn): Likewise. + * testsuite/libffi.call/cls_multi_schar.c (test_func_gn): Mark cif and + data unused. + (main): Cast res_call to silence gcc. + * testsuite/libffi.call/cls_multi_sshort.c (test_func_gn): Mark cif and + data unused. + (main): Cast res_call to silence gcc. + * testsuite/libffi.call/cls_multi_sshortchar.c (test_func_gn): Mark cif + and data unused. + (main): Cast res_call to silence gcc. + * testsuite/libffi.call/cls_multi_uchar.c (test_func_gn): Mark cif and + data unused. + (main): Cast res_call to silence gcc. + * testsuite/libffi.call/cls_multi_ushort.c (test_func_gn): Mark cif and + data unused. + (main): Cast res_call to silence gcc. + * testsuite/libffi.call/cls_multi_ushortchar.c (test_func_gn): Mark cif + and data unused. + (main): Cast res_call to silence gcc. + * testsuite/libffi.call/cls_schar.c (cls_ret_schar_fn): Mark cif and + userdata unused. + (cls_ret_schar_fn): Cast printf parameter to silence gcc. + * testsuite/libffi.call/cls_sint.c (cls_ret_sint_fn): Mark cif and + userdata unused. + (cls_ret_sint_fn): Cast printf parameter to silence gcc. + * testsuite/libffi.call/cls_sshort.c (cls_ret_sshort_fn): Mark cif and + userdata unused. + (cls_ret_sshort_fn): Cast printf parameter to silence gcc. + * testsuite/libffi.call/cls_uchar.c (cls_ret_uchar_fn): Mark cif and + userdata unused. + (cls_ret_uchar_fn): Cast printf parameter to silence gcc. + * testsuite/libffi.call/cls_uint.c (cls_ret_uint_fn): Mark cif and + userdata unused. + (cls_ret_uint_fn): Cast printf parameter to silence gcc. + * testsuite/libffi.call/cls_ulonglong.c (cls_ret_ulonglong_fn): Mark cif + and userdata unused. + * testsuite/libffi.call/cls_ushort.c (cls_ret_ushort_fn): Mark cif and + userdata unused. + (cls_ret_ushort_fn): Cast printf parameter to silence gcc. + * testsuite/libffi.call/float.c (floating): Remove unused parameter e. + * testsuite/libffi.call/float1.c (main): Remove unused variable i. + Cleanup white spaces. + * testsuite/libffi.call/negint.c (checking): Remove unused variable i. + * testsuite/libffi.call/nested_struct.c (cls_struct_combined_gn): Mark + cif and userdata unused. + * testsuite/libffi.call/nested_struct1.c (cls_struct_combined_gn): + Likewise. + * testsuite/libffi.call/nested_struct10.c (B_gn): Likewise. + * testsuite/libffi.call/nested_struct2.c (B_fn): Adjust printf + formatters to silence gcc. + (B_gn): Mark cif and userdata unused. + * testsuite/libffi.call/nested_struct3.c (B_gn): Mark cif and userdata + unused. + * testsuite/libffi.call/nested_struct4.c: Mention related PR. + (B_gn): Mark cif and userdata unused. + * testsuite/libffi.call/nested_struct5.c (B_gn): Mark cif and userdata + unused. + * testsuite/libffi.call/nested_struct6.c: Mention related PR. + (B_gn): Mark cif and userdata unused. + * testsuite/libffi.call/nested_struct7.c (B_gn): Mark cif and userdata + unused. + * testsuite/libffi.call/nested_struct8.c (B_gn): Likewise. + * testsuite/libffi.call/nested_struct9.c (B_gn): Likewise. + * testsuite/libffi.call/problem1.c (stub): Likewise. + * testsuite/libffi.call/pyobjc-tc.c (main): Cast the result to silence + gcc. + * testsuite/libffi.call/return_fl2.c (return_fl): Add the note mentioned + in the last commit for this test case in the test case itself. + * testsuite/libffi.call/closure_fn0.c (closure_test_fn0): Mark cif as + unused. + * testsuite/libffi.call/closure_fn1.c (closure_test_fn1): Likewise. + * testsuite/libffi.call/closure_fn2.c (closure_test_fn2): Likewise. + * testsuite/libffi.call/closure_fn3.c (closure_test_fn3): Likewise. + * testsuite/libffi.call/closure_fn4.c (closure_test_fn0): Likewise. + * testsuite/libffi.call/closure_fn5.c (closure_test_fn5): Likewise. + * testsuite/libffi.call/closure_fn6.c (closure_test_fn0): Likewise. + +2006-02-22 Kaz Kojima + + * src/sh/sysv.S: Fix register numbers in the FDE for + ffi_closure_SYSV. + +2006-02-20 Andreas Tobler + + * testsuite/libffi.call/return_fl2.c (return_fl): Remove static + declaration to avoid a false negative on ix86. See PR323. + +2006-02-18 Kaz Kojima + + * src/sh/ffi.c (ffi_closure_helper_SYSV): Remove unused variable + and cast integer to void * if needed. Update the pointer to + the FP register saved area correctly. + +2006-02-17 Andreas Tobler + + * testsuite/libffi.call/nested_struct6.c: XFAIL this test until PR25630 + is fixed. + * testsuite/libffi.call/nested_struct4.c: Likewise. + +2006-02-16 Andreas Tobler + + * testsuite/libffi.call/return_dbl.c: New test case. + * testsuite/libffi.call/return_dbl1.c: Likewise. + * testsuite/libffi.call/return_dbl2.c: Likewise. + * testsuite/libffi.call/return_fl.c: Likewise. + * testsuite/libffi.call/return_fl1.c: Likewise. + * testsuite/libffi.call/return_fl2.c: Likewise. + * testsuite/libffi.call/return_fl3.c: Likewise. + * testsuite/libffi.call/closure_fn6.c: Likewise. + + * testsuite/libffi.call/nested_struct2.c: Remove ffi_type_mylong + definition. + * testsuite/libffi.call/ffitest.h: Add ffi_type_mylong definition + here to be used by other test cases too. + + * testsuite/libffi.call/nested_struct10.c: New test case. + * testsuite/libffi.call/nested_struct9.c: Likewise. + * testsuite/libffi.call/nested_struct8.c: Likewise. + * testsuite/libffi.call/nested_struct7.c: Likewise. + * testsuite/libffi.call/nested_struct6.c: Likewise. + * testsuite/libffi.call/nested_struct5.c: Likewise. + * testsuite/libffi.call/nested_struct4.c: Likewise. + +2006-01-21 Andreas Tobler + + * configure.ac: Enable libffi for sparc64-*-freebsd*. + * configure: Rebuilt. + +2006-01-18 Jakub Jelinek + + * src/powerpc/sysv.S (smst_two_register): Don't call __ashldi3, + instead do the shifting inline. + * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Don't compute %r5 + shift count unconditionally. Simplify load sequences for 1, 2, 3, 4 + and 8 byte structs, for the remaining struct sizes don't call + __lshrdi3, instead do the shifting inline. + +2005-12-07 Thiemo Seufer + + * src/mips/ffitarget.h: Remove obsolete sgidefs.h include. Add + missing parentheses. + * src/mips/o32.S (ffi_call_O32): Code formatting. Define + and use A3_OFF, FP_OFF, RA_OFF. Micro-optimizations. + (ffi_closure_O32): Likewise, but with newly defined A3_OFF2, + A2_OFF2, A1_OFF2, A0_OFF2, RA_OFF2, FP_OFF2, S0_OFF2, GP_OFF2, + V1_OFF2, V0_OFF2, FA_1_1_OFF2, FA_1_0_OFF2, FA_0_1_OFF2, + FA_0_0_OFF2. + * src/mips/ffi.c (ffi_prep_args): Code formatting. Fix + endianness bugs. + (ffi_prep_closure): Improve trampoline instruction scheduling. + (ffi_closure_mips_inner_O32): Fix endianness bugs. + +2005-12-03 Alan Modra + + * src/powerpc/ffi.c: Formatting. + (ffi_prep_args_SYSV): Avoid possible aliasing problems by using unions. + (ffi_prep_args64): Likewise. + +2005-09-30 Geoffrey Keating + + * testsuite/lib/libffi-dg.exp (libffi_target_compile): For + darwin, use -shared-libgcc not -lgcc_s, and explain why. + +2005-09-26 Tom Tromey + + * testsuite/libffi.call/float1.c (value_type): New typedef. + (CANARY): New define. + (main): Check for result buffer overflow. + * src/powerpc/linux64.S: Handle linux64 long double returns. + * src/powerpc/ffi.c (FLAG_RETURNS_128BITS): New constant. + (ffi_prep_cif_machdep): Handle linux64 long double returns. + +2005-08-25 Alan Modra + + PR target/23404 + * src/powerpc/ffi.c (ffi_prep_args_SYSV): Correct placement of stack + homed fp args. + (ffi_status ffi_prep_cif_machdep): Correct stack sizing for same. + +2005-08-11 Jakub Jelinek + + * configure.ac (HAVE_HIDDEN_VISIBILITY_ATTRIBUTE): New test. + (AH_BOTTOM): Add FFI_HIDDEN definition. + * configure: Rebuilt. + * fficonfig.h.in: Rebuilt. + * src/powerpc/ffi.c (hidden): Remove. + (ffi_closure_LINUX64, ffi_prep_args64, ffi_call_LINUX64, + ffi_closure_helper_LINUX64): Use FFI_HIDDEN instead of hidden. + * src/powerpc/linux64_closure.S (ffi_closure_LINUX64, + .ffi_closure_LINUX64): Use FFI_HIDDEN instead of .hidden. + * src/x86/ffi.c (ffi_closure_SYSV, ffi_closure_raw_SYSV): Remove, + add FFI_HIDDEN to its prototype. + (ffi_closure_SYSV_inner): New. + * src/x86/sysv.S (ffi_closure_SYSV, ffi_closure_raw_SYSV): New. + * src/x86/win32.S (ffi_closure_SYSV, ffi_closure_raw_SYSV): New. + +2005-08-10 Alfred M. Szmidt + + PR libffi/21819: + * configure: Rebuilt. + * configure.ac: Handle i*86-*-gnu*. + +2005-08-09 Jakub Jelinek + + * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Use + DW_CFA_offset_extended_sf rather than + DW_CFA_GNU_negative_offset_extended. + * src/powerpc/sysv.S (ffi_call_SYSV): Likewise. + +2005-07-22 SUGIOKA Toshinobu + + * src/sh/sysv.S (ffi_call_SYSV): Stop argument popping correctly + on sh3. + (ffi_closure_SYSV): Change the stack layout for sh3 struct argument. + * src/sh/ffi.c (ffi_prep_args): Fix sh3 argument copy, when it is + partially on register. + (ffi_closure_helper_SYSV): Likewise. + (ffi_prep_cif_machdep): Don't set too many cif->flags. + +2005-07-20 Kaz Kojima + + * src/sh/ffi.c (ffi_call): Handle small structures correctly. + Remove empty line. + * src/sh64/ffi.c (simple_type): Remove. + (return_type): Handle small structures correctly. + (ffi_prep_args): Likewise. + (ffi_call): Likewise. + (ffi_closure_helper_SYSV): Likewise. + * src/sh64/sysv.S (ffi_call_SYSV): Handle 1, 2 and 4-byte return. + Emit position independent code if PIC and remove wrong datalabel + prefixes from EH data. + +2005-07-19 Andreas Tobler + + * Makefile.am (nodist_libffi_la_SOURCES): Add POWERPC_FREEBSD. + * Makefile.in: Regenerate. + * include/Makefile.in: Likewise. + * testsuite/Makefile.in: Likewise. + * configure.ac: Add POWERPC_FREEBSD rules. + * configure: Regenerate. + * src/powerpc/ffitarget.h: Add POWERPC_FREEBSD rules. + (FFI_SYSV_TYPE_SMALL_STRUCT): Define. + * src/powerpc/ffi.c: Add flags to handle small structure returns + in ffi_call_SYSV. + (ffi_prep_cif_machdep): Handle small structures for SYSV 4 ABI. + Aka FFI_SYSV. + (ffi_closure_helper_SYSV): Likewise. + * src/powerpc/ppc_closure.S: Add return types for small structures. + * src/powerpc/sysv.S: Add bits to handle small structures for + final SYSV 4 ABI. + +2005-07-10 Andreas Tobler + + * testsuite/libffi.call/cls_5_1_byte.c: New test file. + * testsuite/libffi.call/cls_6_1_byte.c: Likewise. + * testsuite/libffi.call/cls_7_1_byte.c: Likewise. + +2005-07-05 Randolph Chung + + * src/pa/ffi.c (ffi_struct_type): Rename FFI_TYPE_SMALL_STRUCT1 + as FFI_TYPE_SMALL_STRUCT3. Break out handling for 5-7 byte + structures. Kill compilation warnings. + (ffi_closure_inner_LINUX): Print return values as hex in debug + message. Rename FFI_TYPE_SMALL_STRUCT1 as FFI_TYPE_SMALL_STRUCT3. + Properly handle 5-7 byte structure returns. + * src/pa/ffitarget.h (FFI_TYPE_SMALL_STRUCT1) + (FFI_TYPE_SMALL_STRUCT2): Remove. + (FFI_TYPE_SMALL_STRUCT3, FFI_TYPE_SMALL_STRUCT5) + (FFI_TYPE_SMALL_STRUCT6, FFI_TYPE_SMALL_STRUCT7): Define. + * src/pa/linux.S: Mark source file as using PA1.1 assembly. + (checksmst1, checksmst2): Remove. + (checksmst3): Optimize handling of 3-byte struct returns. + (checksmst567): Properly handle 5-7 byte struct returns. + +2005-06-15 Rainer Orth + + PR libgcj/21943 + * src/mips/n32.S: Enforce PIC code. + * src/mips/o32.S: Likewise. + +2005-06-15 Rainer Orth + + * configure.ac: Treat i*86-*-solaris2.10 and up as X86_64. + * configure: Regenerate. + +2005-06-01 Alan Modra + + * src/powerpc/ppc_closure.S (ffi_closure_SYSV): Don't use JUMPTARGET + to call ffi_closure_helper_SYSV. Append @local instead. + * src/powerpc/sysv.S (ffi_call_SYSV): Likewise for ffi_prep_args_SYSV. + +2005-05-17 Kelley Cook + + * configure.ac: Use AC_C_BIGENDIAN instead of AC_C_BIGENDIAN_CROSS. + Use AC_CHECK_SIZEOF instead of AC_COMPILE_CHECK_SIZEOF. + * Makefile.am (ACLOCAL_AMFLAGS): Remove -I ../config. + * aclocal.m4, configure, fficonfig.h.in, Makefile.in, + include/Makefile.in, testsuite/Makefile.in: Regenerate. + +2005-05-09 Mike Stump + + * configure: Regenerate. + +2005-05-08 Richard Henderson + + PR libffi/21285 + * src/alpha/osf.S: Update unwind into to match code. + +2005-05-04 Andreas Degert + Richard Henderson + + * src/x86/ffi64.c (ffi_prep_cif_machdep): Save sse-used flag in + bit 11 of flags. + (ffi_call): Mask return type field. Pass ssecount to ffi_call_unix64. + (ffi_prep_closure): Set carry bit if sse-used flag set. + * src/x86/unix64.S (ffi_call_unix64): Add ssecount argument. + Only load sse registers if ssecount non-zero. + (ffi_closure_unix64): Only save sse registers if carry set on entry. + +2005-04-29 Ralf Corsepius + + * configure.ac: Add i*86-*-rtems*, sparc*-*-rtems*, + powerpc-*rtems*, arm*-*-rtems*, sh-*-rtems*. + * configure: Regenerate. + +2005-04-20 Hans-Peter Nilsson + + * testsuite/lib/libffi-dg.exp (libffi-dg-test-1): In regsub use, + have Tcl8.3-compatible intermediate variable. + +2005-04-18 Simon Posnjak + Hans-Peter Nilsson + + * Makefile.am: Add CRIS support. + * configure.ac: Likewise. + * Makefile.in, configure, testsuite/Makefile.in, + include/Makefile.in: Regenerate. + * src/cris: New directory. + * src/cris/ffi.c, src/cris/sysv.S, src/cris/ffitarget.h: New files. + * src/prep_cif.c (ffi_prep_cif): Wrap in #ifndef __CRIS__. + + * testsuite/lib/libffi-dg.exp (libffi-dg-test-1): Replace \n with + \r?\n in output tests. + +2005-04-12 Mike Stump + + * configure: Regenerate. + +2005-03-30 Hans Boehm + + * src/ia64/ffitarget.h (ffi_arg): Use long long instead of DI. + +2005-03-30 Steve Ellcey + + * src/ia64/ffitarget.h (ffi_arg) ADD DI attribute. + (ffi_sarg) Ditto. + * src/ia64/unix.S (ffi_closure_unix): Extend gp + to 64 bits in ILP32 mode. + Load 64 bits even for short data. + +2005-03-23 Mike Stump + + * src/powerpc/darwin.S: Update for -m64 multilib. + * src/powerpc/darwin_closure.S: Likewise. + +2005-03-21 Zack Weinberg + + * configure.ac: Do not invoke TL_AC_GCC_VERSION. + Do not set tool_include_dir. + * aclocal.m4, configure, Makefile.in, testsuite/Makefile.in: + Regenerate. + * include/Makefile.am: Set gcc_version and toollibffidir. + * include/Makefile.in: Regenerate. + +2005-02-22 Andrew Haley + + * src/powerpc/ffi.c (ffi_prep_cif_machdep): Bump alignment to + odd-numbered register pairs for 64-bit integer types. + +2005-02-23 Andreas Tobler + + PR libffi/20104 + * testsuite/libffi.call/return_ll1.c: New test case. + +2005-02-11 Janis Johnson + + * testsuite/libffi.call/cls_align_longdouble.c: Remove dg-options. + * testsuite/libffi.call/float.c: Ditto. + * testsuite/libffi.call/float2.c: Ditto. + * testsuite/libffi.call/float3.c: Ditto. + +2005-02-08 Andreas Tobler + + * src/frv/ffitarget.h: Remove PPC stuff which does not belong to frv. + +2005-01-12 Eric Botcazou + + * testsuite/libffi.special/special.exp (cxx_options): Add + -shared-libgcc. + +2004-12-31 Richard Henderson + + * src/types.c (FFI_AGGREGATE_TYPEDEF): Remove. + (FFI_TYPEDEF): Rename from FFI_INTEGRAL_TYPEDEF. Replace size and + offset parameters with a type parameter; deduce size and structure + alignment. Update all users. + +2004-12-31 Richard Henderson + + * src/types.c (FFI_TYPE_POINTER): Define with sizeof. + (FFI_TYPE_LONGDOUBLE): Fix for ia64. + * src/ia64/ffitarget.h (struct ffi_ia64_trampoline_struct): Move + into ffi_prep_closure. + * src/ia64/ia64_flags.h, src/ia64/ffi.c, src/ia64/unix.S: Rewrite + from scratch. + +2004-12-27 Richard Henderson + + * src/x86/unix64.S: Fix typo in unwind info. + +2004-12-25 Richard Henderson + + * src/x86/ffi64.c (struct register_args): Rename from stackLayout. + (enum x86_64_reg_class): Add X86_64_COMPLEX_X87_CLASS. + (merge_classes): Check for it. + (SSE_CLASS_P): New. + (classify_argument): Pass byte_offset by value; perform all updates + inside struct case. + (examine_argument): Add classes argument; handle + X86_64_COMPLEX_X87_CLASS. + (ffi_prep_args): Merge into ... + (ffi_call): ... here. Share stack frame with ffi_call_unix64. + (ffi_prep_cif_machdep): Setup cif->flags for proper structure return. + (ffi_fill_return_value): Remove. + (ffi_prep_closure): Remove dead assert. + (ffi_closure_unix64_inner): Rename from ffi_closure_UNIX64_inner. + Rewrite to use struct register_args instead of va_list. Create + flags for handling structure returns. + * src/x86/unix64.S: Remove dead strings. + (ffi_call_unix64): Rename from ffi_call_UNIX64. Rewrite to share + stack frame with ffi_call. Handle structure returns properly. + (float2sse, floatfloat2sse, double2sse): Remove. + (sse2float, sse2double, sse2floatfloat): Remove. + (ffi_closure_unix64): Rename from ffi_closure_UNIX64. Rewrite + to handle structure returns properly. + +2004-12-08 David Edelsohn + + * Makefile.am (AM_MAKEFLAGS): Remove duplicate LIBCFLAGS and + PICFLAG. + * Makefile.in: Regenerated. + +2004-12-02 Richard Sandiford + + * configure.ac: Use TL_AC_GCC_VERSION to set gcc_version. + * configure, aclocal.m4, Makefile.in: Regenerate. + * include/Makefile.in, testsuite/Makefile.in: Regenerate. + +2004-11-29 Kelley Cook + + * configure: Regenerate for libtool change. + +2004-11-25 Kelley Cook + + * configure: Regenerate for libtool reversion. + +2004-11-24 Kelley Cook + + * configure: Regenerate for libtool change. + +2004-11-23 John David Anglin + + * testsuite/lib/libffi-dg.exp: Use new procs in target-libpath.exp. + +2004-11-23 Richard Sandiford + + * src/mips/o32.S (ffi_call_O32, ffi_closure_O32): Use jalr instead + of jal. Use an absolute encoding for the frame information. + +2004-11-23 Kelley Cook + + * Makefile.am: Remove no-dependencies. Add ACLOCAL_AMFLAGS. + * acinclude.m4: Delete logic for sincludes. + * aclocal.m4, Makefile.in, configure: Regenerate. + * include/Makefile: Likewise. + * testsuite/Makefile: Likewise. + +2004-11-22 Eric Botcazou + + * src/sparc/ffi.c (ffi_prep_closure): Align doubles and 64-bit integers + on a 8-byte boundary. + * src/sparc/v8.S (ffi_closure_v8): Reserve frame space for arguments. + +2004-10-27 Richard Earnshaw + + * src/arm/ffi.c (ffi_prep_cif_machdep): Handle functions that return + long long values. Round stack allocation to a multiple of 8 bytes + for ATPCS compatibility. + * src/arm/sysv.S (ffi_call_SYSV): Rework to avoid use of APCS register + names. Handle returning long long types. Add Thumb and interworking + support. Improve soft-float code. + +2004-10-27 Richard Earnshaw + + * testsuite/lib/libffi-db.exp (load_gcc_lib): New function. + (libffi_exit): New function. + (libffi_init): Build the testglue wrapper if needed. + +2004-10-25 Eric Botcazou + + PR other/18138 + * testsuite/lib/libffi-dg.exp: Accept more than one multilib libgcc. + +2004-10-25 Kazuhiro Inaoka + + * src/m32r/libffitarget.h (FFI_CLOSURES): Set to 0. + +2004-10-20 Kaz Kojima + + * src/sh/sysv.S (ffi_call_SYSV): Don't align for double data. + * testsuite/libffi.call/float3.c: New test case. + +2004-10-18 Kaz Kojima + + * src/sh/ffi.c (ffi_prep_closure): Set T bit in trampoline for + the function returning a structure pointed with R2. + * src/sh/sysv.S (ffi_closure_SYSV): Use R2 as the pointer to + the structure return value if T bit set. Emit position + independent code and EH data if PIC. + +2004-10-13 Kazuhiro Inaoka + + * Makefile.am: Add m32r support. + * configure.ac: Likewise. + * Makefile.in: Regenerate. + * confiugre: Regenerate. + * src/types.c: Add m32r port to FFI_INTERNAL_TYPEDEF + (uint64, sint64, double, longdouble) + * src/m32r: New directory. + * src/m32r/ffi.c: New file. + * src/m32r/sysv.S: Likewise. + * src/m32r/ffitarget.h: Likewise. + +2004-10-02 Kaz Kojima + + * testsuite/libffi.call/negint.c: New test case. + +2004-09-14 H.J. Lu + + PR libgcj/17465 + * testsuite/lib/libffi-dg.exp: Don't use global ld_library_path. + Set up LD_LIBRARY_PATH, SHLIB_PATH, LD_LIBRARYN32_PATH, + LD_LIBRARY64_PATH, LD_LIBRARY_PATH_32, LD_LIBRARY_PATH_64 and + DYLD_LIBRARY_PATH. + +2004-09-05 Andreas Tobler + + * testsuite/libffi.call/many_win32.c: Remove whitespaces. + * testsuite/libffi.call/promotion.c: Likewise. + * testsuite/libffi.call/return_ll.c: Remove unused var. Cleanup + whitespaces. + * testsuite/libffi.call/return_sc.c: Likewise. + * testsuite/libffi.call/return_uc.c: Likewise. + +2004-09-05 Andreas Tobler + + * src/powerpc/darwin.S: Fix comments and identation. + * src/powerpc/darwin_closure.S: Likewise. + +2004-09-02 Andreas Tobler + + * src/powerpc/ffi_darwin.c: Add flag for longdouble return values. + (ffi_prep_args): Handle longdouble arguments. + (ffi_prep_cif_machdep): Set flags for longdouble. Calculate space for + longdouble. + (ffi_closure_helper_DARWIN): Add closure handling for longdouble. + * src/powerpc/darwin.S (_ffi_call_DARWIN): Add handling of longdouble + values. + * src/powerpc/darwin_closure.S (_ffi_closure_ASM): Likewise. + * src/types.c: Defined longdouble size and alignment for darwin. + +2004-09-02 Andreas Tobler + + * src/powerpc/aix.S: Remove whitespaces. + * src/powerpc/aix_closure.S: Likewise. + * src/powerpc/asm.h: Likewise. + * src/powerpc/ffi.c: Likewise. + * src/powerpc/ffitarget.h: Likewise. + * src/powerpc/linux64.S: Likewise. + * src/powerpc/linux64_closure.S: Likewise. + * src/powerpc/ppc_closure.S: Likewise. + * src/powerpc/sysv.S: Likewise. + +2004-08-30 Anthony Green + + * Makefile.am: Add frv support. + * Makefile.in, testsuite/Makefile.in: Rebuilt. + * configure.ac: Read configure.host. + * configure.in: Read configure.host. + * configure.host: New file. frv-elf needs libgloss. + * include/ffi.h.in: Force ffi_closure to have a nice big (8) + alignment. This is needed to frv and shouldn't harm the others. + * include/ffi_common.h (ALIGN_DOWN): New macro. + * src/frv/ffi.c, src/frv/ffitarget.h, src/frv/eabi.S: New files. + +2004-08-24 David Daney + + * testsuite/libffi.call/closure_fn0.c: Xfail mips64* instead of mips*. + * testsuite/libffi.call/closure_fn1.c: Likewise. + * testsuite/libffi.call/closure_fn2.c Likewise. + * testsuite/libffi.call/closure_fn3.c: Likewise. + * testsuite/libffi.call/closure_fn4.c: Likewise. + * testsuite/libffi.call/closure_fn5.c: Likewise. + * testsuite/libffi.call/cls_18byte.c: Likewise. + * testsuite/libffi.call/cls_19byte.c: Likewise. + * testsuite/libffi.call/cls_1_1byte.c: Likewise. + * testsuite/libffi.call/cls_20byte.c: Likewise. + * testsuite/libffi.call/cls_20byte1.c: Likewise. + * testsuite/libffi.call/cls_24byte.c: Likewise. + * testsuite/libffi.call/cls_2byte.c: Likewise. + * testsuite/libffi.call/cls_3_1byte.c: Likewise. + * testsuite/libffi.call/cls_3byte1.c: Likewise. + * testsuite/libffi.call/cls_3byte2.c: Likewise. + * testsuite/libffi.call/cls_4_1byte.c: Likewise. + * testsuite/libffi.call/cls_4byte.c: Likewise. + * testsuite/libffi.call/cls_64byte.c: Likewise. + * testsuite/libffi.call/cls_6byte.c: Likewise. + * testsuite/libffi.call/cls_7byte.c: Likewise. + * testsuite/libffi.call/cls_8byte.c: Likewise. + * testsuite/libffi.call/cls_9byte1.c: Likewise. + * testsuite/libffi.call/cls_9byte2.c: Likewise. + * testsuite/libffi.call/cls_align_double.c: Likewise. + * testsuite/libffi.call/cls_align_float.c: Likewise. + * testsuite/libffi.call/cls_align_longdouble.c: Likewise. + * testsuite/libffi.call/cls_align_pointer.c: Likewise. + * testsuite/libffi.call/cls_align_sint16.c: Likewise. + * testsuite/libffi.call/cls_align_sint32.c: Likewise. + * testsuite/libffi.call/cls_align_sint64.c: Likewise. + * testsuite/libffi.call/cls_align_uint16.c: Likewise. + * testsuite/libffi.call/cls_align_uint32.c: Likewise. + * testsuite/libffi.call/cls_align_uint64.c: Likewise. + * testsuite/libffi.call/cls_double.c: Likewise. + * testsuite/libffi.call/cls_float.c: Likewise. + * testsuite/libffi.call/cls_multi_schar.c: Likewise. + * testsuite/libffi.call/cls_multi_sshort.c: Likewise. + * testsuite/libffi.call/cls_multi_sshortchar.c: Likewise. + * testsuite/libffi.call/cls_multi_uchar.c: Likewise. + * testsuite/libffi.call/cls_multi_ushort.c: Likewise. + * testsuite/libffi.call/cls_multi_ushortchar.c: Likewise. + * testsuite/libffi.call/cls_schar.c: Likewise. + * testsuite/libffi.call/cls_sint.c: Likewise. + * testsuite/libffi.call/cls_sshort.c: Likewise. + * testsuite/libffi.call/cls_uchar.c: Likewise. + * testsuite/libffi.call/cls_uint.c: Likewise. + * testsuite/libffi.call/cls_ulonglong.c: Likewise. + * testsuite/libffi.call/cls_ushort.c: Likewise. + * testsuite/libffi.call/nested_struct.c: Likewise. + * testsuite/libffi.call/nested_struct1.c: Likewise. + * testsuite/libffi.call/nested_struct2.c: Likewise. + * testsuite/libffi.call/nested_struct3.c: Likewise. + * testsuite/libffi.call/problem1.c: Likewise. + * testsuite/libffi.special/unwindtest.cc: Likewise. + * testsuite/libffi.call/cls_12byte.c: Likewise and set return value + to zero. + * testsuite/libffi.call/cls_16byte.c: Likewise. + * testsuite/libffi.call/cls_5byte.c: Likewise. + +2004-08-23 David Daney + + PR libgcj/13141 + * src/mips/ffitarget.h (FFI_O32_SOFT_FLOAT): New ABI. + * src/mips/ffi.c (ffi_prep_args): Fix alignment calculation. + (ffi_prep_cif_machdep): Handle FFI_O32_SOFT_FLOAT floating point + parameters and return types. + (ffi_call): Handle FFI_O32_SOFT_FLOAT ABI. + (ffi_prep_closure): Ditto. + (ffi_closure_mips_inner_O32): Handle FFI_O32_SOFT_FLOAT ABI, fix + alignment calculations. + * src/mips/o32.S (ffi_closure_O32): Don't use floating point + instructions if FFI_O32_SOFT_FLOAT, make stack frame ABI compliant. + +2004-08-14 Casey Marshall + + * src/mips/ffi.c (ffi_pref_cif_machdep): set `cif->flags' to + contain `FFI_TYPE_UINT64' as return type for any 64-bit + integer (O32 ABI only). + (ffi_prep_closure): new function. + (ffi_closure_mips_inner_O32): new function. + * src/mips/ffitarget.h: Define `FFI_CLOSURES' and + `FFI_TRAMPOLINE_SIZE' appropriately if the ABI is o32. + * src/mips/o32.S (ffi_call_O32): add labels for .eh_frame. Return + 64 bit integers correctly. + (ffi_closure_O32): new function. + Added DWARF-2 unwind info for both functions. + +2004-08-10 Andrew Haley + + * src/x86/ffi64.c (ffi_prep_args ): 8-align all stack arguments. + +2004-08-01 Robert Millan + + * configure.ac: Detect knetbsd-gnu and kfreebsd-gnu. + * configure: Regenerate. + +2004-07-30 Maciej W. Rozycki + + * acinclude.m4 (AC_FUNC_MMAP_BLACKLIST): Check for + and mmap() explicitly instead of relying on preset autoconf cache + variables. + * aclocal.m4: Regenerate. + * configure: Regenerate. + +2004-07-11 Ulrich Weigand + + * src/s390/ffi.c (ffi_prep_args): Fix C aliasing violation. + (ffi_check_float_struct): Remove unused prototype. + +2004-06-30 Geoffrey Keating + + * src/powerpc/ffi_darwin.c (flush_icache): ';' is a comment + character on Darwin, use '\n\t' instead. + +2004-06-26 Matthias Klose + + * libtool-version: Fix typo in revision/age. + +2004-06-17 Matthias Klose + + * libtool-version: New. + * Makefile.am (libffi_la_LDFLAGS): Use -version-info for soname. + * Makefile.in: Regenerate. + +2004-06-15 Paolo Bonzini + + * Makefile.am: Remove useless multilib rules. + * Makefile.in: Regenerate. + * aclocal.m4: Regenerate with automake 1.8.5. + * configure.ac: Remove useless multilib configury. + * configure: Regenerate. + +2004-06-15 Paolo Bonzini + + * .cvsignore: New file. + +2004-06-10 Jakub Jelinek + + * src/ia64/unix.S (ffi_call_unix): Insert group barrier break + fp_done. + (ffi_closure_UNIX): Fix f14/f15 adjustment if FLOAT_SZ is ever + changed from 8. + +2004-06-06 Sean McNeil + + * configure.ac: Add x86_64-*-freebsd* support. + * configure: Regenerate. + +2004-04-26 Joe Buck + + Bug 15093 + * configure.ac: Test for existence of mmap and sys/mman.h before + checking blacklist. Fix suggested by Jim Wilson. + * configure: Regenerate. + +2004-04-26 Matt Austern + + * src/powerpc/darwin.S: Go through a non-lazy pointer for initial + FDE location. + * src/powerpc/darwin_closure.S: Likewise. + +2004-04-24 Andreas Tobler + + * testsuite/libffi.call/cls_multi_schar.c (main): Fix initialization + error. Reported by Thomas Heller . + * testsuite/libffi.call/cls_multi_sshort.c (main): Likewise. + * testsuite/libffi.call/cls_multi_ushort.c (main): Likewise. + +2004-03-20 Matthias Klose + + * src/pa/linux.S: Fix typo. + +2004-03-19 Matthias Klose + + * Makefile.am: Update. + * Makefile.in: Regenerate. + * src/pa/ffi.h.in: Remove. + * src/pa/ffitarget.h: New file. + +2004-02-10 Randolph Chung + + * Makefile.am: Add PA support. + * Makefile.in: Regenerate. + * include/Makefile.in: Regenerate. + * configure.ac: Add PA target. + * configure: Regenerate. + * src/pa/ffi.c: New file. + * src/pa/ffi.h.in: Add PA support. + * src/pa/linux.S: New file. + * prep_cif.c: Add PA support. + +2004-03-16 Hosaka Yuji + + * src/types.c: Fix alignment size of X86_WIN32 case int64 and + double. + * src/x86/ffi.c (ffi_prep_args): Replace ecif->cif->rtype->type + with ecif->cif->flags. + (ffi_call, ffi_prep_incoming_args_SYSV): Replace cif->rtype->type + with cif->flags. + (ffi_prep_cif_machdep): Add X86_WIN32 struct case. + (ffi_closure_SYSV): Add 1 or 2-bytes struct case for X86_WIN32. + * src/x86/win32.S (retstruct1b, retstruct2b, sc_retstruct1b, + sc_retstruct2b): Add for 1 or 2-bytes struct case. + +2004-03-15 Kelley Cook + + * configure.in: Rename file to ... + * configure.ac: ... this. + * fficonfig.h.in: Regenerate. + * Makefile.in: Regenerate. + * include/Makefile.in: Regenerate. + * testsuite/Makefile.in: Regenerate. + +2004-03-12 Matt Austern + + * src/powerpc/darwin.S: Fix EH information so it corresponds to + changes in EH format resulting from addition of linkonce support. + * src/powerpc/darwin_closure.S: Likewise. + +2004-03-11 Andreas Tobler + Paolo Bonzini + + * Makefile.am (AUTOMAKE_OPTIONS): Set them. + Remove VPATH. Remove rules for object files. Remove multilib support. + (AM_CCASFLAGS): Add. + * configure.in (AC_CONFIG_HEADERS): Relace AM_CONFIG_HEADER. + (AC_PREREQ): Bump version to 2.59. + (AC_INIT): Fill with version info and bug address. + (ORIGINAL_LD_FOR_MULTILIBS): Remove. + (AM_ENABLE_MULTILIB): Use this instead of AC_ARG_ENABLE. + De-precious CC so that the right flags are passed down to multilibs. + (AC_MSG_ERROR): Replace obsolete macro AC_ERROR. + (AC_CONFIG_FILES): Replace obsolete macro AC_LINK_FILES. + (AC_OUTPUT): Reorganize the output with AC_CONFIG_COMMANDS. + * configure: Rebuilt. + * aclocal.m4: Likewise. + * Makefile.in, include/Makefile.in, testsuite/Makefile.in: Likewise. + * fficonfig.h.in: Likewise. + +2004-03-11 Andreas Schwab + + * src/ia64/ffi.c (ffi_prep_incoming_args_UNIX): Get floating point + arguments from fp registers only for the first 8 parameter slots. + Don't convert a float parameter when passed in memory. + +2004-03-09 Hans-Peter Nilsson + + * configure: Regenerate for config/accross.m4 correction. + +2004-02-25 Matt Kraai + + * src/powerpc/ffi.c (ffi_prep_args_SYSV): Change + ecif->cif->bytes to bytes. + (ffi_prep_cif_machdep): Add braces around nested if statement. + +2004-02-09 Alan Modra + + * src/types.c (pointer): POWERPC64 has 8 byte pointers. + + * src/powerpc/ffi.c (ffi_prep_args64): Correct long double handling. + (ffi_closure_helper_LINUX64): Fix typo. + * testsuite/libffi.call/cls_align_longdouble.c: Pass -mlong-double-128 + for powerpc64-*-*. + * testsuite/libffi.call/float.c: Likewise. + * testsuite/libffi.call/float2.c: Likewise. + +2004-02-08 Alan Modra + + * src/powerpc/ffi.c (ffi_prep_cif_machdep ): Correct + long double function return and long double arg handling. + (ffi_closure_helper_LINUX64): Formatting. Delete unused "ng" var. + Use "end_pfr" instead of "nf". Correct long double handling. + Localise "temp". + * src/powerpc/linux64.S (ffi_call_LINUX64): Save f2 long double + return value. + * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Allocate + space for long double return value. Adjust stack frame and offsets. + Load f2 long double return. + +2004-02-07 Alan Modra + + * src/types.c: Use 16 byte long double for POWERPC64. + +2004-01-25 Eric Botcazou + + * src/sparc/ffi.c (ffi_prep_args_v9): Shift the parameter array + when the structure return address is passed in %o0. + (ffi_V9_return_struct): Rename into ffi_v9_layout_struct. + (ffi_v9_layout_struct): Align the field following a nested structure + on a word boundary. Use memmove instead of memcpy. + (ffi_call): Update call to ffi_V9_return_struct. + (ffi_prep_closure): Define 'ctx' only for V8. + (ffi_closure_sparc_inner): Clone into ffi_closure_sparc_inner_v8 + and ffi_closure_sparc_inner_v9. + (ffi_closure_sparc_inner_v8): Return long doubles by reference. + Always skip the structure return address. For structures and long + doubles, copy the argument directly. + (ffi_closure_sparc_inner_v9): Skip the structure return address only + if required. Shift the maximum floating-point slot accordingly. For + big structures, copy the argument directly; otherwise, left-justify the + argument and call ffi_v9_layout_struct to lay out the structure on + the stack. + * src/sparc/v8.S: Undef STACKFRAME before defining it. + (ffi_closure_v8): Pass the structure return address. Update call to + ffi_closure_sparc_inner_v8. Short-circuit FFI_TYPE_INT handling. + Skip the 'unimp' insn when returning long doubles and structures. + * src/sparc/v9.S: Undef STACKFRAME before defining it. + (ffi_closure_v9): Increase the frame size by 2 words. Short-circuit + FFI_TYPE_INT handling. Load structures both in integers and + floating-point registers on return. + * README: Update status of the SPARC port. + +2004-01-24 Andreas Tobler + + * testsuite/libffi.call/pyobjc-tc.c (main): Treat result value + as of type ffi_arg. + * testsuite/libffi.call/struct3.c (main): Fix CHECK. + +2004-01-22 Ulrich Weigand + + * testsuite/libffi.call/cls_uint.c (cls_ret_uint_fn): Treat result + value as of type ffi_arg, not unsigned int. + +2004-01-21 Michael Ritzert + + * ffi64.c (ffi_prep_args): Cast the RHS of an assignment instead + of the LHS. + +2004-01-12 Andreas Tobler + + * testsuite/lib/libffi-dg.exp: Set LD_LIBRARY_PATH_32 for + Solaris. + +2004-01-08 Rainer Orth + + * testsuite/libffi.call/ffitest.h (allocate_mmap): Cast MAP_FAILED + to void *. + +2003-12-10 Richard Henderson + + * testsuite/libffi.call/cls_align_pointer.c: Cast pointers to + size_t instead of int. + +2003-12-04 Hosaka Yuji + + * testsuite/libffi.call/many_win32.c: Include . + * testsuite/libffi.call/many_win32.c (main): Replace variable + int i with unsigned long ul. + + * testsuite/libffi.call/cls_align_uint64.c: New test case. + * testsuite/libffi.call/cls_align_sint64.c: Likewise. + * testsuite/libffi.call/cls_align_uint32.c: Likewise. + * testsuite/libffi.call/cls_align_sint32.c: Likewise. + * testsuite/libffi.call/cls_align_uint16.c: Likewise. + * testsuite/libffi.call/cls_align_sint16.c: Likewise. + * testsuite/libffi.call/cls_align_float.c: Likewise. + * testsuite/libffi.call/cls_align_double.c: Likewise. + * testsuite/libffi.call/cls_align_longdouble.c: Likewise. + * testsuite/libffi.call/cls_align_pointer.c: Likewise. + +2003-12-02 Hosaka Yuji + + PR other/13221 + * src/x86/ffi.c (ffi_prep_args, ffi_prep_incoming_args_SYSV): + Align arguments to 32 bits. + +2003-12-01 Andreas Tobler + + PR other/13221 + * testsuite/libffi.call/cls_multi_sshort.c: New test case. + * testsuite/libffi.call/cls_multi_sshortchar.c: Likewise. + * testsuite/libffi.call/cls_multi_uchar.c: Likewise. + * testsuite/libffi.call/cls_multi_schar.c: Likewise. + * testsuite/libffi.call/cls_multi_ushortchar.c: Likewise. + * testsuite/libffi.call/cls_multi_ushort.c: Likewise. + + * testsuite/libffi.special/unwindtest.cc: Cosmetics. + +2003-11-26 Kaveh R. Ghazi + + * testsuite/libffi.call/ffitest.h: Include . + * testsuite/libffi.special/ffitestcxx.h: Likewise. + +2003-11-22 Andreas Tobler + + * Makefile.in: Rebuilt. + * configure: Likewise. + * testsuite/libffi.special/unwindtest.cc: Convert the mmap to + the right type. + +2003-11-21 Andreas Jaeger + Andreas Tobler + + * acinclude.m4: Add AC_FUNC_MMAP_BLACKLIST. + * configure.in: Call AC_FUNC_MMAP_BLACKLIST. + * Makefile.in: Rebuilt. + * aclocal.m4: Likewise. + * configure: Likewise. + * fficonfig.h.in: Likewise. + * testsuite/lib/libffi-dg.exp: Add include dir. + * testsuite/libffi.call/ffitest.h: Add MMAP definitions. + * testsuite/libffi.special/ffitestcxx.h: Likewise. + * testsuite/libffi.call/closure_fn0.c: Use MMAP functionality + for ffi_closure if available. + * testsuite/libffi.call/closure_fn1.c: Likewise. + * testsuite/libffi.call/closure_fn2.c: Likewise. + * testsuite/libffi.call/closure_fn3.c: Likewise. + * testsuite/libffi.call/closure_fn4.c: Likewise. + * testsuite/libffi.call/closure_fn5.c: Likewise. + * testsuite/libffi.call/cls_12byte.c: Likewise. + * testsuite/libffi.call/cls_16byte.c: Likewise. + * testsuite/libffi.call/cls_18byte.c: Likewise. + * testsuite/libffi.call/cls_19byte.c: Likewise. + * testsuite/libffi.call/cls_1_1byte.c: Likewise. + * testsuite/libffi.call/cls_20byte.c: Likewise. + * testsuite/libffi.call/cls_20byte1.c: Likewise. + * testsuite/libffi.call/cls_24byte.c: Likewise. + * testsuite/libffi.call/cls_2byte.c: Likewise. + * testsuite/libffi.call/cls_3_1byte.c: Likewise. + * testsuite/libffi.call/cls_3byte1.c: Likewise. + * testsuite/libffi.call/cls_3byte2.c: Likewise. + * testsuite/libffi.call/cls_4_1byte.c: Likewise. + * testsuite/libffi.call/cls_4byte.c: Likewise. + * testsuite/libffi.call/cls_5byte.c: Likewise. + * testsuite/libffi.call/cls_64byte.c: Likewise. + * testsuite/libffi.call/cls_6byte.c: Likewise. + * testsuite/libffi.call/cls_7byte.c: Likewise. + * testsuite/libffi.call/cls_8byte.c: Likewise. + * testsuite/libffi.call/cls_9byte1.c: Likewise. + * testsuite/libffi.call/cls_9byte2.c: Likewise. + * testsuite/libffi.call/cls_double.c: Likewise. + * testsuite/libffi.call/cls_float.c: Likewise. + * testsuite/libffi.call/cls_schar.c: Likewise. + * testsuite/libffi.call/cls_sint.c: Likewise. + * testsuite/libffi.call/cls_sshort.c: Likewise. + * testsuite/libffi.call/cls_uchar.c: Likewise. + * testsuite/libffi.call/cls_uint.c: Likewise. + * testsuite/libffi.call/cls_ulonglong.c: Likewise. + * testsuite/libffi.call/cls_ushort.c: Likewise. + * testsuite/libffi.call/nested_struct.c: Likewise. + * testsuite/libffi.call/nested_struct1.c: Likewise. + * testsuite/libffi.call/nested_struct2.c: Likewise. + * testsuite/libffi.call/nested_struct3.c: Likewise. + * testsuite/libffi.call/problem1.c: Likewise. + * testsuite/libffi.special/unwindtest.cc: Likewise. + +2003-11-20 Andreas Tobler + + * testsuite/lib/libffi-dg.exp: Make the -lgcc_s conditional. + +2003-11-19 Andreas Tobler + + * testsuite/lib/libffi-dg.exp: Add DYLD_LIBRARY_PATH for darwin. + Add -lgcc_s to additional flags. + +2003-11-12 Andreas Tobler + + * configure.in, include/Makefile.am: PR libgcj/11147, install + the ffitarget.h header file in a gcc versioned and target + dependent place. + * configure: Regenerated. + * Makefile.in, include/Makefile.in: Likewise. + * testsuite/Makefile.in: Likewise. + +2003-11-09 Andreas Tobler + + * testsuite/libffi.call/closure_fn0.c: Print result and check + with dg-output to make debugging easier. + * testsuite/libffi.call/closure_fn1.c: Likewise. + * testsuite/libffi.call/closure_fn2.c: Likewise. + * testsuite/libffi.call/closure_fn3.c: Likewise. + * testsuite/libffi.call/closure_fn4.c: Likewise. + * testsuite/libffi.call/closure_fn5.c: Likewise. + * testsuite/libffi.call/cls_12byte.c: Likewise. + * testsuite/libffi.call/cls_16byte.c: Likewise. + * testsuite/libffi.call/cls_18byte.c: Likewise. + * testsuite/libffi.call/cls_19byte.c: Likewise. + * testsuite/libffi.call/cls_1_1byte.c: Likewise. + * testsuite/libffi.call/cls_20byte.c: Likewise. + * testsuite/libffi.call/cls_20byte1.c: Likewise. + * testsuite/libffi.call/cls_24byte.c: Likewise. + * testsuite/libffi.call/cls_2byte.c: Likewise. + * testsuite/libffi.call/cls_3_1byte.c: Likewise. + * testsuite/libffi.call/cls_3byte1.c: Likewise. + * testsuite/libffi.call/cls_3byte2.c: Likewise. + * testsuite/libffi.call/cls_4_1byte.c: Likewise. + * testsuite/libffi.call/cls_4byte.c: Likewise. + * testsuite/libffi.call/cls_5byte.c: Likewise. + * testsuite/libffi.call/cls_64byte.c: Likewise. + * testsuite/libffi.call/cls_6byte.c: Likewise. + * testsuite/libffi.call/cls_7byte.c: Likewise. + * testsuite/libffi.call/cls_8byte.c: Likewise. + * testsuite/libffi.call/cls_9byte1.c: Likewise. + * testsuite/libffi.call/cls_9byte2.c: Likewise. + * testsuite/libffi.call/cls_double.c: Likewise. + * testsuite/libffi.call/cls_float.c: Likewise. + * testsuite/libffi.call/cls_schar.c: Likewise. + * testsuite/libffi.call/cls_sint.c: Likewise. + * testsuite/libffi.call/cls_sshort.c: Likewise. + * testsuite/libffi.call/cls_uchar.c: Likewise. + * testsuite/libffi.call/cls_uint.c: Likewise. + * testsuite/libffi.call/cls_ulonglong.c: Likewise. + * testsuite/libffi.call/cls_ushort.c: Likewise. + * testsuite/libffi.call/problem1.c: Likewise. + + * testsuite/libffi.special/unwindtest.cc: Make ffi_closure + static. + +2003-11-08 Andreas Tobler + + * testsuite/libffi.call/cls_9byte2.c: New test case. + * testsuite/libffi.call/cls_9byte1.c: Likewise. + * testsuite/libffi.call/cls_64byte.c: Likewise. + * testsuite/libffi.call/cls_20byte1.c: Likewise. + * testsuite/libffi.call/cls_19byte.c: Likewise. + * testsuite/libffi.call/cls_18byte.c: Likewise. + * testsuite/libffi.call/closure_fn4.c: Likewise. + * testsuite/libffi.call/closure_fn5.c: Likewise. + * testsuite/libffi.call/cls_schar.c: Likewise. + * testsuite/libffi.call/cls_sint.c: Likewise. + * testsuite/libffi.call/cls_sshort.c: Likewise. + * testsuite/libffi.call/nested_struct2.c: Likewise. + * testsuite/libffi.call/nested_struct3.c: Likewise. + +2003-11-08 Andreas Tobler + + * testsuite/libffi.call/cls_double.c: Do a check on the result. + * testsuite/libffi.call/cls_uchar.c: Likewise. + * testsuite/libffi.call/cls_uint.c: Likewise. + * testsuite/libffi.call/cls_ulonglong.c: Likewise. + * testsuite/libffi.call/cls_ushort.c: Likewise. + * testsuite/libffi.call/return_sc.c: Cleanup whitespaces. + +2003-11-06 Andreas Tobler + + * src/prep_cif.c (ffi_prep_cif): Move the validity check after + the initialization. + +2003-10-23 Andreas Tobler + + * src/java_raw_api.c (ffi_java_ptrarray_to_raw): Replace + FFI_ASSERT(FALSE) with FFI_ASSERT(0). + +2003-10-22 David Daney + + * src/mips/ffitarget.h: Replace undefined UINT32 and friends with + __attribute__((__mode__(__SI__))) and friends. + +2003-10-22 Andreas Schwab + + * src/ia64/ffi.c: Replace FALSE/TRUE with false/true. + +2003-10-21 Andreas Tobler + + * configure.in: AC_LINK_FILES(ffitarget.h). + * configure: Regenerate. + * Makefile.in: Likewise. + * include/Makefile.in: Likewise. + * testsuite/Makefile.in: Likewise. + * fficonfig.h.in: Likewise. + +2003-10-21 Paolo Bonzini + Richard Henderson + + Avoid that ffi.h includes fficonfig.h. + + * Makefile.am (EXTRA_DIST): Include ffitarget.h files + (TARGET_SRC_MIPS_GCC): Renamed to TARGET_SRC_MIPS_IRIX. + (TARGET_SRC_MIPS_SGI): Removed. + (MIPS_GCC): Renamed to TARGET_SRC_MIPS_IRIX. + (MIPS_SGI): Removed. + (CLEANFILES): Removed. + (mostlyclean-am, clean-am, mostlyclean-sub, clean-sub): New + targets. + * acconfig.h: Removed. + * configure.in: Compute sizeofs only for double and long double. + Use them to define and subst HAVE_LONG_DOUBLE. Include comments + into AC_DEFINE instead of using acconfig.h. Create + include/ffitarget.h instead of include/fficonfig.h. Rename + MIPS_GCC to MIPS_IRIX, drop MIPS_SGI since we are in gcc's tree. + AC_DEFINE EH_FRAME_FLAGS. + * include/Makefile.am (DISTCLEANFILES): New automake macro. + (hack_DATA): Add ffitarget.h. + * include/ffi.h.in: Remove all system specific definitions. + Declare raw API even if it is not installed, why bother? + Use limits.h instead of SIZEOF_* to define ffi_type_*. Do + not define EH_FRAME_FLAGS, it is in fficonfig.h now. Include + ffitarget.h instead of fficonfig.h. Remove ALIGN macro. + (UINT_ARG, INT_ARG): Removed, use ffi_arg and ffi_sarg instead. + * include/ffi_common.h (bool): Do not define. + (ffi_assert): Accept failed assertion. + (ffi_type_test): Return void and accept file/line. + (FFI_ASSERT): Pass stringized failed assertion. + (FFI_ASSERT_AT): New macro. + (FFI_ASSERT_VALID_TYPE): New macro. + (UINT8, SINT8, UINT16, SINT16, UINT32, SINT32, + UINT64, SINT64): Define here with gcc's __attribute__ macro + instead of in ffi.h + (FLOAT32, ALIGN): Define here instead of in ffi.h + * include/ffi-mips.h: Removed. Its content moved to + src/mips/ffitarget.h after separating assembly and C sections. + * src/alpha/ffi.c, src/alpha/ffi.c, src/java_raw_api.c + src/prep_cif.c, src/raw_api.c, src/ia64/ffi.c, + src/mips/ffi.c, src/mips/n32.S, src/mips/o32.S, + src/mips/ffitarget.h, src/sparc/ffi.c, src/x86/ffi64.c: + SIZEOF_ARG -> FFI_SIZEOF_ARG. + * src/ia64/ffi.c: Include stdbool.h (provided by GCC 2.95+). + * src/debug.c (ffi_assert): Accept stringized failed assertion. + (ffi_type_test): Rewritten. + * src/prep-cif.c (initialize_aggregate, ffi_prep_cif): Call + FFI_ASSERT_VALID_TYPE. + * src/alpha/ffitarget.h, src/arm/ffitarget.h, + src/ia64/ffitarget.h, src/m68k/ffitarget.h, + src/mips/ffitarget.h, src/powerpc/ffitarget.h, + src/s390/ffitarget.h, src/sh/ffitarget.h, + src/sh64/ffitarget.h, src/sparc/ffitarget.h, + src/x86/ffitarget.h: New files. + * src/alpha/osf.S, src/arm/sysv.S, src/ia64/unix.S, + src/m68k/sysv.S, src/mips/n32.S, src/mips/o32.S, + src/powerpc/aix.S, src/powerpc/darwin.S, + src/powerpc/ffi_darwin.c, src/powerpc/linux64.S, + src/powerpc/linux64_closure.S, src/powerpc/ppc_closure.S, + src/powerpc/sysv.S, src/s390/sysv.S, src/sh/sysv.S, + src/sh64/sysv.S, src/sparc/v8.S, src/sparc/v9.S, + src/x86/sysv.S, src/x86/unix64.S, src/x86/win32.S: + include fficonfig.h + +2003-10-20 Rainer Orth + + * src/mips/ffi.c: Use _ABIN32, _ABIO32 instead of external + _MIPS_SIM_NABI32, _MIPS_SIM_ABI32. + +2003-10-19 Andreas Tobler + + * src/powerpc/ffi_darwin.c (ffi_prep_args): Declare bytes again. + Used when FFI_DEBUG = 1. + +2003-10-14 Alan Modra + + * src/types.c (double, longdouble): Default POWERPC64 to 8 byte size + and align. + +2003-10-06 Rainer Orth + + * include/ffi_mips.h: Define FFI_MIPS_N32 for N32/N64 ABIs, + FFI_MIPS_O32 for O32 ABI. + +2003-10-01 Andreas Tobler + + * testsuite/lib/libffi-dg.exp: Set LD_LIBRARY_PATH_64 for + SPARC64. Cleanup whitespaces. + +2003-09-19 Andreas Tobler + + * testsuite/libffi.call/closure_fn0.c: Xfail mips, arm, + strongarm, xscale. Cleanup whitespaces. + * testsuite/libffi.call/closure_fn1.c: Likewise. + * testsuite/libffi.call/closure_fn2.c: Likewise. + * testsuite/libffi.call/closure_fn3.c: Likewise. + * testsuite/libffi.call/cls_12byte.c: Likewise. + * testsuite/libffi.call/cls_16byte.c: Likewise. + * testsuite/libffi.call/cls_1_1byte.c: Likewise. + * testsuite/libffi.call/cls_20byte.c: Likewise. + * testsuite/libffi.call/cls_24byte.c: Likewise. + * testsuite/libffi.call/cls_2byte.c: Likewise. + * testsuite/libffi.call/cls_3_1byte.c: Likewise. + * testsuite/libffi.call/cls_3byte1.c: Likewise. + * testsuite/libffi.call/cls_3byte2.c: Likewise. + * testsuite/libffi.call/cls_4_1byte.c: Likewise. + * testsuite/libffi.call/cls_4byte.c: Likewise. + * testsuite/libffi.call/cls_5byte.c: Likewise. + * testsuite/libffi.call/cls_6byte.c: Likewise. + * testsuite/libffi.call/cls_7byte.c: Likewise. + * testsuite/libffi.call/cls_8byte.c: Likewise. + * testsuite/libffi.call/cls_double.c: Likewise. + * testsuite/libffi.call/cls_float.c: Likewise. + * testsuite/libffi.call/cls_uchar.c: Likewise. + * testsuite/libffi.call/cls_uint.c: Likewise. + * testsuite/libffi.call/cls_ulonglong.c: Likewise. + * testsuite/libffi.call/cls_ushort.c: Likewise. + * testsuite/libffi.call/nested_struct.c: Likewise. + * testsuite/libffi.call/nested_struct1.c: Likewise. + * testsuite/libffi.call/problem1.c: Likewise. + * testsuite/libffi.special/unwindtest.cc: Likewise. + * testsuite/libffi.call/pyobjc-tc.c: Cleanup whitespaces. + +2003-09-18 David Edelsohn + + * src/powerpc/aix.S: Cleanup whitespaces. + * src/powerpc/aix_closure.S: Likewise. + +2003-09-18 Andreas Tobler + + * src/powerpc/darwin.S: Cleanup whitespaces, comment formatting. + * src/powerpc/darwin_closure.S: Likewise. + * src/powerpc/ffi_darwin.c: Likewise. + +2003-09-18 Andreas Tobler + David Edelsohn + + * src/types.c (double): Add AIX and Darwin to the right TYPEDEF. + * src/powerpc/aix_closure.S: Remove the pointer to the outgoing + parameter stack. + * src/powerpc/darwin_closure.S: Likewise. + * src/powerpc/ffi_darwin.c (ffi_prep_args): Handle structures + according to the Darwin/AIX ABI. + (ffi_prep_cif_machdep): Likewise. + (ffi_closure_helper_DARWIN): Likewise. + Remove the outgoing parameter stack logic. Simplify the evaluation + of the different CASE types. + (ffi_prep_clousure): Avoid the casts on lvalues. Change the branch + statement in the trampoline code. + +2003-09-18 Kaz Kojima + + * src/sh/ffi.c (ffi_prep_args): Take account into the alignement + for the register size. + (ffi_closure_helper_SYSV): Handle the structure return value + address correctly. + (ffi_closure_helper_SYSV): Return the appropriate type when + the registers are used for the structure return value. + * src/sh/sysv.S (ffi_closure_SYSV): Fix the stack layout for + the 64-bit return value. Update copyright years. + +2003-09-17 Rainer Orth + + * testsuite/lib/libffi-dg.exp (libffi_target_compile): Search in + srcdir for ffi_mips.h. + +2003-09-12 Alan Modra + + * src/prep_cif.c (initialize_aggregate): Include tail padding in + structure size. + * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Correct + placement of float result. + * testsuite/libffi.special/unwindtest.cc (closure_test_fn1): Correct + cast of "resp" for big-endian 64 bit machines. + +2003-09-11 Alan Modra + + * src/types.c (double, longdouble): Merge identical SH and ARM + typedefs, and add POWERPC64. + * src/powerpc/ffi.c (ffi_prep_args64): Correct next_arg calc for + struct split over gpr and rest. + (ffi_prep_cif_machdep): Correct intarg_count for structures. + * src/powerpc/linux64.S (ffi_call_LINUX64): Fix gpr offsets. + +2003-09-09 Andreas Tobler + + * src/powerpc/ffi.c (ffi_closure_helper_SYSV) Handle struct + passing correctly. + +2003-09-09 Alan Modra + + * configure: Regenerate. + +2003-09-04 Andreas Tobler + + * Makefile.am: Remove build rules for ffitest. + * Makefile.in: Rebuilt. + +2003-09-04 Andreas Tobler + + * src/java_raw_api.c: Include to fix compiler warning + about implicit declaration of abort(). + +2003-09-04 Andreas Tobler + + * Makefile.am: Add dejagnu test framework. Fixes PR other/11411. + * Makefile.in: Rebuilt. + * configure.in: Add dejagnu test framework. + * configure: Rebuilt. + + * testsuite/Makefile.am: New file. + * testsuite/Makefile.in: Built + * testsuite/lib/libffi-dg.exp: New file. + * testsuite/config/default.exp: Likewise. + * testsuite/libffi.call/call.exp: Likewise. + * testsuite/libffi.call/ffitest.h: Likewise. + * testsuite/libffi.call/closure_fn0.c: Likewise. + * testsuite/libffi.call/closure_fn1.c: Likewise. + * testsuite/libffi.call/closure_fn2.c: Likewise. + * testsuite/libffi.call/closure_fn3.c: Likewise. + * testsuite/libffi.call/cls_1_1byte.c: Likewise. + * testsuite/libffi.call/cls_3_1byte.c: Likewise. + * testsuite/libffi.call/cls_4_1byte.c: Likewise. + * testsuite/libffi.call/cls_2byte.c: Likewise. + * testsuite/libffi.call/cls_3byte1.c: Likewise. + * testsuite/libffi.call/cls_3byte2.c: Likewise. + * testsuite/libffi.call/cls_4byte.c: Likewise. + * testsuite/libffi.call/cls_5byte.c: Likewise. + * testsuite/libffi.call/cls_6byte.c: Likewise. + * testsuite/libffi.call/cls_7byte.c: Likewise. + * testsuite/libffi.call/cls_8byte.c: Likewise. + * testsuite/libffi.call/cls_12byte.c: Likewise. + * testsuite/libffi.call/cls_16byte.c: Likewise. + * testsuite/libffi.call/cls_20byte.c: Likewise. + * testsuite/libffi.call/cls_24byte.c: Likewise. + * testsuite/libffi.call/cls_double.c: Likewise. + * testsuite/libffi.call/cls_float.c: Likewise. + * testsuite/libffi.call/cls_uchar.c: Likewise. + * testsuite/libffi.call/cls_uint.c: Likewise. + * testsuite/libffi.call/cls_ulonglong.c: Likewise. + * testsuite/libffi.call/cls_ushort.c: Likewise. + * testsuite/libffi.call/float.c: Likewise. + * testsuite/libffi.call/float1.c: Likewise. + * testsuite/libffi.call/float2.c: Likewise. + * testsuite/libffi.call/many.c: Likewise. + * testsuite/libffi.call/many_win32.c: Likewise. + * testsuite/libffi.call/nested_struct.c: Likewise. + * testsuite/libffi.call/nested_struct1.c: Likewise. + * testsuite/libffi.call/pyobjc-tc.c: Likewise. + * testsuite/libffi.call/problem1.c: Likewise. + * testsuite/libffi.call/promotion.c: Likewise. + * testsuite/libffi.call/return_ll.c: Likewise. + * testsuite/libffi.call/return_sc.c: Likewise. + * testsuite/libffi.call/return_uc.c: Likewise. + * testsuite/libffi.call/strlen.c: Likewise. + * testsuite/libffi.call/strlen_win32.c: Likewise. + * testsuite/libffi.call/struct1.c: Likewise. + * testsuite/libffi.call/struct2.c: Likewise. + * testsuite/libffi.call/struct3.c: Likewise. + * testsuite/libffi.call/struct4.c: Likewise. + * testsuite/libffi.call/struct5.c: Likewise. + * testsuite/libffi.call/struct6.c: Likewise. + * testsuite/libffi.call/struct7.c: Likewise. + * testsuite/libffi.call/struct8.c: Likewise. + * testsuite/libffi.call/struct9.c: Likewise. + * testsuite/libffi.special/special.exp: New file. + * testsuite/libffi.special/ffitestcxx.h: Likewise. + * testsuite/libffi.special/unwindtest.cc: Likewise. + + +2003-08-13 Kaz Kojima + + * src/sh/ffi.c (OFS_INT16): Set 0 for little endian case. Update + copyright years. + +2003-08-02 Alan Modra + + * src/powerpc/ffi.c (ffi_prep_args64): Modify for changed gcc + structure passing. + (ffi_closure_helper_LINUX64): Likewise. + * src/powerpc/linux64.S: Remove code writing to parm save area. + * src/powerpc/linux64_closure.S (ffi_closure_LINUX64): Use return + address in lr from ffi_closure_helper_LINUX64 call to calculate + table address. Optimize function tail. + +2003-07-28 Andreas Tobler + + * src/sparc/ffi.c: Handle all floating point registers. + * src/sparc/v9.S: Likewise. Fixes second part of PR target/11410. + +2003-07-11 Gerald Pfeifer + + * README: Note that libffi is not part of GCC. Update the project + URL and status. + +2003-06-19 Franz Sirl + + * src/powerpc/ppc_closure.S: Include ffi.h. + +2003-06-13 Rainer Orth + + * src/x86/sysv.S: Avoid gas-only .uleb128/.sleb128 directives. + Use C style comments. + +2003-06-13 Kaz Kojima + + * Makefile.am: Add SHmedia support. Fix a typo of SH support. + * Makefile.in: Regenerate. + * configure.in (sh64-*-linux*, sh5*-*-linux*): Add target. + * configure: Regenerate. + * include/ffi.h.in: Add SHmedia support. + * src/sh64/ffi.c: New file. + * src/sh64/sysv.S: New file. + +2003-05-16 Jakub Jelinek + + * configure.in (HAVE_RO_EH_FRAME): Check whether .eh_frame section + should be read-only. + * configure: Rebuilt. + * fficonfig.h.in: Rebuilt. + * include/ffi.h.in (EH_FRAME_FLAGS): Define. + * src/alpha/osf.S: Use EH_FRAME_FLAGS. + * src/powerpc/linux64.S: Likewise. + * src/powerpc/linux64_closure.S: Likewise. Include ffi.h. + * src/powerpc/sysv.S: Use EH_FRAME_FLAGS. Use pcrel encoding + if -fpic/-fPIC/-mrelocatable. + * src/powerpc/powerpc_closure.S: Likewise. + * src/sparc/v8.S: If HAVE_RO_EH_FRAME is defined, don't include + #write in .eh_frame flags. + * src/sparc/v9.S: Likewise. + * src/x86/unix64.S: Use EH_FRAME_FLAGS. + * src/x86/sysv.S: Likewise. Use pcrel encoding if -fpic/-fPIC. + * src/s390/sysv.S: Use EH_FRAME_FLAGS. Include ffi.h. + +2003-05-07 Jeff Sturm + + Fixes PR bootstrap/10656 + * configure.in (HAVE_AS_REGISTER_PSEUDO_OP): Test assembler + support for .register pseudo-op. + * src/sparc/v8.S: Use it. + * fficonfig.h.in: Rebuilt. + * configure: Rebuilt. + +2003-04-18 Jakub Jelinek + + * include/ffi.h.in (POWERPC64): Define if 64-bit. + (enum ffi_abi): Add FFI_LINUX64 on POWERPC. + Make it the default on POWERPC64. + (FFI_TRAMPOLINE_SIZE): Define to 24 on POWERPC64. + * configure.in: Change powerpc-*-linux* into powerpc*-*-linux*. + * configure: Rebuilt. + * src/powerpc/ffi.c (hidden): Define. + (ffi_prep_args_SYSV): Renamed from + ffi_prep_args. Cast pointers to unsigned long to shut up warnings. + (NUM_GPR_ARG_REGISTERS64, NUM_FPR_ARG_REGISTERS64, + ASM_NEEDS_REGISTERS64): New. + (ffi_prep_args64): New function. + (ffi_prep_cif_machdep): Handle FFI_LINUX64 ABI. + (ffi_call): Likewise. + (ffi_prep_closure): Likewise. + (flush_icache): Surround by #ifndef POWERPC64. + (ffi_dblfl): New union type. + (ffi_closure_helper_SYSV): Use it to avoid aliasing problems. + (ffi_closure_helper_LINUX64): New function. + * src/powerpc/ppc_closure.S: Surround whole file by #ifndef + __powerpc64__. + * src/powerpc/sysv.S: Likewise. + (ffi_call_SYSV): Rename ffi_prep_args to ffi_prep_args_SYSV. + * src/powerpc/linux64.S: New file. + * src/powerpc/linux64_closure.S: New file. + * Makefile.am (EXTRA_DIST): Add src/powerpc/linux64.S and + src/powerpc/linux64_closure.S. + (TARGET_SRC_POWERPC): Likewise. + + * src/ffitest.c (closure_test_fn, closure_test_fn1, closure_test_fn2, + closure_test_fn3): Fix result printing on big-endian 64-bit + machines. + (main): Print tst2_arg instead of uninitialized tst2_result. + + * src/ffitest.c (main): Hide what closure pointer really points to + from the compiler. + +2003-04-16 Richard Earnshaw + + * configure.in (arm-*-netbsdelf*): Add configuration. + (configure): Regenerated. + +2003-04-04 Loren J. Rittle + + * include/Makefile.in: Regenerate. + +2003-03-21 Zdenek Dvorak + + * libffi/include/ffi.h.in: Define X86 instead of X86_64 in 32 + bit mode. + * libffi/src/x86/ffi.c (ffi_closure_SYSV, ffi_closure_raw_SYSV): + Receive closure pointer through parameter, read args using + __builtin_dwarf_cfa. + (FFI_INIT_TRAMPOLINE): Send closure reference through eax. + +2003-03-12 Andreas Schwab + + * configure.in: Avoid trailing /. in toolexeclibdir. + * configure: Rebuilt. + +2003-03-03 Andreas Tobler + + * src/powerpc/darwin_closure.S: Recode to fit dynamic libraries. + +2003-02-06 Andreas Tobler + + * libffi/src/powerpc/darwin_closure.S: + Fix alignement bug, allocate 8 bytes for the result. + * libffi/src/powerpc/aix_closure.S: + Likewise. + * libffi/src/powerpc/ffi_darwin.c: + Update stackframe description for aix/darwin_closure.S. + +2003-02-06 Jakub Jelinek + + * src/s390/ffi.c (ffi_closure_helper_SYSV): Add hidden visibility + attribute. + +2003-01-31 Christian Cornelssen , + Andreas Schwab + + * configure.in: Adjust command to source config-ml.in to account + for changes to the libffi_basedir definition. + (libffi_basedir): Remove ${srcdir} from value and include trailing + slash if nonempty. + + * configure: Regenerate. + +2003-01-29 Franz Sirl + + * src/powerpc/ppc_closure.S: Recode to fit shared libs. + +2003-01-28 Andrew Haley + + * include/ffi.h.in: Enable FFI_CLOSURES for x86_64. + * src/x86/ffi64.c (ffi_prep_closure): New. + (ffi_closure_UNIX64_inner): New. + * src/x86/unix64.S (ffi_closure_UNIX64): New. + +2003-01-27 Alexandre Oliva + + * configure.in (toolexecdir, toolexeclibdir): Set and AC_SUBST. + Remove USE_LIBDIR conditional. + * Makefile.am (toolexecdir, toolexeclibdir): Don't override. + * Makefile.in, configure: Rebuilt. + +2003-01027 David Edelsohn + + * Makefile.am (TARGET_SRC_POWERPC_AIX): Fix typo. + * Makefile.in: Regenerate. + +2003-01-22 Andrew Haley + + * src/powerpc/darwin.S (_ffi_call_AIX): Add Augmentation size to + unwind info. + +2003-01-21 Andreas Tobler + + * src/powerpc/darwin.S: Add unwind info. + * src/powerpc/darwin_closure.S: Likewise. + +2003-01-14 Andrew Haley + + * src/x86/ffi64.c (ffi_prep_args): Check for void retval. + (ffi_prep_cif_machdep): Likewise. + * src/x86/unix64.S: Add unwind info. + +2003-01-14 Andreas Jaeger + + * src/ffitest.c (main): Only use ffi_closures if those are + supported. + +2003-01-13 Andreas Tobler + + * libffi/src/ffitest.c + add closure testcases + +2003-01-13 Kevin B. Hendricks + + * libffi/src/powerpc/ffi.c + fix alignment bug for float (4 byte aligned iso 8 byte) + +2003-01-09 Geoffrey Keating + + * src/powerpc/ffi_darwin.c: Remove RCS version string. + * src/powerpc/darwin.S: Remove RCS version string. + +2003-01-03 Jeff Sturm + + * include/ffi.h.in: Add closure defines for SPARC, SPARC64. + * src/ffitest.c (main): Use static storage for closure. + * src/sparc/ffi.c (ffi_prep_closure, ffi_closure_sparc_inner): New. + * src/sparc/v8.S (ffi_closure_v8): New. + * src/sparc/v9.S (ffi_closure_v9): New. + +2002-11-10 Ranjit Mathew + + * include/ffi.h.in: Added FFI_STDCALL ffi_type + enumeration for X86_WIN32. + * src/x86/win32.S: Added ffi_call_STDCALL function + definition. + * src/x86/ffi.c (ffi_call/ffi_raw_call): Added + switch cases for recognising FFI_STDCALL and + calling ffi_call_STDCALL if target is X86_WIN32. + * src/ffitest.c (my_stdcall_strlen/stdcall_many): + stdcall versions of the "my_strlen" and "many" + test functions (for X86_WIN32). + Added test cases to test stdcall invocation using + these functions. + +2002-12-02 Kaz Kojima + + * src/sh/sysv.S: Add DWARF2 unwind info. + +2002-11-27 Ulrich Weigand + + * src/s390/sysv.S (.eh_frame section): Make section read-only. + +2002-11-26 Jim Wilson + + * src/types.c (FFI_TYPE_POINTER): Has size 8 on IA64. + +2002-11-23 H.J. Lu + + * acinclude.m4: Add dummy AM_PROG_LIBTOOL. + Include ../config/accross.m4. + * aclocal.m4; Rebuild. + * configure: Likewise. + +2002-11-15 Ulrich Weigand + + * src/s390/sysv.S (.eh_frame section): Adapt to pcrel FDE encoding. + +2002-11-11 DJ Delorie + + * configure.in: Look for common files in the right place. + +2002-10-08 Ulrich Weigand + + * src/java_raw_api.c (ffi_java_raw_to_ptrarray): Interpret + raw data as _Jv_word values, not ffi_raw. + (ffi_java_ptrarray_to_raw): Likewise. + (ffi_java_rvalue_to_raw): New function. + (ffi_java_raw_call): Call it. + (ffi_java_raw_to_rvalue): New function. + (ffi_java_translate_args): Call it. + * src/ffitest.c (closure_test_fn): Interpret return value + as ffi_arg, not int. + * src/s390/ffi.c (ffi_prep_cif_machdep): Add missing + FFI_TYPE_POINTER case. + (ffi_closure_helper_SYSV): Likewise. Also, assume return + values extended to word size. + +2002-10-02 Andreas Jaeger + + * src/x86/ffi64.c (ffi_prep_cif_machdep): Remove debug output. + +2002-10-01 Bo Thorsen + + * include/ffi.h.in: Fix i386 win32 compilation. + +2002-09-30 Ulrich Weigand + + * configure.in: Add s390x-*-linux-* target. + * configure: Regenerate. + * include/ffi.h.in: Define S390X for s390x targets. + (FFI_CLOSURES): Define for s390/s390x. + (FFI_TRAMPOLINE_SIZE): Likewise. + (FFI_NATIVE_RAW_API): Likewise. + * src/prep_cif.c (ffi_prep_cif): Do not compute stack space for s390. + * src/types.c (FFI_TYPE_POINTER): Use 8-byte pointers on s390x. + * src/s390/ffi.c: Major rework of existing code. Add support for + s390x targets. Add closure support. + * src/s390/sysv.S: Likewise. + +2002-09-29 Richard Earnshaw + + * src/arm/sysv.S: Fix typo. + +2002-09-28 Richard Earnshaw + + * src/arm/sysv.S: If we don't have machine/asm.h and the pre-processor + has defined __USER_LABEL_PREFIX__, then use it in CNAME. + (ffi_call_SYSV): Handle soft-float. + +2002-09-27 Bo Thorsen + + * include/ffi.h.in: Fix multilib x86-64 support. + +2002-09-22 Kaveh R. Ghazi + + * Makefile.am (all-multi): Fix multilib parallel build. + +2002-07-19 Kaz Kojima + + * configure.in (sh[34]*-*-linux*): Add brackets. + * configure: Regenerate. + +2002-07-18 Kaz Kojima + + * Makefile.am: Add SH support. + * Makefile.in: Regenerate. + * configure.in (sh-*-linux*, sh[34]*-*-linux*): Add target. + * configure: Regenerate. + * include/ffi.h.in: Add SH support. + * src/sh/ffi.c: New file. + * src/sh/sysv.S: New file. + * src/types.c: Add SH support. + +2002-07-16 Bo Thorsen + + * src/x86/ffi64.c: New file that adds x86-64 support. + * src/x86/unix64.S: New file that handles argument setup for + x86-64. + * src/x86/sysv.S: Don't use this on x86-64. + * src/x86/ffi.c: Don't use this on x86-64. + Remove unused vars. + * src/prep_cif.c (ffi_prep_cif): Don't do stack size calculation + for x86-64. + * src/ffitest.c (struct6): New test that tests a special case in + the x86-64 ABI. + (struct7): Likewise. + (struct8): Likewise. + (struct9): Likewise. + (closure_test_fn): Silence warning about this when it's not used. + (main): Add the new tests. + (main): Fix a couple of wrong casts and silence some compiler warnings. + * include/ffi.h.in: Add x86-64 ABI definition. + * fficonfig.h.in: Regenerate. + * Makefile.am: Add x86-64 support. + * configure.in: Likewise. + * Makefile.in: Regenerate. + * configure: Likewise. + +2002-06-24 Bo Thorsen + + * src/types.c: Merge settings for similar architectures. + Add x86-64 sizes and alignments. + +2002-06-23 Bo Thorsen + + * src/arm/ffi.c (ffi_prep_args): Remove unused vars. + * src/sparc/ffi.c (ffi_prep_args_v8): Likewise. + * src/mips/ffi.c (ffi_prep_args): Likewise. + * src/m68k/ffi.c (ffi_prep_args): Likewise. + +2002-07-18 H.J. Lu (hjl@gnu.org) + + * Makefile.am (TARGET_SRC_MIPS_LINUX): New. + (libffi_la_SOURCES): Support MIPS_LINUX. + (libffi_convenience_la_SOURCES): Likewise. + * Makefile.in: Regenerated. + + * configure.in (mips64*-*): Skip. + (mips*-*-linux*): New. + * configure: Regenerated. + + * src/mips/ffi.c: Include . + +2002-06-06 Ulrich Weigand + + * src/s390/sysv.S: Save/restore %r6. Add DWARF-2 unwind info. + +2002-05-27 Roger Sayle + + * src/x86/ffi.c (ffi_prep_args): Remove reference to avn. + +2002-05-27 Bo Thorsen + + * src/x86/ffi.c (ffi_prep_args): Remove unused variable and + fix formatting. + +2002-05-13 Andreas Tobler + + * src/powerpc/ffi_darwin.c (ffi_prep_closure): Declare fd at + beginning of function (for older apple cc). + +2002-05-08 Alexandre Oliva + + * configure.in (ORIGINAL_LD_FOR_MULTILIBS): Preserve LD at + script entry, and set LD to it when configuring multilibs. + * configure: Rebuilt. + +2002-05-05 Jason Thorpe + + * configure.in (sparc64-*-netbsd*): Add target. + (sparc-*-netbsdelf*): Likewise. + * configure: Regenerate. + +2002-04-28 David S. Miller + + * configure.in, configure: Fix SPARC test in previous change. + +2002-04-29 Gerhard Tonn + + * Makefile.am: Add Linux for S/390 support. + * Makefile.in: Regenerate. + * configure.in: Add Linux for S/390 support. + * configure: Regenerate. + * include/ffi.h.in: Add Linux for S/390 support. + * src/s390/ffi.c: New file from libffi CVS tree. + * src/s390/sysv.S: New file from libffi CVS tree. + +2002-04-28 Jakub Jelinek + + * configure.in (HAVE_AS_SPARC_UA_PCREL): Check for working + %r_disp32(). + * src/sparc/v8.S: Use it. + * src/sparc/v9.S: Likewise. + * fficonfig.h.in: Rebuilt. + * configure: Rebuilt. + +2002-04-08 Hans Boehm + + * src/java_raw_api.c (ffi_java_raw_size): Handle FFI_TYPE_DOUBLE + correctly. + * src/ia64/unix.S: Add unwind information. Fix comments. + Save sp in a way that's compatible with unwind info. + (ffi_call_unix): Correctly restore sp in all cases. + * src/ia64/ffi.c: Add, fix comments. + +2002-04-08 Jakub Jelinek + + * src/sparc/v8.S: Make .eh_frame dependent on target word size. + +2002-04-06 Jason Thorpe + + * configure.in (alpha*-*-netbsd*): Add target. + * configure: Regenerate. + +2002-04-04 Jeff Sturm + + * src/sparc/v8.S: Add unwind info. + * src/sparc/v9.S: Likewise. + +2002-03-30 Krister Walfridsson + + * configure.in: Enable i*86-*-netbsdelf*. + * configure: Rebuilt. + +2002-03-29 David Billinghurst + + PR other/2620 + * src/mips/n32.s: Delete + * src/mips/o32.s: Delete + +2002-03-21 Loren J. Rittle + + * configure.in: Enable alpha*-*-freebsd*. + * configure: Rebuilt. + +2002-03-17 Bryce McKinlay + + * Makefile.am: libfficonvenience -> libffi_convenience. + * Makefile.in: Rebuilt. + + * Makefile.am: Define ffitest_OBJECTS. + * Makefile.in: Rebuilt. + +2002-03-07 Andreas Tobler + David Edelsohn + + * Makefile.am (EXTRA_DIST): Add Darwin and AIX closure files. + (TARGET_SRC_POWERPC_AIX): Add aix_closure.S. + (TARGET_SRC_POWERPC_DARWIN): Add darwin_closure.S. + * Makefile.in: Regenerate. + * include/ffi.h.in: Add AIX and Darwin closure definitions. + * src/powerpc/ffi_darwin.c (ffi_prep_closure): New function. + (flush_icache, flush_range): New functions. + (ffi_closure_helper_DARWIN): New function. + * src/powerpc/aix_closure.S: New file. + * src/powerpc/darwin_closure.S: New file. + +2002-02-24 Jeff Sturm + + * include/ffi.h.in: Add typedef for ffi_arg. + * src/ffitest.c (main): Declare rint with ffi_arg. + +2002-02-21 Andreas Tobler + + * src/powerpc/ffi_darwin.c (ffi_prep_args): Skip appropriate + number of GPRs for floating-point arguments. + +2002-01-31 Anthony Green + + * configure: Rebuilt. + * configure.in: Replace CHECK_SIZEOF and endian tests with + cross-compiler friendly macros. + * aclocal.m4 (AC_COMPILE_CHECK_SIZEOF, AC_C_BIGENDIAN_CROSS): New + macros. + +2002-01-18 David Edelsohn + + * src/powerpc/darwin.S (_ffi_call_AIX): New. + * src/powerpc/aix.S (ffi_call_DARWIN): New. + +2002-01-17 David Edelsohn + + * Makefile.am (EXTRA_DIST): Add Darwin and AIX files. + (TARGET_SRC_POWERPC_AIX): New. + (POWERPC_AIX): New stanza. + * Makefile.in: Regenerate. + * configure.in: Add AIX case. + * configure: Regenerate. + * include/ffi.h.in (ffi_abi): Add FFI_AIX. + * src/powerpc/ffi_darwin.c (ffi_status): Use "long" to scale frame + size. Fix "long double" support. + (ffi_call): Add FFI_AIX case. + * src/powerpc/aix.S: New. + +2001-10-09 John Hornkvist + + Implement Darwin PowerPC ABI. + * configure.in: Handle powerpc-*-darwin*. + * Makefile.am: Set source files for POWERPC_DARWIN. + * configure: Rebuilt. + * Makefile.in: Rebuilt. + * include/ffi.h.in: Define FFI_DARWIN and FFI_DEFAULT_ABI for + POWERPC_DARWIN. + * src/powerpc/darwin.S: New file. + * src/powerpc/ffi_darwin.c: New file. + +2001-10-07 Joseph S. Myers + + * src/x86/ffi.c: Fix spelling error of "separate" as "seperate". + +2001-07-16 Rainer Orth + + * src/x86/sysv.S: Avoid gas-only .balign directive. + Use C style comments. + +2001-07-16 Rainer Orth + + * src/alpha/ffi.c (ffi_prep_closure): Avoid gas-only mnemonic. + Fixes PR bootstrap/3563. + +2001-06-26 Rainer Orth + + * src/alpha/osf.S (ffi_closure_osf): Use .rdata for ECOFF. + +2001-06-25 Rainer Orth + + * configure.in: Recognize sparc*-sun-* host. + * configure: Regenerate. + +2001-06-06 Andrew Haley + + * src/alpha/osf.S (__FRAME_BEGIN__): Conditionalize for ELF. + +2001-06-03 Andrew Haley + + * src/alpha/osf.S: Add unwind info. + * src/powerpc/sysv.S: Add unwind info. + * src/powerpc/ppc_closure.S: Likewise. + +2000-05-31 Jeff Sturm + + * configure.in: Fix AC_ARG_ENABLE usage. + * configure: Rebuilt. + +2001-05-06 Bryce McKinlay + + * configure.in: Remove warning about beta code. + * configure: Rebuilt. + +2001-04-25 Hans Boehm + + * src/ia64/unix.S: Restore stack pointer when returning from + ffi_closure_UNIX. + * src/ia64/ffi.c: Fix typo in comment. + +2001-04-18 Jim Wilson + + * src/ia64/unix.S: Delete unnecessary increment and decrement of loc2 + to eliminate RAW DV. + +2001-04-12 Bryce McKinlay + + * Makefile.am: Make a libtool convenience library. + * Makefile.in: Rebuilt. + +2001-03-29 Bryce McKinlay + + * configure.in: Use different syntax for subdirectory creation. + * configure: Rebuilt. + +2001-03-27 Jon Beniston + + * configure.in: Added X86_WIN32 target (Win32, CygWin, MingW). + * configure: Rebuilt. + * Makefile.am: Added X86_WIN32 target support. + * Makefile.in: Rebuilt. + + * include/ffi.h.in: Added X86_WIN32 target support. + + * src/ffitest.c: Doesn't run structure tests for X86_WIN32 targets. + * src/types.c: Added X86_WIN32 target support. + + * src/x86/win32.S: New file. Based on sysv.S, but with EH + stuff removed and made to work with CygWin's gas. + +2001-03-26 Bryce McKinlay + + * configure.in: Make target subdirectory in build dir. + * Makefile.am: Override suffix based rules to specify correct output + subdirectory. + * Makefile.in: Rebuilt. + * configure: Rebuilt. + +2001-03-23 Kevin B Hendricks + + * src/powerpc/ppc_closure.S: New file. + * src/powerpc/ffi.c (ffi_prep_args): Fixed ABI compatibility bug + involving long long and register pairs. + (ffi_prep_closure): New function. + (flush_icache): Likewise. + (ffi_closure_helper_SYSV): Likewise. + * include/ffi.h.in (FFI_CLOSURES): Define on PPC. + (FFI_TRAMPOLINE_SIZE): Likewise. + (FFI_NATIVE_RAW_API): Likewise. + * Makefile.in: Rebuilt. + * Makefile.am (EXTRA_DIST): Added src/powerpc/ppc_closure.S. + (TARGET_SRC_POWERPC): Likewise. + +2001-03-19 Tom Tromey + + * Makefile.in: Rebuilt. + * Makefile.am (ffitest_LDFLAGS): New macro. + +2001-03-02 Nick Clifton + + * include/ffi.h.in: Remove RCS ident string. + * include/ffi_mips.h: Remove RCS ident string. + * src/debug.c: Remove RCS ident string. + * src/ffitest.c: Remove RCS ident string. + * src/prep_cif.c: Remove RCS ident string. + * src/types.c: Remove RCS ident string. + * src/alpha/ffi.c: Remove RCS ident string. + * src/alpha/osf.S: Remove RCS ident string. + * src/arm/ffi.c: Remove RCS ident string. + * src/arm/sysv.S: Remove RCS ident string. + * src/mips/ffi.c: Remove RCS ident string. + * src/mips/n32.S: Remove RCS ident string. + * src/mips/o32.S: Remove RCS ident string. + * src/sparc/ffi.c: Remove RCS ident string. + * src/sparc/v8.S: Remove RCS ident string. + * src/sparc/v9.S: Remove RCS ident string. + * src/x86/ffi.c: Remove RCS ident string. + * src/x86/sysv.S: Remove RCS ident string. + +2001-02-08 Joseph S. Myers + + * include/ffi.h.in: Change sourceware.cygnus.com references to + gcc.gnu.org. + +2000-12-09 Richard Henderson + + * src/alpha/ffi.c (ffi_call): Simplify struct return test. + (ffi_closure_osf_inner): Index rather than increment avalue + and arg_types. Give ffi_closure_osf the raw return value type. + * src/alpha/osf.S (ffi_closure_osf): Handle return value type + promotion. + +2000-12-07 Richard Henderson + + * src/raw_api.c (ffi_translate_args): Fix typo. + (ffi_prep_closure): Likewise. + + * include/ffi.h.in [ALPHA]: Define FFI_CLOSURES and + FFI_TRAMPOLINE_SIZE. + * src/alpha/ffi.c (ffi_prep_cif_machdep): Adjust minimal + cif->bytes for new ffi_call_osf implementation. + (ffi_prep_args): Absorb into ... + (ffi_call): ... here. Do all stack allocation here and + avoid a callback function. + (ffi_prep_closure, ffi_closure_osf_inner): New. + * src/alpha/osf.S (ffi_call_osf): Reimplement with no callback. + (ffi_closure_osf): New. + +2000-09-10 Alexandre Oliva + + * config.guess, config.sub, install-sh: Removed. + * ltconfig, ltmain.sh, missing, mkinstalldirs: Likewise. + * Makefile.in: Rebuilt. + + * acinclude.m4: Include libtool macros from the top level. + * aclocal.m4, configure: Rebuilt. + +2000-08-22 Alexandre Oliva + + * configure.in [i*86-*-freebsd*] (TARGET, TARGETDIR): Set. + * configure: Rebuilt. + +2000-05-11 Scott Bambrough + + * libffi/src/arm/sysv.S (ffi_call_SYSV): Doubles are not saved to + memory correctly. Use conditional instructions, not branches where + possible. + +2000-05-04 Tom Tromey + + * configure: Rebuilt. + * configure.in: Match `arm*-*-linux-*'. + From Chris Dornan . + +2000-04-28 Jakub Jelinek + + * Makefile.am (SUBDIRS): Define. + (AM_MAKEFLAGS): Likewise. + (Multilib support.): Add section. + * Makefile.in: Rebuilt. + * ltconfig (extra_compiler_flags, extra_compiler_flags_value): + New variables. Set for gcc using -print-multi-lib. Export them + to libtool. + (sparc64-*-linux-gnu*): Use libsuff 64 for search paths. + * ltmain.sh (B|b|V): Don't throw away gcc's -B, -b and -V options + for -shared links. + (extra_compiler_flags_value, extra_compiler_flags): Check these + for extra compiler options which need to be passed down in + compiler_flags. + +2000-04-16 Anthony Green + + * configure: Rebuilt. + * configure.in: Change i*86-pc-linux* to i*86-*-linux*. + +2000-04-14 Jakub Jelinek + + * include/ffi.h.in (SPARC64): Define for 64bit SPARC builds. + Set SPARC FFI_DEFAULT_ABI based on SPARC64 define. + * src/sparc/ffi.c (ffi_prep_args_v8): Renamed from ffi_prep_args. + Replace all void * sizeofs with sizeof(int). + Only compare type with FFI_TYPE_LONGDOUBLE if LONGDOUBLE is + different than DOUBLE. + Remove FFI_TYPE_SINT32 and FFI_TYPE_UINT32 cases (handled elsewhere). + (ffi_prep_args_v9): New function. + (ffi_prep_cif_machdep): Handle V9 ABI and long long on V8. + (ffi_V9_return_struct): New function. + (ffi_call): Handle FFI_V9 ABI from 64bit code and FFI_V8 ABI from + 32bit code (not yet cross-arch calls). + * src/sparc/v8.S: Add struct return delay nop. + Handle long long. + * src/sparc/v9.S: New file. + * src/prep_cif.c (ffi_prep_cif): Return structure pointer + is used on sparc64 only for structures larger than 32 bytes. + Pass by reference for structures is done for structure arguments + larger than 16 bytes. + * src/ffitest.c (main): Use 64bit rint on sparc64. + Run long long tests on sparc. + * src/types.c (FFI_TYPE_POINTER): Pointer is 64bit on alpha and + sparc64. + (FFI_TYPE_LONGDOUBLE): long double is 128 bit aligned to 128 bits + on sparc64. + * configure.in (sparc-*-linux*): New supported target. + (sparc64-*-linux*): Likewise. + * configure: Rebuilt. + * Makefile.am: Add v9.S to SPARC files. + * Makefile.in: Likewise. + (LINK): Surround $(CCLD) into double quotes, so that multilib + compiles work correctly. + +2000-04-04 Alexandre Petit-Bianco + + * configure: Rebuilt. + * configure.in: (i*86-*-solaris*): New libffi target. Patch + proposed by Bryce McKinlay. + +2000-03-20 Tom Tromey + + * Makefile.in: Hand edit for java_raw_api.lo. + +2000-03-08 Bryce McKinlay + + * config.guess, config.sub: Update from the gcc tree. + Fix for PR libgcj/168. + +2000-03-03 Tom Tromey + + * Makefile.in: Fixed ia64 by hand. + + * configure: Rebuilt. + * configure.in (--enable-multilib): New option. + (libffi_basedir): New subst. + (AC_OUTPUT): Added multilib code. + +2000-03-02 Tom Tromey + + * Makefile.in: Rebuilt. + * Makefile.am (TARGET_SRC_IA64): Use `ia64', not `alpha', as + directory name. + +2000-02-25 Hans Boehm + + * src/ia64/ffi.c, src/ia64/ia64_flags.h, src/ia64/unix.S: New + files. + * src/raw_api.c (ffi_translate_args): Fixed typo in argument + list. + (ffi_prep_raw_closure): Use ffi_translate_args, not + ffi_closure_translate. + * src/java_raw_api.c: New file. + * src/ffitest.c (closure_test_fn): New function. + (main): Define `rint' as long long on IA64. Added new test when + FFI_CLOSURES is defined. + * include/ffi.h.in (ALIGN): Use size_t, not unsigned. + (ffi_abi): Recognize IA64. + (ffi_raw): Added `flt' field. + Added "Java raw API" code. + * configure.in: Recognize ia64. + * Makefile.am (TARGET_SRC_IA64): New macro. + (libffi_la_common_SOURCES): Added java_raw_api.c. + (libffi_la_SOURCES): Define in IA64 case. + +2000-01-04 Tom Tromey + + * Makefile.in: Rebuilt with newer automake. + +1999-12-31 Tom Tromey + + * Makefile.am (INCLUDES): Added -I$(top_srcdir)/src. + +1999-09-01 Tom Tromey + + * include/ffi.h.in: Removed PACKAGE and VERSION defines and + undefs. + * fficonfig.h.in: Rebuilt. + * configure: Rebuilt. + * configure.in: Pass 3rd argument to AM_INIT_AUTOMAKE. + Use AM_PROG_LIBTOOL (automake 1.4 compatibility). + * acconfig.h: Don't #undef PACKAGE or VERSION. + +1999-08-09 Anthony Green + + * include/ffi.h.in: Try to work around messy header problem + with PACKAGE and VERSION. + + * configure: Rebuilt. + * configure.in: Change version to 2.00-beta. + + * fficonfig.h.in: Rebuilt. + * acconfig.h (FFI_NO_STRUCTS, FFI_NO_RAW_API): Define. + + * src/x86/ffi.c (ffi_raw_call): Rename. + +1999-08-02 Kresten Krab Thorup + + * src/x86/ffi.c (ffi_closure_SYSV): New function. + (ffi_prep_incoming_args_SYSV): Ditto. + (ffi_prep_closure): Ditto. + (ffi_closure_raw_SYSV): Ditto. + (ffi_prep_raw_closure): More ditto. + (ffi_call_raw): Final ditto. + + * include/ffi.h.in: Add definitions for closure and raw API. + + * src/x86/ffi.c (ffi_prep_cif_machdep): Added case for + FFI_TYPE_UINT64. + + * Makefile.am (libffi_la_common_SOURCES): Added raw_api.c + + * src/raw_api.c: New file. + + * include/ffi.h.in (ffi_raw): New type. + (UINT_ARG, SINT_ARG): New defines. + (ffi_closure, ffi_raw_closure): New types. + (ffi_prep_closure, ffi_prep_raw_closure): New declarations. + + * configure.in: Add check for endianness and sizeof void*. + + * src/x86/sysv.S (ffi_call_SYSV): Call fixup routine via argument, + instead of directly. + + * configure: Rebuilt. + +Thu Jul 8 14:28:42 1999 Anthony Green + + * configure.in: Add x86 and powerpc BeOS configurations. + From Makoto Kato . + +1999-05-09 Anthony Green + + * configure.in: Add warning about this being beta code. + Remove src/Makefile.am from the picture. + * configure: Rebuilt. + + * Makefile.am: Move logic from src/Makefile.am. Add changes + to support libffi as a target library. + * Makefile.in: Rebuilt. + + * aclocal.m4, config.guess, config.sub, ltconfig, ltmain.sh: + Upgraded to new autoconf, automake, libtool. + + * README: Tweaks. + + * LICENSE: Update copyright date. + + * src/Makefile.am, src/Makefile.in: Removed. + +1998-11-29 Anthony Green + + * include/ChangeLog: Removed. + * src/ChangeLog: Removed. + * src/mips/ChangeLog: Removed. + * src/sparc/ChangeLog: Remboved. + * src/x86/ChangeLog: Removed. + + * ChangeLog.v1: Created. + +============================================================================= +From the old ChangeLog.libffi file.... + +2011-02-08 Andreas Tobler + + * testsuite/lib/libffi.exp: Tweak for stand-alone mode. + +2009-12-25 Samuli Suominen + + * configure.ac: Undefine _AC_ARG_VAR_PRECIOUS for autoconf 2.64. + * configure: Rebuilt. + * fficonfig.h.in: Rebuilt. + +2009-06-16 Andrew Haley + + * testsuite/libffi.call/cls_align_sint64.c, + testsuite/libffi.call/cls_align_uint64.c, + testsuite/libffi.call/cls_longdouble_va.c, + testsuite/libffi.call/cls_ulonglong.c, + testsuite/libffi.call/return_ll1.c, + testsuite/libffi.call/stret_medium2.c: Fix printf format + specifiers. + * testsuite/libffi.call/huge_struct.c: Ad x86 XFAILs. + * testsuite/libffi.call/float2.c: Fix dg-excess-errors. + * testsuite/libffi.call/ffitest.h, + testsuite/libffi.special/ffitestcxx.h (PRIdLL, PRIuLL): Define. + +2009-06-12 Andrew Haley + + * testsuite/libffi.call/cls_align_sint64.c, + testsuite/libffi.call/cls_align_uint64.c, + testsuite/libffi.call/cls_ulonglong.c, + testsuite/libffi.call/return_ll1.c, + testsuite/libffi.call/stret_medium2.c: Fix printf format + specifiers. + testsuite/libffi.special/unwindtest.cc: include stdint.h. + +2009-06-11 Timothy Wall + + * Makefile.am, + configure.ac, + include/ffi.h.in, + include/ffi_common.h, + src/closures.c, + src/dlmalloc.c, + src/x86/ffi.c, + src/x86/ffitarget.h, + src/x86/win64.S (new), + README: Added win64 support (mingw or MSVC) + * Makefile.in, + include/Makefile.in, + man/Makefile.in, + testsuite/Makefile.in, + configure, + aclocal.m4: Regenerated + * ltcf-c.sh: properly escape cygwin/w32 path + * man/ffi_call.3: Clarify size requirements for return value. + * src/x86/ffi64.c: Fix filename in comment. + * src/x86/win32.S: Remove unused extern. + + * testsuite/libffi.call/closure_fn0.c, + testsuite/libffi.call/closure_fn1.c, + testsuite/libffi.call/closure_fn2.c, + testsuite/libffi.call/closure_fn3.c, + testsuite/libffi.call/closure_fn4.c, + testsuite/libffi.call/closure_fn5.c, + testsuite/libffi.call/closure_fn6.c, + testsuite/libffi.call/closure_stdcall.c, + testsuite/libffi.call/cls_12byte.c, + testsuite/libffi.call/cls_16byte.c, + testsuite/libffi.call/cls_18byte.c, + testsuite/libffi.call/cls_19byte.c, + testsuite/libffi.call/cls_1_1byte.c, + testsuite/libffi.call/cls_20byte.c, + testsuite/libffi.call/cls_20byte1.c, + testsuite/libffi.call/cls_24byte.c, + testsuite/libffi.call/cls_2byte.c, + testsuite/libffi.call/cls_3_1byte.c, + testsuite/libffi.call/cls_3byte1.c, + testsuite/libffi.call/cls_3byte2.c, + testsuite/libffi.call/cls_4_1byte.c, + testsuite/libffi.call/cls_4byte.c, + testsuite/libffi.call/cls_5_1_byte.c, + testsuite/libffi.call/cls_5byte.c, + testsuite/libffi.call/cls_64byte.c, + testsuite/libffi.call/cls_6_1_byte.c, + testsuite/libffi.call/cls_6byte.c, + testsuite/libffi.call/cls_7_1_byte.c, + testsuite/libffi.call/cls_7byte.c, + testsuite/libffi.call/cls_8byte.c, + testsuite/libffi.call/cls_9byte1.c, + testsuite/libffi.call/cls_9byte2.c, + testsuite/libffi.call/cls_align_double.c, + testsuite/libffi.call/cls_align_float.c, + testsuite/libffi.call/cls_align_longdouble.c, + testsuite/libffi.call/cls_align_longdouble_split.c, + testsuite/libffi.call/cls_align_longdouble_split2.c, + testsuite/libffi.call/cls_align_pointer.c, + testsuite/libffi.call/cls_align_sint16.c, + testsuite/libffi.call/cls_align_sint32.c, + testsuite/libffi.call/cls_align_sint64.c, + testsuite/libffi.call/cls_align_uint16.c, + testsuite/libffi.call/cls_align_uint32.c, + testsuite/libffi.call/cls_align_uint64.c, + testsuite/libffi.call/cls_dbls_struct.c, + testsuite/libffi.call/cls_double.c, + testsuite/libffi.call/cls_double_va.c, + testsuite/libffi.call/cls_float.c, + testsuite/libffi.call/cls_longdouble.c, + testsuite/libffi.call/cls_longdouble_va.c, + testsuite/libffi.call/cls_multi_schar.c, + testsuite/libffi.call/cls_multi_sshort.c, + testsuite/libffi.call/cls_multi_sshortchar.c, + testsuite/libffi.call/cls_multi_uchar.c, + testsuite/libffi.call/cls_multi_ushort.c, + testsuite/libffi.call/cls_multi_ushortchar.c, + testsuite/libffi.call/cls_pointer.c, + testsuite/libffi.call/cls_pointer_stack.c, + testsuite/libffi.call/cls_schar.c, + testsuite/libffi.call/cls_sint.c, + testsuite/libffi.call/cls_sshort.c, + testsuite/libffi.call/cls_uchar.c, + testsuite/libffi.call/cls_uint.c, + testsuite/libffi.call/cls_ulonglong.c, + testsuite/libffi.call/cls_ushort.c, + testsuite/libffi.call/err_bad_abi.c, + testsuite/libffi.call/err_bad_typedef.c, + testsuite/libffi.call/float2.c, + testsuite/libffi.call/huge_struct.c, + testsuite/libffi.call/nested_struct.c, + testsuite/libffi.call/nested_struct1.c, + testsuite/libffi.call/nested_struct10.c, + testsuite/libffi.call/nested_struct2.c, + testsuite/libffi.call/nested_struct3.c, + testsuite/libffi.call/nested_struct4.c, + testsuite/libffi.call/nested_struct5.c, + testsuite/libffi.call/nested_struct6.c, + testsuite/libffi.call/nested_struct7.c, + testsuite/libffi.call/nested_struct8.c, + testsuite/libffi.call/nested_struct9.c, + testsuite/libffi.call/problem1.c, + testsuite/libffi.call/return_ldl.c, + testsuite/libffi.call/return_ll1.c, + testsuite/libffi.call/stret_large.c, + testsuite/libffi.call/stret_large2.c, + testsuite/libffi.call/stret_medium.c, + testsuite/libffi.call/stret_medium2.c, + testsuite/libffi.special/unwindtest.cc: use ffi_closure_alloc instead + of checking for MMAP. Use intptr_t instead of long casts. + +2009-06-04 Andrew Haley + + * src/powerpc/ffitarget.h: Fix misapplied merge from gcc. + +2009-06-04 Andrew Haley + + * src/mips/o32.S, + src/mips/n32.S: Fix licence formatting. + +2009-06-04 Andrew Haley + + * src/x86/darwin.S: Fix licence formatting. + src/x86/win32.S: Likewise. + src/sh64/sysv.S: Likewise. + src/sh/sysv.S: Likewise. + +2009-06-04 Andrew Haley + + * src/sh64/ffi.c: Remove lint directives. Was missing from merge + of Andreas Tobler's patch from 2006-04-22. + +2009-06-04 Andrew Haley + + * src/sh/ffi.c: Apply missing hunk from Alexandre Oliva's patch of + 2007-03-07. + +2008-12-26 Timothy Wall + + * testsuite/libffi.call/cls_longdouble.c, + testsuite/libffi.call/cls_longdouble_va.c, + testsuite/libffi.call/cls_align_longdouble.c, + testsuite/libffi.call/cls_align_longdouble_split.c, + testsuite/libffi.call/cls_align_longdouble_split2.c: mark expected + failures on x86_64 cygwin/mingw. + +2008-12-22 Timothy Wall + + * testsuite/libffi.call/closure_fn0.c, + testsuite/libffi.call/closure_fn1.c, + testsuite/libffi.call/closure_fn2.c, + testsuite/libffi.call/closure_fn3.c, + testsuite/libffi.call/closure_fn4.c, + testsuite/libffi.call/closure_fn5.c, + testsuite/libffi.call/closure_fn6.c, + testsuite/libffi.call/closure_loc_fn0.c, + testsuite/libffi.call/closure_stdcall.c, + testsuite/libffi.call/cls_align_pointer.c, + testsuite/libffi.call/cls_pointer.c, + testsuite/libffi.call/cls_pointer_stack.c: use portable cast from + pointer to integer (intptr_t). + * testsuite/libffi.call/cls_longdouble.c: disable for win64. + +2008-12-19 Anthony Green + + * configure.ac: Bump version to 3.0.8. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + * libtool-version: Increment revision. + * README: Update for new release. + +2008-11-11 Anthony Green + + * configure.ac: Bump version to 3.0.7. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + * libtool-version: Increment revision. + * README: Update for new release. + +2008-08-25 Andreas Tobler + + * src/powerpc/ffitarget.h (ffi_abi): Add FFI_LINUX and + FFI_LINUX_SOFT_FLOAT to the POWERPC_FREEBSD enum. + Add note about flag bits used for FFI_SYSV_TYPE_SMALL_STRUCT. + Adjust copyright notice. + * src/powerpc/ffi.c: Add two new flags to indicate if we have one + register or two register to use for FFI_SYSV structs. + (ffi_prep_cif_machdep): Pass the right register flag introduced above. + (ffi_closure_helper_SYSV): Fix the return type for + FFI_SYSV_TYPE_SMALL_STRUCT. Comment. + Adjust copyright notice. + +2008-07-24 Anthony Green + + * testsuite/libffi.call/cls_dbls_struct.c, + testsuite/libffi.call/cls_double_va.c, + testsuite/libffi.call/cls_longdouble.c, + testsuite/libffi.call/cls_longdouble_va.c, + testsuite/libffi.call/cls_pointer.c, + testsuite/libffi.call/cls_pointer_stack.c, + testsuite/libffi.call/err_bad_abi.c: Clean up failures from + compiler warnings. + +2008-07-17 Anthony Green + + * configure.ac: Bump version to 3.0.6. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + * libtool-version: Increment revision. Add documentation. + * README: Update for new release. + +2008-07-16 Kaz Kojima + + * src/sh/ffi.c (ffi_prep_closure_loc): Turn INSN into an unsigned + int. + +2008-07-16 Kaz Kojima + + * src/sh/sysv.S: Add .note.GNU-stack on Linux. + * src/sh64/sysv.S: Likewise. + +2008-04-03 Anthony Green + + * libffi.pc.in (Libs): Add -L${libdir}. + * configure.ac: Bump version to 3.0.5. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + * libtool-version: Increment revision. + * README: Update for new release. + +2008-04-03 Anthony Green + Xerces Ranby + + * include/ffi.h.in: Wrap definition of target architecture to + protect from double definitions. + +2008-03-22 Moriyoshi Koizumi + + * src/x86/ffi.c (ffi_prep_closure_loc): Fix for bug revealed in + closure_loc_fn0.c. + * testsuite/libffi.call/closure_loc_fn0.c (closure_loc_test_fn0): + New test. + +2008-03-04 Anthony Green + Blake Chaffin + hos@tamanegi.org + + * testsuite/libffi.call/cls_align_longdouble_split2.c + testsuite/libffi.call/cls_align_longdouble_split.c + testsuite/libffi.call/cls_dbls_struct.c + testsuite/libffi.call/cls_double_va.c + testsuite/libffi.call/cls_longdouble.c + testsuite/libffi.call/cls_longdouble_va.c + testsuite/libffi.call/cls_pointer.c + testsuite/libffi.call/cls_pointer_stack.c + testsuite/libffi.call/err_bad_abi.c + testsuite/libffi.call/err_bad_typedef.c + testsuite/libffi.call/huge_struct.c + testsuite/libffi.call/stret_large2.c + testsuite/libffi.call/stret_large.c + testsuite/libffi.call/stret_medium2.c + testsuite/libffi.call/stret_medium.c: New tests from Apple. + +2008-02-26 Jakub Jelinek + Anthony Green + + * src/alpha/osf.S: Add .note.GNU-stack on Linux. + * src/s390/sysv.S: Likewise. + * src/powerpc/linux64.S: Likewise. + * src/powerpc/linux64_closure.S: Likewise. + * src/powerpc/ppc_closure.S: Likewise. + * src/powerpc/sysv.S: Likewise. + * src/x86/unix64.S: Likewise. + * src/x86/sysv.S: Likewise. + * src/sparc/v8.S: Likewise. + * src/sparc/v9.S: Likewise. + * src/m68k/sysv.S: Likewise. + * src/ia64/unix.S: Likewise. + * src/arm/sysv.S: Likewise. + +2008-02-26 Anthony Green + Thomas Heller + + * src/x86/ffi.c (ffi_closure_SYSV_inner): Change C++ comment to C + comment. + +2008-02-26 Anthony Green + Thomas Heller + + * include/ffi.h.in: Change void (*)() to void (*)(void). + +2008-02-26 Anthony Green + Thomas Heller + + * src/alpha/ffi.c: Change void (*)() to void (*)(void). + src/alpha/osf.S, src/arm/ffi.c, src/frv/ffi.c, src/ia64/ffi.c, + src/ia64/unix.S, src/java_raw_api.c, src/m32r/ffi.c, + src/mips/ffi.c, src/pa/ffi.c, src/pa/hpux32.S, src/pa/linux.S, + src/powerpc/ffi.c, src/powerpc/ffi_darwin.c, src/raw_api.c, + src/s390/ffi.c, src/sh/ffi.c, src/sh64/ffi.c, src/sparc/ffi.c, + src/x86/ffi.c, src/x86/unix64.S, src/x86/darwin64.S, + src/x86/ffi64.c: Ditto. + +2008-02-24 Anthony Green + + * configure.ac: Accept openbsd*, not just openbsd. + Bump version to 3.0.4. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + * libtool-version: Increment revision. + * README: Update for new release. + +2008-02-22 Anthony Green + + * README: Clean up list of tested platforms. + +2008-02-22 Anthony Green + + * configure.ac: Bump version to 3.0.3. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + * libtool-version: Increment revision. + * README: Update for new release. Clean up test docs. + +2008-02-22 Bjoern Koenig + Andreas Tobler + + * configure.ac: Add amd64-*-freebsd* target. + * configure: Regenerate. + +2008-02-22 Thomas Heller + + * configure.ac: Add x86 OpenBSD support. + * configure: Rebuilt. + +2008-02-21 Thomas Heller + + * README: Change "make test" to "make check". + +2008-02-21 Anthony Green + + * configure.ac: Bump version to 3.0.2. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + * libtool-version: Increment revision. + * README: Update for new release. + +2008-02-21 Björn König + + * src/x86/freebsd.S: New file. + * configure.ac: Add x86 FreeBSD support. + * Makefile.am: Ditto. + +2008-02-15 Anthony Green + + * configure.ac: Bump version to 3.0.1. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + * libtool-version: Increment revision. + * README: Update for new release. + +2008-02-15 David Daney + + * src/mips/ffi.c: Remove extra '>' from include directive. + (ffi_prep_closure_loc): Use clear_location instead of tramp. + +2008-02-15 Anthony Green + + * configure.ac: Bump version to 3.0.0. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + +2008-02-15 David Daney + + * src/mips/ffi.c (USE__BUILTIN___CLEAR_CACHE): + Define (conditionally), and use it to include cachectl.h. + (ffi_prep_closure_loc): Fix cache flushing. + * src/mips/ffitarget.h (_ABIN32, _ABI64, _ABIO32): Define. + +2008-02-15 Anthony Green + + * man/ffi_call.3, man/ffi_prep_cif.3, man/ffi.3: + Update dates and remove all references to ffi_prep_closure. + * configure.ac: Bump version to 2.99.9. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + +2008-02-15 Anthony Green + + * man/ffi_prep_closure.3: Delete. + * man/Makefile.am (EXTRA_DIST): Remove ffi_prep_closure.3. + (man_MANS): Ditto. + * man/Makefile.in: Rebuilt. + * configure.ac: Bump version to 2.99.8. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + +2008-02-14 Anthony Green + + * configure.ac: Bump version to 2.99.7. + * configure, doc/stamp-vti, doc/version.texi: Rebuilt. + * include/ffi.h.in LICENSE src/debug.c src/closures.c + src/ffitest.c src/s390/sysv.S src/s390/ffitarget.h + src/types.c src/m68k/ffitarget.h src/raw_api.c src/frv/ffi.c + src/frv/ffitarget.h src/sh/ffi.c src/sh/sysv.S + src/sh/ffitarget.h src/powerpc/ffitarget.h src/pa/ffi.c + src/pa/ffitarget.h src/pa/linux.S src/java_raw_api.c + src/cris/ffitarget.h src/x86/ffi.c src/x86/sysv.S + src/x86/unix64.S src/x86/win32.S src/x86/ffitarget.h + src/x86/ffi64.c src/x86/darwin.S src/ia64/ffi.c + src/ia64/ffitarget.h src/ia64/ia64_flags.h src/ia64/unix.S + src/sparc/ffi.c src/sparc/v9.S src/sparc/ffitarget.h + src/sparc/v8.S src/alpha/ffi.c src/alpha/ffitarget.h + src/alpha/osf.S src/sh64/ffi.c src/sh64/sysv.S + src/sh64/ffitarget.h src/mips/ffi.c src/mips/ffitarget.h + src/mips/n32.S src/mips/o32.S src/arm/ffi.c src/arm/sysv.S + src/arm/ffitarget.h src/prep_cif.c: Update license text. + +2008-02-14 Anthony Green + + * README: Update tested platforms. + * configure.ac: Bump version to 2.99.6. + * configure: Rebuilt. + +2008-02-14 Anthony Green + + * configure.ac: Bump version to 2.99.5. + * configure: Rebuilt. + * Makefile.am (EXTRA_DIST): Add darwin64.S + * Makefile.in: Rebuilt. + * testsuite/lib/libffi-dg.exp: Remove libstdc++ bits from GCC tree. + * LICENSE: Update WARRANTY. + +2008-02-14 Anthony Green + + * libffi.pc.in (libdir): Fix libdir definition. + * configure.ac: Bump version to 2.99.4. + * configure: Rebuilt. + +2008-02-14 Anthony Green + + * README: Update. + * libffi.info: New file. + * doc/stamp-vti: New file. + * configure.ac: Bump version to 2.99.3. + * configure: Rebuilt. + +2008-02-14 Anthony Green + + * Makefile.am (SUBDIRS): Add man dir. + * Makefile.in: Rebuilt. + * configure.ac: Create Makefile. + * configure: Rebuilt. + * man/ffi_call.3 man/ffi_prep_cif.3 man/ffi_prep_closure.3 + man/Makefile.am man/Makefile.in: New files. + +2008-02-14 Tom Tromey + + * aclocal.m4, Makefile.in, configure, fficonfig.h.in: Rebuilt. + * mdate-sh, texinfo.tex: New files. + * Makefile.am (info_TEXINFOS): New variable. + * doc/libffi.texi: New file. + * doc/version.texi: Likewise. + +2008-02-14 Anthony Green + + * Makefile.am (AM_CFLAGS): Don't compile with -D$(TARGET). + (lib_LTLIBRARIES): Define. + (toolexeclib_LIBRARIES): Undefine. + * Makefile.in: Rebuilt. + * configure.ac: Reset version to 2.99.1. + * configure.in: Rebuilt. + +2008-02-14 Anthony Green + + * libffi.pc.in: Use @PACKAGE_NAME@ and @PACKAGE_VERSION@. + * configure.ac: Reset version to 2.99.1. + * configure.in: Rebuilt. + * Makefile.am (EXTRA_DIST): Add ChangeLog.libffi. + * Makefile.in: Rebuilt. + * LICENSE: Update copyright notice. + +2008-02-14 Anthony Green + + * include/Makefile.am (nodist_includes_HEADERS): Define. Don't + distribute ffitarget.h or ffi.h from the build include dir. + * Makefile.in: Rebuilt. + +2008-02-14 Anthony Green + + * include/Makefile.am (includesdir): Install headers under libdir. + (pkgconfigdir): Define. Install libffi.pc. + * include/Makefile.in: Rebuilt. + * libffi.pc.in: Create. + * libtool-version: Increment CURRENT + * configure.ac: Add libffi.pc.in + * configure: Rebuilt. + +2008-02-03 Anthony Green + + * include/Makefile.am (includesdir): Fix header install with + DESTDIR. + * include/Makefile.in: Rebuilt. + +2008-02-03 Timothy Wall + + * src/x86/ffi.c (FFI_INIT_TRAMPOLINE_STDCALL): Calculate jump return + offset based on code pointer, not data pointer. + +2008-02-01 Anthony Green + + * include/Makefile.am: Fix header installs. + * Makefile.am: Ditto. + * include/Makefile.in: Rebuilt. + * Makefile.in: Ditto. + +2008-02-01 Anthony Green + + * src/x86/ffi.c (FFI_INIT_TRAMPOLINE_STDCALL, + FFI_INIT_TRAMPOLINE): Revert my broken changes to twall's last + patch. + +2008-01-31 Anthony Green + + * Makefile.am (EXTRA_DIST): Add missing files. + * testsuite/Makefile.am: Ditto. + * Makefile.in, testsuite/Makefile.in: Rebuilt. + +2008-01-31 Timothy Wall + + * testsuite/libffi.call/closure_stdcall.c: Add test for stdcall + closures. + * src/x86/ffitarget.h: Increase size of trampoline for stdcall + closures. + * src/x86/win32.S: Add assembly for stdcall closure. + * src/x86/ffi.c: Initialize stdcall closure trampoline. + +2008-01-30 H.J. Lu + + PR libffi/34612 + * src/x86/sysv.S (ffi_closure_SYSV): Pop 4 byte from stack when + returning struct. + + * testsuite/libffi.call/call.exp: Add "-O2 -fomit-frame-pointer" + tests. + +2008-01-30 Anthony Green + + * Makefile.am, include/Makefile.am: Move headers to + libffi_la_SOURCES for new automake. + * Makefile.in, include/Makefile.in: Rebuilt. + + * testsuite/lib/wrapper.exp: Copied from gcc tree to allow for + execution outside of gcc tree. + * testsuite/lib/target-libpath.exp: Ditto. + + * testsuite/lib/libffi-dg.exp: Many changes to allow for execution + outside of gcc tree. + + +============================================================================= +From the old ChangeLog.libgcj file.... + +2004-01-14 Kelley Cook + + * configure.in: Add in AC_PREREQ(2.13) + +2003-02-20 Alexandre Oliva + + * configure.in: Propagate ORIGINAL_LD_FOR_MULTILIBS to + config.status. + * configure: Rebuilt. + +2002-01-27 Alexandre Oliva + + * configure.in (toolexecdir, toolexeclibdir): Set and AC_SUBST. + Remove USE_LIBDIR conditional. + * Makefile.am (toolexecdir, toolexeclibdir): Don't override. + * Makefile.in, configure: Rebuilt. + +Mon Aug 9 18:33:38 1999 Rainer Orth + + * include/Makefile.in: Rebuilt. + * Makefile.in: Rebuilt + * Makefile.am (toolexeclibdir): Add $(MULTISUBDIR) even for native + builds. + Use USE_LIBDIR. + + * configure: Rebuilt. + * configure.in (USE_LIBDIR): Define for native builds. + Use lowercase in configure --help explanations. + +1999-08-08 Anthony Green + + * include/ffi.h.in (FFI_FN): Remove `...'. + +1999-08-08 Anthony Green + + * Makefile.in: Rebuilt. + * Makefile.am (AM_CFLAGS): Compile with -fexceptions. + + * src/x86/sysv.S: Add exception handling metadata. + + +============================================================================= + +The libffi version 1 ChangeLog archive. + +Version 1 of libffi had per-directory ChangeLogs. Current and future +versions have a single ChangeLog file in the root directory. The +version 1 ChangeLogs have all been concatenated into this file for +future reference only. + +--- libffi ---------------------------------------------------------------- + +Mon Oct 5 02:17:50 1998 Anthony Green + + * configure.in: Boosted rev. + * configure, Makefile.in, aclocal.m4: Rebuilt. + * README: Boosted rev and updated release notes. + +Mon Oct 5 01:03:03 1998 Anthony Green + + * configure.in: Boosted rev. + * configure, Makefile.in, aclocal.m4: Rebuilt. + * README: Boosted rev and updated release notes. + +1998-07-25 Andreas Schwab + + * m68k/ffi.c (ffi_prep_cif_machdep): Use bitmask for cif->flags. + Correctly handle small structures. + (ffi_prep_args): Also handle small structures. + (ffi_call): Pass size of return type to ffi_call_SYSV. + * m68k/sysv.S: Adjust for above changes. Correctly align small + structures in the return value. + + * types.c (uint64, sint64) [M68K]: Change alignment to 4. + +Fri Apr 17 17:26:58 1998 Anthony Green + + * configure.in: Boosted rev. + * configure,Makefile.in,aclocal.m4: Rebuilt. + * README: Boosted rev and added release notes. + +Sun Feb 22 00:50:41 1998 Geoff Keating + + * configure.in: Add PowerPC config bits. + +1998-02-14 Andreas Schwab + + * configure.in: Add m68k config bits. Change AC_CANONICAL_SYSTEM + to AC_CANONICAL_HOST, this is not a compiler. Use $host instead + of $target. Remove AC_CHECK_SIZEOF(char), we already know the + result. Fix argument of AC_ARG_ENABLE. + * configure, fficonfig.h.in: Rebuilt. + +Tue Feb 10 20:53:40 1998 Richard Henderson + + * configure.in: Add Alpha config bits. + +Tue May 13 13:39:20 1997 Anthony Green + + * README: Updated dates and reworded Irix comments. + + * configure.in: Removed AC_PROG_RANLIB. + + * Makefile.in, aclocal.m4, config.guess, config.sub, configure, + ltmain.sh, */Makefile.in: libtoolized again and rebuilt with + automake and autoconf. + +Sat May 10 18:44:50 1997 Tom Tromey + + * configure, aclocal.m4: Rebuilt. + * configure.in: Don't compute EXTRADIST; now handled in + src/Makefile.in. Removed macros implied by AM_INIT_AUTOMAKE. + Don't run AM_MAINTAINER_MODE. + +Thu May 8 14:34:05 1997 Anthony Green + + * missing, ltmain.sh, ltconfig.sh: Created. These are new files + required by automake and libtool. + + * README: Boosted rev to 1.14. Added notes. + + * acconfig.h: Moved PACKAGE and VERSION for new automake. + + * configure.in: Changes for libtool. + + * Makefile.am (check): make test now make check. Uses libtool now. + + * Makefile.in, configure.in, aclocal.h, fficonfig.h.in: Rebuilt. + +Thu May 1 16:27:07 1997 Anthony Green + + * missing: Added file required by new automake. + +Tue Nov 26 14:10:42 1996 Anthony Green + + * acconfig.h: Added USING_PURIFY flag. This is defined when + --enable-purify-safety was used at configure time. + + * configure.in (allsources): Added --enable-purify-safety switch. + (VERSION): Boosted rev to 1.13. + * configure: Rebuilt. + +Fri Nov 22 06:46:12 1996 Anthony Green + + * configure.in (VERSION): Boosted rev to 1.12. + Removed special CFLAGS hack for gcc. + * configure: Rebuilt. + + * README: Boosted rev to 1.12. Added notes. + + * Many files: Cygnus Support changed to Cygnus Solutions. + +Wed Oct 30 11:15:25 1996 Anthony Green + + * configure.in (VERSION): Boosted rev to 1.11. + * configure: Rebuilt. + + * README: Boosted rev to 1.11. Added notes about GNU make. + +Tue Oct 29 12:25:12 1996 Anthony Green + + * configure.in: Fixed -Wall trick. + (VERSION): Boosted rev. + * configure: Rebuilt + + * acconfig.h: Needed for --enable-debug configure switch. + + * README: Boosted rev to 1.09. Added more notes on building + libffi, and LCLint. + + * configure.in: Added --enable-debug switch. Boosted rev to + 1.09. + * configure: Rebuilt + +Tue Oct 15 13:11:28 1996 Anthony Green + + * configure.in (VERSION): Boosted rev to 1.08 + * configure: Rebuilt. + + * README: Added n32 bug fix notes. + + * Makefile.am: Added "make lint" production. + * Makefile.in: Rebuilt. + +Mon Oct 14 10:54:46 1996 Anthony Green + + * README: Added web page reference. + + * configure.in, README: Boosted rev to 1.05 + * configure: Rebuilt. + + * README: Fixed n32 sample code. + +Fri Oct 11 17:09:28 1996 Anthony Green + + * README: Added sparc notes. + + * configure.in, README: Boosted rev to 1.04. + * configure: Rebuilt. + +Thu Oct 10 10:31:03 1996 Anthony Green + + * configure.in, README: Boosted rev to 1.03. + * configure: Rebuilt. + + * README: Added struct notes. + + * Makefile.am (EXTRA_DIST): Added LICENSE to distribution. + * Makefile.in: Rebuilt. + + * README: Removed Linux section. No special notes now + because aggregates arg/return types work. + +Wed Oct 9 16:16:42 1996 Anthony Green + + * README, configure.in (VERSION): Boosted rev to 1.02 + * configure: Rebuilt. + +Tue Oct 8 11:56:33 1996 Anthony Green + + * README (NOTE): Added n32 notes. + + * Makefile.am: Added test production. + * Makefile: Rebuilt + + * README: spell checked! + + * configure.in (VERSION): Boosted rev to 1.01 + * configure: Rebuilt. + +Mon Oct 7 15:50:22 1996 Anthony Green + + * configure.in: Added nasty bit to support SGI tools. + * configure: Rebuilt. + + * README: Added SGI notes. Added note about automake bug. + +Mon Oct 7 11:00:28 1996 Anthony Green + + * README: Rewrote intro, and fixed examples. + +Fri Oct 4 10:19:55 1996 Anthony Green + + * configure.in: -D$TARGET is no longer used as a compiler switch. + It is now inserted into ffi.h at configure time. + * configure: Rebuilt. + + * FFI_ABI and FFI_STATUS are now ffi_abi and ffi_status. + +Thu Oct 3 13:47:34 1996 Anthony Green + + * README, LICENSE: Created. Wrote some docs. + + * configure.in: Don't barf on i586-unknown-linuxaout. + Added EXTRADIST code for "make dist". + * configure: Rebuilt. + + * */Makefile.in: Rebuilt with patched automake. + +Tue Oct 1 17:12:25 1996 Anthony Green + + * Makefile.am, aclocal.m4, config.guess, config.sub, + configure.in, fficonfig.h.in, install-sh, mkinstalldirs, + stamp-h.in: Created + * Makefile.in, configure: Generated + +--- libffi/include -------------------------------------------------------- + +Tue Feb 24 13:09:36 1998 Anthony Green + + * ffi_mips.h: Updated FFI_TYPE_STRUCT_* values based on + ffi.h.in changes. This is a work-around for SGI's "simple" + assembler. + +Sun Feb 22 00:51:55 1998 Geoff Keating + + * ffi.h.in: PowerPC support. + +1998-02-14 Andreas Schwab + + * ffi.h.in: Add m68k support. + (FFI_TYPE_LONGDOUBLE): Make it a separate value. + +Tue Feb 10 20:55:16 1998 Richard Henderson + + * ffi.h.in (SIZEOF_ARG): Use a pointer type by default. + + * ffi.h.in: Alpha support. + +Fri Nov 22 06:48:45 1996 Anthony Green + + * ffi.h.in, ffi_common.h: Cygnus Support -> Cygnus Solutions. + +Wed Nov 20 22:31:01 1996 Anthony Green + + * ffi.h.in: Added ffi_type_void definition. + +Tue Oct 29 12:22:40 1996 Anthony Green + + * Makefile.am (hack_DATA): Always install ffi_mips.h. + + * ffi.h.in: Removed FFI_DEBUG. It's now in the correct + place (acconfig.h). + Added #include for size_t definition. + +Tue Oct 15 17:23:35 1996 Anthony Green + + * ffi.h.in, ffi_common.h, ffi_mips.h: More clean up. + Commented out #define of FFI_DEBUG. + +Tue Oct 15 13:01:06 1996 Anthony Green + + * ffi_common.h: Added bool definition. + + * ffi.h.in, ffi_common.h: Clean up based on LCLint output. + Added funny /*@...@*/ comments to annotate source. + +Mon Oct 14 12:29:23 1996 Anthony Green + + * ffi.h.in: Interface changes based on feedback from Jim + Blandy. + +Fri Oct 11 16:49:35 1996 Anthony Green + + * ffi.h.in: Small change for sparc support. + +Thu Oct 10 14:53:37 1996 Anthony Green + + * ffi_mips.h: Added FFI_TYPE_STRUCT_* definitions for + special structure return types. + +Wed Oct 9 13:55:57 1996 Anthony Green + + * ffi.h.in: Added SIZEOF_ARG definition for X86 + +Tue Oct 8 11:40:36 1996 Anthony Green + + * ffi.h.in (FFI_FN): Added macro for eliminating compiler warnings. + Use it to case your function pointers to the proper type. + + * ffi_mips.h (SIZEOF_ARG): Added magic to fix type promotion bug. + + * Makefile.am (EXTRA_DIST): Added ffi_mips.h to EXTRA_DIST. + * Makefile: Rebuilt. + + * ffi_mips.h: Created. Moved all common mips definitions here. + +Mon Oct 7 10:58:12 1996 Anthony Green + + * ffi.h.in: The SGI assember is very picky about parens. Redefined + some macros to avoid problems. + + * ffi.h.in: Added FFI_DEFAULT_ABI definitions. Also added + externs for pointer, and 64bit integral ffi_types. + +Fri Oct 4 09:51:37 1996 Anthony Green + + * ffi.h.in: Added FFI_ABI member to ffi_cif and changed + function prototypes accordingly. + Added #define @TARGET@. Now programs including ffi.h don't + have to specify this themselves. + +Thu Oct 3 15:36:44 1996 Anthony Green + + * ffi.h.in: Changed ffi_prep_cif's values from void* to void** + + * Makefile.am (EXTRA_DIST): Added EXTRA_DIST for "make dist" + to work. + * Makefile.in: Regenerated. + +Wed Oct 2 10:16:59 1996 Anthony Green + + * Makefile.am: Created + * Makefile.in: Generated + + * ffi_common.h: Added rcsid comment + +Tue Oct 1 17:13:51 1996 Anthony Green + + * ffi.h.in, ffi_common.h: Created + +--- libffi/src ------------------------------------------------------------ + +Mon Oct 5 02:17:50 1998 Anthony Green + + * arm/ffi.c, arm/sysv.S: Created. + + * Makefile.am: Added arm files. + * Makefile.in: Rebuilt. + +Mon Oct 5 01:41:38 1998 Anthony Green + + * Makefile.am (libffi_la_LDFLAGS): Incremented revision. + +Sun Oct 4 16:27:17 1998 Anthony Green + + * alpha/osf.S (ffi_call_osf): Patch for DU assembler. + + * ffitest.c (main): long long and long double return values work + for x86. + +Fri Apr 17 11:50:58 1998 Anthony Green + + * Makefile.in: Rebuilt. + + * ffitest.c (main): Floating point tests not executed for systems + with broken lond double (SunOS 4 w/ GCC). + + * types.c: Fixed x86 alignment info for long long types. + +Thu Apr 16 07:15:28 1998 Anthony Green + + * ffitest.c: Added more notes about GCC bugs under Irix 6. + +Wed Apr 15 08:42:22 1998 Anthony Green + + * ffitest.c (struct5): New test function. + (main): New test with struct5. + +Thu Mar 5 10:48:11 1998 Anthony Green + + * prep_cif.c (initialize_aggregate): Fix assertion for + nested structures. + +Tue Feb 24 16:33:41 1998 Anthony Green + + * prep_cif.c (ffi_prep_cif): Added long double support for sparc. + +Sun Feb 22 00:52:18 1998 Geoff Keating + + * powerpc/asm.h: New file. + * powerpc/ffi.c: New file. + * powerpc/sysv.S: New file. + * Makefile.am: PowerPC port. + * ffitest.c (main): Allow all tests to run even in presence of gcc + bug on PowerPC. + +1998-02-17 Anthony Green + + * mips/ffi.c: Fixed comment typo. + + * x86/ffi.c (ffi_prep_cif_machdep), x86/sysv.S (retfloat): + Fixed x86 long double return handling. + + * types.c: Fixed x86 long double alignment info. + +1998-02-14 Andreas Schwab + + * types.c: Add m68k support. + + * ffitest.c (floating): Add long double parameter. + (return_ll, ldblit): New functions to test long long and long + double return value. + (main): Fix type error in assignment of ts[1-4]_type.elements. + Add tests for long long and long double arguments and return + values. + + * prep_cif.c (ffi_prep_cif) [M68K]: Don't allocate argument for + struct value pointer. + + * m68k/ffi.c, m68k/sysv.S: New files. + * Makefile.am: Add bits for m68k port. Add kludge to work around + automake deficiency. + (test): Don't require "." in $PATH. + * Makefile.in: Rebuilt. + +Wed Feb 11 07:36:50 1998 Anthony Green + + * Makefile.in: Rebuilt. + +Tue Feb 10 20:56:00 1998 Richard Henderson + + * alpha/ffi.c, alpha/osf.S: New files. + * Makefile.am: Alpha port. + +Tue Nov 18 14:12:07 1997 Anthony Green + + * mips/ffi.c (ffi_prep_cif_machdep): Initialize rstruct_flag + for n32. + +Tue Jun 3 17:18:20 1997 Anthony Green + + * ffitest.c (main): Added hack to get structure tests working + correctly. + +Sat May 10 19:06:42 1997 Tom Tromey + + * Makefile.in: Rebuilt. + * Makefile.am (EXTRA_DIST): Explicitly list all distributable + files in subdirs. + (VERSION, CC): Removed. + +Thu May 8 17:19:01 1997 Anthony Green + + * Makefile.am: Many changes for new automake and libtool. + * Makefile.in: Rebuilt. + +Fri Nov 22 06:57:56 1996 Anthony Green + + * ffitest.c (main): Fixed test case for non mips machines. + +Wed Nov 20 22:31:59 1996 Anthony Green + + * types.c: Added ffi_type_void declaration. + +Tue Oct 29 13:07:19 1996 Anthony Green + + * ffitest.c (main): Fixed character constants. + (main): Emit warning for structure test 3 failure on Sun. + + * Makefile.am (VPATH): Fixed VPATH def'n so automake won't + strip it out. + Moved distdir hack from libffi to automake. + (ffitest): Added missing -c for $(COMPILE) (change in automake). + * Makefile.in: Rebuilt. + +Tue Oct 15 13:08:20 1996 Anthony Green + + * Makefile.am: Added "make lint" production. + * Makefile.in: Rebuilt. + + * prep_cif.c (STACK_ARG_SIZE): Improved STACK_ARG_SIZE macro. + Clean up based on LCLint output. Added funny /*@...@*/ comments to + annotate source. + + * ffitest.c, debug.c: Cleaned up code. + +Mon Oct 14 12:26:56 1996 Anthony Green + + * ffitest.c: Changes based on interface changes. + + * prep_cif.c (ffi_prep_cif): Cleaned up interface based on + feedback from Jim Blandy. + +Fri Oct 11 15:53:18 1996 Anthony Green + + * ffitest.c: Reordered tests while porting to sparc. + Made changes to handle lame structure passing for sparc. + Removed calls to fflush(). + + * prep_cif.c (ffi_prep_cif): Added special case for sparc + aggregate type arguments. + +Thu Oct 10 09:56:51 1996 Anthony Green + + * ffitest.c (main): Added structure passing/returning tests. + + * prep_cif.c (ffi_prep_cif): Perform proper initialization + of structure return types if needed. + (initialize_aggregate): Bug fix + +Wed Oct 9 16:04:20 1996 Anthony Green + + * types.c: Added special definitions for x86 (double doesn't + need double word alignment). + + * ffitest.c: Added many tests + +Tue Oct 8 09:19:22 1996 Anthony Green + + * prep_cif.c (ffi_prep_cif): Fixed assertion. + + * debug.c (ffi_assert): Must return a non void now. + + * Makefile.am: Added test production. + * Makefile: Rebuilt. + + * ffitest.c (main): Created. + + * types.c: Created. Stripped common code out of */ffi.c. + + * prep_cif.c: Added missing stdlib.h include. + + * debug.c (ffi_type_test): Used "a" to eliminate compiler + warnings in non-debug builds. Included ffi_common.h. + +Mon Oct 7 15:36:42 1996 Anthony Green + + * Makefile.am: Added a rule for .s -> .o + This is required by the SGI compiler. + * Makefile: Rebuilt. + +Fri Oct 4 09:51:08 1996 Anthony Green + + * prep_cif.c (initialize_aggregate): Moved abi specification + to ffi_prep_cif(). + +Thu Oct 3 15:37:37 1996 Anthony Green + + * prep_cif.c (ffi_prep_cif): Changed values from void* to void**. + (initialize_aggregate): Fixed aggregate type initialization. + + * Makefile.am (EXTRA_DIST): Added support code for "make dist". + * Makefile.in: Regenerated. + +Wed Oct 2 11:41:57 1996 Anthony Green + + * debug.c, prep_cif: Created. + + * Makefile.am: Added debug.o and prep_cif.o to OBJ. + * Makefile.in: Regenerated. + + * Makefile.am (INCLUDES): Added missing -I../include + * Makefile.in: Regenerated. + +Tue Oct 1 17:11:51 1996 Anthony Green + + * error.c, Makefile.am: Created. + * Makefile.in: Generated. + +--- libffi/src/x86 -------------------------------------------------------- + +Sun Oct 4 16:27:17 1998 Anthony Green + + * sysv.S (retlongdouble): Fixed long long return value support. + * ffi.c (ffi_prep_cif_machdep): Ditto. + +Wed May 13 04:30:33 1998 Anthony Green + + * ffi.c (ffi_prep_cif_machdep): Fixed long double return value + support. + +Wed Apr 15 08:43:20 1998 Anthony Green + + * ffi.c (ffi_prep_args): small struct support was missing. + +Thu May 8 16:53:58 1997 Anthony Green + + * objects.mak: Removed. + +Mon Dec 2 15:12:58 1996 Tom Tromey + + * sysv.S: Use .balign, for a.out Linux boxes. + +Tue Oct 15 13:06:50 1996 Anthony Green + + * ffi.c: Clean up based on LCLint output. + Added funny /*@...@*/ comments to annotate source. + +Fri Oct 11 16:43:38 1996 Anthony Green + + * ffi.c (ffi_call): Added assertion for bad ABIs. + +Wed Oct 9 13:57:27 1996 Anthony Green + + * sysv.S (retdouble): Fixed double return problems. + + * ffi.c (ffi_call): Corrected fn arg definition. + (ffi_prep_cif_machdep): Fixed double return problems + +Tue Oct 8 12:12:49 1996 Anthony Green + + * ffi.c: Moved ffi_type definitions to types.c. + (ffi_prep_args): Fixed type promotion bug. + +Mon Oct 7 15:53:06 1996 Anthony Green + + * ffi.c (FFI_*_TYPEDEF): Removed redundant ';' + +Fri Oct 4 09:54:53 1996 Anthony Green + + * ffi.c (ffi_call): Removed FFI_ABI arg, and swapped + remaining args. + +Wed Oct 2 10:07:05 1996 Anthony Green + + * ffi.c, sysv.S, objects.mak: Created. + (ffi_prep_cif): cif->rvalue no longer initialized to NULL. + (ffi_prep_cif_machdep): Moved machine independent cif processing + to src/prep_cif.c. Introduced ffi_prep_cif_machdep(). + +--- libffi/src/mips ------------------------------------------------------- + +Tue Feb 17 17:18:07 1998 Anthony Green + + * o32.S: Fixed typo in comment. + + * ffi.c (ffi_prep_cif_machdep): Fixed argument processing. + +Thu May 8 16:53:58 1997 Anthony Green + + * o32.s, n32.s: Wrappers for SGI tool support. + + * objects.mak: Removed. + +Tue Oct 29 14:37:45 1996 Anthony Green + + * ffi.c (ffi_prep_args): Changed int z to size_t z. + +Tue Oct 15 13:17:25 1996 Anthony Green + + * n32.S: Fixed bad stack munging. + + * ffi.c: Moved prototypes for ffi_call_?32() to here from + ffi_mips.h because extended_cif is not defined in ffi_mips.h. + +Mon Oct 14 12:42:02 1996 Anthony Green + + * ffi.c: Interface changes based on feedback from Jim Blandy. + +Thu Oct 10 11:22:16 1996 Anthony Green + + * n32.S, ffi.c: Lots of changes to support passing and + returning structures with the n32 calling convention. + + * n32.S: Fixed fn pointer bug. + + * ffi.c (ffi_prep_cif_machdep): Fix for o32 structure + return values. + (ffi_prep_args): Fixed n32 structure passing when structures + partially fit in registers. + +Wed Oct 9 13:49:25 1996 Anthony Green + + * objects.mak: Added n32.o. + + * n32.S: Created. + + * ffi.c (ffi_prep_args): Added magic to support proper + n32 processing. + +Tue Oct 8 10:37:35 1996 Anthony Green + + * ffi.c: Moved ffi_type definitions to types.c. + (ffi_prep_args): Fixed type promotion bug. + + * o32.S: This code is only built for o32 compiles. + A lot of the #define cruft has moved to ffi_mips.h. + + * ffi.c (ffi_prep_cif_machdep): Fixed arg flags. Second arg + is only processed if the first is either a float or double. + +Mon Oct 7 15:33:59 1996 Anthony Green + + * o32.S: Modified to compile under each of o32, n32 and n64. + + * ffi.c (FFI_*_TYPEDEF): Removed redundant ';' + +Fri Oct 4 09:53:25 1996 Anthony Green + + * ffi.c (ffi_call): Removed FFI_ABI arg, and swapped + remaining args. + +Wed Oct 2 17:41:22 1996 Anthony Green + + * o32.S: Removed crufty definitions. + +Wed Oct 2 12:53:42 1996 Anthony Green + + * ffi.c (ffi_prep_cif): cif->rvalue no longer initialized to NULL. + (ffi_prep_cif_machdep): Moved all machine independent cif processing + to src/prep_cif.c. Introduced ffi_prep_cif_machdep. Return types + of FFI_TYPE_STRUCT are no different than FFI_TYPE_INT. + +Tue Oct 1 17:11:02 1996 Anthony Green + + * ffi.c, o32.S, object.mak: Created + +--- libffi/src/sparc ------------------------------------------------------ + +Tue Feb 24 16:33:18 1998 Anthony Green + + * ffi.c (ffi_prep_args): Added long double support. + +Thu May 8 16:53:58 1997 Anthony Green + + * objects.mak: Removed. + +Thu May 1 16:07:56 1997 Anthony Green + + * v8.S: Fixed minor portability problem reported by + Russ McManus . + +Tue Nov 26 14:12:43 1996 Anthony Green + + * v8.S: Used STACKFRAME define elsewhere. + + * ffi.c (ffi_prep_args): Zero out space when USING_PURIFY + is set. + (ffi_prep_cif_machdep): Allocate the correct stack frame + space for functions with < 6 args. + +Tue Oct 29 15:08:55 1996 Anthony Green + + * ffi.c (ffi_prep_args): int z is now size_t z. + +Mon Oct 14 13:31:24 1996 Anthony Green + + * v8.S (ffi_call_V8): Gordon rewrites this again. It looks + great now. + + * ffi.c (ffi_call): The comment about hijacked registers + is no longer valid after gordoni hacked v8.S. + + * v8.S (ffi_call_V8): Rewrote with gordoni. Much simpler. + + * v8.S, ffi.c: ffi_call() had changed to accept more than + two args, so v8.S had to change (because it hijacks incoming + arg registers). + + * ffi.c: Interface changes based on feedback from Jim Blandy. + +Thu Oct 10 17:48:16 1996 Anthony Green + + * ffi.c, v8.S, objects.mak: Created. + + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/LICENSE b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/LICENSE new file mode 100644 index 0000000..4f0b762 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/LICENSE @@ -0,0 +1,21 @@ +libffi - Copyright (c) 1996-2020 Anthony Green, Red Hat, Inc and others. +See source files for details. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/LICENSE-BUILDTOOLS b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/LICENSE-BUILDTOOLS new file mode 100644 index 0000000..d1d626e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/LICENSE-BUILDTOOLS @@ -0,0 +1,353 @@ +The libffi source distribution contains certain code that is not part +of libffi, and is only used as tooling to assist with the building and +testing of libffi. This includes the msvcc.sh script used to wrap the +Microsoft compiler with GNU compatible command-line options, +make_sunver.pl, and the libffi test code distributed in the +testsuite/libffi.bhaible directory. This code is distributed with +libffi for the purpose of convenience only, and libffi is in no way +derived from this code. + +msvcc.sh an testsuite/libffi.bhaible are both distributed under the +terms of the GNU GPL version 2, as below. + + + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/Makefile.am b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/Makefile.am new file mode 100644 index 0000000..7654bf5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/Makefile.am @@ -0,0 +1,150 @@ +## Process this with automake to create Makefile.in + +AUTOMAKE_OPTIONS = foreign subdir-objects + +ACLOCAL_AMFLAGS = -I m4 + +SUBDIRS = include testsuite man +if BUILD_DOCS +## This hack is needed because it doesn't seem possible to make a +## conditional info_TEXINFOS in Automake. At least Automake 1.14 +## either gives errors -- if this attempted in the most +## straightforward way -- or simply unconditionally tries to build the +## info file. +SUBDIRS += doc +endif + +EXTRA_DIST = LICENSE ChangeLog.old \ + m4/libtool.m4 m4/lt~obsolete.m4 \ + m4/ltoptions.m4 m4/ltsugar.m4 m4/ltversion.m4 \ + m4/ltversion.m4 src/debug.c msvcc.sh \ + generate-darwin-source-and-headers.py \ + libffi.xcodeproj/project.pbxproj \ + libtool-ldflags libtool-version configure.host README.md \ + libffi.map.in LICENSE-BUILDTOOLS msvc_build make_sunver.pl + +# local.exp is generated by configure +DISTCLEANFILES = local.exp + +# Subdir rules rely on $(FLAGS_TO_PASS) +FLAGS_TO_PASS = $(AM_MAKEFLAGS) + +MAKEOVERRIDES= + +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = libffi.pc + +toolexeclib_LTLIBRARIES = libffi.la +noinst_LTLIBRARIES = libffi_convenience.la + +libffi_la_SOURCES = src/prep_cif.c src/types.c \ + src/raw_api.c src/java_raw_api.c src/closures.c + +if FFI_DEBUG +libffi_la_SOURCES += src/debug.c +endif + +noinst_HEADERS = src/aarch64/ffitarget.h src/aarch64/internal.h \ + src/alpha/ffitarget.h src/alpha/internal.h \ + src/arc/ffitarget.h src/arm/ffitarget.h src/arm/internal.h \ + src/avr32/ffitarget.h src/bfin/ffitarget.h \ + src/cris/ffitarget.h src/csky/ffitarget.h src/frv/ffitarget.h \ + src/ia64/ffitarget.h src/ia64/ia64_flags.h \ + src/m32r/ffitarget.h src/m68k/ffitarget.h \ + src/m88k/ffitarget.h src/metag/ffitarget.h \ + src/microblaze/ffitarget.h src/mips/ffitarget.h \ + src/moxie/ffitarget.h src/nios2/ffitarget.h \ + src/or1k/ffitarget.h src/pa/ffitarget.h \ + src/powerpc/ffitarget.h src/powerpc/asm.h \ + src/powerpc/ffi_powerpc.h src/riscv/ffitarget.h \ + src/s390/ffitarget.h src/s390/internal.h src/sh/ffitarget.h \ + src/sh64/ffitarget.h src/sparc/ffitarget.h \ + src/sparc/internal.h src/tile/ffitarget.h src/vax/ffitarget.h \ + src/x86/ffitarget.h src/x86/internal.h src/x86/internal64.h \ + src/x86/asmnames.h src/xtensa/ffitarget.h src/dlmalloc.c \ + src/kvx/ffitarget.h + +EXTRA_libffi_la_SOURCES = src/aarch64/ffi.c src/aarch64/sysv.S \ + src/aarch64/win64_armasm.S src/alpha/ffi.c src/alpha/osf.S \ + src/arc/ffi.c src/arc/arcompact.S src/arm/ffi.c \ + src/arm/sysv.S src/arm/ffi.c src/arm/sysv_msvc_arm32.S \ + src/avr32/ffi.c src/avr32/sysv.S src/bfin/ffi.c \ + src/bfin/sysv.S src/cris/ffi.c src/cris/sysv.S src/frv/ffi.c \ + src/csky/ffi.c src/csky/sysv.S src/frv/eabi.S src/ia64/ffi.c \ + src/ia64/unix.S src/m32r/ffi.c src/m32r/sysv.S src/m68k/ffi.c \ + src/m68k/sysv.S src/m88k/ffi.c src/m88k/obsd.S \ + src/metag/ffi.c src/metag/sysv.S src/microblaze/ffi.c \ + src/microblaze/sysv.S src/mips/ffi.c src/mips/o32.S \ + src/mips/n32.S src/moxie/ffi.c src/moxie/eabi.S \ + src/nios2/ffi.c src/nios2/sysv.S src/or1k/ffi.c \ + src/or1k/sysv.S src/pa/ffi.c src/pa/linux.S src/pa/hpux32.S \ + src/powerpc/ffi.c src/powerpc/ffi_sysv.c \ + src/powerpc/ffi_linux64.c src/powerpc/sysv.S \ + src/powerpc/linux64.S src/powerpc/linux64_closure.S \ + src/powerpc/ppc_closure.S src/powerpc/aix.S \ + src/powerpc/darwin.S src/powerpc/aix_closure.S \ + src/powerpc/darwin_closure.S src/powerpc/ffi_darwin.c \ + src/riscv/ffi.c src/riscv/sysv.S src/s390/ffi.c \ + src/s390/sysv.S src/sh/ffi.c src/sh/sysv.S src/sh64/ffi.c \ + src/sh64/sysv.S src/sparc/ffi.c src/sparc/ffi64.c \ + src/sparc/v8.S src/sparc/v9.S src/tile/ffi.c src/tile/tile.S \ + src/vax/ffi.c src/vax/elfbsd.S src/x86/ffi.c src/x86/sysv.S \ + src/x86/ffiw64.c src/x86/win64.S src/x86/ffi64.c \ + src/x86/unix64.S src/x86/sysv_intel.S src/x86/win64_intel.S \ + src/xtensa/ffi.c src/xtensa/sysv.S src/kvx/ffi.c \ + src/kvx/sysv.S + +TARGET_OBJ = @TARGET_OBJ@ +libffi_la_LIBADD = $(TARGET_OBJ) + +libffi_convenience_la_SOURCES = $(libffi_la_SOURCES) +EXTRA_libffi_convenience_la_SOURCES = $(EXTRA_libffi_la_SOURCES) +libffi_convenience_la_LIBADD = $(libffi_la_LIBADD) +libffi_convenience_la_DEPENDENCIES = $(libffi_la_DEPENDENCIES) +nodist_libffi_convenience_la_SOURCES = $(nodist_libffi_la_SOURCES) + +LTLDFLAGS = $(shell $(SHELL) $(top_srcdir)/libtool-ldflags $(LDFLAGS)) + +AM_CFLAGS = +if FFI_DEBUG +# Build debug. Define FFI_DEBUG on the commandline so that, when building with +# MSVC, it can link against the debug CRT. +AM_CFLAGS += -DFFI_DEBUG +endif + +if LIBFFI_BUILD_VERSIONED_SHLIB +if LIBFFI_BUILD_VERSIONED_SHLIB_GNU +libffi_version_script = -Wl,--version-script,libffi.map +libffi_version_dep = libffi.map +endif +if LIBFFI_BUILD_VERSIONED_SHLIB_SUN +libffi_version_script = -Wl,-M,libffi.map-sun +libffi_version_dep = libffi.map-sun +libffi.map-sun : libffi.map $(top_srcdir)/make_sunver.pl \ + $(libffi_la_OBJECTS) $(libffi_la_LIBADD) + perl $(top_srcdir)/make_sunver.pl libffi.map \ + `echo $(libffi_la_OBJECTS) $(libffi_la_LIBADD) | \ + sed 's,\([^/ ]*\)\.l\([ao]\),.libs/\1.\2,g'` \ + > $@ || (rm -f $@ ; exit 1) +endif +else +libffi_version_script = +libffi_version_dep = +endif +libffi_version_info = -version-info `grep -v '^\#' $(srcdir)/libtool-version` + +libffi.map: $(top_srcdir)/libffi.map.in + $(COMPILE) -D$(TARGET) -DGENERATE_LIBFFI_MAP \ + -E -x assembler-with-cpp -o $@ $(top_srcdir)/libffi.map.in + +libffi_la_LDFLAGS = -no-undefined $(libffi_version_info) $(libffi_version_script) $(LTLDFLAGS) $(AM_LTLDFLAGS) +libffi_la_DEPENDENCIES = $(libffi_la_LIBADD) $(libffi_version_dep) + +AM_CPPFLAGS = -I. -I$(top_srcdir)/include -Iinclude -I$(top_srcdir)/src +AM_CCASFLAGS = $(AM_CPPFLAGS) + +dist-hook: + d=`(cd $(distdir); pwd)`; (cd doc; make pdf; cp *.pdf $$d/doc) + if [ -d $(top_srcdir)/.git ] ; then (cd $(top_srcdir); git log --no-decorate) ; else echo 'See git log for history.' ; fi > $(distdir)/ChangeLog + s=`awk '/was released on/{ print NR; exit}' $(top_srcdir)/README.md`; tail -n +$$(($$s-1)) $(top_srcdir)/README.md > $(distdir)/README.md + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/README.md b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/README.md new file mode 100644 index 0000000..4225d85 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/README.md @@ -0,0 +1,486 @@ +Status +====== + +[![Build Status](https://travis-ci.org/libffi/libffi.svg?branch=master)](https://travis-ci.org/libffi/libffi) +[![Build status](https://ci.appveyor.com/api/projects/status/8lko9vagbx4w2kxq?svg=true)](https://ci.appveyor.com/project/atgreen/libffi) + +libffi-3.4 was released on TBD. Check the libffi web +page for updates: . + + +What is libffi? +=============== + +Compilers for high level languages generate code that follow certain +conventions. These conventions are necessary, in part, for separate +compilation to work. One such convention is the "calling +convention". The "calling convention" is essentially a set of +assumptions made by the compiler about where function arguments will +be found on entry to a function. A "calling convention" also specifies +where the return value for a function is found. + +Some programs may not know at the time of compilation what arguments +are to be passed to a function. For instance, an interpreter may be +told at run-time about the number and types of arguments used to call +a given function. Libffi can be used in such programs to provide a +bridge from the interpreter program to compiled code. + +The libffi library provides a portable, high level programming +interface to various calling conventions. This allows a programmer to +call any function specified by a call interface description at run +time. + +FFI stands for Foreign Function Interface. A foreign function +interface is the popular name for the interface that allows code +written in one language to call code written in another language. The +libffi library really only provides the lowest, machine dependent +layer of a fully featured foreign function interface. A layer must +exist above libffi that handles type conversions for values passed +between the two languages. + + +Supported Platforms +=================== + +Libffi has been ported to many different platforms. + +At the time of release, the following basic configurations have been +tested: + +| Architecture | Operating System | Compiler | +| --------------- | ---------------- | ----------------------- | +| AArch64 (ARM64) | iOS | Clang | +| AArch64 | Linux | GCC | +| AArch64 | Windows | MSVC | +| Alpha | Linux | GCC | +| Alpha | Tru64 | GCC | +| ARC | Linux | GCC | +| ARM | Linux | GCC | +| ARM | iOS | GCC | +| ARM | Windows | MSVC | +| AVR32 | Linux | GCC | +| Blackfin | uClinux | GCC | +| CSKY | Linux | GCC | +| HPPA | HPUX | GCC | +| KVX | Linux | GCC | +| IA-64 | Linux | GCC | +| M68K | FreeMiNT | GCC | +| M68K | Linux | GCC | +| M68K | RTEMS | GCC | +| M88K | OpenBSD/mvme88k | GCC | +| Meta | Linux | GCC | +| MicroBlaze | Linux | GCC | +| MIPS | IRIX | GCC | +| MIPS | Linux | GCC | +| MIPS | RTEMS | GCC | +| MIPS64 | Linux | GCC | +| Moxie | Bare metal | GCC | +| Nios II | Linux | GCC | +| OpenRISC | Linux | GCC | +| PowerPC 32-bit | AIX | IBM XL C | +| PowerPC 64-bit | AIX | IBM XL C | +| PowerPC | AMIGA | GCC | +| PowerPC | Linux | GCC | +| PowerPC | Mac OSX | GCC | +| PowerPC | FreeBSD | GCC | +| PowerPC 64-bit | FreeBSD | GCC | +| PowerPC 64-bit | Linux ELFv1 | GCC | +| PowerPC 64-bit | Linux ELFv2 | GCC | +| RISC-V 32-bit | Linux | GCC | +| RISC-V 64-bit | Linux | GCC | +| S390 | Linux | GCC | +| S390X | Linux | GCC | +| SPARC | Linux | GCC | +| SPARC | Solaris | GCC | +| SPARC | Solaris | Oracle Solaris Studio C | +| SPARC64 | Linux | GCC | +| SPARC64 | FreeBSD | GCC | +| SPARC64 | Solaris | Oracle Solaris Studio C | +| TILE-Gx/TILEPro | Linux | GCC | +| VAX | OpenBSD/vax | GCC | +| X86 | FreeBSD | GCC | +| X86 | GNU HURD | GCC | +| X86 | Interix | GCC | +| X86 | kFreeBSD | GCC | +| X86 | Linux | GCC | +| X86 | OpenBSD | GCC | +| X86 | OS/2 | GCC | +| X86 | Solaris | GCC | +| X86 | Solaris | Oracle Solaris Studio C | +| X86 | Windows/Cygwin | GCC | +| X86 | Windows/MingW | GCC | +| X86-64 | FreeBSD | GCC | +| X86-64 | Linux | GCC | +| X86-64 | Linux/x32 | GCC | +| X86-64 | OpenBSD | GCC | +| X86-64 | Solaris | Oracle Solaris Studio C | +| X86-64 | Windows/Cygwin | GCC | +| X86-64 | Windows/MingW | GCC | +| X86-64 | Mac OSX | GCC | +| Xtensa | Linux | GCC | + +Please send additional platform test results to +libffi-discuss@sourceware.org. + +Installing libffi +================= + +First you must configure the distribution for your particular +system. Go to the directory you wish to build libffi in and run the +"configure" program found in the root directory of the libffi source +distribution. Note that building libffi requires a C99 compatible +compiler. + +If you're building libffi directly from git hosted sources, configure +won't exist yet; run ./autogen.sh first. This will require that you +install autoconf, automake and libtool. + +You may want to tell configure where to install the libffi library and +header files. To do that, use the ``--prefix`` configure switch. Libffi +will install under /usr/local by default. + +If you want to enable extra run-time debugging checks use the the +``--enable-debug`` configure switch. This is useful when your program dies +mysteriously while using libffi. + +Another useful configure switch is ``--enable-purify-safety``. Using this +will add some extra code which will suppress certain warnings when you +are using Purify with libffi. Only use this switch when using +Purify, as it will slow down the library. + +If you don't want to build documentation, use the ``--disable-docs`` +configure switch. + +It's also possible to build libffi on Windows platforms with +Microsoft's Visual C++ compiler. In this case, use the msvcc.sh +wrapper script during configuration like so: + + path/to/configure CC=path/to/msvcc.sh CXX=path/to/msvcc.sh LD=link CPP="cl -nologo -EP" CPPFLAGS="-DFFI_BUILDING_DLL" + +For 64-bit Windows builds, use ``CC="path/to/msvcc.sh -m64"`` and +``CXX="path/to/msvcc.sh -m64"``. You may also need to specify +``--build`` appropriately. + +It is also possible to build libffi on Windows platforms with the LLVM +project's clang-cl compiler, like below: + + path/to/configure CC="path/to/msvcc.sh -clang-cl" CXX="path/to/msvcc.sh -clang-cl" LD=link CPP="clang-cl -EP" + +When building with MSVC under a MingW environment, you may need to +remove the line in configure that sets 'fix_srcfile_path' to a 'cygpath' +command. ('cygpath' is not present in MingW, and is not required when +using MingW-style paths.) + +To build static library for ARM64 with MSVC using visual studio solution, msvc_build folder have + aarch64/Ffi_staticLib.sln + required header files in aarch64/aarch64_include/ + + +SPARC Solaris builds require the use of the GNU assembler and linker. +Point ``AS`` and ``LD`` environment variables at those tool prior to +configuration. + +For iOS builds, the ``libffi.xcodeproj`` Xcode project is available. + +Configure has many other options. Use ``configure --help`` to see them all. + +Once configure has finished, type "make". Note that you must be using +GNU make. You can ftp GNU make from ftp.gnu.org:/pub/gnu/make . + +To ensure that libffi is working as advertised, type "make check". +This will require that you have DejaGNU installed. + +To install the library and header files, type ``make install``. + + +History +======= + +See the git log for details at http://github.com/libffi/libffi. + + 3.4 TBD + Add support for Alibaba's CSKY architecture. + Add support for Intel Control-flow Enforcement Technology (CET). + Add support for ARM Pointer Authentication (PA). + Fix 32-bit PPC regression. + Fix MIPS soft-float problem. + + 3.3 Nov-23-19 + Add RISC-V support. + New API in support of GO closures. + Add IEEE754 binary128 long double support for 64-bit Power + Default to Microsoft's 64 bit long double ABI with Visual C++. + GNU compiler uses 80 bits (128 in memory) FFI_GNUW64 ABI. + Add Windows on ARM64 (WOA) support. + Add Windows 32-bit ARM support. + Raw java (gcj) API deprecated. + Add pre-built PDF documentation to source distribution. + Many new test cases and bug fixes. + + 3.2.1 Nov-12-14 + Build fix for non-iOS AArch64 targets. + + 3.2 Nov-11-14 + Add C99 Complex Type support (currently only supported on + s390). + Add support for PASCAL and REGISTER calling conventions on x86 + Windows/Linux. + Add OpenRISC and Cygwin-64 support. + Bug fixes. + + 3.1 May-19-14 + Add AArch64 (ARM64) iOS support. + Add Nios II support. + Add m88k and DEC VAX support. + Add support for stdcall, thiscall, and fastcall on non-Windows + 32-bit x86 targets such as Linux. + Various Android, MIPS N32, x86, FreeBSD and UltraSPARC IIi + fixes. + Make the testsuite more robust: eliminate several spurious + failures, and respect the $CC and $CXX environment variables. + Archive off the manually maintained ChangeLog in favor of git + log. + + 3.0.13 Mar-17-13 + Add Meta support. + Add missing Moxie bits. + Fix stack alignment bug on 32-bit x86. + Build fix for m68000 targets. + Build fix for soft-float Power targets. + Fix the install dir location for some platforms when building + with GCC (OS X, Solaris). + Fix Cygwin regression. + + 3.0.12 Feb-11-13 + Add Moxie support. + Add AArch64 support. + Add Blackfin support. + Add TILE-Gx/TILEPro support. + Add MicroBlaze support. + Add Xtensa support. + Add support for PaX enabled kernels with MPROTECT. + Add support for native vendor compilers on + Solaris and AIX. + Work around LLVM/GCC interoperability issue on x86_64. + + 3.0.11 Apr-11-12 + Lots of build fixes. + Add support for variadic functions (ffi_prep_cif_var). + Add Linux/x32 support. + Add thiscall, fastcall and MSVC cdecl support on Windows. + Add Amiga and newer MacOS support. + Add m68k FreeMiNT support. + Integration with iOS' xcode build tools. + Fix Octeon and MC68881 support. + Fix code pessimizations. + + 3.0.10 Aug-23-11 + Add support for Apple's iOS. + Add support for ARM VFP ABI. + Add RTEMS support for MIPS and M68K. + Fix instruction cache clearing problems on + ARM and SPARC. + Fix the N64 build on mips-sgi-irix6.5. + Enable builds with Microsoft's compiler. + Enable x86 builds with Oracle's Solaris compiler. + Fix support for calling code compiled with Oracle's Sparc + Solaris compiler. + Testsuite fixes for Tru64 Unix. + Additional platform support. + + 3.0.9 Dec-31-09 + Add AVR32 and win64 ports. Add ARM softfp support. + Many fixes for AIX, Solaris, HP-UX, *BSD. + Several PowerPC and x86-64 bug fixes. + Build DLL for windows. + + 3.0.8 Dec-19-08 + Add *BSD, BeOS, and PA-Linux support. + + 3.0.7 Nov-11-08 + Fix for ppc FreeBSD. + (thanks to Andreas Tobler) + + 3.0.6 Jul-17-08 + Fix for closures on sh. + Mark the sh/sh64 stack as non-executable. + (both thanks to Kaz Kojima) + + 3.0.5 Apr-3-08 + Fix libffi.pc file. + Fix #define ARM for IcedTea users. + Fix x86 closure bug. + + 3.0.4 Feb-24-08 + Fix x86 OpenBSD configury. + + 3.0.3 Feb-22-08 + Enable x86 OpenBSD thanks to Thomas Heller, and + x86-64 FreeBSD thanks to Björn König and Andreas Tobler. + Clean up test instruction in README. + + 3.0.2 Feb-21-08 + Improved x86 FreeBSD support. + Thanks to Björn König. + + 3.0.1 Feb-15-08 + Fix instruction cache flushing bug on MIPS. + Thanks to David Daney. + + 3.0.0 Feb-15-08 + Many changes, mostly thanks to the GCC project. + Cygnus Solutions is now Red Hat. + + [10 years go by...] + + 1.20 Oct-5-98 + Raffaele Sena produces ARM port. + + 1.19 Oct-5-98 + Fixed x86 long double and long long return support. + m68k bug fixes from Andreas Schwab. + Patch for DU assembler compatibility for the Alpha from Richard + Henderson. + + 1.18 Apr-17-98 + Bug fixes and MIPS configuration changes. + + 1.17 Feb-24-98 + Bug fixes and m68k port from Andreas Schwab. PowerPC port from + Geoffrey Keating. Various bug x86, Sparc and MIPS bug fixes. + + 1.16 Feb-11-98 + Richard Henderson produces Alpha port. + + 1.15 Dec-4-97 + Fixed an n32 ABI bug. New libtool, auto* support. + + 1.14 May-13-97 + libtool is now used to generate shared and static libraries. + Fixed a minor portability problem reported by Russ McManus + . + + 1.13 Dec-2-96 + Added --enable-purify-safety to keep Purify from complaining + about certain low level code. + Sparc fix for calling functions with < 6 args. + Linux x86 a.out fix. + + 1.12 Nov-22-96 + Added missing ffi_type_void, needed for supporting void return + types. Fixed test case for non MIPS machines. Cygnus Support + is now Cygnus Solutions. + + 1.11 Oct-30-96 + Added notes about GNU make. + + 1.10 Oct-29-96 + Added configuration fix for non GNU compilers. + + 1.09 Oct-29-96 + Added --enable-debug configure switch. Clean-ups based on LCLint + feedback. ffi_mips.h is always installed. Many configuration + fixes. Fixed ffitest.c for sparc builds. + + 1.08 Oct-15-96 + Fixed n32 problem. Many clean-ups. + + 1.07 Oct-14-96 + Gordon Irlam rewrites v8.S again. Bug fixes. + + 1.06 Oct-14-96 + Gordon Irlam improved the sparc port. + + 1.05 Oct-14-96 + Interface changes based on feedback. + + 1.04 Oct-11-96 + Sparc port complete (modulo struct passing bug). + + 1.03 Oct-10-96 + Passing struct args, and returning struct values works for + all architectures/calling conventions. Expanded tests. + + 1.02 Oct-9-96 + Added SGI n32 support. Fixed bugs in both o32 and Linux support. + Added "make test". + + 1.01 Oct-8-96 + Fixed float passing bug in mips version. Restructured some + of the code. Builds cleanly with SGI tools. + + 1.00 Oct-7-96 + First release. No public announcement. + +Authors & Credits +================= + +libffi was originally written by Anthony Green . + +The developers of the GNU Compiler Collection project have made +innumerable valuable contributions. See the ChangeLog file for +details. + +Some of the ideas behind libffi were inspired by Gianni Mariani's free +gencall library for Silicon Graphics machines. + +The closure mechanism was designed and implemented by Kresten Krab +Thorup. + +Major processor architecture ports were contributed by the following +developers: + + aarch64 Marcus Shawcroft, James Greenhalgh + alpha Richard Henderson + arc Hackers at Synopsis + arm Raffaele Sena + avr32 Bradley Smith + blackfin Alexandre Keunecke I. de Mendonca + cris Simon Posnjak, Hans-Peter Nilsson + csky Ma Jun, Zhang Wenmeng + frv Anthony Green + ia64 Hans Boehm + m32r Kazuhiro Inaoka + m68k Andreas Schwab + m88k Miod Vallat + metag Hackers at Imagination Technologies + microblaze Nathan Rossi + mips Anthony Green, Casey Marshall + mips64 David Daney + moxie Anthony Green + nios ii Sandra Loosemore + openrisc Sebastian Macke + pa Randolph Chung, Dave Anglin, Andreas Tobler + powerpc Geoffrey Keating, Andreas Tobler, + David Edelsohn, John Hornkvist + powerpc64 Jakub Jelinek + riscv Michael Knyszek, Andrew Waterman, Stef O'Rear + s390 Gerhard Tonn, Ulrich Weigand + sh Kaz Kojima + sh64 Kaz Kojima + sparc Anthony Green, Gordon Irlam + tile-gx/tilepro Walter Lee + vax Miod Vallat + x86 Anthony Green, Jon Beniston + x86-64 Bo Thorsen + xtensa Chris Zankel + +Jesper Skov and Andrew Haley both did more than their fair share of +stepping through the code and tracking down bugs. + +Thanks also to Tom Tromey for bug fixes, documentation and +configuration help. + +Thanks to Jim Blandy, who provided some useful feedback on the libffi +interface. + +Andreas Tobler has done a tremendous amount of work on the testsuite. + +Alex Oliva solved the executable page problem for SElinux. + +The list above is almost certainly incomplete and inaccurate. I'm +happy to make corrections or additions upon request. + +If you have a problem, or have found a bug, please send a note to the +author at green@moxielogic.com, or the project mailing list at +libffi-discuss@sourceware.org. diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/acinclude.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/acinclude.m4 new file mode 100644 index 0000000..1a70efb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/acinclude.m4 @@ -0,0 +1,479 @@ +# mmap(2) blacklisting. Some platforms provide the mmap library routine +# but don't support all of the features we need from it. +AC_DEFUN([AC_FUNC_MMAP_BLACKLIST], +[ +AC_CHECK_HEADER([sys/mman.h], + [libffi_header_sys_mman_h=yes], [libffi_header_sys_mman_h=no]) +AC_CHECK_FUNC([mmap], [libffi_func_mmap=yes], [libffi_func_mmap=no]) +if test "$libffi_header_sys_mman_h" != yes \ + || test "$libffi_func_mmap" != yes; then + ac_cv_func_mmap_file=no + ac_cv_func_mmap_dev_zero=no + ac_cv_func_mmap_anon=no +else + AC_CACHE_CHECK([whether read-only mmap of a plain file works], + ac_cv_func_mmap_file, + [# Add a system to this blacklist if + # mmap(0, stat_size, PROT_READ, MAP_PRIVATE, fd, 0) doesn't return a + # memory area containing the same data that you'd get if you applied + # read() to the same fd. The only system known to have a problem here + # is VMS, where text files have record structure. + case "$host_os" in + vms* | ultrix*) + ac_cv_func_mmap_file=no ;; + *) + ac_cv_func_mmap_file=yes;; + esac]) + AC_CACHE_CHECK([whether mmap from /dev/zero works], + ac_cv_func_mmap_dev_zero, + [# Add a system to this blacklist if it has mmap() but /dev/zero + # does not exist, or if mmapping /dev/zero does not give anonymous + # zeroed pages with both the following properties: + # 1. If you map N consecutive pages in with one call, and then + # unmap any subset of those pages, the pages that were not + # explicitly unmapped remain accessible. + # 2. If you map two adjacent blocks of memory and then unmap them + # both at once, they must both go away. + # Systems known to be in this category are Windows (all variants), + # VMS, and Darwin. + case "$host_os" in + vms* | cygwin* | pe | mingw* | darwin* | ultrix* | hpux10* | hpux11.00) + ac_cv_func_mmap_dev_zero=no ;; + *) + ac_cv_func_mmap_dev_zero=yes;; + esac]) + + # Unlike /dev/zero, the MAP_ANON(YMOUS) defines can be probed for. + AC_CACHE_CHECK([for MAP_ANON(YMOUS)], ac_cv_decl_map_anon, + [AC_TRY_COMPILE( +[#include +#include +#include + +#ifndef MAP_ANONYMOUS +#define MAP_ANONYMOUS MAP_ANON +#endif +], +[int n = MAP_ANONYMOUS;], + ac_cv_decl_map_anon=yes, + ac_cv_decl_map_anon=no)]) + + if test $ac_cv_decl_map_anon = no; then + ac_cv_func_mmap_anon=no + else + AC_CACHE_CHECK([whether mmap with MAP_ANON(YMOUS) works], + ac_cv_func_mmap_anon, + [# Add a system to this blacklist if it has mmap() and MAP_ANON or + # MAP_ANONYMOUS, but using mmap(..., MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) + # doesn't give anonymous zeroed pages with the same properties listed + # above for use of /dev/zero. + # Systems known to be in this category are Windows, VMS, and SCO Unix. + case "$host_os" in + vms* | cygwin* | pe | mingw* | sco* | udk* ) + ac_cv_func_mmap_anon=no ;; + *) + ac_cv_func_mmap_anon=yes;; + esac]) + fi +fi + +if test $ac_cv_func_mmap_file = yes; then + AC_DEFINE(HAVE_MMAP_FILE, 1, + [Define if read-only mmap of a plain file works.]) +fi +if test $ac_cv_func_mmap_dev_zero = yes; then + AC_DEFINE(HAVE_MMAP_DEV_ZERO, 1, + [Define if mmap of /dev/zero works.]) +fi +if test $ac_cv_func_mmap_anon = yes; then + AC_DEFINE(HAVE_MMAP_ANON, 1, + [Define if mmap with MAP_ANON(YMOUS) works.]) +fi +]) + +dnl ---------------------------------------------------------------------- +dnl This whole bit snagged from libstdc++-v3, via libatomic. + +dnl +dnl LIBFFI_ENABLE +dnl (FEATURE, DEFAULT, HELP-ARG, HELP-STRING) +dnl (FEATURE, DEFAULT, HELP-ARG, HELP-STRING, permit a|b|c) +dnl (FEATURE, DEFAULT, HELP-ARG, HELP-STRING, SHELL-CODE-HANDLER) +dnl +dnl See docs/html/17_intro/configury.html#enable for documentation. +dnl +m4_define([LIBFFI_ENABLE],[dnl +m4_define([_g_switch],[--enable-$1])dnl +m4_define([_g_help],[AC_HELP_STRING(_g_switch$3,[$4 @<:@default=$2@:>@])])dnl + AC_ARG_ENABLE($1,_g_help, + m4_bmatch([$5], + [^permit ], + [[ + case "$enableval" in + m4_bpatsubst([$5],[permit ])) ;; + *) AC_MSG_ERROR(Unknown argument to enable/disable $1) ;; + dnl Idea for future: generate a URL pointing to + dnl "onlinedocs/configopts.html#whatever" + esac + ]], + [^$], + [[ + case "$enableval" in + yes|no) ;; + *) AC_MSG_ERROR(Argument to enable/disable $1 must be yes or no) ;; + esac + ]], + [[$5]]), + [enable_]m4_bpatsubst([$1],-,_)[=][$2]) +m4_undefine([_g_switch])dnl +m4_undefine([_g_help])dnl +]) + +dnl +dnl If GNU ld is in use, check to see if tricky linker opts can be used. If +dnl the native linker is in use, all variables will be defined to something +dnl safe (like an empty string). +dnl +dnl Defines: +dnl SECTION_LDFLAGS='-Wl,--gc-sections' if possible +dnl OPT_LDFLAGS='-Wl,-O1' if possible +dnl LD (as a side effect of testing) +dnl Sets: +dnl with_gnu_ld +dnl libat_ld_is_gold (possibly) +dnl libat_gnu_ld_version (possibly) +dnl +dnl The last will be a single integer, e.g., version 1.23.45.0.67.89 will +dnl set libat_gnu_ld_version to 12345. Zeros cause problems. +dnl +AC_DEFUN([LIBFFI_CHECK_LINKER_FEATURES], [ + # If we're not using GNU ld, then there's no point in even trying these + # tests. Check for that first. We should have already tested for gld + # by now (in libtool), but require it now just to be safe... + test -z "$SECTION_LDFLAGS" && SECTION_LDFLAGS='' + test -z "$OPT_LDFLAGS" && OPT_LDFLAGS='' + AC_REQUIRE([AC_PROG_LD]) + AC_REQUIRE([AC_PROG_AWK]) + + # The name set by libtool depends on the version of libtool. Shame on us + # for depending on an impl detail, but c'est la vie. Older versions used + # ac_cv_prog_gnu_ld, but now it's lt_cv_prog_gnu_ld, and is copied back on + # top of with_gnu_ld (which is also set by --with-gnu-ld, so that actually + # makes sense). We'll test with_gnu_ld everywhere else, so if that isn't + # set (hence we're using an older libtool), then set it. + if test x${with_gnu_ld+set} != xset; then + if test x${ac_cv_prog_gnu_ld+set} != xset; then + # We got through "ac_require(ac_prog_ld)" and still not set? Huh? + with_gnu_ld=no + else + with_gnu_ld=$ac_cv_prog_gnu_ld + fi + fi + + # Start by getting the version number. I think the libtool test already + # does some of this, but throws away the result. + libat_ld_is_gold=no + if $LD --version 2>/dev/null | grep 'GNU gold'> /dev/null 2>&1; then + libat_ld_is_gold=yes + fi + changequote(,) + ldver=`$LD --version 2>/dev/null | + sed -e 's/GNU gold /GNU ld /;s/GNU ld version /GNU ld /;s/GNU ld ([^)]*) /GNU ld /;s/GNU ld \([0-9.][0-9.]*\).*/\1/; q'` + changequote([,]) + libat_gnu_ld_version=`echo $ldver | \ + $AWK -F. '{ if (NF<3) [$]3=0; print ([$]1*100+[$]2)*100+[$]3 }'` + + # Set --gc-sections. + if test "$with_gnu_ld" = "notbroken"; then + # GNU ld it is! Joy and bunny rabbits! + + # All these tests are for C++; save the language and the compiler flags. + # Need to do this so that g++ won't try to link in libstdc++ + ac_test_CFLAGS="${CFLAGS+set}" + ac_save_CFLAGS="$CFLAGS" + CFLAGS='-x c++ -Wl,--gc-sections' + + # Check for -Wl,--gc-sections + # XXX This test is broken at the moment, as symbols required for linking + # are now in libsupc++ (not built yet). In addition, this test has + # cored on solaris in the past. In addition, --gc-sections doesn't + # really work at the moment (keeps on discarding used sections, first + # .eh_frame and now some of the glibc sections for iconv). + # Bzzzzt. Thanks for playing, maybe next time. + AC_MSG_CHECKING([for ld that supports -Wl,--gc-sections]) + AC_TRY_RUN([ + int main(void) + { + try { throw 1; } + catch (...) { }; + return 0; + } + ], [ac_sectionLDflags=yes],[ac_sectionLDflags=no], [ac_sectionLDflags=yes]) + if test "$ac_test_CFLAGS" = set; then + CFLAGS="$ac_save_CFLAGS" + else + # this is the suspicious part + CFLAGS='' + fi + if test "$ac_sectionLDflags" = "yes"; then + SECTION_LDFLAGS="-Wl,--gc-sections $SECTION_LDFLAGS" + fi + AC_MSG_RESULT($ac_sectionLDflags) + fi + + # Set linker optimization flags. + if test x"$with_gnu_ld" = x"yes"; then + OPT_LDFLAGS="-Wl,-O1 $OPT_LDFLAGS" + fi + + AC_SUBST(SECTION_LDFLAGS) + AC_SUBST(OPT_LDFLAGS) +]) + + +dnl +dnl If GNU ld is in use, check to see if tricky linker opts can be used. If +dnl the native linker is in use, all variables will be defined to something +dnl safe (like an empty string). +dnl +dnl Defines: +dnl SECTION_LDFLAGS='-Wl,--gc-sections' if possible +dnl OPT_LDFLAGS='-Wl,-O1' if possible +dnl LD (as a side effect of testing) +dnl Sets: +dnl with_gnu_ld +dnl libat_ld_is_gold (possibly) +dnl libat_gnu_ld_version (possibly) +dnl +dnl The last will be a single integer, e.g., version 1.23.45.0.67.89 will +dnl set libat_gnu_ld_version to 12345. Zeros cause problems. +dnl +AC_DEFUN([LIBFFI_CHECK_LINKER_FEATURES], [ + # If we're not using GNU ld, then there's no point in even trying these + # tests. Check for that first. We should have already tested for gld + # by now (in libtool), but require it now just to be safe... + test -z "$SECTION_LDFLAGS" && SECTION_LDFLAGS='' + test -z "$OPT_LDFLAGS" && OPT_LDFLAGS='' + AC_REQUIRE([AC_PROG_LD]) + AC_REQUIRE([AC_PROG_AWK]) + + # The name set by libtool depends on the version of libtool. Shame on us + # for depending on an impl detail, but c'est la vie. Older versions used + # ac_cv_prog_gnu_ld, but now it's lt_cv_prog_gnu_ld, and is copied back on + # top of with_gnu_ld (which is also set by --with-gnu-ld, so that actually + # makes sense). We'll test with_gnu_ld everywhere else, so if that isn't + # set (hence we're using an older libtool), then set it. + if test x${with_gnu_ld+set} != xset; then + if test x${ac_cv_prog_gnu_ld+set} != xset; then + # We got through "ac_require(ac_prog_ld)" and still not set? Huh? + with_gnu_ld=no + else + with_gnu_ld=$ac_cv_prog_gnu_ld + fi + fi + + # Start by getting the version number. I think the libtool test already + # does some of this, but throws away the result. + libat_ld_is_gold=no + if $LD --version 2>/dev/null | grep 'GNU gold'> /dev/null 2>&1; then + libat_ld_is_gold=yes + fi + libat_ld_is_lld=no + if $LD --version 2>/dev/null | grep 'LLD '> /dev/null 2>&1; then + libat_ld_is_lld=yes + fi + changequote(,) + ldver=`$LD --version 2>/dev/null | + sed -e 's/GNU gold /GNU ld /;s/GNU ld version /GNU ld /;s/GNU ld ([^)]*) /GNU ld /;s/GNU ld \([0-9.][0-9.]*\).*/\1/; q'` + changequote([,]) + libat_gnu_ld_version=`echo $ldver | \ + $AWK -F. '{ if (NF<3) [$]3=0; print ([$]1*100+[$]2)*100+[$]3 }'` + + # Set --gc-sections. + if test "$with_gnu_ld" = "notbroken"; then + # GNU ld it is! Joy and bunny rabbits! + + # All these tests are for C++; save the language and the compiler flags. + # Need to do this so that g++ won't try to link in libstdc++ + ac_test_CFLAGS="${CFLAGS+set}" + ac_save_CFLAGS="$CFLAGS" + CFLAGS='-x c++ -Wl,--gc-sections' + + # Check for -Wl,--gc-sections + # XXX This test is broken at the moment, as symbols required for linking + # are now in libsupc++ (not built yet). In addition, this test has + # cored on solaris in the past. In addition, --gc-sections doesn't + # really work at the moment (keeps on discarding used sections, first + # .eh_frame and now some of the glibc sections for iconv). + # Bzzzzt. Thanks for playing, maybe next time. + AC_MSG_CHECKING([for ld that supports -Wl,--gc-sections]) + AC_TRY_RUN([ + int main(void) + { + try { throw 1; } + catch (...) { }; + return 0; + } + ], [ac_sectionLDflags=yes],[ac_sectionLDflags=no], [ac_sectionLDflags=yes]) + if test "$ac_test_CFLAGS" = set; then + CFLAGS="$ac_save_CFLAGS" + else + # this is the suspicious part + CFLAGS='' + fi + if test "$ac_sectionLDflags" = "yes"; then + SECTION_LDFLAGS="-Wl,--gc-sections $SECTION_LDFLAGS" + fi + AC_MSG_RESULT($ac_sectionLDflags) + fi + + # Set linker optimization flags. + if test x"$with_gnu_ld" = x"yes"; then + OPT_LDFLAGS="-Wl,-O1 $OPT_LDFLAGS" + fi + + AC_SUBST(SECTION_LDFLAGS) + AC_SUBST(OPT_LDFLAGS) +]) + + +dnl +dnl Add version tags to symbols in shared library (or not), additionally +dnl marking other symbols as private/local (or not). +dnl +dnl --enable-symvers=style adds a version script to the linker call when +dnl creating the shared library. The choice of version script is +dnl controlled by 'style'. +dnl --disable-symvers does not. +dnl + Usage: LIBFFI_ENABLE_SYMVERS[(DEFAULT)] +dnl Where DEFAULT is either 'yes' or 'no'. Passing `yes' tries to +dnl choose a default style based on linker characteristics. Passing +dnl 'no' disables versioning. +dnl +AC_DEFUN([LIBFFI_ENABLE_SYMVERS], [ + +LIBFFI_ENABLE(symvers,yes,[=STYLE], + [enables symbol versioning of the shared library], + [permit yes|no|gnu*|sun]) + +# If we never went through the LIBFFI_CHECK_LINKER_FEATURES macro, then we +# don't know enough about $LD to do tricks... +AC_REQUIRE([LIBFFI_CHECK_LINKER_FEATURES]) + +# Turn a 'yes' into a suitable default. +if test x$enable_symvers = xyes ; then + # FIXME The following test is too strict, in theory. + if test $enable_shared = no || test "x$LD" = x; then + enable_symvers=no + else + if test $with_gnu_ld = yes ; then + enable_symvers=gnu + else + case ${target_os} in + # Sun symbol versioning exists since Solaris 2.5. + solaris2.[[5-9]]* | solaris2.1[[0-9]]*) + enable_symvers=sun ;; + *) + enable_symvers=no ;; + esac + fi + fi +fi + +# Check if 'sun' was requested on non-Solaris 2 platforms. +if test x$enable_symvers = xsun ; then + case ${target_os} in + solaris2*) + # All fine. + ;; + *) + # Unlikely to work. + AC_MSG_WARN([=== You have requested Sun symbol versioning, but]) + AC_MSG_WARN([=== you are not targetting Solaris 2.]) + AC_MSG_WARN([=== Symbol versioning will be disabled.]) + enable_symvers=no + ;; + esac +fi + +# Check to see if libgcc_s exists, indicating that shared libgcc is possible. +if test $enable_symvers != no; then + AC_MSG_CHECKING([for shared libgcc]) + ac_save_CFLAGS="$CFLAGS" + CFLAGS=' -lgcc_s' + AC_TRY_LINK(, [return 0;], libat_shared_libgcc=yes, libat_shared_libgcc=no) + CFLAGS="$ac_save_CFLAGS" + if test $libat_shared_libgcc = no; then + cat > conftest.c <&1 >/dev/null \ + | sed -n 's/^.* -lgcc_s\([^ ]*\) .*$/\1/p'` +changequote([,])dnl + rm -f conftest.c conftest.so + if test x${libat_libgcc_s_suffix+set} = xset; then + CFLAGS=" -lgcc_s$libat_libgcc_s_suffix" + AC_TRY_LINK(, [return 0;], libat_shared_libgcc=yes) + CFLAGS="$ac_save_CFLAGS" + fi + fi + AC_MSG_RESULT($libat_shared_libgcc) +fi + +# For GNU ld, we need at least this version. The format is described in +# LIBFFI_CHECK_LINKER_FEATURES above. +libat_min_gnu_ld_version=21400 +# XXXXXXXXXXX libat_gnu_ld_version=21390 + +# Check to see if unspecified "yes" value can win, given results above. +# Change "yes" into either "no" or a style name. +if test $enable_symvers != no && test $libat_shared_libgcc = yes; then + if test $with_gnu_ld = yes; then + if test $libat_gnu_ld_version -ge $libat_min_gnu_ld_version ; then + enable_symvers=gnu + elif test $libat_ld_is_gold = yes ; then + enable_symvers=gnu + elif test $libat_ld_is_lld = yes ; then + enable_symvers=gnu + else + # The right tools, the right setup, but too old. Fallbacks? + AC_MSG_WARN(=== Linker version $libat_gnu_ld_version is too old for) + AC_MSG_WARN(=== full symbol versioning support in this release of GCC.) + AC_MSG_WARN(=== You would need to upgrade your binutils to version) + AC_MSG_WARN(=== $libat_min_gnu_ld_version or later and rebuild GCC.) + if test $libat_gnu_ld_version -ge 21200 ; then + # Globbing fix is present, proper block support is not. + dnl AC_MSG_WARN([=== Dude, you are soooo close. Maybe we can fake it.]) + dnl enable_symvers=??? + AC_MSG_WARN([=== Symbol versioning will be disabled.]) + enable_symvers=no + else + # 2.11 or older. + AC_MSG_WARN([=== Symbol versioning will be disabled.]) + enable_symvers=no + fi + fi + elif test $enable_symvers = sun; then + : All interesting versions of Sun ld support sun style symbol versioning. + else + # just fail for now + AC_MSG_WARN([=== You have requested some kind of symbol versioning, but]) + AC_MSG_WARN([=== either you are not using a supported linker, or you are]) + AC_MSG_WARN([=== not building a shared libgcc_s (which is required).]) + AC_MSG_WARN([=== Symbol versioning will be disabled.]) + enable_symvers=no + fi +fi +if test $enable_symvers = gnu; then + AC_DEFINE(LIBFFI_GNU_SYMBOL_VERSIONING, 1, + [Define to 1 if GNU symbol versioning is used for libatomic.]) +fi + +AM_CONDITIONAL(LIBFFI_BUILD_VERSIONED_SHLIB, test $enable_symvers != no) +AM_CONDITIONAL(LIBFFI_BUILD_VERSIONED_SHLIB_GNU, test $enable_symvers = gnu) +AM_CONDITIONAL(LIBFFI_BUILD_VERSIONED_SHLIB_SUN, test $enable_symvers = sun) +AC_MSG_NOTICE(versioning on shared library symbols is $enable_symvers) +]) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/autogen.sh b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/autogen.sh new file mode 100755 index 0000000..fb014a3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/autogen.sh @@ -0,0 +1,2 @@ +#!/bin/sh +exec autoreconf -v -i diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/config.guess b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/config.guess new file mode 100644 index 0000000..e94095c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/config.guess @@ -0,0 +1,1687 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright 1992-2020 Free Software Foundation, Inc. + +timestamp='2020-07-12' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that +# program. This Exception is an additional permission under section 7 +# of the GNU General Public License, version 3 ("GPLv3"). +# +# Originally written by Per Bothner; maintained since 2000 by Ben Elliston. +# +# You can get the latest version of this script from: +# https://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess +# +# Please send patches to . + + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Options: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright 1992-2020 Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + +# CC_FOR_BUILD -- compiler used by this script. Note that the use of a +# compiler to aid in system detection is discouraged as it requires +# temporary files to be created and, as you can see below, it is a +# headache to deal with in a portable fashion. + +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +# Portable tmp directory creation inspired by the Autoconf team. + +tmp= +# shellcheck disable=SC2172 +trap 'test -z "$tmp" || rm -fr "$tmp"' 0 1 2 13 15 + +set_cc_for_build() { + # prevent multiple calls if $tmp is already set + test "$tmp" && return 0 + : "${TMPDIR=/tmp}" + # shellcheck disable=SC2039 + { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir "$tmp" 2>/dev/null) ; } || + { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir "$tmp" 2>/dev/null) && echo "Warning: creating insecure temp directory" >&2 ; } || + { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } + dummy=$tmp/dummy + case ${CC_FOR_BUILD-},${HOST_CC-},${CC-} in + ,,) echo "int x;" > "$dummy.c" + for driver in cc gcc c89 c99 ; do + if ($driver -c -o "$dummy.o" "$dummy.c") >/dev/null 2>&1 ; then + CC_FOR_BUILD="$driver" + break + fi + done + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; + esac +} + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if test -f /.attbin/uname ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +case "$UNAME_SYSTEM" in +Linux|GNU|GNU/*) + # If the system lacks a compiler, then just pick glibc. + # We could probably try harder. + LIBC=gnu + + set_cc_for_build + cat <<-EOF > "$dummy.c" + #include + #if defined(__UCLIBC__) + LIBC=uclibc + #elif defined(__dietlibc__) + LIBC=dietlibc + #else + LIBC=gnu + #endif + EOF + eval "`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`" + + # If ldd exists, use it to detect musl libc. + if command -v ldd >/dev/null && \ + ldd --version 2>&1 | grep -q ^musl + then + LIBC=musl + fi + ;; +esac + +# Note: order is significant - the case branches are not exclusive. + +case "$UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION" in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # + # Note: NetBSD doesn't particularly care about the vendor + # portion of the name. We always set it to "unknown". + sysctl="sysctl -n hw.machine_arch" + UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \ + "/sbin/$sysctl" 2>/dev/null || \ + "/usr/sbin/$sysctl" 2>/dev/null || \ + echo unknown)` + case "$UNAME_MACHINE_ARCH" in + armeb) machine=armeb-unknown ;; + arm*) machine=arm-unknown ;; + sh3el) machine=shl-unknown ;; + sh3eb) machine=sh-unknown ;; + sh5el) machine=sh5le-unknown ;; + earmv*) + arch=`echo "$UNAME_MACHINE_ARCH" | sed -e 's,^e\(armv[0-9]\).*$,\1,'` + endian=`echo "$UNAME_MACHINE_ARCH" | sed -ne 's,^.*\(eb\)$,\1,p'` + machine="${arch}${endian}"-unknown + ;; + *) machine="$UNAME_MACHINE_ARCH"-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently (or will in the future) and ABI. + case "$UNAME_MACHINE_ARCH" in + earm*) + os=netbsdelf + ;; + arm*|i386|m68k|ns32k|sh3*|sparc|vax) + set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ELF__ + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # Determine ABI tags. + case "$UNAME_MACHINE_ARCH" in + earm*) + expr='s/^earmv[0-9]/-eabi/;s/eb$//' + abi=`echo "$UNAME_MACHINE_ARCH" | sed -e "$expr"` + ;; + esac + # The OS release + # Debian GNU/NetBSD machines have a different userland, and + # thus, need a distinct triplet. However, they do not need + # kernel version information, so it can be replaced with a + # suitable tag, in the style of linux-gnu. + case "$UNAME_VERSION" in + Debian*) + release='-gnu' + ;; + *) + release=`echo "$UNAME_RELEASE" | sed -e 's/[-_].*//' | cut -d. -f1,2` + ;; + esac + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "$machine-${os}${release}${abi-}" + exit ;; + *:Bitrig:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` + echo "$UNAME_MACHINE_ARCH"-unknown-bitrig"$UNAME_RELEASE" + exit ;; + *:OpenBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` + echo "$UNAME_MACHINE_ARCH"-unknown-openbsd"$UNAME_RELEASE" + exit ;; + *:LibertyBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'` + echo "$UNAME_MACHINE_ARCH"-unknown-libertybsd"$UNAME_RELEASE" + exit ;; + *:MidnightBSD:*:*) + echo "$UNAME_MACHINE"-unknown-midnightbsd"$UNAME_RELEASE" + exit ;; + *:ekkoBSD:*:*) + echo "$UNAME_MACHINE"-unknown-ekkobsd"$UNAME_RELEASE" + exit ;; + *:SolidBSD:*:*) + echo "$UNAME_MACHINE"-unknown-solidbsd"$UNAME_RELEASE" + exit ;; + *:OS108:*:*) + echo "$UNAME_MACHINE"-unknown-os108_"$UNAME_RELEASE" + exit ;; + macppc:MirBSD:*:*) + echo powerpc-unknown-mirbsd"$UNAME_RELEASE" + exit ;; + *:MirBSD:*:*) + echo "$UNAME_MACHINE"-unknown-mirbsd"$UNAME_RELEASE" + exit ;; + *:Sortix:*:*) + echo "$UNAME_MACHINE"-unknown-sortix + exit ;; + *:Twizzler:*:*) + echo "$UNAME_MACHINE"-unknown-twizzler + exit ;; + *:Redox:*:*) + echo "$UNAME_MACHINE"-unknown-redox + exit ;; + mips:OSF1:*.*) + echo mips-dec-osf1 + exit ;; + alpha:OSF1:*:*) + case $UNAME_RELEASE in + *4.0) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + ;; + *5.*) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + ;; + esac + # According to Compaq, /usr/sbin/psrinfo has been available on + # OSF/1 and Tru64 systems produced since 1995. I hope that + # covers most systems running today. This code pipes the CPU + # types through head -n 1, so we only detect the type of CPU 0. + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` + case "$ALPHA_CPU_TYPE" in + "EV4 (21064)") + UNAME_MACHINE=alpha ;; + "EV4.5 (21064)") + UNAME_MACHINE=alpha ;; + "LCA4 (21066/21068)") + UNAME_MACHINE=alpha ;; + "EV5 (21164)") + UNAME_MACHINE=alphaev5 ;; + "EV5.6 (21164A)") + UNAME_MACHINE=alphaev56 ;; + "EV5.6 (21164PC)") + UNAME_MACHINE=alphapca56 ;; + "EV5.7 (21164PC)") + UNAME_MACHINE=alphapca57 ;; + "EV6 (21264)") + UNAME_MACHINE=alphaev6 ;; + "EV6.7 (21264A)") + UNAME_MACHINE=alphaev67 ;; + "EV6.8CB (21264C)") + UNAME_MACHINE=alphaev68 ;; + "EV6.8AL (21264B)") + UNAME_MACHINE=alphaev68 ;; + "EV6.8CX (21264D)") + UNAME_MACHINE=alphaev68 ;; + "EV6.9A (21264/EV69A)") + UNAME_MACHINE=alphaev69 ;; + "EV7 (21364)") + UNAME_MACHINE=alphaev7 ;; + "EV7.9 (21364A)") + UNAME_MACHINE=alphaev79 ;; + esac + # A Pn.n version is a patched version. + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + echo "$UNAME_MACHINE"-dec-osf"`echo "$UNAME_RELEASE" | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`" + # Reset EXIT trap before exiting to avoid spurious non-zero exit code. + exitcode=$? + trap '' 0 + exit $exitcode ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit ;; + *:[Aa]miga[Oo][Ss]:*:*) + echo "$UNAME_MACHINE"-unknown-amigaos + exit ;; + *:[Mm]orph[Oo][Ss]:*:*) + echo "$UNAME_MACHINE"-unknown-morphos + exit ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit ;; + *:z/VM:*:*) + echo s390-ibm-zvmoe + exit ;; + *:OS400:*:*) + echo powerpc-ibm-os400 + exit ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix"$UNAME_RELEASE" + exit ;; + arm*:riscos:*:*|arm*:RISCOS:*:*) + echo arm-unknown-riscos + exit ;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit ;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit ;; + DRS?6000:unix:4.0:6*) + echo sparc-icl-nx6 + exit ;; + DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) + case `/usr/bin/uname -p` in + sparc) echo sparc-icl-nx7; exit ;; + esac ;; + s390x:SunOS:*:*) + echo "$UNAME_MACHINE"-ibm-solaris2"`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`" + exit ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" + exit ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2"`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`" + exit ;; + i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) + echo i386-pc-auroraux"$UNAME_RELEASE" + exit ;; + i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) + set_cc_for_build + SUN_ARCH=i386 + # If there is a compiler, see if it is configured for 64-bit objects. + # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. + # This test works for both compilers. + if [ "$CC_FOR_BUILD" != no_compiler_found ]; then + if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + SUN_ARCH=x86_64 + fi + fi + echo "$SUN_ARCH"-pc-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" + exit ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" + exit ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos"`echo "$UNAME_RELEASE"|sed -e 's/-/_/'`" + exit ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos"$UNAME_RELEASE" + exit ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x$UNAME_RELEASE" = x && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos"$UNAME_RELEASE" + ;; + sun4) + echo sparc-sun-sunos"$UNAME_RELEASE" + ;; + esac + exit ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos"$UNAME_RELEASE" + exit ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint"$UNAME_RELEASE" + exit ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint"$UNAME_RELEASE" + exit ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint"$UNAME_RELEASE" + exit ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint"$UNAME_RELEASE" + exit ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint"$UNAME_RELEASE" + exit ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint"$UNAME_RELEASE" + exit ;; + m68k:machten:*:*) + echo m68k-apple-machten"$UNAME_RELEASE" + exit ;; + powerpc:machten:*:*) + echo powerpc-apple-machten"$UNAME_RELEASE" + exit ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix"$UNAME_RELEASE" + exit ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix"$UNAME_RELEASE" + exit ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix"$UNAME_RELEASE" + exit ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + set_cc_for_build + sed 's/^ //' << EOF > "$dummy.c" +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD -o "$dummy" "$dummy.c" && + dummyarg=`echo "$UNAME_RELEASE" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`"$dummy" "$dummyarg"` && + { echo "$SYSTEM_NAME"; exit; } + echo mips-mips-riscos"$UNAME_RELEASE" + exit ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit ;; + Motorola:*:4.3:PL8-*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ "$UNAME_PROCESSOR" = mc88100 ] || [ "$UNAME_PROCESSOR" = mc88110 ] + then + if [ "$TARGET_BINARY_INTERFACE"x = m88kdguxelfx ] || \ + [ "$TARGET_BINARY_INTERFACE"x = x ] + then + echo m88k-dg-dgux"$UNAME_RELEASE" + else + echo m88k-dg-dguxbcs"$UNAME_RELEASE" + fi + else + echo i586-dg-dgux"$UNAME_RELEASE" + fi + exit ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit ;; + *:IRIX*:*:*) + echo mips-sgi-irix"`echo "$UNAME_RELEASE"|sed -e 's/-/_/g'`" + exit ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV="$UNAME_VERSION.$UNAME_RELEASE" + fi + echo "$UNAME_MACHINE"-ibm-aix"$IBM_REV" + exit ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + set_cc_for_build + sed 's/^ //' << EOF > "$dummy.c" + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + if $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` + then + echo "$SYSTEM_NAME" + else + echo rs6000-ibm-aix3.2.5 + fi + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit ;; + *:AIX:*:[4567]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` + if /usr/sbin/lsattr -El "$IBM_CPU_ID" | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/lslpp ] ; then + IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc | + awk -F: '{ print $3 }' | sed s/[0-9]*$/0/` + else + IBM_REV="$UNAME_VERSION.$UNAME_RELEASE" + fi + echo "$IBM_ARCH"-ibm-aix"$IBM_REV" + exit ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit ;; + ibmrt:4.4BSD:*|romp-ibm:4.4BSD:*) + echo romp-ibm-bsd4.4 + exit ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd"$UNAME_RELEASE" # 4.3 with uname added to + exit ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo "$UNAME_RELEASE"|sed -e 's/[^.]*.[0B]*//'` + case "$UNAME_MACHINE" in + 9000/31?) HP_ARCH=m68000 ;; + 9000/[34]??) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "$sc_cpu_version" in + 523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0 + 528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "$sc_kernel_bits" in + 32) HP_ARCH=hppa2.0n ;; + 64) HP_ARCH=hppa2.0w ;; + '') HP_ARCH=hppa2.0 ;; # HP-UX 10.20 + esac ;; + esac + fi + if [ "$HP_ARCH" = "" ]; then + set_cc_for_build + sed 's/^ //' << EOF > "$dummy.c" + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS="" $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null) && HP_ARCH=`"$dummy"` + test -z "$HP_ARCH" && HP_ARCH=hppa + fi ;; + esac + if [ "$HP_ARCH" = hppa2.0w ] + then + set_cc_for_build + + # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating + # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler + # generating 64-bit code. GNU and HP use different nomenclature: + # + # $ CC_FOR_BUILD=cc ./config.guess + # => hppa2.0w-hp-hpux11.23 + # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess + # => hppa64-hp-hpux11.23 + + if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | + grep -q __LP64__ + then + HP_ARCH=hppa2.0w + else + HP_ARCH=hppa64 + fi + fi + echo "$HP_ARCH"-hp-hpux"$HPUX_REV" + exit ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo "$UNAME_RELEASE"|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux"$HPUX_REV" + exit ;; + 3050*:HI-UX:*:*) + set_cc_for_build + sed 's/^ //' << EOF > "$dummy.c" + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` && + { echo "$SYSTEM_NAME"; exit; } + echo unknown-hitachi-hiuxwe2 + exit ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:*) + echo hppa1.1-hp-bsd + exit ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:*) + echo hppa1.1-hp-osf + exit ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo "$UNAME_MACHINE"-unknown-osf1mk + else + echo "$UNAME_MACHINE"-unknown-osf1 + fi + exit ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*[A-Z]90:*:*:*) + echo "$UNAME_MACHINE"-cray-unicos"$UNAME_RELEASE" \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' + exit ;; + *:UNICOS/mp:*:*) + echo craynv-cray-unicosmp"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/' + exit ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz` + FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` + FUJITSU_REL=`echo "$UNAME_RELEASE" | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + 5000:UNIX_System_V:4.*:*) + FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'` + FUJITSU_REL=`echo "$UNAME_RELEASE" | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'` + echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo "$UNAME_MACHINE"-pc-bsdi"$UNAME_RELEASE" + exit ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi"$UNAME_RELEASE" + exit ;; + *:BSD/OS:*:*) + echo "$UNAME_MACHINE"-unknown-bsdi"$UNAME_RELEASE" + exit ;; + arm:FreeBSD:*:*) + UNAME_PROCESSOR=`uname -p` + set_cc_for_build + if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_PCS_VFP + then + echo "${UNAME_PROCESSOR}"-unknown-freebsd"`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`"-gnueabi + else + echo "${UNAME_PROCESSOR}"-unknown-freebsd"`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`"-gnueabihf + fi + exit ;; + *:FreeBSD:*:*) + UNAME_PROCESSOR=`/usr/bin/uname -p` + case "$UNAME_PROCESSOR" in + amd64) + UNAME_PROCESSOR=x86_64 ;; + i386) + UNAME_PROCESSOR=i586 ;; + esac + echo "$UNAME_PROCESSOR"-unknown-freebsd"`echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`" + exit ;; + i*:CYGWIN*:*) + echo "$UNAME_MACHINE"-pc-cygwin + exit ;; + *:MINGW64*:*) + echo "$UNAME_MACHINE"-pc-mingw64 + exit ;; + *:MINGW*:*) + echo "$UNAME_MACHINE"-pc-mingw32 + exit ;; + *:MSYS*:*) + echo "$UNAME_MACHINE"-pc-msys + exit ;; + i*:PW*:*) + echo "$UNAME_MACHINE"-pc-pw32 + exit ;; + *:Interix*:*) + case "$UNAME_MACHINE" in + x86) + echo i586-pc-interix"$UNAME_RELEASE" + exit ;; + authenticamd | genuineintel | EM64T) + echo x86_64-unknown-interix"$UNAME_RELEASE" + exit ;; + IA64) + echo ia64-unknown-interix"$UNAME_RELEASE" + exit ;; + esac ;; + i*:UWIN*:*) + echo "$UNAME_MACHINE"-pc-uwin + exit ;; + amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) + echo x86_64-pc-cygwin + exit ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`" + exit ;; + *:GNU:*:*) + # the GNU system + echo "`echo "$UNAME_MACHINE"|sed -e 's,[-/].*$,,'`-unknown-$LIBC`echo "$UNAME_RELEASE"|sed -e 's,/.*$,,'`" + exit ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland + echo "$UNAME_MACHINE-unknown-`echo "$UNAME_SYSTEM" | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"``echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`-$LIBC" + exit ;; + *:Minix:*:*) + echo "$UNAME_MACHINE"-unknown-minix + exit ;; + aarch64:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + aarch64_be:Linux:*:*) + UNAME_MACHINE=aarch64_be + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' /proc/cpuinfo 2>/dev/null` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep -q ld.so.1 + if test "$?" = 0 ; then LIBC=gnulibc1 ; fi + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + arc:Linux:*:* | arceb:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + arm*:Linux:*:*) + set_cc_for_build + if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_EABI__ + then + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + else + if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_PCS_VFP + then + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"eabi + else + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"eabihf + fi + fi + exit ;; + avr32*:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + cris:Linux:*:*) + echo "$UNAME_MACHINE"-axis-linux-"$LIBC" + exit ;; + crisv32:Linux:*:*) + echo "$UNAME_MACHINE"-axis-linux-"$LIBC" + exit ;; + e2k:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + frv:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + hexagon:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + i*86:Linux:*:*) + echo "$UNAME_MACHINE"-pc-linux-"$LIBC" + exit ;; + ia64:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + k1om:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + m32r*:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + m68*:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + mips:Linux:*:* | mips64:Linux:*:*) + set_cc_for_build + IS_GLIBC=0 + test x"${LIBC}" = xgnu && IS_GLIBC=1 + sed 's/^ //' << EOF > "$dummy.c" + #undef CPU + #undef mips + #undef mipsel + #undef mips64 + #undef mips64el + #if ${IS_GLIBC} && defined(_ABI64) + LIBCABI=gnuabi64 + #else + #if ${IS_GLIBC} && defined(_ABIN32) + LIBCABI=gnuabin32 + #else + LIBCABI=${LIBC} + #endif + #endif + + #if ${IS_GLIBC} && defined(__mips64) && defined(__mips_isa_rev) && __mips_isa_rev>=6 + CPU=mipsisa64r6 + #else + #if ${IS_GLIBC} && !defined(__mips64) && defined(__mips_isa_rev) && __mips_isa_rev>=6 + CPU=mipsisa32r6 + #else + #if defined(__mips64) + CPU=mips64 + #else + CPU=mips + #endif + #endif + #endif + + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + MIPS_ENDIAN=el + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + MIPS_ENDIAN= + #else + MIPS_ENDIAN= + #endif + #endif +EOF + eval "`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^CPU\|^MIPS_ENDIAN\|^LIBCABI'`" + test "x$CPU" != x && { echo "$CPU${MIPS_ENDIAN}-unknown-linux-$LIBCABI"; exit; } + ;; + mips64el:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + openrisc*:Linux:*:*) + echo or1k-unknown-linux-"$LIBC" + exit ;; + or32:Linux:*:* | or1k*:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + padre:Linux:*:*) + echo sparc-unknown-linux-"$LIBC" + exit ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-"$LIBC" + exit ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-"$LIBC" ;; + PA8*) echo hppa2.0-unknown-linux-"$LIBC" ;; + *) echo hppa-unknown-linux-"$LIBC" ;; + esac + exit ;; + ppc64:Linux:*:*) + echo powerpc64-unknown-linux-"$LIBC" + exit ;; + ppc:Linux:*:*) + echo powerpc-unknown-linux-"$LIBC" + exit ;; + ppc64le:Linux:*:*) + echo powerpc64le-unknown-linux-"$LIBC" + exit ;; + ppcle:Linux:*:*) + echo powerpcle-unknown-linux-"$LIBC" + exit ;; + riscv32:Linux:*:* | riscv64:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo "$UNAME_MACHINE"-ibm-linux-"$LIBC" + exit ;; + sh64*:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + sh*:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + tile*:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + vax:Linux:*:*) + echo "$UNAME_MACHINE"-dec-linux-"$LIBC" + exit ;; + x86_64:Linux:*:*) + set_cc_for_build + LIBCABI=$LIBC + if [ "$CC_FOR_BUILD" != no_compiler_found ]; then + if (echo '#ifdef __ILP32__'; echo IS_X32; echo '#endif') | \ + (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_X32 >/dev/null + then + LIBCABI="$LIBC"x32 + fi + fi + echo "$UNAME_MACHINE"-pc-linux-"$LIBCABI" + exit ;; + xtensa*:Linux:*:*) + echo "$UNAME_MACHINE"-unknown-linux-"$LIBC" + exit ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + echo i386-sequent-sysv4 + exit ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo "$UNAME_MACHINE"-pc-sysv4.2uw"$UNAME_VERSION" + exit ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo "$UNAME_MACHINE"-pc-os2-emx + exit ;; + i*86:XTS-300:*:STOP) + echo "$UNAME_MACHINE"-unknown-stop + exit ;; + i*86:atheos:*:*) + echo "$UNAME_MACHINE"-unknown-atheos + exit ;; + i*86:syllable:*:*) + echo "$UNAME_MACHINE"-pc-syllable + exit ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) + echo i386-unknown-lynxos"$UNAME_RELEASE" + exit ;; + i*86:*DOS:*:*) + echo "$UNAME_MACHINE"-pc-msdosdjgpp + exit ;; + i*86:*:4.*:*) + UNAME_REL=`echo "$UNAME_RELEASE" | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo "$UNAME_MACHINE"-univel-sysv"$UNAME_REL" + else + echo "$UNAME_MACHINE"-pc-sysv"$UNAME_REL" + fi + exit ;; + i*86:*:5:[678]*) + # UnixWare 7.x, OpenUNIX and OpenServer 6. + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + echo "$UNAME_MACHINE-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}" + exit ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` + (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo "$UNAME_MACHINE"-pc-sco"$UNAME_REL" + else + echo "$UNAME_MACHINE"-pc-sysv32 + fi + exit ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i586. + # Note: whatever this is, it MUST be the same as what config.sub + # prints for the "djgpp" host, or else GDB configure will decide that + # this is a cross-build. + echo i586-pc-msdosdjgpp + exit ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv"$UNAME_RELEASE" # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv"$UNAME_RELEASE" # Unknown i860-SVR4 + fi + exit ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit ;; + mc68k:UNIX:SYSTEM5:3.51m) + echo m68k-convergent-sysv + exit ;; + M680?0:D-NIX:5.3:*) + echo m68k-diab-dnix + exit ;; + M68*:*:R3V[5678]*:*) + test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; + 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4; exit; } ;; + NCR*:*:4.2:* | MPRAS*:*:4.2:*) + OS_REL='.3' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3"$OS_REL"; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } + /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ + && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos"$UNAME_RELEASE" + exit ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos"$UNAME_RELEASE" + exit ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos"$UNAME_RELEASE" + exit ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) + echo powerpc-unknown-lynxos"$UNAME_RELEASE" + exit ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv"$UNAME_RELEASE" + exit ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo "$UNAME_MACHINE"-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + echo i586-unisys-sysv4 + exit ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit ;; + i*86:VOS:*:*) + # From Paul.Green@stratus.com. + echo "$UNAME_MACHINE"-stratus-vos + exit ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + echo hppa1.1-stratus-vos + exit ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux"$UNAME_RELEASE" + exit ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv"$UNAME_RELEASE" + else + echo mips-unknown-sysv"$UNAME_RELEASE" + fi + exit ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit ;; + BePC:Haiku:*:*) # Haiku running on Intel PC compatible. + echo i586-pc-haiku + exit ;; + x86_64:Haiku:*:*) + echo x86_64-unknown-haiku + exit ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux"$UNAME_RELEASE" + exit ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux"$UNAME_RELEASE" + exit ;; + SX-6:SUPER-UX:*:*) + echo sx6-nec-superux"$UNAME_RELEASE" + exit ;; + SX-7:SUPER-UX:*:*) + echo sx7-nec-superux"$UNAME_RELEASE" + exit ;; + SX-8:SUPER-UX:*:*) + echo sx8-nec-superux"$UNAME_RELEASE" + exit ;; + SX-8R:SUPER-UX:*:*) + echo sx8r-nec-superux"$UNAME_RELEASE" + exit ;; + SX-ACE:SUPER-UX:*:*) + echo sxace-nec-superux"$UNAME_RELEASE" + exit ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody"$UNAME_RELEASE" + exit ;; + *:Rhapsody:*:*) + echo "$UNAME_MACHINE"-apple-rhapsody"$UNAME_RELEASE" + exit ;; + arm64:Darwin:*:*) + echo aarch64-apple-darwin"$UNAME_RELEASE" + exit ;; + *:Darwin:*:*) + UNAME_PROCESSOR=`uname -p` + case $UNAME_PROCESSOR in + unknown) UNAME_PROCESSOR=powerpc ;; + esac + if command -v xcode-select > /dev/null 2> /dev/null && \ + ! xcode-select --print-path > /dev/null 2> /dev/null ; then + # Avoid executing cc if there is no toolchain installed as + # cc will be a stub that puts up a graphical alert + # prompting the user to install developer tools. + CC_FOR_BUILD=no_compiler_found + else + set_cc_for_build + fi + if [ "$CC_FOR_BUILD" != no_compiler_found ]; then + if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + case $UNAME_PROCESSOR in + i386) UNAME_PROCESSOR=x86_64 ;; + powerpc) UNAME_PROCESSOR=powerpc64 ;; + esac + fi + # On 10.4-10.6 one might compile for PowerPC via gcc -arch ppc + if (echo '#ifdef __POWERPC__'; echo IS_PPC; echo '#endif') | \ + (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_PPC >/dev/null + then + UNAME_PROCESSOR=powerpc + fi + elif test "$UNAME_PROCESSOR" = i386 ; then + # uname -m returns i386 or x86_64 + UNAME_PROCESSOR=$UNAME_MACHINE + fi + echo "$UNAME_PROCESSOR"-apple-darwin"$UNAME_RELEASE" + exit ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + UNAME_PROCESSOR=`uname -p` + if test "$UNAME_PROCESSOR" = x86; then + UNAME_PROCESSOR=i386 + UNAME_MACHINE=pc + fi + echo "$UNAME_PROCESSOR"-"$UNAME_MACHINE"-nto-qnx"$UNAME_RELEASE" + exit ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit ;; + NEO-*:NONSTOP_KERNEL:*:*) + echo neo-tandem-nsk"$UNAME_RELEASE" + exit ;; + NSE-*:NONSTOP_KERNEL:*:*) + echo nse-tandem-nsk"$UNAME_RELEASE" + exit ;; + NSR-*:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk"$UNAME_RELEASE" + exit ;; + NSV-*:NONSTOP_KERNEL:*:*) + echo nsv-tandem-nsk"$UNAME_RELEASE" + exit ;; + NSX-*:NONSTOP_KERNEL:*:*) + echo nsx-tandem-nsk"$UNAME_RELEASE" + exit ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit ;; + DS/*:UNIX_System_V:*:*) + echo "$UNAME_MACHINE"-"$UNAME_SYSTEM"-"$UNAME_RELEASE" + exit ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + # shellcheck disable=SC2154 + if test "$cputype" = 386; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo "$UNAME_MACHINE"-unknown-plan9 + exit ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit ;; + SEI:*:*:SEIUX) + echo mips-sei-seiux"$UNAME_RELEASE" + exit ;; + *:DragonFly:*:*) + echo "$UNAME_MACHINE"-unknown-dragonfly"`echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`" + exit ;; + *:*VMS:*:*) + UNAME_MACHINE=`(uname -p) 2>/dev/null` + case "$UNAME_MACHINE" in + A*) echo alpha-dec-vms ; exit ;; + I*) echo ia64-dec-vms ; exit ;; + V*) echo vax-dec-vms ; exit ;; + esac ;; + *:XENIX:*:SysV) + echo i386-pc-xenix + exit ;; + i*86:skyos:*:*) + echo "$UNAME_MACHINE"-pc-skyos"`echo "$UNAME_RELEASE" | sed -e 's/ .*$//'`" + exit ;; + i*86:rdos:*:*) + echo "$UNAME_MACHINE"-pc-rdos + exit ;; + i*86:AROS:*:*) + echo "$UNAME_MACHINE"-pc-aros + exit ;; + x86_64:VMkernel:*:*) + echo "$UNAME_MACHINE"-unknown-esx + exit ;; + amd64:Isilon\ OneFS:*:*) + echo x86_64-unknown-onefs + exit ;; + *:Unleashed:*:*) + echo "$UNAME_MACHINE"-unknown-unleashed"$UNAME_RELEASE" + exit ;; +esac + +# No uname command or uname output not recognized. +set_cc_for_build +cat > "$dummy.c" < +#include +#endif +#if defined(ultrix) || defined(_ultrix) || defined(__ultrix) || defined(__ultrix__) +#if defined (vax) || defined (__vax) || defined (__vax__) || defined(mips) || defined(__mips) || defined(__mips__) || defined(MIPS) || defined(__MIPS__) +#include +#if defined(_SIZE_T_) || defined(SIGLOST) +#include +#endif +#endif +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); +#endif + +#if defined (vax) +#if !defined (ultrix) +#include +#if defined (BSD) +#if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +#else +#if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +#else + printf ("vax-dec-bsd\n"); exit (0); +#endif +#endif +#else + printf ("vax-dec-bsd\n"); exit (0); +#endif +#else +#if defined(_SIZE_T_) || defined(SIGLOST) + struct utsname un; + uname (&un); + printf ("vax-dec-ultrix%s\n", un.release); exit (0); +#else + printf ("vax-dec-ultrix\n"); exit (0); +#endif +#endif +#endif +#if defined(ultrix) || defined(_ultrix) || defined(__ultrix) || defined(__ultrix__) +#if defined(mips) || defined(__mips) || defined(__mips__) || defined(MIPS) || defined(__MIPS__) +#if defined(_SIZE_T_) || defined(SIGLOST) + struct utsname *un; + uname (&un); + printf ("mips-dec-ultrix%s\n", un.release); exit (0); +#else + printf ("mips-dec-ultrix\n"); exit (0); +#endif +#endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + +# Apollos put the system type in the environment. +test -d /usr/apollo && { echo "$ISP-apollo-$SYSTYPE"; exit; } + +echo "$0: unable to guess system type" >&2 + +case "$UNAME_MACHINE:$UNAME_SYSTEM" in + mips:Linux | mips64:Linux) + # If we got here on MIPS GNU/Linux, output extra information. + cat >&2 <&2 <&2 </dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = "$UNAME_MACHINE" +UNAME_RELEASE = "$UNAME_RELEASE" +UNAME_SYSTEM = "$UNAME_SYSTEM" +UNAME_VERSION = "$UNAME_VERSION" +EOF +fi + +exit 1 + +# Local variables: +# eval: (add-hook 'before-save-hook 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/config.sub b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/config.sub new file mode 100644 index 0000000..14b5150 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/config.sub @@ -0,0 +1,1851 @@ +#! /bin/sh +# Configuration validation subroutine script. +# Copyright 1992-2020 Free Software Foundation, Inc. + +timestamp='2020-08-05' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that +# program. This Exception is an additional permission under section 7 +# of the GNU General Public License, version 3 ("GPLv3"). + + +# Please send patches to . +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# You can get the latest version of this script from: +# https://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS or ALIAS + +Canonicalize a configuration name. + +Options: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.sub ($timestamp) + +Copyright 1992-2020 Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo "$1" + exit ;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Split fields of configuration type +# shellcheck disable=SC2162 +IFS="-" read field1 field2 field3 field4 <&2 + exit 1 + ;; + *-*-*-*) + basic_machine=$field1-$field2 + basic_os=$field3-$field4 + ;; + *-*-*) + # Ambiguous whether COMPANY is present, or skipped and KERNEL-OS is two + # parts + maybe_os=$field2-$field3 + case $maybe_os in + nto-qnx* | linux-* | uclinux-uclibc* \ + | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* \ + | netbsd*-eabi* | kopensolaris*-gnu* | cloudabi*-eabi* \ + | storm-chaos* | os2-emx* | rtmk-nova*) + basic_machine=$field1 + basic_os=$maybe_os + ;; + android-linux) + basic_machine=$field1-unknown + basic_os=linux-android + ;; + *) + basic_machine=$field1-$field2 + basic_os=$field3 + ;; + esac + ;; + *-*) + # A lone config we happen to match not fitting any pattern + case $field1-$field2 in + decstation-3100) + basic_machine=mips-dec + basic_os= + ;; + *-*) + # Second component is usually, but not always the OS + case $field2 in + # Prevent following clause from handling this valid os + sun*os*) + basic_machine=$field1 + basic_os=$field2 + ;; + # Manufacturers + dec* | mips* | sequent* | encore* | pc533* | sgi* | sony* \ + | att* | 7300* | 3300* | delta* | motorola* | sun[234]* \ + | unicom* | ibm* | next | hp | isi* | apollo | altos* \ + | convergent* | ncr* | news | 32* | 3600* | 3100* \ + | hitachi* | c[123]* | convex* | sun | crds | omron* | dg \ + | ultra | tti* | harris | dolphin | highlevel | gould \ + | cbm | ns | masscomp | apple | axis | knuth | cray \ + | microblaze* | sim | cisco \ + | oki | wec | wrs | winbond) + basic_machine=$field1-$field2 + basic_os= + ;; + *) + basic_machine=$field1 + basic_os=$field2 + ;; + esac + ;; + esac + ;; + *) + # Convert single-component short-hands not valid as part of + # multi-component configurations. + case $field1 in + 386bsd) + basic_machine=i386-pc + basic_os=bsd + ;; + a29khif) + basic_machine=a29k-amd + basic_os=udi + ;; + adobe68k) + basic_machine=m68010-adobe + basic_os=scout + ;; + alliant) + basic_machine=fx80-alliant + basic_os= + ;; + altos | altos3068) + basic_machine=m68k-altos + basic_os= + ;; + am29k) + basic_machine=a29k-none + basic_os=bsd + ;; + amdahl) + basic_machine=580-amdahl + basic_os=sysv + ;; + amiga) + basic_machine=m68k-unknown + basic_os= + ;; + amigaos | amigados) + basic_machine=m68k-unknown + basic_os=amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + basic_os=sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + basic_os=sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + basic_os=bsd + ;; + aros) + basic_machine=i386-pc + basic_os=aros + ;; + aux) + basic_machine=m68k-apple + basic_os=aux + ;; + balance) + basic_machine=ns32k-sequent + basic_os=dynix + ;; + blackfin) + basic_machine=bfin-unknown + basic_os=linux + ;; + cegcc) + basic_machine=arm-unknown + basic_os=cegcc + ;; + convex-c1) + basic_machine=c1-convex + basic_os=bsd + ;; + convex-c2) + basic_machine=c2-convex + basic_os=bsd + ;; + convex-c32) + basic_machine=c32-convex + basic_os=bsd + ;; + convex-c34) + basic_machine=c34-convex + basic_os=bsd + ;; + convex-c38) + basic_machine=c38-convex + basic_os=bsd + ;; + cray) + basic_machine=j90-cray + basic_os=unicos + ;; + crds | unos) + basic_machine=m68k-crds + basic_os= + ;; + da30) + basic_machine=m68k-da30 + basic_os= + ;; + decstation | pmax | pmin | dec3100 | decstatn) + basic_machine=mips-dec + basic_os= + ;; + delta88) + basic_machine=m88k-motorola + basic_os=sysv3 + ;; + dicos) + basic_machine=i686-pc + basic_os=dicos + ;; + djgpp) + basic_machine=i586-pc + basic_os=msdosdjgpp + ;; + ebmon29k) + basic_machine=a29k-amd + basic_os=ebmon + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + basic_os=ose + ;; + gmicro) + basic_machine=tron-gmicro + basic_os=sysv + ;; + go32) + basic_machine=i386-pc + basic_os=go32 + ;; + h8300hms) + basic_machine=h8300-hitachi + basic_os=hms + ;; + h8300xray) + basic_machine=h8300-hitachi + basic_os=xray + ;; + h8500hms) + basic_machine=h8500-hitachi + basic_os=hms + ;; + harris) + basic_machine=m88k-harris + basic_os=sysv3 + ;; + hp300 | hp300hpux) + basic_machine=m68k-hp + basic_os=hpux + ;; + hp300bsd) + basic_machine=m68k-hp + basic_os=bsd + ;; + hppaosf) + basic_machine=hppa1.1-hp + basic_os=osf + ;; + hppro) + basic_machine=hppa1.1-hp + basic_os=proelf + ;; + i386mach) + basic_machine=i386-mach + basic_os=mach + ;; + isi68 | isi) + basic_machine=m68k-isi + basic_os=sysv + ;; + m68knommu) + basic_machine=m68k-unknown + basic_os=linux + ;; + magnum | m3230) + basic_machine=mips-mips + basic_os=sysv + ;; + merlin) + basic_machine=ns32k-utek + basic_os=sysv + ;; + mingw64) + basic_machine=x86_64-pc + basic_os=mingw64 + ;; + mingw32) + basic_machine=i686-pc + basic_os=mingw32 + ;; + mingw32ce) + basic_machine=arm-unknown + basic_os=mingw32ce + ;; + monitor) + basic_machine=m68k-rom68k + basic_os=coff + ;; + morphos) + basic_machine=powerpc-unknown + basic_os=morphos + ;; + moxiebox) + basic_machine=moxie-unknown + basic_os=moxiebox + ;; + msdos) + basic_machine=i386-pc + basic_os=msdos + ;; + msys) + basic_machine=i686-pc + basic_os=msys + ;; + mvs) + basic_machine=i370-ibm + basic_os=mvs + ;; + nacl) + basic_machine=le32-unknown + basic_os=nacl + ;; + ncr3000) + basic_machine=i486-ncr + basic_os=sysv4 + ;; + netbsd386) + basic_machine=i386-pc + basic_os=netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + basic_os=linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + basic_os=newsos + ;; + news1000) + basic_machine=m68030-sony + basic_os=newsos + ;; + necv70) + basic_machine=v70-nec + basic_os=sysv + ;; + nh3000) + basic_machine=m68k-harris + basic_os=cxux + ;; + nh[45]000) + basic_machine=m88k-harris + basic_os=cxux + ;; + nindy960) + basic_machine=i960-intel + basic_os=nindy + ;; + mon960) + basic_machine=i960-intel + basic_os=mon960 + ;; + nonstopux) + basic_machine=mips-compaq + basic_os=nonstopux + ;; + os400) + basic_machine=powerpc-ibm + basic_os=os400 + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + basic_os=ose + ;; + os68k) + basic_machine=m68k-none + basic_os=os68k + ;; + paragon) + basic_machine=i860-intel + basic_os=osf + ;; + parisc) + basic_machine=hppa-unknown + basic_os=linux + ;; + psp) + basic_machine=mipsallegrexel-sony + basic_os=psp + ;; + pw32) + basic_machine=i586-unknown + basic_os=pw32 + ;; + rdos | rdos64) + basic_machine=x86_64-pc + basic_os=rdos + ;; + rdos32) + basic_machine=i386-pc + basic_os=rdos + ;; + rom68k) + basic_machine=m68k-rom68k + basic_os=coff + ;; + sa29200) + basic_machine=a29k-amd + basic_os=udi + ;; + sei) + basic_machine=mips-sei + basic_os=seiux + ;; + sequent) + basic_machine=i386-sequent + basic_os= + ;; + sps7) + basic_machine=m68k-bull + basic_os=sysv2 + ;; + st2000) + basic_machine=m68k-tandem + basic_os= + ;; + stratus) + basic_machine=i860-stratus + basic_os=sysv4 + ;; + sun2) + basic_machine=m68000-sun + basic_os= + ;; + sun2os3) + basic_machine=m68000-sun + basic_os=sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + basic_os=sunos4 + ;; + sun3) + basic_machine=m68k-sun + basic_os= + ;; + sun3os3) + basic_machine=m68k-sun + basic_os=sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + basic_os=sunos4 + ;; + sun4) + basic_machine=sparc-sun + basic_os= + ;; + sun4os3) + basic_machine=sparc-sun + basic_os=sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + basic_os=sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + basic_os=solaris2 + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + basic_os= + ;; + sv1) + basic_machine=sv1-cray + basic_os=unicos + ;; + symmetry) + basic_machine=i386-sequent + basic_os=dynix + ;; + t3e) + basic_machine=alphaev5-cray + basic_os=unicos + ;; + t90) + basic_machine=t90-cray + basic_os=unicos + ;; + toad1) + basic_machine=pdp10-xkl + basic_os=tops20 + ;; + tpf) + basic_machine=s390x-ibm + basic_os=tpf + ;; + udi29k) + basic_machine=a29k-amd + basic_os=udi + ;; + ultra3) + basic_machine=a29k-nyu + basic_os=sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + basic_os=none + ;; + vaxv) + basic_machine=vax-dec + basic_os=sysv + ;; + vms) + basic_machine=vax-dec + basic_os=vms + ;; + vsta) + basic_machine=i386-pc + basic_os=vsta + ;; + vxworks960) + basic_machine=i960-wrs + basic_os=vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + basic_os=vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + basic_os=vxworks + ;; + xbox) + basic_machine=i686-pc + basic_os=mingw32 + ;; + ymp) + basic_machine=ymp-cray + basic_os=unicos + ;; + *) + basic_machine=$1 + basic_os= + ;; + esac + ;; +esac + +# Decode 1-component or ad-hoc basic machines +case $basic_machine in + # Here we handle the default manufacturer of certain CPU types. It is in + # some cases the only manufacturer, in others, it is the most popular. + w89k) + cpu=hppa1.1 + vendor=winbond + ;; + op50n) + cpu=hppa1.1 + vendor=oki + ;; + op60c) + cpu=hppa1.1 + vendor=oki + ;; + ibm*) + cpu=i370 + vendor=ibm + ;; + orion105) + cpu=clipper + vendor=highlevel + ;; + mac | mpw | mac-mpw) + cpu=m68k + vendor=apple + ;; + pmac | pmac-mpw) + cpu=powerpc + vendor=apple + ;; + + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + cpu=m68000 + vendor=att + ;; + 3b*) + cpu=we32k + vendor=att + ;; + bluegene*) + cpu=powerpc + vendor=ibm + basic_os=cnk + ;; + decsystem10* | dec10*) + cpu=pdp10 + vendor=dec + basic_os=tops10 + ;; + decsystem20* | dec20*) + cpu=pdp10 + vendor=dec + basic_os=tops20 + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + cpu=m68k + vendor=motorola + ;; + dpx2*) + cpu=m68k + vendor=bull + basic_os=sysv3 + ;; + encore | umax | mmax) + cpu=ns32k + vendor=encore + ;; + elxsi) + cpu=elxsi + vendor=elxsi + basic_os=${basic_os:-bsd} + ;; + fx2800) + cpu=i860 + vendor=alliant + ;; + genix) + cpu=ns32k + vendor=ns + ;; + h3050r* | hiux*) + cpu=hppa1.1 + vendor=hitachi + basic_os=hiuxwe2 + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + cpu=hppa1.0 + vendor=hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + cpu=m68000 + vendor=hp + ;; + hp9k3[2-9][0-9]) + cpu=m68k + vendor=hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + cpu=hppa1.0 + vendor=hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + cpu=hppa1.1 + vendor=hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + cpu=hppa1.1 + vendor=hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + cpu=hppa1.1 + vendor=hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + cpu=hppa1.1 + vendor=hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + cpu=hppa1.0 + vendor=hp + ;; + i*86v32) + cpu=`echo "$1" | sed -e 's/86.*/86/'` + vendor=pc + basic_os=sysv32 + ;; + i*86v4*) + cpu=`echo "$1" | sed -e 's/86.*/86/'` + vendor=pc + basic_os=sysv4 + ;; + i*86v) + cpu=`echo "$1" | sed -e 's/86.*/86/'` + vendor=pc + basic_os=sysv + ;; + i*86sol2) + cpu=`echo "$1" | sed -e 's/86.*/86/'` + vendor=pc + basic_os=solaris2 + ;; + j90 | j90-cray) + cpu=j90 + vendor=cray + basic_os=${basic_os:-unicos} + ;; + iris | iris4d) + cpu=mips + vendor=sgi + case $basic_os in + irix*) + ;; + *) + basic_os=irix4 + ;; + esac + ;; + miniframe) + cpu=m68000 + vendor=convergent + ;; + *mint | mint[0-9]* | *MiNT | *MiNT[0-9]*) + cpu=m68k + vendor=atari + basic_os=mint + ;; + news-3600 | risc-news) + cpu=mips + vendor=sony + basic_os=newsos + ;; + next | m*-next) + cpu=m68k + vendor=next + case $basic_os in + openstep*) + ;; + nextstep*) + ;; + ns2*) + basic_os=nextstep2 + ;; + *) + basic_os=nextstep3 + ;; + esac + ;; + np1) + cpu=np1 + vendor=gould + ;; + op50n-* | op60c-*) + cpu=hppa1.1 + vendor=oki + basic_os=proelf + ;; + pa-hitachi) + cpu=hppa1.1 + vendor=hitachi + basic_os=hiuxwe2 + ;; + pbd) + cpu=sparc + vendor=tti + ;; + pbb) + cpu=m68k + vendor=tti + ;; + pc532) + cpu=ns32k + vendor=pc532 + ;; + pn) + cpu=pn + vendor=gould + ;; + power) + cpu=power + vendor=ibm + ;; + ps2) + cpu=i386 + vendor=ibm + ;; + rm[46]00) + cpu=mips + vendor=siemens + ;; + rtpc | rtpc-*) + cpu=romp + vendor=ibm + ;; + sde) + cpu=mipsisa32 + vendor=sde + basic_os=${basic_os:-elf} + ;; + simso-wrs) + cpu=sparclite + vendor=wrs + basic_os=vxworks + ;; + tower | tower-32) + cpu=m68k + vendor=ncr + ;; + vpp*|vx|vx-*) + cpu=f301 + vendor=fujitsu + ;; + w65) + cpu=w65 + vendor=wdc + ;; + w89k-*) + cpu=hppa1.1 + vendor=winbond + basic_os=proelf + ;; + none) + cpu=none + vendor=none + ;; + leon|leon[3-9]) + cpu=sparc + vendor=$basic_machine + ;; + leon-*|leon[3-9]-*) + cpu=sparc + vendor=`echo "$basic_machine" | sed 's/-.*//'` + ;; + + *-*) + # shellcheck disable=SC2162 + IFS="-" read cpu vendor <&2 + exit 1 + ;; + esac + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $vendor in + digital*) + vendor=dec + ;; + commodore*) + vendor=cbm + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if [ x$basic_os != x ] +then + +# First recognize some ad-hoc caes, or perhaps split kernel-os, or else just +# set os. +case $basic_os in + gnu/linux*) + kernel=linux + os=`echo $basic_os | sed -e 's|gnu/linux|gnu|'` + ;; + nto-qnx*) + kernel=nto + os=`echo $basic_os | sed -e 's|nto-qnx|qnx|'` + ;; + *-*) + # shellcheck disable=SC2162 + IFS="-" read kernel os <&2 + exit 1 + ;; +esac + +# As a final step for OS-related things, validate the OS-kernel combination +# (given a valid OS), if there is a kernel. +case $kernel-$os in + linux-gnu* | linux-dietlibc* | linux-android* | linux-newlib* | linux-musl* | linux-uclibc* ) + ;; + -dietlibc* | -newlib* | -musl* | -uclibc* ) + # These are just libc implementations, not actual OSes, and thus + # require a kernel. + echo "Invalid configuration \`$1': libc \`$os' needs explicit kernel." 1>&2 + exit 1 + ;; + kfreebsd*-gnu* | kopensolaris*-gnu*) + ;; + nto-qnx*) + ;; + *-eabi* | *-gnueabi*) + ;; + -*) + # Blank kernel with real OS is always fine. + ;; + *-*) + echo "Invalid configuration \`$1': Kernel \`$kernel' not known to work with OS \`$os'." 1>&2 + exit 1 + ;; +esac + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +case $vendor in + unknown) + case $cpu-$os in + *-riscix*) + vendor=acorn + ;; + *-sunos*) + vendor=sun + ;; + *-cnk* | *-aix*) + vendor=ibm + ;; + *-beos*) + vendor=be + ;; + *-hpux*) + vendor=hp + ;; + *-mpeix*) + vendor=hp + ;; + *-hiux*) + vendor=hitachi + ;; + *-unos*) + vendor=crds + ;; + *-dgux*) + vendor=dg + ;; + *-luna*) + vendor=omron + ;; + *-genix*) + vendor=ns + ;; + *-clix*) + vendor=intergraph + ;; + *-mvs* | *-opened*) + vendor=ibm + ;; + *-os400*) + vendor=ibm + ;; + s390-* | s390x-*) + vendor=ibm + ;; + *-ptx*) + vendor=sequent + ;; + *-tpf*) + vendor=ibm + ;; + *-vxsim* | *-vxworks* | *-windiss*) + vendor=wrs + ;; + *-aux*) + vendor=apple + ;; + *-hms*) + vendor=hitachi + ;; + *-mpw* | *-macos*) + vendor=apple + ;; + *-*mint | *-mint[0-9]* | *-*MiNT | *-MiNT[0-9]*) + vendor=atari + ;; + *-vos*) + vendor=stratus + ;; + esac + ;; +esac + +echo "$cpu-$vendor-${kernel:+$kernel-}$os" +exit + +# Local variables: +# eval: (add-hook 'before-save-hook 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/configure.ac b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/configure.ac new file mode 100644 index 0000000..093b87d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/configure.ac @@ -0,0 +1,415 @@ +dnl Process this with autoconf to create configure + +AC_PREREQ(2.68) + +AC_INIT([libffi], [3.3], [http://github.com/libffi/libffi/issues]) +AC_CONFIG_HEADERS([fficonfig.h]) + +AC_CANONICAL_SYSTEM +target_alias=${target_alias-$host_alias} + +case "${host}" in + frv*-elf) + LDFLAGS=`echo $LDFLAGS | sed "s/\-B[^ ]*libgloss\/frv\///"`\ -B`pwd`/../libgloss/frv/ + ;; +esac + +AX_ENABLE_BUILDDIR + +AM_INIT_AUTOMAKE + +# The same as in boehm-gc and libstdc++. Have to borrow it from there. +# We must force CC to /not/ be precious variables; otherwise +# the wrong, non-multilib-adjusted value will be used in multilibs. +# As a side effect, we have to subst CFLAGS ourselves. +# Also save and restore CFLAGS, since AC_PROG_CC will come up with +# defaults of its own if none are provided. + +m4_rename([_AC_ARG_VAR_PRECIOUS],[real_PRECIOUS]) +m4_define([_AC_ARG_VAR_PRECIOUS],[]) +save_CFLAGS=$CFLAGS +AC_PROG_CC +AC_PROG_CXX +CFLAGS=$save_CFLAGS +m4_undefine([_AC_ARG_VAR_PRECIOUS]) +m4_rename_force([real_PRECIOUS],[_AC_ARG_VAR_PRECIOUS]) + +AC_SUBST(CFLAGS) + +AM_PROG_AS +AM_PROG_CC_C_O +AC_PROG_LIBTOOL +AC_CONFIG_MACRO_DIR([m4]) + +# Test for 64-bit build. +AC_CHECK_SIZEOF([size_t]) + +AX_COMPILER_VENDOR +AX_CC_MAXOPT +# The AX_CFLAGS_WARN_ALL macro doesn't currently work for sunpro +# compiler. +if test "$ax_cv_c_compiler_vendor" != "sun"; then + AX_CFLAGS_WARN_ALL +fi + +if test "x$GCC" = "xyes"; then + CFLAGS="$CFLAGS -fexceptions" +fi + +cat > local.exp < conftest.s + if $CC $CFLAGS -c conftest.s > /dev/null 2>&1; then + libffi_cv_as_x86_pcrel=yes + fi + ]) + if test "x$libffi_cv_as_x86_pcrel" = xyes; then + AC_DEFINE(HAVE_AS_X86_PCREL, 1, + [Define if your assembler supports PC relative relocs.]) + fi + ;; + + S390) + AC_CACHE_CHECK([compiler uses zarch features], + libffi_cv_as_s390_zarch, [ + libffi_cv_as_s390_zarch=no + echo 'void foo(void) { bar(); bar(); }' > conftest.c + if $CC $CFLAGS -S conftest.c > /dev/null 2>&1; then + if grep -q brasl conftest.s; then + libffi_cv_as_s390_zarch=yes + fi + fi + ]) + if test "x$libffi_cv_as_s390_zarch" = xyes; then + AC_DEFINE(HAVE_AS_S390_ZARCH, 1, + [Define if the compiler uses zarch features.]) + fi + ;; +esac + +AC_CACHE_CHECK([whether compiler supports pointer authentication], + libffi_cv_as_ptrauth, [ + libffi_cv_as_ptrauth=unknown + AC_TRY_COMPILE(,[ +#ifdef __clang__ +# if __has_feature(ptrauth_calls) +# define HAVE_PTRAUTH 1 +# endif +#endif + +#ifndef HAVE_PTRAUTH +# error Pointer authentication not supported +#endif + ], + [libffi_cv_as_ptrauth=yes], + [libffi_cv_as_ptrauth=no]) +]) +if test "x$libffi_cv_as_ptrauth" = xyes; then + AC_DEFINE(HAVE_PTRAUTH, 1, + [Define if your compiler supports pointer authentication.]) +fi + +# On PaX enable kernels that have MPROTECT enable we can't use PROT_EXEC. +AC_ARG_ENABLE(pax_emutramp, + [ --enable-pax_emutramp enable pax emulated trampolines, for we can't use PROT_EXEC], + if test "$enable_pax_emutramp" = "yes"; then + AC_DEFINE(FFI_MMAP_EXEC_EMUTRAMP_PAX, 1, + [Define this if you want to enable pax emulated trampolines]) + fi) + +LT_SYS_SYMBOL_USCORE +if test "x$sys_symbol_underscore" = xyes; then + AC_DEFINE(SYMBOL_UNDERSCORE, 1, [Define if symbols are underscored.]) +fi + +FFI_EXEC_TRAMPOLINE_TABLE=0 +case "$target" in + *arm*-apple-* | aarch64-apple-*) + FFI_EXEC_TRAMPOLINE_TABLE=1 + AC_DEFINE(FFI_EXEC_TRAMPOLINE_TABLE, 1, + [Cannot use PROT_EXEC on this target, so, we revert to + alternative means]) + ;; + *-apple-* | *-*-freebsd* | *-*-kfreebsd* | *-*-openbsd* | *-pc-solaris* | *-linux-android*) + AC_DEFINE(FFI_MMAP_EXEC_WRIT, 1, + [Cannot use malloc on this target, so, we revert to + alternative means]) + ;; +esac +AM_CONDITIONAL(FFI_EXEC_TRAMPOLINE_TABLE, test x$FFI_EXEC_TRAMPOLINE_TABLE = x1) +AC_SUBST(FFI_EXEC_TRAMPOLINE_TABLE) + +if test x$TARGET = xX86_64; then + AC_CACHE_CHECK([toolchain supports unwind section type], + libffi_cv_as_x86_64_unwind_section_type, [ + cat > conftest1.s << EOF +.text +.globl foo +foo: +jmp bar +.section .eh_frame,"a",@unwind +bar: +EOF + + cat > conftest2.c << EOF +extern void foo(); +int main(){foo();} +EOF + + libffi_cv_as_x86_64_unwind_section_type=no + # we ensure that we can compile _and_ link an assembly file containing an @unwind section + # since the compiler can support it and not the linker (ie old binutils) + if $CC -Wa,--fatal-warnings $CFLAGS -c conftest1.s > /dev/null 2>&1 && \ + $CC conftest2.c conftest1.o > /dev/null 2>&1 ; then + libffi_cv_as_x86_64_unwind_section_type=yes + fi + ]) + if test "x$libffi_cv_as_x86_64_unwind_section_type" = xyes; then + AC_DEFINE(HAVE_AS_X86_64_UNWIND_SECTION_TYPE, 1, + [Define if your assembler supports unwind section type.]) + fi +fi + +if test "x$GCC" = "xyes"; then + AX_CHECK_COMPILE_FLAG(-fno-lto, libffi_cv_no_lto=-fno-lto) + + AC_CACHE_CHECK([whether .eh_frame section should be read-only], + libffi_cv_ro_eh_frame, [ + libffi_cv_ro_eh_frame=yes + echo 'extern void foo (void); void bar (void) { foo (); foo (); }' > conftest.c + if $CC $CFLAGS -c -fpic -fexceptions $libffi_cv_no_lto -o conftest.o conftest.c > /dev/null 2>&1; then + if readelf -WS conftest.o | grep -q -n 'eh_frame .* WA'; then + libffi_cv_ro_eh_frame=no + fi + fi + rm -f conftest.* + ]) + if test "x$libffi_cv_ro_eh_frame" = xyes; then + AC_DEFINE(HAVE_RO_EH_FRAME, 1, + [Define if .eh_frame sections should be read-only.]) + AC_DEFINE(EH_FRAME_FLAGS, "a", + [Define to the flags needed for the .section .eh_frame directive. ]) + else + AC_DEFINE(EH_FRAME_FLAGS, "aw", + [Define to the flags needed for the .section .eh_frame directive. ]) + fi + + AC_CACHE_CHECK([for __attribute__((visibility("hidden")))], + libffi_cv_hidden_visibility_attribute, [ + echo 'int __attribute__ ((visibility ("hidden"))) foo (void) { return 1 ; }' > conftest.c + libffi_cv_hidden_visibility_attribute=no + if AC_TRY_COMMAND(${CC-cc} -Werror -S conftest.c -o conftest.s 1>&AS_MESSAGE_LOG_FD); then + if egrep '(\.hidden|\.private_extern).*foo' conftest.s >/dev/null; then + libffi_cv_hidden_visibility_attribute=yes + fi + fi + rm -f conftest.* + ]) + if test $libffi_cv_hidden_visibility_attribute = yes; then + AC_DEFINE(HAVE_HIDDEN_VISIBILITY_ATTRIBUTE, 1, + [Define if __attribute__((visibility("hidden"))) is supported.]) + fi +fi + +AC_ARG_ENABLE(docs, + AC_HELP_STRING([--disable-docs], + [Disable building of docs (default: no)]), + [enable_docs=no], + [enable_docs=yes]) +AM_CONDITIONAL(BUILD_DOCS, [test x$enable_docs = xyes]) + +AH_BOTTOM([ +#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE +#ifdef LIBFFI_ASM +#ifdef __APPLE__ +#define FFI_HIDDEN(name) .private_extern name +#else +#define FFI_HIDDEN(name) .hidden name +#endif +#else +#define FFI_HIDDEN __attribute__ ((visibility ("hidden"))) +#endif +#else +#ifdef LIBFFI_ASM +#define FFI_HIDDEN(name) +#else +#define FFI_HIDDEN +#endif +#endif +]) + +AC_SUBST(TARGET) +AC_SUBST(TARGETDIR) + +changequote(<,>) +TARGET_OBJ= +for i in $SOURCES; do + TARGET_OBJ="${TARGET_OBJ} src/${TARGETDIR}/"`echo $i | sed 's/[cS]$/lo/'` +done +changequote([,]) +AC_SUBST(TARGET_OBJ) + +AC_SUBST(SHELL) + +AC_ARG_ENABLE(debug, +[ --enable-debug debugging mode], + if test "$enable_debug" = "yes"; then + AC_DEFINE(FFI_DEBUG, 1, [Define this if you want extra debugging.]) + fi) +AM_CONDITIONAL(FFI_DEBUG, test "$enable_debug" = "yes") + +AC_ARG_ENABLE(structs, +[ --disable-structs omit code for struct support], + if test "$enable_structs" = "no"; then + AC_DEFINE(FFI_NO_STRUCTS, 1, [Define this if you do not want support for aggregate types.]) + fi) +AM_CONDITIONAL(FFI_DEBUG, test "$enable_debug" = "yes") + +AC_ARG_ENABLE(raw-api, +[ --disable-raw-api make the raw api unavailable], + if test "$enable_raw_api" = "no"; then + AC_DEFINE(FFI_NO_RAW_API, 1, [Define this if you do not want support for the raw API.]) + fi) + +AC_ARG_ENABLE(purify-safety, +[ --enable-purify-safety purify-safe mode], + if test "$enable_purify_safety" = "yes"; then + AC_DEFINE(USING_PURIFY, 1, [Define this if you are using Purify and want to suppress spurious messages.]) + fi) + +AC_ARG_ENABLE(multi-os-directory, +[ --disable-multi-os-directory + disable use of gcc --print-multi-os-directory to change the library installation directory]) + +# These variables are only ever used when we cross-build to X86_WIN32. +# And we only support this with GCC, so... +if test "x$GCC" = "xyes"; then + if test -n "$with_cross_host" && + test x"$with_cross_host" != x"no"; then + toolexecdir='${exec_prefix}'/'$(target_alias)' + toolexeclibdir='${toolexecdir}'/lib + else + toolexecdir='${libdir}'/gcc-lib/'$(target_alias)' + toolexeclibdir='${libdir}' + fi + if test x"$enable_multi_os_directory" != x"no"; then + multi_os_directory=`$CC $CFLAGS -print-multi-os-directory` + case $multi_os_directory in + .) ;; # Avoid trailing /. + ../*) toolexeclibdir=$toolexeclibdir/$multi_os_directory ;; + esac + fi + AC_SUBST(toolexecdir) +else + toolexeclibdir='${libdir}' +fi +AC_SUBST(toolexeclibdir) + +# Check linker support. +LIBFFI_ENABLE_SYMVERS + +AC_CONFIG_COMMANDS(include, [test -d include || mkdir include]) +AC_CONFIG_COMMANDS(src, [ +test -d src || mkdir src +test -d src/$TARGETDIR || mkdir src/$TARGETDIR +], [TARGETDIR="$TARGETDIR"]) + +AC_CONFIG_FILES(include/Makefile include/ffi.h Makefile testsuite/Makefile man/Makefile doc/Makefile libffi.pc) + +AC_OUTPUT + +# Copy this file instead of using AC_CONFIG_LINK in order to support +# compiling with MSVC, which won't understand cygwin style symlinks. +cp ${srcdir}/src/$TARGETDIR/ffitarget.h include/ffitarget.h diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/configure.host b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/configure.host new file mode 100644 index 0000000..257b784 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/configure.host @@ -0,0 +1,318 @@ +# configure.host +# +# This shell script handles all host based configuration for libffi. +# + +# THIS TABLE IS SORTED. KEEP IT THAT WAY. +# Most of the time we can define all the variables all at once... +case "${host}" in + aarch64*-*-cygwin* | aarch64*-*-mingw* | aarch64*-*-win* ) + TARGET=ARM_WIN64; TARGETDIR=aarch64 + if test "${ax_cv_c_compiler_vendor}" = "microsoft"; then + MSVC=1 + fi + ;; + + aarch64*-*-*) + TARGET=AARCH64; TARGETDIR=aarch64 + SOURCES="ffi.c sysv.S" + ;; + + alpha*-*-*) + TARGET=ALPHA; TARGETDIR=alpha; + # Support 128-bit long double, changeable via command-line switch. + HAVE_LONG_DOUBLE='defined(__LONG_DOUBLE_128__)' + SOURCES="ffi.c osf.S" + ;; + + arc*-*-*) + TARGET=ARC; TARGETDIR=arc + SOURCES="ffi.c arcompact.S" + ;; + + arm*-*-cygwin* | arm*-*-mingw* | arm*-*-win* ) + TARGET=ARM_WIN32; TARGETDIR=arm + MSVC=1 + ;; + + arm*-*-*) + TARGET=ARM; TARGETDIR=arm + SOURCES="ffi.c sysv.S" + ;; + + avr32*-*-*) + TARGET=AVR32; TARGETDIR=avr32 + SOURCES="ffi.c sysv.S" + ;; + + bfin*) + TARGET=BFIN; TARGETDIR=bfin + SOURCES="ffi.c sysv.S" + ;; + + cris-*-*) + TARGET=LIBFFI_CRIS; TARGETDIR=cris + SOURCES="ffi.c sysv.S" + ;; + + csky-*-*) + TARGET=CSKY; TARGETDIR=csky + SOURCES="ffi.c sysv.S" + ;; + + frv-*-*) + TARGET=FRV; TARGETDIR=frv + SOURCES="ffi.c eabi.S" + ;; + + hppa*-*-linux* | parisc*-*-linux* | hppa*-*-openbsd*) + TARGET=PA_LINUX; TARGETDIR=pa + SOURCES="ffi.c linux.S" + ;; + hppa*64-*-hpux*) + TARGET=PA64_HPUX; TARGETDIR=pa + ;; + hppa*-*-hpux*) + TARGET=PA_HPUX; TARGETDIR=pa + SOURCES="ffi.c hpux32.S" + ;; + + i?86-*-freebsd* | i?86-*-openbsd*) + TARGET=X86_FREEBSD; TARGETDIR=x86 + ;; + + i?86-*-cygwin* | i?86-*-mingw* | i?86-*-win* | i?86-*-os2* | i?86-*-interix* \ + | x86_64-*-cygwin* | x86_64-*-mingw* | x86_64-*-win* ) + TARGETDIR=x86 + if test $ac_cv_sizeof_size_t = 4; then + TARGET=X86_WIN32 + else + TARGET=X86_WIN64 + fi + if test "${ax_cv_c_compiler_vendor}" = "microsoft"; then + MSVC=1 + fi + # All mingw/cygwin/win32 builds require -no-undefined for sharedlib. + # We must also check with_cross_host to decide if this is a native + # or cross-build and select where to install dlls appropriately. + if test -n "$with_cross_host" && + test x"$with_cross_host" != x"no"; then + AM_LTLDFLAGS='-no-undefined -bindir "$(toolexeclibdir)"'; + else + AM_LTLDFLAGS='-no-undefined -bindir "$(bindir)"'; + fi + ;; + + i?86-*-darwin* | x86_64-*-darwin* | i?86-*-ios | x86_64-*-ios) + TARGETDIR=x86 + if test $ac_cv_sizeof_size_t = 4; then + TARGET=X86_DARWIN + else + TARGET=X86_64 + fi + ;; + + i?86-*-* | x86_64-*-* | amd64-*) + TARGETDIR=x86 + if test $ac_cv_sizeof_size_t = 4; then + echo 'int foo (void) { return __x86_64__; }' > conftest.c + if $CC $CFLAGS -Werror -S conftest.c -o conftest.s > /dev/null 2>&1; then + TARGET_X32=yes + TARGET=X86_64 + else + TARGET=X86; + fi + rm -f conftest.* + else + TARGET=X86_64; + fi + ;; + + ia64*-*-*) + TARGET=IA64; TARGETDIR=ia64 + SOURCES="ffi.c unix.S" + ;; + + kvx-*-*) + TARGET=KVX; TARGETDIR=kvx + SOURCES="ffi.c sysv.S" + ;; + + m32r*-*-*) + TARGET=M32R; TARGETDIR=m32r + SOURCES="ffi.c sysv.S" + ;; + + m68k-*-*) + TARGET=M68K; TARGETDIR=m68k + SOURCES="ffi.c sysv.S" + ;; + + m88k-*-*) + TARGET=M88K; TARGETDIR=m88k + SOURCES="ffi.c obsd.S" + ;; + + microblaze*-*-*) + TARGET=MICROBLAZE; TARGETDIR=microblaze + SOURCES="ffi.c sysv.S" + ;; + + moxie-*-*) + TARGET=MOXIE; TARGETDIR=moxie + SOURCES="ffi.c eabi.S" + ;; + + metag-*-*) + TARGET=METAG; TARGETDIR=metag + SOURCES="ffi.c sysv.S" + ;; + + mips-sgi-irix5.* | mips-sgi-irix6.* | mips*-*-rtems*) + TARGET=MIPS; TARGETDIR=mips + ;; + mips*-*linux* | mips*-*-openbsd* | mips*-*-freebsd*) + # Support 128-bit long double for NewABI. + HAVE_LONG_DOUBLE='defined(__mips64)' + TARGET=MIPS; TARGETDIR=mips + ;; + + nios2*-linux*) + TARGET=NIOS2; TARGETDIR=nios2 + SOURCES="ffi.c sysv.S" + ;; + + or1k*-*-*) + TARGET=OR1K; TARGETDIR=or1k + SOURCES="ffi.c sysv.S" + ;; + + powerpc*-*-linux* | powerpc-*-sysv*) + TARGET=POWERPC; TARGETDIR=powerpc + HAVE_LONG_DOUBLE_VARIANT=1 + ;; + powerpc-*-amigaos*) + TARGET=POWERPC; TARGETDIR=powerpc + ;; + powerpc-*-eabi*) + TARGET=POWERPC; TARGETDIR=powerpc + ;; + powerpc-*-beos*) + TARGET=POWERPC; TARGETDIR=powerpc + ;; + powerpc-*-darwin* | powerpc64-*-darwin*) + TARGET=POWERPC_DARWIN; TARGETDIR=powerpc + ;; + powerpc-*-aix* | rs6000-*-aix*) + TARGET=POWERPC_AIX; TARGETDIR=powerpc + ;; + powerpc-*-freebsd* | powerpc-*-openbsd* | powerpc-*-netbsd*) + TARGET=POWERPC_FREEBSD; TARGETDIR=powerpc + HAVE_LONG_DOUBLE_VARIANT=1 + ;; + powerpcspe-*-freebsd*) + TARGET=POWERPC_FREEBSD; TARGETDIR=powerpc + CFLAGS="$CFLAGS -D__NO_FPRS__" + ;; + powerpc64-*-freebsd* | powerpc64le-*-freebsd*) + TARGET=POWERPC; TARGETDIR=powerpc + ;; + powerpc*-*-rtems*) + TARGET=POWERPC; TARGETDIR=powerpc + ;; + + riscv*-*) + TARGET=RISCV; TARGETDIR=riscv + SOURCES="ffi.c sysv.S" + ;; + + s390-*-* | s390x-*-*) + TARGET=S390; TARGETDIR=s390 + SOURCES="ffi.c sysv.S" + ;; + + sh-*-* | sh[34]*-*-*) + TARGET=SH; TARGETDIR=sh + SOURCES="ffi.c sysv.S" + ;; + sh64-*-* | sh5*-*-*) + TARGET=SH64; TARGETDIR=sh64 + SOURCES="ffi.c sysv.S" + ;; + + sparc*-*-*) + TARGET=SPARC; TARGETDIR=sparc + SOURCES="ffi.c ffi64.c v8.S v9.S" + ;; + + tile*-*) + TARGET=TILE; TARGETDIR=tile + SOURCES="ffi.c tile.S" + ;; + + vax-*-*) + TARGET=VAX; TARGETDIR=vax + SOURCES="ffi.c elfbsd.S" + ;; + + xtensa*-*) + TARGET=XTENSA; TARGETDIR=xtensa + SOURCES="ffi.c sysv.S" + ;; +esac + +# ... but some of the cases above share configury. +case "${TARGET}" in + ARM_WIN32) + SOURCES="ffi.c sysv_msvc_arm32.S" + ;; + ARM_WIN64) + if test "$MSVC" = 1; then + SOURCES="ffi.c win64_armasm.S" + else + SOURCES="ffi.c sysv.S" + fi + ;; + MIPS) + SOURCES="ffi.c o32.S n32.S" + ;; + POWERPC) + SOURCES="ffi.c ffi_sysv.c ffi_linux64.c sysv.S ppc_closure.S" + SOURCES="${SOURCES} linux64.S linux64_closure.S" + ;; + POWERPC_AIX) + SOURCES="ffi_darwin.c aix.S aix_closure.S" + ;; + POWERPC_DARWIN) + SOURCES="ffi_darwin.c darwin.S darwin_closure.S" + ;; + POWERPC_FREEBSD) + SOURCES="ffi.c ffi_sysv.c sysv.S ppc_closure.S" + ;; + X86 | X86_DARWIN | X86_FREEBSD | X86_WIN32) + if test "$MSVC" = 1; then + SOURCES="ffi.c sysv_intel.S" + else + SOURCES="ffi.c sysv.S" + fi + ;; + X86_64) + if test x"$TARGET_X32" = xyes; then + SOURCES="ffi64.c unix64.S" + else + SOURCES="ffi64.c unix64.S ffiw64.c win64.S" + fi + ;; + X86_WIN64) + if test "$MSVC" = 1; then + SOURCES="ffiw64.c win64_intel.S" + else + SOURCES="ffiw64.c win64.S" + fi + ;; +esac + +# If we failed to configure SOURCES, we can't do anything. +if test -z "${SOURCES}"; then + UNSUPPORTED=1 +fi diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/doc/Makefile.am b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/doc/Makefile.am new file mode 100644 index 0000000..43b650a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/doc/Makefile.am @@ -0,0 +1,3 @@ +## Process this with automake to create Makefile.in + +info_TEXINFOS = libffi.texi diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/doc/libffi.texi b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/doc/libffi.texi new file mode 100644 index 0000000..bd30593 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/doc/libffi.texi @@ -0,0 +1,997 @@ +\input texinfo @c -*-texinfo-*- +@c %**start of header +@setfilename libffi.info +@include version.texi +@settitle libffi: the portable foreign function interface library +@setchapternewpage off +@c %**end of header + +@c Merge the standard indexes into a single one. +@syncodeindex fn cp +@syncodeindex vr cp +@syncodeindex ky cp +@syncodeindex pg cp +@syncodeindex tp cp + +@copying + +This manual is for libffi, a portable foreign function interface +library. + +Copyright @copyright{} 2008--2019 Anthony Green and Red Hat, Inc. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +@end copying + +@dircategory Development +@direntry +* libffi: (libffi). Portable foreign function interface library. +@end direntry + +@titlepage +@title libffi: a foreign function interface library +@subtitle For Version @value{VERSION} of libffi +@author Anthony Green +@page +@vskip 0pt plus 1filll +@insertcopying +@end titlepage + + +@ifnottex +@node Top +@top libffi + +@insertcopying + +@menu +* Introduction:: What is libffi? +* Using libffi:: How to use libffi. +* Missing Features:: Things libffi can't do. +* Index:: Index. +@end menu + +@end ifnottex + + +@node Introduction +@chapter What is libffi? + +Compilers for high level languages generate code that follow certain +conventions. These conventions are necessary, in part, for separate +compilation to work. One such convention is the @dfn{calling +convention}. The calling convention is a set of assumptions made by +the compiler about where function arguments will be found on entry to +a function. A calling convention also specifies where the return +value for a function is found. The calling convention is also +sometimes called the @dfn{ABI} or @dfn{Application Binary Interface}. +@cindex calling convention +@cindex ABI +@cindex Application Binary Interface + +Some programs may not know at the time of compilation what arguments +are to be passed to a function. For instance, an interpreter may be +told at run-time about the number and types of arguments used to call +a given function. @samp{Libffi} can be used in such programs to +provide a bridge from the interpreter program to compiled code. + +The @samp{libffi} library provides a portable, high level programming +interface to various calling conventions. This allows a programmer to +call any function specified by a call interface description at run +time. + +@acronym{FFI} stands for Foreign Function Interface. A foreign +function interface is the popular name for the interface that allows +code written in one language to call code written in another language. +The @samp{libffi} library really only provides the lowest, machine +dependent layer of a fully featured foreign function interface. A +layer must exist above @samp{libffi} that handles type conversions for +values passed between the two languages. +@cindex FFI +@cindex Foreign Function Interface + + +@node Using libffi +@chapter Using libffi + +@menu +* The Basics:: The basic libffi API. +* Simple Example:: A simple example. +* Types:: libffi type descriptions. +* Multiple ABIs:: Different passing styles on one platform. +* The Closure API:: Writing a generic function. +* Closure Example:: A closure example. +* Thread Safety:: Thread safety. +@end menu + + +@node The Basics +@section The Basics + +@samp{Libffi} assumes that you have a pointer to the function you wish +to call and that you know the number and types of arguments to pass +it, as well as the return type of the function. + +The first thing you must do is create an @code{ffi_cif} object that +matches the signature of the function you wish to call. This is a +separate step because it is common to make multiple calls using a +single @code{ffi_cif}. The @dfn{cif} in @code{ffi_cif} stands for +Call InterFace. To prepare a call interface object, use the function +@code{ffi_prep_cif}. +@cindex cif + +@findex ffi_prep_cif +@defun ffi_status ffi_prep_cif (ffi_cif *@var{cif}, ffi_abi @var{abi}, unsigned int @var{nargs}, ffi_type *@var{rtype}, ffi_type **@var{argtypes}) +This initializes @var{cif} according to the given parameters. + +@var{abi} is the ABI to use; normally @code{FFI_DEFAULT_ABI} is what +you want. @ref{Multiple ABIs} for more information. + +@var{nargs} is the number of arguments that this function accepts. + +@var{rtype} is a pointer to an @code{ffi_type} structure that +describes the return type of the function. @xref{Types}. + +@var{argtypes} is a vector of @code{ffi_type} pointers. +@var{argtypes} must have @var{nargs} elements. If @var{nargs} is 0, +this argument is ignored. + +@code{ffi_prep_cif} returns a @code{libffi} status code, of type +@code{ffi_status}. This will be either @code{FFI_OK} if everything +worked properly; @code{FFI_BAD_TYPEDEF} if one of the @code{ffi_type} +objects is incorrect; or @code{FFI_BAD_ABI} if the @var{abi} parameter +is invalid. +@end defun + +If the function being called is variadic (varargs) then +@code{ffi_prep_cif_var} must be used instead of @code{ffi_prep_cif}. + +@findex ffi_prep_cif_var +@defun ffi_status ffi_prep_cif_var (ffi_cif *@var{cif}, ffi_abi @var{abi}, unsigned int @var{nfixedargs}, unsigned int @var{ntotalargs}, ffi_type *@var{rtype}, ffi_type **@var{argtypes}) +This initializes @var{cif} according to the given parameters for +a call to a variadic function. In general its operation is the +same as for @code{ffi_prep_cif} except that: + +@var{nfixedargs} is the number of fixed arguments, prior to any +variadic arguments. It must be greater than zero. + +@var{ntotalargs} the total number of arguments, including variadic +and fixed arguments. @var{argtypes} must have this many elements. + +Note that, different cif's must be prepped for calls to the same +function when different numbers of arguments are passed. + +Also note that a call to @code{ffi_prep_cif_var} with +@var{nfixedargs}=@var{nototalargs} is NOT equivalent to a call to +@code{ffi_prep_cif}. + +@end defun + +Note that the resulting @code{ffi_cif} holds pointers to all the +@code{ffi_type} objects that were used during initialization. You +must ensure that these type objects have a lifetime at least as long +as that of the @code{ffi_cif}. + +To call a function using an initialized @code{ffi_cif}, use the +@code{ffi_call} function: + +@findex ffi_call +@defun void ffi_call (ffi_cif *@var{cif}, void *@var{fn}, void *@var{rvalue}, void **@var{avalues}) +This calls the function @var{fn} according to the description given in +@var{cif}. @var{cif} must have already been prepared using +@code{ffi_prep_cif}. + +@var{rvalue} is a pointer to a chunk of memory that will hold the +result of the function call. This must be large enough to hold the +result, no smaller than the system register size (generally 32 or 64 +bits), and must be suitably aligned; it is the caller's responsibility +to ensure this. If @var{cif} declares that the function returns +@code{void} (using @code{ffi_type_void}), then @var{rvalue} is +ignored. + +In most situations, @samp{libffi} will handle promotion according to +the ABI. However, for historical reasons, there is a special case +with return values that must be handled by your code. In particular, +for integral (not @code{struct}) types that are narrower than the +system register size, the return value will be widened by +@samp{libffi}. @samp{libffi} provides a type, @code{ffi_arg}, that +can be used as the return type. For example, if the CIF was defined +with a return type of @code{char}, @samp{libffi} will try to store a +full @code{ffi_arg} into the return value. + +@var{avalues} is a vector of @code{void *} pointers that point to the +memory locations holding the argument values for a call. If @var{cif} +declares that the function has no arguments (i.e., @var{nargs} was 0), +then @var{avalues} is ignored. Note that argument values may be +modified by the callee (for instance, structs passed by value); the +burden of copying pass-by-value arguments is placed on the caller. + +Note that while the return value must be register-sized, arguments +should exactly match their declared type. For example, if an argument +is a @code{short}, then the entry in @var{avalues} should point to an +object declared as @code{short}; but if the return type is +@code{short}, then @var{rvalue} should point to an object declared as +a larger type -- usually @code{ffi_arg}. +@end defun + + +@node Simple Example +@section Simple Example + +Here is a trivial example that calls @code{puts} a few times. + +@example +#include +#include + +int main() +@{ + ffi_cif cif; + ffi_type *args[1]; + void *values[1]; + char *s; + ffi_arg rc; + + /* Initialize the argument info vectors */ + args[0] = &ffi_type_pointer; + values[0] = &s; + + /* Initialize the cif */ + if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_sint, args) == FFI_OK) + @{ + s = "Hello World!"; + ffi_call(&cif, puts, &rc, values); + /* rc now holds the result of the call to puts */ + + /* values holds a pointer to the function's arg, so to + call puts() again all we need to do is change the + value of s */ + s = "This is cool!"; + ffi_call(&cif, puts, &rc, values); + @} + + return 0; +@} +@end example + + +@node Types +@section Types + +@menu +* Primitive Types:: Built-in types. +* Structures:: Structure types. +* Size and Alignment:: Size and alignment of types. +* Arrays Unions Enums:: Arrays, unions, and enumerations. +* Type Example:: Structure type example. +* Complex:: Complex types. +* Complex Type Example:: Complex type example. +@end menu + +@node Primitive Types +@subsection Primitive Types + +@code{Libffi} provides a number of built-in type descriptors that can +be used to describe argument and return types: + +@table @code +@item ffi_type_void +@tindex ffi_type_void +The type @code{void}. This cannot be used for argument types, only +for return values. + +@item ffi_type_uint8 +@tindex ffi_type_uint8 +An unsigned, 8-bit integer type. + +@item ffi_type_sint8 +@tindex ffi_type_sint8 +A signed, 8-bit integer type. + +@item ffi_type_uint16 +@tindex ffi_type_uint16 +An unsigned, 16-bit integer type. + +@item ffi_type_sint16 +@tindex ffi_type_sint16 +A signed, 16-bit integer type. + +@item ffi_type_uint32 +@tindex ffi_type_uint32 +An unsigned, 32-bit integer type. + +@item ffi_type_sint32 +@tindex ffi_type_sint32 +A signed, 32-bit integer type. + +@item ffi_type_uint64 +@tindex ffi_type_uint64 +An unsigned, 64-bit integer type. + +@item ffi_type_sint64 +@tindex ffi_type_sint64 +A signed, 64-bit integer type. + +@item ffi_type_float +@tindex ffi_type_float +The C @code{float} type. + +@item ffi_type_double +@tindex ffi_type_double +The C @code{double} type. + +@item ffi_type_uchar +@tindex ffi_type_uchar +The C @code{unsigned char} type. + +@item ffi_type_schar +@tindex ffi_type_schar +The C @code{signed char} type. (Note that there is not an exact +equivalent to the C @code{char} type in @code{libffi}; ordinarily you +should either use @code{ffi_type_schar} or @code{ffi_type_uchar} +depending on whether @code{char} is signed.) + +@item ffi_type_ushort +@tindex ffi_type_ushort +The C @code{unsigned short} type. + +@item ffi_type_sshort +@tindex ffi_type_sshort +The C @code{short} type. + +@item ffi_type_uint +@tindex ffi_type_uint +The C @code{unsigned int} type. + +@item ffi_type_sint +@tindex ffi_type_sint +The C @code{int} type. + +@item ffi_type_ulong +@tindex ffi_type_ulong +The C @code{unsigned long} type. + +@item ffi_type_slong +@tindex ffi_type_slong +The C @code{long} type. + +@item ffi_type_longdouble +@tindex ffi_type_longdouble +On platforms that have a C @code{long double} type, this is defined. +On other platforms, it is not. + +@item ffi_type_pointer +@tindex ffi_type_pointer +A generic @code{void *} pointer. You should use this for all +pointers, regardless of their real type. + +@item ffi_type_complex_float +@tindex ffi_type_complex_float +The C @code{_Complex float} type. + +@item ffi_type_complex_double +@tindex ffi_type_complex_double +The C @code{_Complex double} type. + +@item ffi_type_complex_longdouble +@tindex ffi_type_complex_longdouble +The C @code{_Complex long double} type. +On platforms that have a C @code{long double} type, this is defined. +On other platforms, it is not. +@end table + +Each of these is of type @code{ffi_type}, so you must take the address +when passing to @code{ffi_prep_cif}. + + +@node Structures +@subsection Structures + +@samp{libffi} is perfectly happy passing structures back and forth. +You must first describe the structure to @samp{libffi} by creating a +new @code{ffi_type} object for it. + +@tindex ffi_type +@deftp {Data type} ffi_type +The @code{ffi_type} has the following members: +@table @code +@item size_t size +This is set by @code{libffi}; you should initialize it to zero. + +@item unsigned short alignment +This is set by @code{libffi}; you should initialize it to zero. + +@item unsigned short type +For a structure, this should be set to @code{FFI_TYPE_STRUCT}. + +@item ffi_type **elements +This is a @samp{NULL}-terminated array of pointers to @code{ffi_type} +objects. There is one element per field of the struct. + +Note that @samp{libffi} has no special support for bit-fields. You +must manage these manually. +@end table +@end deftp + +The @code{size} and @code{alignment} fields will be filled in by +@code{ffi_prep_cif} or @code{ffi_prep_cif_var}, as needed. + +@node Size and Alignment +@subsection Size and Alignment + +@code{libffi} will set the @code{size} and @code{alignment} fields of +an @code{ffi_type} object for you. It does so using its knowledge of +the ABI. + +You might expect that you can simply read these fields for a type that +has been laid out by @code{libffi}. However, there are some caveats. + +@itemize @bullet +@item +The size or alignment of some of the built-in types may vary depending +on the chosen ABI. + +@item +The size and alignment of a new structure type will not be set by +@code{libffi} until it has been passed to @code{ffi_prep_cif} or +@code{ffi_get_struct_offsets}. + +@item +A structure type cannot be shared across ABIs. Instead each ABI needs +its own copy of the structure type. +@end itemize + +So, before examining these fields, it is safest to pass the +@code{ffi_type} object to @code{ffi_prep_cif} or +@code{ffi_get_struct_offsets} first. This function will do all the +needed setup. + +@example +ffi_type *desired_type; +ffi_abi desired_abi; +@dots{} +ffi_cif cif; +if (ffi_prep_cif (&cif, desired_abi, 0, desired_type, NULL) == FFI_OK) + @{ + size_t size = desired_type->size; + unsigned short alignment = desired_type->alignment; + @} +@end example + +@code{libffi} also provides a way to get the offsets of the members of +a structure. + +@findex ffi_get_struct_offsets +@defun ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type, size_t *offsets) +Compute the offset of each element of the given structure type. +@var{abi} is the ABI to use; this is needed because in some cases the +layout depends on the ABI. + +@var{offsets} is an out parameter. The caller is responsible for +providing enough space for all the results to be written -- one +element per element type in @var{struct_type}. If @var{offsets} is +@code{NULL}, then the type will be laid out but not otherwise +modified. This can be useful for accessing the type's size or layout, +as mentioned above. + +This function returns @code{FFI_OK} on success; @code{FFI_BAD_ABI} if +@var{abi} is invalid; or @code{FFI_BAD_TYPEDEF} if @var{struct_type} +is invalid in some way. Note that only @code{FFI_STRUCT} types are +valid here. +@end defun + +@node Arrays Unions Enums +@subsection Arrays, Unions, and Enumerations + +@subsubsection Arrays + +@samp{libffi} does not have direct support for arrays or unions. +However, they can be emulated using structures. + +To emulate an array, simply create an @code{ffi_type} using +@code{FFI_TYPE_STRUCT} with as many members as there are elements in +the array. + +@example +ffi_type array_type; +ffi_type **elements +int i; + +elements = malloc ((n + 1) * sizeof (ffi_type *)); +for (i = 0; i < n; ++i) + elements[i] = array_element_type; +elements[n] = NULL; + +array_type.size = array_type.alignment = 0; +array_type.type = FFI_TYPE_STRUCT; +array_type.elements = elements; +@end example + +Note that arrays cannot be passed or returned by value in C -- +structure types created like this should only be used to refer to +members of real @code{FFI_TYPE_STRUCT} objects. + +However, a phony array type like this will not cause any errors from +@samp{libffi} if you use it as an argument or return type. This may +be confusing. + +@subsubsection Unions + +A union can also be emulated using @code{FFI_TYPE_STRUCT}. In this +case, however, you must make sure that the size and alignment match +the real requirements of the union. + +One simple way to do this is to ensue that each element type is laid +out. Then, give the new structure type a single element; the size of +the largest element; and the largest alignment seen as well. + +This example uses the @code{ffi_prep_cif} trick to ensure that each +element type is laid out. + +@example +ffi_abi desired_abi; +ffi_type union_type; +ffi_type **union_elements; + +int i; +ffi_type element_types[2]; + +element_types[1] = NULL; + +union_type.size = union_type.alignment = 0; +union_type.type = FFI_TYPE_STRUCT; +union_type.elements = element_types; + +for (i = 0; union_elements[i]; ++i) + @{ + ffi_cif cif; + if (ffi_prep_cif (&cif, desired_abi, 0, union_elements[i], NULL) == FFI_OK) + @{ + if (union_elements[i]->size > union_type.size) + @{ + union_type.size = union_elements[i]; + size = union_elements[i]->size; + @} + if (union_elements[i]->alignment > union_type.alignment) + union_type.alignment = union_elements[i]->alignment; + @} + @} +@end example + +@subsubsection Enumerations + +@code{libffi} does not have any special support for C @code{enum}s. +Although any given @code{enum} is implemented using a specific +underlying integral type, exactly which type will be used cannot be +determined by @code{libffi} -- it may depend on the values in the +enumeration or on compiler flags such as @option{-fshort-enums}. +@xref{Structures unions enumerations and bit-fields implementation, , , gcc}, +for more information about how GCC handles enumerations. + +@node Type Example +@subsection Type Example + +The following example initializes a @code{ffi_type} object +representing the @code{tm} struct from Linux's @file{time.h}. + +Here is how the struct is defined: + +@example +struct tm @{ + int tm_sec; + int tm_min; + int tm_hour; + int tm_mday; + int tm_mon; + int tm_year; + int tm_wday; + int tm_yday; + int tm_isdst; + /* Those are for future use. */ + long int __tm_gmtoff__; + __const char *__tm_zone__; +@}; +@end example + +Here is the corresponding code to describe this struct to +@code{libffi}: + +@example + @{ + ffi_type tm_type; + ffi_type *tm_type_elements[12]; + int i; + + tm_type.size = tm_type.alignment = 0; + tm_type.type = FFI_TYPE_STRUCT; + tm_type.elements = &tm_type_elements; + + for (i = 0; i < 9; i++) + tm_type_elements[i] = &ffi_type_sint; + + tm_type_elements[9] = &ffi_type_slong; + tm_type_elements[10] = &ffi_type_pointer; + tm_type_elements[11] = NULL; + + /* tm_type can now be used to represent tm argument types and + return types for ffi_prep_cif() */ + @} +@end example + +@node Complex +@subsection Complex Types + +@samp{libffi} supports the complex types defined by the C99 +standard (@code{_Complex float}, @code{_Complex double} and +@code{_Complex long double} with the built-in type descriptors +@code{ffi_type_complex_float}, @code{ffi_type_complex_double} and +@code{ffi_type_complex_longdouble}. + +Custom complex types like @code{_Complex int} can also be used. +An @code{ffi_type} object has to be defined to describe the +complex type to @samp{libffi}. + +@tindex ffi_type +@deftp {Data type} ffi_type +@table @code +@item size_t size +This must be manually set to the size of the complex type. + +@item unsigned short alignment +This must be manually set to the alignment of the complex type. + +@item unsigned short type +For a complex type, this must be set to @code{FFI_TYPE_COMPLEX}. + +@item ffi_type **elements + +This is a @samp{NULL}-terminated array of pointers to +@code{ffi_type} objects. The first element is set to the +@code{ffi_type} of the complex's base type. The second element +must be set to @code{NULL}. +@end table +@end deftp + +The section @ref{Complex Type Example} shows a way to determine +the @code{size} and @code{alignment} members in a platform +independent way. + +For platforms that have no complex support in @code{libffi} yet, +the functions @code{ffi_prep_cif} and @code{ffi_prep_args} abort +the program if they encounter a complex type. + +@node Complex Type Example +@subsection Complex Type Example + +This example demonstrates how to use complex types: + +@example +#include +#include +#include + +void complex_fn(_Complex float cf, + _Complex double cd, + _Complex long double cld) +@{ + printf("cf=%f+%fi\ncd=%f+%fi\ncld=%f+%fi\n", + (float)creal (cf), (float)cimag (cf), + (float)creal (cd), (float)cimag (cd), + (float)creal (cld), (float)cimag (cld)); +@} + +int main() +@{ + ffi_cif cif; + ffi_type *args[3]; + void *values[3]; + _Complex float cf; + _Complex double cd; + _Complex long double cld; + + /* Initialize the argument info vectors */ + args[0] = &ffi_type_complex_float; + args[1] = &ffi_type_complex_double; + args[2] = &ffi_type_complex_longdouble; + values[0] = &cf; + values[1] = &cd; + values[2] = &cld; + + /* Initialize the cif */ + if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, + &ffi_type_void, args) == FFI_OK) + @{ + cf = 1.0 + 20.0 * I; + cd = 300.0 + 4000.0 * I; + cld = 50000.0 + 600000.0 * I; + /* Call the function */ + ffi_call(&cif, (void (*)(void))complex_fn, 0, values); + @} + + return 0; +@} +@end example + +This is an example for defining a custom complex type descriptor +for compilers that support them: + +@example +/* + * This macro can be used to define new complex type descriptors + * in a platform independent way. + * + * name: Name of the new descriptor is ffi_type_complex_. + * type: The C base type of the complex type. + */ +#define FFI_COMPLEX_TYPEDEF(name, type, ffitype) \ + static ffi_type *ffi_elements_complex_##name [2] = @{ \ + (ffi_type *)(&ffitype), NULL \ + @}; \ + struct struct_align_complex_##name @{ \ + char c; \ + _Complex type x; \ + @}; \ + ffi_type ffi_type_complex_##name = @{ \ + sizeof(_Complex type), \ + offsetof(struct struct_align_complex_##name, x), \ + FFI_TYPE_COMPLEX, \ + (ffi_type **)ffi_elements_complex_##name \ + @} + +/* Define new complex type descriptors using the macro: */ +/* ffi_type_complex_sint */ +FFI_COMPLEX_TYPEDEF(sint, int, ffi_type_sint); +/* ffi_type_complex_uchar */ +FFI_COMPLEX_TYPEDEF(uchar, unsigned char, ffi_type_uint8); +@end example + +The new type descriptors can then be used like one of the built-in +type descriptors in the previous example. + +@node Multiple ABIs +@section Multiple ABIs + +A given platform may provide multiple different ABIs at once. For +instance, the x86 platform has both @samp{stdcall} and @samp{fastcall} +functions. + +@code{libffi} provides some support for this. However, this is +necessarily platform-specific. + +@c FIXME: document the platforms + +@node The Closure API +@section The Closure API + +@code{libffi} also provides a way to write a generic function -- a +function that can accept and decode any combination of arguments. +This can be useful when writing an interpreter, or to provide wrappers +for arbitrary functions. + +This facility is called the @dfn{closure API}. Closures are not +supported on all platforms; you can check the @code{FFI_CLOSURES} +define to determine whether they are supported on the current +platform. +@cindex closures +@cindex closure API +@findex FFI_CLOSURES + +Because closures work by assembling a tiny function at runtime, they +require special allocation on platforms that have a non-executable +heap. Memory management for closures is handled by a pair of +functions: + +@findex ffi_closure_alloc +@defun void *ffi_closure_alloc (size_t @var{size}, void **@var{code}) +Allocate a chunk of memory holding @var{size} bytes. This returns a +pointer to the writable address, and sets *@var{code} to the +corresponding executable address. + +@var{size} should be sufficient to hold a @code{ffi_closure} object. +@end defun + +@findex ffi_closure_free +@defun void ffi_closure_free (void *@var{writable}) +Free memory allocated using @code{ffi_closure_alloc}. The argument is +the writable address that was returned. +@end defun + + +Once you have allocated the memory for a closure, you must construct a +@code{ffi_cif} describing the function call. Finally you can prepare +the closure function: + +@findex ffi_prep_closure_loc +@defun ffi_status ffi_prep_closure_loc (ffi_closure *@var{closure}, ffi_cif *@var{cif}, void (*@var{fun}) (ffi_cif *@var{cif}, void *@var{ret}, void **@var{args}, void *@var{user_data}), void *@var{user_data}, void *@var{codeloc}) +Prepare a closure function. The arguments to +@code{ffi_prep_closure_loc} are: + +@table @var +@item closure +The address of a @code{ffi_closure} object; this is the writable +address returned by @code{ffi_closure_alloc}. + +@item cif +The @code{ffi_cif} describing the function parameters. Note that this +object, and the types to which it refers, must be kept alive until the +closure itself is freed. + +@item user_data +An arbitrary datum that is passed, uninterpreted, to your closure +function. + +@item codeloc +The executable address returned by @code{ffi_closure_alloc}. + +@item fun +The function which will be called when the closure is invoked. It is +called with the arguments: + +@table @var +@item cif +The @code{ffi_cif} passed to @code{ffi_prep_closure_loc}. + +@item ret +A pointer to the memory used for the function's return value. + +If the function is declared as returning @code{void}, then this value +is garbage and should not be used. + +Otherwise, @var{fun} must fill the object to which this points, +following the same special promotion behavior as @code{ffi_call}. +That is, in most cases, @var{ret} points to an object of exactly the +size of the type specified when @var{cif} was constructed. However, +integral types narrower than the system register size are widened. In +these cases your program may assume that @var{ret} points to an +@code{ffi_arg} object. + +@item args +A vector of pointers to memory holding the arguments to the function. + +@item user_data +The same @var{user_data} that was passed to +@code{ffi_prep_closure_loc}. +@end table +@end table + +@code{ffi_prep_closure_loc} will return @code{FFI_OK} if everything +went ok, and one of the other @code{ffi_status} values on error. + +After calling @code{ffi_prep_closure_loc}, you can cast @var{codeloc} +to the appropriate pointer-to-function type. +@end defun + +You may see old code referring to @code{ffi_prep_closure}. This +function is deprecated, as it cannot handle the need for separate +writable and executable addresses. + +@node Closure Example +@section Closure Example + +A trivial example that creates a new @code{puts} by binding +@code{fputs} with @code{stdout}. + +@example +#include +#include + +/* Acts like puts with the file given at time of enclosure. */ +void puts_binding(ffi_cif *cif, void *ret, void* args[], + void *stream) +@{ + *(ffi_arg *)ret = fputs(*(char **)args[0], (FILE *)stream); +@} + +typedef int (*puts_t)(char *); + +int main() +@{ + ffi_cif cif; + ffi_type *args[1]; + ffi_closure *closure; + + void *bound_puts; + int rc; + + /* Allocate closure and bound_puts */ + closure = ffi_closure_alloc(sizeof(ffi_closure), &bound_puts); + + if (closure) + @{ + /* Initialize the argument info vectors */ + args[0] = &ffi_type_pointer; + + /* Initialize the cif */ + if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_sint, args) == FFI_OK) + @{ + /* Initialize the closure, setting stream to stdout */ + if (ffi_prep_closure_loc(closure, &cif, puts_binding, + stdout, bound_puts) == FFI_OK) + @{ + rc = ((puts_t)bound_puts)("Hello World!"); + /* rc now holds the result of the call to fputs */ + @} + @} + @} + + /* Deallocate both closure, and bound_puts */ + ffi_closure_free(closure); + + return 0; +@} + +@end example + +@node Thread Safety +@section Thread Safety + +@code{libffi} is not completely thread-safe. However, many parts are, +and if you follow some simple rules, you can use it safely in a +multi-threaded program. + +@itemize @bullet +@item +@code{ffi_prep_cif} may modify the @code{ffi_type} objects passed to +it. It is best to ensure that only a single thread prepares a given +@code{ffi_cif} at a time. + +@item +On some platforms, @code{ffi_prep_cif} may modify the size and +alignment of some types, depending on the chosen ABI. On these +platforms, if you switch between ABIs, you must ensure that there is +only one call to @code{ffi_prep_cif} at a time. + +Currently the only affected platform is PowerPC and the only affected +type is @code{long double}. +@end itemize + +@node Missing Features +@chapter Missing Features + +@code{libffi} is missing a few features. We welcome patches to add +support for these. + +@itemize @bullet +@item +Variadic closures. + +@item +There is no support for bit fields in structures. + +@item +The ``raw'' API is undocumented. +@c anything else? + +@item +The Go API is undocumented. +@end itemize + +Note that variadic support is very new and tested on a relatively +small number of platforms. + +@node Index +@unnumbered Index + +@printindex cp + +@bye diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/doc/version.texi b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/doc/version.texi new file mode 100644 index 0000000..d9d5094 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/doc/version.texi @@ -0,0 +1,4 @@ +@set UPDATED 22 November 2019 +@set UPDATED-MONTH November 2019 +@set EDITION 3.3 +@set VERSION 3.3 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/generate-darwin-source-and-headers.py b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/generate-darwin-source-and-headers.py new file mode 100755 index 0000000..516464f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/generate-darwin-source-and-headers.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python +import subprocess +import os +import errno +import collections +import glob +import argparse + +class Platform(object): + pass + +class simulator_platform(Platform): + directory = 'darwin_ios' + sdk = 'iphonesimulator' + arch = 'i386' + triple = 'i386-apple-darwin11' + version_min = '-miphoneos-version-min=7.0' + + prefix = "#ifdef __i386__\n\n" + suffix = "\n\n#endif" + src_dir = 'x86' + src_files = ['sysv.S', 'ffi.c', 'internal.h'] + + +class simulator64_platform(Platform): + directory = 'darwin_ios' + sdk = 'iphonesimulator' + arch = 'x86_64' + triple = 'x86_64-apple-darwin13' + version_min = '-miphoneos-version-min=7.0' + + prefix = "#ifdef __x86_64__\n\n" + suffix = "\n\n#endif" + src_dir = 'x86' + src_files = ['unix64.S', 'ffi64.c', 'ffiw64.c', 'win64.S', 'internal64.h', 'asmnames.h'] + + +class device_platform(Platform): + directory = 'darwin_ios' + sdk = 'iphoneos' + arch = 'armv7' + triple = 'arm-apple-darwin11' + version_min = '-miphoneos-version-min=7.0' + + prefix = "#ifdef __arm__\n\n" + suffix = "\n\n#endif" + src_dir = 'arm' + src_files = ['sysv.S', 'ffi.c', 'internal.h'] + + +class device64_platform(Platform): + directory = 'darwin_ios' + sdk = 'iphoneos' + arch = 'arm64' + triple = 'aarch64-apple-darwin13' + version_min = '-miphoneos-version-min=7.0' + + prefix = "#ifdef __arm64__\n\n" + suffix = "\n\n#endif" + src_dir = 'aarch64' + src_files = ['sysv.S', 'ffi.c', 'internal.h'] + + +class desktop32_platform(Platform): + directory = 'darwin_osx' + sdk = 'macosx' + arch = 'i386' + triple = 'i386-apple-darwin10' + version_min = '-mmacosx-version-min=10.6' + src_dir = 'x86' + src_files = ['sysv.S', 'ffi.c', 'internal.h'] + + prefix = "#ifdef __i386__\n\n" + suffix = "\n\n#endif" + + +class desktop64_platform(Platform): + directory = 'darwin_osx' + sdk = 'macosx' + arch = 'x86_64' + triple = 'x86_64-apple-darwin10' + version_min = '-mmacosx-version-min=10.6' + + prefix = "#ifdef __x86_64__\n\n" + suffix = "\n\n#endif" + src_dir = 'x86' + src_files = ['unix64.S', 'ffi64.c', 'ffiw64.c', 'win64.S', 'internal64.h', 'asmnames.h'] + + +def mkdir_p(path): + try: + os.makedirs(path) + except OSError as exc: # Python >2.5 + if exc.errno != errno.EEXIST: + raise + + +def move_file(src_dir, dst_dir, filename, file_suffix=None, prefix='', suffix=''): + mkdir_p(dst_dir) + out_filename = filename + + if file_suffix: + if filename in ['internal64.h', 'asmnames.h', 'internal.h']: + out_filename = filename + else: + split_name = os.path.splitext(filename) + out_filename = "%s_%s%s" % (split_name[0], file_suffix, split_name[1]) + + with open(os.path.join(src_dir, filename)) as in_file: + with open(os.path.join(dst_dir, out_filename), 'w') as out_file: + if prefix: + out_file.write(prefix) + + out_file.write(in_file.read()) + + if suffix: + out_file.write(suffix) + + +def list_files(src_dir, pattern=None, filelist=None): + if pattern: filelist = glob.iglob(os.path.join(src_dir, pattern)) + for file in filelist: + yield os.path.basename(file) + + +def copy_files(src_dir, dst_dir, pattern=None, filelist=None, file_suffix=None, prefix=None, suffix=None): + for filename in list_files(src_dir, pattern=pattern, filelist=filelist): + move_file(src_dir, dst_dir, filename, file_suffix=file_suffix, prefix=prefix, suffix=suffix) + + +def copy_src_platform_files(platform): + src_dir = os.path.join('src', platform.src_dir) + dst_dir = os.path.join(platform.directory, 'src', platform.src_dir) + copy_files(src_dir, dst_dir, filelist=platform.src_files, file_suffix=platform.arch, prefix=platform.prefix, suffix=platform.suffix) + + +def build_target(platform, platform_headers): + def xcrun_cmd(cmd): + return 'xcrun -sdk %s %s -arch %s' % (platform.sdk, cmd, platform.arch) + + tag='%s-%s' % (platform.sdk, platform.arch) + build_dir = 'build_%s' % tag + mkdir_p(build_dir) + env = dict(CC=xcrun_cmd('clang'), + LD=xcrun_cmd('ld'), + CFLAGS='%s -fembed-bitcode' % (platform.version_min)) + working_dir = os.getcwd() + try: + os.chdir(build_dir) + subprocess.check_call(['../configure', '-host', platform.triple], env=env) + finally: + os.chdir(working_dir) + + for src_dir in [build_dir, os.path.join(build_dir, 'include')]: + copy_files(src_dir, + os.path.join(platform.directory, 'include'), + pattern='*.h', + file_suffix=platform.arch, + prefix=platform.prefix, + suffix=platform.suffix) + + for filename in list_files(src_dir, pattern='*.h'): + platform_headers[filename].add((platform.prefix, platform.arch, platform.suffix)) + + +def generate_source_and_headers(generate_osx=True, generate_ios=True): + copy_files('src', 'darwin_common/src', pattern='*.c') + copy_files('include', 'darwin_common/include', pattern='*.h') + + if generate_ios: + copy_src_platform_files(simulator_platform) + copy_src_platform_files(simulator64_platform) + copy_src_platform_files(device_platform) + copy_src_platform_files(device64_platform) + if generate_osx: + copy_src_platform_files(desktop64_platform) + + platform_headers = collections.defaultdict(set) + + if generate_ios: + build_target(simulator_platform, platform_headers) + build_target(simulator64_platform, platform_headers) + build_target(device_platform, platform_headers) + build_target(device64_platform, platform_headers) + if generate_osx: + build_target(desktop64_platform, platform_headers) + + mkdir_p('darwin_common/include') + for header_name, tag_tuples in platform_headers.items(): + basename, suffix = os.path.splitext(header_name) + with open(os.path.join('darwin_common/include', header_name), 'w') as header: + for tag_tuple in tag_tuples: + header.write('%s#include <%s_%s%s>\n%s\n' % (tag_tuple[0], basename, tag_tuple[1], suffix, tag_tuple[2])) + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--only-ios', action='store_true', default=False) + parser.add_argument('--only-osx', action='store_true', default=False) + args = parser.parse_args() + + generate_source_and_headers(generate_osx=not args.only_ios, generate_ios=not args.only_osx) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/Makefile.am b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/Makefile.am new file mode 100644 index 0000000..c59df9f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/Makefile.am @@ -0,0 +1,9 @@ +## Process this with automake to create Makefile.in + +AUTOMAKE_OPTIONS=foreign + +DISTCLEANFILES=ffitarget.h +noinst_HEADERS=ffi_common.h ffi_cfi.h +EXTRA_DIST=ffi.h.in + +nodist_include_HEADERS = ffi.h ffitarget.h diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/ffi.h.in b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/ffi.h.in new file mode 100644 index 0000000..38885b0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/ffi.h.in @@ -0,0 +1,523 @@ +/* -----------------------------------------------------------------*-C-*- + libffi @VERSION@ - Copyright (c) 2011, 2014, 2019 Anthony Green + - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the ``Software''), to deal in the Software without + restriction, including without limitation the rights to use, copy, + modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +/* ------------------------------------------------------------------- + Most of the API is documented in doc/libffi.texi. + + The raw API is designed to bypass some of the argument packing and + unpacking on architectures for which it can be avoided. Routines + are provided to emulate the raw API if the underlying platform + doesn't allow faster implementation. + + More details on the raw API can be found in: + + http://gcc.gnu.org/ml/java/1999-q3/msg00138.html + + and + + http://gcc.gnu.org/ml/java/1999-q3/msg00174.html + -------------------------------------------------------------------- */ + +#ifndef LIBFFI_H +#define LIBFFI_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Specify which architecture libffi is configured for. */ +#ifndef @TARGET@ +#define @TARGET@ +#endif + +/* ---- System configuration information --------------------------------- */ + +#include + +#ifndef LIBFFI_ASM + +#if defined(_MSC_VER) && !defined(__clang__) +#define __attribute__(X) +#endif + +#include +#include + +/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example). + But we can find it either under the correct ANSI name, or under GNU + C's internal name. */ + +#define FFI_64_BIT_MAX 9223372036854775807 + +#ifdef LONG_LONG_MAX +# define FFI_LONG_LONG_MAX LONG_LONG_MAX +#else +# ifdef LLONG_MAX +# define FFI_LONG_LONG_MAX LLONG_MAX +# ifdef _AIX52 /* or newer has C99 LLONG_MAX */ +# undef FFI_64_BIT_MAX +# define FFI_64_BIT_MAX 9223372036854775807LL +# endif /* _AIX52 or newer */ +# else +# ifdef __GNUC__ +# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__ +# endif +# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */ +# ifndef __PPC64__ +# if defined (__IBMC__) || defined (__IBMCPP__) +# define FFI_LONG_LONG_MAX LONGLONG_MAX +# endif +# endif /* __PPC64__ */ +# undef FFI_64_BIT_MAX +# define FFI_64_BIT_MAX 9223372036854775807LL +# endif +# endif +#endif + +/* The closure code assumes that this works on pointers, i.e. a size_t + can hold a pointer. */ + +typedef struct _ffi_type +{ + size_t size; + unsigned short alignment; + unsigned short type; + struct _ffi_type **elements; +} ffi_type; + +/* Need minimal decorations for DLLs to work on Windows. GCC has + autoimport and autoexport. Always mark externally visible symbols + as dllimport for MSVC clients, even if it means an extra indirection + when using the static version of the library. + Besides, as a workaround, they can define FFI_BUILDING if they + *know* they are going to link with the static library. */ +#if defined _MSC_VER +# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */ +# define FFI_API __declspec(dllexport) +# elif !defined FFI_BUILDING /* Importing libffi.DLL */ +# define FFI_API __declspec(dllimport) +# else /* Building/linking static library */ +# define FFI_API +# endif +#else +# define FFI_API +#endif + +/* The externally visible type declarations also need the MSVC DLL + decorations, or they will not be exported from the object file. */ +#if defined LIBFFI_HIDE_BASIC_TYPES +# define FFI_EXTERN FFI_API +#else +# define FFI_EXTERN extern FFI_API +#endif + +#ifndef LIBFFI_HIDE_BASIC_TYPES +#if SCHAR_MAX == 127 +# define ffi_type_uchar ffi_type_uint8 +# define ffi_type_schar ffi_type_sint8 +#else + #error "char size not supported" +#endif + +#if SHRT_MAX == 32767 +# define ffi_type_ushort ffi_type_uint16 +# define ffi_type_sshort ffi_type_sint16 +#elif SHRT_MAX == 2147483647 +# define ffi_type_ushort ffi_type_uint32 +# define ffi_type_sshort ffi_type_sint32 +#else + #error "short size not supported" +#endif + +#if INT_MAX == 32767 +# define ffi_type_uint ffi_type_uint16 +# define ffi_type_sint ffi_type_sint16 +#elif INT_MAX == 2147483647 +# define ffi_type_uint ffi_type_uint32 +# define ffi_type_sint ffi_type_sint32 +#elif INT_MAX == 9223372036854775807 +# define ffi_type_uint ffi_type_uint64 +# define ffi_type_sint ffi_type_sint64 +#else + #error "int size not supported" +#endif + +#if LONG_MAX == 2147483647 +# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX + #error "no 64-bit data type supported" +# endif +#elif LONG_MAX != FFI_64_BIT_MAX + #error "long size not supported" +#endif + +#if LONG_MAX == 2147483647 +# define ffi_type_ulong ffi_type_uint32 +# define ffi_type_slong ffi_type_sint32 +#elif LONG_MAX == FFI_64_BIT_MAX +# define ffi_type_ulong ffi_type_uint64 +# define ffi_type_slong ffi_type_sint64 +#else + #error "long size not supported" +#endif + +/* These are defined in types.c. */ +FFI_EXTERN ffi_type ffi_type_void; +FFI_EXTERN ffi_type ffi_type_uint8; +FFI_EXTERN ffi_type ffi_type_sint8; +FFI_EXTERN ffi_type ffi_type_uint16; +FFI_EXTERN ffi_type ffi_type_sint16; +FFI_EXTERN ffi_type ffi_type_uint32; +FFI_EXTERN ffi_type ffi_type_sint32; +FFI_EXTERN ffi_type ffi_type_uint64; +FFI_EXTERN ffi_type ffi_type_sint64; +FFI_EXTERN ffi_type ffi_type_float; +FFI_EXTERN ffi_type ffi_type_double; +FFI_EXTERN ffi_type ffi_type_pointer; + +#if @HAVE_LONG_DOUBLE@ +FFI_EXTERN ffi_type ffi_type_longdouble; +#else +#define ffi_type_longdouble ffi_type_double +#endif + +#ifdef FFI_TARGET_HAS_COMPLEX_TYPE +FFI_EXTERN ffi_type ffi_type_complex_float; +FFI_EXTERN ffi_type ffi_type_complex_double; +#if @HAVE_LONG_DOUBLE@ +FFI_EXTERN ffi_type ffi_type_complex_longdouble; +#else +#define ffi_type_complex_longdouble ffi_type_complex_double +#endif +#endif +#endif /* LIBFFI_HIDE_BASIC_TYPES */ + +typedef enum { + FFI_OK = 0, + FFI_BAD_TYPEDEF, + FFI_BAD_ABI +} ffi_status; + +typedef struct { + ffi_abi abi; + unsigned nargs; + ffi_type **arg_types; + ffi_type *rtype; + unsigned bytes; + unsigned flags; +#ifdef FFI_EXTRA_CIF_FIELDS + FFI_EXTRA_CIF_FIELDS; +#endif +} ffi_cif; + +/* ---- Definitions for the raw API -------------------------------------- */ + +#ifndef FFI_SIZEOF_ARG +# if LONG_MAX == 2147483647 +# define FFI_SIZEOF_ARG 4 +# elif LONG_MAX == FFI_64_BIT_MAX +# define FFI_SIZEOF_ARG 8 +# endif +#endif + +#ifndef FFI_SIZEOF_JAVA_RAW +# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG +#endif + +typedef union { + ffi_sarg sint; + ffi_arg uint; + float flt; + char data[FFI_SIZEOF_ARG]; + void* ptr; +} ffi_raw; + +#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8 +/* This is a special case for mips64/n32 ABI (and perhaps others) where + sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */ +typedef union { + signed int sint; + unsigned int uint; + float flt; + char data[FFI_SIZEOF_JAVA_RAW]; + void* ptr; +} ffi_java_raw; +#else +typedef ffi_raw ffi_java_raw; +#endif + + +FFI_API +void ffi_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_raw *avalue); + +FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); +FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); +FFI_API size_t ffi_raw_size (ffi_cif *cif); + +/* This is analogous to the raw API, except it uses Java parameter + packing, even on 64-bit machines. I.e. on 64-bit machines longs + and doubles are followed by an empty 64-bit word. */ + +#if !FFI_NATIVE_RAW_API +FFI_API +void ffi_java_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_java_raw *avalue) __attribute__((deprecated)); +#endif + +FFI_API +void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) __attribute__((deprecated)); +FFI_API +void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) __attribute__((deprecated)); +FFI_API +size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated)); + +/* ---- Definitions for closures ----------------------------------------- */ + +#if FFI_CLOSURES + +#ifdef _MSC_VER +__declspec(align(8)) +#endif +typedef struct { +#if @FFI_EXEC_TRAMPOLINE_TABLE@ + void *trampoline_table; + void *trampoline_table_entry; +#else + char tramp[FFI_TRAMPOLINE_SIZE]; +#endif + ffi_cif *cif; + void (*fun)(ffi_cif*,void*,void**,void*); + void *user_data; +} ffi_closure +#ifdef __GNUC__ + __attribute__((aligned (8))) +#endif + ; + +#ifndef __GNUC__ +# ifdef __sgi +# pragma pack 0 +# endif +#endif + +FFI_API void *ffi_closure_alloc (size_t size, void **code); +FFI_API void ffi_closure_free (void *); + +#if defined(PA_LINUX) || defined(PA_HPUX) +#define FFI_CLOSURE_PTR(X) ((void *)((unsigned int)(X) | 2)) +#define FFI_RESTORE_PTR(X) ((void *)((unsigned int)(X) & ~3)) +#else +#define FFI_CLOSURE_PTR(X) (X) +#define FFI_RESTORE_PTR(X) (X) +#endif + +FFI_API ffi_status +ffi_prep_closure (ffi_closure*, + ffi_cif *, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data) +#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405) + __attribute__((deprecated ("use ffi_prep_closure_loc instead"))) +#elif defined(__GNUC__) && __GNUC__ >= 3 + __attribute__((deprecated)) +#endif + ; + +FFI_API ffi_status +ffi_prep_closure_loc (ffi_closure*, + ffi_cif *, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void*codeloc); + +#ifdef __sgi +# pragma pack 8 +#endif +typedef struct { +#if @FFI_EXEC_TRAMPOLINE_TABLE@ + void *trampoline_table; + void *trampoline_table_entry; +#else + char tramp[FFI_TRAMPOLINE_SIZE]; +#endif + ffi_cif *cif; + +#if !FFI_NATIVE_RAW_API + + /* If this is enabled, then a raw closure has the same layout + as a regular closure. We use this to install an intermediate + handler to do the transaltion, void** -> ffi_raw*. */ + + void (*translate_args)(ffi_cif*,void*,void**,void*); + void *this_closure; + +#endif + + void (*fun)(ffi_cif*,void*,ffi_raw*,void*); + void *user_data; + +} ffi_raw_closure; + +typedef struct { +#if @FFI_EXEC_TRAMPOLINE_TABLE@ + void *trampoline_table; + void *trampoline_table_entry; +#else + char tramp[FFI_TRAMPOLINE_SIZE]; +#endif + + ffi_cif *cif; + +#if !FFI_NATIVE_RAW_API + + /* If this is enabled, then a raw closure has the same layout + as a regular closure. We use this to install an intermediate + handler to do the translation, void** -> ffi_raw*. */ + + void (*translate_args)(ffi_cif*,void*,void**,void*); + void *this_closure; + +#endif + + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*); + void *user_data; + +} ffi_java_raw_closure; + +FFI_API ffi_status +ffi_prep_raw_closure (ffi_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data); + +FFI_API ffi_status +ffi_prep_raw_closure_loc (ffi_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data, + void *codeloc); + +#if !FFI_NATIVE_RAW_API +FFI_API ffi_status +ffi_prep_java_raw_closure (ffi_java_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), + void *user_data) __attribute__((deprecated)); + +FFI_API ffi_status +ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), + void *user_data, + void *codeloc) __attribute__((deprecated)); +#endif + +#endif /* FFI_CLOSURES */ + +#if FFI_GO_CLOSURES + +typedef struct { + void *tramp; + ffi_cif *cif; + void (*fun)(ffi_cif*,void*,void**,void*); +} ffi_go_closure; + +FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *, + void (*fun)(ffi_cif*,void*,void**,void*)); + +FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure); + +#endif /* FFI_GO_CLOSURES */ + +/* ---- Public interface definition -------------------------------------- */ + +FFI_API +ffi_status ffi_prep_cif(ffi_cif *cif, + ffi_abi abi, + unsigned int nargs, + ffi_type *rtype, + ffi_type **atypes); + +FFI_API +ffi_status ffi_prep_cif_var(ffi_cif *cif, + ffi_abi abi, + unsigned int nfixedargs, + unsigned int ntotalargs, + ffi_type *rtype, + ffi_type **atypes); + +FFI_API +void ffi_call(ffi_cif *cif, + void (*fn)(void), + void *rvalue, + void **avalue); + +FFI_API +ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type, + size_t *offsets); + +/* Useful for eliminating compiler warnings. */ +#define FFI_FN(f) ((void (*)(void))f) + +/* ---- Definitions shared with assembly code ---------------------------- */ + +#endif + +/* If these change, update src/mips/ffitarget.h. */ +#define FFI_TYPE_VOID 0 +#define FFI_TYPE_INT 1 +#define FFI_TYPE_FLOAT 2 +#define FFI_TYPE_DOUBLE 3 +#if @HAVE_LONG_DOUBLE@ +#define FFI_TYPE_LONGDOUBLE 4 +#else +#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE +#endif +#define FFI_TYPE_UINT8 5 +#define FFI_TYPE_SINT8 6 +#define FFI_TYPE_UINT16 7 +#define FFI_TYPE_SINT16 8 +#define FFI_TYPE_UINT32 9 +#define FFI_TYPE_SINT32 10 +#define FFI_TYPE_UINT64 11 +#define FFI_TYPE_SINT64 12 +#define FFI_TYPE_STRUCT 13 +#define FFI_TYPE_POINTER 14 +#define FFI_TYPE_COMPLEX 15 + +/* This should always refer to the last type code (for sanity checks). */ +#define FFI_TYPE_LAST FFI_TYPE_COMPLEX + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/ffi_cfi.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/ffi_cfi.h new file mode 100644 index 0000000..244ce57 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/ffi_cfi.h @@ -0,0 +1,55 @@ +/* ----------------------------------------------------------------------- + ffi_cfi.h - Copyright (c) 2014 Red Hat, Inc. + + Conditionally assemble cfi directives. Only necessary for building libffi. + ----------------------------------------------------------------------- */ + +#ifndef FFI_CFI_H +#define FFI_CFI_H + +#ifdef HAVE_AS_CFI_PSEUDO_OP + +# define cfi_startproc .cfi_startproc +# define cfi_endproc .cfi_endproc +# define cfi_def_cfa(reg, off) .cfi_def_cfa reg, off +# define cfi_def_cfa_register(reg) .cfi_def_cfa_register reg +# define cfi_def_cfa_offset(off) .cfi_def_cfa_offset off +# define cfi_adjust_cfa_offset(off) .cfi_adjust_cfa_offset off +# define cfi_offset(reg, off) .cfi_offset reg, off +# define cfi_rel_offset(reg, off) .cfi_rel_offset reg, off +# define cfi_register(r1, r2) .cfi_register r1, r2 +# define cfi_return_column(reg) .cfi_return_column reg +# define cfi_restore(reg) .cfi_restore reg +# define cfi_same_value(reg) .cfi_same_value reg +# define cfi_undefined(reg) .cfi_undefined reg +# define cfi_remember_state .cfi_remember_state +# define cfi_restore_state .cfi_restore_state +# define cfi_window_save .cfi_window_save +# define cfi_personality(enc, exp) .cfi_personality enc, exp +# define cfi_lsda(enc, exp) .cfi_lsda enc, exp +# define cfi_escape(...) .cfi_escape __VA_ARGS__ + +#else + +# define cfi_startproc +# define cfi_endproc +# define cfi_def_cfa(reg, off) +# define cfi_def_cfa_register(reg) +# define cfi_def_cfa_offset(off) +# define cfi_adjust_cfa_offset(off) +# define cfi_offset(reg, off) +# define cfi_rel_offset(reg, off) +# define cfi_register(r1, r2) +# define cfi_return_column(reg) +# define cfi_restore(reg) +# define cfi_same_value(reg) +# define cfi_undefined(reg) +# define cfi_remember_state +# define cfi_restore_state +# define cfi_window_save +# define cfi_personality(enc, exp) +# define cfi_lsda(enc, exp) +# define cfi_escape(...) + +#endif /* HAVE_AS_CFI_PSEUDO_OP */ +#endif /* FFI_CFI_H */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/ffi_common.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/ffi_common.h new file mode 100644 index 0000000..76b9dd6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/include/ffi_common.h @@ -0,0 +1,153 @@ +/* ----------------------------------------------------------------------- + ffi_common.h - Copyright (C) 2011, 2012, 2013 Anthony Green + Copyright (C) 2007 Free Software Foundation, Inc + Copyright (c) 1996 Red Hat, Inc. + + Common internal definitions and macros. Only necessary for building + libffi. + ----------------------------------------------------------------------- */ + +#ifndef FFI_COMMON_H +#define FFI_COMMON_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/* Do not move this. Some versions of AIX are very picky about where + this is positioned. */ +#ifdef __GNUC__ +# if HAVE_ALLOCA_H +# include +# else + /* mingw64 defines this already in malloc.h. */ +# ifndef alloca +# define alloca __builtin_alloca +# endif +# endif +# define MAYBE_UNUSED __attribute__((__unused__)) +#else +# define MAYBE_UNUSED +# if HAVE_ALLOCA_H +# include +# else +# ifdef _AIX +# pragma alloca +# else +# ifndef alloca /* predefined by HP cc +Olibcalls */ +# ifdef _MSC_VER +# define alloca _alloca +# else +char *alloca (); +# endif +# endif +# endif +# endif +#endif + +/* Check for the existence of memcpy. */ +#if STDC_HEADERS +# include +#else +# ifndef HAVE_MEMCPY +# define memcpy(d, s, n) bcopy ((s), (d), (n)) +# endif +#endif + +#if defined(FFI_DEBUG) +#include +#endif + +#ifdef FFI_DEBUG +void ffi_assert(char *expr, char *file, int line); +void ffi_stop_here(void); +void ffi_type_test(ffi_type *a, char *file, int line); + +#define FFI_ASSERT(x) ((x) ? (void)0 : ffi_assert(#x, __FILE__,__LINE__)) +#define FFI_ASSERT_AT(x, f, l) ((x) ? 0 : ffi_assert(#x, (f), (l))) +#define FFI_ASSERT_VALID_TYPE(x) ffi_type_test (x, __FILE__, __LINE__) +#else +#define FFI_ASSERT(x) +#define FFI_ASSERT_AT(x, f, l) +#define FFI_ASSERT_VALID_TYPE(x) +#endif + +/* v cast to size_t and aligned up to a multiple of a */ +#define FFI_ALIGN(v, a) (((((size_t) (v))-1) | ((a)-1))+1) +/* v cast to size_t and aligned down to a multiple of a */ +#define FFI_ALIGN_DOWN(v, a) (((size_t) (v)) & -a) + +/* Perform machine dependent cif processing */ +ffi_status ffi_prep_cif_machdep(ffi_cif *cif); +ffi_status ffi_prep_cif_machdep_var(ffi_cif *cif, + unsigned int nfixedargs, unsigned int ntotalargs); + + +#if HAVE_LONG_DOUBLE_VARIANT +/* Used to adjust size/alignment of ffi types. */ +void ffi_prep_types (ffi_abi abi); +#endif + +/* Used internally, but overridden by some architectures */ +ffi_status ffi_prep_cif_core(ffi_cif *cif, + ffi_abi abi, + unsigned int isvariadic, + unsigned int nfixedargs, + unsigned int ntotalargs, + ffi_type *rtype, + ffi_type **atypes); + +/* Translate a data pointer to a code pointer. Needed for closures on + some targets. */ +void *ffi_data_to_code_pointer (void *data) FFI_HIDDEN; + +/* Extended cif, used in callback from assembly routine */ +typedef struct +{ + ffi_cif *cif; + void *rvalue; + void **avalue; +} extended_cif; + +/* Terse sized type definitions. */ +#if defined(_MSC_VER) || defined(__sgi) || defined(__SUNPRO_C) +typedef unsigned char UINT8; +typedef signed char SINT8; +typedef unsigned short UINT16; +typedef signed short SINT16; +typedef unsigned int UINT32; +typedef signed int SINT32; +# ifdef _MSC_VER +typedef unsigned __int64 UINT64; +typedef signed __int64 SINT64; +# else +# include +typedef uint64_t UINT64; +typedef int64_t SINT64; +# endif +#else +typedef unsigned int UINT8 __attribute__((__mode__(__QI__))); +typedef signed int SINT8 __attribute__((__mode__(__QI__))); +typedef unsigned int UINT16 __attribute__((__mode__(__HI__))); +typedef signed int SINT16 __attribute__((__mode__(__HI__))); +typedef unsigned int UINT32 __attribute__((__mode__(__SI__))); +typedef signed int SINT32 __attribute__((__mode__(__SI__))); +typedef unsigned int UINT64 __attribute__((__mode__(__DI__))); +typedef signed int SINT64 __attribute__((__mode__(__DI__))); +#endif + +typedef float FLOAT32; + +#ifndef __GNUC__ +#define __builtin_expect(x, expected_value) (x) +#endif +#define LIKELY(x) __builtin_expect(!!(x),1) +#define UNLIKELY(x) __builtin_expect((x)!=0,0) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libffi.map.in b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libffi.map.in new file mode 100644 index 0000000..de8778a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libffi.map.in @@ -0,0 +1,76 @@ +#define LIBFFI_ASM +#define LIBFFI_H +#include +#include + +/* These version numbers correspond to the libtool-version abi numbers, + not to the libffi release numbers. */ + +LIBFFI_BASE_8.0 { + global: + /* Exported data variables. */ + ffi_type_void; + ffi_type_uint8; + ffi_type_sint8; + ffi_type_uint16; + ffi_type_sint16; + ffi_type_uint32; + ffi_type_sint32; + ffi_type_uint64; + ffi_type_sint64; + ffi_type_float; + ffi_type_double; + ffi_type_longdouble; + ffi_type_pointer; + + /* Exported functions. */ + ffi_call; + ffi_prep_cif; + ffi_prep_cif_var; + + ffi_raw_call; + ffi_ptrarray_to_raw; + ffi_raw_to_ptrarray; + ffi_raw_size; + + ffi_java_raw_call; + ffi_java_ptrarray_to_raw; + ffi_java_raw_to_ptrarray; + ffi_java_raw_size; + + ffi_get_struct_offsets; + local: + *; +}; + +#ifdef FFI_TARGET_HAS_COMPLEX_TYPE +LIBFFI_COMPLEX_8.0 { + global: + /* Exported data variables. */ + ffi_type_complex_float; + ffi_type_complex_double; + ffi_type_complex_longdouble; +} LIBFFI_BASE_8.0; +#endif + +#if FFI_CLOSURES +LIBFFI_CLOSURE_8.0 { + global: + ffi_closure_alloc; + ffi_closure_free; + ffi_prep_closure; + ffi_prep_closure_loc; + ffi_prep_raw_closure; + ffi_prep_raw_closure_loc; + ffi_prep_java_raw_closure; + ffi_prep_java_raw_closure_loc; +} LIBFFI_BASE_8.0; +#endif + +#if FFI_GO_CLOSURES +LIBFFI_GO_CLOSURE_8.0 { + global: + ffi_call_go; + ffi_prep_go_closure; +} LIBFFI_CLOSURE_8.0; +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libffi.pc.in b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libffi.pc.in new file mode 100644 index 0000000..6fad83b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libffi.pc.in @@ -0,0 +1,11 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +toolexeclibdir=@toolexeclibdir@ +includedir=@includedir@ + +Name: @PACKAGE_NAME@ +Description: Library supporting Foreign Function Interfaces +Version: @PACKAGE_VERSION@ +Libs: -L${toolexeclibdir} -lffi +Cflags: -I${includedir} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libffi.xcodeproj/project.pbxproj b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libffi.xcodeproj/project.pbxproj new file mode 100644 index 0000000..480c4a4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libffi.xcodeproj/project.pbxproj @@ -0,0 +1,997 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 43B5D3F81D35473200D1E1FD /* ffiw64_x86_64.c in Sources */ = {isa = PBXBuildFile; fileRef = 43B5D3F71D35473200D1E1FD /* ffiw64_x86_64.c */; }; + 43B5D3FA1D3547CE00D1E1FD /* win64_x86_64.S in Sources */ = {isa = PBXBuildFile; fileRef = 43B5D3F91D3547CE00D1E1FD /* win64_x86_64.S */; }; + 43E9A5C81D352C1500926A8F /* unix64_x86_64.S in Sources */ = {isa = PBXBuildFile; fileRef = 43E9A5C61D352C1500926A8F /* unix64_x86_64.S */; }; + DBFA714A187F1D8600A76262 /* ffi.h in Headers */ = {isa = PBXBuildFile; fileRef = DBFA713E187F1D8600A76262 /* ffi.h */; }; + DBFA714B187F1D8600A76262 /* ffi_common.h in Headers */ = {isa = PBXBuildFile; fileRef = DBFA713F187F1D8600A76262 /* ffi_common.h */; }; + DBFA714C187F1D8600A76262 /* fficonfig.h in Headers */ = {isa = PBXBuildFile; fileRef = DBFA7140187F1D8600A76262 /* fficonfig.h */; }; + DBFA714D187F1D8600A76262 /* ffitarget.h in Headers */ = {isa = PBXBuildFile; fileRef = DBFA7141187F1D8600A76262 /* ffitarget.h */; }; + DBFA714E187F1D8600A76262 /* closures.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7143187F1D8600A76262 /* closures.c */; }; + DBFA714F187F1D8600A76262 /* closures.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7143187F1D8600A76262 /* closures.c */; }; + DBFA7156187F1D8600A76262 /* prep_cif.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7147187F1D8600A76262 /* prep_cif.c */; }; + DBFA7157187F1D8600A76262 /* prep_cif.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7147187F1D8600A76262 /* prep_cif.c */; }; + DBFA7158187F1D8600A76262 /* raw_api.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7148187F1D8600A76262 /* raw_api.c */; }; + DBFA7159187F1D8600A76262 /* raw_api.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7148187F1D8600A76262 /* raw_api.c */; }; + DBFA715A187F1D8600A76262 /* types.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7149187F1D8600A76262 /* types.c */; }; + DBFA715B187F1D8600A76262 /* types.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7149187F1D8600A76262 /* types.c */; }; + DBFA7177187F1D9B00A76262 /* ffi_arm64.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA716C187F1D9B00A76262 /* ffi_arm64.c */; }; + DBFA7178187F1D9B00A76262 /* sysv_arm64.S in Sources */ = {isa = PBXBuildFile; fileRef = DBFA716D187F1D9B00A76262 /* sysv_arm64.S */; }; + DBFA7179187F1D9B00A76262 /* ffi_armv7.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA716F187F1D9B00A76262 /* ffi_armv7.c */; }; + DBFA717A187F1D9B00A76262 /* sysv_armv7.S in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7170187F1D9B00A76262 /* sysv_armv7.S */; }; + DBFA717E187F1D9B00A76262 /* ffi64_x86_64.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7175187F1D9B00A76262 /* ffi64_x86_64.c */; }; + DBFA718F187F1DA100A76262 /* ffi_x86_64.h in Headers */ = {isa = PBXBuildFile; fileRef = DBFA7183187F1DA100A76262 /* ffi_x86_64.h */; }; + DBFA7191187F1DA100A76262 /* fficonfig_x86_64.h in Headers */ = {isa = PBXBuildFile; fileRef = DBFA7185187F1DA100A76262 /* fficonfig_x86_64.h */; }; + DBFA7193187F1DA100A76262 /* ffitarget_x86_64.h in Headers */ = {isa = PBXBuildFile; fileRef = DBFA7187187F1DA100A76262 /* ffitarget_x86_64.h */; }; + DBFA7194187F1DA100A76262 /* unix64_x86_64.S in Sources */ = {isa = PBXBuildFile; fileRef = DBFA718A187F1DA100A76262 /* unix64_x86_64.S */; }; + DBFA7196187F1DA100A76262 /* ffi64_x86_64.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA718C187F1DA100A76262 /* ffi64_x86_64.c */; }; + FDB52FB31F6144FA00AA92E6 /* unix64_x86_64.S in Sources */ = {isa = PBXBuildFile; fileRef = 43E9A5C61D352C1500926A8F /* unix64_x86_64.S */; }; + FDB52FB51F6144FA00AA92E6 /* ffi64_x86_64.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7175187F1D9B00A76262 /* ffi64_x86_64.c */; }; + FDB52FB61F6144FA00AA92E6 /* ffi_armv7.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA716F187F1D9B00A76262 /* ffi_armv7.c */; }; + FDB52FB71F6144FA00AA92E6 /* closures.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7143187F1D8600A76262 /* closures.c */; }; + FDB52FB81F6144FA00AA92E6 /* sysv_armv7.S in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7170187F1D9B00A76262 /* sysv_armv7.S */; }; + FDB52FB91F6144FA00AA92E6 /* ffiw64_x86_64.c in Sources */ = {isa = PBXBuildFile; fileRef = 43B5D3F71D35473200D1E1FD /* ffiw64_x86_64.c */; }; + FDB52FBA1F6144FA00AA92E6 /* prep_cif.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7147187F1D8600A76262 /* prep_cif.c */; }; + FDB52FBC1F6144FA00AA92E6 /* raw_api.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7148187F1D8600A76262 /* raw_api.c */; }; + FDB52FBD1F6144FA00AA92E6 /* sysv_arm64.S in Sources */ = {isa = PBXBuildFile; fileRef = DBFA716D187F1D9B00A76262 /* sysv_arm64.S */; }; + FDB52FBE1F6144FA00AA92E6 /* types.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7149187F1D8600A76262 /* types.c */; }; + FDB52FBF1F6144FA00AA92E6 /* ffi_arm64.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA716C187F1D9B00A76262 /* ffi_arm64.c */; }; + FDB52FC01F6144FA00AA92E6 /* win64_x86_64.S in Sources */ = {isa = PBXBuildFile; fileRef = 43B5D3F91D3547CE00D1E1FD /* win64_x86_64.S */; }; + FDB52FD01F614A8B00AA92E6 /* ffi.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA713E187F1D8600A76262 /* ffi.h */; }; + FDB52FD11F614AA700AA92E6 /* ffi_arm64.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA715E187F1D9B00A76262 /* ffi_arm64.h */; }; + FDB52FD21F614AAB00AA92E6 /* ffi_armv7.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA715F187F1D9B00A76262 /* ffi_armv7.h */; }; + FDB52FD41F614AB500AA92E6 /* ffi_x86_64.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7161187F1D9B00A76262 /* ffi_x86_64.h */; }; + FDB52FD51F614AE200AA92E6 /* ffi.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA713E187F1D8600A76262 /* ffi.h */; }; + FDB52FD61F614AEA00AA92E6 /* ffi_arm64.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA715E187F1D9B00A76262 /* ffi_arm64.h */; }; + FDB52FD71F614AED00AA92E6 /* ffi_x86_64.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7161187F1D9B00A76262 /* ffi_x86_64.h */; }; + FDB52FD81F614B8700AA92E6 /* ffitarget.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7141187F1D8600A76262 /* ffitarget.h */; }; + FDB52FD91F614B8E00AA92E6 /* ffitarget_arm64.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7166187F1D9B00A76262 /* ffitarget_arm64.h */; }; + FDB52FDA1F614B9300AA92E6 /* ffitarget_armv7.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7167187F1D9B00A76262 /* ffitarget_armv7.h */; }; + FDB52FDD1F614BA900AA92E6 /* ffitarget_x86_64.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7169187F1D9B00A76262 /* ffitarget_x86_64.h */; }; + FDB52FDE1F6155E300AA92E6 /* ffitarget.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7141187F1D8600A76262 /* ffitarget.h */; }; + FDB52FDF1F6155EA00AA92E6 /* ffitarget_arm64.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7166187F1D9B00A76262 /* ffitarget_arm64.h */; }; + FDB52FE01F6155EF00AA92E6 /* ffitarget_x86_64.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7169187F1D9B00A76262 /* ffitarget_x86_64.h */; }; + FDB52FE21F6156FA00AA92E6 /* ffi.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA713E187F1D8600A76262 /* ffi.h */; }; + FDB52FE31F61571A00AA92E6 /* ffi_x86_64.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7183187F1DA100A76262 /* ffi_x86_64.h */; }; + FDB52FE41F61571D00AA92E6 /* ffitarget.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7141187F1D8600A76262 /* ffitarget.h */; }; + FDB52FE61F61573100AA92E6 /* ffitarget_x86_64.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = DBFA7187187F1DA100A76262 /* ffitarget_x86_64.h */; }; + FDDB2F411F5D66E200EF414E /* ffiw64_x86_64.c in Sources */ = {isa = PBXBuildFile; fileRef = FDDB2F3F1F5D666900EF414E /* ffiw64_x86_64.c */; }; + FDDB2F461F5D691E00EF414E /* win64_x86_64.S in Sources */ = {isa = PBXBuildFile; fileRef = FDDB2F441F5D68C900EF414E /* win64_x86_64.S */; }; + FDDB2F4A1F5D846400EF414E /* ffi64_x86_64.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA718C187F1DA100A76262 /* ffi64_x86_64.c */; }; + FDDB2F4C1F5D846400EF414E /* prep_cif.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7147187F1D8600A76262 /* prep_cif.c */; }; + FDDB2F4E1F5D846400EF414E /* ffiw64_x86_64.c in Sources */ = {isa = PBXBuildFile; fileRef = FDDB2F3F1F5D666900EF414E /* ffiw64_x86_64.c */; }; + FDDB2F4F1F5D846400EF414E /* types.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7149187F1D8600A76262 /* types.c */; }; + FDDB2F501F5D846400EF414E /* raw_api.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7148187F1D8600A76262 /* raw_api.c */; }; + FDDB2F511F5D846400EF414E /* closures.c in Sources */ = {isa = PBXBuildFile; fileRef = DBFA7143187F1D8600A76262 /* closures.c */; }; + FDDB2F521F5D846400EF414E /* unix64_x86_64.S in Sources */ = {isa = PBXBuildFile; fileRef = DBFA718A187F1DA100A76262 /* unix64_x86_64.S */; }; + FDDB2F531F5D846400EF414E /* win64_x86_64.S in Sources */ = {isa = PBXBuildFile; fileRef = FDDB2F441F5D68C900EF414E /* win64_x86_64.S */; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + DB13B1641849DF1E0010F42D /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 12; + dstPath = "include/$(PRODUCT_NAME)"; + dstSubfolderSpec = 16; + files = ( + FDB52FD01F614A8B00AA92E6 /* ffi.h in CopyFiles */, + FDB52FD11F614AA700AA92E6 /* ffi_arm64.h in CopyFiles */, + FDB52FD21F614AAB00AA92E6 /* ffi_armv7.h in CopyFiles */, + FDB52FD41F614AB500AA92E6 /* ffi_x86_64.h in CopyFiles */, + FDB52FD81F614B8700AA92E6 /* ffitarget.h in CopyFiles */, + FDB52FD91F614B8E00AA92E6 /* ffitarget_arm64.h in CopyFiles */, + FDB52FDA1F614B9300AA92E6 /* ffitarget_armv7.h in CopyFiles */, + FDB52FDD1F614BA900AA92E6 /* ffitarget_x86_64.h in CopyFiles */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FDB52FC11F6144FA00AA92E6 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 12; + dstPath = "include/$(PRODUCT_NAME)"; + dstSubfolderSpec = 16; + files = ( + FDB52FD51F614AE200AA92E6 /* ffi.h in CopyFiles */, + FDB52FD61F614AEA00AA92E6 /* ffi_arm64.h in CopyFiles */, + FDB52FD71F614AED00AA92E6 /* ffi_x86_64.h in CopyFiles */, + FDB52FDE1F6155E300AA92E6 /* ffitarget.h in CopyFiles */, + FDB52FDF1F6155EA00AA92E6 /* ffitarget_arm64.h in CopyFiles */, + FDB52FE01F6155EF00AA92E6 /* ffitarget_x86_64.h in CopyFiles */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FDB52FE11F6156E000AA92E6 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = "include/$(PRODUCT_NAME)"; + dstSubfolderSpec = 16; + files = ( + FDB52FE21F6156FA00AA92E6 /* ffi.h in CopyFiles */, + FDB52FE31F61571A00AA92E6 /* ffi_x86_64.h in CopyFiles */, + FDB52FE41F61571D00AA92E6 /* ffitarget.h in CopyFiles */, + FDB52FE61F61573100AA92E6 /* ffitarget_x86_64.h in CopyFiles */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 43B5D3F71D35473200D1E1FD /* ffiw64_x86_64.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ffiw64_x86_64.c; sourceTree = ""; }; + 43B5D3F91D3547CE00D1E1FD /* win64_x86_64.S */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = win64_x86_64.S; sourceTree = ""; }; + 43E9A5C61D352C1500926A8F /* unix64_x86_64.S */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = unix64_x86_64.S; sourceTree = ""; }; + 43E9A5DA1D35373600926A8F /* internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = internal.h; sourceTree = ""; }; + 43E9A5DB1D35374400926A8F /* internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = internal.h; sourceTree = ""; }; + 43E9A5DC1D35375400926A8F /* internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = internal.h; sourceTree = ""; }; + 43E9A5DD1D35375400926A8F /* internal64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = internal64.h; sourceTree = ""; }; + DB13B1661849DF1E0010F42D /* libffi.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libffi.a; sourceTree = BUILT_PRODUCTS_DIR; }; + DB13B1911849DF510010F42D /* ffi.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = ffi.dylib; sourceTree = BUILT_PRODUCTS_DIR; }; + DBFA713E187F1D8600A76262 /* ffi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ffi.h; sourceTree = ""; }; + DBFA713F187F1D8600A76262 /* ffi_common.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ffi_common.h; sourceTree = ""; }; + DBFA7140187F1D8600A76262 /* fficonfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = fficonfig.h; sourceTree = ""; }; + DBFA7141187F1D8600A76262 /* ffitarget.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ffitarget.h; sourceTree = ""; }; + DBFA7143187F1D8600A76262 /* closures.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = closures.c; sourceTree = ""; }; + DBFA7145187F1D8600A76262 /* dlmalloc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dlmalloc.c; sourceTree = ""; }; + DBFA7147187F1D8600A76262 /* prep_cif.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = prep_cif.c; sourceTree = ""; }; + DBFA7148187F1D8600A76262 /* raw_api.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = raw_api.c; sourceTree = ""; }; + DBFA7149187F1D8600A76262 /* types.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = types.c; sourceTree = ""; }; + DBFA715E187F1D9B00A76262 /* ffi_arm64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ffi_arm64.h; sourceTree = ""; }; + DBFA715F187F1D9B00A76262 /* ffi_armv7.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ffi_armv7.h; sourceTree = ""; }; + DBFA7161187F1D9B00A76262 /* ffi_x86_64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ffi_x86_64.h; sourceTree = ""; }; + DBFA7162187F1D9B00A76262 /* fficonfig_arm64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = fficonfig_arm64.h; sourceTree = ""; }; + DBFA7163187F1D9B00A76262 /* fficonfig_armv7.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = fficonfig_armv7.h; sourceTree = ""; }; + DBFA7165187F1D9B00A76262 /* fficonfig_x86_64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = fficonfig_x86_64.h; sourceTree = ""; }; + DBFA7166187F1D9B00A76262 /* ffitarget_arm64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ffitarget_arm64.h; sourceTree = ""; }; + DBFA7167187F1D9B00A76262 /* ffitarget_armv7.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ffitarget_armv7.h; sourceTree = ""; }; + DBFA7169187F1D9B00A76262 /* ffitarget_x86_64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ffitarget_x86_64.h; sourceTree = ""; }; + DBFA716C187F1D9B00A76262 /* ffi_arm64.c */ = {isa = PBXFileReference; fileEncoding = 4; indentWidth = 2; lastKnownFileType = sourcecode.c.c; path = ffi_arm64.c; sourceTree = ""; }; + DBFA716D187F1D9B00A76262 /* sysv_arm64.S */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = sysv_arm64.S; sourceTree = ""; }; + DBFA716F187F1D9B00A76262 /* ffi_armv7.c */ = {isa = PBXFileReference; fileEncoding = 4; indentWidth = 2; lastKnownFileType = sourcecode.c.c; path = ffi_armv7.c; sourceTree = ""; }; + DBFA7170187F1D9B00A76262 /* sysv_armv7.S */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = sysv_armv7.S; sourceTree = ""; }; + DBFA7175187F1D9B00A76262 /* ffi64_x86_64.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ffi64_x86_64.c; sourceTree = ""; }; + DBFA7183187F1DA100A76262 /* ffi_x86_64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ffi_x86_64.h; sourceTree = ""; }; + DBFA7185187F1DA100A76262 /* fficonfig_x86_64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = fficonfig_x86_64.h; sourceTree = ""; }; + DBFA7187187F1DA100A76262 /* ffitarget_x86_64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ffitarget_x86_64.h; sourceTree = ""; }; + DBFA718A187F1DA100A76262 /* unix64_x86_64.S */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = unix64_x86_64.S; sourceTree = ""; }; + DBFA718C187F1DA100A76262 /* ffi64_x86_64.c */ = {isa = PBXFileReference; fileEncoding = 4; indentWidth = 2; lastKnownFileType = sourcecode.c.c; path = ffi64_x86_64.c; sourceTree = ""; }; + FDB52FC51F6144FA00AA92E6 /* libffi.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libffi.a; sourceTree = BUILT_PRODUCTS_DIR; }; + FDDB2F3E1F5D61BC00EF414E /* asmnames.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = asmnames.h; sourceTree = ""; }; + FDDB2F3F1F5D666900EF414E /* ffiw64_x86_64.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ffiw64_x86_64.c; sourceTree = ""; }; + FDDB2F421F5D68C900EF414E /* internal64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = internal64.h; sourceTree = ""; }; + FDDB2F431F5D68C900EF414E /* internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = internal.h; sourceTree = ""; }; + FDDB2F441F5D68C900EF414E /* win64_x86_64.S */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = win64_x86_64.S; sourceTree = ""; }; + FDDB2F621F5D846400EF414E /* libffi.a */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libffi.a; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXGroup section */ + DB13B15B1849DEB70010F42D = { + isa = PBXGroup; + children = ( + DBFA713C187F1D8600A76262 /* darwin_common */, + DBFA715C187F1D9B00A76262 /* darwin_ios */, + DBFA7180187F1DA100A76262 /* darwin_osx */, + DB13B1671849DF1E0010F42D /* Products */, + ); + sourceTree = ""; + }; + DB13B1671849DF1E0010F42D /* Products */ = { + isa = PBXGroup; + children = ( + DB13B1661849DF1E0010F42D /* libffi.a */, + DB13B1911849DF510010F42D /* ffi.dylib */, + FDDB2F621F5D846400EF414E /* libffi.a */, + FDB52FC51F6144FA00AA92E6 /* libffi.a */, + ); + name = Products; + sourceTree = ""; + }; + DBFA713C187F1D8600A76262 /* darwin_common */ = { + isa = PBXGroup; + children = ( + DBFA713D187F1D8600A76262 /* include */, + DBFA7142187F1D8600A76262 /* src */, + ); + path = darwin_common; + sourceTree = ""; + }; + DBFA713D187F1D8600A76262 /* include */ = { + isa = PBXGroup; + children = ( + DBFA713E187F1D8600A76262 /* ffi.h */, + DBFA713F187F1D8600A76262 /* ffi_common.h */, + DBFA7140187F1D8600A76262 /* fficonfig.h */, + DBFA7141187F1D8600A76262 /* ffitarget.h */, + ); + path = include; + sourceTree = ""; + }; + DBFA7142187F1D8600A76262 /* src */ = { + isa = PBXGroup; + children = ( + DBFA7143187F1D8600A76262 /* closures.c */, + DBFA7145187F1D8600A76262 /* dlmalloc.c */, + DBFA7147187F1D8600A76262 /* prep_cif.c */, + DBFA7148187F1D8600A76262 /* raw_api.c */, + DBFA7149187F1D8600A76262 /* types.c */, + ); + path = src; + sourceTree = ""; + }; + DBFA715C187F1D9B00A76262 /* darwin_ios */ = { + isa = PBXGroup; + children = ( + DBFA715D187F1D9B00A76262 /* include */, + DBFA716A187F1D9B00A76262 /* src */, + ); + path = darwin_ios; + sourceTree = ""; + }; + DBFA715D187F1D9B00A76262 /* include */ = { + isa = PBXGroup; + children = ( + DBFA715E187F1D9B00A76262 /* ffi_arm64.h */, + DBFA715F187F1D9B00A76262 /* ffi_armv7.h */, + DBFA7161187F1D9B00A76262 /* ffi_x86_64.h */, + DBFA7162187F1D9B00A76262 /* fficonfig_arm64.h */, + DBFA7163187F1D9B00A76262 /* fficonfig_armv7.h */, + DBFA7165187F1D9B00A76262 /* fficonfig_x86_64.h */, + DBFA7166187F1D9B00A76262 /* ffitarget_arm64.h */, + DBFA7167187F1D9B00A76262 /* ffitarget_armv7.h */, + DBFA7169187F1D9B00A76262 /* ffitarget_x86_64.h */, + ); + path = include; + sourceTree = ""; + }; + DBFA716A187F1D9B00A76262 /* src */ = { + isa = PBXGroup; + children = ( + DBFA716B187F1D9B00A76262 /* aarch64 */, + DBFA716E187F1D9B00A76262 /* arm */, + DBFA7172187F1D9B00A76262 /* x86 */, + ); + path = src; + sourceTree = ""; + }; + DBFA716B187F1D9B00A76262 /* aarch64 */ = { + isa = PBXGroup; + children = ( + 43E9A5DA1D35373600926A8F /* internal.h */, + DBFA716C187F1D9B00A76262 /* ffi_arm64.c */, + DBFA716D187F1D9B00A76262 /* sysv_arm64.S */, + ); + path = aarch64; + sourceTree = ""; + }; + DBFA716E187F1D9B00A76262 /* arm */ = { + isa = PBXGroup; + children = ( + 43E9A5DB1D35374400926A8F /* internal.h */, + DBFA716F187F1D9B00A76262 /* ffi_armv7.c */, + DBFA7170187F1D9B00A76262 /* sysv_armv7.S */, + ); + path = arm; + sourceTree = ""; + }; + DBFA7172187F1D9B00A76262 /* x86 */ = { + isa = PBXGroup; + children = ( + 43E9A5DC1D35375400926A8F /* internal.h */, + 43E9A5DD1D35375400926A8F /* internal64.h */, + DBFA7175187F1D9B00A76262 /* ffi64_x86_64.c */, + 43B5D3F71D35473200D1E1FD /* ffiw64_x86_64.c */, + 43E9A5C61D352C1500926A8F /* unix64_x86_64.S */, + 43B5D3F91D3547CE00D1E1FD /* win64_x86_64.S */, + ); + path = x86; + sourceTree = ""; + }; + DBFA7180187F1DA100A76262 /* darwin_osx */ = { + isa = PBXGroup; + children = ( + DBFA7181187F1DA100A76262 /* include */, + DBFA7188187F1DA100A76262 /* src */, + ); + path = darwin_osx; + sourceTree = ""; + }; + DBFA7181187F1DA100A76262 /* include */ = { + isa = PBXGroup; + children = ( + DBFA7183187F1DA100A76262 /* ffi_x86_64.h */, + DBFA7185187F1DA100A76262 /* fficonfig_x86_64.h */, + DBFA7187187F1DA100A76262 /* ffitarget_x86_64.h */, + ); + path = include; + sourceTree = ""; + }; + DBFA7188187F1DA100A76262 /* src */ = { + isa = PBXGroup; + children = ( + DBFA7189187F1DA100A76262 /* x86 */, + ); + path = src; + sourceTree = ""; + }; + DBFA7189187F1DA100A76262 /* x86 */ = { + isa = PBXGroup; + children = ( + FDDB2F431F5D68C900EF414E /* internal.h */, + FDDB2F421F5D68C900EF414E /* internal64.h */, + FDDB2F3E1F5D61BC00EF414E /* asmnames.h */, + DBFA718C187F1DA100A76262 /* ffi64_x86_64.c */, + FDDB2F3F1F5D666900EF414E /* ffiw64_x86_64.c */, + DBFA718A187F1DA100A76262 /* unix64_x86_64.S */, + FDDB2F441F5D68C900EF414E /* win64_x86_64.S */, + ); + path = x86; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + DB13B18F1849DF510010F42D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + DBFA714C187F1D8600A76262 /* fficonfig.h in Headers */, + DBFA714D187F1D8600A76262 /* ffitarget.h in Headers */, + DBFA714A187F1D8600A76262 /* ffi.h in Headers */, + DBFA718F187F1DA100A76262 /* ffi_x86_64.h in Headers */, + DBFA7191187F1DA100A76262 /* fficonfig_x86_64.h in Headers */, + DBFA714B187F1D8600A76262 /* ffi_common.h in Headers */, + DBFA7193187F1DA100A76262 /* ffitarget_x86_64.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + DB13B1651849DF1E0010F42D /* libffi-iOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = DB13B18B1849DF1E0010F42D /* Build configuration list for PBXNativeTarget "libffi-iOS" */; + buildPhases = ( + 43B5D3FB1D35480D00D1E1FD /* Run Script */, + DB13B1621849DF1E0010F42D /* Sources */, + DB13B1641849DF1E0010F42D /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "libffi-iOS"; + productName = ffi; + productReference = DB13B1661849DF1E0010F42D /* libffi.a */; + productType = "com.apple.product-type.library.static"; + }; + DB13B1901849DF510010F42D /* libffi-Mac */ = { + isa = PBXNativeTarget; + buildConfigurationList = DB13B1B01849DF520010F42D /* Build configuration list for PBXNativeTarget "libffi-Mac" */; + buildPhases = ( + DB13B3061849E0490010F42D /* ShellScript */, + DB13B18D1849DF510010F42D /* Sources */, + DB13B18F1849DF510010F42D /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "libffi-Mac"; + productName = ffi; + productReference = DB13B1911849DF510010F42D /* ffi.dylib */; + productType = "com.apple.product-type.library.dynamic"; + }; + FDB52FB01F6144FA00AA92E6 /* libffi-tvOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = FDB52FC21F6144FA00AA92E6 /* Build configuration list for PBXNativeTarget "libffi-tvOS" */; + buildPhases = ( + FDB52FB11F6144FA00AA92E6 /* Run Script */, + FDB52FB21F6144FA00AA92E6 /* Sources */, + FDB52FC11F6144FA00AA92E6 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "libffi-tvOS"; + productName = ffi; + productReference = FDB52FC51F6144FA00AA92E6 /* libffi.a */; + productType = "com.apple.product-type.library.static"; + }; + FDDB2F471F5D846400EF414E /* libffi-static-Mac */ = { + isa = PBXNativeTarget; + buildConfigurationList = FDDB2F5F1F5D846400EF414E /* Build configuration list for PBXNativeTarget "libffi-static-Mac" */; + buildPhases = ( + FDDB2F481F5D846400EF414E /* ShellScript */, + FDDB2F491F5D846400EF414E /* Sources */, + FDB52FE11F6156E000AA92E6 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "libffi-static-Mac"; + productName = ffi; + productReference = FDDB2F621F5D846400EF414E /* libffi.a */; + productType = "com.apple.product-type.library.dynamic"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + DB13B15C1849DEB70010F42D /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0830; + }; + buildConfigurationList = DB13B15F1849DEB70010F42D /* Build configuration list for PBXProject "libffi" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = DB13B15B1849DEB70010F42D; + productRefGroup = DB13B1671849DF1E0010F42D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + DB13B1651849DF1E0010F42D /* libffi-iOS */, + FDB52FB01F6144FA00AA92E6 /* libffi-tvOS */, + DB13B1901849DF510010F42D /* libffi-Mac */, + FDDB2F471F5D846400EF414E /* libffi-static-Mac */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXShellScriptBuildPhase section */ + 43B5D3FB1D35480D00D1E1FD /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if [ ! -f \"./compile\" ]\nthen\nautoreconf -i -f -v\nif [ -f \"../ltmain.sh\" ]\nthen\necho \"fixing ltmain.sh for some reason\"\nmv ../ltmain.sh ./\nautoreconf -i -f -v\nfi\n/usr/bin/python generate-darwin-source-and-headers.py --only-ios\nfi"; + }; + DB13B3061849E0490010F42D /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if [ ! -f \"./compile\" ]\nthen\nautoreconf -i -f -v\nif [ -f \"../ltmain.sh\" ]\nthen\necho \"fixing ltmain.sh for some reason\"\nmv ../ltmain.sh ./\nautoreconf -i -f -v\nfi\n/usr/bin/python generate-darwin-source-and-headers.py --only-osx\nfi"; + }; + FDB52FB11F6144FA00AA92E6 /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if [ ! -f \"./compile\" ]\nthen\nautoreconf -i -f -v\nif [ -f \"../ltmain.sh\" ]\nthen\necho \"fixing ltmain.sh for some reason\"\nmv ../ltmain.sh ./\nautoreconf -i -f -v\nfi\n/usr/bin/python generate-darwin-source-and-headers.py --only-ios\nfi"; + }; + FDDB2F481F5D846400EF414E /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if [ ! -f \"./compile\" ]\nthen\nautoreconf -i -f -v\nif [ -f \"../ltmain.sh\" ]\nthen\necho \"fixing ltmain.sh for some reason\"\nmv ../ltmain.sh ./\nautoreconf -i -f -v\nfi\n/usr/bin/python generate-darwin-source-and-headers.py --only-osx\nfi"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + DB13B1621849DF1E0010F42D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 43E9A5C81D352C1500926A8F /* unix64_x86_64.S in Sources */, + DBFA717E187F1D9B00A76262 /* ffi64_x86_64.c in Sources */, + DBFA7179187F1D9B00A76262 /* ffi_armv7.c in Sources */, + DBFA714E187F1D8600A76262 /* closures.c in Sources */, + DBFA717A187F1D9B00A76262 /* sysv_armv7.S in Sources */, + 43B5D3F81D35473200D1E1FD /* ffiw64_x86_64.c in Sources */, + DBFA7156187F1D8600A76262 /* prep_cif.c in Sources */, + DBFA7158187F1D8600A76262 /* raw_api.c in Sources */, + DBFA7178187F1D9B00A76262 /* sysv_arm64.S in Sources */, + DBFA715A187F1D8600A76262 /* types.c in Sources */, + DBFA7177187F1D9B00A76262 /* ffi_arm64.c in Sources */, + 43B5D3FA1D3547CE00D1E1FD /* win64_x86_64.S in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DB13B18D1849DF510010F42D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + DBFA7196187F1DA100A76262 /* ffi64_x86_64.c in Sources */, + DBFA7157187F1D8600A76262 /* prep_cif.c in Sources */, + FDDB2F411F5D66E200EF414E /* ffiw64_x86_64.c in Sources */, + DBFA715B187F1D8600A76262 /* types.c in Sources */, + DBFA7159187F1D8600A76262 /* raw_api.c in Sources */, + DBFA714F187F1D8600A76262 /* closures.c in Sources */, + DBFA7194187F1DA100A76262 /* unix64_x86_64.S in Sources */, + FDDB2F461F5D691E00EF414E /* win64_x86_64.S in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FDB52FB21F6144FA00AA92E6 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FDB52FB31F6144FA00AA92E6 /* unix64_x86_64.S in Sources */, + FDB52FB51F6144FA00AA92E6 /* ffi64_x86_64.c in Sources */, + FDB52FB61F6144FA00AA92E6 /* ffi_armv7.c in Sources */, + FDB52FB71F6144FA00AA92E6 /* closures.c in Sources */, + FDB52FB81F6144FA00AA92E6 /* sysv_armv7.S in Sources */, + FDB52FB91F6144FA00AA92E6 /* ffiw64_x86_64.c in Sources */, + FDB52FBA1F6144FA00AA92E6 /* prep_cif.c in Sources */, + FDB52FBC1F6144FA00AA92E6 /* raw_api.c in Sources */, + FDB52FBD1F6144FA00AA92E6 /* sysv_arm64.S in Sources */, + FDB52FBE1F6144FA00AA92E6 /* types.c in Sources */, + FDB52FBF1F6144FA00AA92E6 /* ffi_arm64.c in Sources */, + FDB52FC01F6144FA00AA92E6 /* win64_x86_64.S in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FDDB2F491F5D846400EF414E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FDDB2F4A1F5D846400EF414E /* ffi64_x86_64.c in Sources */, + FDDB2F4C1F5D846400EF414E /* prep_cif.c in Sources */, + FDDB2F4E1F5D846400EF414E /* ffiw64_x86_64.c in Sources */, + FDDB2F4F1F5D846400EF414E /* types.c in Sources */, + FDDB2F501F5D846400EF414E /* raw_api.c in Sources */, + FDDB2F511F5D846400EF414E /* closures.c in Sources */, + FDDB2F521F5D846400EF414E /* unix64_x86_64.S in Sources */, + FDDB2F531F5D846400EF414E /* win64_x86_64.S in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + DB13B1601849DEB70010F42D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + darwin_common/include, + ); + ONLY_ACTIVE_ARCH = YES; + }; + name = Debug; + }; + DB13B1611849DEB70010F42D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + darwin_common/include, + ); + }; + name = Release; + }; + DB13B1871849DF1E0010F42D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DSTROOT = /tmp/ffi.dst; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + darwin_ios/include, + ); + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + PRODUCT_NAME = ffi; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + VALID_ARCHS = "arm64 armv7 armv7s x86_64"; + }; + name = Debug; + }; + DB13B1881849DF1E0010F42D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + DSTROOT = /tmp/ffi.dst; + ENABLE_NS_ASSERTIONS = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + darwin_ios/include, + ); + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + PRODUCT_NAME = ffi; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + VALIDATE_PRODUCT = YES; + VALID_ARCHS = "arm64 armv7 armv7s x86_64"; + }; + name = Release; + }; + DB13B1B11849DF520010F42D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = NO; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_ENABLE_OBJC_EXCEPTIONS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + darwin_osx/include, + ); + MACOSX_DEPLOYMENT_TARGET = 10.6; + ONLY_ACTIVE_ARCH = YES; + OTHER_LDFLAGS = "-Wl,-no_compact_unwind"; + PRODUCT_NAME = ffi; + SDKROOT = macosx; + }; + name = Debug; + }; + DB13B1B21849DF520010F42D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_ENABLE_OBJC_EXCEPTIONS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + darwin_osx/include, + ); + MACOSX_DEPLOYMENT_TARGET = 10.6; + OTHER_LDFLAGS = "-Wl,-no_compact_unwind"; + PRODUCT_NAME = ffi; + SDKROOT = macosx; + }; + name = Release; + }; + FDB52FC31F6144FA00AA92E6 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + darwin_ios/include, + ); + PRODUCT_NAME = ffi; + SDKROOT = appletvos; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + }; + name = Debug; + }; + FDB52FC41F6144FA00AA92E6 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + darwin_ios/include, + ); + PRODUCT_NAME = ffi; + SDKROOT = appletvos; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + FDDB2F601F5D846400EF414E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = NO; + EXECUTABLE_EXTENSION = a; + EXECUTABLE_PREFIX = lib; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_ENABLE_OBJC_EXCEPTIONS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + darwin_osx/include, + ); + MACH_O_TYPE = staticlib; + MACOSX_DEPLOYMENT_TARGET = 10.6; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = ffi; + SDKROOT = macosx; + }; + name = Debug; + }; + FDDB2F611F5D846400EF414E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + EXECUTABLE_EXTENSION = a; + EXECUTABLE_PREFIX = lib; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_ENABLE_OBJC_EXCEPTIONS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + darwin_osx/include, + ); + MACH_O_TYPE = staticlib; + MACOSX_DEPLOYMENT_TARGET = 10.6; + PRODUCT_NAME = ffi; + SDKROOT = macosx; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + DB13B15F1849DEB70010F42D /* Build configuration list for PBXProject "libffi" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + DB13B1601849DEB70010F42D /* Debug */, + DB13B1611849DEB70010F42D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + DB13B18B1849DF1E0010F42D /* Build configuration list for PBXNativeTarget "libffi-iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + DB13B1871849DF1E0010F42D /* Debug */, + DB13B1881849DF1E0010F42D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + DB13B1B01849DF520010F42D /* Build configuration list for PBXNativeTarget "libffi-Mac" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + DB13B1B11849DF520010F42D /* Debug */, + DB13B1B21849DF520010F42D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FDB52FC21F6144FA00AA92E6 /* Build configuration list for PBXNativeTarget "libffi-tvOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FDB52FC31F6144FA00AA92E6 /* Debug */, + FDB52FC41F6144FA00AA92E6 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FDDB2F5F1F5D846400EF414E /* Build configuration list for PBXNativeTarget "libffi-static-Mac" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FDDB2F601F5D846400EF414E /* Debug */, + FDDB2F611F5D846400EF414E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = DB13B15C1849DEB70010F42D /* Project object */; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libtool-version b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libtool-version new file mode 100644 index 0000000..607fee5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/libtool-version @@ -0,0 +1,29 @@ +# This file is used to maintain libtool version info for libffi. See +# the libtool manual to understand the meaning of the fields. This is +# a separate file so that version updates don't involve re-running +# automake. +# +# Here are a set of rules to help you update your library version +# information: +# +# 1. Start with version information of `0:0:0' for each libtool library. +# +# 2. Update the version information only immediately before a public +# release of your software. More frequent updates are unnecessary, +# and only guarantee that the current interface number gets larger +# faster. +# +# 3. If the library source code has changed at all since the last +# update, then increment revision (`c:r:a' becomes `c:r+1:a'). +# +# 4. If any interfaces have been added, removed, or changed since the +# last update, increment current, and set revision to 0. +# +# 5. If any interfaces have been added since the last public release, +# then increment age. +# +# 6. If any interfaces have been removed since the last public +# release, then set age to 0. +# +# CURRENT:REVISION:AGE +9:0:1 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/asmcfi.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/asmcfi.m4 new file mode 100644 index 0000000..3e28602 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/asmcfi.m4 @@ -0,0 +1,13 @@ +AC_DEFUN([GCC_AS_CFI_PSEUDO_OP], +[AC_CACHE_CHECK([assembler .cfi pseudo-op support], + gcc_cv_as_cfi_pseudo_op, [ + gcc_cv_as_cfi_pseudo_op=unknown + AC_TRY_COMPILE([asm (".cfi_sections\n\t.cfi_startproc\n\t.cfi_endproc");],, + [gcc_cv_as_cfi_pseudo_op=yes], + [gcc_cv_as_cfi_pseudo_op=no]) + ]) + if test "x$gcc_cv_as_cfi_pseudo_op" = xyes; then + AC_DEFINE(HAVE_AS_CFI_PSEUDO_OP, 1, + [Define if your assembler supports .cfi_* directives.]) + fi +]) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_append_flag.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_append_flag.m4 new file mode 100644 index 0000000..dd6d8b6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_append_flag.m4 @@ -0,0 +1,50 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_append_flag.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_APPEND_FLAG(FLAG, [FLAGS-VARIABLE]) +# +# DESCRIPTION +# +# FLAG is appended to the FLAGS-VARIABLE shell variable, with a space +# added in between. +# +# If FLAGS-VARIABLE is not specified, the current language's flags (e.g. +# CFLAGS) is used. FLAGS-VARIABLE is not changed if it already contains +# FLAG. If FLAGS-VARIABLE is unset in the shell, it is set to exactly +# FLAG. +# +# NOTE: Implementation based on AX_CFLAGS_GCC_OPTION. +# +# LICENSE +# +# Copyright (c) 2008 Guido U. Draheim +# Copyright (c) 2011 Maarten Bosmans +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 8 + +AC_DEFUN([AX_APPEND_FLAG], +[dnl +AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_SET_IF +AS_VAR_PUSHDEF([FLAGS], [m4_default($2,_AC_LANG_PREFIX[FLAGS])]) +AS_VAR_SET_IF(FLAGS,[ + AS_CASE([" AS_VAR_GET(FLAGS) "], + [*" $1 "*], [AC_RUN_LOG([: FLAGS already contains $1])], + [ + AS_VAR_APPEND(FLAGS,[" $1"]) + AC_RUN_LOG([: FLAGS="$FLAGS"]) + ]) + ], + [ + AS_VAR_SET(FLAGS,[$1]) + AC_RUN_LOG([: FLAGS="$FLAGS"]) + ]) +AS_VAR_POPDEF([FLAGS])dnl +])dnl AX_APPEND_FLAG diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_cc_maxopt.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_cc_maxopt.m4 new file mode 100644 index 0000000..9e7f1ee --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_cc_maxopt.m4 @@ -0,0 +1,194 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_cc_maxopt.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_CC_MAXOPT +# +# DESCRIPTION +# +# Try to turn on "good" C optimization flags for various compilers and +# architectures, for some definition of "good". (In our case, good for +# FFTW and hopefully for other scientific codes. Modify as needed.) +# +# The user can override the flags by setting the CFLAGS environment +# variable. The user can also specify --enable-portable-binary in order to +# disable any optimization flags that might result in a binary that only +# runs on the host architecture. +# +# Note also that the flags assume that ANSI C aliasing rules are followed +# by the code (e.g. for gcc's -fstrict-aliasing), and that floating-point +# computations can be re-ordered as needed. +# +# Requires macros: AX_CHECK_COMPILE_FLAG, AX_COMPILER_VENDOR, +# AX_GCC_ARCHFLAG, AX_GCC_X86_CPUID. +# +# LICENSE +# +# Copyright (c) 2008 Steven G. Johnson +# Copyright (c) 2008 Matteo Frigo +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. + +#serial 17 + +AC_DEFUN([AX_CC_MAXOPT], +[ +AC_REQUIRE([AC_PROG_CC]) +AC_REQUIRE([AX_COMPILER_VENDOR]) +AC_REQUIRE([AC_CANONICAL_HOST]) + +AC_ARG_ENABLE(portable-binary, [AS_HELP_STRING([--enable-portable-binary], [disable compiler optimizations that would produce unportable binaries])], + acx_maxopt_portable=$enableval, acx_maxopt_portable=no) + +# Try to determine "good" native compiler flags if none specified via CFLAGS +if test "$ac_test_CFLAGS" != "set"; then + CFLAGS="" + case $ax_cv_c_compiler_vendor in + dec) CFLAGS="-newc -w0 -O5 -ansi_alias -ansi_args -fp_reorder -tune host" + if test "x$acx_maxopt_portable" = xno; then + CFLAGS="$CFLAGS -arch host" + fi;; + + sun) CFLAGS="-native -fast -xO5 -dalign" + if test "x$acx_maxopt_portable" = xyes; then + CFLAGS="$CFLAGS -xarch=generic" + fi;; + + hp) CFLAGS="+Oall +Optrs_ansi +DSnative" + if test "x$acx_maxopt_portable" = xyes; then + CFLAGS="$CFLAGS +DAportable" + fi;; + + ibm) if test "x$acx_maxopt_portable" = xno; then + xlc_opt="-qarch=auto -qtune=auto" + else + xlc_opt="-qtune=auto" + fi + AX_CHECK_COMPILE_FLAG($xlc_opt, + CFLAGS="-O3 -qansialias -w $xlc_opt", + [CFLAGS="-O3 -qansialias -w" + echo "******************************************************" + echo "* You seem to have the IBM C compiler. It is *" + echo "* recommended for best performance that you use: *" + echo "* *" + echo "* CFLAGS=-O3 -qarch=xxx -qtune=xxx -qansialias -w *" + echo "* ^^^ ^^^ *" + echo "* where xxx is pwr2, pwr3, 604, or whatever kind of *" + echo "* CPU you have. (Set the CFLAGS environment var. *" + echo "* and re-run configure.) For more info, man cc. *" + echo "******************************************************"]) + ;; + + intel) CFLAGS="-O3 -ansi_alias" + if test "x$acx_maxopt_portable" = xno; then + icc_archflag=unknown + icc_flags="" + case $host_cpu in + i686*|x86_64*) + # icc accepts gcc assembly syntax, so these should work: + AX_GCC_X86_CPUID(0) + AX_GCC_X86_CPUID(1) + case $ax_cv_gcc_x86_cpuid_0 in # see AX_GCC_ARCHFLAG + *:756e6547:6c65746e:49656e69) # Intel + case $ax_cv_gcc_x86_cpuid_1 in + *0?6[[78ab]]?:*:*:*|?6[[78ab]]?:*:*:*|6[[78ab]]?:*:*:*) icc_flags="-xK" ;; + *0?6[[9d]]?:*:*:*|?6[[9d]]?:*:*:*|6[[9d]]?:*:*:*|*1?65?:*:*:*) icc_flags="-xSSE2 -xB -xK" ;; + *0?6e?:*:*:*|?6e?:*:*:*|6e?:*:*:*) icc_flags="-xSSE3 -xP -xO -xB -xK" ;; + *0?6f?:*:*:*|?6f?:*:*:*|6f?:*:*:*|*1?66?:*:*:*) icc_flags="-xSSSE3 -xT -xB -xK" ;; + *1?6[[7d]]?:*:*:*) icc_flags="-xSSE4.1 -xS -xT -xB -xK" ;; + *1?6[[aef]]?:*:*:*|*2?6[[5cef]]?:*:*:*) icc_flags="-xSSE4.2 -xS -xT -xB -xK" ;; + *2?6[[ad]]?:*:*:*) icc_flags="-xAVX -SSE4.2 -xS -xT -xB -xK" ;; + *3?6[[ae]]?:*:*:*) icc_flags="-xCORE-AVX-I -xAVX -SSE4.2 -xS -xT -xB -xK" ;; + *3?6[[cf]]?:*:*:*|*4?6[[56]]?:*:*:*) icc_flags="-xCORE-AVX2 -xCORE-AVX-I -xAVX -SSE4.2 -xS -xT -xB -xK" ;; + *000?f[[346]]?:*:*:*|?f[[346]]?:*:*:*|f[[346]]?:*:*:*) icc_flags="-xSSE3 -xP -xO -xN -xW -xK" ;; + *00??f??:*:*:*|??f??:*:*:*|?f??:*:*:*|f??:*:*:*) icc_flags="-xSSE2 -xN -xW -xK" ;; + esac ;; + esac ;; + esac + if test "x$icc_flags" != x; then + for flag in $icc_flags; do + AX_CHECK_COMPILE_FLAG($flag, [icc_archflag=$flag; break]) + done + fi + AC_MSG_CHECKING([for icc architecture flag]) + AC_MSG_RESULT($icc_archflag) + if test "x$icc_archflag" != xunknown; then + CFLAGS="$CFLAGS $icc_archflag" + fi + fi + ;; + + gnu) + # default optimization flags for gcc on all systems + CFLAGS="-O3 -fomit-frame-pointer" + + # -malign-double for x86 systems + # libffi local change -- don't align double, as it changes the ABI + # AX_CHECK_COMPILE_FLAG(-malign-double, CFLAGS="$CFLAGS -malign-double") + + # -fstrict-aliasing for gcc-2.95+ + AX_CHECK_COMPILE_FLAG(-fstrict-aliasing, + CFLAGS="$CFLAGS -fstrict-aliasing") + + # note that we enable "unsafe" fp optimization with other compilers, too + AX_CHECK_COMPILE_FLAG(-ffast-math, CFLAGS="$CFLAGS -ffast-math") + + AX_GCC_ARCHFLAG($acx_maxopt_portable) + ;; + + microsoft) + # default optimization flags for MSVC opt builds + CFLAGS="-O2" + ;; + esac + + if test -z "$CFLAGS"; then + echo "" + echo "********************************************************" + echo "* WARNING: Don't know the best CFLAGS for this system *" + echo "* Use ./configure CFLAGS=... to specify your own flags *" + echo "* (otherwise, a default of CFLAGS=-O3 will be used) *" + echo "********************************************************" + echo "" + CFLAGS="-O3" + fi + + AX_CHECK_COMPILE_FLAG($CFLAGS, [], [ + echo "" + echo "********************************************************" + echo "* WARNING: The guessed CFLAGS don't seem to work with *" + echo "* your compiler. *" + echo "* Use ./configure CFLAGS=... to specify your own flags *" + echo "********************************************************" + echo "" + CFLAGS="" + ]) + +fi +]) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_cflags_warn_all.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_cflags_warn_all.m4 new file mode 100644 index 0000000..094577e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_cflags_warn_all.m4 @@ -0,0 +1,122 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_cflags_warn_all.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_CFLAGS_WARN_ALL [(shellvar [,default, [A/NA]])] +# AX_CXXFLAGS_WARN_ALL [(shellvar [,default, [A/NA]])] +# AX_FCFLAGS_WARN_ALL [(shellvar [,default, [A/NA]])] +# +# DESCRIPTION +# +# Try to find a compiler option that enables most reasonable warnings. +# +# For the GNU compiler it will be -Wall (and -ansi -pedantic) The result +# is added to the shellvar being CFLAGS, CXXFLAGS, or FCFLAGS by default. +# +# Currently this macro knows about the GCC, Solaris, Digital Unix, AIX, +# HP-UX, IRIX, NEC SX-5 (Super-UX 10), Cray J90 (Unicos 10.0.0.8), and +# Intel compilers. For a given compiler, the Fortran flags are much more +# experimental than their C equivalents. +# +# - $1 shell-variable-to-add-to : CFLAGS, CXXFLAGS, or FCFLAGS +# - $2 add-value-if-not-found : nothing +# - $3 action-if-found : add value to shellvariable +# - $4 action-if-not-found : nothing +# +# NOTE: These macros depend on AX_APPEND_FLAG. +# +# LICENSE +# +# Copyright (c) 2008 Guido U. Draheim +# Copyright (c) 2010 Rhys Ulerich +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation; either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. + +#serial 16 + +AC_DEFUN([AX_FLAGS_WARN_ALL],[dnl +AS_VAR_PUSHDEF([FLAGS],[_AC_LANG_PREFIX[]FLAGS])dnl +AS_VAR_PUSHDEF([VAR],[ac_cv_[]_AC_LANG_ABBREV[]flags_warn_all])dnl +AC_CACHE_CHECK([m4_ifval($1,$1,FLAGS) for maximum warnings], +VAR,[VAR="no, unknown" +ac_save_[]FLAGS="$[]FLAGS" +for ac_arg dnl +in "-warn all % -warn all" dnl Intel + "-pedantic % -Wall" dnl GCC + "-xstrconst % -v" dnl Solaris C + "-std1 % -verbose -w0 -warnprotos" dnl Digital Unix + "-qlanglvl=ansi % -qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd" dnl AIX + "-ansi -ansiE % -fullwarn" dnl IRIX + "+ESlit % +w1" dnl HP-UX C + "-Xc % -pvctl[,]fullmsg" dnl NEC SX-5 (Super-UX 10) + "-h conform % -h msglevel 2" dnl Cray C (Unicos) + # +do FLAGS="$ac_save_[]FLAGS "`echo $ac_arg | sed -e 's,%%.*,,' -e 's,%,,'` + AC_COMPILE_IFELSE([AC_LANG_PROGRAM], + [VAR=`echo $ac_arg | sed -e 's,.*% *,,'` ; break]) +done +FLAGS="$ac_save_[]FLAGS" +]) +AS_VAR_POPDEF([FLAGS])dnl +AX_REQUIRE_DEFINED([AX_APPEND_FLAG]) +case ".$VAR" in + .ok|.ok,*) m4_ifvaln($3,$3) ;; + .|.no|.no,*) m4_default($4,[m4_ifval($2,[AX_APPEND_FLAG([$2], [$1])])]) ;; + *) m4_default($3,[AX_APPEND_FLAG([$VAR], [$1])]) ;; +esac +AS_VAR_POPDEF([VAR])dnl +])dnl AX_FLAGS_WARN_ALL +dnl implementation tactics: +dnl the for-argument contains a list of options. The first part of +dnl these does only exist to detect the compiler - usually it is +dnl a global option to enable -ansi or -extrawarnings. All other +dnl compilers will fail about it. That was needed since a lot of +dnl compilers will give false positives for some option-syntax +dnl like -Woption or -Xoption as they think of it is a pass-through +dnl to later compile stages or something. The "%" is used as a +dnl delimiter. A non-option comment can be given after "%%" marks +dnl which will be shown but not added to the respective C/CXXFLAGS. + +AC_DEFUN([AX_CFLAGS_WARN_ALL],[dnl +AC_LANG_PUSH([C]) +AX_FLAGS_WARN_ALL([$1], [$2], [$3], [$4]) +AC_LANG_POP([C]) +]) + +AC_DEFUN([AX_CXXFLAGS_WARN_ALL],[dnl +AC_LANG_PUSH([C++]) +AX_FLAGS_WARN_ALL([$1], [$2], [$3], [$4]) +AC_LANG_POP([C++]) +]) + +AC_DEFUN([AX_FCFLAGS_WARN_ALL],[dnl +AC_LANG_PUSH([Fortran]) +AX_FLAGS_WARN_ALL([$1], [$2], [$3], [$4]) +AC_LANG_POP([Fortran]) +]) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_check_compile_flag.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_check_compile_flag.m4 new file mode 100644 index 0000000..bd753b3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_check_compile_flag.m4 @@ -0,0 +1,53 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_check_compile_flag.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_CHECK_COMPILE_FLAG(FLAG, [ACTION-SUCCESS], [ACTION-FAILURE], [EXTRA-FLAGS], [INPUT]) +# +# DESCRIPTION +# +# Check whether the given FLAG works with the current language's compiler +# or gives an error. (Warnings, however, are ignored) +# +# ACTION-SUCCESS/ACTION-FAILURE are shell commands to execute on +# success/failure. +# +# If EXTRA-FLAGS is defined, it is added to the current language's default +# flags (e.g. CFLAGS) when the check is done. The check is thus made with +# the flags: "CFLAGS EXTRA-FLAGS FLAG". This can for example be used to +# force the compiler to issue an error when a bad flag is given. +# +# INPUT gives an alternative input source to AC_COMPILE_IFELSE. +# +# NOTE: Implementation based on AX_CFLAGS_GCC_OPTION. Please keep this +# macro in sync with AX_CHECK_{PREPROC,LINK}_FLAG. +# +# LICENSE +# +# Copyright (c) 2008 Guido U. Draheim +# Copyright (c) 2011 Maarten Bosmans +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 6 + +AC_DEFUN([AX_CHECK_COMPILE_FLAG], +[AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF +AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_[]_AC_LANG_ABBREV[]flags_$4_$1])dnl +AC_CACHE_CHECK([whether _AC_LANG compiler accepts $1], CACHEVAR, [ + ax_check_save_flags=$[]_AC_LANG_PREFIX[]FLAGS + _AC_LANG_PREFIX[]FLAGS="$[]_AC_LANG_PREFIX[]FLAGS $4 $1" + AC_COMPILE_IFELSE([m4_default([$5],[AC_LANG_PROGRAM()])], + [AS_VAR_SET(CACHEVAR,[yes])], + [AS_VAR_SET(CACHEVAR,[no])]) + _AC_LANG_PREFIX[]FLAGS=$ax_check_save_flags]) +AS_VAR_IF(CACHEVAR,yes, + [m4_default([$2], :)], + [m4_default([$3], :)]) +AS_VAR_POPDEF([CACHEVAR])dnl +])dnl AX_CHECK_COMPILE_FLAGS diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_compiler_vendor.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_compiler_vendor.m4 new file mode 100644 index 0000000..73efdb0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_compiler_vendor.m4 @@ -0,0 +1,88 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_compiler_vendor.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_COMPILER_VENDOR +# +# DESCRIPTION +# +# Determine the vendor of the C/C++ compiler, e.g., gnu, intel, ibm, sun, +# hp, borland, comeau, dec, cray, kai, lcc, metrowerks, sgi, microsoft, +# watcom, etc. The vendor is returned in the cache variable +# $ax_cv_c_compiler_vendor for C and $ax_cv_cxx_compiler_vendor for C++. +# +# LICENSE +# +# Copyright (c) 2008 Steven G. Johnson +# Copyright (c) 2008 Matteo Frigo +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. + +#serial 17 + +AC_DEFUN([AX_COMPILER_VENDOR], +[AC_CACHE_CHECK([for _AC_LANG compiler vendor], ax_cv_[]_AC_LANG_ABBREV[]_compiler_vendor, + dnl Please add if possible support to ax_compiler_version.m4 + [# note: don't check for gcc first since some other compilers define __GNUC__ + vendors="intel: __ICC,__ECC,__INTEL_COMPILER + ibm: __xlc__,__xlC__,__IBMC__,__IBMCPP__ + pathscale: __PATHCC__,__PATHSCALE__ + clang: __clang__ + cray: _CRAYC + fujitsu: __FUJITSU + sdcc: SDCC, __SDCC + gnu: __GNUC__ + sun: __SUNPRO_C,__SUNPRO_CC + hp: __HP_cc,__HP_aCC + dec: __DECC,__DECCXX,__DECC_VER,__DECCXX_VER + borland: __BORLANDC__,__CODEGEARC__,__TURBOC__ + comeau: __COMO__ + kai: __KCC + lcc: __LCC__ + sgi: __sgi,sgi + microsoft: _MSC_VER + metrowerks: __MWERKS__ + watcom: __WATCOMC__ + portland: __PGI + tcc: __TINYC__ + unknown: UNKNOWN" + for ventest in $vendors; do + case $ventest in + *:) vendor=$ventest; continue ;; + *) vencpp="defined("`echo $ventest | sed 's/,/) || defined(/g'`")" ;; + esac + AC_COMPILE_IFELSE([AC_LANG_PROGRAM(,[ + #if !($vencpp) + thisisanerror; + #endif + ])], [break]) + done + ax_cv_[]_AC_LANG_ABBREV[]_compiler_vendor=`echo $vendor | cut -d: -f1` + ]) +]) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_configure_args.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_configure_args.m4 new file mode 100644 index 0000000..9237efe --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_configure_args.m4 @@ -0,0 +1,49 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_configure_args.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_CONFIGURE_ARGS +# +# DESCRIPTION +# +# Helper macro for AX_ENABLE_BUILDDIR. +# +# The traditional way of starting a subdir-configure is running the script +# with ${1+"$@"} but since autoconf 2.60 this is broken. Instead we have +# to rely on eval'ing $ac_configure_args however some old autoconf +# versions do not provide that. To ensure maximum portability of autoconf +# extension macros this helper can be AC_REQUIRE'd so that +# $ac_configure_args will always be present. +# +# Sadly, the traditional "exec $SHELL" of the enable_builddir macros is +# spoiled now and must be replaced by "eval + exit $?". +# +# Example: +# +# AC_DEFUN([AX_ENABLE_SUBDIR],[dnl +# AC_REQUIRE([AX_CONFIGURE_ARGS])dnl +# eval $SHELL $ac_configure_args || exit $? +# ...]) +# +# LICENSE +# +# Copyright (c) 2008 Guido U. Draheim +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 14 + +AC_DEFUN([AX_CONFIGURE_ARGS],[ + # [$]@ is unusable in 2.60+ but earlier autoconf had no ac_configure_args + if test "${ac_configure_args+set}" != "set" ; then + ac_configure_args= + for ac_arg in ${1+"[$]@"}; do + ac_configure_args="$ac_configure_args '$ac_arg'" + done + fi +]) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_enable_builddir.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_enable_builddir.m4 new file mode 100644 index 0000000..710384d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_enable_builddir.m4 @@ -0,0 +1,302 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_enable_builddir.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_ENABLE_BUILDDIR [(dirstring-or-command [,Makefile.mk [,-all]])] +# +# DESCRIPTION +# +# If the current configure was run within the srcdir then we move all +# configure-files into a subdir and let the configure steps continue +# there. We provide an option --disable-builddir to suppress the move into +# a separate builddir. +# +# Defaults: +# +# $1 = $host (overridden with $HOST) +# $2 = Makefile.mk +# $3 = -all +# +# This macro must be called before AM_INIT_AUTOMAKE. It creates a default +# toplevel srcdir Makefile from the information found in the created +# toplevel builddir Makefile. It just copies the variables and +# rule-targets, each extended with a default rule-execution that recurses +# into the build directory of the current "HOST". You can override the +# auto-detection through `config.guess` and build-time of course, as in +# +# make HOST=i386-mingw-cross +# +# which can of course set at configure time as well using +# +# configure --host=i386-mingw-cross +# +# After the default has been created, additional rules can be appended +# that will not just recurse into the subdirectories and only ever exist +# in the srcdir toplevel makefile - these parts are read from the $2 = +# Makefile.mk file +# +# The automatic rules are usually scanning the toplevel Makefile for lines +# like '#### $host |$builddir' to recognize the place where to recurse +# into. Usually, the last one is the only one used. However, almost all +# targets have an additional "*-all" rule which makes the script to +# recurse into _all_ variants of the current HOST (!!) setting. The "-all" +# suffix can be overridden for the macro as well. +# +# a special rule is only given for things like "dist" that will copy the +# tarball from the builddir to the sourcedir (or $(PUB)) for reason of +# convenience. +# +# LICENSE +# +# Copyright (c) 2009 Guido U. Draheim +# Copyright (c) 2009 Alan Jenkins +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation; either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. + +#serial 30 + +AC_DEFUN([AX_ENABLE_BUILDDIR],[ +AC_REQUIRE([AC_CANONICAL_HOST])[]dnl +AC_REQUIRE([AC_CANONICAL_TARGET])[]dnl +AC_REQUIRE([AX_CONFIGURE_ARGS])[]dnl +AC_REQUIRE([AM_AUX_DIR_EXPAND])[]dnl +AC_BEFORE([$0],[AM_INIT_AUTOMAKE])dnl +AS_VAR_PUSHDEF([SUB],[ax_enable_builddir])dnl +AS_VAR_PUSHDEF([AUX],[ax_enable_builddir_auxdir])dnl +AS_VAR_PUSHDEF([SED],[ax_enable_builddir_sed])dnl +SUB="." +AC_ARG_ENABLE([builddir], AS_HELP_STRING( + [--disable-builddir],[disable automatic build in subdir of sources]) + ,[SUB="$enableval"], [SUB="auto"]) +if test ".$ac_srcdir_defaulted" != ".no" ; then +if test ".$srcdir" = ".." ; then + if test -f config.status ; then + AC_MSG_NOTICE(toplevel srcdir already configured... skipping subdir build) + else + test ".$SUB" = "." && SUB="." + test ".$SUB" = ".no" && SUB="." + test ".$TARGET" = "." && TARGET="$target" + test ".$SUB" = ".auto" && SUB="m4_ifval([$1], [$1],[$TARGET])" + if test ".$SUB" != ".." ; then # we know where to go and + AS_MKDIR_P([$SUB]) + echo __.$SUB.__ > $SUB/conftest.tmp + cd $SUB + if grep __.$SUB.__ conftest.tmp >/dev/null 2>/dev/null ; then + rm conftest.tmp + AC_MSG_RESULT([continue configure in default builddir "./$SUB"]) + else + AC_MSG_ERROR([could not change to default builddir "./$SUB"]) + fi + srcdir=`echo "$SUB" | + sed -e 's,^\./,,;s,[[^/]]$,&/,;s,[[^/]]*/,../,g;s,[[/]]$,,;'` + # going to restart from subdirectory location + test -f $srcdir/config.log && mv $srcdir/config.log . + test -f $srcdir/confdefs.h && mv $srcdir/confdefs.h . + test -f $srcdir/conftest.log && mv $srcdir/conftest.log . + test -f $srcdir/$cache_file && mv $srcdir/$cache_file . + AC_MSG_RESULT(....exec $SHELL $srcdir/[$]0 "--srcdir=$srcdir" "--enable-builddir=$SUB" ${1+"[$]@"}) + case "[$]0" in # restart + [[\\/]]* | ?:[[\\/]]*) # Absolute name + eval $SHELL "'[$]0'" "'--srcdir=$srcdir'" "'--enable-builddir=$SUB'" $ac_configure_args ;; + *) eval $SHELL "'$srcdir/[$]0'" "'--srcdir=$srcdir'" "'--enable-builddir=$SUB'" $ac_configure_args ;; + esac ; exit $? + fi + fi +fi fi +test ".$SUB" = ".auto" && SUB="." +dnl ac_path_prog uses "set dummy" to override $@ which would defeat the "exec" +AC_PATH_PROG(SED,gsed sed, sed) +AUX="$am_aux_dir" +AS_VAR_POPDEF([SED])dnl +AS_VAR_POPDEF([AUX])dnl +AS_VAR_POPDEF([SUB])dnl +AC_CONFIG_COMMANDS([buildir],[dnl .............. config.status .............. +AS_VAR_PUSHDEF([SUB],[ax_enable_builddir])dnl +AS_VAR_PUSHDEF([TOP],[top_srcdir])dnl +AS_VAR_PUSHDEF([SRC],[ac_top_srcdir])dnl +AS_VAR_PUSHDEF([AUX],[ax_enable_builddir_auxdir])dnl +AS_VAR_PUSHDEF([SED],[ax_enable_builddir_sed])dnl +pushdef([END],[Makefile.mk])dnl +pushdef([_ALL],[ifelse([$3],,[-all],[$3])])dnl + SRC="$ax_enable_builddir_srcdir" + if test ".$SUB" = ".." ; then + if test -f "$TOP/Makefile" ; then + AC_MSG_NOTICE([skipping TOP/Makefile - left untouched]) + else + AC_MSG_NOTICE([skipping TOP/Makefile - not created]) + fi + else + if test -f "$SRC/Makefile" ; then + a=`grep "^VERSION " "$SRC/Makefile"` ; b=`grep "^VERSION " Makefile` + test "$a" != "$b" && rm "$SRC/Makefile" + fi + if test -f "$SRC/Makefile" ; then + echo "$SRC/Makefile : $SRC/Makefile.in" > $tmp/conftemp.mk + echo " []@ echo 'REMOVED,,,' >\$[]@" >> $tmp/conftemp.mk + eval "${MAKE-make} -f $tmp/conftemp.mk 2>/dev/null >/dev/null" + if grep '^REMOVED,,,' "$SRC/Makefile" >/dev/null + then rm $SRC/Makefile ; fi + cp $tmp/conftemp.mk $SRC/makefiles.mk~ ## DEBUGGING + fi + if test ! -f "$SRC/Makefile" ; then + AC_MSG_NOTICE([create TOP/Makefile guessed from local Makefile]) + x='`' ; cat >$tmp/conftemp.sed <<_EOF +/^\$/n +x +/^\$/bS +x +/\\\\\$/{H;d;} +{H;s/.*//;x;} +bM +:S +x +/\\\\\$/{h;d;} +{h;s/.*//;x;} +:M +s/\\(\\n\\) /\\1 /g +/^ /d +/^[[ ]]*[[\\#]]/d +/^VPATH *=/d +s/^srcdir *=.*/srcdir = ./ +s/^top_srcdir *=.*/top_srcdir = ./ +/[[:=]]/!d +/^\\./d +dnl Now handle rules (i.e. lines containing ":" but not " = "). +/ = /b +/ .= /b +/:/!b +s/:.*/:/ +s/ / /g +s/ \\([[a-z]][[a-z-]]*[[a-zA-Z0-9]]\\)\\([[ :]]\\)/ \\1 \\1[]_ALL\\2/g +s/^\\([[a-z]][[a-z-]]*[[a-zA-Z0-9]]\\)\\([[ :]]\\)/\\1 \\1[]_ALL\\2/ +s/ / /g +/^all all[]_ALL[[ :]]/i\\ +all-configured : all[]_ALL +dnl dist-all exists... and would make for dist-all-all +s/ [[a-zA-Z0-9-]]*[]_ALL [[a-zA-Z0-9-]]*[]_ALL[]_ALL//g +/[]_ALL[]_ALL/d +a\\ + @ HOST="\$(HOST)\" \\\\\\ + ; test ".\$\$HOST" = "." && HOST=$x sh $AUX/config.guess $x \\\\\\ + ; BUILD=$x grep "^#### \$\$HOST " Makefile | sed -e 's/.*|//' $x \\\\\\ + ; use=$x basename "\$\@" _ALL $x; n=$x echo \$\$BUILD | wc -w $x \\\\\\ + ; echo "MAKE \$\$HOST : \$\$n * \$\@"; if test "\$\$n" -eq "0" ; then : \\\\\\ + ; BUILD=$x grep "^####.*|" Makefile |tail -1| sed -e 's/.*|//' $x ; fi \\\\\\ + ; test ".\$\$BUILD" = "." && BUILD="." \\\\\\ + ; test "\$\$use" = "\$\@" && BUILD=$x echo "\$\$BUILD" | tail -1 $x \\\\\\ + ; for i in \$\$BUILD ; do test ".\$\$i" = "." && continue \\\\\\ + ; (cd "\$\$i" && test ! -f configure && \$(MAKE) \$\$use) || exit; done +dnl special rule add-on: "dist" copies the tarball to $(PUB). (source tree) +/dist[]_ALL *:/a\\ + @ HOST="\$(HOST)\" \\\\\\ + ; test ".\$\$HOST" = "." && HOST=$x sh $AUX/config.guess $x \\\\\\ + ; BUILD=$x grep "^#### \$\$HOST " Makefile | sed -e 's/.*|//' $x \\\\\\ + ; found=$x echo \$\$BUILD | wc -w $x \\\\\\ + ; echo "MAKE \$\$HOST : \$\$found \$(PACKAGE)-\$(VERSION).tar.*" \\\\\\ + ; if test "\$\$found" -eq "0" ; then : \\\\\\ + ; BUILD=$x grep "^#### .*|" Makefile |tail -1| sed -e 's/.*|//' $x \\\\\\ + ; fi ; for i in \$\$BUILD ; do test ".\$\$i" = "." && continue \\\\\\ + ; for f in \$\$i/\$(PACKAGE)-\$(VERSION).tar.* \\\\\\ + ; do test -f "\$\$f" && mv "\$\$f" \$(PUB). ; done ; break ; done +dnl special rule add-on: "dist-foo" copies all the archives to $(PUB). (source tree) +/dist-[[a-zA-Z0-9]]*[]_ALL *:/a\\ + @ HOST="\$(HOST)\" \\\\\\ + ; test ".\$\$HOST" = "." && HOST=$x sh ./config.guess $x \\\\\\ + ; BUILD=$x grep "^#### \$\$HOST " Makefile | sed -e 's/.*|//' $x \\\\\\ + ; found=$x echo \$\$BUILD | wc -w $x \\\\\\ + ; echo "MAKE \$\$HOST : \$\$found \$(PACKAGE)-\$(VERSION).*" \\\\\\ + ; if test "\$\$found" -eq "0" ; then : \\\\\\ + ; BUILD=$x grep "^#### .*|" Makefile |tail -1| sed -e 's/.*|//' $x \\\\\\ + ; fi ; for i in \$\$BUILD ; do test ".\$\$i" = "." && continue \\\\\\ + ; for f in \$\$i/\$(PACKAGE)-\$(VERSION).* \\\\\\ + ; do test -f "\$\$f" && mv "\$\$f" \$(PUB). ; done ; break ; done +dnl special rule add-on: "distclean" removes all local builddirs completely +/distclean[]_ALL *:/a\\ + @ HOST="\$(HOST)\" \\\\\\ + ; test ".\$\$HOST" = "." && HOST=$x sh $AUX/config.guess $x \\\\\\ + ; BUILD=$x grep "^#### .*|" Makefile | sed -e 's/.*|//' $x \\\\\\ + ; use=$x basename "\$\@" _ALL $x; n=$x echo \$\$BUILD | wc -w $x \\\\\\ + ; echo "MAKE \$\$HOST : \$\$n * \$\@ (all local builds)" \\\\\\ + ; test ".\$\$BUILD" = "." && BUILD="." \\\\\\ + ; for i in \$\$BUILD ; do test ".\$\$i" = "." && continue \\\\\\ + ; echo "# rm -r \$\$i"; done ; echo "# (sleep 3)" ; sleep 3 \\\\\\ + ; for i in \$\$BUILD ; do test ".\$\$i" = "." && continue \\\\\\ + ; echo "\$\$i" | grep "^/" > /dev/null && continue \\\\\\ + ; echo "\$\$i" | grep "^../" > /dev/null && continue \\\\\\ + ; echo "rm -r \$\$i"; (rm -r "\$\$i") ; done ; rm Makefile +_EOF + cp "$tmp/conftemp.sed" "$SRC/makefile.sed~" ## DEBUGGING + $SED -f $tmp/conftemp.sed Makefile >$SRC/Makefile + if test -f "$SRC/m4_ifval([$2],[$2],[END])" ; then + AC_MSG_NOTICE([extend TOP/Makefile with TOP/m4_ifval([$2],[$2],[END])]) + cat $SRC/END >>$SRC/Makefile + fi ; xxxx="####" + echo "$xxxx CONFIGURATIONS FOR TOPLEVEL MAKEFILE: " >>$SRC/Makefile + # sanity check + if grep '^; echo "MAKE ' $SRC/Makefile >/dev/null ; then + AC_MSG_NOTICE([buggy sed found - it deletes tab in "a" text parts]) + $SED -e '/^@ HOST=/s/^/ /' -e '/^; /s/^/ /' $SRC/Makefile \ + >$SRC/Makefile~ + (test -s $SRC/Makefile~ && mv $SRC/Makefile~ $SRC/Makefile) 2>/dev/null + fi + else + xxxx="\\#\\#\\#\\#" + # echo "/^$xxxx *$ax_enable_builddir_host /d" >$tmp/conftemp.sed + echo "s!^$xxxx [[^|]]* | *$SUB *\$!$xxxx ...... $SUB!" >$tmp/conftemp.sed + $SED -f "$tmp/conftemp.sed" "$SRC/Makefile" >$tmp/mkfile.tmp + cp "$tmp/conftemp.sed" "$SRC/makefiles.sed~" ## DEBUGGING + cp "$tmp/mkfile.tmp" "$SRC/makefiles.out~" ## DEBUGGING + if cmp -s "$SRC/Makefile" "$tmp/mkfile.tmp" 2>/dev/null ; then + AC_MSG_NOTICE([keeping TOP/Makefile from earlier configure]) + rm "$tmp/mkfile.tmp" + else + AC_MSG_NOTICE([reusing TOP/Makefile from earlier configure]) + mv "$tmp/mkfile.tmp" "$SRC/Makefile" + fi + fi + AC_MSG_NOTICE([build in $SUB (HOST=$ax_enable_builddir_host)]) + xxxx="####" + echo "$xxxx" "$ax_enable_builddir_host" "|$SUB" >>$SRC/Makefile + fi +popdef([END])dnl +AS_VAR_POPDEF([SED])dnl +AS_VAR_POPDEF([AUX])dnl +AS_VAR_POPDEF([SRC])dnl +AS_VAR_POPDEF([TOP])dnl +AS_VAR_POPDEF([SUB])dnl +],[dnl +ax_enable_builddir_srcdir="$srcdir" # $srcdir +ax_enable_builddir_host="$HOST" # $HOST / $host +ax_enable_builddir_version="$VERSION" # $VERSION +ax_enable_builddir_package="$PACKAGE" # $PACKAGE +ax_enable_builddir_auxdir="$ax_enable_builddir_auxdir" # $AUX +ax_enable_builddir_sed="$ax_enable_builddir_sed" # $SED +ax_enable_builddir="$ax_enable_builddir" # $SUB +])dnl +]) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_gcc_archflag.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_gcc_archflag.m4 new file mode 100644 index 0000000..c52b9b2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_gcc_archflag.m4 @@ -0,0 +1,267 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_gcc_archflag.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_GCC_ARCHFLAG([PORTABLE?], [ACTION-SUCCESS], [ACTION-FAILURE]) +# +# DESCRIPTION +# +# This macro tries to guess the "native" arch corresponding to the target +# architecture for use with gcc's -march=arch or -mtune=arch flags. If +# found, the cache variable $ax_cv_gcc_archflag is set to this flag and +# ACTION-SUCCESS is executed; otherwise $ax_cv_gcc_archflag is set to +# "unknown" and ACTION-FAILURE is executed. The default ACTION-SUCCESS is +# to add $ax_cv_gcc_archflag to the end of $CFLAGS. +# +# PORTABLE? should be either [yes] (default) or [no]. In the former case, +# the flag is set to -mtune (or equivalent) so that the architecture is +# only used for tuning, but the instruction set used is still portable. In +# the latter case, the flag is set to -march (or equivalent) so that +# architecture-specific instructions are enabled. +# +# The user can specify --with-gcc-arch= in order to override the +# macro's choice of architecture, or --without-gcc-arch to disable this. +# +# When cross-compiling, or if $CC is not gcc, then ACTION-FAILURE is +# called unless the user specified --with-gcc-arch manually. +# +# Requires macros: AX_CHECK_COMPILE_FLAG, AX_GCC_X86_CPUID +# +# (The main emphasis here is on recent CPUs, on the principle that doing +# high-performance computing on old hardware is uncommon.) +# +# LICENSE +# +# Copyright (c) 2008 Steven G. Johnson +# Copyright (c) 2008 Matteo Frigo +# Copyright (c) 2014 Tsukasa Oi +# Copyright (c) 2017-2018 Alexey Kopytov +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. + +#serial 22 + +AC_DEFUN([AX_GCC_ARCHFLAG], +[AC_REQUIRE([AC_PROG_CC]) +AC_REQUIRE([AC_CANONICAL_HOST]) +AC_REQUIRE([AC_PROG_SED]) +AC_REQUIRE([AX_COMPILER_VENDOR]) + +AC_ARG_WITH(gcc-arch, [AS_HELP_STRING([--with-gcc-arch=], [use architecture for gcc -march/-mtune, instead of guessing])], + ax_gcc_arch=$withval, ax_gcc_arch=yes) + +AC_MSG_CHECKING([for gcc architecture flag]) +AC_MSG_RESULT([]) +AC_CACHE_VAL(ax_cv_gcc_archflag, +[ +ax_cv_gcc_archflag="unknown" + +if test "$GCC" = yes; then + +if test "x$ax_gcc_arch" = xyes; then +ax_gcc_arch="" +if test "$cross_compiling" = no; then +case $host_cpu in + i[[3456]]86*|x86_64*|amd64*) # use cpuid codes + AX_GCC_X86_CPUID(0) + AX_GCC_X86_CPUID(1) + case $ax_cv_gcc_x86_cpuid_0 in + *:756e6547:6c65746e:49656e69) # Intel + case $ax_cv_gcc_x86_cpuid_1 in + *5[[4578]]?:*:*:*) ax_gcc_arch="pentium-mmx pentium" ;; + *5[[123]]?:*:*:*) ax_gcc_arch=pentium ;; + *0?61?:*:*:*|?61?:*:*:*|61?:*:*:*) ax_gcc_arch=pentiumpro ;; + *0?6[[356]]?:*:*:*|?6[[356]]?:*:*:*|6[[356]]?:*:*:*) ax_gcc_arch="pentium2 pentiumpro" ;; + *0?6[[78ab]]?:*:*:*|?6[[78ab]]?:*:*:*|6[[78ab]]?:*:*:*) ax_gcc_arch="pentium3 pentiumpro" ;; + *0?6[[9d]]?:*:*:*|?6[[9d]]?:*:*:*|6[[9d]]?:*:*:*|*1?65?:*:*:*) ax_gcc_arch="pentium-m pentium3 pentiumpro" ;; + *0?6e?:*:*:*|?6e?:*:*:*|6e?:*:*:*) ax_gcc_arch="yonah pentium-m pentium3 pentiumpro" ;; + *0?6f?:*:*:*|?6f?:*:*:*|6f?:*:*:*|*1?66?:*:*:*) ax_gcc_arch="core2 pentium-m pentium3 pentiumpro" ;; + *1?6[[7d]]?:*:*:*) ax_gcc_arch="penryn core2 pentium-m pentium3 pentiumpro" ;; + *1?6[[aef]]?:*:*:*|*2?6e?:*:*:*) ax_gcc_arch="nehalem corei7 core2 pentium-m pentium3 pentiumpro" ;; + *2?6[[5cf]]?:*:*:*) ax_gcc_arch="westmere corei7 core2 pentium-m pentium3 pentiumpro" ;; + *2?6[[ad]]?:*:*:*) ax_gcc_arch="sandybridge corei7-avx corei7 core2 pentium-m pentium3 pentiumpro" ;; + *3?6[[ae]]?:*:*:*) ax_gcc_arch="ivybridge core-avx-i corei7-avx corei7 core2 pentium-m pentium3 pentiumpro" ;; + *3?6[[cf]]?:*:*:*|*4?6[[56]]?:*:*:*) ax_gcc_arch="haswell core-avx2 core-avx-i corei7-avx corei7 core2 pentium-m pentium3 pentiumpro" ;; + *3?6d?:*:*:*|*4?6[[7f]]?:*:*:*|*5?66?:*:*:*) ax_gcc_arch="broadwell core-avx2 core-avx-i corei7-avx corei7 core2 pentium-m pentium3 pentiumpro" ;; + *1?6c?:*:*:*|*2?6[[67]]?:*:*:*|*3?6[[56]]?:*:*:*) ax_gcc_arch="bonnell atom core2 pentium-m pentium3 pentiumpro" ;; + *3?67?:*:*:*|*[[45]]?6[[ad]]?:*:*:*) ax_gcc_arch="silvermont atom core2 pentium-m pentium3 pentiumpro" ;; + *000?f[[012]]?:*:*:*|?f[[012]]?:*:*:*|f[[012]]?:*:*:*) ax_gcc_arch="pentium4 pentiumpro" ;; + *000?f[[346]]?:*:*:*|?f[[346]]?:*:*:*|f[[346]]?:*:*:*) ax_gcc_arch="nocona prescott pentium4 pentiumpro" ;; + # fallback + *5??:*:*:*) ax_gcc_arch=pentium ;; + *??6??:*:*:*) ax_gcc_arch="core2 pentiumpro" ;; + *6??:*:*:*) ax_gcc_arch=pentiumpro ;; + *00??f??:*:*:*|??f??:*:*:*|?f??:*:*:*|f??:*:*:*) ax_gcc_arch="pentium4 pentiumpro" ;; + esac ;; + *:68747541:444d4163:69746e65) # AMD + case $ax_cv_gcc_x86_cpuid_1 in + *5[[67]]?:*:*:*) ax_gcc_arch=k6 ;; + *5[[8]]?:*:*:*) ax_gcc_arch="k6-2 k6" ;; + *5[[9d]]?:*:*:*) ax_gcc_arch="k6-3 k6" ;; + *6[[12]]?:*:*:*) ax_gcc_arch="athlon k7" ;; + *6[[34]]?:*:*:*) ax_gcc_arch="athlon-tbird k7" ;; + *6[[678a]]?:*:*:*) ax_gcc_arch="athlon-xp athlon-4 athlon k7" ;; + *000?f[[4578bcef]]?:*:*:*|?f[[4578bcef]]?:*:*:*|f[[4578bcef]]?:*:*:*|*001?f[[4578bcf]]?:*:*:*|1?f[[4578bcf]]?:*:*:*) ax_gcc_arch="athlon64 k8" ;; + *002?f[[13457bcf]]?:*:*:*|2?f[[13457bcf]]?:*:*:*|*004?f[[138bcf]]?:*:*:*|4?f[[138bcf]]?:*:*:*|*005?f[[df]]?:*:*:*|5?f[[df]]?:*:*:*|*006?f[[8bcf]]?:*:*:*|6?f[[8bcf]]?:*:*:*|*007?f[[cf]]?:*:*:*|7?f[[cf]]?:*:*:*|*00c?f1?:*:*:*|c?f1?:*:*:*|*020?f3?:*:*:*|20?f3?:*:*:*) ax_gcc_arch="athlon64-sse3 k8-sse3 athlon64 k8" ;; + *010?f[[245689a]]?:*:*:*|10?f[[245689a]]?:*:*:*|*030?f1?:*:*:*|30?f1?:*:*:*) ax_gcc_arch="barcelona amdfam10 k8" ;; + *050?f[[12]]?:*:*:*|50?f[[12]]?:*:*:*) ax_gcc_arch="btver1 amdfam10 k8" ;; + *060?f1?:*:*:*|60?f1?:*:*:*) ax_gcc_arch="bdver1 amdfam10 k8" ;; + *060?f2?:*:*:*|60?f2?:*:*:*|*061?f[[03]]?:*:*:*|61?f[[03]]?:*:*:*) ax_gcc_arch="bdver2 bdver1 amdfam10 k8" ;; + *063?f0?:*:*:*|63?f0?:*:*:*) ax_gcc_arch="bdver3 bdver2 bdver1 amdfam10 k8" ;; + *07[[03]]?f0?:*:*:*|7[[03]]?f0?:*:*:*) ax_gcc_arch="btver2 btver1 amdfam10 k8" ;; + # fallback + *0[[13]]??f??:*:*:*|[[13]]??f??:*:*:*) ax_gcc_arch="barcelona amdfam10 k8" ;; + *020?f??:*:*:*|20?f??:*:*:*) ax_gcc_arch="athlon64-sse3 k8-sse3 athlon64 k8" ;; + *05??f??:*:*:*|5??f??:*:*:*) ax_gcc_arch="btver1 amdfam10 k8" ;; + *060?f??:*:*:*|60?f??:*:*:*) ax_gcc_arch="bdver1 amdfam10 k8" ;; + *061?f??:*:*:*|61?f??:*:*:*) ax_gcc_arch="bdver2 bdver1 amdfam10 k8" ;; + *06??f??:*:*:*|6??f??:*:*:*) ax_gcc_arch="bdver3 bdver2 bdver1 amdfam10 k8" ;; + *070?f??:*:*:*|70?f??:*:*:*) ax_gcc_arch="btver2 btver1 amdfam10 k8" ;; + *???f??:*:*:*) ax_gcc_arch="amdfam10 k8" ;; + esac ;; + *:746e6543:736c7561:48727561) # IDT / VIA (Centaur) + case $ax_cv_gcc_x86_cpuid_1 in + *54?:*:*:*) ax_gcc_arch=winchip-c6 ;; + *5[[89]]?:*:*:*) ax_gcc_arch=winchip2 ;; + *66?:*:*:*) ax_gcc_arch=winchip2 ;; + *6[[78]]?:*:*:*) ax_gcc_arch=c3 ;; + *6[[9adf]]?:*:*:*) ax_gcc_arch="c3-2 c3" ;; + esac ;; + esac + if test x"$ax_gcc_arch" = x; then # fallback + case $host_cpu in + i586*) ax_gcc_arch=pentium ;; + i686*) ax_gcc_arch=pentiumpro ;; + esac + fi + ;; + + sparc*) + AC_PATH_PROG([PRTDIAG], [prtdiag], [prtdiag], [$PATH:/usr/platform/`uname -i`/sbin/:/usr/platform/`uname -m`/sbin/]) + cputype=`(((grep cpu /proc/cpuinfo | cut -d: -f2) ; ($PRTDIAG -v |grep -i sparc) ; grep -i cpu /var/run/dmesg.boot ) | head -n 1) 2> /dev/null` + cputype=`echo "$cputype" | tr -d ' -' | $SED 's/SPARCIIi/SPARCII/' |tr $as_cr_LETTERS $as_cr_letters` + case $cputype in + *ultrasparciv*) ax_gcc_arch="ultrasparc4 ultrasparc3 ultrasparc v9" ;; + *ultrasparciii*) ax_gcc_arch="ultrasparc3 ultrasparc v9" ;; + *ultrasparc*) ax_gcc_arch="ultrasparc v9" ;; + *supersparc*|*tms390z5[[05]]*) ax_gcc_arch="supersparc v8" ;; + *hypersparc*|*rt62[[056]]*) ax_gcc_arch="hypersparc v8" ;; + *cypress*) ax_gcc_arch=cypress ;; + esac ;; + + alphaev5) ax_gcc_arch=ev5 ;; + alphaev56) ax_gcc_arch=ev56 ;; + alphapca56) ax_gcc_arch="pca56 ev56" ;; + alphapca57) ax_gcc_arch="pca57 pca56 ev56" ;; + alphaev6) ax_gcc_arch=ev6 ;; + alphaev67) ax_gcc_arch=ev67 ;; + alphaev68) ax_gcc_arch="ev68 ev67" ;; + alphaev69) ax_gcc_arch="ev69 ev68 ev67" ;; + alphaev7) ax_gcc_arch="ev7 ev69 ev68 ev67" ;; + alphaev79) ax_gcc_arch="ev79 ev7 ev69 ev68 ev67" ;; + + powerpc*) + cputype=`((grep cpu /proc/cpuinfo | head -n 1 | cut -d: -f2 | cut -d, -f1 | $SED 's/ //g') ; /usr/bin/machine ; /bin/machine; grep CPU /var/run/dmesg.boot | head -n 1 | cut -d" " -f2) 2> /dev/null` + cputype=`echo $cputype | $SED -e 's/ppc//g;s/ *//g'` + case $cputype in + *750*) ax_gcc_arch="750 G3" ;; + *740[[0-9]]*) ax_gcc_arch="$cputype 7400 G4" ;; + *74[[4-5]][[0-9]]*) ax_gcc_arch="$cputype 7450 G4" ;; + *74[[0-9]][[0-9]]*) ax_gcc_arch="$cputype G4" ;; + *970*) ax_gcc_arch="970 G5 power4";; + *POWER4*|*power4*|*gq*) ax_gcc_arch="power4 970";; + *POWER5*|*power5*|*gr*|*gs*) ax_gcc_arch="power5 power4 970";; + 603ev|8240) ax_gcc_arch="$cputype 603e 603";; + *POWER7*) ax_gcc_arch="power7";; + *POWER8*) ax_gcc_arch="power8";; + *POWER9*) ax_gcc_arch="power9";; + *POWER10*) ax_gcc_arch="power10";; + *) ax_gcc_arch=$cputype ;; + esac + ax_gcc_arch="$ax_gcc_arch powerpc" + ;; + aarch64) + cpuimpl=`grep 'CPU implementer' /proc/cpuinfo 2> /dev/null | cut -d: -f2 | tr -d " " | head -n 1` + cpuarch=`grep 'CPU architecture' /proc/cpuinfo 2> /dev/null | cut -d: -f2 | tr -d " " | head -n 1` + cpuvar=`grep 'CPU variant' /proc/cpuinfo 2> /dev/null | cut -d: -f2 | tr -d " " | head -n 1` + case $cpuimpl in + 0x42) case $cpuarch in + 8) case $cpuvar in + 0x0) ax_gcc_arch="thunderx2t99 vulcan armv8.1-a armv8-a+lse armv8-a native" ;; + esac + ;; + esac + ;; + 0x43) case $cpuarch in + 8) case $cpuvar in + 0x0) ax_gcc_arch="thunderx armv8-a native" ;; + 0x1) ax_gcc_arch="thunderx+lse armv8.1-a armv8-a+lse armv8-a native" ;; + esac + ;; + esac + ;; + esac + ;; +esac +fi # not cross-compiling +fi # guess arch + +if test "x$ax_gcc_arch" != x -a "x$ax_gcc_arch" != xno; then +if test "x[]m4_default([$1],yes)" = xyes; then # if we require portable code + flag_prefixes="-mtune=" + if test "x$ax_cv_[]_AC_LANG_ABBREV[]_compiler_vendor" = xclang; then flag_prefixes="-march="; fi + # -mcpu=$arch and m$arch generate nonportable code on every arch except + # x86. And some other arches (e.g. Alpha) don't accept -mtune. Grrr. + case $host_cpu in i*86|x86_64*|amd64*) flag_prefixes="$flag_prefixes -mcpu= -m";; esac +else + flag_prefixes="-march= -mcpu= -m" +fi +for flag_prefix in $flag_prefixes; do + for arch in $ax_gcc_arch; do + flag="$flag_prefix$arch" + AX_CHECK_COMPILE_FLAG($flag, [if test "x$ax_cv_[]_AC_LANG_ABBREV[]_compiler_vendor" = xclang; then + if test "x[]m4_default([$1],yes)" = xyes; then + if test "x$flag" = "x-march=$arch"; then flag=-mtune=$arch; fi + fi + fi; ax_cv_gcc_archflag=$flag; break]) + done + test "x$ax_cv_gcc_archflag" = xunknown || break +done +fi + +fi # $GCC=yes +]) +AC_MSG_CHECKING([for gcc architecture flag]) +AC_MSG_RESULT($ax_cv_gcc_archflag) +if test "x$ax_cv_gcc_archflag" = xunknown; then + m4_default([$3],:) +else + m4_default([$2], [CFLAGS="$CFLAGS $ax_cv_gcc_archflag"]) +fi +]) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_gcc_x86_cpuid.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_gcc_x86_cpuid.m4 new file mode 100644 index 0000000..df95465 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_gcc_x86_cpuid.m4 @@ -0,0 +1,89 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_gcc_x86_cpuid.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_GCC_X86_CPUID(OP) +# AX_GCC_X86_CPUID_COUNT(OP, COUNT) +# +# DESCRIPTION +# +# On Pentium and later x86 processors, with gcc or a compiler that has a +# compatible syntax for inline assembly instructions, run a small program +# that executes the cpuid instruction with input OP. This can be used to +# detect the CPU type. AX_GCC_X86_CPUID_COUNT takes an additional COUNT +# parameter that gets passed into register ECX before calling cpuid. +# +# On output, the values of the eax, ebx, ecx, and edx registers are stored +# as hexadecimal strings as "eax:ebx:ecx:edx" in the cache variable +# ax_cv_gcc_x86_cpuid_OP. +# +# If the cpuid instruction fails (because you are running a +# cross-compiler, or because you are not using gcc, or because you are on +# a processor that doesn't have this instruction), ax_cv_gcc_x86_cpuid_OP +# is set to the string "unknown". +# +# This macro mainly exists to be used in AX_GCC_ARCHFLAG. +# +# LICENSE +# +# Copyright (c) 2008 Steven G. Johnson +# Copyright (c) 2008 Matteo Frigo +# Copyright (c) 2015 Michael Petch +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. + +#serial 10 + +AC_DEFUN([AX_GCC_X86_CPUID], +[AX_GCC_X86_CPUID_COUNT($1, 0) +]) + +AC_DEFUN([AX_GCC_X86_CPUID_COUNT], +[AC_REQUIRE([AC_PROG_CC]) +AC_LANG_PUSH([C]) +AC_CACHE_CHECK(for x86 cpuid $1 output, ax_cv_gcc_x86_cpuid_$1, + [AC_RUN_IFELSE([AC_LANG_PROGRAM([#include ], [ + int op = $1, level = $2, eax, ebx, ecx, edx; + FILE *f; + __asm__ __volatile__ ("xchg %%ebx, %1\n" + "cpuid\n" + "xchg %%ebx, %1\n" + : "=a" (eax), "=r" (ebx), "=c" (ecx), "=d" (edx) + : "a" (op), "2" (level)); + + f = fopen("conftest_cpuid", "w"); if (!f) return 1; + fprintf(f, "%x:%x:%x:%x\n", eax, ebx, ecx, edx); + fclose(f); + return 0; +])], + [ax_cv_gcc_x86_cpuid_$1=`cat conftest_cpuid`; rm -f conftest_cpuid], + [ax_cv_gcc_x86_cpuid_$1=unknown; rm -f conftest_cpuid], + [ax_cv_gcc_x86_cpuid_$1=unknown])]) +AC_LANG_POP([C]) +]) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_require_defined.m4 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_require_defined.m4 new file mode 100644 index 0000000..17c3eab --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/m4/ax_require_defined.m4 @@ -0,0 +1,37 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_require_defined.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_REQUIRE_DEFINED(MACRO) +# +# DESCRIPTION +# +# AX_REQUIRE_DEFINED is a simple helper for making sure other macros have +# been defined and thus are available for use. This avoids random issues +# where a macro isn't expanded. Instead the configure script emits a +# non-fatal: +# +# ./configure: line 1673: AX_CFLAGS_WARN_ALL: command not found +# +# It's like AC_REQUIRE except it doesn't expand the required macro. +# +# Here's an example: +# +# AX_REQUIRE_DEFINED([AX_CHECK_LINK_FLAG]) +# +# LICENSE +# +# Copyright (c) 2014 Mike Frysinger +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 2 + +AC_DEFUN([AX_REQUIRE_DEFINED], [dnl + m4_ifndef([$1], [m4_fatal([macro ]$1[ is not defined; is a m4 file missing?])]) +])dnl AX_REQUIRE_DEFINED diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/make_sunver.pl b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/make_sunver.pl new file mode 100644 index 0000000..8a90b1f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/make_sunver.pl @@ -0,0 +1,333 @@ +#!/usr/bin/perl -w + +# make_sunver.pl +# +# This script takes at least two arguments, a GNU style version script and +# a list of object and archive files, and generates a corresponding Sun +# style version script as follows: +# +# Each glob pattern, C++ mangled pattern or literal in the input script is +# matched against all global symbols in the input objects, emitting those +# that matched (or nothing if no match was found). +# A comment with the original pattern and its type is left in the output +# file to make it easy to understand the matches. +# +# It uses elfdump when present (native), GNU readelf otherwise. +# It depends on the GNU version of c++filt, since it must understand the +# GNU mangling style. + +use FileHandle; +use IPC::Open2; + +# Enforce C locale. +$ENV{'LC_ALL'} = "C"; +$ENV{'LANG'} = "C"; + +# Input version script, GNU style. +my $symvers = shift; + +########## +# Get all the symbols from the library, match them, and add them to a hash. + +my %sym_hash = (); + +# List of objects and archives to process. +my @OBJECTS = (); + +# List of shared objects to omit from processing. +my @SHAREDOBJS = (); + +# Filter out those input archives that have corresponding shared objects to +# avoid adding all symbols matched in the archive to the output map. +foreach $file (@ARGV) { + if (($so = $file) =~ s/\.a$/.so/ && -e $so) { + printf STDERR "omitted $file -> $so\n"; + push (@SHAREDOBJS, $so); + } else { + push (@OBJECTS, $file); + } +} + +# We need to detect and ignore hidden symbols. Solaris nm can only detect +# this in the harder to parse default output format, and GNU nm not at all, +# so use elfdump -s in the native case and GNU readelf -s otherwise. +# GNU objdump -t cannot be used since it produces a variable number of +# columns. + +# The path to elfdump. +my $elfdump = "/usr/ccs/bin/elfdump"; + +if (-f $elfdump) { + open ELFDUMP,$elfdump.' -s '.(join ' ',@OBJECTS).'|' or die $!; + my $skip_arsym = 0; + + while () { + chomp; + + # Ignore empty lines. + if (/^$/) { + # End of archive symbol table, stop skipping. + $skip_arsym = 0 if $skip_arsym; + next; + } + + # Keep skipping until end of archive symbol table. + next if ($skip_arsym); + + # Ignore object name header for individual objects and archives. + next if (/:$/); + + # Ignore table header lines. + next if (/^Symbol Table Section:/); + next if (/index.*value.*size/); + + # Start of archive symbol table: start skipping. + if (/^Symbol Table: \(archive/) { + $skip_arsym = 1; + next; + } + + # Split table. + (undef, undef, undef, undef, $bind, $oth, undef, $shndx, $name) = split; + + # Error out for unknown input. + die "unknown input line:\n$_" unless defined($bind); + + # Ignore local symbols. + next if ($bind eq "LOCL"); + # Ignore hidden symbols. + next if ($oth eq "H"); + # Ignore undefined symbols. + next if ($shndx eq "UNDEF"); + # Error out for unhandled cases. + if ($bind !~ /^(GLOB|WEAK)/ or $oth ne "D") { + die "unhandled symbol:\n$_"; + } + + # Remember symbol. + $sym_hash{$name}++; + } + close ELFDUMP or die "$elfdump error"; +} else { + open READELF, 'readelf -s -W '.(join ' ',@OBJECTS).'|' or die $!; + # Process each symbol. + while () { + chomp; + + # Ignore empty lines. + next if (/^$/); + + # Ignore object name header. + next if (/^File: .*$/); + + # Ignore table header lines. + next if (/^Symbol table.*contains.*:/); + next if (/Num:.*Value.*Size/); + + # Split table. + (undef, undef, undef, undef, $bind, $vis, $ndx, $name) = split; + + # Error out for unknown input. + die "unknown input line:\n$_" unless defined($bind); + + # Ignore local symbols. + next if ($bind eq "LOCAL"); + # Ignore hidden symbols. + next if ($vis eq "HIDDEN"); + # Ignore undefined symbols. + next if ($ndx eq "UND"); + # Error out for unhandled cases. + if ($bind !~ /^(GLOBAL|WEAK)/ or $vis ne "DEFAULT") { + die "unhandled symbol:\n$_"; + } + + # Remember symbol. + $sym_hash{$name}++; + } + close READELF or die "readelf error"; +} + +########## +# The various types of glob patterns. +# +# A glob pattern that is to be applied to the demangled name: 'cxx'. +# A glob patterns that applies directly to the name in the .o files: 'glob'. +# This pattern is ignored; used for local variables (usually just '*'): 'ign'. + +# The type of the current pattern. +my $glob = 'glob'; + +# We're currently inside `extern "C++"', which Sun ld doesn't understand. +my $in_extern = 0; + +# The c++filt command to use. This *must* be GNU c++filt; the Sun Studio +# c++filt doesn't handle the GNU mangling style. +my $cxxfilt = $ENV{'CXXFILT'} || "c++filt"; + +# The current version name. +my $current_version = ""; + +# Was there any attempt to match a symbol to this version? +my $matches_attempted; + +# The number of versions which matched this symbol. +my $matched_symbols; + +open F,$symvers or die $!; + +# Print information about generating this file +print "# This file was generated by make_sunver.pl. DO NOT EDIT!\n"; +print "# It was generated by:\n"; +printf "# %s %s %s\n", $0, $symvers, (join ' ',@ARGV); +printf "# Omitted archives with corresponding shared libraries: %s\n", + (join ' ', @SHAREDOBJS) if $#SHAREDOBJS >= 0; +print "#\n\n"; + +while () { + # Lines of the form '};' + if (/^([ \t]*)(\}[ \t]*;[ \t]*)$/) { + $glob = 'glob'; + if ($in_extern) { + $in_extern--; + print "$1##$2\n"; + } else { + print; + } + next; + } + + # Lines of the form '} SOME_VERSION_NAME_1.0;' + if (/^[ \t]*\}[ \tA-Z0-9_.a-z]+;[ \t]*$/) { + $glob = 'glob'; + # We tried to match symbols agains this version, but none matched. + # Emit dummy hidden symbol to avoid marking this version WEAK. + if ($matches_attempted && $matched_symbols == 0) { + print " hidden:\n"; + print " .force_WEAK_off_$current_version = DATA S0x0 V0x0;\n"; + } + print; next; + } + + # Comment and blank lines + if (/^[ \t]*\#/) { print; next; } + if (/^[ \t]*$/) { print; next; } + + # Lines of the form '{' + if (/^([ \t]*){$/) { + if ($in_extern) { + print "$1##{\n"; + } else { + print; + } + next; + } + + # Lines of the form 'SOME_VERSION_NAME_1.1 {' + if (/^([A-Z0-9_.]+)[ \t]+{$/) { + # Record version name. + $current_version = $1; + # Reset match attempts, #matched symbols for this version. + $matches_attempted = 0; + $matched_symbols = 0; + print; + next; + } + + # Ignore 'global:' + if (/^[ \t]*global:$/) { print; next; } + + # After 'local:', globs should be ignored, they won't be exported. + if (/^[ \t]*local:$/) { + $glob = 'ign'; + print; + next; + } + + # After 'extern "C++"', globs are C++ patterns + if (/^([ \t]*)(extern \"C\+\+\"[ \t]*)$/) { + $in_extern++; + $glob = 'cxx'; + # Need to comment, Sun ld cannot handle this. + print "$1##$2\n"; next; + } + + # Chomp newline now we're done with passing through the input file. + chomp; + + # Catch globs. Note that '{}' is not allowed in globs by this script, + # so only '*' and '[]' are available. + if (/^([ \t]*)([^ \t;{}#]+);?[ \t]*$/) { + my $ws = $1; + my $ptn = $2; + # Turn the glob into a regex by replacing '*' with '.*', '?' with '.'. + # Keep $ptn so we can still print the original form. + ($pattern = $ptn) =~ s/\*/\.\*/g; + $pattern =~ s/\?/\./g; + + if ($glob eq 'ign') { + # We're in a local: * section; just continue. + print "$_\n"; + next; + } + + # Print the glob commented for human readers. + print "$ws##$ptn ($glob)\n"; + # We tried to match a symbol to this version. + $matches_attempted++; + + if ($glob eq 'glob') { + my %ptn_syms = (); + + # Match ptn against symbols in %sym_hash. + foreach my $sym (keys %sym_hash) { + # Maybe it matches one of the patterns based on the symbol in + # the .o file. + $ptn_syms{$sym}++ if ($sym =~ /^$pattern$/); + } + + foreach my $sym (sort keys(%ptn_syms)) { + $matched_symbols++; + print "$ws$sym;\n"; + } + } elsif ($glob eq 'cxx') { + my %dem_syms = (); + + # Verify that we're actually using GNU c++filt. Other versions + # most likely cannot handle GNU style symbol mangling. + my $cxxout = `$cxxfilt --version 2>&1`; + $cxxout =~ m/GNU/ or die "$0 requires GNU c++filt to function"; + + # Talk to c++filt through a pair of file descriptors. + # Need to start a fresh instance per pattern, otherwise the + # process grows to 500+ MB. + my $pid = open2(*FILTIN, *FILTOUT, $cxxfilt) or die $!; + + # Match ptn against symbols in %sym_hash. + foreach my $sym (keys %sym_hash) { + # No? Well, maybe its demangled form matches one of those + # patterns. + printf FILTOUT "%s\n",$sym; + my $dem = ; + chomp $dem; + $dem_syms{$sym}++ if ($dem =~ /^$pattern$/); + } + + close FILTOUT or die "c++filt error"; + close FILTIN or die "c++filt error"; + # Need to wait for the c++filt process to avoid lots of zombies. + waitpid $pid, 0; + + foreach my $sym (sort keys(%dem_syms)) { + $matched_symbols++; + print "$ws$sym;\n"; + } + } else { + # No? Well, then ignore it. + } + next; + } + # Important sanity check. This script can't handle lots of formats + # that GNU ld can, so be sure to error out if one is seen! + die "strange line `$_'"; +} +close F; diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/Makefile.am b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/Makefile.am new file mode 100644 index 0000000..afcbfb6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/Makefile.am @@ -0,0 +1,8 @@ +## Process this with automake to create Makefile.in + +AUTOMAKE_OPTIONS=foreign + +EXTRA_DIST = ffi.3 ffi_call.3 ffi_prep_cif.3 ffi_prep_cif_var.3 + +man_MANS = ffi.3 ffi_call.3 ffi_prep_cif.3 ffi_prep_cif_var.3 + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi.3 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi.3 new file mode 100644 index 0000000..1f1d303 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi.3 @@ -0,0 +1,41 @@ +.Dd February 15, 2008 +.Dt FFI 3 +.Sh NAME +.Nm FFI +.Nd Foreign Function Interface +.Sh LIBRARY +libffi, -lffi +.Sh SYNOPSIS +.In ffi.h +.Ft ffi_status +.Fo ffi_prep_cif +.Fa "ffi_cif *cif" +.Fa "ffi_abi abi" +.Fa "unsigned int nargs" +.Fa "ffi_type *rtype" +.Fa "ffi_type **atypes" +.Fc +.Ft void +.Fo ffi_prep_cif_var +.Fa "ffi_cif *cif" +.Fa "ffi_abi abi" +.Fa "unsigned int nfixedargs" +.Fa "unsigned int ntotalargs" +.Fa "ffi_type *rtype" +.Fa "ffi_type **atypes" +.Fc +.Ft void +.Fo ffi_call +.Fa "ffi_cif *cif" +.Fa "void (*fn)(void)" +.Fa "void *rvalue" +.Fa "void **avalue" +.Fc +.Sh DESCRIPTION +The foreign function interface provides a mechanism by which a function can +generate a call to another function at runtime without requiring knowledge of +the called function's interface at compile time. +.Sh SEE ALSO +.Xr ffi_prep_cif 3 , +.Xr ffi_prep_cif_var 3 , +.Xr ffi_call 3 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi_call.3 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi_call.3 new file mode 100644 index 0000000..5351513 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi_call.3 @@ -0,0 +1,103 @@ +.Dd February 15, 2008 +.Dt ffi_call 3 +.Sh NAME +.Nm ffi_call +.Nd Invoke a foreign function. +.Sh SYNOPSIS +.In ffi.h +.Ft void +.Fo ffi_call +.Fa "ffi_cif *cif" +.Fa "void (*fn)(void)" +.Fa "void *rvalue" +.Fa "void **avalue" +.Fc +.Sh DESCRIPTION +The +.Nm ffi_call +function provides a simple mechanism for invoking a function without +requiring knowledge of the function's interface at compile time. +.Fa fn +is called with the values retrieved from the pointers in the +.Fa avalue +array. The return value from +.Fa fn +is placed in storage pointed to by +.Fa rvalue . +.Fa cif +contains information describing the data types, sizes and alignments of the +arguments to and return value from +.Fa fn , +and must be initialized with +.Nm ffi_prep_cif +before it is used with +.Nm ffi_call . +.Pp +.Fa rvalue +must point to storage that is sizeof(ffi_arg) or larger for non-floating point +types. For smaller-sized return value types, the +.Nm ffi_arg +or +.Nm ffi_sarg +integral type must be used to hold +the return value. +.Sh EXAMPLES +.Bd -literal +#include +#include + +unsigned char +foo(unsigned int, float); + +int +main(int argc, const char **argv) +{ + ffi_cif cif; + ffi_type *arg_types[2]; + void *arg_values[2]; + ffi_status status; + + // Because the return value from foo() is smaller than sizeof(long), it + // must be passed as ffi_arg or ffi_sarg. + ffi_arg result; + + // Specify the data type of each argument. Available types are defined + // in . + arg_types[0] = &ffi_type_uint; + arg_types[1] = &ffi_type_float; + + // Prepare the ffi_cif structure. + if ((status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, + 2, &ffi_type_uint8, arg_types)) != FFI_OK) + { + // Handle the ffi_status error. + } + + // Specify the values of each argument. + unsigned int arg1 = 42; + float arg2 = 5.1; + + arg_values[0] = &arg1; + arg_values[1] = &arg2; + + // Invoke the function. + ffi_call(&cif, FFI_FN(foo), &result, arg_values); + + // The ffi_arg 'result' now contains the unsigned char returned from foo(), + // which can be accessed by a typecast. + printf("result is %hhu", (unsigned char)result); + + return 0; +} + +// The target function. +unsigned char +foo(unsigned int x, float y) +{ + unsigned char result = x - y; + return result; +} +.Ed +.Sh SEE ALSO +.Xr ffi 3 , +.Xr ffi_prep_cif 3 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi_prep_cif.3 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi_prep_cif.3 new file mode 100644 index 0000000..ab2be8a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi_prep_cif.3 @@ -0,0 +1,68 @@ +.Dd February 15, 2008 +.Dt ffi_prep_cif 3 +.Sh NAME +.Nm ffi_prep_cif +.Nd Prepare a +.Nm ffi_cif +structure for use with +.Nm ffi_call +. +.Sh SYNOPSIS +.In ffi.h +.Ft ffi_status +.Fo ffi_prep_cif +.Fa "ffi_cif *cif" +.Fa "ffi_abi abi" +.Fa "unsigned int nargs" +.Fa "ffi_type *rtype" +.Fa "ffi_type **atypes" +.Fc +.Sh DESCRIPTION +The +.Nm ffi_prep_cif +function prepares a +.Nm ffi_cif +structure for use with +.Nm ffi_call +. +.Fa abi +specifies a set of calling conventions to use. +.Fa atypes +is an array of +.Fa nargs +pointers to +.Nm ffi_type +structs that describe the data type, size and alignment of each argument. +.Fa rtype +points to an +.Nm ffi_type +that describes the data type, size and alignment of the +return value. Note that to call a variadic function +.Nm ffi_prep_cif_var +must be used instead. +.Sh RETURN VALUES +Upon successful completion, +.Nm ffi_prep_cif +returns +.Nm FFI_OK . +It will return +.Nm FFI_BAD_TYPEDEF +if +.Fa cif +is +.Nm NULL +or +.Fa atypes +or +.Fa rtype +is malformed. If +.Fa abi +does not refer to a valid ABI, +.Nm FFI_BAD_ABI +will be returned. Available ABIs are +defined in +.Nm . +.Sh SEE ALSO +.Xr ffi 3 , +.Xr ffi_call 3 , +.Xr ffi_prep_cif_var 3 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi_prep_cif_var.3 b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi_prep_cif_var.3 new file mode 100644 index 0000000..7e19d0b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/man/ffi_prep_cif_var.3 @@ -0,0 +1,73 @@ +.Dd January 25, 2011 +.Dt ffi_prep_cif_var 3 +.Sh NAME +.Nm ffi_prep_cif_var +.Nd Prepare a +.Nm ffi_cif +structure for use with +.Nm ffi_call +for variadic functions. +.Sh SYNOPSIS +.In ffi.h +.Ft ffi_status +.Fo ffi_prep_cif_var +.Fa "ffi_cif *cif" +.Fa "ffi_abi abi" +.Fa "unsigned int nfixedargs" +.Fa "unsigned int ntotalargs" +.Fa "ffi_type *rtype" +.Fa "ffi_type **atypes" +.Fc +.Sh DESCRIPTION +The +.Nm ffi_prep_cif_var +function prepares a +.Nm ffi_cif +structure for use with +.Nm ffi_call +for variadic functions. +.Fa abi +specifies a set of calling conventions to use. +.Fa atypes +is an array of +.Fa ntotalargs +pointers to +.Nm ffi_type +structs that describe the data type, size and alignment of each argument. +.Fa rtype +points to an +.Nm ffi_type +that describes the data type, size and alignment of the +return value. +.Fa nfixedargs +must contain the number of fixed (non-variadic) arguments. +Note that to call a non-variadic function +.Nm ffi_prep_cif +must be used. +.Sh RETURN VALUES +Upon successful completion, +.Nm ffi_prep_cif_var +returns +.Nm FFI_OK . +It will return +.Nm FFI_BAD_TYPEDEF +if +.Fa cif +is +.Nm NULL +or +.Fa atypes +or +.Fa rtype +is malformed. If +.Fa abi +does not refer to a valid ABI, +.Nm FFI_BAD_ABI +will be returned. Available ABIs are +defined in +.Nm +. +.Sh SEE ALSO +.Xr ffi 3 , +.Xr ffi_call 3 , +.Xr ffi_prep_cif 3 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.sln b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.sln new file mode 100644 index 0000000..d9119df --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.sln @@ -0,0 +1,33 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28302.56 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Ffi_staticLib_arm64", "Ffi_staticLib.vcxproj", "{115502C0-BE05-4767-BF19-5C87D805FAD6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {115502C0-BE05-4767-BF19-5C87D805FAD6}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {115502C0-BE05-4767-BF19-5C87D805FAD6}.Debug|ARM64.Build.0 = Debug|ARM64 + {115502C0-BE05-4767-BF19-5C87D805FAD6}.Debug|x64.ActiveCfg = Debug|ARM64 + {115502C0-BE05-4767-BF19-5C87D805FAD6}.Debug|x86.ActiveCfg = Debug|ARM64 + {115502C0-BE05-4767-BF19-5C87D805FAD6}.Release|ARM64.ActiveCfg = Release|ARM64 + {115502C0-BE05-4767-BF19-5C87D805FAD6}.Release|ARM64.Build.0 = Release|ARM64 + {115502C0-BE05-4767-BF19-5C87D805FAD6}.Release|x64.ActiveCfg = Release|ARM64 + {115502C0-BE05-4767-BF19-5C87D805FAD6}.Release|x86.ActiveCfg = Release|ARM64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {241C54C7-20DD-4897-9376-E6B6D1B43BD5} + EndGlobalSection +EndGlobal diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.vcxproj b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.vcxproj new file mode 100644 index 0000000..3187699 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.vcxproj @@ -0,0 +1,130 @@ + + + + + Debug + ARM64 + + + Release + ARM64 + + + + 15.0 + {115502C0-BE05-4767-BF19-5C87D805FAD6} + Win32Proj + FfistaticLib + 10.0.17763.0 + Ffi_staticLib_arm64 + + + + StaticLibrary + true + v141 + Unicode + + + StaticLibrary + false + v141 + true + Unicode + + + + + + + + + + + + + + + true + + + false + + + + NotUsing + Level3 + Disabled + true + FFI_BUILDING_DLL;_DEBUG;_LIB;USE_DL_PREFIX;ARM64;_M_ARM64;NDEBUG;%(PreprocessorDefinitions) + true + ..\..\include;.\aarch64_include;..\..\src\aarch64;%(AdditionalIncludeDirectories) + false + true + + + false + + + Windows + true + + + + + NotUsing + Level3 + MaxSpeed + true + true + true + FFI_BUILDING_DLL;USE_DL_PREFIX;ARM64;NDEBUG;_LIB;%(PreprocessorDefinitions) + true + ..\..\include;.\aarch64_include;..\..\src\aarch64;%(AdditionalIncludeDirectories) + true + Speed + true + ..\..\src;..\..\src\aarch64;%(AdditionalUsingDirectories) + + + Windows + true + true + true + + + true + + + + + + + + + + + + + + + + + + + + + + + cl /FA /EP /nologo /I"..\..\include" /I".\aarch64_include" /I"..\..\src\aarch64" "%(FullPath)" > $(IntDir)win64_armasm.i + armasm64 $(IntDir)win64_armasm.i /I"src\" /I"..\..\include" /I"..\..\src\aarch64" -o "$(IntDir)win64_armasm.obj" + + win64_armasm.obj;%(Outputs) + + + + + + \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.vcxproj.filters b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.vcxproj.filters new file mode 100644 index 0000000..1f8c6e1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.vcxproj.filters @@ -0,0 +1,57 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + + \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.vcxproj.user b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.vcxproj.user new file mode 100644 index 0000000..be25078 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/Ffi_staticLib.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/aarch64_include/ffi.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/aarch64_include/ffi.h new file mode 100644 index 0000000..02f26a2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvc_build/aarch64/aarch64_include/ffi.h @@ -0,0 +1,511 @@ +/* -----------------------------------------------------------------*-C-*- + libffi 3.3-rc0 - Copyright (c) 2011, 2014 Anthony Green + - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the ``Software''), to deal in the Software without + restriction, including without limitation the rights to use, copy, + modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +/* ------------------------------------------------------------------- + Most of the API is documented in doc/libffi.texi. + + The raw API is designed to bypass some of the argument packing and + unpacking on architectures for which it can be avoided. Routines + are provided to emulate the raw API if the underlying platform + doesn't allow faster implementation. + + More details on the raw API can be found in: + + http://gcc.gnu.org/ml/java/1999-q3/msg00138.html + + and + + http://gcc.gnu.org/ml/java/1999-q3/msg00174.html + -------------------------------------------------------------------- */ + +#ifndef LIBFFI_H +#define LIBFFI_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Specify which architecture libffi is configured for. */ +#ifndef AARCH64 +#define AARCH64 +#endif + +/* ---- System configuration information --------------------------------- */ + +#include + +#ifndef LIBFFI_ASM + +#if defined(_MSC_VER) && !defined(__clang__) +#define __attribute__(X) +#endif + +#include +#include + +/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example). + But we can find it either under the correct ANSI name, or under GNU + C's internal name. */ + +#define FFI_64_BIT_MAX 9223372036854775807 + +#ifdef LONG_LONG_MAX +# define FFI_LONG_LONG_MAX LONG_LONG_MAX +#else +# ifdef LLONG_MAX +# define FFI_LONG_LONG_MAX LLONG_MAX +# ifdef _AIX52 /* or newer has C99 LLONG_MAX */ +# undef FFI_64_BIT_MAX +# define FFI_64_BIT_MAX 9223372036854775807LL +# endif /* _AIX52 or newer */ +# else +# ifdef __GNUC__ +# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__ +# endif +# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */ +# ifndef __PPC64__ +# if defined (__IBMC__) || defined (__IBMCPP__) +# define FFI_LONG_LONG_MAX LONGLONG_MAX +# endif +# endif /* __PPC64__ */ +# undef FFI_64_BIT_MAX +# define FFI_64_BIT_MAX 9223372036854775807LL +# endif +# endif +#endif + +/* The closure code assumes that this works on pointers, i.e. a size_t + can hold a pointer. */ + +typedef struct _ffi_type +{ + size_t size; + unsigned short alignment; + unsigned short type; + struct _ffi_type **elements; +} ffi_type; + +/* Need minimal decorations for DLLs to work on Windows. GCC has + autoimport and autoexport. Always mark externally visible symbols + as dllimport for MSVC clients, even if it means an extra indirection + when using the static version of the library. + Besides, as a workaround, they can define FFI_BUILDING if they + *know* they are going to link with the static library. */ +#if defined _MSC_VER +# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */ +# define FFI_API __declspec(dllexport) +# elif !defined FFI_BUILDING /* Importing libffi.DLL */ +# define FFI_API __declspec(dllimport) +# else /* Building/linking static library */ +# define FFI_API +# endif +#else +# define FFI_API +#endif + +/* The externally visible type declarations also need the MSVC DLL + decorations, or they will not be exported from the object file. */ +#if defined LIBFFI_HIDE_BASIC_TYPES +# define FFI_EXTERN FFI_API +#else +# define FFI_EXTERN extern FFI_API +#endif + +#ifndef LIBFFI_HIDE_BASIC_TYPES +#if SCHAR_MAX == 127 +# define ffi_type_uchar ffi_type_uint8 +# define ffi_type_schar ffi_type_sint8 +#else + #error "char size not supported" +#endif + +#if SHRT_MAX == 32767 +# define ffi_type_ushort ffi_type_uint16 +# define ffi_type_sshort ffi_type_sint16 +#elif SHRT_MAX == 2147483647 +# define ffi_type_ushort ffi_type_uint32 +# define ffi_type_sshort ffi_type_sint32 +#else + #error "short size not supported" +#endif + +#if INT_MAX == 32767 +# define ffi_type_uint ffi_type_uint16 +# define ffi_type_sint ffi_type_sint16 +#elif INT_MAX == 2147483647 +# define ffi_type_uint ffi_type_uint32 +# define ffi_type_sint ffi_type_sint32 +#elif INT_MAX == 9223372036854775807 +# define ffi_type_uint ffi_type_uint64 +# define ffi_type_sint ffi_type_sint64 +#else + #error "int size not supported" +#endif + +#if LONG_MAX == 2147483647 +# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX + #error "no 64-bit data type supported" +# endif +#elif LONG_MAX != FFI_64_BIT_MAX + #error "long size not supported" +#endif + +#if LONG_MAX == 2147483647 +# define ffi_type_ulong ffi_type_uint32 +# define ffi_type_slong ffi_type_sint32 +#elif LONG_MAX == FFI_64_BIT_MAX +# define ffi_type_ulong ffi_type_uint64 +# define ffi_type_slong ffi_type_sint64 +#else + #error "long size not supported" +#endif + +/* These are defined in types.c. */ +FFI_EXTERN ffi_type ffi_type_void; +FFI_EXTERN ffi_type ffi_type_uint8; +FFI_EXTERN ffi_type ffi_type_sint8; +FFI_EXTERN ffi_type ffi_type_uint16; +FFI_EXTERN ffi_type ffi_type_sint16; +FFI_EXTERN ffi_type ffi_type_uint32; +FFI_EXTERN ffi_type ffi_type_sint32; +FFI_EXTERN ffi_type ffi_type_uint64; +FFI_EXTERN ffi_type ffi_type_sint64; +FFI_EXTERN ffi_type ffi_type_float; +FFI_EXTERN ffi_type ffi_type_double; +FFI_EXTERN ffi_type ffi_type_pointer; + +#ifndef _M_ARM64 +FFI_EXTERN ffi_type ffi_type_longdouble; +#else +#define ffi_type_longdouble ffi_type_double +#endif + +#ifdef FFI_TARGET_HAS_COMPLEX_TYPE +FFI_EXTERN ffi_type ffi_type_complex_float; +FFI_EXTERN ffi_type ffi_type_complex_double; +#if 1 +FFI_EXTERN ffi_type ffi_type_complex_longdouble; +#else +#define ffi_type_complex_longdouble ffi_type_complex_double +#endif +#endif +#endif /* LIBFFI_HIDE_BASIC_TYPES */ + +typedef enum { + FFI_OK = 0, + FFI_BAD_TYPEDEF, + FFI_BAD_ABI +} ffi_status; + +typedef struct { + ffi_abi abi; + unsigned nargs; + ffi_type **arg_types; + ffi_type *rtype; + unsigned bytes; + unsigned flags; +#ifdef FFI_EXTRA_CIF_FIELDS + FFI_EXTRA_CIF_FIELDS; +#endif +} ffi_cif; + +/* ---- Definitions for the raw API -------------------------------------- */ + +#ifndef FFI_SIZEOF_ARG +# if LONG_MAX == 2147483647 +# define FFI_SIZEOF_ARG 4 +# elif LONG_MAX == FFI_64_BIT_MAX +# define FFI_SIZEOF_ARG 8 +# endif +#endif + +#ifndef FFI_SIZEOF_JAVA_RAW +# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG +#endif + +typedef union { + ffi_sarg sint; + ffi_arg uint; + float flt; + char data[FFI_SIZEOF_ARG]; + void* ptr; +} ffi_raw; + +#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8 +/* This is a special case for mips64/n32 ABI (and perhaps others) where + sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */ +typedef union { + signed int sint; + unsigned int uint; + float flt; + char data[FFI_SIZEOF_JAVA_RAW]; + void* ptr; +} ffi_java_raw; +#else +typedef ffi_raw ffi_java_raw; +#endif + + +FFI_API +void ffi_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_raw *avalue); + +FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); +FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); +FFI_API size_t ffi_raw_size (ffi_cif *cif); + +/* This is analogous to the raw API, except it uses Java parameter + packing, even on 64-bit machines. I.e. on 64-bit machines longs + and doubles are followed by an empty 64-bit word. */ + +FFI_API +void ffi_java_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_java_raw *avalue); + +FFI_API +void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw); +FFI_API +void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args); +FFI_API +size_t ffi_java_raw_size (ffi_cif *cif); + +/* ---- Definitions for closures ----------------------------------------- */ + +#if FFI_CLOSURES + +#ifdef _MSC_VER +__declspec(align(8)) +#endif +typedef struct { +#if 0 + void *trampoline_table; + void *trampoline_table_entry; +#else + char tramp[FFI_TRAMPOLINE_SIZE]; +#endif + ffi_cif *cif; + void (*fun)(ffi_cif*,void*,void**,void*); + void *user_data; +} ffi_closure +#ifdef __GNUC__ + __attribute__((aligned (8))) +#endif + ; + +#ifndef __GNUC__ +# ifdef __sgi +# pragma pack 0 +# endif +#endif + +FFI_API void *ffi_closure_alloc (size_t size, void **code); +FFI_API void ffi_closure_free (void *); + +FFI_API ffi_status +ffi_prep_closure (ffi_closure*, + ffi_cif *, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data) +#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405) + __attribute__((deprecated ("use ffi_prep_closure_loc instead"))) +#elif defined(__GNUC__) && __GNUC__ >= 3 + __attribute__((deprecated)) +#endif + ; + +FFI_API ffi_status +ffi_prep_closure_loc (ffi_closure*, + ffi_cif *, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void*codeloc); + +#ifdef __sgi +# pragma pack 8 +#endif +typedef struct { +#if 0 + void *trampoline_table; + void *trampoline_table_entry; +#else + char tramp[FFI_TRAMPOLINE_SIZE]; +#endif + ffi_cif *cif; + +#if !FFI_NATIVE_RAW_API + + /* If this is enabled, then a raw closure has the same layout + as a regular closure. We use this to install an intermediate + handler to do the transaltion, void** -> ffi_raw*. */ + + void (*translate_args)(ffi_cif*,void*,void**,void*); + void *this_closure; + +#endif + + void (*fun)(ffi_cif*,void*,ffi_raw*,void*); + void *user_data; + +} ffi_raw_closure; + +typedef struct { +#if 0 + void *trampoline_table; + void *trampoline_table_entry; +#else + char tramp[FFI_TRAMPOLINE_SIZE]; +#endif + + ffi_cif *cif; + +#if !FFI_NATIVE_RAW_API + + /* If this is enabled, then a raw closure has the same layout + as a regular closure. We use this to install an intermediate + handler to do the translation, void** -> ffi_raw*. */ + + void (*translate_args)(ffi_cif*,void*,void**,void*); + void *this_closure; + +#endif + + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*); + void *user_data; + +} ffi_java_raw_closure; + +FFI_API ffi_status +ffi_prep_raw_closure (ffi_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data); + +FFI_API ffi_status +ffi_prep_raw_closure_loc (ffi_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data, + void *codeloc); + +FFI_API ffi_status +ffi_prep_java_raw_closure (ffi_java_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), + void *user_data); + +FFI_API ffi_status +ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), + void *user_data, + void *codeloc); + +#endif /* FFI_CLOSURES */ + +#if FFI_GO_CLOSURES + +typedef struct { + void *tramp; + ffi_cif *cif; + void (*fun)(ffi_cif*,void*,void**,void*); +} ffi_go_closure; + +FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *, + void (*fun)(ffi_cif*,void*,void**,void*)); + +FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure); + +#endif /* FFI_GO_CLOSURES */ + +/* ---- Public interface definition -------------------------------------- */ + +FFI_API +ffi_status ffi_prep_cif(ffi_cif *cif, + ffi_abi abi, + unsigned int nargs, + ffi_type *rtype, + ffi_type **atypes); + +FFI_API +ffi_status ffi_prep_cif_var(ffi_cif *cif, + ffi_abi abi, + unsigned int nfixedargs, + unsigned int ntotalargs, + ffi_type *rtype, + ffi_type **atypes); + +FFI_API +void ffi_call(ffi_cif *cif, + void (*fn)(void), + void *rvalue, + void **avalue); + +FFI_API +ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type, + size_t *offsets); + +/* Useful for eliminating compiler warnings. */ +#define FFI_FN(f) ((void (*)(void))f) + +/* ---- Definitions shared with assembly code ---------------------------- */ + +#endif + +/* If these change, update src/mips/ffitarget.h. */ +#define FFI_TYPE_VOID 0 +#define FFI_TYPE_INT 1 +#define FFI_TYPE_FLOAT 2 +#define FFI_TYPE_DOUBLE 3 +#ifndef _M_ARM64 +#define FFI_TYPE_LONGDOUBLE 4 +#else +#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE +#endif +#define FFI_TYPE_UINT8 5 +#define FFI_TYPE_SINT8 6 +#define FFI_TYPE_UINT16 7 +#define FFI_TYPE_SINT16 8 +#define FFI_TYPE_UINT32 9 +#define FFI_TYPE_SINT32 10 +#define FFI_TYPE_UINT64 11 +#define FFI_TYPE_SINT64 12 +#define FFI_TYPE_STRUCT 13 +#define FFI_TYPE_POINTER 14 +#define FFI_TYPE_COMPLEX 15 +/* This should always refer to the last type code (for sanity checks). */ +#define FFI_TYPE_LAST FFI_TYPE_COMPLEX + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvcc.sh b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvcc.sh new file mode 100755 index 0000000..7cfc509 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/msvcc.sh @@ -0,0 +1,353 @@ +#!/bin/sh + +# ***** BEGIN LICENSE BLOCK ***** +# Version: MPL 1.1/GPL 2.0/LGPL 2.1 +# +# The contents of this file are subject to the Mozilla Public License Version +# 1.1 (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# http://www.mozilla.org/MPL/ +# +# Software distributed under the License is distributed on an "AS IS" basis, +# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License +# for the specific language governing rights and limitations under the +# License. +# +# The Original Code is the MSVC wrappificator. +# +# The Initial Developer of the Original Code is +# Timothy Wall . +# Portions created by the Initial Developer are Copyright (C) 2009 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Daniel Witte +# +# Alternatively, the contents of this file may be used under the terms of +# either the GNU General Public License Version 2 or later (the "GPL"), or +# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +# in which case the provisions of the GPL or the LGPL are applicable instead +# of those above. If you wish to allow use of your version of this file only +# under the terms of either the GPL or the LGPL, and not to allow others to +# use your version of this file under the terms of the MPL, indicate your +# decision by deleting the provisions above and replace them with the notice +# and other provisions required by the GPL or the LGPL. If you do not delete +# the provisions above, a recipient may use your version of this file under +# the terms of any one of the MPL, the GPL or the LGPL. +# +# ***** END LICENSE BLOCK ***** + +# +# GCC-compatible wrapper for cl.exe and ml.exe. Arguments are given in GCC +# format and translated into something sensible for cl or ml. +# + +args_orig=$@ +args="-nologo -W3" +linkargs= +static_crt= +debug_crt= +cl="cl" +ml="ml" +safeseh="-safeseh" +output= +libpaths= +libversion=7 +verbose= + +while [ $# -gt 0 ] +do + case $1 + in + --verbose) + verbose=1 + shift 1 + ;; + --version) + args="-help" + shift 1 + ;; + -fexceptions) + # Don't enable exceptions for now. + #args="$args -EHac" + shift 1 + ;; + -m32) + shift 1 + ;; + -m64) + ml="ml64" # "$MSVC/x86_amd64/ml64" + safeseh= + shift 1 + ;; + -marm) + ml='armasm' + safeseh= + shift 1 + ;; + -marm64) + ml='armasm64' + safeseh= + shift 1 + ;; + -clang-cl) + cl="clang-cl" + shift 1 + ;; + -O0) + args="$args -Od" + shift 1 + ;; + -O*) + # Runtime error checks (enabled by setting -RTC1 in the -DFFI_DEBUG + # case below) are not compatible with optimization flags and will + # cause the build to fail. Therefore, drop the optimization flag if + # -DFFI_DEBUG is also set. + case $args_orig in + *-DFFI_DEBUG*) + args="$args" + ;; + *) + # The ax_cc_maxopt.m4 macro from the upstream autoconf-archive + # project doesn't support MSVC and therefore ends up trying to + # use -O3. Use the equivalent "max optimization" flag for MSVC + # instead of erroring out. + case $1 in + -O3) + args="$args -O2" + ;; + *) + args="$args $1" + ;; + esac + opt="true" + ;; + esac + shift 1 + ;; + -g) + # Enable debug symbol generation. + args="$args -Zi" + shift 1 + ;; + -DFFI_DEBUG) + # Enable runtime error checks. + args="$args -RTC1" + defines="$defines $1" + shift 1 + ;; + -DUSE_STATIC_RTL) + # Link against static CRT. + static_crt=1 + shift 1 + ;; + -DUSE_DEBUG_RTL) + # Link against debug CRT. + debug_crt=1 + shift 1 + ;; + -c) + args="$args -c" + args="$(echo $args | sed 's%/Fe%/Fo%g')" + single="-c" + shift 1 + ;; + -D*=*) + name="$(echo $1|sed 's/-D\([^=][^=]*\)=.*/\1/g')" + value="$(echo $1|sed 's/-D[^=][^=]*=//g')" + args="$args -D${name}='$value'" + defines="$defines -D${name}='$value'" + shift 1 + ;; + -D*) + args="$args $1" + defines="$defines $1" + shift 1 + ;; + -I) + p=$(cygpath -ma "$2") + args="$args -I\"$p\"" + includes="$includes -I\"$p\"" + shift 2 + ;; + -I*) + p=$(cygpath -ma "${1#-I}") + args="$args -I\"$p\"" + includes="$includes -I\"$p\"" + shift 1 + ;; + -L) + p=$(cygpath -ma $2) + linkargs="$linkargs -LIBPATH:$p" + shift 2 + ;; + -L*) + p=$(cygpath -ma ${1#-L}) + linkargs="$linkargs -LIBPATH:$p" + shift 1 + ;; + -link) + # add next argument verbatim to linker args + linkargs="$linkargs $2" + shift 2 + ;; + -l*) + case $1 + in + -lffi) + linkargs="$linkargs lib${1#-l}-${libversion}.lib" + ;; + *) + # ignore other libraries like -lm, hope they are + # covered by MSVCRT + # linkargs="$linkargs ${1#-l}.lib" + ;; + esac + shift 1 + ;; + -W|-Wextra) + # TODO map extra warnings + shift 1 + ;; + -Wall) + # -Wall on MSVC is overzealous, and we already build with -W3. Nothing + # to do here. + shift 1 + ;; + -pedantic) + # libffi tests -pedantic with -Wall, so drop it also. + shift 1 + ;; + -warn) + # ignore -warn all from libtool as well. + if test "$2" = "all"; then + shift 2 + else + args="$args -warn" + shift 1 + fi + ;; + -Werror) + args="$args -WX" + shift 1 + ;; + -W*) + # TODO map specific warnings + shift 1 + ;; + -S) + args="$args -FAs" + shift 1 + ;; + -o) + outdir="$(dirname $2)" + base="$(basename $2|sed 's/\.[^.]*//g')" + if [ -n "$single" ]; then + output="-Fo$2" + else + output="-Fe$2" + fi + armasm_output="-o $2" + if [ -n "$assembly" ]; then + args="$args $output" + else + args="$args $output -Fd$outdir/$base -Fp$outdir/$base -Fa$outdir/$base" + fi + shift 2 + ;; + *.S) + src="$(cygpath -ma $1)" + assembly="true" + shift 1 + ;; + *.c) + args="$args $(cygpath -ma $1)" + shift 1 + ;; + *) + # Assume it's an MSVC argument, and pass it through. + args="$args $1" + shift 1 + ;; + esac +done + +if [ -n "$linkargs" ]; then + + # If -Zi is specified, certain optimizations are implicitly disabled + # by MSVC. Add back those optimizations if this is an optimized build. + # NOTE: These arguments must come after all others. + if [ -n "$opt" ]; then + linkargs="$linkargs -OPT:REF -OPT:ICF -INCREMENTAL:NO" + fi + + args="$args -link $linkargs" +fi + +if [ -n "$static_crt" ]; then + md=-MT +else + md=-MD +fi + +if [ -n "$debug_crt" ]; then + md="${md}d" +fi + +if [ -n "$assembly" ]; then + if [ -z "$outdir" ]; then + outdir="." + fi + ppsrc="$outdir/$(basename $src|sed 's/.S$/.asm/g')" + + if [ $ml = "armasm" ]; then + defines="$defines -D_M_ARM" + fi + + if [ $ml = "armasm64" ]; then + defines="$defines -D_M_ARM64" + fi + + if test -n "$verbose"; then + echo "$cl -nologo -EP $includes $defines $src > $ppsrc" + fi + + eval "\"$cl\" -nologo -EP $includes $defines $src" > $ppsrc || exit $? + output="$(echo $output | sed 's%/F[dpa][^ ]*%%g')" + if [ $ml = "armasm" ]; then + args="-nologo -g -oldit $armasm_output $ppsrc -errorReport:prompt" + elif [ $ml = "armasm64" ]; then + args="-nologo -g $armasm_output $ppsrc -errorReport:prompt" + else + args="-nologo $safeseh $single $output $ppsrc" + fi + + if test -n "$verbose"; then + echo "$ml $args" + fi + + eval "\"$ml\" $args" + result=$? + + # required to fix ml64 broken output? + #mv *.obj $outdir +else + args="$md $args" + + if test -n "$verbose"; then + echo "$cl $args" + fi + # Return an error code of 1 if an invalid command line parameter is passed + # instead of just ignoring it. Any output that is not a warning or an + # error is filtered so this command behaves more like gcc. cl.exe prints + # the name of the compiled file otherwise, which breaks the dejagnu checks + # for excess warnings and errors. + eval "(\"$cl\" $args 2>&1 1>&3 | \ + awk '{print \$0} /D9002/ {error=1} END{exit error}' >&2) 3>&1 | \ + awk '/warning|error/'" + result=$? +fi + +exit $result + +# vim: noai:ts=4:sw=4 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/ffi.c new file mode 100644 index 0000000..ef09f4d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/ffi.c @@ -0,0 +1,1025 @@ +/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + +#if defined(__aarch64__) || defined(__arm64__)|| defined (_M_ARM64) +#include +#include +#include +#include +#include +#include +#include "internal.h" +#ifdef _WIN32 +#include /* FlushInstructionCache */ +#endif + +/* Force FFI_TYPE_LONGDOUBLE to be different than FFI_TYPE_DOUBLE; + all further uses in this file will refer to the 128-bit type. */ +#if FFI_TYPE_DOUBLE != FFI_TYPE_LONGDOUBLE +# if FFI_TYPE_LONGDOUBLE != 4 +# error FFI_TYPE_LONGDOUBLE out of date +# endif +#else +# undef FFI_TYPE_LONGDOUBLE +# define FFI_TYPE_LONGDOUBLE 4 +#endif + +union _d +{ + UINT64 d; + UINT32 s[2]; +}; + +struct _v +{ + union _d d[2] __attribute__((aligned(16))); +}; + +struct call_context +{ + struct _v v[N_V_ARG_REG]; + UINT64 x[N_X_ARG_REG]; +}; + +#if FFI_EXEC_TRAMPOLINE_TABLE + +#ifdef __MACH__ +#ifdef HAVE_PTRAUTH +#include +#endif +#include +#endif + +#else + +#if defined (__clang__) && defined (__APPLE__) +extern void sys_icache_invalidate (void *start, size_t len); +#endif + +static inline void +ffi_clear_cache (void *start, void *end) +{ +#if defined (__clang__) && defined (__APPLE__) + sys_icache_invalidate (start, (char *)end - (char *)start); +#elif defined (__GNUC__) + __builtin___clear_cache (start, end); +#elif defined (_WIN32) + FlushInstructionCache(GetCurrentProcess(), start, (char*)end - (char*)start); +#else +#error "Missing builtin to flush instruction cache" +#endif +} + +#endif + +/* A subroutine of is_vfp_type. Given a structure type, return the type code + of the first non-structure element. Recurse for structure elements. + Return -1 if the structure is in fact empty, i.e. no nested elements. */ + +static int +is_hfa0 (const ffi_type *ty) +{ + ffi_type **elements = ty->elements; + int i, ret = -1; + + if (elements != NULL) + for (i = 0; elements[i]; ++i) + { + ret = elements[i]->type; + if (ret == FFI_TYPE_STRUCT || ret == FFI_TYPE_COMPLEX) + { + ret = is_hfa0 (elements[i]); + if (ret < 0) + continue; + } + break; + } + + return ret; +} + +/* A subroutine of is_vfp_type. Given a structure type, return true if all + of the non-structure elements are the same as CANDIDATE. */ + +static int +is_hfa1 (const ffi_type *ty, int candidate) +{ + ffi_type **elements = ty->elements; + int i; + + if (elements != NULL) + for (i = 0; elements[i]; ++i) + { + int t = elements[i]->type; + if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX) + { + if (!is_hfa1 (elements[i], candidate)) + return 0; + } + else if (t != candidate) + return 0; + } + + return 1; +} + +/* Determine if TY may be allocated to the FP registers. This is both an + fp scalar type as well as an homogenous floating point aggregate (HFA). + That is, a structure consisting of 1 to 4 members of all the same type, + where that type is an fp scalar. + + Returns non-zero iff TY is an HFA. The result is the AARCH64_RET_* + constant for the type. */ + +static int +is_vfp_type (const ffi_type *ty) +{ + ffi_type **elements; + int candidate, i; + size_t size, ele_count; + + /* Quickest tests first. */ + candidate = ty->type; + switch (candidate) + { + default: + return 0; + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_LONGDOUBLE: + ele_count = 1; + goto done; + case FFI_TYPE_COMPLEX: + candidate = ty->elements[0]->type; + switch (candidate) + { + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_LONGDOUBLE: + ele_count = 2; + goto done; + } + return 0; + case FFI_TYPE_STRUCT: + break; + } + + /* No HFA types are smaller than 4 bytes, or larger than 64 bytes. */ + size = ty->size; + if (size < 4 || size > 64) + return 0; + + /* Find the type of the first non-structure member. */ + elements = ty->elements; + candidate = elements[0]->type; + if (candidate == FFI_TYPE_STRUCT || candidate == FFI_TYPE_COMPLEX) + { + for (i = 0; ; ++i) + { + candidate = is_hfa0 (elements[i]); + if (candidate >= 0) + break; + } + } + + /* If the first member is not a floating point type, it's not an HFA. + Also quickly re-check the size of the structure. */ + switch (candidate) + { + case FFI_TYPE_FLOAT: + ele_count = size / sizeof(float); + if (size != ele_count * sizeof(float)) + return 0; + break; + case FFI_TYPE_DOUBLE: + ele_count = size / sizeof(double); + if (size != ele_count * sizeof(double)) + return 0; + break; + case FFI_TYPE_LONGDOUBLE: + ele_count = size / sizeof(long double); + if (size != ele_count * sizeof(long double)) + return 0; + break; + default: + return 0; + } + if (ele_count > 4) + return 0; + + /* Finally, make sure that all scalar elements are the same type. */ + for (i = 0; elements[i]; ++i) + { + int t = elements[i]->type; + if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX) + { + if (!is_hfa1 (elements[i], candidate)) + return 0; + } + else if (t != candidate) + return 0; + } + + /* All tests succeeded. Encode the result. */ + done: + return candidate * 4 + (4 - (int)ele_count); +} + +/* Representation of the procedure call argument marshalling + state. + + The terse state variable names match the names used in the AARCH64 + PCS. */ + +struct arg_state +{ + unsigned ngrn; /* Next general-purpose register number. */ + unsigned nsrn; /* Next vector register number. */ + size_t nsaa; /* Next stack offset. */ + +#if defined (__APPLE__) + unsigned allocating_variadic; +#endif +}; + +/* Initialize a procedure call argument marshalling state. */ +static void +arg_init (struct arg_state *state) +{ + state->ngrn = 0; + state->nsrn = 0; + state->nsaa = 0; +#if defined (__APPLE__) + state->allocating_variadic = 0; +#endif +} + +/* Allocate an aligned slot on the stack and return a pointer to it. */ +static void * +allocate_to_stack (struct arg_state *state, void *stack, + size_t alignment, size_t size) +{ + size_t nsaa = state->nsaa; + + /* Round up the NSAA to the larger of 8 or the natural + alignment of the argument's type. */ +#if defined (__APPLE__) + if (state->allocating_variadic && alignment < 8) + alignment = 8; +#else + if (alignment < 8) + alignment = 8; +#endif + + nsaa = FFI_ALIGN (nsaa, alignment); + state->nsaa = nsaa + size; + + return (char *)stack + nsaa; +} + +static ffi_arg +extend_integer_type (void *source, int type) +{ + switch (type) + { + case FFI_TYPE_UINT8: + return *(UINT8 *) source; + case FFI_TYPE_SINT8: + return *(SINT8 *) source; + case FFI_TYPE_UINT16: + return *(UINT16 *) source; + case FFI_TYPE_SINT16: + return *(SINT16 *) source; + case FFI_TYPE_UINT32: + return *(UINT32 *) source; + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + return *(SINT32 *) source; + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + return *(UINT64 *) source; + break; + case FFI_TYPE_POINTER: + return *(uintptr_t *) source; + default: + abort(); + } +} + +#if defined(_MSC_VER) +void extend_hfa_type (void *dest, void *src, int h); +#else +static void +extend_hfa_type (void *dest, void *src, int h) +{ + ssize_t f = h - AARCH64_RET_S4; + void *x0; + + asm volatile ( + "adr %0, 0f\n" +" add %0, %0, %1\n" +" br %0\n" +"0: ldp s16, s17, [%3]\n" /* S4 */ +" ldp s18, s19, [%3, #8]\n" +" b 4f\n" +" ldp s16, s17, [%3]\n" /* S3 */ +" ldr s18, [%3, #8]\n" +" b 3f\n" +" ldp s16, s17, [%3]\n" /* S2 */ +" b 2f\n" +" nop\n" +" ldr s16, [%3]\n" /* S1 */ +" b 1f\n" +" nop\n" +" ldp d16, d17, [%3]\n" /* D4 */ +" ldp d18, d19, [%3, #16]\n" +" b 4f\n" +" ldp d16, d17, [%3]\n" /* D3 */ +" ldr d18, [%3, #16]\n" +" b 3f\n" +" ldp d16, d17, [%3]\n" /* D2 */ +" b 2f\n" +" nop\n" +" ldr d16, [%3]\n" /* D1 */ +" b 1f\n" +" nop\n" +" ldp q16, q17, [%3]\n" /* Q4 */ +" ldp q18, q19, [%3, #32]\n" +" b 4f\n" +" ldp q16, q17, [%3]\n" /* Q3 */ +" ldr q18, [%3, #32]\n" +" b 3f\n" +" ldp q16, q17, [%3]\n" /* Q2 */ +" b 2f\n" +" nop\n" +" ldr q16, [%3]\n" /* Q1 */ +" b 1f\n" +"4: str q19, [%2, #48]\n" +"3: str q18, [%2, #32]\n" +"2: str q17, [%2, #16]\n" +"1: str q16, [%2]" + : "=&r"(x0) + : "r"(f * 12), "r"(dest), "r"(src) + : "memory", "v16", "v17", "v18", "v19"); +} +#endif + +#if defined(_MSC_VER) +void* compress_hfa_type (void *dest, void *src, int h); +#else +static void * +compress_hfa_type (void *dest, void *reg, int h) +{ + switch (h) + { + case AARCH64_RET_S1: + if (dest == reg) + { +#ifdef __AARCH64EB__ + dest += 12; +#endif + } + else + *(float *)dest = *(float *)reg; + break; + case AARCH64_RET_S2: + asm ("ldp q16, q17, [%1]\n\t" + "st2 { v16.s, v17.s }[0], [%0]" + : : "r"(dest), "r"(reg) : "memory", "v16", "v17"); + break; + case AARCH64_RET_S3: + asm ("ldp q16, q17, [%1]\n\t" + "ldr q18, [%1, #32]\n\t" + "st3 { v16.s, v17.s, v18.s }[0], [%0]" + : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18"); + break; + case AARCH64_RET_S4: + asm ("ldp q16, q17, [%1]\n\t" + "ldp q18, q19, [%1, #32]\n\t" + "st4 { v16.s, v17.s, v18.s, v19.s }[0], [%0]" + : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18", "v19"); + break; + + case AARCH64_RET_D1: + if (dest == reg) + { +#ifdef __AARCH64EB__ + dest += 8; +#endif + } + else + *(double *)dest = *(double *)reg; + break; + case AARCH64_RET_D2: + asm ("ldp q16, q17, [%1]\n\t" + "st2 { v16.d, v17.d }[0], [%0]" + : : "r"(dest), "r"(reg) : "memory", "v16", "v17"); + break; + case AARCH64_RET_D3: + asm ("ldp q16, q17, [%1]\n\t" + "ldr q18, [%1, #32]\n\t" + "st3 { v16.d, v17.d, v18.d }[0], [%0]" + : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18"); + break; + case AARCH64_RET_D4: + asm ("ldp q16, q17, [%1]\n\t" + "ldp q18, q19, [%1, #32]\n\t" + "st4 { v16.d, v17.d, v18.d, v19.d }[0], [%0]" + : : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18", "v19"); + break; + + default: + if (dest != reg) + return memcpy (dest, reg, 16 * (4 - (h & 3))); + break; + } + return dest; +} +#endif + +/* Either allocate an appropriate register for the argument type, or if + none are available, allocate a stack slot and return a pointer + to the allocated space. */ + +static void * +allocate_int_to_reg_or_stack (struct call_context *context, + struct arg_state *state, + void *stack, size_t size) +{ + if (state->ngrn < N_X_ARG_REG) + return &context->x[state->ngrn++]; + + state->ngrn = N_X_ARG_REG; + return allocate_to_stack (state, stack, size, size); +} + +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep (ffi_cif *cif) +{ + ffi_type *rtype = cif->rtype; + size_t bytes = cif->bytes; + int flags, i, n; + + switch (rtype->type) + { + case FFI_TYPE_VOID: + flags = AARCH64_RET_VOID; + break; + case FFI_TYPE_UINT8: + flags = AARCH64_RET_UINT8; + break; + case FFI_TYPE_UINT16: + flags = AARCH64_RET_UINT16; + break; + case FFI_TYPE_UINT32: + flags = AARCH64_RET_UINT32; + break; + case FFI_TYPE_SINT8: + flags = AARCH64_RET_SINT8; + break; + case FFI_TYPE_SINT16: + flags = AARCH64_RET_SINT16; + break; + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + flags = AARCH64_RET_SINT32; + break; + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + flags = AARCH64_RET_INT64; + break; + case FFI_TYPE_POINTER: + flags = (sizeof(void *) == 4 ? AARCH64_RET_UINT32 : AARCH64_RET_INT64); + break; + + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_LONGDOUBLE: + case FFI_TYPE_STRUCT: + case FFI_TYPE_COMPLEX: + flags = is_vfp_type (rtype); + if (flags == 0) + { + size_t s = rtype->size; + if (s > 16) + { + flags = AARCH64_RET_VOID | AARCH64_RET_IN_MEM; + bytes += 8; + } + else if (s == 16) + flags = AARCH64_RET_INT128; + else if (s == 8) + flags = AARCH64_RET_INT64; + else + flags = AARCH64_RET_INT128 | AARCH64_RET_NEED_COPY; + } + break; + + default: + abort(); + } + + for (i = 0, n = cif->nargs; i < n; i++) + if (is_vfp_type (cif->arg_types[i])) + { + flags |= AARCH64_FLAG_ARG_V; + break; + } + + /* Round the stack up to a multiple of the stack alignment requirement. */ + cif->bytes = (unsigned) FFI_ALIGN(bytes, 16); + cif->flags = flags; +#if defined (__APPLE__) + cif->aarch64_nfixedargs = 0; +#endif + + return FFI_OK; +} + +#if defined (__APPLE__) +/* Perform Apple-specific cif processing for variadic calls */ +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep_var(ffi_cif *cif, unsigned int nfixedargs, + unsigned int ntotalargs) +{ + ffi_status status = ffi_prep_cif_machdep (cif); + cif->aarch64_nfixedargs = nfixedargs; + return status; +} +#else +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep_var(ffi_cif *cif, unsigned int nfixedargs, unsigned int ntotalargs) +{ + ffi_status status = ffi_prep_cif_machdep (cif); + cif->flags |= AARCH64_FLAG_VARARG; + return status; +} +#endif /* __APPLE__ */ + +extern void ffi_call_SYSV (struct call_context *context, void *frame, + void (*fn)(void), void *rvalue, int flags, + void *closure) FFI_HIDDEN; + +/* Call a function with the provided arguments and capture the return + value. */ +static void +ffi_call_int (ffi_cif *cif, void (*fn)(void), void *orig_rvalue, + void **avalue, void *closure) +{ + struct call_context *context; + void *stack, *frame, *rvalue; + struct arg_state state; + size_t stack_bytes, rtype_size, rsize; + int i, nargs, flags, isvariadic = 0; + ffi_type *rtype; + + flags = cif->flags; + rtype = cif->rtype; + rtype_size = rtype->size; + stack_bytes = cif->bytes; + + if (flags & AARCH64_FLAG_VARARG) + { + isvariadic = 1; + flags &= ~AARCH64_FLAG_VARARG; + } + + /* If the target function returns a structure via hidden pointer, + then we cannot allow a null rvalue. Otherwise, mash a null + rvalue to void return type. */ + rsize = 0; + if (flags & AARCH64_RET_IN_MEM) + { + if (orig_rvalue == NULL) + rsize = rtype_size; + } + else if (orig_rvalue == NULL) + flags &= AARCH64_FLAG_ARG_V; + else if (flags & AARCH64_RET_NEED_COPY) + rsize = 16; + + /* Allocate consectutive stack for everything we'll need. */ + context = alloca (sizeof(struct call_context) + stack_bytes + 32 + rsize); + stack = context + 1; + frame = (void*)((uintptr_t)stack + (uintptr_t)stack_bytes); + rvalue = (rsize ? (void*)((uintptr_t)frame + 32) : orig_rvalue); + + arg_init (&state); + for (i = 0, nargs = cif->nargs; i < nargs; i++) + { + ffi_type *ty = cif->arg_types[i]; + size_t s = ty->size; + void *a = avalue[i]; + int h, t; + + t = ty->type; + switch (t) + { + case FFI_TYPE_VOID: + FFI_ASSERT (0); + break; + + /* If the argument is a basic type the argument is allocated to an + appropriate register, or if none are available, to the stack. */ + case FFI_TYPE_INT: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_POINTER: + do_pointer: + { + ffi_arg ext = extend_integer_type (a, t); + if (state.ngrn < N_X_ARG_REG) + context->x[state.ngrn++] = ext; + else + { + void *d = allocate_to_stack (&state, stack, ty->alignment, s); + state.ngrn = N_X_ARG_REG; + /* Note that the default abi extends each argument + to a full 64-bit slot, while the iOS abi allocates + only enough space. */ +#ifdef __APPLE__ + memcpy(d, a, s); +#else + *(ffi_arg *)d = ext; +#endif + } + } + break; + + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_LONGDOUBLE: + case FFI_TYPE_STRUCT: + case FFI_TYPE_COMPLEX: + { + void *dest; + + h = is_vfp_type (ty); + if (h) + { + int elems = 4 - (h & 3); + if (cif->abi == FFI_WIN64 && isvariadic) + { + if (state.ngrn + elems <= N_X_ARG_REG) + { + dest = &context->x[state.ngrn]; + state.ngrn += elems; + extend_hfa_type(dest, a, h); + break; + } + state.nsrn = N_X_ARG_REG; + dest = allocate_to_stack(&state, stack, ty->alignment, s); + } + else + { + if (state.nsrn + elems <= N_V_ARG_REG) + { + dest = &context->v[state.nsrn]; + state.nsrn += elems; + extend_hfa_type (dest, a, h); + break; + } + state.nsrn = N_V_ARG_REG; + dest = allocate_to_stack (&state, stack, ty->alignment, s); + } + } + else if (s > 16) + { + /* If the argument is a composite type that is larger than 16 + bytes, then the argument has been copied to memory, and + the argument is replaced by a pointer to the copy. */ + a = &avalue[i]; + t = FFI_TYPE_POINTER; + s = sizeof (void *); + goto do_pointer; + } + else + { + size_t n = (s + 7) / 8; + if (state.ngrn + n <= N_X_ARG_REG) + { + /* If the argument is a composite type and the size in + double-words is not more than the number of available + X registers, then the argument is copied into + consecutive X registers. */ + dest = &context->x[state.ngrn]; + state.ngrn += (unsigned int)n; + } + else + { + /* Otherwise, there are insufficient X registers. Further + X register allocations are prevented, the NSAA is + adjusted and the argument is copied to memory at the + adjusted NSAA. */ + state.ngrn = N_X_ARG_REG; + dest = allocate_to_stack (&state, stack, ty->alignment, s); + } + } + memcpy (dest, a, s); + } + break; + + default: + abort(); + } + +#if defined (__APPLE__) + if (i + 1 == cif->aarch64_nfixedargs) + { + state.ngrn = N_X_ARG_REG; + state.nsrn = N_V_ARG_REG; + state.allocating_variadic = 1; + } +#endif + } + + ffi_call_SYSV (context, frame, fn, rvalue, flags, closure); + + if (flags & AARCH64_RET_NEED_COPY) + memcpy (orig_rvalue, rvalue, rtype_size); +} + +void +ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue) +{ + ffi_call_int (cif, fn, rvalue, avalue, NULL); +} + +#ifdef FFI_GO_CLOSURES +void +ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue, + void **avalue, void *closure) +{ + ffi_call_int (cif, fn, rvalue, avalue, closure); +} +#endif /* FFI_GO_CLOSURES */ + +/* Build a trampoline. */ + +extern void ffi_closure_SYSV (void) FFI_HIDDEN; +extern void ffi_closure_SYSV_V (void) FFI_HIDDEN; + +ffi_status +ffi_prep_closure_loc (ffi_closure *closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + void (*start)(void); + + if (cif->flags & AARCH64_FLAG_ARG_V) + start = ffi_closure_SYSV_V; + else + start = ffi_closure_SYSV; + +#if FFI_EXEC_TRAMPOLINE_TABLE +#ifdef __MACH__ +#ifdef HAVE_PTRAUTH + codeloc = ptrauth_strip (codeloc, ptrauth_key_asia); +#endif + void **config = (void **)((uint8_t *)codeloc - PAGE_MAX_SIZE); + config[0] = closure; + config[1] = start; +#endif +#else + static const unsigned char trampoline[16] = { + 0x90, 0x00, 0x00, 0x58, /* ldr x16, tramp+16 */ + 0xf1, 0xff, 0xff, 0x10, /* adr x17, tramp+0 */ + 0x00, 0x02, 0x1f, 0xd6 /* br x16 */ + }; + char *tramp = closure->tramp; + + memcpy (tramp, trampoline, sizeof(trampoline)); + + *(UINT64 *)(tramp + 16) = (uintptr_t)start; + + ffi_clear_cache(tramp, tramp + FFI_TRAMPOLINE_SIZE); + + /* Also flush the cache for code mapping. */ +#ifdef _WIN32 + // Not using dlmalloc.c for Windows ARM64 builds + // so calling ffi_data_to_code_pointer() isn't necessary + unsigned char *tramp_code = tramp; + #else + unsigned char *tramp_code = ffi_data_to_code_pointer (tramp); + #endif + ffi_clear_cache (tramp_code, tramp_code + FFI_TRAMPOLINE_SIZE); +#endif + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + return FFI_OK; +} + +#ifdef FFI_GO_CLOSURES +extern void ffi_go_closure_SYSV (void) FFI_HIDDEN; +extern void ffi_go_closure_SYSV_V (void) FFI_HIDDEN; + +ffi_status +ffi_prep_go_closure (ffi_go_closure *closure, ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*)) +{ + void (*start)(void); + + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + if (cif->flags & AARCH64_FLAG_ARG_V) + start = ffi_go_closure_SYSV_V; + else + start = ffi_go_closure_SYSV; + + closure->tramp = start; + closure->cif = cif; + closure->fun = fun; + + return FFI_OK; +} +#endif /* FFI_GO_CLOSURES */ + +/* Primary handler to setup and invoke a function within a closure. + + A closure when invoked enters via the assembler wrapper + ffi_closure_SYSV(). The wrapper allocates a call context on the + stack, saves the interesting registers (from the perspective of + the calling convention) into the context then passes control to + ffi_closure_SYSV_inner() passing the saved context and a pointer to + the stack at the point ffi_closure_SYSV() was invoked. + + On the return path the assembler wrapper will reload call context + registers. + + ffi_closure_SYSV_inner() marshalls the call context into ffi value + descriptors, invokes the wrapped function, then marshalls the return + value back into the call context. */ + +int FFI_HIDDEN +ffi_closure_SYSV_inner (ffi_cif *cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + struct call_context *context, + void *stack, void *rvalue, void *struct_rvalue) +{ + void **avalue = (void**) alloca (cif->nargs * sizeof (void*)); + int i, h, nargs, flags; + struct arg_state state; + + arg_init (&state); + + for (i = 0, nargs = cif->nargs; i < nargs; i++) + { + ffi_type *ty = cif->arg_types[i]; + int t = ty->type; + size_t n, s = ty->size; + + switch (t) + { + case FFI_TYPE_VOID: + FFI_ASSERT (0); + break; + + case FFI_TYPE_INT: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_POINTER: + avalue[i] = allocate_int_to_reg_or_stack (context, &state, stack, s); + break; + + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_LONGDOUBLE: + case FFI_TYPE_STRUCT: + case FFI_TYPE_COMPLEX: + h = is_vfp_type (ty); + if (h) + { + n = 4 - (h & 3); +#ifdef _WIN32 /* for handling armasm calling convention */ + if (cif->is_variadic) + { + if (state.ngrn + n <= N_X_ARG_REG) + { + void *reg = &context->x[state.ngrn]; + state.ngrn += (unsigned int)n; + + /* Eeek! We need a pointer to the structure, however the + homogeneous float elements are being passed in individual + registers, therefore for float and double the structure + is not represented as a contiguous sequence of bytes in + our saved register context. We don't need the original + contents of the register storage, so we reformat the + structure into the same memory. */ + avalue[i] = compress_hfa_type(reg, reg, h); + } + else + { + state.ngrn = N_X_ARG_REG; + state.nsrn = N_V_ARG_REG; + avalue[i] = allocate_to_stack(&state, stack, + ty->alignment, s); + } + } + else + { +#endif /* for handling armasm calling convention */ + if (state.nsrn + n <= N_V_ARG_REG) + { + void *reg = &context->v[state.nsrn]; + state.nsrn += (unsigned int)n; + avalue[i] = compress_hfa_type(reg, reg, h); + } + else + { + state.nsrn = N_V_ARG_REG; + avalue[i] = allocate_to_stack(&state, stack, + ty->alignment, s); + } +#ifdef _WIN32 /* for handling armasm calling convention */ + } +#endif /* for handling armasm calling convention */ + } + else if (s > 16) + { + /* Replace Composite type of size greater than 16 with a + pointer. */ + avalue[i] = *(void **) + allocate_int_to_reg_or_stack (context, &state, stack, + sizeof (void *)); + } + else + { + n = (s + 7) / 8; + if (state.ngrn + n <= N_X_ARG_REG) + { + avalue[i] = &context->x[state.ngrn]; + state.ngrn += (unsigned int)n; + } + else + { + state.ngrn = N_X_ARG_REG; + avalue[i] = allocate_to_stack(&state, stack, + ty->alignment, s); + } + } + break; + + default: + abort(); + } + +#if defined (__APPLE__) + if (i + 1 == cif->aarch64_nfixedargs) + { + state.ngrn = N_X_ARG_REG; + state.nsrn = N_V_ARG_REG; + state.allocating_variadic = 1; + } +#endif + } + + flags = cif->flags; + if (flags & AARCH64_RET_IN_MEM) + rvalue = struct_rvalue; + + fun (cif, rvalue, avalue, user_data); + + return flags; +} + +#endif /* (__aarch64__) || defined(__arm64__)|| defined (_M_ARM64)*/ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/ffitarget.h new file mode 100644 index 0000000..d5622e1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/ffitarget.h @@ -0,0 +1,97 @@ +/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +#ifdef __ILP32__ +#define FFI_SIZEOF_ARG 8 +#define FFI_SIZEOF_JAVA_RAW 4 +typedef unsigned long long ffi_arg; +typedef signed long long ffi_sarg; +#elif defined(_WIN32) +#define FFI_SIZEOF_ARG 8 +typedef unsigned long long ffi_arg; +typedef signed long long ffi_sarg; +#else +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; +#endif + +typedef enum ffi_abi + { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_WIN64, + FFI_LAST_ABI, +#if defined(_WIN32) + FFI_DEFAULT_ABI = FFI_WIN64 +#else + FFI_DEFAULT_ABI = FFI_SYSV +#endif + } ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 + +#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE + +#ifdef __MACH__ +#define FFI_TRAMPOLINE_SIZE 16 +#define FFI_TRAMPOLINE_CLOSURE_OFFSET 16 +#else +#error "No trampoline table implementation" +#endif + +#else +#define FFI_TRAMPOLINE_SIZE 24 +#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE +#endif + +#ifdef _WIN32 +#define FFI_EXTRA_CIF_FIELDS unsigned is_variadic +#endif +#define FFI_TARGET_SPECIFIC_VARIADIC + +/* ---- Internal ---- */ + +#if defined (__APPLE__) +#define FFI_EXTRA_CIF_FIELDS unsigned aarch64_nfixedargs +#elif !defined(_WIN32) +/* iOS and Windows reserve x18 for the system. Disable Go closures until + a new static chain is chosen. */ +#define FFI_GO_CLOSURES 1 +#endif + +#ifndef _WIN32 +/* No complex type on Windows */ +#define FFI_TARGET_HAS_COMPLEX_TYPE +#endif + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/internal.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/internal.h new file mode 100644 index 0000000..3d4d035 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/internal.h @@ -0,0 +1,68 @@ +/* +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + +#define AARCH64_RET_VOID 0 +#define AARCH64_RET_INT64 1 +#define AARCH64_RET_INT128 2 + +#define AARCH64_RET_UNUSED3 3 +#define AARCH64_RET_UNUSED4 4 +#define AARCH64_RET_UNUSED5 5 +#define AARCH64_RET_UNUSED6 6 +#define AARCH64_RET_UNUSED7 7 + +/* Note that FFI_TYPE_FLOAT == 2, _DOUBLE == 3, _LONGDOUBLE == 4, + so _S4 through _Q1 are layed out as (TYPE * 4) + (4 - COUNT). */ +#define AARCH64_RET_S4 8 +#define AARCH64_RET_S3 9 +#define AARCH64_RET_S2 10 +#define AARCH64_RET_S1 11 + +#define AARCH64_RET_D4 12 +#define AARCH64_RET_D3 13 +#define AARCH64_RET_D2 14 +#define AARCH64_RET_D1 15 + +#define AARCH64_RET_Q4 16 +#define AARCH64_RET_Q3 17 +#define AARCH64_RET_Q2 18 +#define AARCH64_RET_Q1 19 + +/* Note that each of the sub-64-bit integers gets two entries. */ +#define AARCH64_RET_UINT8 20 +#define AARCH64_RET_UINT16 22 +#define AARCH64_RET_UINT32 24 + +#define AARCH64_RET_SINT8 26 +#define AARCH64_RET_SINT16 28 +#define AARCH64_RET_SINT32 30 + +#define AARCH64_RET_MASK 31 + +#define AARCH64_RET_IN_MEM (1 << 5) +#define AARCH64_RET_NEED_COPY (1 << 6) + +#define AARCH64_FLAG_ARG_V_BIT 7 +#define AARCH64_FLAG_ARG_V (1 << AARCH64_FLAG_ARG_V_BIT) +#define AARCH64_FLAG_VARARG (1 << 8) + +#define N_X_ARG_REG 8 +#define N_V_ARG_REG 8 +#define CALL_CONTEXT_SIZE (N_V_ARG_REG * 16 + N_X_ARG_REG * 8) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/sysv.S new file mode 100644 index 0000000..b720a92 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/sysv.S @@ -0,0 +1,451 @@ +/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + +#if defined(__aarch64__) || defined(__arm64__) +#define LIBFFI_ASM +#include +#include +#include +#include "internal.h" + +#ifdef HAVE_MACHINE_ASM_H +#include +#else +#ifdef __USER_LABEL_PREFIX__ +#define CONCAT1(a, b) CONCAT2(a, b) +#define CONCAT2(a, b) a ## b + +/* Use the right prefix for global labels. */ +#define CNAME(x) CONCAT1 (__USER_LABEL_PREFIX__, x) +#else +#define CNAME(x) x +#endif +#endif + +#ifdef __AARCH64EB__ +# define BE(X) X +#else +# define BE(X) 0 +#endif + +#ifdef __ILP32__ +#define PTR_REG(n) w##n +#else +#define PTR_REG(n) x##n +#endif + +#ifdef __ILP32__ +#define PTR_SIZE 4 +#else +#define PTR_SIZE 8 +#endif + +#if FFI_EXEC_TRAMPOLINE_TABLE && defined(__MACH__) && defined(HAVE_PTRAUTH) +# define BR(r) braaz r +# define BLR(r) blraaz r +#else +# define BR(r) br r +# define BLR(r) blr r +#endif + + .text + .align 4 + +/* ffi_call_SYSV + extern void ffi_call_SYSV (void *stack, void *frame, + void (*fn)(void), void *rvalue, + int flags, void *closure); + + Therefore on entry we have: + + x0 stack + x1 frame + x2 fn + x3 rvalue + x4 flags + x5 closure +*/ + + cfi_startproc +CNAME(ffi_call_SYSV): + /* Use a stack frame allocated by our caller. */ + cfi_def_cfa(x1, 32); + stp x29, x30, [x1] + mov x29, x1 + mov sp, x0 + cfi_def_cfa_register(x29) + cfi_rel_offset (x29, 0) + cfi_rel_offset (x30, 8) + + mov x9, x2 /* save fn */ + mov x8, x3 /* install structure return */ +#ifdef FFI_GO_CLOSURES + mov x18, x5 /* install static chain */ +#endif + stp x3, x4, [x29, #16] /* save rvalue and flags */ + + /* Load the vector argument passing registers, if necessary. */ + tbz w4, #AARCH64_FLAG_ARG_V_BIT, 1f + ldp q0, q1, [sp, #0] + ldp q2, q3, [sp, #32] + ldp q4, q5, [sp, #64] + ldp q6, q7, [sp, #96] +1: + /* Load the core argument passing registers, including + the structure return pointer. */ + ldp x0, x1, [sp, #16*N_V_ARG_REG + 0] + ldp x2, x3, [sp, #16*N_V_ARG_REG + 16] + ldp x4, x5, [sp, #16*N_V_ARG_REG + 32] + ldp x6, x7, [sp, #16*N_V_ARG_REG + 48] + + /* Deallocate the context, leaving the stacked arguments. */ + add sp, sp, #CALL_CONTEXT_SIZE + + BLR(x9) /* call fn */ + + ldp x3, x4, [x29, #16] /* reload rvalue and flags */ + + /* Partially deconstruct the stack frame. */ + mov sp, x29 + cfi_def_cfa_register (sp) + ldp x29, x30, [x29] + + /* Save the return value as directed. */ + adr x5, 0f + and w4, w4, #AARCH64_RET_MASK + add x5, x5, x4, lsl #3 + br x5 + + /* Note that each table entry is 2 insns, and thus 8 bytes. + For integer data, note that we're storing into ffi_arg + and therefore we want to extend to 64 bits; these types + have two consecutive entries allocated for them. */ + .align 4 +0: ret /* VOID */ + nop +1: str x0, [x3] /* INT64 */ + ret +2: stp x0, x1, [x3] /* INT128 */ + ret +3: brk #1000 /* UNUSED */ + ret +4: brk #1000 /* UNUSED */ + ret +5: brk #1000 /* UNUSED */ + ret +6: brk #1000 /* UNUSED */ + ret +7: brk #1000 /* UNUSED */ + ret +8: st4 { v0.s, v1.s, v2.s, v3.s }[0], [x3] /* S4 */ + ret +9: st3 { v0.s, v1.s, v2.s }[0], [x3] /* S3 */ + ret +10: stp s0, s1, [x3] /* S2 */ + ret +11: str s0, [x3] /* S1 */ + ret +12: st4 { v0.d, v1.d, v2.d, v3.d }[0], [x3] /* D4 */ + ret +13: st3 { v0.d, v1.d, v2.d }[0], [x3] /* D3 */ + ret +14: stp d0, d1, [x3] /* D2 */ + ret +15: str d0, [x3] /* D1 */ + ret +16: str q3, [x3, #48] /* Q4 */ + nop +17: str q2, [x3, #32] /* Q3 */ + nop +18: stp q0, q1, [x3] /* Q2 */ + ret +19: str q0, [x3] /* Q1 */ + ret +20: uxtb w0, w0 /* UINT8 */ + str x0, [x3] +21: ret /* reserved */ + nop +22: uxth w0, w0 /* UINT16 */ + str x0, [x3] +23: ret /* reserved */ + nop +24: mov w0, w0 /* UINT32 */ + str x0, [x3] +25: ret /* reserved */ + nop +26: sxtb x0, w0 /* SINT8 */ + str x0, [x3] +27: ret /* reserved */ + nop +28: sxth x0, w0 /* SINT16 */ + str x0, [x3] +29: ret /* reserved */ + nop +30: sxtw x0, w0 /* SINT32 */ + str x0, [x3] +31: ret /* reserved */ + nop + + cfi_endproc + + .globl CNAME(ffi_call_SYSV) + FFI_HIDDEN(CNAME(ffi_call_SYSV)) +#ifdef __ELF__ + .type CNAME(ffi_call_SYSV), #function + .size CNAME(ffi_call_SYSV), .-CNAME(ffi_call_SYSV) +#endif + +/* ffi_closure_SYSV + + Closure invocation glue. This is the low level code invoked directly by + the closure trampoline to setup and call a closure. + + On entry x17 points to a struct ffi_closure, x16 has been clobbered + all other registers are preserved. + + We allocate a call context and save the argument passing registers, + then invoked the generic C ffi_closure_SYSV_inner() function to do all + the real work, on return we load the result passing registers back from + the call context. +*/ + +#define ffi_closure_SYSV_FS (8*2 + CALL_CONTEXT_SIZE + 64) + + .align 4 +CNAME(ffi_closure_SYSV_V): + cfi_startproc + stp x29, x30, [sp, #-ffi_closure_SYSV_FS]! + cfi_adjust_cfa_offset (ffi_closure_SYSV_FS) + cfi_rel_offset (x29, 0) + cfi_rel_offset (x30, 8) + + /* Save the argument passing vector registers. */ + stp q0, q1, [sp, #16 + 0] + stp q2, q3, [sp, #16 + 32] + stp q4, q5, [sp, #16 + 64] + stp q6, q7, [sp, #16 + 96] + b 0f + cfi_endproc + + .globl CNAME(ffi_closure_SYSV_V) + FFI_HIDDEN(CNAME(ffi_closure_SYSV_V)) +#ifdef __ELF__ + .type CNAME(ffi_closure_SYSV_V), #function + .size CNAME(ffi_closure_SYSV_V), . - CNAME(ffi_closure_SYSV_V) +#endif + + .align 4 + cfi_startproc +CNAME(ffi_closure_SYSV): + stp x29, x30, [sp, #-ffi_closure_SYSV_FS]! + cfi_adjust_cfa_offset (ffi_closure_SYSV_FS) + cfi_rel_offset (x29, 0) + cfi_rel_offset (x30, 8) +0: + mov x29, sp + + /* Save the argument passing core registers. */ + stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0] + stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16] + stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32] + stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48] + + /* Load ffi_closure_inner arguments. */ + ldp PTR_REG(0), PTR_REG(1), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET] /* load cif, fn */ + ldr PTR_REG(2), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET+PTR_SIZE*2] /* load user_data */ +.Ldo_closure: + add x3, sp, #16 /* load context */ + add x4, sp, #ffi_closure_SYSV_FS /* load stack */ + add x5, sp, #16+CALL_CONTEXT_SIZE /* load rvalue */ + mov x6, x8 /* load struct_rval */ + bl CNAME(ffi_closure_SYSV_inner) + + /* Load the return value as directed. */ +#if FFI_EXEC_TRAMPOLINE_TABLE && defined(__MACH__) && defined(HAVE_PTRAUTH) + autiza x1 +#endif + adr x1, 0f + and w0, w0, #AARCH64_RET_MASK + add x1, x1, x0, lsl #3 + add x3, sp, #16+CALL_CONTEXT_SIZE + br x1 + + /* Note that each table entry is 2 insns, and thus 8 bytes. */ + .align 4 +0: b 99f /* VOID */ + nop +1: ldr x0, [x3] /* INT64 */ + b 99f +2: ldp x0, x1, [x3] /* INT128 */ + b 99f +3: brk #1000 /* UNUSED */ + nop +4: brk #1000 /* UNUSED */ + nop +5: brk #1000 /* UNUSED */ + nop +6: brk #1000 /* UNUSED */ + nop +7: brk #1000 /* UNUSED */ + nop +8: ldr s3, [x3, #12] /* S4 */ + nop +9: ldr s2, [x3, #8] /* S3 */ + nop +10: ldp s0, s1, [x3] /* S2 */ + b 99f +11: ldr s0, [x3] /* S1 */ + b 99f +12: ldr d3, [x3, #24] /* D4 */ + nop +13: ldr d2, [x3, #16] /* D3 */ + nop +14: ldp d0, d1, [x3] /* D2 */ + b 99f +15: ldr d0, [x3] /* D1 */ + b 99f +16: ldr q3, [x3, #48] /* Q4 */ + nop +17: ldr q2, [x3, #32] /* Q3 */ + nop +18: ldp q0, q1, [x3] /* Q2 */ + b 99f +19: ldr q0, [x3] /* Q1 */ + b 99f +20: ldrb w0, [x3, #BE(7)] /* UINT8 */ + b 99f +21: brk #1000 /* reserved */ + nop +22: ldrh w0, [x3, #BE(6)] /* UINT16 */ + b 99f +23: brk #1000 /* reserved */ + nop +24: ldr w0, [x3, #BE(4)] /* UINT32 */ + b 99f +25: brk #1000 /* reserved */ + nop +26: ldrsb x0, [x3, #BE(7)] /* SINT8 */ + b 99f +27: brk #1000 /* reserved */ + nop +28: ldrsh x0, [x3, #BE(6)] /* SINT16 */ + b 99f +29: brk #1000 /* reserved */ + nop +30: ldrsw x0, [x3, #BE(4)] /* SINT32 */ + nop +31: /* reserved */ +99: ldp x29, x30, [sp], #ffi_closure_SYSV_FS + cfi_adjust_cfa_offset (-ffi_closure_SYSV_FS) + cfi_restore (x29) + cfi_restore (x30) + ret + cfi_endproc + + .globl CNAME(ffi_closure_SYSV) + FFI_HIDDEN(CNAME(ffi_closure_SYSV)) +#ifdef __ELF__ + .type CNAME(ffi_closure_SYSV), #function + .size CNAME(ffi_closure_SYSV), . - CNAME(ffi_closure_SYSV) +#endif + +#if FFI_EXEC_TRAMPOLINE_TABLE + +#ifdef __MACH__ +#include + .align PAGE_MAX_SHIFT +CNAME(ffi_closure_trampoline_table_page): + .rept PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE + adr x16, -PAGE_MAX_SIZE + ldp x17, x16, [x16] + BR(x16) + nop /* each entry in the trampoline config page is 2*sizeof(void*) so the trampoline itself cannot be smaller than 16 bytes */ + .endr + + .globl CNAME(ffi_closure_trampoline_table_page) + FFI_HIDDEN(CNAME(ffi_closure_trampoline_table_page)) + #ifdef __ELF__ + .type CNAME(ffi_closure_trampoline_table_page), #function + .size CNAME(ffi_closure_trampoline_table_page), . - CNAME(ffi_closure_trampoline_table_page) + #endif +#endif + +#endif /* FFI_EXEC_TRAMPOLINE_TABLE */ + +#ifdef FFI_GO_CLOSURES + .align 4 +CNAME(ffi_go_closure_SYSV_V): + cfi_startproc + stp x29, x30, [sp, #-ffi_closure_SYSV_FS]! + cfi_adjust_cfa_offset (ffi_closure_SYSV_FS) + cfi_rel_offset (x29, 0) + cfi_rel_offset (x30, 8) + + /* Save the argument passing vector registers. */ + stp q0, q1, [sp, #16 + 0] + stp q2, q3, [sp, #16 + 32] + stp q4, q5, [sp, #16 + 64] + stp q6, q7, [sp, #16 + 96] + b 0f + cfi_endproc + + .globl CNAME(ffi_go_closure_SYSV_V) + FFI_HIDDEN(CNAME(ffi_go_closure_SYSV_V)) +#ifdef __ELF__ + .type CNAME(ffi_go_closure_SYSV_V), #function + .size CNAME(ffi_go_closure_SYSV_V), . - CNAME(ffi_go_closure_SYSV_V) +#endif + + .align 4 + cfi_startproc +CNAME(ffi_go_closure_SYSV): + stp x29, x30, [sp, #-ffi_closure_SYSV_FS]! + cfi_adjust_cfa_offset (ffi_closure_SYSV_FS) + cfi_rel_offset (x29, 0) + cfi_rel_offset (x30, 8) +0: + mov x29, sp + + /* Save the argument passing core registers. */ + stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0] + stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16] + stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32] + stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48] + + /* Load ffi_closure_inner arguments. */ + ldp PTR_REG(0), PTR_REG(1), [x18, #PTR_SIZE]/* load cif, fn */ + mov x2, x18 /* load user_data */ + b .Ldo_closure + cfi_endproc + + .globl CNAME(ffi_go_closure_SYSV) + FFI_HIDDEN(CNAME(ffi_go_closure_SYSV)) +#ifdef __ELF__ + .type CNAME(ffi_go_closure_SYSV), #function + .size CNAME(ffi_go_closure_SYSV), . - CNAME(ffi_go_closure_SYSV) +#endif +#endif /* FFI_GO_CLOSURES */ +#endif /* __arm64__ */ + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",%progbits +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/win64_armasm.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/win64_armasm.S new file mode 100644 index 0000000..7fc185b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/aarch64/win64_armasm.S @@ -0,0 +1,506 @@ +/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd. +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + +#define LIBFFI_ASM +#include +#include +#include +#include "internal.h" + + OPT 2 /*disable listing */ +/* For some macros to add unwind information */ +#include "ksarm64.h" + OPT 1 /*re-enable listing */ + +#define BE(X) 0 +#define PTR_REG(n) x##n +#define PTR_SIZE 8 + + IMPORT ffi_closure_SYSV_inner + EXPORT ffi_call_SYSV + EXPORT ffi_closure_SYSV_V + EXPORT ffi_closure_SYSV + EXPORT extend_hfa_type + EXPORT compress_hfa_type +#ifdef FFI_GO_CLOSURES + EXPORT ffi_go_closure_SYSV_V + EXPORT ffi_go_closure_SYSV +#endif + + TEXTAREA, ALIGN=8 + +/* ffi_call_SYSV + extern void ffi_call_SYSV (void *stack, void *frame, + void (*fn)(void), void *rvalue, + int flags, void *closure); + Therefore on entry we have: + x0 stack + x1 frame + x2 fn + x3 rvalue + x4 flags + x5 closure +*/ + + NESTED_ENTRY ffi_call_SYSV_fake + + /* For unwind information, Windows has to store fp and lr */ + PROLOG_SAVE_REG_PAIR x29, x30, #-32! + + ALTERNATE_ENTRY ffi_call_SYSV + /* Use a stack frame allocated by our caller. */ + stp x29, x30, [x1] + mov x29, x1 + mov sp, x0 + + mov x9, x2 /* save fn */ + mov x8, x3 /* install structure return */ +#ifdef FFI_GO_CLOSURES + /*mov x18, x5 install static chain */ +#endif + stp x3, x4, [x29, #16] /* save rvalue and flags */ + + /* Load the vector argument passing registers, if necessary. */ + tbz x4, #AARCH64_FLAG_ARG_V_BIT, ffi_call_SYSV_L1 + ldp q0, q1, [sp, #0] + ldp q2, q3, [sp, #32] + ldp q4, q5, [sp, #64] + ldp q6, q7, [sp, #96] + +ffi_call_SYSV_L1 + /* Load the core argument passing registers, including + the structure return pointer. */ + ldp x0, x1, [sp, #16*N_V_ARG_REG + 0] + ldp x2, x3, [sp, #16*N_V_ARG_REG + 16] + ldp x4, x5, [sp, #16*N_V_ARG_REG + 32] + ldp x6, x7, [sp, #16*N_V_ARG_REG + 48] + + /* Deallocate the context, leaving the stacked arguments. */ + add sp, sp, #CALL_CONTEXT_SIZE + + blr x9 /* call fn */ + + ldp x3, x4, [x29, #16] /* reload rvalue and flags */ + + /* Partially deconstruct the stack frame. */ + mov sp, x29 + ldp x29, x30, [x29] + + /* Save the return value as directed. */ + adr x5, ffi_call_SYSV_return + and w4, w4, #AARCH64_RET_MASK + add x5, x5, x4, lsl #3 + br x5 + + /* Note that each table entry is 2 insns, and thus 8 bytes. + For integer data, note that we're storing into ffi_arg + and therefore we want to extend to 64 bits; these types + have two consecutive entries allocated for them. */ + ALIGN 4 +ffi_call_SYSV_return + ret /* VOID */ + nop + str x0, [x3] /* INT64 */ + ret + stp x0, x1, [x3] /* INT128 */ + ret + brk #1000 /* UNUSED */ + ret + brk #1000 /* UNUSED */ + ret + brk #1000 /* UNUSED */ + ret + brk #1000 /* UNUSED */ + ret + brk #1000 /* UNUSED */ + ret + st4 { v0.s, v1.s, v2.s, v3.s }[0], [x3] /* S4 */ + ret + st3 { v0.s, v1.s, v2.s }[0], [x3] /* S3 */ + ret + stp s0, s1, [x3] /* S2 */ + ret + str s0, [x3] /* S1 */ + ret + st4 { v0.d, v1.d, v2.d, v3.d }[0], [x3] /* D4 */ + ret + st3 { v0.d, v1.d, v2.d }[0], [x3] /* D3 */ + ret + stp d0, d1, [x3] /* D2 */ + ret + str d0, [x3] /* D1 */ + ret + str q3, [x3, #48] /* Q4 */ + nop + str q2, [x3, #32] /* Q3 */ + nop + stp q0, q1, [x3] /* Q2 */ + ret + str q0, [x3] /* Q1 */ + ret + uxtb w0, w0 /* UINT8 */ + str x0, [x3] + ret /* reserved */ + nop + uxth w0, w0 /* UINT16 */ + str x0, [x3] + ret /* reserved */ + nop + mov w0, w0 /* UINT32 */ + str x0, [x3] + ret /* reserved */ + nop + sxtb x0, w0 /* SINT8 */ + str x0, [x3] + ret /* reserved */ + nop + sxth x0, w0 /* SINT16 */ + str x0, [x3] + ret /* reserved */ + nop + sxtw x0, w0 /* SINT32 */ + str x0, [x3] + ret /* reserved */ + nop + + + NESTED_END ffi_call_SYSV_fake + + +/* ffi_closure_SYSV + Closure invocation glue. This is the low level code invoked directly by + the closure trampoline to setup and call a closure. + On entry x17 points to a struct ffi_closure, x16 has been clobbered + all other registers are preserved. + We allocate a call context and save the argument passing registers, + then invoked the generic C ffi_closure_SYSV_inner() function to do all + the real work, on return we load the result passing registers back from + the call context. +*/ + +#define ffi_closure_SYSV_FS (8*2 + CALL_CONTEXT_SIZE + 64) + + NESTED_ENTRY ffi_closure_SYSV_V + PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS! + + /* Save the argument passing vector registers. */ + stp q0, q1, [sp, #16 + 0] + stp q2, q3, [sp, #16 + 32] + stp q4, q5, [sp, #16 + 64] + stp q6, q7, [sp, #16 + 96] + + b ffi_closure_SYSV_save_argument + NESTED_END ffi_closure_SYSV_V + + NESTED_ENTRY ffi_closure_SYSV + PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS! + +ffi_closure_SYSV_save_argument + /* Save the argument passing core registers. */ + stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0] + stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16] + stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32] + stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48] + + /* Load ffi_closure_inner arguments. */ + ldp PTR_REG(0), PTR_REG(1), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET] /* load cif, fn */ + ldr PTR_REG(2), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET+PTR_SIZE*2] /* load user_data */ + +do_closure + add x3, sp, #16 /* load context */ + add x4, sp, #ffi_closure_SYSV_FS /* load stack */ + add x5, sp, #16+CALL_CONTEXT_SIZE /* load rvalue */ + mov x6, x8 /* load struct_rval */ + + bl ffi_closure_SYSV_inner + + /* Load the return value as directed. */ + adr x1, ffi_closure_SYSV_return_base + and w0, w0, #AARCH64_RET_MASK + add x1, x1, x0, lsl #3 + add x3, sp, #16+CALL_CONTEXT_SIZE + br x1 + + /* Note that each table entry is 2 insns, and thus 8 bytes. */ + ALIGN 8 +ffi_closure_SYSV_return_base + b ffi_closure_SYSV_epilog /* VOID */ + nop + ldr x0, [x3] /* INT64 */ + b ffi_closure_SYSV_epilog + ldp x0, x1, [x3] /* INT128 */ + b ffi_closure_SYSV_epilog + brk #1000 /* UNUSED */ + nop + brk #1000 /* UNUSED */ + nop + brk #1000 /* UNUSED */ + nop + brk #1000 /* UNUSED */ + nop + brk #1000 /* UNUSED */ + nop + ldr s3, [x3, #12] /* S4 */ + nop + ldr s2, [x3, #8] /* S3 */ + nop + ldp s0, s1, [x3] /* S2 */ + b ffi_closure_SYSV_epilog + ldr s0, [x3] /* S1 */ + b ffi_closure_SYSV_epilog + ldr d3, [x3, #24] /* D4 */ + nop + ldr d2, [x3, #16] /* D3 */ + nop + ldp d0, d1, [x3] /* D2 */ + b ffi_closure_SYSV_epilog + ldr d0, [x3] /* D1 */ + b ffi_closure_SYSV_epilog + ldr q3, [x3, #48] /* Q4 */ + nop + ldr q2, [x3, #32] /* Q3 */ + nop + ldp q0, q1, [x3] /* Q2 */ + b ffi_closure_SYSV_epilog + ldr q0, [x3] /* Q1 */ + b ffi_closure_SYSV_epilog + ldrb w0, [x3, #BE(7)] /* UINT8 */ + b ffi_closure_SYSV_epilog + brk #1000 /* reserved */ + nop + ldrh w0, [x3, #BE(6)] /* UINT16 */ + b ffi_closure_SYSV_epilog + brk #1000 /* reserved */ + nop + ldr w0, [x3, #BE(4)] /* UINT32 */ + b ffi_closure_SYSV_epilog + brk #1000 /* reserved */ + nop + ldrsb x0, [x3, #BE(7)] /* SINT8 */ + b ffi_closure_SYSV_epilog + brk #1000 /* reserved */ + nop + ldrsh x0, [x3, #BE(6)] /* SINT16 */ + b ffi_closure_SYSV_epilog + brk #1000 /* reserved */ + nop + ldrsw x0, [x3, #BE(4)] /* SINT32 */ + nop + /* reserved */ + +ffi_closure_SYSV_epilog + EPILOG_RESTORE_REG_PAIR x29, x30, #ffi_closure_SYSV_FS! + EPILOG_RETURN + NESTED_END ffi_closure_SYSV + + +#ifdef FFI_GO_CLOSURES + NESTED_ENTRY ffi_go_closure_SYSV_V + PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS! + + /* Save the argument passing vector registers. */ + stp q0, q1, [sp, #16 + 0] + stp q2, q3, [sp, #16 + 32] + stp q4, q5, [sp, #16 + 64] + stp q6, q7, [sp, #16 + 96] + b ffi_go_closure_SYSV_save_argument + NESTED_END ffi_go_closure_SYSV_V + + NESTED_ENTRY ffi_go_closure_SYSV + PROLOG_SAVE_REG_PAIR x29, x30, #-ffi_closure_SYSV_FS! + +ffi_go_closure_SYSV_save_argument + /* Save the argument passing core registers. */ + stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0] + stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16] + stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32] + stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48] + + /* Load ffi_closure_inner arguments. */ + ldp PTR_REG(0), PTR_REG(1), [x18, #PTR_SIZE]/* load cif, fn */ + mov x2, x18 /* load user_data */ + b do_closure + NESTED_END ffi_go_closure_SYSV + +#endif /* FFI_GO_CLOSURES */ + + +/* void extend_hfa_type (void *dest, void *src, int h) */ + + LEAF_ENTRY extend_hfa_type + + adr x3, extend_hfa_type_jump_base + and w2, w2, #AARCH64_RET_MASK + sub x2, x2, #AARCH64_RET_S4 + add x3, x3, x2, lsl #4 + br x3 + + ALIGN 4 +extend_hfa_type_jump_base + ldp s16, s17, [x1] /* S4 */ + ldp s18, s19, [x1, #8] + b extend_hfa_type_store_4 + nop + + ldp s16, s17, [x1] /* S3 */ + ldr s18, [x1, #8] + b extend_hfa_type_store_3 + nop + + ldp s16, s17, [x1] /* S2 */ + b extend_hfa_type_store_2 + nop + nop + + ldr s16, [x1] /* S1 */ + b extend_hfa_type_store_1 + nop + nop + + ldp d16, d17, [x1] /* D4 */ + ldp d18, d19, [x1, #16] + b extend_hfa_type_store_4 + nop + + ldp d16, d17, [x1] /* D3 */ + ldr d18, [x1, #16] + b extend_hfa_type_store_3 + nop + + ldp d16, d17, [x1] /* D2 */ + b extend_hfa_type_store_2 + nop + nop + + ldr d16, [x1] /* D1 */ + b extend_hfa_type_store_1 + nop + nop + + ldp q16, q17, [x1] /* Q4 */ + ldp q18, q19, [x1, #16] + b extend_hfa_type_store_4 + nop + + ldp q16, q17, [x1] /* Q3 */ + ldr q18, [x1, #16] + b extend_hfa_type_store_3 + nop + + ldp q16, q17, [x1] /* Q2 */ + b extend_hfa_type_store_2 + nop + nop + + ldr q16, [x1] /* Q1 */ + b extend_hfa_type_store_1 + +extend_hfa_type_store_4 + str q19, [x0, #48] +extend_hfa_type_store_3 + str q18, [x0, #32] +extend_hfa_type_store_2 + str q17, [x0, #16] +extend_hfa_type_store_1 + str q16, [x0] + ret + + LEAF_END extend_hfa_type + + +/* void compress_hfa_type (void *dest, void *reg, int h) */ + + LEAF_ENTRY compress_hfa_type + + adr x3, compress_hfa_type_jump_base + and w2, w2, #AARCH64_RET_MASK + sub x2, x2, #AARCH64_RET_S4 + add x3, x3, x2, lsl #4 + br x3 + + ALIGN 4 +compress_hfa_type_jump_base + ldp q16, q17, [x1] /* S4 */ + ldp q18, q19, [x1, #32] + st4 { v16.s, v17.s, v18.s, v19.s }[0], [x0] + ret + + ldp q16, q17, [x1] /* S3 */ + ldr q18, [x1, #32] + st3 { v16.s, v17.s, v18.s }[0], [x0] + ret + + ldp q16, q17, [x1] /* S2 */ + st2 { v16.s, v17.s }[0], [x0] + ret + nop + + ldr q16, [x1] /* S1 */ + st1 { v16.s }[0], [x0] + ret + nop + + ldp q16, q17, [x1] /* D4 */ + ldp q18, q19, [x1, #32] + st4 { v16.d, v17.d, v18.d, v19.d }[0], [x0] + ret + + ldp q16, q17, [x1] /* D3 */ + ldr q18, [x1, #32] + st3 { v16.d, v17.d, v18.d }[0], [x0] + ret + + ldp q16, q17, [x1] /* D2 */ + st2 { v16.d, v17.d }[0], [x0] + ret + nop + + ldr q16, [x1] /* D1 */ + st1 { v16.d }[0], [x0] + ret + nop + + ldp q16, q17, [x1] /* Q4 */ + ldp q18, q19, [x1, #32] + b compress_hfa_type_store_q4 + nop + + ldp q16, q17, [x1] /* Q3 */ + ldr q18, [x1, #32] + b compress_hfa_type_store_q3 + nop + + ldp q16, q17, [x1] /* Q2 */ + stp q16, q17, [x0] + ret + nop + + ldr q16, [x1] /* Q1 */ + str q16, [x0] + ret + +compress_hfa_type_store_q4 + str q19, [x0, #48] +compress_hfa_type_store_q3 + str q18, [x0, #32] + stp q16, q17, [x0] + ret + + LEAF_END compress_hfa_type + + END \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/ffi.c new file mode 100644 index 0000000..7a95e97 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/ffi.c @@ -0,0 +1,521 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2012 Anthony Green + Copyright (c) 1998, 2001, 2007, 2008 Red Hat, Inc. + + Alpha Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include +#include +#include "internal.h" + +/* Force FFI_TYPE_LONGDOUBLE to be different than FFI_TYPE_DOUBLE; + all further uses in this file will refer to the 128-bit type. */ +#if defined(__LONG_DOUBLE_128__) +# if FFI_TYPE_LONGDOUBLE != 4 +# error FFI_TYPE_LONGDOUBLE out of date +# endif +#else +# undef FFI_TYPE_LONGDOUBLE +# define FFI_TYPE_LONGDOUBLE 4 +#endif + +extern void ffi_call_osf(void *stack, void *frame, unsigned flags, + void *raddr, void (*fn)(void), void *closure) + FFI_HIDDEN; +extern void ffi_closure_osf(void) FFI_HIDDEN; +extern void ffi_go_closure_osf(void) FFI_HIDDEN; + +/* Promote a float value to its in-register double representation. + Unlike actually casting to double, this does not trap on NaN. */ +static inline UINT64 lds(void *ptr) +{ + UINT64 ret; + asm("lds %0,%1" : "=f"(ret) : "m"(*(UINT32 *)ptr)); + return ret; +} + +/* And the reverse. */ +static inline void sts(void *ptr, UINT64 val) +{ + asm("sts %1,%0" : "=m"(*(UINT32 *)ptr) : "f"(val)); +} + +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep(ffi_cif *cif) +{ + size_t bytes = 0; + int flags, i, avn; + ffi_type *rtype, *itype; + + if (cif->abi != FFI_OSF) + return FFI_BAD_ABI; + + /* Compute the size of the argument area. */ + for (i = 0, avn = cif->nargs; i < avn; i++) + { + itype = cif->arg_types[i]; + switch (itype->type) + { + case FFI_TYPE_INT: + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_POINTER: + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_LONGDOUBLE: + /* All take one 8 byte slot. */ + bytes += 8; + break; + + case FFI_TYPE_VOID: + case FFI_TYPE_STRUCT: + /* Passed by value in N slots. */ + bytes += FFI_ALIGN(itype->size, FFI_SIZEOF_ARG); + break; + + case FFI_TYPE_COMPLEX: + /* _Complex long double passed by reference; others in 2 slots. */ + if (itype->elements[0]->type == FFI_TYPE_LONGDOUBLE) + bytes += 8; + else + bytes += 16; + break; + + default: + abort(); + } + } + + /* Set the return type flag */ + rtype = cif->rtype; + switch (rtype->type) + { + case FFI_TYPE_VOID: + flags = ALPHA_FLAGS(ALPHA_ST_VOID, ALPHA_LD_VOID); + break; + case FFI_TYPE_INT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + flags = ALPHA_FLAGS(ALPHA_ST_INT, ALPHA_LD_INT32); + break; + case FFI_TYPE_FLOAT: + flags = ALPHA_FLAGS(ALPHA_ST_FLOAT, ALPHA_LD_FLOAT); + break; + case FFI_TYPE_DOUBLE: + flags = ALPHA_FLAGS(ALPHA_ST_DOUBLE, ALPHA_LD_DOUBLE); + break; + case FFI_TYPE_UINT8: + flags = ALPHA_FLAGS(ALPHA_ST_INT, ALPHA_LD_UINT8); + break; + case FFI_TYPE_SINT8: + flags = ALPHA_FLAGS(ALPHA_ST_INT, ALPHA_LD_SINT8); + break; + case FFI_TYPE_UINT16: + flags = ALPHA_FLAGS(ALPHA_ST_INT, ALPHA_LD_UINT16); + break; + case FFI_TYPE_SINT16: + flags = ALPHA_FLAGS(ALPHA_ST_INT, ALPHA_LD_SINT16); + break; + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_POINTER: + flags = ALPHA_FLAGS(ALPHA_ST_INT, ALPHA_LD_INT64); + break; + case FFI_TYPE_LONGDOUBLE: + case FFI_TYPE_STRUCT: + /* Passed in memory, with a hidden pointer. */ + flags = ALPHA_RET_IN_MEM; + break; + case FFI_TYPE_COMPLEX: + itype = rtype->elements[0]; + switch (itype->type) + { + case FFI_TYPE_FLOAT: + flags = ALPHA_FLAGS(ALPHA_ST_CPLXF, ALPHA_LD_CPLXF); + break; + case FFI_TYPE_DOUBLE: + flags = ALPHA_FLAGS(ALPHA_ST_CPLXD, ALPHA_LD_CPLXD); + break; + default: + if (rtype->size <= 8) + flags = ALPHA_FLAGS(ALPHA_ST_INT, ALPHA_LD_INT64); + else + flags = ALPHA_RET_IN_MEM; + break; + } + break; + default: + abort(); + } + cif->flags = flags; + + /* Include the hidden structure pointer in args requirement. */ + if (flags == ALPHA_RET_IN_MEM) + bytes += 8; + /* Minimum size is 6 slots, so that ffi_call_osf can pop them. */ + if (bytes < 6*8) + bytes = 6*8; + cif->bytes = bytes; + + return FFI_OK; +} + +static unsigned long +extend_basic_type(void *valp, int type, int argn) +{ + switch (type) + { + case FFI_TYPE_SINT8: + return *(SINT8 *)valp; + case FFI_TYPE_UINT8: + return *(UINT8 *)valp; + case FFI_TYPE_SINT16: + return *(SINT16 *)valp; + case FFI_TYPE_UINT16: + return *(UINT16 *)valp; + + case FFI_TYPE_FLOAT: + if (argn < 6) + return lds(valp); + /* FALLTHRU */ + + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + /* Note that unsigned 32-bit quantities are sign extended. */ + return *(SINT32 *)valp; + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_POINTER: + case FFI_TYPE_DOUBLE: + return *(UINT64 *)valp; + + default: + abort(); + } +} + +static void +ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + unsigned long *argp; + long i, avn, argn, flags = cif->flags; + ffi_type **arg_types; + void *frame; + + /* If the return value is a struct and we don't have a return + value address then we need to make one. */ + if (rvalue == NULL && flags == ALPHA_RET_IN_MEM) + rvalue = alloca(cif->rtype->size); + + /* Allocate the space for the arguments, plus 4 words of temp + space for ffi_call_osf. */ + argp = frame = alloca(cif->bytes + 4*FFI_SIZEOF_ARG); + frame += cif->bytes; + + argn = 0; + if (flags == ALPHA_RET_IN_MEM) + argp[argn++] = (unsigned long)rvalue; + + avn = cif->nargs; + arg_types = cif->arg_types; + + for (i = 0, avn = cif->nargs; i < avn; i++) + { + ffi_type *ty = arg_types[i]; + void *valp = avalue[i]; + int type = ty->type; + size_t size; + + switch (type) + { + case FFI_TYPE_INT: + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_POINTER: + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + argp[argn] = extend_basic_type(valp, type, argn); + argn++; + break; + + case FFI_TYPE_LONGDOUBLE: + by_reference: + /* Note that 128-bit long double is passed by reference. */ + argp[argn++] = (unsigned long)valp; + break; + + case FFI_TYPE_VOID: + case FFI_TYPE_STRUCT: + size = ty->size; + memcpy(argp + argn, valp, size); + argn += FFI_ALIGN(size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; + break; + + case FFI_TYPE_COMPLEX: + type = ty->elements[0]->type; + if (type == FFI_TYPE_LONGDOUBLE) + goto by_reference; + + /* Most complex types passed as two separate arguments. */ + size = ty->elements[0]->size; + argp[argn] = extend_basic_type(valp, type, argn); + argp[argn + 1] = extend_basic_type(valp + size, type, argn + 1); + argn += 2; + break; + + default: + abort(); + } + } + + flags = (flags >> ALPHA_ST_SHIFT) & 0xff; + ffi_call_osf(argp, frame, flags, rvalue, fn, closure); +} + +void +ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + ffi_call_int(cif, fn, rvalue, avalue, NULL); +} + +void +ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + ffi_call_int(cif, fn, rvalue, avalue, closure); +} + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + unsigned int *tramp; + + if (cif->abi != FFI_OSF) + return FFI_BAD_ABI; + + tramp = (unsigned int *) &closure->tramp[0]; + tramp[0] = 0x47fb0401; /* mov $27,$1 */ + tramp[1] = 0xa77b0010; /* ldq $27,16($27) */ + tramp[2] = 0x6bfb0000; /* jmp $31,($27),0 */ + tramp[3] = 0x47ff041f; /* nop */ + *(void **) &tramp[4] = ffi_closure_osf; + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + /* Flush the Icache. + + Tru64 UNIX as doesn't understand the imb mnemonic, so use call_pal + instead, since both Compaq as and gas can handle it. + + 0x86 is PAL_imb in Tru64 UNIX . */ + asm volatile ("call_pal 0x86" : : : "memory"); + + return FFI_OK; +} + +ffi_status +ffi_prep_go_closure (ffi_go_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*)) +{ + if (cif->abi != FFI_OSF) + return FFI_BAD_ABI; + + closure->tramp = (void *)ffi_go_closure_osf; + closure->cif = cif; + closure->fun = fun; + + return FFI_OK; +} + +long FFI_HIDDEN +ffi_closure_osf_inner (ffi_cif *cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *rvalue, unsigned long *argp) +{ + void **avalue; + ffi_type **arg_types; + long i, avn, argn, flags; + + avalue = alloca(cif->nargs * sizeof(void *)); + flags = cif->flags; + argn = 0; + + /* Copy the caller's structure return address to that the closure + returns the data directly to the caller. */ + if (flags == ALPHA_RET_IN_MEM) + { + rvalue = (void *) argp[0]; + argn = 1; + } + + arg_types = cif->arg_types; + + /* Grab the addresses of the arguments from the stack frame. */ + for (i = 0, avn = cif->nargs; i < avn; i++) + { + ffi_type *ty = arg_types[i]; + int type = ty->type; + void *valp = &argp[argn]; + size_t size; + + switch (type) + { + case FFI_TYPE_INT: + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_POINTER: + argn += 1; + break; + + case FFI_TYPE_VOID: + case FFI_TYPE_STRUCT: + size = ty->size; + argn += FFI_ALIGN(size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; + break; + + case FFI_TYPE_FLOAT: + /* Floats coming from registers need conversion from double + back to float format. */ + if (argn < 6) + { + valp = &argp[argn - 6]; + sts(valp, argp[argn - 6]); + } + argn += 1; + break; + + case FFI_TYPE_DOUBLE: + if (argn < 6) + valp = &argp[argn - 6]; + argn += 1; + break; + + case FFI_TYPE_LONGDOUBLE: + by_reference: + /* 128-bit long double is passed by reference. */ + valp = (void *)argp[argn]; + argn += 1; + break; + + case FFI_TYPE_COMPLEX: + type = ty->elements[0]->type; + switch (type) + { + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + /* Passed as separate arguments, but they wind up sequential. */ + break; + + case FFI_TYPE_INT: + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + /* Passed as separate arguments. Disjoint, but there's room + enough in one slot to hold the pair. */ + size = ty->elements[0]->size; + memcpy(valp + size, valp + 8, size); + break; + + case FFI_TYPE_FLOAT: + /* Passed as separate arguments. Disjoint, and each piece + may need conversion back to float. */ + if (argn < 6) + { + valp = &argp[argn - 6]; + sts(valp, argp[argn - 6]); + } + if (argn + 1 < 6) + sts(valp + 4, argp[argn + 1 - 6]); + else + *(UINT32 *)(valp + 4) = argp[argn + 1]; + break; + + case FFI_TYPE_DOUBLE: + /* Passed as separate arguments. Only disjoint if one part + is in fp regs and the other is on the stack. */ + if (argn < 5) + valp = &argp[argn - 6]; + else if (argn == 5) + { + valp = alloca(16); + ((UINT64 *)valp)[0] = argp[5 - 6]; + ((UINT64 *)valp)[1] = argp[6]; + } + break; + + case FFI_TYPE_LONGDOUBLE: + goto by_reference; + + default: + abort(); + } + argn += 2; + break; + + default: + abort (); + } + + avalue[i] = valp; + } + + /* Invoke the closure. */ + fun (cif, rvalue, avalue, user_data); + + /* Tell ffi_closure_osf how to perform return type promotions. */ + return (flags >> ALPHA_LD_SHIFT) & 0xff; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/ffitarget.h new file mode 100644 index 0000000..a02dbd0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/ffitarget.h @@ -0,0 +1,57 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 1996-2003 Red Hat, Inc. + Target configuration macros for Alpha. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_OSF, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_OSF +} ffi_abi; +#endif + +#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION +#define FFI_TARGET_HAS_COMPLEX_TYPE + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_GO_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 24 +#define FFI_NATIVE_RAW_API 0 + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/internal.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/internal.h new file mode 100644 index 0000000..44da192 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/internal.h @@ -0,0 +1,23 @@ +#define ALPHA_ST_VOID 0 +#define ALPHA_ST_INT 1 +#define ALPHA_ST_FLOAT 2 +#define ALPHA_ST_DOUBLE 3 +#define ALPHA_ST_CPLXF 4 +#define ALPHA_ST_CPLXD 5 + +#define ALPHA_LD_VOID 0 +#define ALPHA_LD_INT64 1 +#define ALPHA_LD_INT32 2 +#define ALPHA_LD_UINT16 3 +#define ALPHA_LD_SINT16 4 +#define ALPHA_LD_UINT8 5 +#define ALPHA_LD_SINT8 6 +#define ALPHA_LD_FLOAT 7 +#define ALPHA_LD_DOUBLE 8 +#define ALPHA_LD_CPLXF 9 +#define ALPHA_LD_CPLXD 10 + +#define ALPHA_ST_SHIFT 0 +#define ALPHA_LD_SHIFT 8 +#define ALPHA_RET_IN_MEM 0x10000 +#define ALPHA_FLAGS(S, L) (((L) << ALPHA_LD_SHIFT) | (S)) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/osf.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/osf.S new file mode 100644 index 0000000..b031828 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/alpha/osf.S @@ -0,0 +1,282 @@ +/* ----------------------------------------------------------------------- + osf.S - Copyright (c) 1998, 2001, 2007, 2008, 2011, 2014 Red Hat + + Alpha/OSF Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include +#include +#include "internal.h" + + .arch ev6 + .text + +/* Aid in building a direct addressed jump table, 4 insns per entry. */ +.macro E index + .align 4 + .org 99b + \index * 16 +.endm + +/* ffi_call_osf (void *stack, void *frame, unsigned flags, + void *raddr, void (*fnaddr)(void), void *closure) + + Bit o trickiness here -- FRAME is the base of the stack frame + for this function. This has been allocated by ffi_call. We also + deallocate some of the stack that has been alloca'd. */ + + .align 4 + .globl ffi_call_osf + .ent ffi_call_osf + FFI_HIDDEN(ffi_call_osf) + +ffi_call_osf: + cfi_startproc + cfi_def_cfa($17, 32) + mov $16, $30 + stq $26, 0($17) + stq $15, 8($17) + mov $17, $15 + .prologue 0 + cfi_def_cfa_register($15) + cfi_rel_offset($26, 0) + cfi_rel_offset($15, 8) + + stq $18, 16($17) # save flags into frame + stq $19, 24($17) # save rvalue into frame + mov $20, $27 # fn into place for call + mov $21, $1 # closure into static chain + + # Load up all of the (potential) argument registers. + ldq $16, 0($30) + ldt $f16, 0($30) + ldt $f17, 8($30) + ldq $17, 8($30) + ldt $f18, 16($30) + ldq $18, 16($30) + ldt $f19, 24($30) + ldq $19, 24($30) + ldt $f20, 32($30) + ldq $20, 32($30) + ldt $f21, 40($30) + ldq $21, 40($30) + + # Deallocate the register argument area. + lda $30, 48($30) + + jsr $26, ($27), 0 +0: + ldah $29, 0($26) !gpdisp!1 + ldq $2, 24($15) # reload rvalue + lda $29, 0($29) !gpdisp!1 + ldq $3, 16($15) # reload flags + lda $1, 99f-0b($26) + ldq $26, 0($15) + ldq $15, 8($15) + cfi_restore($26) + cfi_restore($15) + cfi_def_cfa($sp, 0) + cmoveq $2, ALPHA_ST_VOID, $3 # mash null rvalue to void + addq $3, $3, $3 + s8addq $3, $1, $1 # 99f + stcode * 16 + jmp $31, ($1), $st_int + + .align 4 +99: +E ALPHA_ST_VOID + ret +E ALPHA_ST_INT +$st_int: + stq $0, 0($2) + ret +E ALPHA_ST_FLOAT + sts $f0, 0($2) + ret +E ALPHA_ST_DOUBLE + stt $f0, 0($2) + ret +E ALPHA_ST_CPLXF + sts $f0, 0($2) + sts $f1, 4($2) + ret +E ALPHA_ST_CPLXD + stt $f0, 0($2) + stt $f1, 8($2) + ret + + cfi_endproc + .end ffi_call_osf + +/* ffi_closure_osf(...) + + Receives the closure argument in $1. */ + +#define CLOSURE_FS (16*8) + + .align 4 + .globl ffi_go_closure_osf + .ent ffi_go_closure_osf + FFI_HIDDEN(ffi_go_closure_osf) + +ffi_go_closure_osf: + cfi_startproc + ldgp $29, 0($27) + subq $30, CLOSURE_FS, $30 + cfi_adjust_cfa_offset(CLOSURE_FS) + stq $26, 0($30) + .prologue 1 + cfi_rel_offset($26, 0) + + stq $16, 10*8($30) + stq $17, 11*8($30) + stq $18, 12*8($30) + + ldq $16, 8($1) # load cif + ldq $17, 16($1) # load fun + mov $1, $18 # closure is user_data + br $do_closure + + cfi_endproc + .end ffi_go_closure_osf + + .align 4 + .globl ffi_closure_osf + .ent ffi_closure_osf + FFI_HIDDEN(ffi_closure_osf) + +ffi_closure_osf: + cfi_startproc + ldgp $29, 0($27) + subq $30, CLOSURE_FS, $30 + cfi_adjust_cfa_offset(CLOSURE_FS) + stq $26, 0($30) + .prologue 1 + cfi_rel_offset($26, 0) + + # Store all of the potential argument registers in va_list format. + stq $16, 10*8($30) + stq $17, 11*8($30) + stq $18, 12*8($30) + + ldq $16, 24($1) # load cif + ldq $17, 32($1) # load fun + ldq $18, 40($1) # load user_data + +$do_closure: + stq $19, 13*8($30) + stq $20, 14*8($30) + stq $21, 15*8($30) + stt $f16, 4*8($30) + stt $f17, 5*8($30) + stt $f18, 6*8($30) + stt $f19, 7*8($30) + stt $f20, 8*8($30) + stt $f21, 9*8($30) + + # Call ffi_closure_osf_inner to do the bulk of the work. + lda $19, 2*8($30) + lda $20, 10*8($30) + jsr $26, ffi_closure_osf_inner +0: + ldah $29, 0($26) !gpdisp!2 + lda $2, 99f-0b($26) + s4addq $0, 0, $1 # ldcode * 4 + ldq $0, 16($30) # preload return value + s4addq $1, $2, $1 # 99f + ldcode * 16 + lda $29, 0($29) !gpdisp!2 + ldq $26, 0($30) + cfi_restore($26) + jmp $31, ($1), $load_32 + +.macro epilogue + addq $30, CLOSURE_FS, $30 + cfi_adjust_cfa_offset(-CLOSURE_FS) + ret + .align 4 + cfi_adjust_cfa_offset(CLOSURE_FS) +.endm + + .align 4 +99: +E ALPHA_LD_VOID + epilogue + +E ALPHA_LD_INT64 + epilogue + +E ALPHA_LD_INT32 +$load_32: + sextl $0, $0 + epilogue + +E ALPHA_LD_UINT16 + zapnot $0, 3, $0 + epilogue + +E ALPHA_LD_SINT16 +#ifdef __alpha_bwx__ + sextw $0, $0 +#else + sll $0, 48, $0 + sra $0, 48, $0 +#endif + epilogue + +E ALPHA_LD_UINT8 + and $0, 0xff, $0 + epilogue + +E ALPHA_LD_SINT8 +#ifdef __alpha_bwx__ + sextb $0, $0 +#else + sll $0, 56, $0 + sra $0, 56, $0 +#endif + epilogue + +E ALPHA_LD_FLOAT + lds $f0, 16($sp) + epilogue + +E ALPHA_LD_DOUBLE + ldt $f0, 16($sp) + epilogue + +E ALPHA_LD_CPLXF + lds $f0, 16($sp) + lds $f1, 20($sp) + epilogue + +E ALPHA_LD_CPLXD + ldt $f0, 16($sp) + ldt $f1, 24($sp) + epilogue + + cfi_endproc + .end ffi_closure_osf + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arc/arcompact.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arc/arcompact.S new file mode 100644 index 0000000..03715fd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arc/arcompact.S @@ -0,0 +1,135 @@ +/* ----------------------------------------------------------------------- + arcompact.S - Copyright (c) 2013 Synposys, Inc. (www.synopsys.com) + + ARCompact Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL RENESAS TECHNOLOGY BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include +#ifdef HAVE_MACHINE_ASM_H +#include +#else +#define CNAME(x) x +#define ENTRY(x) .globl CNAME(x)` .type CNAME(x),%function` CNAME(x): +#endif + +.text + + /* R0: ffi_prep_args */ + /* R1: &ecif */ + /* R2: cif->bytes */ + /* R3: fig->flags */ + /* R4: ecif.rvalue */ + /* R5: fn */ +ENTRY(ffi_call_ARCompact) + /* Save registers. */ + st.a fp, [sp, -4] /* fp + 20, fp */ + push_s blink /* fp + 16, blink */ + st.a r4, [sp, -4] /* fp + 12, ecif.rvalue */ + push_s r3 /* fp + 8, fig->flags */ + st.a r5, [sp, -4] /* fp + 4, fn */ + push_s r2 /* fp + 0, cif->bytes */ + mov fp, sp + + /* Make room for all of the new args. */ + sub sp, sp, r2 + + /* Place all of the ffi_prep_args in position. */ + /* ffi_prep_args(char *stack, extended_cif *ecif) */ + /* R1 already set. */ + + /* And call. */ + jl_s.d [r0] + mov_s r0, sp + + ld.ab r12, [fp, 4] /* cif->bytes */ + ld.ab r11, [fp, 4] /* fn */ + + /* Move first 8 parameters in registers... */ + ld_s r0, [sp] + ld_s r1, [sp, 4] + ld_s r2, [sp, 8] + ld_s r3, [sp, 12] + ld r4, [sp, 16] + ld r5, [sp, 20] + ld r6, [sp, 24] + ld r7, [sp, 28] + + /* ...and adjust the stack. */ + min r12, r12, 32 + + /* Call the function. */ + jl.d [r11] + add sp, sp, r12 + + mov sp, fp + pop_s r3 /* fig->flags, return type */ + pop_s r2 /* ecif.rvalue, pointer for return value */ + + /* If the return value pointer is NULL, assume no return value. */ + breq.d r2, 0, epilogue + pop_s blink + + /* Return INT. */ + brne r3, FFI_TYPE_INT, return_double + b.d epilogue + st_s r0, [r2] + +return_double: + brne r3, FFI_TYPE_DOUBLE, epilogue + st_s r0, [r2] + st_s r1, [r2,4] + +epilogue: + j_s.d [blink] + ld.ab fp, [sp, 4] + +ENTRY(ffi_closure_ARCompact) + st.a r0, [sp, -32] + st_s r1, [sp, 4] + st_s r2, [sp, 8] + st_s r3, [sp, 12] + st r4, [sp, 16] + st r5, [sp, 20] + st r6, [sp, 24] + st r7, [sp, 28] + + /* pointer to arguments */ + mov_s r2, sp + + /* return value goes here */ + sub sp, sp, 8 + mov_s r1, sp + + push_s blink + + bl.d ffi_closure_inner_ARCompact + mov_s r0, r8 /* codeloc, set by trampoline */ + + pop_s blink + + /* set return value to r1:r0 */ + pop_s r0 + pop_s r1 + j_s.d [blink] + add_s sp, sp, 32 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arc/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arc/ffi.c new file mode 100644 index 0000000..4d10b21 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arc/ffi.c @@ -0,0 +1,266 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2013 Synopsys, Inc. (www.synopsys.com) + + ARC Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL RENESAS TECHNOLOGY BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include +#include + +#include + +/* for little endian ARC, the code is in fact stored as mixed endian for + performance reasons */ +#if __BIG_ENDIAN__ +#define CODE_ENDIAN(x) (x) +#else +#define CODE_ENDIAN(x) ( (((uint32_t) (x)) << 16) | (((uint32_t) (x)) >> 16)) +#endif + +/* ffi_prep_args is called by the assembly routine once stack + space has been allocated for the function's arguments. */ + +void +ffi_prep_args (char *stack, extended_cif * ecif) +{ + unsigned int i; + void **p_argv; + char *argp; + ffi_type **p_arg; + + argp = stack; + + if (ecif->cif->rtype->type == FFI_TYPE_STRUCT) + { + *(void **) argp = ecif->rvalue; + argp += 4; + } + + p_argv = ecif->avalue; + + for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; + (i != 0); i--, p_arg++) + { + size_t z; + int alignment; + + /* align alignment to 4 */ + alignment = (((*p_arg)->alignment - 1) | 3) + 1; + + /* Align if necessary. */ + if ((alignment - 1) & (unsigned) argp) + argp = (char *) FFI_ALIGN (argp, alignment); + + z = (*p_arg)->size; + if (z < sizeof (int)) + { + z = sizeof (int); + + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int) *(SINT8 *) (*p_argv); + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int) *(UINT8 *) (*p_argv); + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int) *(SINT16 *) (*p_argv); + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int) *(UINT16 *) (*p_argv); + break; + + case FFI_TYPE_STRUCT: + memcpy (argp, *p_argv, (*p_arg)->size); + break; + + default: + FFI_ASSERT (0); + } + } + else if (z == sizeof (int)) + { + *(unsigned int *) argp = (unsigned int) *(UINT32 *) (*p_argv); + } + else + { + if ((*p_arg)->type == FFI_TYPE_STRUCT) + { + memcpy (argp, *p_argv, z); + } + else + { + /* Double or long long 64bit. */ + memcpy (argp, *p_argv, z); + } + } + p_argv++; + argp += z; + } + + return; +} + +/* Perform machine dependent cif processing. */ +ffi_status +ffi_prep_cif_machdep (ffi_cif * cif) +{ + /* Set the return type flag. */ + switch (cif->rtype->type) + { + case FFI_TYPE_VOID: + cif->flags = (unsigned) cif->rtype->type; + break; + + case FFI_TYPE_STRUCT: + cif->flags = (unsigned) cif->rtype->type; + break; + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_DOUBLE: + cif->flags = FFI_TYPE_DOUBLE; + break; + + case FFI_TYPE_FLOAT: + default: + cif->flags = FFI_TYPE_INT; + break; + } + + return FFI_OK; +} + +extern void ffi_call_ARCompact (void (*)(char *, extended_cif *), + extended_cif *, unsigned, unsigned, + unsigned *, void (*fn) (void)); + +void +ffi_call (ffi_cif * cif, void (*fn) (void), void *rvalue, void **avalue) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have + a return value address then we need to make one. */ + if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) + { + ecif.rvalue = alloca (cif->rtype->size); + } + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_ARCOMPACT: + ffi_call_ARCompact (ffi_prep_args, &ecif, cif->bytes, + cif->flags, ecif.rvalue, fn); + break; + + default: + FFI_ASSERT (0); + break; + } +} + +int +ffi_closure_inner_ARCompact (ffi_closure * closure, void *rvalue, + ffi_arg * args) +{ + void **arg_area, **p_argv; + ffi_cif *cif = closure->cif; + char *argp = (char *) args; + ffi_type **p_argt; + int i; + + arg_area = (void **) alloca (cif->nargs * sizeof (void *)); + + /* handle hidden argument */ + if (cif->flags == FFI_TYPE_STRUCT) + { + rvalue = *(void **) argp; + argp += 4; + } + + p_argv = arg_area; + + for (i = 0, p_argt = cif->arg_types; i < cif->nargs; + i++, p_argt++, p_argv++) + { + size_t z; + int alignment; + + /* align alignment to 4 */ + alignment = (((*p_argt)->alignment - 1) | 3) + 1; + + /* Align if necessary. */ + if ((alignment - 1) & (unsigned) argp) + argp = (char *) FFI_ALIGN (argp, alignment); + + z = (*p_argt)->size; + *p_argv = (void *) argp; + argp += z; + } + + (closure->fun) (cif, rvalue, arg_area, closure->user_data); + + return cif->flags; +} + +extern void ffi_closure_ARCompact (void); + +ffi_status +ffi_prep_closure_loc (ffi_closure * closure, ffi_cif * cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, void *codeloc) +{ + uint32_t *tramp = (uint32_t *) & (closure->tramp[0]); + + switch (cif->abi) + { + case FFI_ARCOMPACT: + FFI_ASSERT (tramp == codeloc); + tramp[0] = CODE_ENDIAN (0x200a1fc0); /* mov r8, pcl */ + tramp[1] = CODE_ENDIAN (0x20200f80); /* j [long imm] */ + tramp[2] = CODE_ENDIAN (ffi_closure_ARCompact); + break; + + default: + return FFI_BAD_ABI; + } + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + cacheflush (codeloc, FFI_TRAMPOLINE_SIZE, BCACHE); + + return FFI_OK; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arc/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arc/ffitarget.h new file mode 100644 index 0000000..bf8311b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arc/ffitarget.h @@ -0,0 +1,53 @@ +/* ----------------------------------------------------------------------- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 2013 Synopsys, Inc. (www.synopsys.com) + Target configuration macros for ARC. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL RENESAS TECHNOLOGY BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +/* ---- Generic type definitions ----------------------------------------- */ + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi +{ + FFI_FIRST_ABI = 0, + FFI_ARCOMPACT, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_ARCOMPACT +} ffi_abi; +#endif + +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 12 +#define FFI_NATIVE_RAW_API 0 + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/ffi.c new file mode 100644 index 0000000..0058390 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/ffi.c @@ -0,0 +1,876 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2011 Timothy Wall + Copyright (c) 2011 Plausible Labs Cooperative, Inc. + Copyright (c) 2011 Anthony Green + Copyright (c) 2011 Free Software Foundation + Copyright (c) 1998, 2008, 2011 Red Hat, Inc. + + ARM Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#if defined(__arm__) || defined(_M_ARM) +#include +#include +#include +#include +#include +#include "internal.h" + +#if defined(_MSC_VER) && defined(_M_ARM) +#define WIN32_LEAN_AND_MEAN +#include +#endif + +#if FFI_EXEC_TRAMPOLINE_TABLE + +#ifdef __MACH__ +#include +#endif + +#else +#ifndef _M_ARM +extern unsigned int ffi_arm_trampoline[2] FFI_HIDDEN; +#else +extern unsigned int ffi_arm_trampoline[3] FFI_HIDDEN; +#endif +#endif + +#if defined(__FreeBSD__) && defined(__arm__) +#include +#include +#endif + +/* Forward declares. */ +static int vfp_type_p (const ffi_type *); +static void layout_vfp_args (ffi_cif *); + +static void * +ffi_align (ffi_type *ty, void *p) +{ + /* Align if necessary */ + size_t alignment; +#ifdef _WIN32_WCE + alignment = 4; +#else + alignment = ty->alignment; + if (alignment < 4) + alignment = 4; +#endif + return (void *) FFI_ALIGN (p, alignment); +} + +static size_t +ffi_put_arg (ffi_type *ty, void *src, void *dst) +{ + size_t z = ty->size; + + switch (ty->type) + { + case FFI_TYPE_SINT8: + *(UINT32 *)dst = *(SINT8 *)src; + break; + case FFI_TYPE_UINT8: + *(UINT32 *)dst = *(UINT8 *)src; + break; + case FFI_TYPE_SINT16: + *(UINT32 *)dst = *(SINT16 *)src; + break; + case FFI_TYPE_UINT16: + *(UINT32 *)dst = *(UINT16 *)src; + break; + + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_POINTER: +#ifndef _MSC_VER + case FFI_TYPE_FLOAT: +#endif + *(UINT32 *)dst = *(UINT32 *)src; + break; + +#ifdef _MSC_VER + // casting a float* to a UINT32* doesn't work on Windows + case FFI_TYPE_FLOAT: + *(uintptr_t *)dst = 0; + *(float *)dst = *(float *)src; + break; +#endif + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_DOUBLE: + *(UINT64 *)dst = *(UINT64 *)src; + break; + + case FFI_TYPE_STRUCT: + case FFI_TYPE_COMPLEX: + memcpy (dst, src, z); + break; + + default: + abort(); + } + + return FFI_ALIGN (z, 4); +} + +/* ffi_prep_args is called once stack space has been allocated + for the function's arguments. + + The vfp_space parameter is the load area for VFP regs, the return + value is cif->vfp_used (word bitset of VFP regs used for passing + arguments). These are only used for the VFP hard-float ABI. +*/ +static void +ffi_prep_args_SYSV (ffi_cif *cif, int flags, void *rvalue, + void **avalue, char *argp) +{ + ffi_type **arg_types = cif->arg_types; + int i, n; + + if (flags == ARM_TYPE_STRUCT) + { + *(void **) argp = rvalue; + argp += 4; + } + + for (i = 0, n = cif->nargs; i < n; i++) + { + ffi_type *ty = arg_types[i]; + argp = ffi_align (ty, argp); + argp += ffi_put_arg (ty, avalue[i], argp); + } +} + +static void +ffi_prep_args_VFP (ffi_cif *cif, int flags, void *rvalue, + void **avalue, char *stack, char *vfp_space) +{ + ffi_type **arg_types = cif->arg_types; + int i, n, vi = 0; + char *argp, *regp, *eo_regp; + char stack_used = 0; + char done_with_regs = 0; + + /* The first 4 words on the stack are used for values + passed in core registers. */ + regp = stack; + eo_regp = argp = regp + 16; + + /* If the function returns an FFI_TYPE_STRUCT in memory, + that address is passed in r0 to the function. */ + if (flags == ARM_TYPE_STRUCT) + { + *(void **) regp = rvalue; + regp += 4; + } + + for (i = 0, n = cif->nargs; i < n; i++) + { + ffi_type *ty = arg_types[i]; + void *a = avalue[i]; + int is_vfp_type = vfp_type_p (ty); + + /* Allocated in VFP registers. */ + if (vi < cif->vfp_nargs && is_vfp_type) + { + char *vfp_slot = vfp_space + cif->vfp_args[vi++] * 4; + ffi_put_arg (ty, a, vfp_slot); + continue; + } + /* Try allocating in core registers. */ + else if (!done_with_regs && !is_vfp_type) + { + char *tregp = ffi_align (ty, regp); + size_t size = ty->size; + size = (size < 4) ? 4 : size; // pad + /* Check if there is space left in the aligned register + area to place the argument. */ + if (tregp + size <= eo_regp) + { + regp = tregp + ffi_put_arg (ty, a, tregp); + done_with_regs = (regp == argp); + // ensure we did not write into the stack area + FFI_ASSERT (regp <= argp); + continue; + } + /* In case there are no arguments in the stack area yet, + the argument is passed in the remaining core registers + and on the stack. */ + else if (!stack_used) + { + stack_used = 1; + done_with_regs = 1; + argp = tregp + ffi_put_arg (ty, a, tregp); + FFI_ASSERT (eo_regp < argp); + continue; + } + } + /* Base case, arguments are passed on the stack */ + stack_used = 1; + argp = ffi_align (ty, argp); + argp += ffi_put_arg (ty, a, argp); + } +} + +/* Perform machine dependent cif processing */ +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep (ffi_cif *cif) +{ + int flags = 0, cabi = cif->abi; + size_t bytes = cif->bytes; + + /* Map out the register placements of VFP register args. The VFP + hard-float calling conventions are slightly more sophisticated + than the base calling conventions, so we do it here instead of + in ffi_prep_args(). */ + if (cabi == FFI_VFP) + layout_vfp_args (cif); + + /* Set the return type flag */ + switch (cif->rtype->type) + { + case FFI_TYPE_VOID: + flags = ARM_TYPE_VOID; + break; + + case FFI_TYPE_INT: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_POINTER: + flags = ARM_TYPE_INT; + break; + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + flags = ARM_TYPE_INT64; + break; + + case FFI_TYPE_FLOAT: + flags = (cabi == FFI_VFP ? ARM_TYPE_VFP_S : ARM_TYPE_INT); + break; + case FFI_TYPE_DOUBLE: + flags = (cabi == FFI_VFP ? ARM_TYPE_VFP_D : ARM_TYPE_INT64); + break; + + case FFI_TYPE_STRUCT: + case FFI_TYPE_COMPLEX: + if (cabi == FFI_VFP) + { + int h = vfp_type_p (cif->rtype); + + flags = ARM_TYPE_VFP_N; + if (h == 0x100 + FFI_TYPE_FLOAT) + flags = ARM_TYPE_VFP_S; + if (h == 0x100 + FFI_TYPE_DOUBLE) + flags = ARM_TYPE_VFP_D; + if (h != 0) + break; + } + + /* A Composite Type not larger than 4 bytes is returned in r0. + A Composite Type larger than 4 bytes, or whose size cannot + be determined statically ... is stored in memory at an + address passed [in r0]. */ + if (cif->rtype->size <= 4) + flags = ARM_TYPE_INT; + else + { + flags = ARM_TYPE_STRUCT; + bytes += 4; + } + break; + + default: + abort(); + } + + /* Round the stack up to a multiple of 8 bytes. This isn't needed + everywhere, but it is on some platforms, and it doesn't harm anything + when it isn't needed. */ + bytes = FFI_ALIGN (bytes, 8); + + /* Minimum stack space is the 4 register arguments that we pop. */ + if (bytes < 4*4) + bytes = 4*4; + + cif->bytes = bytes; + cif->flags = flags; + + return FFI_OK; +} + +/* Perform machine dependent cif processing for variadic calls */ +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep_var (ffi_cif * cif, + unsigned int nfixedargs, unsigned int ntotalargs) +{ + /* VFP variadic calls actually use the SYSV ABI */ + if (cif->abi == FFI_VFP) + cif->abi = FFI_SYSV; + + return ffi_prep_cif_machdep (cif); +} + +/* Prototypes for assembly functions, in sysv.S. */ + +struct call_frame +{ + void *fp; + void *lr; + void *rvalue; + int flags; + void *closure; +}; + +extern void ffi_call_SYSV (void *stack, struct call_frame *, + void (*fn) (void)) FFI_HIDDEN; +extern void ffi_call_VFP (void *vfp_space, struct call_frame *, + void (*fn) (void), unsigned vfp_used) FFI_HIDDEN; + +static void +ffi_call_int (ffi_cif * cif, void (*fn) (void), void *rvalue, + void **avalue, void *closure) +{ + int flags = cif->flags; + ffi_type *rtype = cif->rtype; + size_t bytes, rsize, vfp_size; + char *stack, *vfp_space, *new_rvalue; + struct call_frame *frame; + + rsize = 0; + if (rvalue == NULL) + { + /* If the return value is a struct and we don't have a return + value address then we need to make one. Otherwise the return + value is in registers and we can ignore them. */ + if (flags == ARM_TYPE_STRUCT) + rsize = rtype->size; + else + flags = ARM_TYPE_VOID; + } + else if (flags == ARM_TYPE_VFP_N) + { + /* Largest case is double x 4. */ + rsize = 32; + } + else if (flags == ARM_TYPE_INT && rtype->type == FFI_TYPE_STRUCT) + rsize = 4; + + /* Largest case. */ + vfp_size = (cif->abi == FFI_VFP && cif->vfp_used ? 8*8: 0); + + bytes = cif->bytes; + stack = alloca (vfp_size + bytes + sizeof(struct call_frame) + rsize); + + vfp_space = NULL; + if (vfp_size) + { + vfp_space = stack; + stack += vfp_size; + } + + frame = (struct call_frame *)(stack + bytes); + + new_rvalue = rvalue; + if (rsize) + new_rvalue = (void *)(frame + 1); + + frame->rvalue = new_rvalue; + frame->flags = flags; + frame->closure = closure; + + if (vfp_space) + { + ffi_prep_args_VFP (cif, flags, new_rvalue, avalue, stack, vfp_space); + ffi_call_VFP (vfp_space, frame, fn, cif->vfp_used); + } + else + { + ffi_prep_args_SYSV (cif, flags, new_rvalue, avalue, stack); + ffi_call_SYSV (stack, frame, fn); + } + + if (rvalue && rvalue != new_rvalue) + memcpy (rvalue, new_rvalue, rtype->size); +} + +void +ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue) +{ + ffi_call_int (cif, fn, rvalue, avalue, NULL); +} + +#ifdef FFI_GO_CLOSURES +void +ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue, + void **avalue, void *closure) +{ + ffi_call_int (cif, fn, rvalue, avalue, closure); +} +#endif + +static void * +ffi_prep_incoming_args_SYSV (ffi_cif *cif, void *rvalue, + char *argp, void **avalue) +{ + ffi_type **arg_types = cif->arg_types; + int i, n; + + if (cif->flags == ARM_TYPE_STRUCT) + { + rvalue = *(void **) argp; + argp += 4; + } + else + { + if (cif->rtype->size && cif->rtype->size < 4) + *(uint32_t *) rvalue = 0; + } + + for (i = 0, n = cif->nargs; i < n; i++) + { + ffi_type *ty = arg_types[i]; + size_t z = ty->size; + + argp = ffi_align (ty, argp); + avalue[i] = (void *) argp; + argp += z; + } + + return rvalue; +} + +static void * +ffi_prep_incoming_args_VFP (ffi_cif *cif, void *rvalue, char *stack, + char *vfp_space, void **avalue) +{ + ffi_type **arg_types = cif->arg_types; + int i, n, vi = 0; + char *argp, *regp, *eo_regp; + char done_with_regs = 0; + char stack_used = 0; + + regp = stack; + eo_regp = argp = regp + 16; + + if (cif->flags == ARM_TYPE_STRUCT) + { + rvalue = *(void **) regp; + regp += 4; + } + + for (i = 0, n = cif->nargs; i < n; i++) + { + ffi_type *ty = arg_types[i]; + int is_vfp_type = vfp_type_p (ty); + size_t z = ty->size; + + if (vi < cif->vfp_nargs && is_vfp_type) + { + avalue[i] = vfp_space + cif->vfp_args[vi++] * 4; + continue; + } + else if (!done_with_regs && !is_vfp_type) + { + char *tregp = ffi_align (ty, regp); + + z = (z < 4) ? 4 : z; // pad + + /* If the arguments either fits into the registers or uses registers + and stack, while we haven't read other things from the stack */ + if (tregp + z <= eo_regp || !stack_used) + { + /* Because we're little endian, this is what it turns into. */ + avalue[i] = (void *) tregp; + regp = tregp + z; + + /* If we read past the last core register, make sure we + have not read from the stack before and continue + reading after regp. */ + if (regp > eo_regp) + { + FFI_ASSERT (!stack_used); + argp = regp; + } + if (regp >= eo_regp) + { + done_with_regs = 1; + stack_used = 1; + } + continue; + } + } + + stack_used = 1; + argp = ffi_align (ty, argp); + avalue[i] = (void *) argp; + argp += z; + } + + return rvalue; +} + +struct closure_frame +{ + char vfp_space[8*8] __attribute__((aligned(8))); + char result[8*4]; + char argp[]; +}; + +int FFI_HIDDEN +ffi_closure_inner_SYSV (ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + struct closure_frame *frame) +{ + void **avalue = (void **) alloca (cif->nargs * sizeof (void *)); + void *rvalue = ffi_prep_incoming_args_SYSV (cif, frame->result, + frame->argp, avalue); + fun (cif, rvalue, avalue, user_data); + return cif->flags; +} + +int FFI_HIDDEN +ffi_closure_inner_VFP (ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + struct closure_frame *frame) +{ + void **avalue = (void **) alloca (cif->nargs * sizeof (void *)); + void *rvalue = ffi_prep_incoming_args_VFP (cif, frame->result, frame->argp, + frame->vfp_space, avalue); + fun (cif, rvalue, avalue, user_data); + return cif->flags; +} + +void ffi_closure_SYSV (void) FFI_HIDDEN; +void ffi_closure_VFP (void) FFI_HIDDEN; + +#ifdef FFI_GO_CLOSURES +void ffi_go_closure_SYSV (void) FFI_HIDDEN; +void ffi_go_closure_VFP (void) FFI_HIDDEN; +#endif + +/* the cif must already be prep'ed */ + +#if defined(__FreeBSD__) && defined(__arm__) +#define __clear_cache(start, end) do { \ + struct arm_sync_icache_args ua; \ + \ + ua.addr = (uintptr_t)(start); \ + ua.len = (char *)(end) - (char *)start; \ + sysarch(ARM_SYNC_ICACHE, &ua); \ + } while (0); +#endif + +ffi_status +ffi_prep_closure_loc (ffi_closure * closure, + ffi_cif * cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, void *codeloc) +{ + void (*closure_func) (void) = ffi_closure_SYSV; + + if (cif->abi == FFI_VFP) + { + /* We only need take the vfp path if there are vfp arguments. */ + if (cif->vfp_used) + closure_func = ffi_closure_VFP; + } + else if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + +#if FFI_EXEC_TRAMPOLINE_TABLE + void **config = (void **)((uint8_t *)codeloc - PAGE_MAX_SIZE); + config[0] = closure; + config[1] = closure_func; +#else + +#ifndef _M_ARM + memcpy(closure->tramp, ffi_arm_trampoline, 8); +#else + // cast away function type so MSVC doesn't set the lower bit of the function pointer + memcpy(closure->tramp, (void*)((uintptr_t)ffi_arm_trampoline & 0xFFFFFFFE), FFI_TRAMPOLINE_CLOSURE_OFFSET); +#endif + +#if defined (__QNX__) + msync(closure->tramp, 8, 0x1000000); /* clear data map */ + msync(codeloc, 8, 0x1000000); /* clear insn map */ +#elif defined(_MSC_VER) + FlushInstructionCache(GetCurrentProcess(), closure->tramp, FFI_TRAMPOLINE_SIZE); +#else + __clear_cache(closure->tramp, closure->tramp + 8); /* clear data map */ + __clear_cache(codeloc, codeloc + 8); /* clear insn map */ +#endif +#ifdef _M_ARM + *(void(**)(void))(closure->tramp + FFI_TRAMPOLINE_CLOSURE_FUNCTION) = closure_func; +#else + *(void (**)(void))(closure->tramp + 8) = closure_func; +#endif +#endif + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + return FFI_OK; +} + +#ifdef FFI_GO_CLOSURES +ffi_status +ffi_prep_go_closure (ffi_go_closure *closure, ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *)) +{ + void (*closure_func) (void) = ffi_go_closure_SYSV; + + if (cif->abi == FFI_VFP) + { + /* We only need take the vfp path if there are vfp arguments. */ + if (cif->vfp_used) + closure_func = ffi_go_closure_VFP; + } + else if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + closure->tramp = closure_func; + closure->cif = cif; + closure->fun = fun; + + return FFI_OK; +} +#endif + +/* Below are routines for VFP hard-float support. */ + +/* A subroutine of vfp_type_p. Given a structure type, return the type code + of the first non-structure element. Recurse for structure elements. + Return -1 if the structure is in fact empty, i.e. no nested elements. */ + +static int +is_hfa0 (const ffi_type *ty) +{ + ffi_type **elements = ty->elements; + int i, ret = -1; + + if (elements != NULL) + for (i = 0; elements[i]; ++i) + { + ret = elements[i]->type; + if (ret == FFI_TYPE_STRUCT || ret == FFI_TYPE_COMPLEX) + { + ret = is_hfa0 (elements[i]); + if (ret < 0) + continue; + } + break; + } + + return ret; +} + +/* A subroutine of vfp_type_p. Given a structure type, return true if all + of the non-structure elements are the same as CANDIDATE. */ + +static int +is_hfa1 (const ffi_type *ty, int candidate) +{ + ffi_type **elements = ty->elements; + int i; + + if (elements != NULL) + for (i = 0; elements[i]; ++i) + { + int t = elements[i]->type; + if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX) + { + if (!is_hfa1 (elements[i], candidate)) + return 0; + } + else if (t != candidate) + return 0; + } + + return 1; +} + +/* Determine if TY is an homogenous floating point aggregate (HFA). + That is, a structure consisting of 1 to 4 members of all the same type, + where that type is a floating point scalar. + + Returns non-zero iff TY is an HFA. The result is an encoded value where + bits 0-7 contain the type code, and bits 8-10 contain the element count. */ + +static int +vfp_type_p (const ffi_type *ty) +{ + ffi_type **elements; + int candidate, i; + size_t size, ele_count; + + /* Quickest tests first. */ + candidate = ty->type; + switch (ty->type) + { + default: + return 0; + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + ele_count = 1; + goto done; + case FFI_TYPE_COMPLEX: + candidate = ty->elements[0]->type; + if (candidate != FFI_TYPE_FLOAT && candidate != FFI_TYPE_DOUBLE) + return 0; + ele_count = 2; + goto done; + case FFI_TYPE_STRUCT: + break; + } + + /* No HFA types are smaller than 4 bytes, or larger than 32 bytes. */ + size = ty->size; + if (size < 4 || size > 32) + return 0; + + /* Find the type of the first non-structure member. */ + elements = ty->elements; + candidate = elements[0]->type; + if (candidate == FFI_TYPE_STRUCT || candidate == FFI_TYPE_COMPLEX) + { + for (i = 0; ; ++i) + { + candidate = is_hfa0 (elements[i]); + if (candidate >= 0) + break; + } + } + + /* If the first member is not a floating point type, it's not an HFA. + Also quickly re-check the size of the structure. */ + switch (candidate) + { + case FFI_TYPE_FLOAT: + ele_count = size / sizeof(float); + if (size != ele_count * sizeof(float)) + return 0; + break; + case FFI_TYPE_DOUBLE: + ele_count = size / sizeof(double); + if (size != ele_count * sizeof(double)) + return 0; + break; + default: + return 0; + } + if (ele_count > 4) + return 0; + + /* Finally, make sure that all scalar elements are the same type. */ + for (i = 0; elements[i]; ++i) + { + int t = elements[i]->type; + if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX) + { + if (!is_hfa1 (elements[i], candidate)) + return 0; + } + else if (t != candidate) + return 0; + } + + /* All tests succeeded. Encode the result. */ + done: + return (ele_count << 8) | candidate; +} + +static int +place_vfp_arg (ffi_cif *cif, int h) +{ + unsigned short reg = cif->vfp_reg_free; + int align = 1, nregs = h >> 8; + + if ((h & 0xff) == FFI_TYPE_DOUBLE) + align = 2, nregs *= 2; + + /* Align register number. */ + if ((reg & 1) && align == 2) + reg++; + + while (reg + nregs <= 16) + { + int s, new_used = 0; + for (s = reg; s < reg + nregs; s++) + { + new_used |= (1 << s); + if (cif->vfp_used & (1 << s)) + { + reg += align; + goto next_reg; + } + } + /* Found regs to allocate. */ + cif->vfp_used |= new_used; + cif->vfp_args[cif->vfp_nargs++] = (signed char)reg; + + /* Update vfp_reg_free. */ + if (cif->vfp_used & (1 << cif->vfp_reg_free)) + { + reg += nregs; + while (cif->vfp_used & (1 << reg)) + reg += 1; + cif->vfp_reg_free = reg; + } + return 0; + next_reg:; + } + // done, mark all regs as used + cif->vfp_reg_free = 16; + cif->vfp_used = 0xFFFF; + return 1; +} + +static void +layout_vfp_args (ffi_cif * cif) +{ + unsigned int i; + /* Init VFP fields */ + cif->vfp_used = 0; + cif->vfp_nargs = 0; + cif->vfp_reg_free = 0; + memset (cif->vfp_args, -1, 16); /* Init to -1. */ + + for (i = 0; i < cif->nargs; i++) + { + int h = vfp_type_p (cif->arg_types[i]); + if (h && place_vfp_arg (cif, h) == 1) + break; + } +} + +#endif /* __arm__ or _M_ARM */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/ffitarget.h new file mode 100644 index 0000000..cb57b84 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/ffitarget.h @@ -0,0 +1,89 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 2010 CodeSourcery + Copyright (c) 1996-2003 Red Hat, Inc. + + Target configuration macros for ARM. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_VFP, + FFI_LAST_ABI, +#if defined(__ARM_PCS_VFP) || defined(_M_ARM) + FFI_DEFAULT_ABI = FFI_VFP, +#else + FFI_DEFAULT_ABI = FFI_SYSV, +#endif +} ffi_abi; +#endif + +#define FFI_EXTRA_CIF_FIELDS \ + int vfp_used; \ + unsigned short vfp_reg_free, vfp_nargs; \ + signed char vfp_args[16] \ + +#define FFI_TARGET_SPECIFIC_VARIADIC +#ifndef _M_ARM +#define FFI_TARGET_HAS_COMPLEX_TYPE +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_GO_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 + +#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE + +#ifdef __MACH__ +#define FFI_TRAMPOLINE_SIZE 12 +#define FFI_TRAMPOLINE_CLOSURE_OFFSET 8 +#else +#error "No trampoline table implementation" +#endif + +#else +#ifdef _MSC_VER +#define FFI_TRAMPOLINE_SIZE 16 +#define FFI_TRAMPOLINE_CLOSURE_FUNCTION 12 +#else +#define FFI_TRAMPOLINE_SIZE 12 +#endif +#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE +#endif + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/internal.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/internal.h new file mode 100644 index 0000000..6cf0b2a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/internal.h @@ -0,0 +1,7 @@ +#define ARM_TYPE_VFP_S 0 +#define ARM_TYPE_VFP_D 1 +#define ARM_TYPE_VFP_N 2 +#define ARM_TYPE_INT64 3 +#define ARM_TYPE_INT 4 +#define ARM_TYPE_VOID 5 +#define ARM_TYPE_STRUCT 6 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/sysv.S new file mode 100644 index 0000000..74bc53f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/sysv.S @@ -0,0 +1,385 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 1998, 2008, 2011 Red Hat, Inc. + Copyright (c) 2011 Plausible Labs Cooperative, Inc. + + ARM Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#ifdef __arm__ +#define LIBFFI_ASM +#include +#include +#include +#include "internal.h" + +/* GCC 4.8 provides __ARM_ARCH; construct it otherwise. */ +#ifndef __ARM_ARCH +# if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \ + || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \ + || defined(__ARM_ARCH_7EM__) +# define __ARM_ARCH 7 +# elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \ + || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) \ + || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) \ + || defined(__ARM_ARCH_6M__) +# define __ARM_ARCH 6 +# elif defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) \ + || defined(__ARM_ARCH_5E__) || defined(__ARM_ARCH_5TE__) \ + || defined(__ARM_ARCH_5TEJ__) +# define __ARM_ARCH 5 +# else +# define __ARM_ARCH 4 +# endif +#endif + +/* Conditionally compile unwinder directives. */ +#ifdef __ARM_EABI__ +# define UNWIND(...) __VA_ARGS__ +#else +# define UNWIND(...) +#endif + +#if defined(HAVE_AS_CFI_PSEUDO_OP) && defined(__ARM_EABI__) + .cfi_sections .debug_frame +#endif + +#define CONCAT(a, b) CONCAT2(a, b) +#define CONCAT2(a, b) a ## b + +#ifdef __USER_LABEL_PREFIX__ +# define CNAME(X) CONCAT (__USER_LABEL_PREFIX__, X) +#else +# define CNAME(X) X +#endif +#ifdef __ELF__ +# define SIZE(X) .size CNAME(X), . - CNAME(X) +# define TYPE(X, Y) .type CNAME(X), Y +#else +# define SIZE(X) +# define TYPE(X, Y) +#endif + +#define ARM_FUNC_START_LOCAL(name) \ + .align 3; \ + TYPE(CNAME(name), %function); \ + CNAME(name): + +#define ARM_FUNC_START(name) \ + .globl CNAME(name); \ + FFI_HIDDEN(CNAME(name)); \ + ARM_FUNC_START_LOCAL(name) + +#define ARM_FUNC_END(name) \ + SIZE(name) + +/* Aid in defining a jump table with 8 bytes between entries. */ +/* ??? The clang assembler doesn't handle .if with symbolic expressions. */ +#ifdef __clang__ +# define E(index) +#else +# define E(index) \ + .if . - 0b - 8*index; \ + .error "type table out of sync"; \ + .endif +#endif + + .text + .syntax unified + .arm + +#ifndef __clang__ + /* We require interworking on LDM, which implies ARMv5T, + which implies the existance of BLX. */ + .arch armv5t +#endif + + /* Note that we use STC and LDC to encode VFP instructions, + so that we do not need ".fpu vfp", nor get that added to + the object file attributes. These will not be executed + unless the FFI_VFP abi is used. */ + + @ r0: stack + @ r1: frame + @ r2: fn + @ r3: vfp_used + +ARM_FUNC_START(ffi_call_VFP) + UNWIND(.fnstart) + cfi_startproc + + cmp r3, #3 @ load only d0 if possible +#ifdef __clang__ + vldrle d0, [r0] + vldmgt r0, {d0-d7} +#else + ldcle p11, cr0, [r0] @ vldrle d0, [r0] + ldcgt p11, cr0, [r0], {16} @ vldmgt r0, {d0-d7} +#endif + add r0, r0, #64 @ discard the vfp register args + /* FALLTHRU */ +ARM_FUNC_END(ffi_call_VFP) + +ARM_FUNC_START(ffi_call_SYSV) + stm r1, {fp, lr} + mov fp, r1 + + @ This is a bit of a lie wrt the origin of the unwind info, but + @ now we've got the usual frame pointer and two saved registers. + UNWIND(.save {fp,lr}) + UNWIND(.setfp fp, sp) + cfi_def_cfa(fp, 8) + cfi_rel_offset(fp, 0) + cfi_rel_offset(lr, 4) + + mov sp, r0 @ install the stack pointer + mov lr, r2 @ move the fn pointer out of the way + ldr ip, [fp, #16] @ install the static chain + ldmia sp!, {r0-r3} @ move first 4 parameters in registers. + blx lr @ call fn + + @ Load r2 with the pointer to storage for the return value + @ Load r3 with the return type code + ldr r2, [fp, #8] + ldr r3, [fp, #12] + + @ Deallocate the stack with the arguments. + mov sp, fp + cfi_def_cfa_register(sp) + + @ Store values stored in registers. + .align 3 + add pc, pc, r3, lsl #3 + nop +0: +E(ARM_TYPE_VFP_S) +#ifdef __clang__ + vstr s0, [r2] +#else + stc p10, cr0, [r2] @ vstr s0, [r2] +#endif + pop {fp,pc} +E(ARM_TYPE_VFP_D) +#ifdef __clang__ + vstr d0, [r2] +#else + stc p11, cr0, [r2] @ vstr d0, [r2] +#endif + pop {fp,pc} +E(ARM_TYPE_VFP_N) +#ifdef __clang__ + vstm r2, {d0-d3} +#else + stc p11, cr0, [r2], {8} @ vstm r2, {d0-d3} +#endif + pop {fp,pc} +E(ARM_TYPE_INT64) + str r1, [r2, #4] + nop +E(ARM_TYPE_INT) + str r0, [r2] + pop {fp,pc} +E(ARM_TYPE_VOID) + pop {fp,pc} + nop +E(ARM_TYPE_STRUCT) + pop {fp,pc} + + cfi_endproc + UNWIND(.fnend) +ARM_FUNC_END(ffi_call_SYSV) + + +/* + int ffi_closure_inner_* (cif, fun, user_data, frame) +*/ + +ARM_FUNC_START(ffi_go_closure_SYSV) + cfi_startproc + stmdb sp!, {r0-r3} @ save argument regs + cfi_adjust_cfa_offset(16) + ldr r0, [ip, #4] @ load cif + ldr r1, [ip, #8] @ load fun + mov r2, ip @ load user_data + b 0f + cfi_endproc +ARM_FUNC_END(ffi_go_closure_SYSV) + +ARM_FUNC_START(ffi_closure_SYSV) + UNWIND(.fnstart) + cfi_startproc + stmdb sp!, {r0-r3} @ save argument regs + cfi_adjust_cfa_offset(16) + +#if FFI_EXEC_TRAMPOLINE_TABLE + ldr ip, [ip] @ ip points to the config page, dereference to get the ffi_closure* +#endif + ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] @ load cif + ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] @ load fun + ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] @ load user_data +0: + add ip, sp, #16 @ compute entry sp + sub sp, sp, #64+32 @ allocate frame + cfi_adjust_cfa_offset(64+32) + stmdb sp!, {ip,lr} + + /* Remember that EABI unwind info only applies at call sites. + We need do nothing except note the save of the stack pointer + and the link registers. */ + UNWIND(.save {sp,lr}) + cfi_adjust_cfa_offset(8) + cfi_rel_offset(lr, 4) + + add r3, sp, #8 @ load frame + bl CNAME(ffi_closure_inner_SYSV) + + @ Load values returned in registers. + add r2, sp, #8+64 @ load result + adr r3, CNAME(ffi_closure_ret) + add pc, r3, r0, lsl #3 + cfi_endproc + UNWIND(.fnend) +ARM_FUNC_END(ffi_closure_SYSV) + +ARM_FUNC_START(ffi_go_closure_VFP) + cfi_startproc + stmdb sp!, {r0-r3} @ save argument regs + cfi_adjust_cfa_offset(16) + ldr r0, [ip, #4] @ load cif + ldr r1, [ip, #8] @ load fun + mov r2, ip @ load user_data + b 0f + cfi_endproc +ARM_FUNC_END(ffi_go_closure_VFP) + +ARM_FUNC_START(ffi_closure_VFP) + UNWIND(.fnstart) + cfi_startproc + stmdb sp!, {r0-r3} @ save argument regs + cfi_adjust_cfa_offset(16) + +#if FFI_EXEC_TRAMPOLINE_TABLE + ldr ip, [ip] @ ip points to the config page, dereference to get the ffi_closure* +#endif + ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] @ load cif + ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] @ load fun + ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] @ load user_data +0: + add ip, sp, #16 + sub sp, sp, #64+32 @ allocate frame + cfi_adjust_cfa_offset(64+32) +#ifdef __clang__ + vstm sp, {d0-d7} +#else + stc p11, cr0, [sp], {16} @ vstm sp, {d0-d7} +#endif + stmdb sp!, {ip,lr} + + /* See above. */ + UNWIND(.save {sp,lr}) + cfi_adjust_cfa_offset(8) + cfi_rel_offset(lr, 4) + + add r3, sp, #8 @ load frame + bl CNAME(ffi_closure_inner_VFP) + + @ Load values returned in registers. + add r2, sp, #8+64 @ load result + adr r3, CNAME(ffi_closure_ret) + add pc, r3, r0, lsl #3 + cfi_endproc + UNWIND(.fnend) +ARM_FUNC_END(ffi_closure_VFP) + +/* Load values returned in registers for both closure entry points. + Note that we use LDM with SP in the register set. This is deprecated + by ARM, but not yet unpredictable. */ + +ARM_FUNC_START_LOCAL(ffi_closure_ret) + cfi_startproc + cfi_rel_offset(sp, 0) + cfi_rel_offset(lr, 4) +0: +E(ARM_TYPE_VFP_S) +#ifdef __clang__ + vldr s0, [r2] +#else + ldc p10, cr0, [r2] @ vldr s0, [r2] +#endif + ldm sp, {sp,pc} +E(ARM_TYPE_VFP_D) +#ifdef __clang__ + vldr d0, [r2] +#else + ldc p11, cr0, [r2] @ vldr d0, [r2] +#endif + ldm sp, {sp,pc} +E(ARM_TYPE_VFP_N) +#ifdef __clang__ + vldm r2, {d0-d3} +#else + ldc p11, cr0, [r2], {8} @ vldm r2, {d0-d3} +#endif + ldm sp, {sp,pc} +E(ARM_TYPE_INT64) + ldr r1, [r2, #4] + nop +E(ARM_TYPE_INT) + ldr r0, [r2] + ldm sp, {sp,pc} +E(ARM_TYPE_VOID) + ldm sp, {sp,pc} + nop +E(ARM_TYPE_STRUCT) + ldm sp, {sp,pc} + cfi_endproc +ARM_FUNC_END(ffi_closure_ret) + +#if FFI_EXEC_TRAMPOLINE_TABLE + +#ifdef __MACH__ +#include + +.align PAGE_MAX_SHIFT +ARM_FUNC_START(ffi_closure_trampoline_table_page) +.rept PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE + adr ip, #-PAGE_MAX_SIZE @ the config page is PAGE_MAX_SIZE behind the trampoline page + sub ip, #8 @ account for pc bias + ldr pc, [ip, #4] @ jump to ffi_closure_SYSV or ffi_closure_VFP +.endr +ARM_FUNC_END(ffi_closure_trampoline_table_page) +#endif + +#else + +ARM_FUNC_START(ffi_arm_trampoline) +0: adr ip, 0b + ldr pc, 1f +1: .long 0 +ARM_FUNC_END(ffi_arm_trampoline) + +#endif /* FFI_EXEC_TRAMPOLINE_TABLE */ +#endif /* __arm__ */ + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",%progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/sysv_msvc_arm32.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/sysv_msvc_arm32.S new file mode 100644 index 0000000..5c99d02 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/arm/sysv_msvc_arm32.S @@ -0,0 +1,311 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 1998, 2008, 2011 Red Hat, Inc. + Copyright (c) 2011 Plausible Labs Cooperative, Inc. + Copyright (c) 2019 Microsoft Corporation. + + ARM Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include +#include +#include "internal.h" +#include "ksarm.h" + + + ; 8 byte aligned AREA to support 8 byte aligned jump tables + MACRO + NESTED_ENTRY_FFI $FuncName, $AreaName, $ExceptHandler + + ; compute the function's labels + __DeriveFunctionLabels $FuncName + + ; determine the area we will put the function into +__FuncArea SETS "|.text|" + IF "$AreaName" != "" +__FuncArea SETS "$AreaName" + ENDIF + + ; set up the exception handler itself +__FuncExceptionHandler SETS "" + IF "$ExceptHandler" != "" +__FuncExceptionHandler SETS "|$ExceptHandler|" + ENDIF + + ; switch to the specified area, jump tables require 8 byte alignment + AREA $__FuncArea,CODE,CODEALIGN,ALIGN=3,READONLY + + ; export the function name + __ExportProc $FuncName + + ; flush any pending literal pool stuff + ROUT + + ; reset the state of the unwind code tracking + __ResetUnwindState + + MEND + +; MACRO +; TABLE_ENTRY $Type, $Table +;$Type_$Table +; MEND + +#define E(index,table) return_##index##_##table + + ; r0: stack + ; r1: frame + ; r2: fn + ; r3: vfp_used + + ; fake entry point exists only to generate exists only to + ; generate .pdata for exception unwinding + NESTED_ENTRY_FFI ffi_call_VFP_fake + PROLOG_PUSH {r11, lr} ; save fp and lr for unwind + + ALTERNATE_ENTRY ffi_call_VFP + cmp r3, #3 ; load only d0 if possible + vldrle d0, [r0] + vldmgt r0, {d0-d7} + add r0, r0, #64 ; discard the vfp register args + b ffi_call_SYSV + NESTED_END ffi_call_VFP_fake + + ; fake entry point exists only to generate exists only to + ; generate .pdata for exception unwinding + NESTED_ENTRY_FFI ffi_call_SYSV_fake + PROLOG_PUSH {r11, lr} ; save fp and lr for unwind + + ALTERNATE_ENTRY ffi_call_SYSV + stm r1, {fp, lr} + mov fp, r1 + + mov sp, r0 ; install the stack pointer + mov lr, r2 ; move the fn pointer out of the way + ldr ip, [fp, #16] ; install the static chain + ldmia sp!, {r0-r3} ; move first 4 parameters in registers. + blx lr ; call fn + + ; Load r2 with the pointer to storage for the return value + ; Load r3 with the return type code + ldr r2, [fp, #8] + ldr r3, [fp, #12] + + ; Deallocate the stack with the arguments. + mov sp, fp + + ; Store values stored in registers. + ALIGN 8 + lsl r3, #3 + add r3, r3, pc + add r3, #8 + mov pc, r3 + + +E(ARM_TYPE_VFP_S, ffi_call) + ALIGN 8 + vstr s0, [r2] + pop {fp,pc} +E(ARM_TYPE_VFP_D, ffi_call) + ALIGN 8 + vstr d0, [r2] + pop {fp,pc} +E(ARM_TYPE_VFP_N, ffi_call) + ALIGN 8 + vstm r2, {d0-d3} + pop {fp,pc} +E(ARM_TYPE_INT64, ffi_call) + ALIGN 8 + str r1, [r2, #4] + nop +E(ARM_TYPE_INT, ffi_call) + ALIGN 8 + str r0, [r2] + pop {fp,pc} +E(ARM_TYPE_VOID, ffi_call) + ALIGN 8 + pop {fp,pc} + nop +E(ARM_TYPE_STRUCT, ffi_call) + ALIGN 8 + cmp r3, #ARM_TYPE_STRUCT + pop {fp,pc} + NESTED_END ffi_call_SYSV_fake + + IMPORT |ffi_closure_inner_SYSV| + /* + int ffi_closure_inner_SYSV + ( + cif, ; r0 + fun, ; r1 + user_data, ; r2 + frame ; r3 + ) + */ + + NESTED_ENTRY_FFI ffi_go_closure_SYSV + stmdb sp!, {r0-r3} ; save argument regs + ldr r0, [ip, #4] ; load cif + ldr r1, [ip, #8] ; load fun + mov r2, ip ; load user_data + b ffi_go_closure_SYSV_0 + NESTED_END ffi_go_closure_SYSV + + ; r3: ffi_closure + + ; fake entry point exists only to generate exists only to + ; generate .pdata for exception unwinding + NESTED_ENTRY_FFI ffi_closure_SYSV_fake + PROLOG_PUSH {r11, lr} ; save fp and lr for unwind + ALTERNATE_ENTRY ffi_closure_SYSV + ldmfd sp!, {ip,r0} ; restore fp (r0 is used for stack alignment) + stmdb sp!, {r0-r3} ; save argument regs + + ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] ; ffi_closure->cif + ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] ; ffi_closure->fun + ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] ; ffi_closure->user_data + + ALTERNATE_ENTRY ffi_go_closure_SYSV_0 + add ip, sp, #16 ; compute entry sp + + sub sp, sp, #64+32 ; allocate frame parameter (sizeof(vfp_space) = 64, sizeof(result) = 32) + mov r3, sp ; set frame parameter + stmdb sp!, {ip,lr} + + bl ffi_closure_inner_SYSV ; call the Python closure + + ; Load values returned in registers. + add r2, sp, #64+8 ; address of closure_frame->result + bl ffi_closure_ret ; move result to correct register or memory for type + + ldmfd sp!, {ip,lr} + mov sp, ip ; restore stack pointer + mov pc, lr + NESTED_END ffi_closure_SYSV_fake + + IMPORT |ffi_closure_inner_VFP| + /* + int ffi_closure_inner_VFP + ( + cif, ; r0 + fun, ; r1 + user_data, ; r2 + frame ; r3 + ) + */ + + NESTED_ENTRY_FFI ffi_go_closure_VFP + stmdb sp!, {r0-r3} ; save argument regs + ldr r0, [ip, #4] ; load cif + ldr r1, [ip, #8] ; load fun + mov r2, ip ; load user_data + b ffi_go_closure_VFP_0 + NESTED_END ffi_go_closure_VFP + + ; fake entry point exists only to generate exists only to + ; generate .pdata for exception unwinding + ; r3: closure + NESTED_ENTRY_FFI ffi_closure_VFP_fake + PROLOG_PUSH {r11, lr} ; save fp and lr for unwind + + ALTERNATE_ENTRY ffi_closure_VFP + ldmfd sp!, {ip,r0} ; restore fp (r0 is used for stack alignment) + stmdb sp!, {r0-r3} ; save argument regs + + ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] ; load cif + ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] ; load fun + ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] ; load user_data + + ALTERNATE_ENTRY ffi_go_closure_VFP_0 + add ip, sp, #16 ; compute entry sp + sub sp, sp, #32 ; save space for closure_frame->result + vstmdb sp!, {d0-d7} ; push closure_frame->vfp_space + + mov r3, sp ; save closure_frame + stmdb sp!, {ip,lr} + + bl ffi_closure_inner_VFP + + ; Load values returned in registers. + add r2, sp, #64+8 ; load result + bl ffi_closure_ret + ldmfd sp!, {ip,lr} + mov sp, ip ; restore stack pointer + mov pc, lr + NESTED_END ffi_closure_VFP_fake + +/* Load values returned in registers for both closure entry points. + Note that we use LDM with SP in the register set. This is deprecated + by ARM, but not yet unpredictable. */ + + NESTED_ENTRY_FFI ffi_closure_ret + stmdb sp!, {fp,lr} + + ALIGN 8 + lsl r0, #3 + add r0, r0, pc + add r0, #8 + mov pc, r0 + +E(ARM_TYPE_VFP_S, ffi_closure) + ALIGN 8 + vldr s0, [r2] + b call_epilogue +E(ARM_TYPE_VFP_D, ffi_closure) + ALIGN 8 + vldr d0, [r2] + b call_epilogue +E(ARM_TYPE_VFP_N, ffi_closure) + ALIGN 8 + vldm r2, {d0-d3} + b call_epilogue +E(ARM_TYPE_INT64, ffi_closure) + ALIGN 8 + ldr r1, [r2, #4] + nop +E(ARM_TYPE_INT, ffi_closure) + ALIGN 8 + ldr r0, [r2] + b call_epilogue +E(ARM_TYPE_VOID, ffi_closure) + ALIGN 8 + b call_epilogue + nop +E(ARM_TYPE_STRUCT, ffi_closure) + ALIGN 8 + b call_epilogue +call_epilogue + ldmfd sp!, {fp,pc} + NESTED_END ffi_closure_ret + + AREA |.trampoline|, DATA, THUMB, READONLY + EXPORT |ffi_arm_trampoline| +|ffi_arm_trampoline| DATA +thisproc adr ip, thisproc + stmdb sp!, {ip, r0} + ldr pc, [pc, #0] + DCD 0 + ;ENDP + + END \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/avr32/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/avr32/ffi.c new file mode 100644 index 0000000..3d43397 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/avr32/ffi.c @@ -0,0 +1,423 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2011 Anthony Green + Copyright (c) 2009 Bradley Smith + + AVR32 Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include +#include +#include +#include + +/* #define DEBUG */ + +extern void ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *, + unsigned int, unsigned int, unsigned int*, unsigned int, + void (*fn)(void)); +extern void ffi_closure_SYSV (ffi_closure *); + +unsigned int pass_struct_on_stack(ffi_type *type) +{ + if(type->type != FFI_TYPE_STRUCT) + return 0; + + if(type->alignment < type->size && + !(type->size == 4 || type->size == 8) && + !(type->size == 8 && type->alignment >= 4)) + return 1; + + if(type->size == 3 || type->size == 5 || type->size == 6 || + type->size == 7) + return 1; + + return 0; +} + +/* ffi_prep_args is called by the assembly routine once stack space + * has been allocated for the function's arguments + * + * This is annoyingly complex since we need to keep track of used + * registers. + */ + +void ffi_prep_args(char *stack, extended_cif *ecif) +{ + unsigned int i; + void **p_argv; + ffi_type **p_arg; + char *reg_base = stack; + char *stack_base = stack + 20; + unsigned int stack_offset = 0; + unsigned int reg_mask = 0; + + p_argv = ecif->avalue; + + /* If cif->flags is struct then we know it's not passed in registers */ + if(ecif->cif->flags == FFI_TYPE_STRUCT) + { + *(void**)reg_base = ecif->rvalue; + reg_mask |= 1; + } + + for(i = 0, p_arg = ecif->cif->arg_types; i < ecif->cif->nargs; + i++, p_arg++) + { + size_t z = (*p_arg)->size; + int alignment = (*p_arg)->alignment; + int type = (*p_arg)->type; + char *addr = 0; + + if(z % 4 != 0) + z += (4 - z % 4); + + if(reg_mask != 0x1f) + { + if(pass_struct_on_stack(*p_arg)) + { + addr = stack_base + stack_offset; + stack_offset += z; + } + else if(z == sizeof(int)) + { + char index = 0; + + while((reg_mask >> index) & 1) + index++; + + addr = reg_base + (index * 4); + reg_mask |= (1 << index); + } + else if(z == 2 * sizeof(int)) + { + if(!((reg_mask >> 1) & 1)) + { + addr = reg_base + 4; + reg_mask |= (3 << 1); + } + else if(!((reg_mask >> 3) & 1)) + { + addr = reg_base + 12; + reg_mask |= (3 << 3); + } + } + } + + if(!addr) + { + addr = stack_base + stack_offset; + stack_offset += z; + } + + if(type == FFI_TYPE_STRUCT && (*p_arg)->elements[1] == NULL) + type = (*p_arg)->elements[0]->type; + + switch(type) + { + case FFI_TYPE_UINT8: + *(unsigned int *)addr = (unsigned int)*(UINT8 *)(*p_argv); + break; + case FFI_TYPE_SINT8: + *(signed int *)addr = (signed int)*(SINT8 *)(*p_argv); + break; + case FFI_TYPE_UINT16: + *(unsigned int *)addr = (unsigned int)*(UINT16 *)(*p_argv); + break; + case FFI_TYPE_SINT16: + *(signed int *)addr = (signed int)*(SINT16 *)(*p_argv); + break; + default: + memcpy(addr, *p_argv, z); + } + + p_argv++; + } + +#ifdef DEBUG + /* Debugging */ + for(i = 0; i < 5; i++) + { + if((reg_mask & (1 << i)) == 0) + printf("r%d: (unused)\n", 12 - i); + else + printf("r%d: 0x%08x\n", 12 - i, ((unsigned int*)reg_base)[i]); + } + + for(i = 0; i < stack_offset / 4; i++) + { + printf("sp+%d: 0x%08x\n", i*4, ((unsigned int*)stack_base)[i]); + } +#endif +} + +/* Perform machine dependent cif processing */ +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + /* Round the stack up to a multiple of 8 bytes. This isn't needed + * everywhere, but it is on some platforms, and it doesn't harm + * anything when it isn't needed. */ + cif->bytes = (cif->bytes + 7) & ~7; + + /* Flag to indicate that he return value is in fact a struct */ + cif->rstruct_flag = 0; + + /* Set the return type flag */ + switch(cif->rtype->type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + cif->flags = (unsigned)FFI_TYPE_UINT8; + break; + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + cif->flags = (unsigned)FFI_TYPE_UINT16; + break; + case FFI_TYPE_FLOAT: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_POINTER: + cif->flags = (unsigned)FFI_TYPE_UINT32; + break; + case FFI_TYPE_DOUBLE: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + cif->flags = (unsigned)FFI_TYPE_UINT64; + break; + case FFI_TYPE_STRUCT: + cif->rstruct_flag = 1; + if(!pass_struct_on_stack(cif->rtype)) + { + if(cif->rtype->size <= 1) + cif->flags = (unsigned)FFI_TYPE_UINT8; + else if(cif->rtype->size <= 2) + cif->flags = (unsigned)FFI_TYPE_UINT16; + else if(cif->rtype->size <= 4) + cif->flags = (unsigned)FFI_TYPE_UINT32; + else if(cif->rtype->size <= 8) + cif->flags = (unsigned)FFI_TYPE_UINT64; + else + cif->flags = (unsigned)cif->rtype->type; + } + else + cif->flags = (unsigned)cif->rtype->type; + break; + default: + cif->flags = (unsigned)cif->rtype->type; + break; + } + + return FFI_OK; +} + +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + extended_cif ecif; + + unsigned int size = 0, i = 0; + ffi_type **p_arg; + + ecif.cif = cif; + ecif.avalue = avalue; + + for(i = 0, p_arg = cif->arg_types; i < cif->nargs; i++, p_arg++) + size += (*p_arg)->size + (4 - (*p_arg)->size % 4); + + /* If the return value is a struct and we don't have a return value + * address then we need to make one */ + + /* If cif->flags is struct then it's not suitable for registers */ + if((rvalue == NULL) && (cif->flags == FFI_TYPE_STRUCT)) + ecif.rvalue = alloca(cif->rtype->size); + else + ecif.rvalue = rvalue; + + switch(cif->abi) + { + case FFI_SYSV: + ffi_call_SYSV(ffi_prep_args, &ecif, size, cif->flags, + ecif.rvalue, cif->rstruct_flag, fn); + break; + default: + FFI_ASSERT(0); + break; + } +} + +static void ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, + void **avalue, ffi_cif *cif) +{ + register unsigned int i, reg_mask = 0; + register void **p_argv; + register ffi_type **p_arg; + register char *reg_base = stack; + register char *stack_base = stack + 20; + register unsigned int stack_offset = 0; + +#ifdef DEBUG + /* Debugging */ + for(i = 0; i < cif->nargs + 7; i++) + { + printf("sp+%d: 0x%08x\n", i*4, ((unsigned int*)stack)[i]); + } +#endif + + /* If cif->flags is struct then we know it's not passed in registers */ + if(cif->flags == FFI_TYPE_STRUCT) + { + *rvalue = *(void **)reg_base; + reg_mask |= 1; + } + + p_argv = avalue; + + for(i = 0, p_arg = cif->arg_types; i < cif->nargs; i++, p_arg++) + { + size_t z = (*p_arg)->size; + int alignment = (*p_arg)->alignment; + + *p_argv = 0; + + if(z % 4 != 0) + z += (4 - z % 4); + + if(reg_mask != 0x1f) + { + if(pass_struct_on_stack(*p_arg)) + { + *p_argv = (void*)stack_base + stack_offset; + stack_offset += z; + } + else if(z <= sizeof(int)) + { + char index = 0; + + while((reg_mask >> index) & 1) + index++; + + *p_argv = (void*)reg_base + (index * 4); + reg_mask |= (1 << index); + } + else if(z == 2 * sizeof(int)) + { + if(!((reg_mask >> 1) & 1)) + { + *p_argv = (void*)reg_base + 4; + reg_mask |= (3 << 1); + } + else if(!((reg_mask >> 3) & 1)) + { + *p_argv = (void*)reg_base + 12; + reg_mask |= (3 << 3); + } + } + } + + if(!*p_argv) + { + *p_argv = (void*)stack_base + stack_offset; + stack_offset += z; + } + + if((*p_arg)->type != FFI_TYPE_STRUCT || + (*p_arg)->elements[1] == NULL) + { + if(alignment == 1) + **(unsigned int**)p_argv <<= 24; + else if(alignment == 2) + **(unsigned int**)p_argv <<= 16; + } + + p_argv++; + } + +#ifdef DEBUG + /* Debugging */ + for(i = 0; i < cif->nargs; i++) + { + printf("sp+%d: 0x%08x\n", i*4, *(((unsigned int**)avalue)[i])); + } +#endif +} + +/* This function is jumped to by the trampoline */ + +unsigned int ffi_closure_SYSV_inner(ffi_closure *closure, void **respp, + void *args) +{ + ffi_cif *cif; + void **arg_area; + unsigned int i, size = 0; + ffi_type **p_arg; + + cif = closure->cif; + + for(i = 0, p_arg = cif->arg_types; i < cif->nargs; i++, p_arg++) + size += (*p_arg)->size + (4 - (*p_arg)->size % 4); + + arg_area = (void **)alloca(size); + + /* this call will initialize ARG_AREA, such that each element in that + * array points to the corresponding value on the stack; and if the + * function returns a structure, it will re-set RESP to point to the + * structure return address. */ + + ffi_prep_incoming_args_SYSV(args, respp, arg_area, cif); + + (closure->fun)(cif, *respp, arg_area, closure->user_data); + + return cif->flags; +} + +ffi_status ffi_prep_closure_loc(ffi_closure* closure, ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), void *user_data, + void *codeloc) +{ + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + unsigned char *__tramp = (unsigned char*)(&closure->tramp[0]); + unsigned int __fun = (unsigned int)(&ffi_closure_SYSV); + unsigned int __ctx = (unsigned int)(codeloc); + unsigned int __rstruct_flag = (unsigned int)(cif->rstruct_flag); + unsigned int __inner = (unsigned int)(&ffi_closure_SYSV_inner); + *(unsigned int*) &__tramp[0] = 0xebcd1f00; /* pushm r8-r12 */ + *(unsigned int*) &__tramp[4] = 0xfefc0010; /* ld.w r12, pc[16] */ + *(unsigned int*) &__tramp[8] = 0xfefb0010; /* ld.w r11, pc[16] */ + *(unsigned int*) &__tramp[12] = 0xfefa0010; /* ld.w r10, pc[16] */ + *(unsigned int*) &__tramp[16] = 0xfeff0010; /* ld.w pc, pc[16] */ + *(unsigned int*) &__tramp[20] = __ctx; + *(unsigned int*) &__tramp[24] = __rstruct_flag; + *(unsigned int*) &__tramp[28] = __inner; + *(unsigned int*) &__tramp[32] = __fun; + syscall(__NR_cacheflush, 0, (&__tramp[0]), 36); + + closure->cif = cif; + closure->user_data = user_data; + closure->fun = fun; + + return FFI_OK; +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/avr32/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/avr32/ffitarget.h new file mode 100644 index 0000000..d0c7586 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/avr32/ffitarget.h @@ -0,0 +1,55 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 2009 Bradley Smith + Target configuration macros for AVR32. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; +#endif + +#define FFI_EXTRA_CIF_FIELDS unsigned int rstruct_flag + +/* Definitions for closures */ + +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 36 +#define FFI_NATIVE_RAW_API 0 + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/avr32/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/avr32/sysv.S new file mode 100644 index 0000000..a984b3c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/avr32/sysv.S @@ -0,0 +1,208 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2009 Bradley Smith + + AVR32 Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + --------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + + /* r12: ffi_prep_args + * r11: &ecif + * r10: size + * r9: cif->flags + * r8: ecif.rvalue + * sp+0: cif->rstruct_flag + * sp+4: fn */ + + .text + .align 1 + .globl ffi_call_SYSV + .type ffi_call_SYSV, @function +ffi_call_SYSV: + stm --sp, r0,r1,lr + stm --sp, r8-r12 + mov r0, sp + + /* Make room for all of the new args. */ + sub sp, r10 + /* Pad to make way for potential skipped registers */ + sub sp, 20 + + /* Call ffi_prep_args(stack, &ecif). */ + /* r11 already set */ + mov r1, r12 + mov r12, sp + icall r1 + + /* Save new argument size */ + mov r1, r12 + + /* Move first 5 parameters in registers. */ + ldm sp++, r8-r12 + + /* call (fn) (...). */ + ld.w r1, r0[36] + icall r1 + + /* Remove the space we pushed for the args. */ + mov sp, r0 + + /* Load r1 with the rstruct flag. */ + ld.w r1, sp[32] + + /* Load r9 with the return type code. */ + ld.w r9, sp[12] + + /* Load r8 with the return value pointer. */ + ld.w r8, sp[16] + + /* If the return value pointer is NULL, assume no return value. */ + cp.w r8, 0 + breq .Lend + + /* Check if return type is actually a struct */ + cp.w r1, 0 + breq 1f + + /* Return 8bit */ + cp.w r9, FFI_TYPE_UINT8 + breq .Lstore8 + + /* Return 16bit */ + cp.w r9, FFI_TYPE_UINT16 + breq .Lstore16 + +1: + /* Return 32bit */ + cp.w r9, FFI_TYPE_UINT32 + breq .Lstore32 + cp.w r9, FFI_TYPE_UINT16 + breq .Lstore32 + cp.w r9, FFI_TYPE_UINT8 + breq .Lstore32 + + /* Return 64bit */ + cp.w r9, FFI_TYPE_UINT64 + breq .Lstore64 + + /* Didn't match anything */ + bral .Lend + +.Lstore64: + st.w r8[0], r11 + st.w r8[4], r10 + bral .Lend + +.Lstore32: + st.w r8[0], r12 + bral .Lend + +.Lstore16: + st.h r8[0], r12 + bral .Lend + +.Lstore8: + st.b r8[0], r12 + bral .Lend + +.Lend: + sub sp, -20 + ldm sp++, r0,r1,pc + + .size ffi_call_SYSV, . - ffi_call_SYSV + + + /* r12: __ctx + * r11: __rstruct_flag + * r10: __inner */ + + .align 1 + .globl ffi_closure_SYSV + .type ffi_closure_SYSV, @function +ffi_closure_SYSV: + stm --sp, r0,lr + mov r0, r11 + mov r8, r10 + sub r10, sp, -8 + sub sp, 12 + st.w sp[8], sp + sub r11, sp, -8 + icall r8 + + /* Check if return type is actually a struct */ + cp.w r0, 0 + breq 1f + + /* Return 8bit */ + cp.w r12, FFI_TYPE_UINT8 + breq .Lget8 + + /* Return 16bit */ + cp.w r12, FFI_TYPE_UINT16 + breq .Lget16 + +1: + /* Return 32bit */ + cp.w r12, FFI_TYPE_UINT32 + breq .Lget32 + cp.w r12, FFI_TYPE_UINT16 + breq .Lget32 + cp.w r12, FFI_TYPE_UINT8 + breq .Lget32 + + /* Return 64bit */ + cp.w r12, FFI_TYPE_UINT64 + breq .Lget64 + + /* Didn't match anything */ + bral .Lclend + +.Lget64: + ld.w r11, sp[0] + ld.w r10, sp[4] + bral .Lclend + +.Lget32: + ld.w r12, sp[0] + bral .Lclend + +.Lget16: + ld.uh r12, sp[0] + bral .Lclend + +.Lget8: + ld.ub r12, sp[0] + bral .Lclend + +.Lclend: + sub sp, -12 + ldm sp++, r0,lr + sub sp, -20 + mov pc, lr + + .size ffi_closure_SYSV, . - ffi_closure_SYSV + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/bfin/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/bfin/ffi.c new file mode 100644 index 0000000..22a2acd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/bfin/ffi.c @@ -0,0 +1,196 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2012 Alexandre K. I. de Mendonca , + Paulo Pizarro + + Blackfin Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ +#include +#include + +#include +#include + +/* Maximum number of GPRs available for argument passing. */ +#define MAX_GPRARGS 3 + +/* + * Return types + */ +#define FFIBFIN_RET_VOID 0 +#define FFIBFIN_RET_BYTE 1 +#define FFIBFIN_RET_HALFWORD 2 +#define FFIBFIN_RET_INT64 3 +#define FFIBFIN_RET_INT32 4 + +/*====================================================================*/ +/* PROTOTYPE * + /*====================================================================*/ +void ffi_prep_args(unsigned char *, extended_cif *); + +/*====================================================================*/ +/* Externals */ +/* (Assembly) */ +/*====================================================================*/ + +extern void ffi_call_SYSV(unsigned, extended_cif *, void(*)(unsigned char *, extended_cif *), unsigned, void *, void(*fn)(void)); + +/*====================================================================*/ +/* Implementation */ +/* */ +/*====================================================================*/ + + +/* + * This function calculates the return type (size) based on type. + */ + +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + /* --------------------------------------* + * Return handling * + * --------------------------------------*/ + switch (cif->rtype->type) { + case FFI_TYPE_VOID: + cif->flags = FFIBFIN_RET_VOID; + break; + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + cif->flags = FFIBFIN_RET_HALFWORD; + break; + case FFI_TYPE_UINT8: + cif->flags = FFIBFIN_RET_BYTE; + break; + case FFI_TYPE_INT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_FLOAT: + case FFI_TYPE_POINTER: + case FFI_TYPE_SINT8: + cif->flags = FFIBFIN_RET_INT32; + break; + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_DOUBLE: + cif->flags = FFIBFIN_RET_INT64; + break; + case FFI_TYPE_STRUCT: + if (cif->rtype->size <= 4){ + cif->flags = FFIBFIN_RET_INT32; + }else if (cif->rtype->size == 8){ + cif->flags = FFIBFIN_RET_INT64; + }else{ + //it will return via a hidden pointer in P0 + cif->flags = FFIBFIN_RET_VOID; + } + break; + default: + FFI_ASSERT(0); + break; + } + return FFI_OK; +} + +/* + * This will prepare the arguments and will call the assembly routine + * cif = the call interface + * fn = the function to be called + * rvalue = the return value + * avalue = the arguments + */ +void ffi_call(ffi_cif *cif, void(*fn)(void), void *rvalue, void **avalue) +{ + int ret_type = cif->flags; + extended_cif ecif; + ecif.cif = cif; + ecif.avalue = avalue; + ecif.rvalue = rvalue; + + switch (cif->abi) { + case FFI_SYSV: + ffi_call_SYSV(cif->bytes, &ecif, ffi_prep_args, ret_type, ecif.rvalue, fn); + break; + default: + FFI_ASSERT(0); + break; + } +} + + +/* +* This function prepares the parameters (copies them from the ecif to the stack) +* to call the function (ffi_prep_args is called by the assembly routine in file +* sysv.S, which also calls the actual function) +*/ +void ffi_prep_args(unsigned char *stack, extended_cif *ecif) +{ + register unsigned int i = 0; + void **p_argv; + unsigned char *argp; + ffi_type **p_arg; + argp = stack; + p_argv = ecif->avalue; + for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; + (i != 0); + i--, p_arg++) { + size_t z; + z = (*p_arg)->size; + if (z < sizeof(int)) { + z = sizeof(int); + switch ((*p_arg)->type) { + case FFI_TYPE_SINT8: { + signed char v = *(SINT8 *)(* p_argv); + signed int t = v; + *(signed int *) argp = t; + } + break; + case FFI_TYPE_UINT8: { + unsigned char v = *(UINT8 *)(* p_argv); + unsigned int t = v; + *(unsigned int *) argp = t; + } + break; + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int) * (SINT16 *)(* p_argv); + break; + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int) * (UINT16 *)(* p_argv); + break; + case FFI_TYPE_STRUCT: + memcpy(argp, *p_argv, (*p_arg)->size); + break; + default: + FFI_ASSERT(0); + break; + } + } else if (z == sizeof(int)) { + *(unsigned int *) argp = (unsigned int) * (UINT32 *)(* p_argv); + } else { + memcpy(argp, *p_argv, z); + } + p_argv++; + argp += z; + } +} + + + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/bfin/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/bfin/ffitarget.h new file mode 100644 index 0000000..2175c01 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/bfin/ffitarget.h @@ -0,0 +1,43 @@ +/* ----------------------------------------------------------------------- + ffitarget.h - Copyright (c) 2012 Alexandre K. I. de Mendonca + + Blackfin Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; +#endif + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/bfin/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/bfin/sysv.S new file mode 100644 index 0000000..f4278be --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/bfin/sysv.S @@ -0,0 +1,179 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2012 Alexandre K. I. de Mendonca , + Paulo Pizarro + + Blackfin Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + +.text +.align 4 + + /* + There is a "feature" in the bfin toolchain that it puts a _ before function names + that's why the function here it's called _ffi_call_SYSV and not ffi_call_SYSV + */ + .global _ffi_call_SYSV; + .type _ffi_call_SYSV, STT_FUNC; + .func ffi_call_SYSV + + /* + cif->bytes = R0 (fp+8) + &ecif = R1 (fp+12) + ffi_prep_args = R2 (fp+16) + ret_type = stack (fp+20) + ecif.rvalue = stack (fp+24) + fn = stack (fp+28) + got (fp+32) + + There is room for improvement here (we can use temporary registers + instead of saving the values in the memory) + REGS: + P5 => Stack pointer (function arguments) + R5 => cif->bytes + R4 => ret->type + + FP-20 = P3 + FP-16 = SP (parameters area) + FP-12 = SP (temp) + FP-08 = function return part 1 [R0] + FP-04 = function return part 2 [R1] + */ + +_ffi_call_SYSV: +.prologue: + LINK 20; + [FP-20] = P3; + [FP+8] = R0; + [FP+12] = R1; + [FP+16] = R2; + +.allocate_stack: + //alocate cif->bytes into the stack + R1 = [FP+8]; + R0 = SP; + R0 = R0 - R1; + R1 = 4; + R0 = R0 - R1; + [FP-12] = SP; + SP = R0; + [FP-16] = SP; + +.call_prep_args: + //get the addr of prep_args + P0 = [P3 + _ffi_prep_args@FUNCDESC_GOT17M4]; + P1 = [P0]; + P3 = [P0+4]; + R0 = [FP-16];//SP (parameter area) + R1 = [FP+12];//ecif + call (P1); + +.call_user_function: + //ajust SP so as to allow the user function access the parameters on the stack + SP = [FP-16]; //point to function parameters + R0 = [SP]; + R1 = [SP+4]; + R2 = [SP+8]; + //load user function address + P0 = FP; + P0 +=28; + P1 = [P0]; + P1 = [P1]; + P3 = [P0+4]; + /* + For functions returning aggregate values (struct) occupying more than 8 bytes, + the caller allocates the return value object on the stack and the address + of this object is passed to the callee as a hidden argument in register P0. + */ + P0 = [FP+24]; + + call (P1); + SP = [FP-12]; +.compute_return: + P2 = [FP-20]; + [FP-8] = R0; + [FP-4] = R1; + + R0 = [FP+20]; + R1 = R0 << 2; + + R0 = [P2+.rettable@GOT17M4]; + R0 = R1 + R0; + P2 = R0; + R1 = [P2]; + + P2 = [FP+-20]; + R0 = [P2+.rettable@GOT17M4]; + R0 = R1 + R0; + P2 = R0; + R0 = [FP-8]; + R1 = [FP-4]; + jump (P2); + +/* +#define FFIBFIN_RET_VOID 0 +#define FFIBFIN_RET_BYTE 1 +#define FFIBFIN_RET_HALFWORD 2 +#define FFIBFIN_RET_INT64 3 +#define FFIBFIN_RET_INT32 4 +*/ +.align 4 +.align 4 +.rettable: + .dd .epilogue - .rettable + .dd .rbyte - .rettable; + .dd .rhalfword - .rettable; + .dd .rint64 - .rettable; + .dd .rint32 - .rettable; + +.rbyte: + P0 = [FP+24]; + R0 = R0.B (Z); + [P0] = R0; + JUMP .epilogue +.rhalfword: + P0 = [FP+24]; + R0 = R0.L; + [P0] = R0; + JUMP .epilogue +.rint64: + P0 = [FP+24];// &rvalue + [P0] = R0; + [P0+4] = R1; + JUMP .epilogue +.rint32: + P0 = [FP+24]; + [P0] = R0; +.epilogue: + R0 = [FP+8]; + R1 = [FP+12]; + R2 = [FP+16]; + P3 = [FP-20]; + UNLINK; + RTS; + +.size _ffi_call_SYSV,.-_ffi_call_SYSV; +.endfunc diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/closures.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/closures.c new file mode 100644 index 0000000..dfc2f68 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/closures.c @@ -0,0 +1,1021 @@ +/* ----------------------------------------------------------------------- + closures.c - Copyright (c) 2019 Anthony Green + Copyright (c) 2007, 2009, 2010 Red Hat, Inc. + Copyright (C) 2007, 2009, 2010 Free Software Foundation, Inc + Copyright (c) 2011 Plausible Labs Cooperative, Inc. + + Code to allocate and deallocate memory for closures. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#if defined __linux__ && !defined _GNU_SOURCE +#define _GNU_SOURCE 1 +#endif + +#include +#include +#include + +#ifdef __NetBSD__ +#include +#endif + +#if __NetBSD_Version__ - 0 >= 799007200 +/* NetBSD with PROT_MPROTECT */ +#include + +#include +#include +#ifdef HAVE_SYS_MEMFD_H +#include +#endif + +static const size_t overhead = + (sizeof(max_align_t) > sizeof(void *) + sizeof(size_t)) ? + sizeof(max_align_t) + : sizeof(void *) + sizeof(size_t); + +#define ADD_TO_POINTER(p, d) ((void *)((uintptr_t)(p) + (d))) + +void * +ffi_closure_alloc (size_t size, void **code) +{ + static size_t page_size; + size_t rounded_size; + void *codeseg, *dataseg; + int prot; + + /* Expect that PAX mprotect is active and a separate code mapping is necessary. */ + if (!code) + return NULL; + + /* Obtain system page size. */ + if (!page_size) + page_size = sysconf(_SC_PAGESIZE); + + /* Round allocation size up to the next page, keeping in mind the size field and pointer to code map. */ + rounded_size = (size + overhead + page_size - 1) & ~(page_size - 1); + + /* Primary mapping is RW, but request permission to switch to PROT_EXEC later. */ + prot = PROT_READ | PROT_WRITE | PROT_MPROTECT(PROT_EXEC); + dataseg = mmap(NULL, rounded_size, prot, MAP_ANON | MAP_PRIVATE, -1, 0); + if (dataseg == MAP_FAILED) + return NULL; + + /* Create secondary mapping and switch it to RX. */ + codeseg = mremap(dataseg, rounded_size, NULL, rounded_size, MAP_REMAPDUP); + if (codeseg == MAP_FAILED) { + munmap(dataseg, rounded_size); + return NULL; + } + if (mprotect(codeseg, rounded_size, PROT_READ | PROT_EXEC) == -1) { + munmap(codeseg, rounded_size); + munmap(dataseg, rounded_size); + return NULL; + } + + /* Remember allocation size and location of the secondary mapping for ffi_closure_free. */ + memcpy(dataseg, &rounded_size, sizeof(rounded_size)); + memcpy(ADD_TO_POINTER(dataseg, sizeof(size_t)), &codeseg, sizeof(void *)); + *code = ADD_TO_POINTER(codeseg, overhead); + return ADD_TO_POINTER(dataseg, overhead); +} + +void +ffi_closure_free (void *ptr) +{ + void *codeseg, *dataseg; + size_t rounded_size; + + dataseg = ADD_TO_POINTER(ptr, -overhead); + memcpy(&rounded_size, dataseg, sizeof(rounded_size)); + memcpy(&codeseg, ADD_TO_POINTER(dataseg, sizeof(size_t)), sizeof(void *)); + munmap(dataseg, rounded_size); + munmap(codeseg, rounded_size); +} +#else /* !NetBSD with PROT_MPROTECT */ + +#if !FFI_MMAP_EXEC_WRIT && !FFI_EXEC_TRAMPOLINE_TABLE +# if __linux__ && !defined(__ANDROID__) +/* This macro indicates it may be forbidden to map anonymous memory + with both write and execute permission. Code compiled when this + option is defined will attempt to map such pages once, but if it + fails, it falls back to creating a temporary file in a writable and + executable filesystem and mapping pages from it into separate + locations in the virtual memory space, one location writable and + another executable. */ +# define FFI_MMAP_EXEC_WRIT 1 +# define HAVE_MNTENT 1 +# endif +# if defined(_WIN32) || defined(__OS2__) +/* Windows systems may have Data Execution Protection (DEP) enabled, + which requires the use of VirtualMalloc/VirtualFree to alloc/free + executable memory. */ +# define FFI_MMAP_EXEC_WRIT 1 +# endif +#endif + +#if FFI_MMAP_EXEC_WRIT && !defined FFI_MMAP_EXEC_SELINUX +# if defined(__linux__) && !defined(__ANDROID__) +/* When defined to 1 check for SELinux and if SELinux is active, + don't attempt PROT_EXEC|PROT_WRITE mapping at all, as that + might cause audit messages. */ +# define FFI_MMAP_EXEC_SELINUX 1 +# endif +#endif + +#if FFI_CLOSURES + +#if FFI_EXEC_TRAMPOLINE_TABLE + +#ifdef __MACH__ + +#include +#include +#ifdef HAVE_PTRAUTH +#include +#endif +#include +#include + +extern void *ffi_closure_trampoline_table_page; + +typedef struct ffi_trampoline_table ffi_trampoline_table; +typedef struct ffi_trampoline_table_entry ffi_trampoline_table_entry; + +struct ffi_trampoline_table +{ + /* contiguous writable and executable pages */ + vm_address_t config_page; + vm_address_t trampoline_page; + + /* free list tracking */ + uint16_t free_count; + ffi_trampoline_table_entry *free_list; + ffi_trampoline_table_entry *free_list_pool; + + ffi_trampoline_table *prev; + ffi_trampoline_table *next; +}; + +struct ffi_trampoline_table_entry +{ + void *(*trampoline) (void); + ffi_trampoline_table_entry *next; +}; + +/* Total number of trampolines that fit in one trampoline table */ +#define FFI_TRAMPOLINE_COUNT (PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE) + +static pthread_mutex_t ffi_trampoline_lock = PTHREAD_MUTEX_INITIALIZER; +static ffi_trampoline_table *ffi_trampoline_tables = NULL; + +static ffi_trampoline_table * +ffi_trampoline_table_alloc (void) +{ + ffi_trampoline_table *table; + vm_address_t config_page; + vm_address_t trampoline_page; + vm_address_t trampoline_page_template; + vm_prot_t cur_prot; + vm_prot_t max_prot; + kern_return_t kt; + uint16_t i; + + /* Allocate two pages -- a config page and a placeholder page */ + config_page = 0x0; + kt = vm_allocate (mach_task_self (), &config_page, PAGE_MAX_SIZE * 2, + VM_FLAGS_ANYWHERE); + if (kt != KERN_SUCCESS) + return NULL; + + /* Remap the trampoline table on top of the placeholder page */ + trampoline_page = config_page + PAGE_MAX_SIZE; + trampoline_page_template = (vm_address_t)&ffi_closure_trampoline_table_page; +#ifdef __arm__ + /* ffi_closure_trampoline_table_page can be thumb-biased on some ARM archs */ + trampoline_page_template &= ~1UL; +#endif + kt = vm_remap (mach_task_self (), &trampoline_page, PAGE_MAX_SIZE, 0x0, + VM_FLAGS_OVERWRITE, mach_task_self (), trampoline_page_template, + FALSE, &cur_prot, &max_prot, VM_INHERIT_SHARE); + if (kt != KERN_SUCCESS) + { + vm_deallocate (mach_task_self (), config_page, PAGE_MAX_SIZE * 2); + return NULL; + } + + /* We have valid trampoline and config pages */ + table = calloc (1, sizeof (ffi_trampoline_table)); + table->free_count = FFI_TRAMPOLINE_COUNT; + table->config_page = config_page; + table->trampoline_page = trampoline_page; + + /* Create and initialize the free list */ + table->free_list_pool = + calloc (FFI_TRAMPOLINE_COUNT, sizeof (ffi_trampoline_table_entry)); + + for (i = 0; i < table->free_count; i++) + { + ffi_trampoline_table_entry *entry = &table->free_list_pool[i]; + entry->trampoline = + (void *) (table->trampoline_page + (i * FFI_TRAMPOLINE_SIZE)); + + if (i < table->free_count - 1) + entry->next = &table->free_list_pool[i + 1]; + } + + table->free_list = table->free_list_pool; + + return table; +} + +static void +ffi_trampoline_table_free (ffi_trampoline_table *table) +{ + /* Remove from the list */ + if (table->prev != NULL) + table->prev->next = table->next; + + if (table->next != NULL) + table->next->prev = table->prev; + + /* Deallocate pages */ + vm_deallocate (mach_task_self (), table->config_page, PAGE_MAX_SIZE * 2); + + /* Deallocate free list */ + free (table->free_list_pool); + free (table); +} + +void * +ffi_closure_alloc (size_t size, void **code) +{ + /* Create the closure */ + ffi_closure *closure = malloc (size); + if (closure == NULL) + return NULL; + + pthread_mutex_lock (&ffi_trampoline_lock); + + /* Check for an active trampoline table with available entries. */ + ffi_trampoline_table *table = ffi_trampoline_tables; + if (table == NULL || table->free_list == NULL) + { + table = ffi_trampoline_table_alloc (); + if (table == NULL) + { + pthread_mutex_unlock (&ffi_trampoline_lock); + free (closure); + return NULL; + } + + /* Insert the new table at the top of the list */ + table->next = ffi_trampoline_tables; + if (table->next != NULL) + table->next->prev = table; + + ffi_trampoline_tables = table; + } + + /* Claim the free entry */ + ffi_trampoline_table_entry *entry = ffi_trampoline_tables->free_list; + ffi_trampoline_tables->free_list = entry->next; + ffi_trampoline_tables->free_count--; + entry->next = NULL; + + pthread_mutex_unlock (&ffi_trampoline_lock); + + /* Initialize the return values */ + *code = entry->trampoline; +#ifdef HAVE_PTRAUTH + *code = ptrauth_sign_unauthenticated (*code, ptrauth_key_asia, 0); +#endif + closure->trampoline_table = table; + closure->trampoline_table_entry = entry; + + return closure; +} + +void +ffi_closure_free (void *ptr) +{ + ffi_closure *closure = ptr; + + pthread_mutex_lock (&ffi_trampoline_lock); + + /* Fetch the table and entry references */ + ffi_trampoline_table *table = closure->trampoline_table; + ffi_trampoline_table_entry *entry = closure->trampoline_table_entry; + + /* Return the entry to the free list */ + entry->next = table->free_list; + table->free_list = entry; + table->free_count++; + + /* If all trampolines within this table are free, and at least one other table exists, deallocate + * the table */ + if (table->free_count == FFI_TRAMPOLINE_COUNT + && ffi_trampoline_tables != table) + { + ffi_trampoline_table_free (table); + } + else if (ffi_trampoline_tables != table) + { + /* Otherwise, bump this table to the top of the list */ + table->prev = NULL; + table->next = ffi_trampoline_tables; + if (ffi_trampoline_tables != NULL) + ffi_trampoline_tables->prev = table; + + ffi_trampoline_tables = table; + } + + pthread_mutex_unlock (&ffi_trampoline_lock); + + /* Free the closure */ + free (closure); +} + +#endif + +// Per-target implementation; It's unclear what can reasonable be shared between two OS/architecture implementations. + +#elif FFI_MMAP_EXEC_WRIT /* !FFI_EXEC_TRAMPOLINE_TABLE */ + +#define USE_LOCKS 1 +#define USE_DL_PREFIX 1 +#ifdef __GNUC__ +#ifndef USE_BUILTIN_FFS +#define USE_BUILTIN_FFS 1 +#endif +#endif + +/* We need to use mmap, not sbrk. */ +#define HAVE_MORECORE 0 + +/* We could, in theory, support mremap, but it wouldn't buy us anything. */ +#define HAVE_MREMAP 0 + +/* We have no use for this, so save some code and data. */ +#define NO_MALLINFO 1 + +/* We need all allocations to be in regular segments, otherwise we + lose track of the corresponding code address. */ +#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T + +/* Don't allocate more than a page unless needed. */ +#define DEFAULT_GRANULARITY ((size_t)malloc_getpagesize) + +#include +#include +#include +#include +#ifndef _MSC_VER +#include +#endif +#include +#include +#if !defined(_WIN32) +#ifdef HAVE_MNTENT +#include +#endif /* HAVE_MNTENT */ +#include +#include + +/* We don't want sys/mman.h to be included after we redefine mmap and + dlmunmap. */ +#include +#define LACKS_SYS_MMAN_H 1 + +#if FFI_MMAP_EXEC_SELINUX +#include +#include + +static int selinux_enabled = -1; + +static int +selinux_enabled_check (void) +{ + struct statfs sfs; + FILE *f; + char *buf = NULL; + size_t len = 0; + + if (statfs ("/selinux", &sfs) >= 0 + && (unsigned int) sfs.f_type == 0xf97cff8cU) + return 1; + f = fopen ("/proc/mounts", "r"); + if (f == NULL) + return 0; + while (getline (&buf, &len, f) >= 0) + { + char *p = strchr (buf, ' '); + if (p == NULL) + break; + p = strchr (p + 1, ' '); + if (p == NULL) + break; + if (strncmp (p + 1, "selinuxfs ", 10) == 0) + { + free (buf); + fclose (f); + return 1; + } + } + free (buf); + fclose (f); + return 0; +} + +#define is_selinux_enabled() (selinux_enabled >= 0 ? selinux_enabled \ + : (selinux_enabled = selinux_enabled_check ())) + +#else + +#define is_selinux_enabled() 0 + +#endif /* !FFI_MMAP_EXEC_SELINUX */ + +/* On PaX enable kernels that have MPROTECT enable we can't use PROT_EXEC. */ +#ifdef FFI_MMAP_EXEC_EMUTRAMP_PAX +#include + +static int emutramp_enabled = -1; + +static int +emutramp_enabled_check (void) +{ + char *buf = NULL; + size_t len = 0; + FILE *f; + int ret; + f = fopen ("/proc/self/status", "r"); + if (f == NULL) + return 0; + ret = 0; + + while (getline (&buf, &len, f) != -1) + if (!strncmp (buf, "PaX:", 4)) + { + char emutramp; + if (sscanf (buf, "%*s %*c%c", &emutramp) == 1) + ret = (emutramp == 'E'); + break; + } + free (buf); + fclose (f); + return ret; +} + +#define is_emutramp_enabled() (emutramp_enabled >= 0 ? emutramp_enabled \ + : (emutramp_enabled = emutramp_enabled_check ())) +#endif /* FFI_MMAP_EXEC_EMUTRAMP_PAX */ + +#elif defined (__CYGWIN__) || defined(__INTERIX) + +#include + +/* Cygwin is Linux-like, but not quite that Linux-like. */ +#define is_selinux_enabled() 0 + +#endif /* !defined(X86_WIN32) && !defined(X86_WIN64) */ + +#ifndef FFI_MMAP_EXEC_EMUTRAMP_PAX +#define is_emutramp_enabled() 0 +#endif /* FFI_MMAP_EXEC_EMUTRAMP_PAX */ + +/* Declare all functions defined in dlmalloc.c as static. */ +static void *dlmalloc(size_t); +static void dlfree(void*); +static void *dlcalloc(size_t, size_t) MAYBE_UNUSED; +static void *dlrealloc(void *, size_t) MAYBE_UNUSED; +static void *dlmemalign(size_t, size_t) MAYBE_UNUSED; +static void *dlvalloc(size_t) MAYBE_UNUSED; +static int dlmallopt(int, int) MAYBE_UNUSED; +static size_t dlmalloc_footprint(void) MAYBE_UNUSED; +static size_t dlmalloc_max_footprint(void) MAYBE_UNUSED; +static void** dlindependent_calloc(size_t, size_t, void**) MAYBE_UNUSED; +static void** dlindependent_comalloc(size_t, size_t*, void**) MAYBE_UNUSED; +static void *dlpvalloc(size_t) MAYBE_UNUSED; +static int dlmalloc_trim(size_t) MAYBE_UNUSED; +static size_t dlmalloc_usable_size(void*) MAYBE_UNUSED; +static void dlmalloc_stats(void) MAYBE_UNUSED; + +#if !(defined(_WIN32) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) +/* Use these for mmap and munmap within dlmalloc.c. */ +static void *dlmmap(void *, size_t, int, int, int, off_t); +static int dlmunmap(void *, size_t); +#endif /* !(defined(_WIN32) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) */ + +#define mmap dlmmap +#define munmap dlmunmap + +#include "dlmalloc.c" + +#undef mmap +#undef munmap + +#if !(defined(_WIN32) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) + +/* A mutex used to synchronize access to *exec* variables in this file. */ +static pthread_mutex_t open_temp_exec_file_mutex = PTHREAD_MUTEX_INITIALIZER; + +/* A file descriptor of a temporary file from which we'll map + executable pages. */ +static int execfd = -1; + +/* The amount of space already allocated from the temporary file. */ +static size_t execsize = 0; + +#ifdef HAVE_MEMFD_CREATE +/* Open a temporary file name, and immediately unlink it. */ +static int +open_temp_exec_file_memfd (const char *name) +{ + int fd; + fd = memfd_create (name, MFD_CLOEXEC); + return fd; +} +#endif + +/* Open a temporary file name, and immediately unlink it. */ +static int +open_temp_exec_file_name (char *name, int flags) +{ + int fd; + +#ifdef HAVE_MKOSTEMP + fd = mkostemp (name, flags); +#else + fd = mkstemp (name); +#endif + + if (fd != -1) + unlink (name); + + return fd; +} + +/* Open a temporary file in the named directory. */ +static int +open_temp_exec_file_dir (const char *dir) +{ + static const char suffix[] = "/ffiXXXXXX"; + int lendir, flags; + char *tempname; +#ifdef O_TMPFILE + int fd; +#endif + +#ifdef O_CLOEXEC + flags = O_CLOEXEC; +#else + flags = 0; +#endif + +#ifdef O_TMPFILE + fd = open (dir, flags | O_RDWR | O_EXCL | O_TMPFILE, 0700); + /* If the running system does not support the O_TMPFILE flag then retry without it. */ + if (fd != -1 || (errno != EINVAL && errno != EISDIR && errno != EOPNOTSUPP)) { + return fd; + } else { + errno = 0; + } +#endif + + lendir = (int) strlen (dir); + tempname = __builtin_alloca (lendir + sizeof (suffix)); + + if (!tempname) + return -1; + + memcpy (tempname, dir, lendir); + memcpy (tempname + lendir, suffix, sizeof (suffix)); + + return open_temp_exec_file_name (tempname, flags); +} + +/* Open a temporary file in the directory in the named environment + variable. */ +static int +open_temp_exec_file_env (const char *envvar) +{ + const char *value = getenv (envvar); + + if (!value) + return -1; + + return open_temp_exec_file_dir (value); +} + +#ifdef HAVE_MNTENT +/* Open a temporary file in an executable and writable mount point + listed in the mounts file. Subsequent calls with the same mounts + keep searching for mount points in the same file. Providing NULL + as the mounts file closes the file. */ +static int +open_temp_exec_file_mnt (const char *mounts) +{ + static const char *last_mounts; + static FILE *last_mntent; + + if (mounts != last_mounts) + { + if (last_mntent) + endmntent (last_mntent); + + last_mounts = mounts; + + if (mounts) + last_mntent = setmntent (mounts, "r"); + else + last_mntent = NULL; + } + + if (!last_mntent) + return -1; + + for (;;) + { + int fd; + struct mntent mnt; + char buf[MAXPATHLEN * 3]; + + if (getmntent_r (last_mntent, &mnt, buf, sizeof (buf)) == NULL) + return -1; + + if (hasmntopt (&mnt, "ro") + || hasmntopt (&mnt, "noexec") + || access (mnt.mnt_dir, W_OK)) + continue; + + fd = open_temp_exec_file_dir (mnt.mnt_dir); + + if (fd != -1) + return fd; + } +} +#endif /* HAVE_MNTENT */ + +/* Instructions to look for a location to hold a temporary file that + can be mapped in for execution. */ +static struct +{ + int (*func)(const char *); + const char *arg; + int repeat; +} open_temp_exec_file_opts[] = { +#ifdef HAVE_MEMFD_CREATE + { open_temp_exec_file_memfd, "libffi", 0 }, +#endif + { open_temp_exec_file_env, "TMPDIR", 0 }, + { open_temp_exec_file_dir, "/tmp", 0 }, + { open_temp_exec_file_dir, "/var/tmp", 0 }, + { open_temp_exec_file_dir, "/dev/shm", 0 }, + { open_temp_exec_file_env, "HOME", 0 }, +#ifdef HAVE_MNTENT + { open_temp_exec_file_mnt, "/etc/mtab", 1 }, + { open_temp_exec_file_mnt, "/proc/mounts", 1 }, +#endif /* HAVE_MNTENT */ +}; + +/* Current index into open_temp_exec_file_opts. */ +static int open_temp_exec_file_opts_idx = 0; + +/* Reset a current multi-call func, then advances to the next entry. + If we're at the last, go back to the first and return nonzero, + otherwise return zero. */ +static int +open_temp_exec_file_opts_next (void) +{ + if (open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat) + open_temp_exec_file_opts[open_temp_exec_file_opts_idx].func (NULL); + + open_temp_exec_file_opts_idx++; + if (open_temp_exec_file_opts_idx + == (sizeof (open_temp_exec_file_opts) + / sizeof (*open_temp_exec_file_opts))) + { + open_temp_exec_file_opts_idx = 0; + return 1; + } + + return 0; +} + +/* Return a file descriptor of a temporary zero-sized file in a + writable and executable filesystem. */ +static int +open_temp_exec_file (void) +{ + int fd; + + do + { + fd = open_temp_exec_file_opts[open_temp_exec_file_opts_idx].func + (open_temp_exec_file_opts[open_temp_exec_file_opts_idx].arg); + + if (!open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat + || fd == -1) + { + if (open_temp_exec_file_opts_next ()) + break; + } + } + while (fd == -1); + + return fd; +} + +/* We need to allocate space in a file that will be backing a writable + mapping. Several problems exist with the usual approaches: + - fallocate() is Linux-only + - posix_fallocate() is not available on all platforms + - ftruncate() does not allocate space on filesystems with sparse files + Failure to allocate the space will cause SIGBUS to be thrown when + the mapping is subsequently written to. */ +static int +allocate_space (int fd, off_t offset, off_t len) +{ + static size_t page_size; + + /* Obtain system page size. */ + if (!page_size) + page_size = sysconf(_SC_PAGESIZE); + + unsigned char buf[page_size]; + memset (buf, 0, page_size); + + while (len > 0) + { + off_t to_write = (len < page_size) ? len : page_size; + if (write (fd, buf, to_write) < to_write) + return -1; + len -= to_write; + } + + return 0; +} + +/* Map in a chunk of memory from the temporary exec file into separate + locations in the virtual memory address space, one writable and one + executable. Returns the address of the writable portion, after + storing an offset to the corresponding executable portion at the + last word of the requested chunk. */ +static void * +dlmmap_locked (void *start, size_t length, int prot, int flags, off_t offset) +{ + void *ptr; + + if (execfd == -1) + { + open_temp_exec_file_opts_idx = 0; + retry_open: + execfd = open_temp_exec_file (); + if (execfd == -1) + return MFAIL; + } + + offset = execsize; + + if (allocate_space (execfd, offset, length)) + return MFAIL; + + flags &= ~(MAP_PRIVATE | MAP_ANONYMOUS); + flags |= MAP_SHARED; + + ptr = mmap (NULL, length, (prot & ~PROT_WRITE) | PROT_EXEC, + flags, execfd, offset); + if (ptr == MFAIL) + { + if (!offset) + { + close (execfd); + goto retry_open; + } + if (ftruncate (execfd, offset) != 0) + { + /* Fixme : Error logs can be added here. Returning an error for + * ftruncte() will not add any advantage as it is being + * validating in the error case. */ + } + + return MFAIL; + } + else if (!offset + && open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat) + open_temp_exec_file_opts_next (); + + start = mmap (start, length, prot, flags, execfd, offset); + + if (start == MFAIL) + { + munmap (ptr, length); + if (ftruncate (execfd, offset) != 0) + { + /* Fixme : Error logs can be added here. Returning an error for + * ftruncte() will not add any advantage as it is being + * validating in the error case. */ + } + return start; + } + + mmap_exec_offset ((char *)start, length) = (char*)ptr - (char*)start; + + execsize += length; + + return start; +} + +/* Map in a writable and executable chunk of memory if possible. + Failing that, fall back to dlmmap_locked. */ +static void * +dlmmap (void *start, size_t length, int prot, + int flags, int fd, off_t offset) +{ + void *ptr; + + assert (start == NULL && length % malloc_getpagesize == 0 + && prot == (PROT_READ | PROT_WRITE) + && flags == (MAP_PRIVATE | MAP_ANONYMOUS) + && fd == -1 && offset == 0); + + if (execfd == -1 && is_emutramp_enabled ()) + { + ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); + return ptr; + } + + if (execfd == -1 && !is_selinux_enabled ()) + { + ptr = mmap (start, length, prot | PROT_EXEC, flags, fd, offset); + + if (ptr != MFAIL || (errno != EPERM && errno != EACCES)) + /* Cool, no need to mess with separate segments. */ + return ptr; + + /* If MREMAP_DUP is ever introduced and implemented, try mmap + with ((prot & ~PROT_WRITE) | PROT_EXEC) and mremap with + MREMAP_DUP and prot at this point. */ + } + + if (execsize == 0 || execfd == -1) + { + pthread_mutex_lock (&open_temp_exec_file_mutex); + ptr = dlmmap_locked (start, length, prot, flags, offset); + pthread_mutex_unlock (&open_temp_exec_file_mutex); + + return ptr; + } + + return dlmmap_locked (start, length, prot, flags, offset); +} + +/* Release memory at the given address, as well as the corresponding + executable page if it's separate. */ +static int +dlmunmap (void *start, size_t length) +{ + /* We don't bother decreasing execsize or truncating the file, since + we can't quite tell whether we're unmapping the end of the file. + We don't expect frequent deallocation anyway. If we did, we + could locate pages in the file by writing to the pages being + deallocated and checking that the file contents change. + Yuck. */ + msegmentptr seg = segment_holding (gm, start); + void *code; + + if (seg && (code = add_segment_exec_offset (start, seg)) != start) + { + int ret = munmap (code, length); + if (ret) + return ret; + } + + return munmap (start, length); +} + +#if FFI_CLOSURE_FREE_CODE +/* Return segment holding given code address. */ +static msegmentptr +segment_holding_code (mstate m, char* addr) +{ + msegmentptr sp = &m->seg; + for (;;) { + if (addr >= add_segment_exec_offset (sp->base, sp) + && addr < add_segment_exec_offset (sp->base, sp) + sp->size) + return sp; + if ((sp = sp->next) == 0) + return 0; + } +} +#endif + +#endif /* !(defined(_WIN32) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) */ + +/* Allocate a chunk of memory with the given size. Returns a pointer + to the writable address, and sets *CODE to the executable + corresponding virtual address. */ +void * +ffi_closure_alloc (size_t size, void **code) +{ + void *ptr; + + if (!code) + return NULL; + + ptr = FFI_CLOSURE_PTR (dlmalloc (size)); + + if (ptr) + { + msegmentptr seg = segment_holding (gm, ptr); + + *code = add_segment_exec_offset (ptr, seg); + } + + return ptr; +} + +void * +ffi_data_to_code_pointer (void *data) +{ + msegmentptr seg = segment_holding (gm, data); + /* We expect closures to be allocated with ffi_closure_alloc(), in + which case seg will be non-NULL. However, some users take on the + burden of managing this memory themselves, in which case this + we'll just return data. */ + if (seg) + return add_segment_exec_offset (data, seg); + else + return data; +} + +/* Release a chunk of memory allocated with ffi_closure_alloc. If + FFI_CLOSURE_FREE_CODE is nonzero, the given address can be the + writable or the executable address given. Otherwise, only the + writable address can be provided here. */ +void +ffi_closure_free (void *ptr) +{ +#if FFI_CLOSURE_FREE_CODE + msegmentptr seg = segment_holding_code (gm, ptr); + + if (seg) + ptr = sub_segment_exec_offset (ptr, seg); +#endif + + dlfree (FFI_RESTORE_PTR (ptr)); +} + +# else /* ! FFI_MMAP_EXEC_WRIT */ + +/* On many systems, memory returned by malloc is writable and + executable, so just use it. */ + +#include + +void * +ffi_closure_alloc (size_t size, void **code) +{ + if (!code) + return NULL; + + return *code = FFI_CLOSURE_PTR (malloc (size)); +} + +void +ffi_closure_free (void *ptr) +{ + free (FFI_RESTORE_PTR (ptr)); +} + +void * +ffi_data_to_code_pointer (void *data) +{ + return data; +} + +# endif /* ! FFI_MMAP_EXEC_WRIT */ +#endif /* FFI_CLOSURES */ + +#endif /* NetBSD with PROT_MPROTECT */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/cris/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/cris/ffi.c new file mode 100644 index 0000000..9011fde --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/cris/ffi.c @@ -0,0 +1,386 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 1998 Cygnus Solutions + Copyright (c) 2004 Simon Posnjak + Copyright (c) 2005 Axis Communications AB + Copyright (C) 2007 Free Software Foundation, Inc. + + CRIS Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL SIMON POSNJAK BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#define STACK_ARG_SIZE(x) FFI_ALIGN(x, FFI_SIZEOF_ARG) + +static ffi_status +initialize_aggregate_packed_struct (ffi_type * arg) +{ + ffi_type **ptr; + + FFI_ASSERT (arg != NULL); + + FFI_ASSERT (arg->elements != NULL); + FFI_ASSERT (arg->size == 0); + FFI_ASSERT (arg->alignment == 0); + + ptr = &(arg->elements[0]); + + while ((*ptr) != NULL) + { + if (((*ptr)->size == 0) + && (initialize_aggregate_packed_struct ((*ptr)) != FFI_OK)) + return FFI_BAD_TYPEDEF; + + FFI_ASSERT (ffi_type_test ((*ptr))); + + arg->size += (*ptr)->size; + + arg->alignment = (arg->alignment > (*ptr)->alignment) ? + arg->alignment : (*ptr)->alignment; + + ptr++; + } + + if (arg->size == 0) + return FFI_BAD_TYPEDEF; + else + return FFI_OK; +} + +int +ffi_prep_args (char *stack, extended_cif * ecif) +{ + unsigned int i; + unsigned int struct_count = 0; + void **p_argv; + char *argp; + ffi_type **p_arg; + + argp = stack; + + p_argv = ecif->avalue; + + for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; + (i != 0); i--, p_arg++) + { + size_t z; + + switch ((*p_arg)->type) + { + case FFI_TYPE_STRUCT: + { + z = (*p_arg)->size; + if (z <= 4) + { + memcpy (argp, *p_argv, z); + z = 4; + } + else if (z <= 8) + { + memcpy (argp, *p_argv, z); + z = 8; + } + else + { + unsigned int uiLocOnStack; + z = sizeof (void *); + uiLocOnStack = 4 * ecif->cif->nargs + struct_count; + struct_count = struct_count + (*p_arg)->size; + *(unsigned int *) argp = + (unsigned int) (UINT32 *) (stack + uiLocOnStack); + memcpy ((stack + uiLocOnStack), *p_argv, (*p_arg)->size); + } + break; + } + default: + z = (*p_arg)->size; + if (z < sizeof (int)) + { + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int) *(SINT8 *) (*p_argv); + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = + (unsigned int) *(UINT8 *) (*p_argv); + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int) *(SINT16 *) (*p_argv); + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = + (unsigned int) *(UINT16 *) (*p_argv); + break; + + default: + FFI_ASSERT (0); + } + z = sizeof (int); + } + else if (z == sizeof (int)) + *(unsigned int *) argp = (unsigned int) *(UINT32 *) (*p_argv); + else + memcpy (argp, *p_argv, z); + break; + } + p_argv++; + argp += z; + } + + return (struct_count); +} + +ffi_status FFI_HIDDEN +ffi_prep_cif_core (ffi_cif * cif, + ffi_abi abi, unsigned int isvariadic, + unsigned int nfixedargs, unsigned int ntotalargs, + ffi_type * rtype, ffi_type ** atypes) +{ + unsigned bytes = 0; + unsigned int i; + ffi_type **ptr; + + FFI_ASSERT (cif != NULL); + FFI_ASSERT((!isvariadic) || (nfixedargs >= 1)); + FFI_ASSERT(nfixedargs <= ntotalargs); + FFI_ASSERT (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI); + + cif->abi = abi; + cif->arg_types = atypes; + cif->nargs = ntotalargs; + cif->rtype = rtype; + + cif->flags = 0; + + if ((cif->rtype->size == 0) + && (initialize_aggregate_packed_struct (cif->rtype) != FFI_OK)) + return FFI_BAD_TYPEDEF; + + FFI_ASSERT_VALID_TYPE (cif->rtype); + + for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) + { + if (((*ptr)->size == 0) + && (initialize_aggregate_packed_struct ((*ptr)) != FFI_OK)) + return FFI_BAD_TYPEDEF; + + FFI_ASSERT_VALID_TYPE (*ptr); + + if (((*ptr)->alignment - 1) & bytes) + bytes = FFI_ALIGN (bytes, (*ptr)->alignment); + if ((*ptr)->type == FFI_TYPE_STRUCT) + { + if ((*ptr)->size > 8) + { + bytes += (*ptr)->size; + bytes += sizeof (void *); + } + else + { + if ((*ptr)->size > 4) + bytes += 8; + else + bytes += 4; + } + } + else + bytes += STACK_ARG_SIZE ((*ptr)->size); + } + + cif->bytes = bytes; + + return ffi_prep_cif_machdep (cif); +} + +ffi_status +ffi_prep_cif_machdep (ffi_cif * cif) +{ + switch (cif->rtype->type) + { + case FFI_TYPE_VOID: + case FFI_TYPE_STRUCT: + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + cif->flags = (unsigned) cif->rtype->type; + break; + + default: + cif->flags = FFI_TYPE_INT; + break; + } + + return FFI_OK; +} + +extern void ffi_call_SYSV (int (*)(char *, extended_cif *), + extended_cif *, + unsigned, unsigned, unsigned *, void (*fn) ()) + __attribute__ ((__visibility__ ("hidden"))); + +void +ffi_call (ffi_cif * cif, void (*fn) (), void *rvalue, void **avalue) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) + { + ecif.rvalue = alloca (cif->rtype->size); + } + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_SYSV: + ffi_call_SYSV (ffi_prep_args, &ecif, cif->bytes, + cif->flags, ecif.rvalue, fn); + break; + default: + FFI_ASSERT (0); + break; + } +} + +/* Because the following variables are not exported outside libffi, we + mark them hidden. */ + +/* Assembly code for the jump stub. */ +extern const char ffi_cris_trampoline_template[] + __attribute__ ((__visibility__ ("hidden"))); + +/* Offset into ffi_cris_trampoline_template of where to put the + ffi_prep_closure_inner function. */ +extern const int ffi_cris_trampoline_fn_offset + __attribute__ ((__visibility__ ("hidden"))); + +/* Offset into ffi_cris_trampoline_template of where to put the + closure data. */ +extern const int ffi_cris_trampoline_closure_offset + __attribute__ ((__visibility__ ("hidden"))); + +/* This function is sibling-called (jumped to) by the closure + trampoline. We get R10..R13 at PARAMS[0..3] and a copy of [SP] at + PARAMS[4] to simplify handling of a straddling parameter. A copy + of R9 is at PARAMS[5] and SP at PARAMS[6]. These parameters are + put at the appropriate place in CLOSURE which is then executed and + the return value is passed back to the caller. */ + +static unsigned long long +ffi_prep_closure_inner (void **params, ffi_closure* closure) +{ + char *register_args = (char *) params; + void *struct_ret = params[5]; + char *stack_args = params[6]; + char *ptr = register_args; + ffi_cif *cif = closure->cif; + ffi_type **arg_types = cif->arg_types; + + /* Max room needed is number of arguments as 64-bit values. */ + void **avalue = alloca (closure->cif->nargs * sizeof(void *)); + int i; + int doing_regs; + long long llret = 0; + + /* Find the address of each argument. */ + for (i = 0, doing_regs = 1; i < cif->nargs; i++) + { + /* Types up to and including 8 bytes go by-value. */ + if (arg_types[i]->size <= 4) + { + avalue[i] = ptr; + ptr += 4; + } + else if (arg_types[i]->size <= 8) + { + avalue[i] = ptr; + ptr += 8; + } + else + { + FFI_ASSERT (arg_types[i]->type == FFI_TYPE_STRUCT); + + /* Passed by-reference, so copy the pointer. */ + avalue[i] = *(void **) ptr; + ptr += 4; + } + + /* If we've handled more arguments than fit in registers, start + looking at the those passed on the stack. Step over the + first one if we had a straddling parameter. */ + if (doing_regs && ptr >= register_args + 4*4) + { + ptr = stack_args + ((ptr > register_args + 4*4) ? 4 : 0); + doing_regs = 0; + } + } + + /* Invoke the closure. */ + (closure->fun) (cif, + + cif->rtype->type == FFI_TYPE_STRUCT + /* The caller allocated space for the return + structure, and passed a pointer to this space in + R9. */ + ? struct_ret + + /* We take advantage of being able to ignore that + the high part isn't set if the return value is + not in R10:R11, but in R10 only. */ + : (void *) &llret, + + avalue, closure->user_data); + + return llret; +} + +/* API function: Prepare the trampoline. */ + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif *, void *, void **, void*), + void *user_data, + void *codeloc) +{ + void *innerfn = ffi_prep_closure_inner; + FFI_ASSERT (cif->abi == FFI_SYSV); + closure->cif = cif; + closure->user_data = user_data; + closure->fun = fun; + memcpy (closure->tramp, ffi_cris_trampoline_template, + FFI_CRIS_TRAMPOLINE_CODE_PART_SIZE); + memcpy (closure->tramp + ffi_cris_trampoline_fn_offset, + &innerfn, sizeof (void *)); + memcpy (closure->tramp + ffi_cris_trampoline_closure_offset, + &codeloc, sizeof (void *)); + + return FFI_OK; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/cris/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/cris/ffitarget.h new file mode 100644 index 0000000..b837e97 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/cris/ffitarget.h @@ -0,0 +1,56 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 1996-2003 Red Hat, Inc. + Target configuration macros for CRIS. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_CRIS_TRAMPOLINE_CODE_PART_SIZE 36 +#define FFI_CRIS_TRAMPOLINE_DATA_PART_SIZE (7*4) +#define FFI_TRAMPOLINE_SIZE \ + (FFI_CRIS_TRAMPOLINE_CODE_PART_SIZE + FFI_CRIS_TRAMPOLINE_DATA_PART_SIZE) +#define FFI_NATIVE_RAW_API 0 + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/cris/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/cris/sysv.S new file mode 100644 index 0000000..79abaee --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/cris/sysv.S @@ -0,0 +1,215 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2004 Simon Posnjak + Copyright (c) 2005 Axis Communications AB + + CRIS Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL SIMON POSNJAK BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#define CONCAT(x,y) x ## y +#define XCONCAT(x,y) CONCAT (x, y) +#define L(x) XCONCAT (__USER_LABEL_PREFIX__, x) + + .text + + ;; OK, when we get called we should have this (according to + ;; AXIS ETRAX 100LX Programmer's Manual chapter 6.3). + ;; + ;; R10: ffi_prep_args (func. pointer) + ;; R11: &ecif + ;; R12: cif->bytes + ;; R13: fig->flags + ;; sp+0: ecif.rvalue + ;; sp+4: fn (function pointer to the function that we need to call) + + .globl L(ffi_call_SYSV) + .type L(ffi_call_SYSV),@function + .hidden L(ffi_call_SYSV) + +L(ffi_call_SYSV): + ;; Save the regs to the stack. + push $srp + ;; Used for stack pointer saving. + push $r6 + ;; Used for function address pointer. + push $r7 + ;; Used for stack pointer saving. + push $r8 + ;; We save fig->flags to stack we will need them after we + ;; call The Function. + push $r13 + + ;; Saving current stack pointer. + move.d $sp,$r8 + move.d $sp,$r6 + + ;; Move address of ffi_prep_args to r13. + move.d $r10,$r13 + + ;; Make room on the stack for the args of fn. + sub.d $r12,$sp + + ;; Function void ffi_prep_args(char *stack, extended_cif *ecif) parameters are: + ;; r10 <-- stack pointer + ;; r11 <-- &ecif (already there) + move.d $sp,$r10 + + ;; Call the function. + jsr $r13 + + ;; Save the size of the structures which are passed on stack. + move.d $r10,$r7 + + ;; Move first four args in to r10..r13. + move.d [$sp+0],$r10 + move.d [$sp+4],$r11 + move.d [$sp+8],$r12 + move.d [$sp+12],$r13 + + ;; Adjust the stack and check if any parameters are given on stack. + addq 16,$sp + sub.d $r7,$r6 + cmp.d $sp,$r6 + + bpl go_on + nop + +go_on_no_params_on_stack: + move.d $r6,$sp + +go_on: + ;; Discover if we need to put rval address in to r9. + move.d [$r8+0],$r7 + cmpq FFI_TYPE_STRUCT,$r7 + bne call_now + nop + + ;; Move rval address to $r9. + move.d [$r8+20],$r9 + +call_now: + ;; Move address of The Function in to r7. + move.d [$r8+24],$r7 + + ;; Call The Function. + jsr $r7 + + ;; Reset stack. + move.d $r8,$sp + + ;; Load rval type (fig->flags) in to r13. + pop $r13 + + ;; Detect rval type. + cmpq FFI_TYPE_VOID,$r13 + beq epilogue + + cmpq FFI_TYPE_STRUCT,$r13 + beq epilogue + + cmpq FFI_TYPE_DOUBLE,$r13 + beq return_double_or_longlong + + cmpq FFI_TYPE_UINT64,$r13 + beq return_double_or_longlong + + cmpq FFI_TYPE_SINT64,$r13 + beq return_double_or_longlong + nop + + ;; Just return the 32 bit value. + ba return + nop + +return_double_or_longlong: + ;; Load half of the rval to r10 and the other half to r11. + move.d [$sp+16],$r13 + move.d $r10,[$r13] + addq 4,$r13 + move.d $r11,[$r13] + ba epilogue + nop + +return: + ;; Load the rval to r10. + move.d [$sp+16],$r13 + move.d $r10,[$r13] + +epilogue: + pop $r8 + pop $r7 + pop $r6 + Jump [$sp+] + + .size ffi_call_SYSV,.-ffi_call_SYSV + +/* Save R10..R13 into an array, somewhat like varargs. Copy the next + argument too, to simplify handling of any straddling parameter. + Save R9 and SP after those. Jump to function handling the rest. + Since this is a template, copied and the main function filled in by + the user. */ + + .globl L(ffi_cris_trampoline_template) + .type L(ffi_cris_trampoline_template),@function + .hidden L(ffi_cris_trampoline_template) + +L(ffi_cris_trampoline_template): +0: + /* The value we get for "PC" is right after the prefix instruction, + two bytes from the beginning, i.e. 0b+2. */ + move.d $r10,[$pc+2f-(0b+2)] + move.d $pc,$r10 +1: + addq 2f-1b+4,$r10 + move.d $r11,[$r10+] + move.d $r12,[$r10+] + move.d $r13,[$r10+] + move.d [$sp],$r11 + move.d $r11,[$r10+] + move.d $r9,[$r10+] + move.d $sp,[$r10+] + subq FFI_CRIS_TRAMPOLINE_DATA_PART_SIZE,$r10 + move.d 0,$r11 +3: + jump 0 +2: + .size ffi_cris_trampoline_template,.-0b + +/* This macro create a constant usable as "extern const int \name" in + C from within libffi, when \name has no prefix decoration. */ + + .macro const name,value + .globl \name + .type \name,@object + .hidden \name +\name: + .dword \value + .size \name,4 + .endm + +/* Constants for offsets within the trampoline. We could do this with + just symbols, avoiding memory contents and memory accesses, but the + C usage code would look a bit stranger. */ + + const L(ffi_cris_trampoline_fn_offset),2b-4-0b + const L(ffi_cris_trampoline_closure_offset),3b-4-0b diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/csky/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/csky/ffi.c new file mode 100644 index 0000000..af50b7c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/csky/ffi.c @@ -0,0 +1,395 @@ +/* ----------------------------------------------------------------------- + ffi.c + + CSKY Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments +*/ +void ffi_prep_args(char *stack, extended_cif *ecif) +{ + register unsigned int i; + register void **p_argv; + register char *argp; + register ffi_type **p_arg; + + argp = stack; + + if ( ecif->cif->flags == FFI_TYPE_STRUCT ) { + *(void **) argp = ecif->rvalue; + argp += 4; + } + + p_argv = ecif->avalue; + + for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; + (i != 0); + i--, p_arg++) + { + size_t z; + size_t alignment; + + /* Align if necessary */ + alignment = (*p_arg)->alignment; +#ifdef __CSKYABIV1__ + /* + * Adapt ABIV1 bug. + * If struct's size is larger than 8 bytes, then it always alignment as 4 bytes. + */ + if (((*p_arg)->type == FFI_TYPE_STRUCT) && ((*p_arg)->size > 8) && (alignment == 8)) { + alignment = 4; + } +#endif + + if ((alignment - 1) & (unsigned) argp) { + argp = (char *) FFI_ALIGN(argp, alignment); + } + + if ((*p_arg)->type == FFI_TYPE_STRUCT) + argp = (char *) FFI_ALIGN(argp, 4); + + z = (*p_arg)->size; + if (z < sizeof(int)) + { + z = sizeof(int); + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); + break; + + case FFI_TYPE_STRUCT: +#ifdef __CSKYBE__ + memcpy((argp + 4 - (*p_arg)->size), *p_argv, (*p_arg)->size); +#else + memcpy(argp, *p_argv, (*p_arg)->size); +#endif + break; + + default: + FFI_ASSERT(0); + } + } + else if (z == sizeof(int)) + { + *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); + } + else + { + memcpy(argp, *p_argv, z); + } + p_argv++; + argp += z; + } + + return; +} + +/* Perform machine dependent cif processing */ +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + /* Round the stack up to a multiple of 8 bytes. This isn't needed + everywhere, but it is on some platforms, and it doesn't hcsky anything + when it isn't needed. */ + cif->bytes = (cif->bytes + 7) & ~7; + + /* Set the return type flag */ + switch (cif->rtype->type) + { + + case FFI_TYPE_DOUBLE: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + cif->flags = (unsigned) FFI_TYPE_SINT64; + break; + + case FFI_TYPE_STRUCT: + if (cif->rtype->size <= 4) + /* A Composite Type not larger than 4 bytes is returned in r0. */ + cif->flags = (unsigned)FFI_TYPE_INT; + else if (cif->rtype->size <= 8) + /* A Composite Type not larger than 8 bytes is returned in r0, r1. */ + cif->flags = (unsigned)FFI_TYPE_SINT64; + else + /* A Composite Type larger than 8 bytes, or whose size cannot + be determined statically ... is stored in memory at an + address passed [in r0]. */ + cif->flags = (unsigned)FFI_TYPE_STRUCT; + break; + + default: + cif->flags = FFI_TYPE_INT; + break; + } + + return FFI_OK; +} + +/* Perform machine dependent cif processing for variadic calls */ +ffi_status ffi_prep_cif_machdep_var(ffi_cif *cif, + unsigned int nfixedargs, + unsigned int ntotalargs) +{ + return ffi_prep_cif_machdep(cif); +} + +/* Prototypes for assembly functions, in sysv.S */ +extern void ffi_call_SYSV (void (*fn)(void), extended_cif *, unsigned, unsigned, unsigned *); + +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + extended_cif ecif; + + int small_struct = (cif->flags == FFI_TYPE_INT + && cif->rtype->type == FFI_TYPE_STRUCT); + + ecif.cif = cif; + ecif.avalue = avalue; + + unsigned int temp; + + /* If the return value is a struct and we don't have a return */ + /* value address then we need to make one */ + + if ((rvalue == NULL) && + (cif->flags == FFI_TYPE_STRUCT)) + { + ecif.rvalue = alloca(cif->rtype->size); + } + else if (small_struct) + ecif.rvalue = &temp; + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_SYSV: + ffi_call_SYSV (fn, &ecif, cif->bytes, cif->flags, ecif.rvalue); + break; + + default: + FFI_ASSERT(0); + break; + } + if (small_struct) +#ifdef __CSKYBE__ + memcpy (rvalue, ((unsigned char *)&temp + (4 - cif->rtype->size)), cif->rtype->size); +#else + memcpy (rvalue, &temp, cif->rtype->size); +#endif +} + +/** private members **/ + +static void ffi_prep_incoming_args_SYSV (char *stack, void **ret, + void** args, ffi_cif* cif); + +void ffi_closure_SYSV (ffi_closure *); + +/* This function is jumped to by the trampoline */ + +unsigned int +ffi_closure_SYSV_inner (closure, respp, args) + ffi_closure *closure; + void **respp; + void *args; +{ + // our various things... + ffi_cif *cif; + void **arg_area; + + cif = closure->cif; + arg_area = (void**) alloca (cif->nargs * sizeof (void*)); + + /* this call will initialize ARG_AREA, such that each + * element in that array points to the corresponding + * value on the stack; and if the function returns + * a structure, it will re-set RESP to point to the + * structure return address. */ + + ffi_prep_incoming_args_SYSV(args, respp, arg_area, cif); + + (closure->fun) (cif, *respp, arg_area, closure->user_data); + +#ifdef __CSKYBE__ + if (cif->flags == FFI_TYPE_INT && cif->rtype->type == FFI_TYPE_STRUCT) { + unsigned int tmp = 0; + tmp = *(unsigned int *)(*respp); + *(unsigned int *)(*respp) = (tmp >> ((4 - cif->rtype->size) * 8)); + } +#endif + + return cif->flags; +} + + +static void +ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, + void **avalue, ffi_cif *cif) +{ + register unsigned int i; + register void **p_argv; + register char *argp; + register ffi_type **p_arg; + + argp = stack; + + if ( cif->flags == FFI_TYPE_STRUCT ) { + *rvalue = *(void **) argp; + argp += 4; + } + + p_argv = avalue; + + for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) + { + size_t z; + size_t alignment; + + alignment = (*p_arg)->alignment; + if (alignment < 4) + alignment = 4; + +#ifdef __CSKYABIV1__ + /* + * Adapt ABIV1 bug. + * If struct's size is larger than 8 bytes, then it always alignment as 4 bytes. + */ + if (((*p_arg)->type == FFI_TYPE_STRUCT) && ((*p_arg)->size > 8) && (alignment == 8)) { + alignment = 4; + } +#endif + + /* Align if necessary */ + if ((alignment - 1) & (unsigned) argp) { + argp = (char *) FFI_ALIGN(argp, alignment); + } + + z = (*p_arg)->size; + +#ifdef __CSKYBE__ + unsigned int tmp = 0; + if ((*p_arg)->size < 4) { + tmp = *(unsigned int *)argp; + memcpy(argp, ((unsigned char *)&tmp + (4 - (*p_arg)->size)), (*p_arg)->size); + } +#else + /* because we're little endian, this is what it turns into. */ +#endif + *p_argv = (void*) argp; + + p_argv++; + argp += z; + } + + return; +} + +/* How to make a trampoline. */ + +extern unsigned char ffi_csky_trampoline[TRAMPOLINE_SIZE]; + +/* + * Since there is no __clear_cache in libgcc in csky toolchain. + * define ffi_csky_cacheflush in sysv.S. + * void ffi_csky_cacheflush(uint32 start_addr, uint32 size, int cache) + */ +#define CACHEFLUSH_IN_FFI 1 +#if CACHEFLUSH_IN_FFI +extern void ffi_csky_cacheflush(unsigned char *__tramp, unsigned int k, + int i); +#define FFI_INIT_TRAMPOLINE(TRAMP,FUN,CTX) \ +({ unsigned char *__tramp = (unsigned char*)(TRAMP); \ + unsigned int __fun = (unsigned int)(FUN); \ + unsigned int __ctx = (unsigned int)(CTX); \ + unsigned char *insns = (unsigned char *)(CTX); \ + memcpy (__tramp, ffi_csky_trampoline, TRAMPOLINE_SIZE); \ + *(unsigned int*) &__tramp[TRAMPOLINE_SIZE] = __ctx; \ + *(unsigned int*) &__tramp[TRAMPOLINE_SIZE + 4] = __fun; \ + ffi_csky_cacheflush(&__tramp[0], TRAMPOLINE_SIZE, 3); /* Clear data mapping. */ \ + ffi_csky_cacheflush(insns, TRAMPOLINE_SIZE, 3); \ + /* Clear instruction \ + mapping. */ \ + }) +#else +#define FFI_INIT_TRAMPOLINE(TRAMP,FUN,CTX) \ +({ unsigned char *__tramp = (unsigned char*)(TRAMP); \ + unsigned int __fun = (unsigned int)(FUN); \ + unsigned int __ctx = (unsigned int)(CTX); \ + unsigned char *insns = (unsigned char *)(CTX); \ + memcpy (__tramp, ffi_csky_trampoline, TRAMPOLINE_SIZE); \ + *(unsigned int*) &__tramp[TRAMPOLINE_SIZE] = __ctx; \ + *(unsigned int*) &__tramp[TRAMPOLINE_SIZE + 4] = __fun; \ + __clear_cache((&__tramp[0]), (&__tramp[TRAMPOLINE_SIZE-1])); /* Clear data mapping. */ \ + __clear_cache(insns, insns + TRAMPOLINE_SIZE); \ + /* Clear instruction \ + mapping. */ \ + }) +#endif + +/* the cif must already be prep'ed */ + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + void (*closure_func)(ffi_closure*) = NULL; + + if (cif->abi == FFI_SYSV) + closure_func = &ffi_closure_SYSV; + else + return FFI_BAD_ABI; + + FFI_INIT_TRAMPOLINE (&closure->tramp[0], \ + closure_func, \ + codeloc); + + closure->cif = cif; + closure->user_data = user_data; + closure->fun = fun; + + return FFI_OK; +} + + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/csky/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/csky/ffitarget.h new file mode 100644 index 0000000..f770aac --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/csky/ffitarget.h @@ -0,0 +1,63 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 2010 CodeSourcery + Copyright (c) 1996-2003 Red Hat, Inc. + + Target configuration macros for CSKY. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV, +} ffi_abi; +#endif + +#ifdef __CSKYABIV2__ +#define FFI_ASM_ARGREG_SIZE 16 +#define TRAMPOLINE_SIZE 16 +#define FFI_TRAMPOLINE_SIZE 24 +#else +#define FFI_ASM_ARGREG_SIZE 24 +#define TRAMPOLINE_SIZE 20 +#define FFI_TRAMPOLINE_SIZE 28 +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/csky/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/csky/sysv.S new file mode 100644 index 0000000..21670bf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/csky/sysv.S @@ -0,0 +1,371 @@ +/* ----------------------------------------------------------------------- + sysv.S + + CSKY Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + +.macro CSKY_FUNC_START name + .text + .align 2 + .globl \name + .type \name, @function + \name: +.endm + +#ifdef __CSKYABIV2__ + + /* + * a0: fn + * a1: &ecif + * a2: cif->bytes + * a3: fig->flags + * sp+0: ecif.rvalue + */ +CSKY_FUNC_START ffi_call_SYSV + /* Save registers */ + .cfi_startproc + subi sp, 28 + .cfi_def_cfa_offset 28 + stw a0, (sp, 0x0) + .cfi_offset 0, -28 + stw a1, (sp, 0x4) + .cfi_offset 1, -24 + stw a2, (sp, 0x8) + .cfi_offset 2, -20 + stw a3, (sp, 0xC) + .cfi_offset 3, -16 + stw l0, (sp, 0x10) + .cfi_offset 4, -12 + stw l1, (sp, 0x14) + .cfi_offset 5, -8 + stw lr, (sp, 0x18) + .cfi_offset 15, -4 + + mov l0, sp + .cfi_def_cfa_register 4 + + /* Make room for all of the new args. */ + subu sp, sp, a2 + + /* Place all of the ffi_prep_args in position */ + mov a0, sp + /* a1 already set */ + + /* Call ffi_prep_args(stack, &ecif) */ + jsri ffi_prep_args + + /* move first 4 parameters in registers */ + ldw a0, (sp, 0x0) + ldw a1, (sp, 0x4) + ldw a2, (sp, 0x8) + ldw a3, (sp, 0xC) + + /* and adjust stack */ + subu lr, l0, sp /* cif->bytes == l0 - sp */ + cmphsi lr, 16 + movi l1, 16 + movt lr, l1 + addu sp, sp, lr + + ldw l1, (l0, 0) /* load fn() in advance */ + + /* call (fn) (...) */ + jsr l1 + + /* Remove the space we pushed for the args */ + mov sp, l0 + + /* Load r2 with the pointer to storage for the return value */ + ldw a2, (sp, 0x1C) + + /* Load r3 with the return type code */ + ldw a3, (sp, 0xC) + + /* If the return value pointer is NULL, assume no return value. */ + cmpnei a2, 0 + bf .Lepilogue + + cmpnei a3, FFI_TYPE_STRUCT + bf .Lepilogue + + /* return INT64 */ + cmpnei a3, FFI_TYPE_SINT64 + bt .Lretint + /* stw a0, (a2, 0x0) at .Lretint */ + stw a1, (a2, 0x4) + +.Lretint: + /* return INT */ + stw a0, (a2, 0x0) + +.Lepilogue: + ldw a0, (sp, 0x0) + ldw a1, (sp, 0x4) + ldw a2, (sp, 0x8) + ldw a3, (sp, 0xC) + ldw l0, (sp, 0x10) + ldw l1, (sp, 0x14) + ldw lr, (sp, 0x18) + addi sp, sp, 28 + rts + .cfi_endproc + .size ffi_call_SYSV, .-ffi_call_SYSV + + + /* + * unsigned int FFI_HIDDEN + * ffi_closure_SYSV_inner (closure, respp, args) + * ffi_closure *closure; + * void **respp; + * void *args; + */ +CSKY_FUNC_START ffi_closure_SYSV + .cfi_startproc + mov a2, sp + addi a1, sp, 16 + subi sp, sp, 24 + .cfi_def_cfa_offset 40 + stw a1, (sp, 0x10) + .cfi_offset 1, -24 + stw lr, (sp, 0x14) + .cfi_offset 15, -20 + stw sp, (sp, 0x8) + addi a1, sp, 8 + jsri ffi_closure_SYSV_inner + ldw a0, (sp, 0x0) + /* + * if FFI_TYPE_SINT64, need a1. + * if FFI_TYPE_INT, ignore a1. + */ + ldw a1, (sp, 0x4) + + ldw lr, (sp, 0x14) + addi sp, sp, 40 + rts + .cfi_endproc + .size ffi_closure_SYSV, .-ffi_closure_SYSV + +CSKY_FUNC_START ffi_csky_trampoline + subi sp, sp, 16 + stw a0, (sp, 0x0) + stw a1, (sp, 0x4) + stw a2, (sp, 0x8) + stw a3, (sp, 0xC) + lrw a0, [.Lctx] + lrw a1, [.Lfun] + jmp a1 +.Lctx: + mov a0, a0 + mov a0, a0 +.Lfun: + + .size ffi_csky_trampoline, .-ffi_csky_trampoline + +CSKY_FUNC_START ffi_csky_cacheflush + mov t0, r7 + movi r7, 123 + trap 0 + mov r7, t0 + rts + + .size ffi_csky_cacheflush, .-ffi_csky_cacheflush + +#else /* !__CSKYABIV2__ */ + + /* + * a0: fn + * a1: &ecif + * a2: cif->bytes + * a3: fig->flags + * a4: ecif.rvalue + */ +CSKY_FUNC_START ffi_call_SYSV + /* Save registers */ + .cfi_startproc + subi sp, 32 + subi sp, 8 + .cfi_def_cfa_offset 40 + stw a0, (sp, 0x0) + .cfi_offset 2, -40 + stw a1, (sp, 0x4) + .cfi_offset 3, -36 + stw a2, (sp, 0x8) + .cfi_offset 4, -32 + stw a3, (sp, 0xC) + .cfi_offset 5, -28 + stw a4, (sp, 0x10) + .cfi_offset 6, -24 + stw a5, (sp, 0x14) + .cfi_offset 7, -20 + stw l0, (sp, 0x18) + .cfi_offset 8, -16 + stw l1, (sp, 0x1C) + .cfi_offset 9, -12 + stw lr, (sp, 0x20) + .cfi_offset 15, -8 + + mov l0, sp + .cfi_def_cfa_register 8 + + /* Make room for all of the new args. */ + subu sp, sp, a2 + + /* Place all of the ffi_prep_args in position */ + mov a0, sp + /* a1 already set */ + + /* Call ffi_prep_args(stack, &ecif) */ + jsri ffi_prep_args + + /* move first 4 parameters in registers */ + ldw a0, (sp, 0x0) + ldw a1, (sp, 0x4) + ldw a2, (sp, 0x8) + ldw a3, (sp, 0xC) + ldw a4, (sp, 0x10) + ldw a5, (sp, 0x14) + + /* and adjust stack */ + mov lr, l0 + subu lr, sp /* cif->bytes == l0 - sp */ + movi l1, 24 + cmphs lr, l1 + movt lr, l1 + addu sp, sp, lr + + ldw l1, (l0, 0) /* load fn() in advance */ + + /* call (fn) (...) */ + jsr l1 + + /* Remove the space we pushed for the args */ + mov sp, l0 + + /* Load r2 with the pointer to storage for the return value */ + ldw a2, (sp, 0x10) + + /* Load r3 with the return type code */ + ldw a3, (sp, 0xC) + + /* If the return value pointer is NULL, assume no return value. */ + cmpnei a2, 0 + bf .Lepilogue + + cmpnei a3, FFI_TYPE_STRUCT + bf .Lepilogue + + /* return INT64 */ + cmpnei a3, FFI_TYPE_SINT64 + bt .Lretint + /* stw a0, (a2, 0x0) at .Lretint */ + stw a1, (a2, 0x4) + +.Lretint: + /* return INT */ + stw a0, (a2, 0x0) + +.Lepilogue: + ldw a0, (sp, 0x0) + ldw a1, (sp, 0x4) + ldw a2, (sp, 0x8) + ldw a3, (sp, 0xC) + ldw a4, (sp, 0x10) + ldw a5, (sp, 0x14) + ldw l0, (sp, 0x18) + ldw l1, (sp, 0x1C) + ldw lr, (sp, 0x20) + addi sp, sp, 32 + addi sp, sp, 8 + rts + .cfi_endproc + + .size ffi_call_SYSV, .-ffi_call_SYSV + + + /* + * unsigned int FFI_HIDDEN + * ffi_closure_SYSV_inner (closure, respp, args) + * ffi_closure *closure; + * void **respp; + * void *args; + */ +CSKY_FUNC_START ffi_closure_SYSV + .cfi_startproc + mov a2, sp + mov a1, sp + addi a1, 24 + subi sp, sp, 24 + .cfi_def_cfa_offset 48 + stw a1, (sp, 0x10) + .cfi_offset 3, -32 + stw lr, (sp, 0x14) + .cfi_offset 15, -28 + stw sp, (sp, 0x8) + mov a1, sp + addi a1, 8 + jsri ffi_closure_SYSV_inner + ldw a0, (sp, 0x0) + /* + * if FFI_TYPE_SINT64, need a1. + * if FFI_TYPE_INT, ignore a1. + */ + ldw a1, (sp, 0x4) + + ldw lr, (sp, 0x14) + addi sp, sp, 24 + addi sp, sp, 24 + rts + .cfi_endproc + + .size ffi_closure_SYSV, .-ffi_closure_SYSV + +CSKY_FUNC_START ffi_csky_trampoline + subi sp, 24 + stw a0, (sp, 0x0) + stw a1, (sp, 0x4) + stw a2, (sp, 0x8) + stw a3, (sp, 0xC) + stw a4, (sp, 0x10) + stw a5, (sp, 0x14) + lrw a0, [.Lctx] + lrw a1, [.Lfun] + jmp a1 +.Lctx: + mov a0, a0 + mov a0, a0 +.Lfun: + + .size ffi_csky_trampoline, .-ffi_csky_trampoline + +CSKY_FUNC_START ffi_csky_cacheflush + lrw r1, 123 + trap 0 + rts + + .size ffi_csky_cacheflush, .-ffi_csky_cacheflush + +#endif /* __CSKYABIV2__ */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/debug.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/debug.c new file mode 100644 index 0000000..f3172b1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/debug.c @@ -0,0 +1,64 @@ +/* ----------------------------------------------------------------------- + debug.c - Copyright (c) 1996 Red Hat, Inc. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include +#include +#include + +/* General debugging routines */ + +void ffi_stop_here(void) +{ + /* This function is only useful for debugging purposes. + Place a breakpoint on ffi_stop_here to be notified of + significant events. */ +} + +/* This function should only be called via the FFI_ASSERT() macro */ + +void ffi_assert(char *expr, char *file, int line) +{ + fprintf(stderr, "ASSERTION FAILURE: %s at %s:%d\n", expr, file, line); + ffi_stop_here(); + abort(); +} + +/* Perform a sanity check on an ffi_type structure */ + +void ffi_type_test(ffi_type *a, char *file, int line) +{ + FFI_ASSERT_AT(a != NULL, file, line); + + FFI_ASSERT_AT(a->type <= FFI_TYPE_LAST, file, line); + FFI_ASSERT_AT(a->type == FFI_TYPE_VOID || a->size > 0, file, line); + FFI_ASSERT_AT(a->type == FFI_TYPE_VOID || a->alignment > 0, file, line); + FFI_ASSERT_AT((a->type != FFI_TYPE_STRUCT && a->type != FFI_TYPE_COMPLEX) + || a->elements != NULL, file, line); + FFI_ASSERT_AT(a->type != FFI_TYPE_COMPLEX + || (a->elements != NULL + && a->elements[0] != NULL && a->elements[1] == NULL), + file, line); + +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/dlmalloc.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/dlmalloc.c new file mode 100644 index 0000000..1aba657 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/dlmalloc.c @@ -0,0 +1,5166 @@ +/* + This is a version (aka dlmalloc) of malloc/free/realloc written by + Doug Lea and released to the public domain, as explained at + http://creativecommons.org/licenses/publicdomain. Send questions, + comments, complaints, performance data, etc to dl@cs.oswego.edu + +* Version 2.8.3 Thu Sep 22 11:16:15 2005 Doug Lea (dl at gee) + + Note: There may be an updated version of this malloc obtainable at + ftp://gee.cs.oswego.edu/pub/misc/malloc.c + Check before installing! + +* Quickstart + + This library is all in one file to simplify the most common usage: + ftp it, compile it (-O3), and link it into another program. All of + the compile-time options default to reasonable values for use on + most platforms. You might later want to step through various + compile-time and dynamic tuning options. + + For convenience, an include file for code using this malloc is at: + ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.3.h + You don't really need this .h file unless you call functions not + defined in your system include files. The .h file contains only the + excerpts from this file needed for using this malloc on ANSI C/C++ + systems, so long as you haven't changed compile-time options about + naming and tuning parameters. If you do, then you can create your + own malloc.h that does include all settings by cutting at the point + indicated below. Note that you may already by default be using a C + library containing a malloc that is based on some version of this + malloc (for example in linux). You might still want to use the one + in this file to customize settings or to avoid overheads associated + with library versions. + +* Vital statistics: + + Supported pointer/size_t representation: 4 or 8 bytes + size_t MUST be an unsigned type of the same width as + pointers. (If you are using an ancient system that declares + size_t as a signed type, or need it to be a different width + than pointers, you can use a previous release of this malloc + (e.g. 2.7.2) supporting these.) + + Alignment: 8 bytes (default) + This suffices for nearly all current machines and C compilers. + However, you can define MALLOC_ALIGNMENT to be wider than this + if necessary (up to 128bytes), at the expense of using more space. + + Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes) + 8 or 16 bytes (if 8byte sizes) + Each malloced chunk has a hidden word of overhead holding size + and status information, and additional cross-check word + if FOOTERS is defined. + + Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead) + 8-byte ptrs: 32 bytes (including overhead) + + Even a request for zero bytes (i.e., malloc(0)) returns a + pointer to something of the minimum allocatable size. + The maximum overhead wastage (i.e., number of extra bytes + allocated than were requested in malloc) is less than or equal + to the minimum size, except for requests >= mmap_threshold that + are serviced via mmap(), where the worst case wastage is about + 32 bytes plus the remainder from a system page (the minimal + mmap unit); typically 4096 or 8192 bytes. + + Security: static-safe; optionally more or less + The "security" of malloc refers to the ability of malicious + code to accentuate the effects of errors (for example, freeing + space that is not currently malloc'ed or overwriting past the + ends of chunks) in code that calls malloc. This malloc + guarantees not to modify any memory locations below the base of + heap, i.e., static variables, even in the presence of usage + errors. The routines additionally detect most improper frees + and reallocs. All this holds as long as the static bookkeeping + for malloc itself is not corrupted by some other means. This + is only one aspect of security -- these checks do not, and + cannot, detect all possible programming errors. + + If FOOTERS is defined nonzero, then each allocated chunk + carries an additional check word to verify that it was malloced + from its space. These check words are the same within each + execution of a program using malloc, but differ across + executions, so externally crafted fake chunks cannot be + freed. This improves security by rejecting frees/reallocs that + could corrupt heap memory, in addition to the checks preventing + writes to statics that are always on. This may further improve + security at the expense of time and space overhead. (Note that + FOOTERS may also be worth using with MSPACES.) + + By default detected errors cause the program to abort (calling + "abort()"). You can override this to instead proceed past + errors by defining PROCEED_ON_ERROR. In this case, a bad free + has no effect, and a malloc that encounters a bad address + caused by user overwrites will ignore the bad address by + dropping pointers and indices to all known memory. This may + be appropriate for programs that should continue if at all + possible in the face of programming errors, although they may + run out of memory because dropped memory is never reclaimed. + + If you don't like either of these options, you can define + CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything + else. And if if you are sure that your program using malloc has + no errors or vulnerabilities, you can define INSECURE to 1, + which might (or might not) provide a small performance improvement. + + Thread-safety: NOT thread-safe unless USE_LOCKS defined + When USE_LOCKS is defined, each public call to malloc, free, + etc is surrounded with either a pthread mutex or a win32 + spinlock (depending on WIN32). This is not especially fast, and + can be a major bottleneck. It is designed only to provide + minimal protection in concurrent environments, and to provide a + basis for extensions. If you are using malloc in a concurrent + program, consider instead using ptmalloc, which is derived from + a version of this malloc. (See http://www.malloc.de). + + System requirements: Any combination of MORECORE and/or MMAP/MUNMAP + This malloc can use unix sbrk or any emulation (invoked using + the CALL_MORECORE macro) and/or mmap/munmap or any emulation + (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system + memory. On most unix systems, it tends to work best if both + MORECORE and MMAP are enabled. On Win32, it uses emulations + based on VirtualAlloc. It also uses common C library functions + like memset. + + Compliance: I believe it is compliant with the Single Unix Specification + (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably + others as well. + +* Overview of algorithms + + This is not the fastest, most space-conserving, most portable, or + most tunable malloc ever written. However it is among the fastest + while also being among the most space-conserving, portable and + tunable. Consistent balance across these factors results in a good + general-purpose allocator for malloc-intensive programs. + + In most ways, this malloc is a best-fit allocator. Generally, it + chooses the best-fitting existing chunk for a request, with ties + broken in approximately least-recently-used order. (This strategy + normally maintains low fragmentation.) However, for requests less + than 256bytes, it deviates from best-fit when there is not an + exactly fitting available chunk by preferring to use space adjacent + to that used for the previous small request, as well as by breaking + ties in approximately most-recently-used order. (These enhance + locality of series of small allocations.) And for very large requests + (>= 256Kb by default), it relies on system memory mapping + facilities, if supported. (This helps avoid carrying around and + possibly fragmenting memory used only for large chunks.) + + All operations (except malloc_stats and mallinfo) have execution + times that are bounded by a constant factor of the number of bits in + a size_t, not counting any clearing in calloc or copying in realloc, + or actions surrounding MORECORE and MMAP that have times + proportional to the number of non-contiguous regions returned by + system allocation routines, which is often just 1. + + The implementation is not very modular and seriously overuses + macros. Perhaps someday all C compilers will do as good a job + inlining modular code as can now be done by brute-force expansion, + but now, enough of them seem not to. + + Some compilers issue a lot of warnings about code that is + dead/unreachable only on some platforms, and also about intentional + uses of negation on unsigned types. All known cases of each can be + ignored. + + For a longer but out of date high-level description, see + http://gee.cs.oswego.edu/dl/html/malloc.html + +* MSPACES + If MSPACES is defined, then in addition to malloc, free, etc., + this file also defines mspace_malloc, mspace_free, etc. These + are versions of malloc routines that take an "mspace" argument + obtained using create_mspace, to control all internal bookkeeping. + If ONLY_MSPACES is defined, only these versions are compiled. + So if you would like to use this allocator for only some allocations, + and your system malloc for others, you can compile with + ONLY_MSPACES and then do something like... + static mspace mymspace = create_mspace(0,0); // for example + #define mymalloc(bytes) mspace_malloc(mymspace, bytes) + + (Note: If you only need one instance of an mspace, you can instead + use "USE_DL_PREFIX" to relabel the global malloc.) + + You can similarly create thread-local allocators by storing + mspaces as thread-locals. For example: + static __thread mspace tlms = 0; + void* tlmalloc(size_t bytes) { + if (tlms == 0) tlms = create_mspace(0, 0); + return mspace_malloc(tlms, bytes); + } + void tlfree(void* mem) { mspace_free(tlms, mem); } + + Unless FOOTERS is defined, each mspace is completely independent. + You cannot allocate from one and free to another (although + conformance is only weakly checked, so usage errors are not always + caught). If FOOTERS is defined, then each chunk carries around a tag + indicating its originating mspace, and frees are directed to their + originating spaces. + + ------------------------- Compile-time options --------------------------- + +Be careful in setting #define values for numerical constants of type +size_t. On some systems, literal values are not automatically extended +to size_t precision unless they are explicitly casted. + +WIN32 default: defined if _WIN32 defined + Defining WIN32 sets up defaults for MS environment and compilers. + Otherwise defaults are for unix. + +MALLOC_ALIGNMENT default: (size_t)8 + Controls the minimum alignment for malloc'ed chunks. It must be a + power of two and at least 8, even on machines for which smaller + alignments would suffice. It may be defined as larger than this + though. Note however that code and data structures are optimized for + the case of 8-byte alignment. + +MSPACES default: 0 (false) + If true, compile in support for independent allocation spaces. + This is only supported if HAVE_MMAP is true. + +ONLY_MSPACES default: 0 (false) + If true, only compile in mspace versions, not regular versions. + +USE_LOCKS default: 0 (false) + Causes each call to each public routine to be surrounded with + pthread or WIN32 mutex lock/unlock. (If set true, this can be + overridden on a per-mspace basis for mspace versions.) + +FOOTERS default: 0 + If true, provide extra checking and dispatching by placing + information in the footers of allocated chunks. This adds + space and time overhead. + +INSECURE default: 0 + If true, omit checks for usage errors and heap space overwrites. + +USE_DL_PREFIX default: NOT defined + Causes compiler to prefix all public routines with the string 'dl'. + This can be useful when you only want to use this malloc in one part + of a program, using your regular system malloc elsewhere. + +ABORT default: defined as abort() + Defines how to abort on failed checks. On most systems, a failed + check cannot die with an "assert" or even print an informative + message, because the underlying print routines in turn call malloc, + which will fail again. Generally, the best policy is to simply call + abort(). It's not very useful to do more than this because many + errors due to overwriting will show up as address faults (null, odd + addresses etc) rather than malloc-triggered checks, so will also + abort. Also, most compilers know that abort() does not return, so + can better optimize code conditionally calling it. + +PROCEED_ON_ERROR default: defined as 0 (false) + Controls whether detected bad addresses cause them to bypassed + rather than aborting. If set, detected bad arguments to free and + realloc are ignored. And all bookkeeping information is zeroed out + upon a detected overwrite of freed heap space, thus losing the + ability to ever return it from malloc again, but enabling the + application to proceed. If PROCEED_ON_ERROR is defined, the + static variable malloc_corruption_error_count is compiled in + and can be examined to see if errors have occurred. This option + generates slower code than the default abort policy. + +DEBUG default: NOT defined + The DEBUG setting is mainly intended for people trying to modify + this code or diagnose problems when porting to new platforms. + However, it may also be able to better isolate user errors than just + using runtime checks. The assertions in the check routines spell + out in more detail the assumptions and invariants underlying the + algorithms. The checking is fairly extensive, and will slow down + execution noticeably. Calling malloc_stats or mallinfo with DEBUG + set will attempt to check every non-mmapped allocated and free chunk + in the course of computing the summaries. + +ABORT_ON_ASSERT_FAILURE default: defined as 1 (true) + Debugging assertion failures can be nearly impossible if your + version of the assert macro causes malloc to be called, which will + lead to a cascade of further failures, blowing the runtime stack. + ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(), + which will usually make debugging easier. + +MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32 + The action to take before "return 0" when malloc fails to be able to + return memory because there is none available. + +HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES + True if this system supports sbrk or an emulation of it. + +MORECORE default: sbrk + The name of the sbrk-style system routine to call to obtain more + memory. See below for guidance on writing custom MORECORE + functions. The type of the argument to sbrk/MORECORE varies across + systems. It cannot be size_t, because it supports negative + arguments, so it is normally the signed type of the same width as + size_t (sometimes declared as "intptr_t"). It doesn't much matter + though. Internally, we only call it with arguments less than half + the max value of a size_t, which should work across all reasonable + possibilities, although sometimes generating compiler warnings. See + near the end of this file for guidelines for creating a custom + version of MORECORE. + +MORECORE_CONTIGUOUS default: 1 (true) + If true, take advantage of fact that consecutive calls to MORECORE + with positive arguments always return contiguous increasing + addresses. This is true of unix sbrk. It does not hurt too much to + set it true anyway, since malloc copes with non-contiguities. + Setting it false when definitely non-contiguous saves time + and possibly wasted space it would take to discover this though. + +MORECORE_CANNOT_TRIM default: NOT defined + True if MORECORE cannot release space back to the system when given + negative arguments. This is generally necessary only if you are + using a hand-crafted MORECORE function that cannot handle negative + arguments. + +HAVE_MMAP default: 1 (true) + True if this system supports mmap or an emulation of it. If so, and + HAVE_MORECORE is not true, MMAP is used for all system + allocation. If set and HAVE_MORECORE is true as well, MMAP is + primarily used to directly allocate very large blocks. It is also + used as a backup strategy in cases where MORECORE fails to provide + space from system. Note: A single call to MUNMAP is assumed to be + able to unmap memory that may have be allocated using multiple calls + to MMAP, so long as they are adjacent. + +HAVE_MREMAP default: 1 on linux, else 0 + If true realloc() uses mremap() to re-allocate large blocks and + extend or shrink allocation spaces. + +MMAP_CLEARS default: 1 on unix + True if mmap clears memory so calloc doesn't need to. This is true + for standard unix mmap using /dev/zero. + +USE_BUILTIN_FFS default: 0 (i.e., not used) + Causes malloc to use the builtin ffs() function to compute indices. + Some compilers may recognize and intrinsify ffs to be faster than the + supplied C version. Also, the case of x86 using gcc is special-cased + to an asm instruction, so is already as fast as it can be, and so + this setting has no effect. (On most x86s, the asm version is only + slightly faster than the C version.) + +malloc_getpagesize default: derive from system includes, or 4096. + The system page size. To the extent possible, this malloc manages + memory from the system in page-size units. This may be (and + usually is) a function rather than a constant. This is ignored + if WIN32, where page size is determined using getSystemInfo during + initialization. + +USE_DEV_RANDOM default: 0 (i.e., not used) + Causes malloc to use /dev/random to initialize secure magic seed for + stamping footers. Otherwise, the current time is used. + +NO_MALLINFO default: 0 + If defined, don't compile "mallinfo". This can be a simple way + of dealing with mismatches between system declarations and + those in this file. + +MALLINFO_FIELD_TYPE default: size_t + The type of the fields in the mallinfo struct. This was originally + defined as "int" in SVID etc, but is more usefully defined as + size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set + +REALLOC_ZERO_BYTES_FREES default: not defined + This should be set if a call to realloc with zero bytes should + be the same as a call to free. Some people think it should. Otherwise, + since this malloc returns a unique pointer for malloc(0), so does + realloc(p, 0). + +LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H +LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H +LACKS_STDLIB_H default: NOT defined unless on WIN32 + Define these if your system does not have these header files. + You might need to manually insert some of the declarations they provide. + +DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS, + system_info.dwAllocationGranularity in WIN32, + otherwise 64K. + Also settable using mallopt(M_GRANULARITY, x) + The unit for allocating and deallocating memory from the system. On + most systems with contiguous MORECORE, there is no reason to + make this more than a page. However, systems with MMAP tend to + either require or encourage larger granularities. You can increase + this value to prevent system allocation functions to be called so + often, especially if they are slow. The value must be at least one + page and must be a power of two. Setting to 0 causes initialization + to either page size or win32 region size. (Note: In previous + versions of malloc, the equivalent of this option was called + "TOP_PAD") + +DEFAULT_TRIM_THRESHOLD default: 2MB + Also settable using mallopt(M_TRIM_THRESHOLD, x) + The maximum amount of unused top-most memory to keep before + releasing via malloc_trim in free(). Automatic trimming is mainly + useful in long-lived programs using contiguous MORECORE. Because + trimming via sbrk can be slow on some systems, and can sometimes be + wasteful (in cases where programs immediately afterward allocate + more large chunks) the value should be high enough so that your + overall system performance would improve by releasing this much + memory. As a rough guide, you might set to a value close to the + average size of a process (program) running on your system. + Releasing this much memory would allow such a process to run in + memory. Generally, it is worth tuning trim thresholds when a + program undergoes phases where several large chunks are allocated + and released in ways that can reuse each other's storage, perhaps + mixed with phases where there are no such chunks at all. The trim + value must be greater than page size to have any useful effect. To + disable trimming completely, you can set to MAX_SIZE_T. Note that the trick + some people use of mallocing a huge space and then freeing it at + program startup, in an attempt to reserve system memory, doesn't + have the intended effect under automatic trimming, since that memory + will immediately be returned to the system. + +DEFAULT_MMAP_THRESHOLD default: 256K + Also settable using mallopt(M_MMAP_THRESHOLD, x) + The request size threshold for using MMAP to directly service a + request. Requests of at least this size that cannot be allocated + using already-existing space will be serviced via mmap. (If enough + normal freed space already exists it is used instead.) Using mmap + segregates relatively large chunks of memory so that they can be + individually obtained and released from the host system. A request + serviced through mmap is never reused by any other request (at least + not directly; the system may just so happen to remap successive + requests to the same locations). Segregating space in this way has + the benefits that: Mmapped space can always be individually released + back to the system, which helps keep the system level memory demands + of a long-lived program low. Also, mapped memory doesn't become + `locked' between other chunks, as can happen with normally allocated + chunks, which means that even trimming via malloc_trim would not + release them. However, it has the disadvantage that the space + cannot be reclaimed, consolidated, and then used to service later + requests, as happens with normal chunks. The advantages of mmap + nearly always outweigh disadvantages for "large" chunks, but the + value of "large" may vary across systems. The default is an + empirically derived value that works well in most systems. You can + disable mmap by setting to MAX_SIZE_T. + +*/ + +#if defined __linux__ && !defined _GNU_SOURCE +/* mremap() on Linux requires this via sys/mman.h */ +#define _GNU_SOURCE 1 +#endif + +#ifndef WIN32 +#ifdef _WIN32 +#define WIN32 1 +#endif /* _WIN32 */ +#endif /* WIN32 */ +#ifdef WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#define HAVE_MMAP 1 +#define HAVE_MORECORE 0 +#define LACKS_UNISTD_H +#define LACKS_SYS_PARAM_H +#define LACKS_SYS_MMAN_H +#define LACKS_STRING_H +#define LACKS_STRINGS_H +#define LACKS_SYS_TYPES_H +#define LACKS_ERRNO_H +#define MALLOC_FAILURE_ACTION +#define MMAP_CLEARS 0 /* WINCE and some others apparently don't clear */ +#endif /* WIN32 */ + +#ifdef __OS2__ +#define INCL_DOS +#include +#define HAVE_MMAP 1 +#define HAVE_MORECORE 0 +#define LACKS_SYS_MMAN_H +#endif /* __OS2__ */ + +#if defined(DARWIN) || defined(_DARWIN) +/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */ +#ifndef HAVE_MORECORE +#define HAVE_MORECORE 0 +#define HAVE_MMAP 1 +#endif /* HAVE_MORECORE */ +#endif /* DARWIN */ + +#ifndef LACKS_SYS_TYPES_H +#include /* For size_t */ +#endif /* LACKS_SYS_TYPES_H */ + +/* The maximum possible size_t value has all bits set */ +#define MAX_SIZE_T (~(size_t)0) + +#ifndef ONLY_MSPACES +#define ONLY_MSPACES 0 +#endif /* ONLY_MSPACES */ +#ifndef MSPACES +#if ONLY_MSPACES +#define MSPACES 1 +#else /* ONLY_MSPACES */ +#define MSPACES 0 +#endif /* ONLY_MSPACES */ +#endif /* MSPACES */ +#ifndef MALLOC_ALIGNMENT +#define MALLOC_ALIGNMENT ((size_t)8U) +#endif /* MALLOC_ALIGNMENT */ +#ifndef FOOTERS +#define FOOTERS 0 +#endif /* FOOTERS */ +#ifndef ABORT +#define ABORT abort() +#endif /* ABORT */ +#ifndef ABORT_ON_ASSERT_FAILURE +#define ABORT_ON_ASSERT_FAILURE 1 +#endif /* ABORT_ON_ASSERT_FAILURE */ +#ifndef PROCEED_ON_ERROR +#define PROCEED_ON_ERROR 0 +#endif /* PROCEED_ON_ERROR */ +#ifndef USE_LOCKS +#define USE_LOCKS 0 +#endif /* USE_LOCKS */ +#ifndef INSECURE +#define INSECURE 0 +#endif /* INSECURE */ +#ifndef HAVE_MMAP +#define HAVE_MMAP 1 +#endif /* HAVE_MMAP */ +#ifndef MMAP_CLEARS +#define MMAP_CLEARS 1 +#endif /* MMAP_CLEARS */ +#ifndef HAVE_MREMAP +#ifdef linux +#define HAVE_MREMAP 1 +#else /* linux */ +#define HAVE_MREMAP 0 +#endif /* linux */ +#endif /* HAVE_MREMAP */ +#ifndef MALLOC_FAILURE_ACTION +#define MALLOC_FAILURE_ACTION errno = ENOMEM; +#endif /* MALLOC_FAILURE_ACTION */ +#ifndef HAVE_MORECORE +#if ONLY_MSPACES +#define HAVE_MORECORE 0 +#else /* ONLY_MSPACES */ +#define HAVE_MORECORE 1 +#endif /* ONLY_MSPACES */ +#endif /* HAVE_MORECORE */ +#if !HAVE_MORECORE +#define MORECORE_CONTIGUOUS 0 +#else /* !HAVE_MORECORE */ +#ifndef MORECORE +#define MORECORE sbrk +#endif /* MORECORE */ +#ifndef MORECORE_CONTIGUOUS +#define MORECORE_CONTIGUOUS 1 +#endif /* MORECORE_CONTIGUOUS */ +#endif /* HAVE_MORECORE */ +#ifndef DEFAULT_GRANULARITY +#if MORECORE_CONTIGUOUS +#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */ +#else /* MORECORE_CONTIGUOUS */ +#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U) +#endif /* MORECORE_CONTIGUOUS */ +#endif /* DEFAULT_GRANULARITY */ +#ifndef DEFAULT_TRIM_THRESHOLD +#ifndef MORECORE_CANNOT_TRIM +#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U) +#else /* MORECORE_CANNOT_TRIM */ +#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T +#endif /* MORECORE_CANNOT_TRIM */ +#endif /* DEFAULT_TRIM_THRESHOLD */ +#ifndef DEFAULT_MMAP_THRESHOLD +#if HAVE_MMAP +#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U) +#else /* HAVE_MMAP */ +#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T +#endif /* HAVE_MMAP */ +#endif /* DEFAULT_MMAP_THRESHOLD */ +#ifndef USE_BUILTIN_FFS +#define USE_BUILTIN_FFS 0 +#endif /* USE_BUILTIN_FFS */ +#ifndef USE_DEV_RANDOM +#define USE_DEV_RANDOM 0 +#endif /* USE_DEV_RANDOM */ +#ifndef NO_MALLINFO +#define NO_MALLINFO 0 +#endif /* NO_MALLINFO */ +#ifndef MALLINFO_FIELD_TYPE +#define MALLINFO_FIELD_TYPE size_t +#endif /* MALLINFO_FIELD_TYPE */ + +/* + mallopt tuning options. SVID/XPG defines four standard parameter + numbers for mallopt, normally defined in malloc.h. None of these + are used in this malloc, so setting them has no effect. But this + malloc does support the following options. +*/ + +#define M_TRIM_THRESHOLD (-1) +#define M_GRANULARITY (-2) +#define M_MMAP_THRESHOLD (-3) + +/* ------------------------ Mallinfo declarations ------------------------ */ + +#if !NO_MALLINFO +/* + This version of malloc supports the standard SVID/XPG mallinfo + routine that returns a struct containing usage properties and + statistics. It should work on any system that has a + /usr/include/malloc.h defining struct mallinfo. The main + declaration needed is the mallinfo struct that is returned (by-copy) + by mallinfo(). The malloinfo struct contains a bunch of fields that + are not even meaningful in this version of malloc. These fields are + are instead filled by mallinfo() with other numbers that might be of + interest. + + HAVE_USR_INCLUDE_MALLOC_H should be set if you have a + /usr/include/malloc.h file that includes a declaration of struct + mallinfo. If so, it is included; else a compliant version is + declared below. These must be precisely the same for mallinfo() to + work. The original SVID version of this struct, defined on most + systems with mallinfo, declares all fields as ints. But some others + define as unsigned long. If your system defines the fields using a + type of different width than listed here, you MUST #include your + system version and #define HAVE_USR_INCLUDE_MALLOC_H. +*/ + +/* #define HAVE_USR_INCLUDE_MALLOC_H */ + +#ifdef HAVE_USR_INCLUDE_MALLOC_H +#include "/usr/include/malloc.h" +#else /* HAVE_USR_INCLUDE_MALLOC_H */ + +/* HP-UX's stdlib.h redefines mallinfo unless _STRUCT_MALLINFO is defined */ +#define _STRUCT_MALLINFO + +struct mallinfo { + MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ + MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ + MALLINFO_FIELD_TYPE smblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ + MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ + MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ + MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ + MALLINFO_FIELD_TYPE fordblks; /* total free space */ + MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ +}; + +#endif /* HAVE_USR_INCLUDE_MALLOC_H */ +#endif /* NO_MALLINFO */ + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#if !ONLY_MSPACES + +/* ------------------- Declarations of public routines ------------------- */ + +#ifndef USE_DL_PREFIX +#define dlcalloc calloc +#define dlfree free +#define dlmalloc malloc +#define dlmemalign memalign +#define dlrealloc realloc +#define dlvalloc valloc +#define dlpvalloc pvalloc +#define dlmallinfo mallinfo +#define dlmallopt mallopt +#define dlmalloc_trim malloc_trim +#define dlmalloc_stats malloc_stats +#define dlmalloc_usable_size malloc_usable_size +#define dlmalloc_footprint malloc_footprint +#define dlmalloc_max_footprint malloc_max_footprint +#define dlindependent_calloc independent_calloc +#define dlindependent_comalloc independent_comalloc +#endif /* USE_DL_PREFIX */ + + +/* + malloc(size_t n) + Returns a pointer to a newly allocated chunk of at least n bytes, or + null if no space is available, in which case errno is set to ENOMEM + on ANSI C systems. + + If n is zero, malloc returns a minimum-sized chunk. (The minimum + size is 16 bytes on most 32bit systems, and 32 bytes on 64bit + systems.) Note that size_t is an unsigned type, so calls with + arguments that would be negative if signed are interpreted as + requests for huge amounts of space, which will often fail. The + maximum supported value of n differs across systems, but is in all + cases less than the maximum representable value of a size_t. +*/ +void* dlmalloc(size_t); + +/* + free(void* p) + Releases the chunk of memory pointed to by p, that had been previously + allocated using malloc or a related routine such as realloc. + It has no effect if p is null. If p was not malloced or already + freed, free(p) will by default cause the current program to abort. +*/ +void dlfree(void*); + +/* + calloc(size_t n_elements, size_t element_size); + Returns a pointer to n_elements * element_size bytes, with all locations + set to zero. +*/ +void* dlcalloc(size_t, size_t); + +/* + realloc(void* p, size_t n) + Returns a pointer to a chunk of size n that contains the same data + as does chunk p up to the minimum of (n, p's size) bytes, or null + if no space is available. + + The returned pointer may or may not be the same as p. The algorithm + prefers extending p in most cases when possible, otherwise it + employs the equivalent of a malloc-copy-free sequence. + + If p is null, realloc is equivalent to malloc. + + If space is not available, realloc returns null, errno is set (if on + ANSI) and p is NOT freed. + + if n is for fewer bytes than already held by p, the newly unused + space is lopped off and freed if possible. realloc with a size + argument of zero (re)allocates a minimum-sized chunk. + + The old unix realloc convention of allowing the last-free'd chunk + to be used as an argument to realloc is not supported. +*/ + +void* dlrealloc(void*, size_t); + +/* + memalign(size_t alignment, size_t n); + Returns a pointer to a newly allocated chunk of n bytes, aligned + in accord with the alignment argument. + + The alignment argument should be a power of two. If the argument is + not a power of two, the nearest greater power is used. + 8-byte alignment is guaranteed by normal malloc calls, so don't + bother calling memalign with an argument of 8 or less. + + Overreliance on memalign is a sure way to fragment space. +*/ +void* dlmemalign(size_t, size_t); + +/* + valloc(size_t n); + Equivalent to memalign(pagesize, n), where pagesize is the page + size of the system. If the pagesize is unknown, 4096 is used. +*/ +void* dlvalloc(size_t); + +/* + mallopt(int parameter_number, int parameter_value) + Sets tunable parameters The format is to provide a + (parameter-number, parameter-value) pair. mallopt then sets the + corresponding parameter to the argument value if it can (i.e., so + long as the value is meaningful), and returns 1 if successful else + 0. SVID/XPG/ANSI defines four standard param numbers for mallopt, + normally defined in malloc.h. None of these are use in this malloc, + so setting them has no effect. But this malloc also supports other + options in mallopt. See below for details. Briefly, supported + parameters are as follows (listed defaults are for "typical" + configurations). + + Symbol param # default allowed param values + M_TRIM_THRESHOLD -1 2*1024*1024 any (MAX_SIZE_T disables) + M_GRANULARITY -2 page size any power of 2 >= page size + M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support) +*/ +int dlmallopt(int, int); + +/* + malloc_footprint(); + Returns the number of bytes obtained from the system. The total + number of bytes allocated by malloc, realloc etc., is less than this + value. Unlike mallinfo, this function returns only a precomputed + result, so can be called frequently to monitor memory consumption. + Even if locks are otherwise defined, this function does not use them, + so results might not be up to date. +*/ +size_t dlmalloc_footprint(void); + +/* + malloc_max_footprint(); + Returns the maximum number of bytes obtained from the system. This + value will be greater than current footprint if deallocated space + has been reclaimed by the system. The peak number of bytes allocated + by malloc, realloc etc., is less than this value. Unlike mallinfo, + this function returns only a precomputed result, so can be called + frequently to monitor memory consumption. Even if locks are + otherwise defined, this function does not use them, so results might + not be up to date. +*/ +size_t dlmalloc_max_footprint(void); + +#if !NO_MALLINFO +/* + mallinfo() + Returns (by copy) a struct containing various summary statistics: + + arena: current total non-mmapped bytes allocated from system + ordblks: the number of free chunks + smblks: always zero. + hblks: current number of mmapped regions + hblkhd: total bytes held in mmapped regions + usmblks: the maximum total allocated space. This will be greater + than current total if trimming has occurred. + fsmblks: always zero + uordblks: current total allocated space (normal or mmapped) + fordblks: total free space + keepcost: the maximum number of bytes that could ideally be released + back to system via malloc_trim. ("ideally" means that + it ignores page restrictions etc.) + + Because these fields are ints, but internal bookkeeping may + be kept as longs, the reported values may wrap around zero and + thus be inaccurate. +*/ +struct mallinfo dlmallinfo(void); +#endif /* NO_MALLINFO */ + +/* + independent_calloc(size_t n_elements, size_t element_size, void* chunks[]); + + independent_calloc is similar to calloc, but instead of returning a + single cleared space, it returns an array of pointers to n_elements + independent elements that can hold contents of size elem_size, each + of which starts out cleared, and can be independently freed, + realloc'ed etc. The elements are guaranteed to be adjacently + allocated (this is not guaranteed to occur with multiple callocs or + mallocs), which may also improve cache locality in some + applications. + + The "chunks" argument is optional (i.e., may be null, which is + probably the most typical usage). If it is null, the returned array + is itself dynamically allocated and should also be freed when it is + no longer needed. Otherwise, the chunks array must be of at least + n_elements in length. It is filled in with the pointers to the + chunks. + + In either case, independent_calloc returns this pointer array, or + null if the allocation failed. If n_elements is zero and "chunks" + is null, it returns a chunk representing an array with zero elements + (which should be freed if not wanted). + + Each element must be individually freed when it is no longer + needed. If you'd like to instead be able to free all at once, you + should instead use regular calloc and assign pointers into this + space to represent elements. (In this case though, you cannot + independently free elements.) + + independent_calloc simplifies and speeds up implementations of many + kinds of pools. It may also be useful when constructing large data + structures that initially have a fixed number of fixed-sized nodes, + but the number is not known at compile time, and some of the nodes + may later need to be freed. For example: + + struct Node { int item; struct Node* next; }; + + struct Node* build_list() { + struct Node** pool; + int n = read_number_of_nodes_needed(); + if (n <= 0) return 0; + pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0); + if (pool == 0) die(); + // organize into a linked list... + struct Node* first = pool[0]; + for (i = 0; i < n-1; ++i) + pool[i]->next = pool[i+1]; + free(pool); // Can now free the array (or not, if it is needed later) + return first; + } +*/ +void** dlindependent_calloc(size_t, size_t, void**); + +/* + independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); + + independent_comalloc allocates, all at once, a set of n_elements + chunks with sizes indicated in the "sizes" array. It returns + an array of pointers to these elements, each of which can be + independently freed, realloc'ed etc. The elements are guaranteed to + be adjacently allocated (this is not guaranteed to occur with + multiple callocs or mallocs), which may also improve cache locality + in some applications. + + The "chunks" argument is optional (i.e., may be null). If it is null + the returned array is itself dynamically allocated and should also + be freed when it is no longer needed. Otherwise, the chunks array + must be of at least n_elements in length. It is filled in with the + pointers to the chunks. + + In either case, independent_comalloc returns this pointer array, or + null if the allocation failed. If n_elements is zero and chunks is + null, it returns a chunk representing an array with zero elements + (which should be freed if not wanted). + + Each element must be individually freed when it is no longer + needed. If you'd like to instead be able to free all at once, you + should instead use a single regular malloc, and assign pointers at + particular offsets in the aggregate space. (In this case though, you + cannot independently free elements.) + + independent_comallac differs from independent_calloc in that each + element may have a different size, and also that it does not + automatically clear elements. + + independent_comalloc can be used to speed up allocation in cases + where several structs or objects must always be allocated at the + same time. For example: + + struct Head { ... } + struct Foot { ... } + + void send_message(char* msg) { + int msglen = strlen(msg); + size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) }; + void* chunks[3]; + if (independent_comalloc(3, sizes, chunks) == 0) + die(); + struct Head* head = (struct Head*)(chunks[0]); + char* body = (char*)(chunks[1]); + struct Foot* foot = (struct Foot*)(chunks[2]); + // ... + } + + In general though, independent_comalloc is worth using only for + larger values of n_elements. For small values, you probably won't + detect enough difference from series of malloc calls to bother. + + Overuse of independent_comalloc can increase overall memory usage, + since it cannot reuse existing noncontiguous small chunks that + might be available for some of the elements. +*/ +void** dlindependent_comalloc(size_t, size_t*, void**); + + +/* + pvalloc(size_t n); + Equivalent to valloc(minimum-page-that-holds(n)), that is, + round up n to nearest pagesize. + */ +void* dlpvalloc(size_t); + +/* + malloc_trim(size_t pad); + + If possible, gives memory back to the system (via negative arguments + to sbrk) if there is unused memory at the `high' end of the malloc + pool or in unused MMAP segments. You can call this after freeing + large blocks of memory to potentially reduce the system-level memory + requirements of a program. However, it cannot guarantee to reduce + memory. Under some allocation patterns, some large free blocks of + memory will be locked between two used chunks, so they cannot be + given back to the system. + + The `pad' argument to malloc_trim represents the amount of free + trailing space to leave untrimmed. If this argument is zero, only + the minimum amount of memory to maintain internal data structures + will be left. Non-zero arguments can be supplied to maintain enough + trailing space to service future expected allocations without having + to re-obtain memory from the system. + + Malloc_trim returns 1 if it actually released any memory, else 0. +*/ +int dlmalloc_trim(size_t); + +/* + malloc_usable_size(void* p); + + Returns the number of bytes you can actually use in + an allocated chunk, which may be more than you requested (although + often not) due to alignment and minimum size constraints. + You can use this many bytes without worrying about + overwriting other allocated objects. This is not a particularly great + programming practice. malloc_usable_size can be more useful in + debugging and assertions, for example: + + p = malloc(n); + assert(malloc_usable_size(p) >= 256); +*/ +size_t dlmalloc_usable_size(void*); + +/* + malloc_stats(); + Prints on stderr the amount of space obtained from the system (both + via sbrk and mmap), the maximum amount (which may be more than + current if malloc_trim and/or munmap got called), and the current + number of bytes allocated via malloc (or realloc, etc) but not yet + freed. Note that this is the number of bytes allocated, not the + number requested. It will be larger than the number requested + because of alignment and bookkeeping overhead. Because it includes + alignment wastage as being in use, this figure may be greater than + zero even when no user-level chunks are allocated. + + The reported current and maximum system memory can be inaccurate if + a program makes other calls to system memory allocation functions + (normally sbrk) outside of malloc. + + malloc_stats prints only the most commonly interesting statistics. + More information can be obtained by calling mallinfo. +*/ +void dlmalloc_stats(void); + +#endif /* ONLY_MSPACES */ + +#if MSPACES + +/* + mspace is an opaque type representing an independent + region of space that supports mspace_malloc, etc. +*/ +typedef void* mspace; + +/* + create_mspace creates and returns a new independent space with the + given initial capacity, or, if 0, the default granularity size. It + returns null if there is no system memory available to create the + space. If argument locked is non-zero, the space uses a separate + lock to control access. The capacity of the space will grow + dynamically as needed to service mspace_malloc requests. You can + control the sizes of incremental increases of this space by + compiling with a different DEFAULT_GRANULARITY or dynamically + setting with mallopt(M_GRANULARITY, value). +*/ +mspace create_mspace(size_t capacity, int locked); + +/* + destroy_mspace destroys the given space, and attempts to return all + of its memory back to the system, returning the total number of + bytes freed. After destruction, the results of access to all memory + used by the space become undefined. +*/ +size_t destroy_mspace(mspace msp); + +/* + create_mspace_with_base uses the memory supplied as the initial base + of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this + space is used for bookkeeping, so the capacity must be at least this + large. (Otherwise 0 is returned.) When this initial space is + exhausted, additional memory will be obtained from the system. + Destroying this space will deallocate all additionally allocated + space (if possible) but not the initial base. +*/ +mspace create_mspace_with_base(void* base, size_t capacity, int locked); + +/* + mspace_malloc behaves as malloc, but operates within + the given space. +*/ +void* mspace_malloc(mspace msp, size_t bytes); + +/* + mspace_free behaves as free, but operates within + the given space. + + If compiled with FOOTERS==1, mspace_free is not actually needed. + free may be called instead of mspace_free because freed chunks from + any space are handled by their originating spaces. +*/ +void mspace_free(mspace msp, void* mem); + +/* + mspace_realloc behaves as realloc, but operates within + the given space. + + If compiled with FOOTERS==1, mspace_realloc is not actually + needed. realloc may be called instead of mspace_realloc because + realloced chunks from any space are handled by their originating + spaces. +*/ +void* mspace_realloc(mspace msp, void* mem, size_t newsize); + +/* + mspace_calloc behaves as calloc, but operates within + the given space. +*/ +void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); + +/* + mspace_memalign behaves as memalign, but operates within + the given space. +*/ +void* mspace_memalign(mspace msp, size_t alignment, size_t bytes); + +/* + mspace_independent_calloc behaves as independent_calloc, but + operates within the given space. +*/ +void** mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void* chunks[]); + +/* + mspace_independent_comalloc behaves as independent_comalloc, but + operates within the given space. +*/ +void** mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void* chunks[]); + +/* + mspace_footprint() returns the number of bytes obtained from the + system for this space. +*/ +size_t mspace_footprint(mspace msp); + +/* + mspace_max_footprint() returns the peak number of bytes obtained from the + system for this space. +*/ +size_t mspace_max_footprint(mspace msp); + + +#if !NO_MALLINFO +/* + mspace_mallinfo behaves as mallinfo, but reports properties of + the given space. +*/ +struct mallinfo mspace_mallinfo(mspace msp); +#endif /* NO_MALLINFO */ + +/* + mspace_malloc_stats behaves as malloc_stats, but reports + properties of the given space. +*/ +void mspace_malloc_stats(mspace msp); + +/* + mspace_trim behaves as malloc_trim, but + operates within the given space. +*/ +int mspace_trim(mspace msp, size_t pad); + +/* + An alias for mallopt. +*/ +int mspace_mallopt(int, int); + +#endif /* MSPACES */ + +#ifdef __cplusplus +}; /* end of extern "C" */ +#endif /* __cplusplus */ + +/* + ======================================================================== + To make a fully customizable malloc.h header file, cut everything + above this line, put into file malloc.h, edit to suit, and #include it + on the next line, as well as in programs that use this malloc. + ======================================================================== +*/ + +/* #include "malloc.h" */ + +/*------------------------------ internal #includes ---------------------- */ + +#ifdef _MSC_VER +#pragma warning( disable : 4146 ) /* no "unsigned" warnings */ +#endif /* _MSC_VER */ + +#include /* for printing in malloc_stats */ + +#ifndef LACKS_ERRNO_H +#include /* for MALLOC_FAILURE_ACTION */ +#endif /* LACKS_ERRNO_H */ +#if FOOTERS +#include /* for magic initialization */ +#endif /* FOOTERS */ +#ifndef LACKS_STDLIB_H +#include /* for abort() */ +#endif /* LACKS_STDLIB_H */ +#ifdef DEBUG +#if ABORT_ON_ASSERT_FAILURE +#define assert(x) if(!(x)) ABORT +#else /* ABORT_ON_ASSERT_FAILURE */ +#include +#endif /* ABORT_ON_ASSERT_FAILURE */ +#else /* DEBUG */ +#define assert(x) +#endif /* DEBUG */ +#ifndef LACKS_STRING_H +#include /* for memset etc */ +#endif /* LACKS_STRING_H */ +#if USE_BUILTIN_FFS +#ifndef LACKS_STRINGS_H +#include /* for ffs */ +#endif /* LACKS_STRINGS_H */ +#endif /* USE_BUILTIN_FFS */ +#if HAVE_MMAP +#ifndef LACKS_SYS_MMAN_H +#include /* for mmap */ +#endif /* LACKS_SYS_MMAN_H */ +#ifndef LACKS_FCNTL_H +#include +#endif /* LACKS_FCNTL_H */ +#endif /* HAVE_MMAP */ +#if HAVE_MORECORE +#ifndef LACKS_UNISTD_H +#include /* for sbrk */ +#else /* LACKS_UNISTD_H */ +#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) +extern void* sbrk(ptrdiff_t); +#endif /* FreeBSD etc */ +#endif /* LACKS_UNISTD_H */ +#endif /* HAVE_MMAP */ + +#ifndef WIN32 +#ifndef malloc_getpagesize +# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ +# ifndef _SC_PAGE_SIZE +# define _SC_PAGE_SIZE _SC_PAGESIZE +# endif +# endif +# ifdef _SC_PAGE_SIZE +# define malloc_getpagesize sysconf(_SC_PAGE_SIZE) +# else +# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE) + extern size_t getpagesize(); +# define malloc_getpagesize getpagesize() +# else +# ifdef WIN32 /* use supplied emulation of getpagesize */ +# define malloc_getpagesize getpagesize() +# else +# ifndef LACKS_SYS_PARAM_H +# include +# endif +# ifdef EXEC_PAGESIZE +# define malloc_getpagesize EXEC_PAGESIZE +# else +# ifdef NBPG +# ifndef CLSIZE +# define malloc_getpagesize NBPG +# else +# define malloc_getpagesize (NBPG * CLSIZE) +# endif +# else +# ifdef NBPC +# define malloc_getpagesize NBPC +# else +# ifdef PAGESIZE +# define malloc_getpagesize PAGESIZE +# else /* just guess */ +# define malloc_getpagesize ((size_t)4096U) +# endif +# endif +# endif +# endif +# endif +# endif +# endif +#endif +#endif + +/* ------------------- size_t and alignment properties -------------------- */ + +/* The byte and bit size of a size_t */ +#define SIZE_T_SIZE (sizeof(size_t)) +#define SIZE_T_BITSIZE (sizeof(size_t) << 3) + +/* Some constants coerced to size_t */ +/* Annoying but necessary to avoid errors on some platforms */ +#define SIZE_T_ZERO ((size_t)0) +#define SIZE_T_ONE ((size_t)1) +#define SIZE_T_TWO ((size_t)2) +#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1) +#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2) +#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES) +#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U) + +/* The bit mask value corresponding to MALLOC_ALIGNMENT */ +#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE) + +/* True if address a has acceptable alignment */ +#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0) + +/* the number of bytes to offset an address to align it */ +#define align_offset(A)\ + ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\ + ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK)) + +/* -------------------------- MMAP preliminaries ------------------------- */ + +/* + If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and + checks to fail so compiler optimizer can delete code rather than + using so many "#if"s. +*/ + + +/* MORECORE and MMAP must return MFAIL on failure */ +#define MFAIL ((void*)(MAX_SIZE_T)) +#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */ + +#if !HAVE_MMAP +#define IS_MMAPPED_BIT (SIZE_T_ZERO) +#define USE_MMAP_BIT (SIZE_T_ZERO) +#define CALL_MMAP(s) MFAIL +#define CALL_MUNMAP(a, s) (-1) +#define DIRECT_MMAP(s) MFAIL + +#else /* HAVE_MMAP */ +#define IS_MMAPPED_BIT (SIZE_T_ONE) +#define USE_MMAP_BIT (SIZE_T_ONE) + +#if !defined(WIN32) && !defined (__OS2__) +#define CALL_MUNMAP(a, s) munmap((a), (s)) +#define MMAP_PROT (PROT_READ|PROT_WRITE) +#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) +#define MAP_ANONYMOUS MAP_ANON +#endif /* MAP_ANON */ +#ifdef MAP_ANONYMOUS +#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS) +#define CALL_MMAP(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0) +#else /* MAP_ANONYMOUS */ +/* + Nearly all versions of mmap support MAP_ANONYMOUS, so the following + is unlikely to be needed, but is supplied just in case. +*/ +#define MMAP_FLAGS (MAP_PRIVATE) +static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ +#define CALL_MMAP(s) ((dev_zero_fd < 0) ? \ + (dev_zero_fd = open("/dev/zero", O_RDWR), \ + mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \ + mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) +#endif /* MAP_ANONYMOUS */ + +#define DIRECT_MMAP(s) CALL_MMAP(s) + +#elif defined(__OS2__) + +/* OS/2 MMAP via DosAllocMem */ +static void* os2mmap(size_t size) { + void* ptr; + if (DosAllocMem(&ptr, size, OBJ_ANY|PAG_COMMIT|PAG_READ|PAG_WRITE) && + DosAllocMem(&ptr, size, PAG_COMMIT|PAG_READ|PAG_WRITE)) + return MFAIL; + return ptr; +} + +#define os2direct_mmap(n) os2mmap(n) + +/* This function supports releasing coalesed segments */ +static int os2munmap(void* ptr, size_t size) { + while (size) { + ULONG ulSize = size; + ULONG ulFlags = 0; + if (DosQueryMem(ptr, &ulSize, &ulFlags) != 0) + return -1; + if ((ulFlags & PAG_BASE) == 0 ||(ulFlags & PAG_COMMIT) == 0 || + ulSize > size) + return -1; + if (DosFreeMem(ptr) != 0) + return -1; + ptr = ( void * ) ( ( char * ) ptr + ulSize ); + size -= ulSize; + } + return 0; +} + +#define CALL_MMAP(s) os2mmap(s) +#define CALL_MUNMAP(a, s) os2munmap((a), (s)) +#define DIRECT_MMAP(s) os2direct_mmap(s) + +#else /* WIN32 */ + +/* Win32 MMAP via VirtualAlloc */ +static void* win32mmap(size_t size) { + void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE); + return (ptr != 0)? ptr: MFAIL; +} + +/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ +static void* win32direct_mmap(size_t size) { + void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, + PAGE_EXECUTE_READWRITE); + return (ptr != 0)? ptr: MFAIL; +} + +/* This function supports releasing coalesed segments */ +static int win32munmap(void* ptr, size_t size) { + MEMORY_BASIC_INFORMATION minfo; + char* cptr = ptr; + while (size) { + if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) + return -1; + if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || + minfo.State != MEM_COMMIT || minfo.RegionSize > size) + return -1; + if (VirtualFree(cptr, 0, MEM_RELEASE) == 0) + return -1; + cptr += minfo.RegionSize; + size -= minfo.RegionSize; + } + return 0; +} + +#define CALL_MMAP(s) win32mmap(s) +#define CALL_MUNMAP(a, s) win32munmap((a), (s)) +#define DIRECT_MMAP(s) win32direct_mmap(s) +#endif /* WIN32 */ +#endif /* HAVE_MMAP */ + +#if HAVE_MMAP && HAVE_MREMAP +#define CALL_MREMAP(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv)) +#else /* HAVE_MMAP && HAVE_MREMAP */ +#define CALL_MREMAP(addr, osz, nsz, mv) MFAIL +#endif /* HAVE_MMAP && HAVE_MREMAP */ + +#if HAVE_MORECORE +#define CALL_MORECORE(S) MORECORE(S) +#else /* HAVE_MORECORE */ +#define CALL_MORECORE(S) MFAIL +#endif /* HAVE_MORECORE */ + +/* mstate bit set if contiguous morecore disabled or failed */ +#define USE_NONCONTIGUOUS_BIT (4U) + +/* segment bit set in create_mspace_with_base */ +#define EXTERN_BIT (8U) + + +/* --------------------------- Lock preliminaries ------------------------ */ + +#if USE_LOCKS + +/* + When locks are defined, there are up to two global locks: + + * If HAVE_MORECORE, morecore_mutex protects sequences of calls to + MORECORE. In many cases sys_alloc requires two calls, that should + not be interleaved with calls by other threads. This does not + protect against direct calls to MORECORE by other threads not + using this lock, so there is still code to cope the best we can on + interference. + + * magic_init_mutex ensures that mparams.magic and other + unique mparams values are initialized only once. +*/ + +#if !defined(WIN32) && !defined(__OS2__) +/* By default use posix locks */ +#include +#define MLOCK_T pthread_mutex_t +#define INITIAL_LOCK(l) pthread_mutex_init(l, NULL) +#define ACQUIRE_LOCK(l) pthread_mutex_lock(l) +#define RELEASE_LOCK(l) pthread_mutex_unlock(l) + +#if HAVE_MORECORE +static MLOCK_T morecore_mutex = PTHREAD_MUTEX_INITIALIZER; +#endif /* HAVE_MORECORE */ + +static MLOCK_T magic_init_mutex = PTHREAD_MUTEX_INITIALIZER; + +#elif defined(__OS2__) +#define MLOCK_T HMTX +#define INITIAL_LOCK(l) DosCreateMutexSem(0, l, 0, FALSE) +#define ACQUIRE_LOCK(l) DosRequestMutexSem(*l, SEM_INDEFINITE_WAIT) +#define RELEASE_LOCK(l) DosReleaseMutexSem(*l) +#if HAVE_MORECORE +static MLOCK_T morecore_mutex; +#endif /* HAVE_MORECORE */ +static MLOCK_T magic_init_mutex; + +#else /* WIN32 */ +/* + Because lock-protected regions have bounded times, and there + are no recursive lock calls, we can use simple spinlocks. +*/ + +#define MLOCK_T long +static int win32_acquire_lock (MLOCK_T *sl) { + for (;;) { +#ifdef InterlockedCompareExchangePointer + if (!InterlockedCompareExchange(sl, 1, 0)) + return 0; +#else /* Use older void* version */ + if (!InterlockedCompareExchange((void**)sl, (void*)1, (void*)0)) + return 0; +#endif /* InterlockedCompareExchangePointer */ + Sleep (0); + } +} + +static void win32_release_lock (MLOCK_T *sl) { + InterlockedExchange (sl, 0); +} + +#define INITIAL_LOCK(l) *(l)=0 +#define ACQUIRE_LOCK(l) win32_acquire_lock(l) +#define RELEASE_LOCK(l) win32_release_lock(l) +#if HAVE_MORECORE +static MLOCK_T morecore_mutex; +#endif /* HAVE_MORECORE */ +static MLOCK_T magic_init_mutex; +#endif /* WIN32 */ + +#define USE_LOCK_BIT (2U) +#else /* USE_LOCKS */ +#define USE_LOCK_BIT (0U) +#define INITIAL_LOCK(l) +#endif /* USE_LOCKS */ + +#if USE_LOCKS && HAVE_MORECORE +#define ACQUIRE_MORECORE_LOCK() ACQUIRE_LOCK(&morecore_mutex); +#define RELEASE_MORECORE_LOCK() RELEASE_LOCK(&morecore_mutex); +#else /* USE_LOCKS && HAVE_MORECORE */ +#define ACQUIRE_MORECORE_LOCK() +#define RELEASE_MORECORE_LOCK() +#endif /* USE_LOCKS && HAVE_MORECORE */ + +#if USE_LOCKS +#define ACQUIRE_MAGIC_INIT_LOCK() ACQUIRE_LOCK(&magic_init_mutex); +#define RELEASE_MAGIC_INIT_LOCK() RELEASE_LOCK(&magic_init_mutex); +#else /* USE_LOCKS */ +#define ACQUIRE_MAGIC_INIT_LOCK() +#define RELEASE_MAGIC_INIT_LOCK() +#endif /* USE_LOCKS */ + + +/* ----------------------- Chunk representations ------------------------ */ + +/* + (The following includes lightly edited explanations by Colin Plumb.) + + The malloc_chunk declaration below is misleading (but accurate and + necessary). It declares a "view" into memory allowing access to + necessary fields at known offsets from a given base. + + Chunks of memory are maintained using a `boundary tag' method as + originally described by Knuth. (See the paper by Paul Wilson + ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such + techniques.) Sizes of free chunks are stored both in the front of + each chunk and at the end. This makes consolidating fragmented + chunks into bigger chunks fast. The head fields also hold bits + representing whether chunks are free or in use. + + Here are some pictures to make it clearer. They are "exploded" to + show that the state of a chunk can be thought of as extending from + the high 31 bits of the head field of its header through the + prev_foot and PINUSE_BIT bit of the following chunk header. + + A chunk that's in use looks like: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk (if P = 1) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| + | Size of this chunk 1| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | | + +- -+ + | | + +- -+ + | : + +- size - sizeof(size_t) available payload bytes -+ + : | + chunk-> +- -+ + | | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1| + | Size of next chunk (may or may not be in use) | +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + And if it's free, it looks like this: + + chunk-> +- -+ + | User payload (must be in use, or we would have merged!) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| + | Size of this chunk 0| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Next pointer | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Prev pointer | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | : + +- size - sizeof(struct chunk) unused bytes -+ + : | + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of this chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0| + | Size of next chunk (must be in use, or we would have merged)| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | : + +- User payload -+ + : | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |0| + +-+ + Note that since we always merge adjacent free chunks, the chunks + adjacent to a free chunk must be in use. + + Given a pointer to a chunk (which can be derived trivially from the + payload pointer) we can, in O(1) time, find out whether the adjacent + chunks are free, and if so, unlink them from the lists that they + are on and merge them with the current chunk. + + Chunks always begin on even word boundaries, so the mem portion + (which is returned to the user) is also on an even word boundary, and + thus at least double-word aligned. + + The P (PINUSE_BIT) bit, stored in the unused low-order bit of the + chunk size (which is always a multiple of two words), is an in-use + bit for the *previous* chunk. If that bit is *clear*, then the + word before the current chunk size contains the previous chunk + size, and can be used to find the front of the previous chunk. + The very first chunk allocated always has this bit set, preventing + access to non-existent (or non-owned) memory. If pinuse is set for + any given chunk, then you CANNOT determine the size of the + previous chunk, and might even get a memory addressing fault when + trying to do so. + + The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of + the chunk size redundantly records whether the current chunk is + inuse. This redundancy enables usage checks within free and realloc, + and reduces indirection when freeing and consolidating chunks. + + Each freshly allocated chunk must have both cinuse and pinuse set. + That is, each allocated chunk borders either a previously allocated + and still in-use chunk, or the base of its memory arena. This is + ensured by making all allocations from the the `lowest' part of any + found chunk. Further, no free chunk physically borders another one, + so each free chunk is known to be preceded and followed by either + inuse chunks or the ends of memory. + + Note that the `foot' of the current chunk is actually represented + as the prev_foot of the NEXT chunk. This makes it easier to + deal with alignments etc but can be very confusing when trying + to extend or adapt this code. + + The exceptions to all this are + + 1. The special chunk `top' is the top-most available chunk (i.e., + the one bordering the end of available memory). It is treated + specially. Top is never included in any bin, is used only if + no other chunk is available, and is released back to the + system if it is very large (see M_TRIM_THRESHOLD). In effect, + the top chunk is treated as larger (and thus less well + fitting) than any other available chunk. The top chunk + doesn't update its trailing size field since there is no next + contiguous chunk that would have to index off it. However, + space is still allocated for it (TOP_FOOT_SIZE) to enable + separation or merging when space is extended. + + 3. Chunks allocated via mmap, which have the lowest-order bit + (IS_MMAPPED_BIT) set in their prev_foot fields, and do not set + PINUSE_BIT in their head fields. Because they are allocated + one-by-one, each must carry its own prev_foot field, which is + also used to hold the offset this chunk has within its mmapped + region, which is needed to preserve alignment. Each mmapped + chunk is trailed by the first two fields of a fake next-chunk + for sake of usage checks. + +*/ + +struct malloc_chunk { + size_t prev_foot; /* Size of previous chunk (if free). */ + size_t head; /* Size and inuse bits. */ + struct malloc_chunk* fd; /* double links -- used only if free. */ + struct malloc_chunk* bk; +}; + +typedef struct malloc_chunk mchunk; +typedef struct malloc_chunk* mchunkptr; +typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */ +typedef size_t bindex_t; /* Described below */ +typedef unsigned int binmap_t; /* Described below */ +typedef unsigned int flag_t; /* The type of various bit flag sets */ + +/* ------------------- Chunks sizes and alignments ----------------------- */ + +#define MCHUNK_SIZE (sizeof(mchunk)) + +#if FOOTERS +#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) +#else /* FOOTERS */ +#define CHUNK_OVERHEAD (SIZE_T_SIZE) +#endif /* FOOTERS */ + +/* MMapped chunks need a second word of overhead ... */ +#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) +/* ... and additional padding for fake next-chunk at foot */ +#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES) + +/* The smallest size we can malloc is an aligned minimal chunk */ +#define MIN_CHUNK_SIZE\ + ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) + +/* conversion from malloc headers to user pointers, and back */ +#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES)) +#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES)) +/* chunk associated with aligned address A */ +#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A))) + +/* Bounds on request (not chunk) sizes. */ +#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2) +#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE) + +/* pad request bytes into a usable size */ +#define pad_request(req) \ + (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) + +/* pad request, checking for minimum (but not maximum) */ +#define request2size(req) \ + (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req)) + + +/* ------------------ Operations on head and foot fields ----------------- */ + +/* + The head field of a chunk is or'ed with PINUSE_BIT when previous + adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in + use. If the chunk was obtained with mmap, the prev_foot field has + IS_MMAPPED_BIT set, otherwise holding the offset of the base of the + mmapped region to the base of the chunk. +*/ + +#define PINUSE_BIT (SIZE_T_ONE) +#define CINUSE_BIT (SIZE_T_TWO) +#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT) + +/* Head value for fenceposts */ +#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE) + +/* extraction of fields from head words */ +#define cinuse(p) ((p)->head & CINUSE_BIT) +#define pinuse(p) ((p)->head & PINUSE_BIT) +#define chunksize(p) ((p)->head & ~(INUSE_BITS)) + +#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT) +#define clear_cinuse(p) ((p)->head &= ~CINUSE_BIT) + +/* Treat space at ptr +/- offset as a chunk */ +#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s))) +#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s))) + +/* Ptr to next or previous physical malloc_chunk. */ +#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~INUSE_BITS))) +#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) )) + +/* extract next chunk's pinuse bit */ +#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT) + +/* Get/set size at footer */ +#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot) +#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s)) + +/* Set size, pinuse bit, and foot */ +#define set_size_and_pinuse_of_free_chunk(p, s)\ + ((p)->head = (s|PINUSE_BIT), set_foot(p, s)) + +/* Set size, pinuse bit, foot, and clear next pinuse */ +#define set_free_with_pinuse(p, s, n)\ + (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s)) + +#define is_mmapped(p)\ + (!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_MMAPPED_BIT)) + +/* Get the internal overhead associated with chunk p */ +#define overhead_for(p)\ + (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD) + +/* Return true if malloced space is not necessarily cleared */ +#if MMAP_CLEARS +#define calloc_must_clear(p) (!is_mmapped(p)) +#else /* MMAP_CLEARS */ +#define calloc_must_clear(p) (1) +#endif /* MMAP_CLEARS */ + +/* ---------------------- Overlaid data structures ----------------------- */ + +/* + When chunks are not in use, they are treated as nodes of either + lists or trees. + + "Small" chunks are stored in circular doubly-linked lists, and look + like this: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `head:' | Size of chunk, in bytes |P| + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Forward pointer to next chunk in list | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Back pointer to previous chunk in list | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Unused space (may be 0 bytes long) . + . . + . | +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `foot:' | Size of chunk, in bytes | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Larger chunks are kept in a form of bitwise digital trees (aka + tries) keyed on chunksizes. Because malloc_tree_chunks are only for + free chunks greater than 256 bytes, their size doesn't impose any + constraints on user chunk sizes. Each node looks like: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `head:' | Size of chunk, in bytes |P| + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Forward pointer to next chunk of same size | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Back pointer to previous chunk of same size | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to left child (child[0]) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to right child (child[1]) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to parent | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | bin index of this chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Unused space . + . | +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `foot:' | Size of chunk, in bytes | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Each tree holding treenodes is a tree of unique chunk sizes. Chunks + of the same size are arranged in a circularly-linked list, with only + the oldest chunk (the next to be used, in our FIFO ordering) + actually in the tree. (Tree members are distinguished by a non-null + parent pointer.) If a chunk with the same size an an existing node + is inserted, it is linked off the existing node using pointers that + work in the same way as fd/bk pointers of small chunks. + + Each tree contains a power of 2 sized range of chunk sizes (the + smallest is 0x100 <= x < 0x180), which is is divided in half at each + tree level, with the chunks in the smaller half of the range (0x100 + <= x < 0x140 for the top nose) in the left subtree and the larger + half (0x140 <= x < 0x180) in the right subtree. This is, of course, + done by inspecting individual bits. + + Using these rules, each node's left subtree contains all smaller + sizes than its right subtree. However, the node at the root of each + subtree has no particular ordering relationship to either. (The + dividing line between the subtree sizes is based on trie relation.) + If we remove the last chunk of a given size from the interior of the + tree, we need to replace it with a leaf node. The tree ordering + rules permit a node to be replaced by any leaf below it. + + The smallest chunk in a tree (a common operation in a best-fit + allocator) can be found by walking a path to the leftmost leaf in + the tree. Unlike a usual binary tree, where we follow left child + pointers until we reach a null, here we follow the right child + pointer any time the left one is null, until we reach a leaf with + both child pointers null. The smallest chunk in the tree will be + somewhere along that path. + + The worst case number of steps to add, find, or remove a node is + bounded by the number of bits differentiating chunks within + bins. Under current bin calculations, this ranges from 6 up to 21 + (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case + is of course much better. +*/ + +struct malloc_tree_chunk { + /* The first four fields must be compatible with malloc_chunk */ + size_t prev_foot; + size_t head; + struct malloc_tree_chunk* fd; + struct malloc_tree_chunk* bk; + + struct malloc_tree_chunk* child[2]; + struct malloc_tree_chunk* parent; + bindex_t index; +}; + +typedef struct malloc_tree_chunk tchunk; +typedef struct malloc_tree_chunk* tchunkptr; +typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */ + +/* A little helper macro for trees */ +#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1]) + +/* ----------------------------- Segments -------------------------------- */ + +/* + Each malloc space may include non-contiguous segments, held in a + list headed by an embedded malloc_segment record representing the + top-most space. Segments also include flags holding properties of + the space. Large chunks that are directly allocated by mmap are not + included in this list. They are instead independently created and + destroyed without otherwise keeping track of them. + + Segment management mainly comes into play for spaces allocated by + MMAP. Any call to MMAP might or might not return memory that is + adjacent to an existing segment. MORECORE normally contiguously + extends the current space, so this space is almost always adjacent, + which is simpler and faster to deal with. (This is why MORECORE is + used preferentially to MMAP when both are available -- see + sys_alloc.) When allocating using MMAP, we don't use any of the + hinting mechanisms (inconsistently) supported in various + implementations of unix mmap, or distinguish reserving from + committing memory. Instead, we just ask for space, and exploit + contiguity when we get it. It is probably possible to do + better than this on some systems, but no general scheme seems + to be significantly better. + + Management entails a simpler variant of the consolidation scheme + used for chunks to reduce fragmentation -- new adjacent memory is + normally prepended or appended to an existing segment. However, + there are limitations compared to chunk consolidation that mostly + reflect the fact that segment processing is relatively infrequent + (occurring only when getting memory from system) and that we + don't expect to have huge numbers of segments: + + * Segments are not indexed, so traversal requires linear scans. (It + would be possible to index these, but is not worth the extra + overhead and complexity for most programs on most platforms.) + * New segments are only appended to old ones when holding top-most + memory; if they cannot be prepended to others, they are held in + different segments. + + Except for the top-most segment of an mstate, each segment record + is kept at the tail of its segment. Segments are added by pushing + segment records onto the list headed by &mstate.seg for the + containing mstate. + + Segment flags control allocation/merge/deallocation policies: + * If EXTERN_BIT set, then we did not allocate this segment, + and so should not try to deallocate or merge with others. + (This currently holds only for the initial segment passed + into create_mspace_with_base.) + * If IS_MMAPPED_BIT set, the segment may be merged with + other surrounding mmapped segments and trimmed/de-allocated + using munmap. + * If neither bit is set, then the segment was obtained using + MORECORE so can be merged with surrounding MORECORE'd segments + and deallocated/trimmed using MORECORE with negative arguments. +*/ + +struct malloc_segment { + char* base; /* base address */ + size_t size; /* allocated size */ + struct malloc_segment* next; /* ptr to next segment */ +#if FFI_MMAP_EXEC_WRIT + /* The mmap magic is supposed to store the address of the executable + segment at the very end of the requested block. */ + +# define mmap_exec_offset(b,s) (*(ptrdiff_t*)((b)+(s)-sizeof(ptrdiff_t))) + + /* We can only merge segments if their corresponding executable + segments are at identical offsets. */ +# define check_segment_merge(S,b,s) \ + (mmap_exec_offset((b),(s)) == (S)->exec_offset) + +# define add_segment_exec_offset(p,S) ((char*)(p) + (S)->exec_offset) +# define sub_segment_exec_offset(p,S) ((char*)(p) - (S)->exec_offset) + + /* The removal of sflags only works with HAVE_MORECORE == 0. */ + +# define get_segment_flags(S) (IS_MMAPPED_BIT) +# define set_segment_flags(S,v) \ + (((v) != IS_MMAPPED_BIT) ? (ABORT, (v)) : \ + (((S)->exec_offset = \ + mmap_exec_offset((S)->base, (S)->size)), \ + (mmap_exec_offset((S)->base + (S)->exec_offset, (S)->size) != \ + (S)->exec_offset) ? (ABORT, (v)) : \ + (mmap_exec_offset((S)->base, (S)->size) = 0), (v))) + + /* We use an offset here, instead of a pointer, because then, when + base changes, we don't have to modify this. On architectures + with segmented addresses, this might not work. */ + ptrdiff_t exec_offset; +#else + +# define get_segment_flags(S) ((S)->sflags) +# define set_segment_flags(S,v) ((S)->sflags = (v)) +# define check_segment_merge(S,b,s) (1) + + flag_t sflags; /* mmap and extern flag */ +#endif +}; + +#define is_mmapped_segment(S) (get_segment_flags(S) & IS_MMAPPED_BIT) +#define is_extern_segment(S) (get_segment_flags(S) & EXTERN_BIT) + +typedef struct malloc_segment msegment; +typedef struct malloc_segment* msegmentptr; + +/* ---------------------------- malloc_state ----------------------------- */ + +/* + A malloc_state holds all of the bookkeeping for a space. + The main fields are: + + Top + The topmost chunk of the currently active segment. Its size is + cached in topsize. The actual size of topmost space is + topsize+TOP_FOOT_SIZE, which includes space reserved for adding + fenceposts and segment records if necessary when getting more + space from the system. The size at which to autotrim top is + cached from mparams in trim_check, except that it is disabled if + an autotrim fails. + + Designated victim (dv) + This is the preferred chunk for servicing small requests that + don't have exact fits. It is normally the chunk split off most + recently to service another small request. Its size is cached in + dvsize. The link fields of this chunk are not maintained since it + is not kept in a bin. + + SmallBins + An array of bin headers for free chunks. These bins hold chunks + with sizes less than MIN_LARGE_SIZE bytes. Each bin contains + chunks of all the same size, spaced 8 bytes apart. To simplify + use in double-linked lists, each bin header acts as a malloc_chunk + pointing to the real first node, if it exists (else pointing to + itself). This avoids special-casing for headers. But to avoid + waste, we allocate only the fd/bk pointers of bins, and then use + repositioning tricks to treat these as the fields of a chunk. + + TreeBins + Treebins are pointers to the roots of trees holding a range of + sizes. There are 2 equally spaced treebins for each power of two + from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything + larger. + + Bin maps + There is one bit map for small bins ("smallmap") and one for + treebins ("treemap). Each bin sets its bit when non-empty, and + clears the bit when empty. Bit operations are then used to avoid + bin-by-bin searching -- nearly all "search" is done without ever + looking at bins that won't be selected. The bit maps + conservatively use 32 bits per map word, even if on 64bit system. + For a good description of some of the bit-based techniques used + here, see Henry S. Warren Jr's book "Hacker's Delight" (and + supplement at http://hackersdelight.org/). Many of these are + intended to reduce the branchiness of paths through malloc etc, as + well as to reduce the number of memory locations read or written. + + Segments + A list of segments headed by an embedded malloc_segment record + representing the initial space. + + Address check support + The least_addr field is the least address ever obtained from + MORECORE or MMAP. Attempted frees and reallocs of any address less + than this are trapped (unless INSECURE is defined). + + Magic tag + A cross-check field that should always hold same value as mparams.magic. + + Flags + Bits recording whether to use MMAP, locks, or contiguous MORECORE + + Statistics + Each space keeps track of current and maximum system memory + obtained via MORECORE or MMAP. + + Locking + If USE_LOCKS is defined, the "mutex" lock is acquired and released + around every public call using this mspace. +*/ + +/* Bin types, widths and sizes */ +#define NSMALLBINS (32U) +#define NTREEBINS (32U) +#define SMALLBIN_SHIFT (3U) +#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT) +#define TREEBIN_SHIFT (8U) +#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT) +#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE) +#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD) + +struct malloc_state { + binmap_t smallmap; + binmap_t treemap; + size_t dvsize; + size_t topsize; + char* least_addr; + mchunkptr dv; + mchunkptr top; + size_t trim_check; + size_t magic; + mchunkptr smallbins[(NSMALLBINS+1)*2]; + tbinptr treebins[NTREEBINS]; + size_t footprint; + size_t max_footprint; + flag_t mflags; +#if USE_LOCKS + MLOCK_T mutex; /* locate lock among fields that rarely change */ +#endif /* USE_LOCKS */ + msegment seg; +}; + +typedef struct malloc_state* mstate; + +/* ------------- Global malloc_state and malloc_params ------------------- */ + +/* + malloc_params holds global properties, including those that can be + dynamically set using mallopt. There is a single instance, mparams, + initialized in init_mparams. +*/ + +struct malloc_params { + size_t magic; + size_t page_size; + size_t granularity; + size_t mmap_threshold; + size_t trim_threshold; + flag_t default_mflags; +}; + +static struct malloc_params mparams; + +/* The global malloc_state used for all non-"mspace" calls */ +static struct malloc_state _gm_; +#define gm (&_gm_) +#define is_global(M) ((M) == &_gm_) +#define is_initialized(M) ((M)->top != 0) + +/* -------------------------- system alloc setup ------------------------- */ + +/* Operations on mflags */ + +#define use_lock(M) ((M)->mflags & USE_LOCK_BIT) +#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT) +#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT) + +#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT) +#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT) +#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT) + +#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT) +#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT) + +#define set_lock(M,L)\ + ((M)->mflags = (L)?\ + ((M)->mflags | USE_LOCK_BIT) :\ + ((M)->mflags & ~USE_LOCK_BIT)) + +/* page-align a size */ +#define page_align(S)\ + (((S) + (mparams.page_size)) & ~(mparams.page_size - SIZE_T_ONE)) + +/* granularity-align a size */ +#define granularity_align(S)\ + (((S) + (mparams.granularity)) & ~(mparams.granularity - SIZE_T_ONE)) + +#define is_page_aligned(S)\ + (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0) +#define is_granularity_aligned(S)\ + (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0) + +/* True if segment S holds address A */ +#define segment_holds(S, A)\ + ((char*)(A) >= S->base && (char*)(A) < S->base + S->size) + +/* Return segment holding given address */ +static msegmentptr segment_holding(mstate m, char* addr) { + msegmentptr sp = &m->seg; + for (;;) { + if (addr >= sp->base && addr < sp->base + sp->size) + return sp; + if ((sp = sp->next) == 0) + return 0; + } +} + +/* Return true if segment contains a segment link */ +static int has_segment_link(mstate m, msegmentptr ss) { + msegmentptr sp = &m->seg; + for (;;) { + if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size) + return 1; + if ((sp = sp->next) == 0) + return 0; + } +} + +#ifndef MORECORE_CANNOT_TRIM +#define should_trim(M,s) ((s) > (M)->trim_check) +#else /* MORECORE_CANNOT_TRIM */ +#define should_trim(M,s) (0) +#endif /* MORECORE_CANNOT_TRIM */ + +/* + TOP_FOOT_SIZE is padding at the end of a segment, including space + that may be needed to place segment records and fenceposts when new + noncontiguous segments are added. +*/ +#define TOP_FOOT_SIZE\ + (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE) + + +/* ------------------------------- Hooks -------------------------------- */ + +/* + PREACTION should be defined to return 0 on success, and nonzero on + failure. If you are not using locking, you can redefine these to do + anything you like. +*/ + +#if USE_LOCKS + +/* Ensure locks are initialized */ +#define GLOBALLY_INITIALIZE() (mparams.page_size == 0 && init_mparams()) + +#define PREACTION(M) ((GLOBALLY_INITIALIZE() || use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0) +#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); } +#else /* USE_LOCKS */ + +#ifndef PREACTION +#define PREACTION(M) (0) +#endif /* PREACTION */ + +#ifndef POSTACTION +#define POSTACTION(M) +#endif /* POSTACTION */ + +#endif /* USE_LOCKS */ + +/* + CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses. + USAGE_ERROR_ACTION is triggered on detected bad frees and + reallocs. The argument p is an address that might have triggered the + fault. It is ignored by the two predefined actions, but might be + useful in custom actions that try to help diagnose errors. +*/ + +#if PROCEED_ON_ERROR + +/* A count of the number of corruption errors causing resets */ +int malloc_corruption_error_count; + +/* default corruption action */ +static void reset_on_error(mstate m); + +#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m) +#define USAGE_ERROR_ACTION(m, p) + +#else /* PROCEED_ON_ERROR */ + +#ifndef CORRUPTION_ERROR_ACTION +#define CORRUPTION_ERROR_ACTION(m) ABORT +#endif /* CORRUPTION_ERROR_ACTION */ + +#ifndef USAGE_ERROR_ACTION +#define USAGE_ERROR_ACTION(m,p) ABORT +#endif /* USAGE_ERROR_ACTION */ + +#endif /* PROCEED_ON_ERROR */ + +/* -------------------------- Debugging setup ---------------------------- */ + +#if ! DEBUG + +#define check_free_chunk(M,P) +#define check_inuse_chunk(M,P) +#define check_malloced_chunk(M,P,N) +#define check_mmapped_chunk(M,P) +#define check_malloc_state(M) +#define check_top_chunk(M,P) + +#else /* DEBUG */ +#define check_free_chunk(M,P) do_check_free_chunk(M,P) +#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P) +#define check_top_chunk(M,P) do_check_top_chunk(M,P) +#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N) +#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P) +#define check_malloc_state(M) do_check_malloc_state(M) + +static void do_check_any_chunk(mstate m, mchunkptr p); +static void do_check_top_chunk(mstate m, mchunkptr p); +static void do_check_mmapped_chunk(mstate m, mchunkptr p); +static void do_check_inuse_chunk(mstate m, mchunkptr p); +static void do_check_free_chunk(mstate m, mchunkptr p); +static void do_check_malloced_chunk(mstate m, void* mem, size_t s); +static void do_check_tree(mstate m, tchunkptr t); +static void do_check_treebin(mstate m, bindex_t i); +static void do_check_smallbin(mstate m, bindex_t i); +static void do_check_malloc_state(mstate m); +static int bin_find(mstate m, mchunkptr x); +static size_t traverse_and_check(mstate m); +#endif /* DEBUG */ + +/* ---------------------------- Indexing Bins ---------------------------- */ + +#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS) +#define small_index(s) ((s) >> SMALLBIN_SHIFT) +#define small_index2size(i) ((i) << SMALLBIN_SHIFT) +#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE)) + +/* addressing by index. See above about smallbin repositioning */ +#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1]))) +#define treebin_at(M,i) (&((M)->treebins[i])) + +/* assign tree index for size S to variable I */ +#if defined(__GNUC__) && defined(__i386__) +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K;\ + __asm__("bsrl %1,%0\n\t" : "=r" (K) : "rm" (X));\ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} +#else /* GNUC */ +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int Y = (unsigned int)X;\ + unsigned int N = ((Y - 0x100) >> 16) & 8;\ + unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\ + N += K;\ + N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\ + K = 14 - N + ((Y <<= K) >> 15);\ + I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\ + }\ +} +#endif /* GNUC */ + +/* Bit representing maximum resolved size in a treebin at i */ +#define bit_for_tree_index(i) \ + (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2) + +/* Shift placing maximum resolved bit in a treebin at i as sign bit */ +#define leftshift_for_tree_index(i) \ + ((i == NTREEBINS-1)? 0 : \ + ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2))) + +/* The size of the smallest chunk held in bin with index i */ +#define minsize_for_tree_index(i) \ + ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \ + (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1))) + + +/* ------------------------ Operations on bin maps ----------------------- */ + +/* bit corresponding to given index */ +#define idx2bit(i) ((binmap_t)(1) << (i)) + +/* Mark/Clear bits with given index */ +#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i)) +#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i)) +#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i)) + +#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i)) +#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i)) +#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i)) + +/* index corresponding to given bit */ + +#if defined(__GNUC__) && defined(__i386__) +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + __asm__("bsfl %1,%0\n\t" : "=r" (J) : "rm" (X));\ + I = (bindex_t)J;\ +} + +#else /* GNUC */ +#if USE_BUILTIN_FFS +#define compute_bit2idx(X, I) I = __builtin_ffs(X)-1 + +#else /* USE_BUILTIN_FFS */ +#define compute_bit2idx(X, I)\ +{\ + unsigned int Y = X - 1;\ + unsigned int K = Y >> (16-4) & 16;\ + unsigned int N = K; Y >>= K;\ + N += K = Y >> (8-3) & 8; Y >>= K;\ + N += K = Y >> (4-2) & 4; Y >>= K;\ + N += K = Y >> (2-1) & 2; Y >>= K;\ + N += K = Y >> (1-0) & 1; Y >>= K;\ + I = (bindex_t)(N + Y);\ +} +#endif /* USE_BUILTIN_FFS */ +#endif /* GNUC */ + +/* isolate the least set bit of a bitmap */ +#define least_bit(x) ((x) & -(x)) + +/* mask with all bits to left of least bit of x on */ +#define left_bits(x) ((x<<1) | -(x<<1)) + +/* mask with all bits to left of or equal to least bit of x on */ +#define same_or_left_bits(x) ((x) | -(x)) + + +/* ----------------------- Runtime Check Support ------------------------- */ + +/* + For security, the main invariant is that malloc/free/etc never + writes to a static address other than malloc_state, unless static + malloc_state itself has been corrupted, which cannot occur via + malloc (because of these checks). In essence this means that we + believe all pointers, sizes, maps etc held in malloc_state, but + check all of those linked or offsetted from other embedded data + structures. These checks are interspersed with main code in a way + that tends to minimize their run-time cost. + + When FOOTERS is defined, in addition to range checking, we also + verify footer fields of inuse chunks, which can be used guarantee + that the mstate controlling malloc/free is intact. This is a + streamlined version of the approach described by William Robertson + et al in "Run-time Detection of Heap-based Overflows" LISA'03 + http://www.usenix.org/events/lisa03/tech/robertson.html The footer + of an inuse chunk holds the xor of its mstate and a random seed, + that is checked upon calls to free() and realloc(). This is + (probablistically) unguessable from outside the program, but can be + computed by any code successfully malloc'ing any chunk, so does not + itself provide protection against code that has already broken + security through some other means. Unlike Robertson et al, we + always dynamically check addresses of all offset chunks (previous, + next, etc). This turns out to be cheaper than relying on hashes. +*/ + +#if !INSECURE +/* Check if address a is at least as high as any from MORECORE or MMAP */ +#define ok_address(M, a) ((char*)(a) >= (M)->least_addr) +/* Check if address of next chunk n is higher than base chunk p */ +#define ok_next(p, n) ((char*)(p) < (char*)(n)) +/* Check if p has its cinuse bit on */ +#define ok_cinuse(p) cinuse(p) +/* Check if p has its pinuse bit on */ +#define ok_pinuse(p) pinuse(p) + +#else /* !INSECURE */ +#define ok_address(M, a) (1) +#define ok_next(b, n) (1) +#define ok_cinuse(p) (1) +#define ok_pinuse(p) (1) +#endif /* !INSECURE */ + +#if (FOOTERS && !INSECURE) +/* Check if (alleged) mstate m has expected magic field */ +#define ok_magic(M) ((M)->magic == mparams.magic) +#else /* (FOOTERS && !INSECURE) */ +#define ok_magic(M) (1) +#endif /* (FOOTERS && !INSECURE) */ + + +/* In gcc, use __builtin_expect to minimize impact of checks */ +#if !INSECURE +#if defined(__GNUC__) && __GNUC__ >= 3 +#define RTCHECK(e) __builtin_expect(e, 1) +#else /* GNUC */ +#define RTCHECK(e) (e) +#endif /* GNUC */ +#else /* !INSECURE */ +#define RTCHECK(e) (1) +#endif /* !INSECURE */ + +/* macros to set up inuse chunks with or without footers */ + +#if !FOOTERS + +#define mark_inuse_foot(M,p,s) + +/* Set cinuse bit and pinuse bit of next chunk */ +#define set_inuse(M,p,s)\ + ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ + ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) + +/* Set cinuse and pinuse of this chunk and pinuse of next chunk */ +#define set_inuse_and_pinuse(M,p,s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) + +/* Set size, cinuse and pinuse bit of this chunk */ +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT)) + +#else /* FOOTERS */ + +/* Set foot of inuse chunk to be xor of mstate and seed */ +#define mark_inuse_foot(M,p,s)\ + (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic)) + +#define get_mstate_for(p)\ + ((mstate)(((mchunkptr)((char*)(p) +\ + (chunksize(p))))->prev_foot ^ mparams.magic)) + +#define set_inuse(M,p,s)\ + ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ + (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \ + mark_inuse_foot(M,p,s)) + +#define set_inuse_and_pinuse(M,p,s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\ + mark_inuse_foot(M,p,s)) + +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + mark_inuse_foot(M, p, s)) + +#endif /* !FOOTERS */ + +/* ---------------------------- setting mparams -------------------------- */ + +/* Initialize mparams */ +static int init_mparams(void) { + if (mparams.page_size == 0) { + size_t s; + + mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD; + mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD; +#if MORECORE_CONTIGUOUS + mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT; +#else /* MORECORE_CONTIGUOUS */ + mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT; +#endif /* MORECORE_CONTIGUOUS */ + +#if (FOOTERS && !INSECURE) + { +#if USE_DEV_RANDOM + int fd; + unsigned char buf[sizeof(size_t)]; + /* Try to use /dev/urandom, else fall back on using time */ + if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 && + read(fd, buf, sizeof(buf)) == sizeof(buf)) { + s = *((size_t *) buf); + close(fd); + } + else +#endif /* USE_DEV_RANDOM */ + s = (size_t)(time(0) ^ (size_t)0x55555555U); + + s |= (size_t)8U; /* ensure nonzero */ + s &= ~(size_t)7U; /* improve chances of fault for bad values */ + + } +#else /* (FOOTERS && !INSECURE) */ + s = (size_t)0x58585858U; +#endif /* (FOOTERS && !INSECURE) */ + ACQUIRE_MAGIC_INIT_LOCK(); + if (mparams.magic == 0) { + mparams.magic = s; + /* Set up lock for main malloc area */ + INITIAL_LOCK(&gm->mutex); + gm->mflags = mparams.default_mflags; + } + RELEASE_MAGIC_INIT_LOCK(); + +#if !defined(WIN32) && !defined(__OS2__) + mparams.page_size = malloc_getpagesize; + mparams.granularity = ((DEFAULT_GRANULARITY != 0)? + DEFAULT_GRANULARITY : mparams.page_size); +#elif defined (__OS2__) + /* if low-memory is used, os2munmap() would break + if it were anything other than 64k */ + mparams.page_size = 4096u; + mparams.granularity = 65536u; +#else /* WIN32 */ + { + SYSTEM_INFO system_info; + GetSystemInfo(&system_info); + mparams.page_size = system_info.dwPageSize; + mparams.granularity = system_info.dwAllocationGranularity; + } +#endif /* WIN32 */ + + /* Sanity-check configuration: + size_t must be unsigned and as wide as pointer type. + ints must be at least 4 bytes. + alignment must be at least 8. + Alignment, min chunk size, and page size must all be powers of 2. + */ + if ((sizeof(size_t) != sizeof(char*)) || + (MAX_SIZE_T < MIN_CHUNK_SIZE) || + (sizeof(int) < 4) || + (MALLOC_ALIGNMENT < (size_t)8U) || + ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) || + ((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) || + ((mparams.granularity & (mparams.granularity-SIZE_T_ONE)) != 0) || + ((mparams.page_size & (mparams.page_size-SIZE_T_ONE)) != 0)) + ABORT; + } + return 0; +} + +/* support for mallopt */ +static int change_mparam(int param_number, int value) { + size_t val = (size_t)value; + init_mparams(); + switch(param_number) { + case M_TRIM_THRESHOLD: + mparams.trim_threshold = val; + return 1; + case M_GRANULARITY: + if (val >= mparams.page_size && ((val & (val-1)) == 0)) { + mparams.granularity = val; + return 1; + } + else + return 0; + case M_MMAP_THRESHOLD: + mparams.mmap_threshold = val; + return 1; + default: + return 0; + } +} + +#if DEBUG +/* ------------------------- Debugging Support --------------------------- */ + +/* Check properties of any chunk, whether free, inuse, mmapped etc */ +static void do_check_any_chunk(mstate m, mchunkptr p) { + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); +} + +/* Check properties of top chunk */ +static void do_check_top_chunk(mstate m, mchunkptr p) { + msegmentptr sp = segment_holding(m, (char*)p); + size_t sz = chunksize(p); + assert(sp != 0); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(sz == m->topsize); + assert(sz > 0); + assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE); + assert(pinuse(p)); + assert(!next_pinuse(p)); +} + +/* Check properties of (inuse) mmapped chunks */ +static void do_check_mmapped_chunk(mstate m, mchunkptr p) { + size_t sz = chunksize(p); + size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD); + assert(is_mmapped(p)); + assert(use_mmap(m)); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(!is_small(sz)); + assert((len & (mparams.page_size-SIZE_T_ONE)) == 0); + assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD); + assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0); +} + +/* Check properties of inuse chunks */ +static void do_check_inuse_chunk(mstate m, mchunkptr p) { + do_check_any_chunk(m, p); + assert(cinuse(p)); + assert(next_pinuse(p)); + /* If not pinuse and not mmapped, previous chunk has OK offset */ + assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p); + if (is_mmapped(p)) + do_check_mmapped_chunk(m, p); +} + +/* Check properties of free chunks */ +static void do_check_free_chunk(mstate m, mchunkptr p) { + size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT); + mchunkptr next = chunk_plus_offset(p, sz); + do_check_any_chunk(m, p); + assert(!cinuse(p)); + assert(!next_pinuse(p)); + assert (!is_mmapped(p)); + if (p != m->dv && p != m->top) { + if (sz >= MIN_CHUNK_SIZE) { + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(is_aligned(chunk2mem(p))); + assert(next->prev_foot == sz); + assert(pinuse(p)); + assert (next == m->top || cinuse(next)); + assert(p->fd->bk == p); + assert(p->bk->fd == p); + } + else /* markers are always of size SIZE_T_SIZE */ + assert(sz == SIZE_T_SIZE); + } +} + +/* Check properties of malloced chunks at the point they are malloced */ +static void do_check_malloced_chunk(mstate m, void* mem, size_t s) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT); + do_check_inuse_chunk(m, p); + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(sz >= MIN_CHUNK_SIZE); + assert(sz >= s); + /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */ + assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE)); + } +} + +/* Check a tree and its subtrees. */ +static void do_check_tree(mstate m, tchunkptr t) { + tchunkptr head = 0; + tchunkptr u = t; + bindex_t tindex = t->index; + size_t tsize = chunksize(t); + bindex_t idx; + compute_tree_index(tsize, idx); + assert(tindex == idx); + assert(tsize >= MIN_LARGE_SIZE); + assert(tsize >= minsize_for_tree_index(idx)); + assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1)))); + + do { /* traverse through chain of same-sized nodes */ + do_check_any_chunk(m, ((mchunkptr)u)); + assert(u->index == tindex); + assert(chunksize(u) == tsize); + assert(!cinuse(u)); + assert(!next_pinuse(u)); + assert(u->fd->bk == u); + assert(u->bk->fd == u); + if (u->parent == 0) { + assert(u->child[0] == 0); + assert(u->child[1] == 0); + } + else { + assert(head == 0); /* only one node on chain has parent */ + head = u; + assert(u->parent != u); + assert (u->parent->child[0] == u || + u->parent->child[1] == u || + *((tbinptr*)(u->parent)) == u); + if (u->child[0] != 0) { + assert(u->child[0]->parent == u); + assert(u->child[0] != u); + do_check_tree(m, u->child[0]); + } + if (u->child[1] != 0) { + assert(u->child[1]->parent == u); + assert(u->child[1] != u); + do_check_tree(m, u->child[1]); + } + if (u->child[0] != 0 && u->child[1] != 0) { + assert(chunksize(u->child[0]) < chunksize(u->child[1])); + } + } + u = u->fd; + } while (u != t); + assert(head != 0); +} + +/* Check all the chunks in a treebin. */ +static void do_check_treebin(mstate m, bindex_t i) { + tbinptr* tb = treebin_at(m, i); + tchunkptr t = *tb; + int empty = (m->treemap & (1U << i)) == 0; + if (t == 0) + assert(empty); + if (!empty) + do_check_tree(m, t); +} + +/* Check all the chunks in a smallbin. */ +static void do_check_smallbin(mstate m, bindex_t i) { + sbinptr b = smallbin_at(m, i); + mchunkptr p = b->bk; + unsigned int empty = (m->smallmap & (1U << i)) == 0; + if (p == b) + assert(empty); + if (!empty) { + for (; p != b; p = p->bk) { + size_t size = chunksize(p); + mchunkptr q; + /* each chunk claims to be free */ + do_check_free_chunk(m, p); + /* chunk belongs in bin */ + assert(small_index(size) == i); + assert(p->bk == b || chunksize(p->bk) == chunksize(p)); + /* chunk is followed by an inuse chunk */ + q = next_chunk(p); + if (q->head != FENCEPOST_HEAD) + do_check_inuse_chunk(m, q); + } + } +} + +/* Find x in a bin. Used in other check functions. */ +static int bin_find(mstate m, mchunkptr x) { + size_t size = chunksize(x); + if (is_small(size)) { + bindex_t sidx = small_index(size); + sbinptr b = smallbin_at(m, sidx); + if (smallmap_is_marked(m, sidx)) { + mchunkptr p = b; + do { + if (p == x) + return 1; + } while ((p = p->fd) != b); + } + } + else { + bindex_t tidx; + compute_tree_index(size, tidx); + if (treemap_is_marked(m, tidx)) { + tchunkptr t = *treebin_at(m, tidx); + size_t sizebits = size << leftshift_for_tree_index(tidx); + while (t != 0 && chunksize(t) != size) { + t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; + sizebits <<= 1; + } + if (t != 0) { + tchunkptr u = t; + do { + if (u == (tchunkptr)x) + return 1; + } while ((u = u->fd) != t); + } + } + } + return 0; +} + +/* Traverse each chunk and check it; return total */ +static size_t traverse_and_check(mstate m) { + size_t sum = 0; + if (is_initialized(m)) { + msegmentptr s = &m->seg; + sum += m->topsize + TOP_FOOT_SIZE; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + mchunkptr lastq = 0; + assert(pinuse(q)); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + sum += chunksize(q); + if (cinuse(q)) { + assert(!bin_find(m, q)); + do_check_inuse_chunk(m, q); + } + else { + assert(q == m->dv || bin_find(m, q)); + assert(lastq == 0 || cinuse(lastq)); /* Not 2 consecutive free */ + do_check_free_chunk(m, q); + } + lastq = q; + q = next_chunk(q); + } + s = s->next; + } + } + return sum; +} + +/* Check all properties of malloc_state. */ +static void do_check_malloc_state(mstate m) { + bindex_t i; + size_t total; + /* check bins */ + for (i = 0; i < NSMALLBINS; ++i) + do_check_smallbin(m, i); + for (i = 0; i < NTREEBINS; ++i) + do_check_treebin(m, i); + + if (m->dvsize != 0) { /* check dv chunk */ + do_check_any_chunk(m, m->dv); + assert(m->dvsize == chunksize(m->dv)); + assert(m->dvsize >= MIN_CHUNK_SIZE); + assert(bin_find(m, m->dv) == 0); + } + + if (m->top != 0) { /* check top chunk */ + do_check_top_chunk(m, m->top); + assert(m->topsize == chunksize(m->top)); + assert(m->topsize > 0); + assert(bin_find(m, m->top) == 0); + } + + total = traverse_and_check(m); + assert(total <= m->footprint); + assert(m->footprint <= m->max_footprint); +} +#endif /* DEBUG */ + +/* ----------------------------- statistics ------------------------------ */ + +#if !NO_MALLINFO +static struct mallinfo internal_mallinfo(mstate m) { + struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + if (!PREACTION(m)) { + check_malloc_state(m); + if (is_initialized(m)) { + size_t nfree = SIZE_T_ONE; /* top always free */ + size_t mfree = m->topsize + TOP_FOOT_SIZE; + size_t sum = mfree; + msegmentptr s = &m->seg; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + size_t sz = chunksize(q); + sum += sz; + if (!cinuse(q)) { + mfree += sz; + ++nfree; + } + q = next_chunk(q); + } + s = s->next; + } + + nm.arena = sum; + nm.ordblks = nfree; + nm.hblkhd = m->footprint - sum; + nm.usmblks = m->max_footprint; + nm.uordblks = m->footprint - mfree; + nm.fordblks = mfree; + nm.keepcost = m->topsize; + } + + POSTACTION(m); + } + return nm; +} +#endif /* !NO_MALLINFO */ + +static void internal_malloc_stats(mstate m) { + if (!PREACTION(m)) { + size_t maxfp = 0; + size_t fp = 0; + size_t used = 0; + check_malloc_state(m); + if (is_initialized(m)) { + msegmentptr s = &m->seg; + maxfp = m->max_footprint; + fp = m->footprint; + used = fp - (m->topsize + TOP_FOOT_SIZE); + + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + if (!cinuse(q)) + used -= chunksize(q); + q = next_chunk(q); + } + s = s->next; + } + } + + fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp)); + fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp)); + fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used)); + + POSTACTION(m); + } +} + +/* ----------------------- Operations on smallbins ----------------------- */ + +/* + Various forms of linking and unlinking are defined as macros. Even + the ones for trees, which are very long but have very short typical + paths. This is ugly but reduces reliance on inlining support of + compilers. +*/ + +/* Link a free chunk into a smallbin */ +#define insert_small_chunk(M, P, S) {\ + bindex_t I = small_index(S);\ + mchunkptr B = smallbin_at(M, I);\ + mchunkptr F = B;\ + assert(S >= MIN_CHUNK_SIZE);\ + if (!smallmap_is_marked(M, I))\ + mark_smallmap(M, I);\ + else if (RTCHECK(ok_address(M, B->fd)))\ + F = B->fd;\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + B->fd = P;\ + F->bk = P;\ + P->fd = F;\ + P->bk = B;\ +} + +/* Unlink a chunk from a smallbin */ +#define unlink_small_chunk(M, P, S) {\ + mchunkptr F = P->fd;\ + mchunkptr B = P->bk;\ + bindex_t I = small_index(S);\ + assert(P != B);\ + assert(P != F);\ + assert(chunksize(P) == small_index2size(I));\ + if (F == B)\ + clear_smallmap(M, I);\ + else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\ + (B == smallbin_at(M,I) || ok_address(M, B)))) {\ + F->bk = B;\ + B->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ +} + +/* Unlink the first chunk from a smallbin */ +#define unlink_first_small_chunk(M, B, P, I) {\ + mchunkptr F = P->fd;\ + assert(P != B);\ + assert(P != F);\ + assert(chunksize(P) == small_index2size(I));\ + if (B == F)\ + clear_smallmap(M, I);\ + else if (RTCHECK(ok_address(M, F))) {\ + B->fd = F;\ + F->bk = B;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ +} + +/* Replace dv node, binning the old one */ +/* Used only when dvsize known to be small */ +#define replace_dv(M, P, S) {\ + size_t DVS = M->dvsize;\ + if (DVS != 0) {\ + mchunkptr DV = M->dv;\ + assert(is_small(DVS));\ + insert_small_chunk(M, DV, DVS);\ + }\ + M->dvsize = S;\ + M->dv = P;\ +} + +/* ------------------------- Operations on trees ------------------------- */ + +/* Insert chunk into tree */ +#define insert_large_chunk(M, X, S) {\ + tbinptr* H;\ + bindex_t I;\ + compute_tree_index(S, I);\ + H = treebin_at(M, I);\ + X->index = I;\ + X->child[0] = X->child[1] = 0;\ + if (!treemap_is_marked(M, I)) {\ + mark_treemap(M, I);\ + *H = X;\ + X->parent = (tchunkptr)H;\ + X->fd = X->bk = X;\ + }\ + else {\ + tchunkptr T = *H;\ + size_t K = S << leftshift_for_tree_index(I);\ + for (;;) {\ + if (chunksize(T) != S) {\ + tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\ + K <<= 1;\ + if (*C != 0)\ + T = *C;\ + else if (RTCHECK(ok_address(M, C))) {\ + *C = X;\ + X->parent = T;\ + X->fd = X->bk = X;\ + break;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + break;\ + }\ + }\ + else {\ + tchunkptr F = T->fd;\ + if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\ + T->fd = F->bk = X;\ + X->fd = F;\ + X->bk = T;\ + X->parent = 0;\ + break;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + break;\ + }\ + }\ + }\ + }\ +} + +/* + Unlink steps: + + 1. If x is a chained node, unlink it from its same-sized fd/bk links + and choose its bk node as its replacement. + 2. If x was the last node of its size, but not a leaf node, it must + be replaced with a leaf node (not merely one with an open left or + right), to make sure that lefts and rights of descendants + correspond properly to bit masks. We use the rightmost descendant + of x. We could use any other leaf, but this is easy to locate and + tends to counteract removal of leftmosts elsewhere, and so keeps + paths shorter than minimally guaranteed. This doesn't loop much + because on average a node in a tree is near the bottom. + 3. If x is the base of a chain (i.e., has parent links) relink + x's parent and children to x's replacement (or null if none). +*/ + +#define unlink_large_chunk(M, X) {\ + tchunkptr XP = X->parent;\ + tchunkptr R;\ + if (X->bk != X) {\ + tchunkptr F = X->fd;\ + R = X->bk;\ + if (RTCHECK(ok_address(M, F))) {\ + F->bk = R;\ + R->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else {\ + tchunkptr* RP;\ + if (((R = *(RP = &(X->child[1]))) != 0) ||\ + ((R = *(RP = &(X->child[0]))) != 0)) {\ + tchunkptr* CP;\ + while ((*(CP = &(R->child[1])) != 0) ||\ + (*(CP = &(R->child[0])) != 0)) {\ + R = *(RP = CP);\ + }\ + if (RTCHECK(ok_address(M, RP)))\ + *RP = 0;\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + }\ + if (XP != 0) {\ + tbinptr* H = treebin_at(M, X->index);\ + if (X == *H) {\ + if ((*H = R) == 0) \ + clear_treemap(M, X->index);\ + }\ + else if (RTCHECK(ok_address(M, XP))) {\ + if (XP->child[0] == X) \ + XP->child[0] = R;\ + else \ + XP->child[1] = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + if (R != 0) {\ + if (RTCHECK(ok_address(M, R))) {\ + tchunkptr C0, C1;\ + R->parent = XP;\ + if ((C0 = X->child[0]) != 0) {\ + if (RTCHECK(ok_address(M, C0))) {\ + R->child[0] = C0;\ + C0->parent = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + if ((C1 = X->child[1]) != 0) {\ + if (RTCHECK(ok_address(M, C1))) {\ + R->child[1] = C1;\ + C1->parent = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ +} + +/* Relays to large vs small bin operations */ + +#define insert_chunk(M, P, S)\ + if (is_small(S)) insert_small_chunk(M, P, S)\ + else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); } + +#define unlink_chunk(M, P, S)\ + if (is_small(S)) unlink_small_chunk(M, P, S)\ + else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); } + + +/* Relays to internal calls to malloc/free from realloc, memalign etc */ + +#if ONLY_MSPACES +#define internal_malloc(m, b) mspace_malloc(m, b) +#define internal_free(m, mem) mspace_free(m,mem); +#else /* ONLY_MSPACES */ +#if MSPACES +#define internal_malloc(m, b)\ + (m == gm)? dlmalloc(b) : mspace_malloc(m, b) +#define internal_free(m, mem)\ + if (m == gm) dlfree(mem); else mspace_free(m,mem); +#else /* MSPACES */ +#define internal_malloc(m, b) dlmalloc(b) +#define internal_free(m, mem) dlfree(mem) +#endif /* MSPACES */ +#endif /* ONLY_MSPACES */ + +/* ----------------------- Direct-mmapping chunks ----------------------- */ + +/* + Directly mmapped chunks are set up with an offset to the start of + the mmapped region stored in the prev_foot field of the chunk. This + allows reconstruction of the required argument to MUNMAP when freed, + and also allows adjustment of the returned chunk to meet alignment + requirements (especially in memalign). There is also enough space + allocated to hold a fake next chunk of size SIZE_T_SIZE to maintain + the PINUSE bit so frees can be checked. +*/ + +/* Malloc using mmap */ +static void* mmap_alloc(mstate m, size_t nb) { + size_t mmsize = granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + if (mmsize > nb) { /* Check for wrap around 0 */ + char* mm = (char*)(DIRECT_MMAP(mmsize)); + if (mm != CMFAIL) { + size_t offset = align_offset(chunk2mem(mm)); + size_t psize = mmsize - offset - MMAP_FOOT_PAD; + mchunkptr p = (mchunkptr)(mm + offset); + p->prev_foot = offset | IS_MMAPPED_BIT; + (p)->head = (psize|CINUSE_BIT); + mark_inuse_foot(m, p, psize); + chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0; + + if (mm < m->least_addr) + m->least_addr = mm; + if ((m->footprint += mmsize) > m->max_footprint) + m->max_footprint = m->footprint; + assert(is_aligned(chunk2mem(p))); + check_mmapped_chunk(m, p); + return chunk2mem(p); + } + } + return 0; +} + +/* Realloc using mmap */ +static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) { + size_t oldsize = chunksize(oldp); + if (is_small(nb)) /* Can't shrink mmap regions below small size */ + return 0; + /* Keep old chunk if big enough but not too big */ + if (oldsize >= nb + SIZE_T_SIZE && + (oldsize - nb) <= (mparams.granularity << 1)) + return oldp; + else { + size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT; + size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD; + size_t newmmsize = granularity_align(nb + SIX_SIZE_T_SIZES + + CHUNK_ALIGN_MASK); + char* cp = (char*)CALL_MREMAP((char*)oldp - offset, + oldmmsize, newmmsize, 1); + if (cp != CMFAIL) { + mchunkptr newp = (mchunkptr)(cp + offset); + size_t psize = newmmsize - offset - MMAP_FOOT_PAD; + newp->head = (psize|CINUSE_BIT); + mark_inuse_foot(m, newp, psize); + chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0; + + if (cp < m->least_addr) + m->least_addr = cp; + if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint) + m->max_footprint = m->footprint; + check_mmapped_chunk(m, newp); + return newp; + } + } + return 0; +} + +/* -------------------------- mspace management -------------------------- */ + +/* Initialize top chunk and its size */ +static void init_top(mstate m, mchunkptr p, size_t psize) { + /* Ensure alignment */ + size_t offset = align_offset(chunk2mem(p)); + p = (mchunkptr)((char*)p + offset); + psize -= offset; + + m->top = p; + m->topsize = psize; + p->head = psize | PINUSE_BIT; + /* set size of fake trailing chunk holding overhead space only once */ + chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE; + m->trim_check = mparams.trim_threshold; /* reset on each update */ +} + +/* Initialize bins for a new mstate that is otherwise zeroed out */ +static void init_bins(mstate m) { + /* Establish circular links for smallbins */ + bindex_t i; + for (i = 0; i < NSMALLBINS; ++i) { + sbinptr bin = smallbin_at(m,i); + bin->fd = bin->bk = bin; + } +} + +#if PROCEED_ON_ERROR + +/* default corruption action */ +static void reset_on_error(mstate m) { + int i; + ++malloc_corruption_error_count; + /* Reinitialize fields to forget about all memory */ + m->smallbins = m->treebins = 0; + m->dvsize = m->topsize = 0; + m->seg.base = 0; + m->seg.size = 0; + m->seg.next = 0; + m->top = m->dv = 0; + for (i = 0; i < NTREEBINS; ++i) + *treebin_at(m, i) = 0; + init_bins(m); +} +#endif /* PROCEED_ON_ERROR */ + +/* Allocate chunk and prepend remainder with chunk in successor base. */ +static void* prepend_alloc(mstate m, char* newbase, char* oldbase, + size_t nb) { + mchunkptr p = align_as_chunk(newbase); + mchunkptr oldfirst = align_as_chunk(oldbase); + size_t psize = (char*)oldfirst - (char*)p; + mchunkptr q = chunk_plus_offset(p, nb); + size_t qsize = psize - nb; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + + assert((char*)oldfirst > (char*)q); + assert(pinuse(oldfirst)); + assert(qsize >= MIN_CHUNK_SIZE); + + /* consolidate remainder with first chunk of old base */ + if (oldfirst == m->top) { + size_t tsize = m->topsize += qsize; + m->top = q; + q->head = tsize | PINUSE_BIT; + check_top_chunk(m, q); + } + else if (oldfirst == m->dv) { + size_t dsize = m->dvsize += qsize; + m->dv = q; + set_size_and_pinuse_of_free_chunk(q, dsize); + } + else { + if (!cinuse(oldfirst)) { + size_t nsize = chunksize(oldfirst); + unlink_chunk(m, oldfirst, nsize); + oldfirst = chunk_plus_offset(oldfirst, nsize); + qsize += nsize; + } + set_free_with_pinuse(q, qsize, oldfirst); + insert_chunk(m, q, qsize); + check_free_chunk(m, q); + } + + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); +} + + +/* Add a segment to hold a new noncontiguous region */ +static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) { + /* Determine locations and sizes of segment, fenceposts, old top */ + char* old_top = (char*)m->top; + msegmentptr oldsp = segment_holding(m, old_top); + char* old_end = oldsp->base + oldsp->size; + size_t ssize = pad_request(sizeof(struct malloc_segment)); + char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + size_t offset = align_offset(chunk2mem(rawsp)); + char* asp = rawsp + offset; + char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp; + mchunkptr sp = (mchunkptr)csp; + msegmentptr ss = (msegmentptr)(chunk2mem(sp)); + mchunkptr tnext = chunk_plus_offset(sp, ssize); + mchunkptr p = tnext; + int nfences = 0; + + /* reset top to new space */ + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + + /* Set up segment record */ + assert(is_aligned(ss)); + set_size_and_pinuse_of_inuse_chunk(m, sp, ssize); + *ss = m->seg; /* Push current record */ + m->seg.base = tbase; + m->seg.size = tsize; + (void)set_segment_flags(&m->seg, mmapped); + m->seg.next = ss; + + /* Insert trailing fenceposts */ + for (;;) { + mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE); + p->head = FENCEPOST_HEAD; + ++nfences; + if ((char*)(&(nextp->head)) < old_end) + p = nextp; + else + break; + } + assert(nfences >= 2); + + /* Insert the rest of old top into a bin as an ordinary free chunk */ + if (csp != old_top) { + mchunkptr q = (mchunkptr)old_top; + size_t psize = csp - old_top; + mchunkptr tn = chunk_plus_offset(q, psize); + set_free_with_pinuse(q, psize, tn); + insert_chunk(m, q, psize); + } + + check_top_chunk(m, m->top); +} + +/* -------------------------- System allocation -------------------------- */ + +/* Get memory from system using MORECORE or MMAP */ +static void* sys_alloc(mstate m, size_t nb) { + char* tbase = CMFAIL; + size_t tsize = 0; + flag_t mmap_flag = 0; + + init_mparams(); + + /* Directly map large chunks */ + if (use_mmap(m) && nb >= mparams.mmap_threshold) { + void* mem = mmap_alloc(m, nb); + if (mem != 0) + return mem; + } + + /* + Try getting memory in any of three ways (in most-preferred to + least-preferred order): + 1. A call to MORECORE that can normally contiguously extend memory. + (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or + or main space is mmapped or a previous contiguous call failed) + 2. A call to MMAP new space (disabled if not HAVE_MMAP). + Note that under the default settings, if MORECORE is unable to + fulfill a request, and HAVE_MMAP is true, then mmap is + used as a noncontiguous system allocator. This is a useful backup + strategy for systems with holes in address spaces -- in this case + sbrk cannot contiguously expand the heap, but mmap may be able to + find space. + 3. A call to MORECORE that cannot usually contiguously extend memory. + (disabled if not HAVE_MORECORE) + */ + + if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) { + char* br = CMFAIL; + msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top); + size_t asize = 0; + ACQUIRE_MORECORE_LOCK(); + + if (ss == 0) { /* First time through or recovery */ + char* base = (char*)CALL_MORECORE(0); + if (base != CMFAIL) { + asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE); + /* Adjust to end on a page boundary */ + if (!is_page_aligned(base)) + asize += (page_align((size_t)base) - (size_t)base); + /* Can't call MORECORE if size is negative when treated as signed */ + if (asize < HALF_MAX_SIZE_T && + (br = (char*)(CALL_MORECORE(asize))) == base) { + tbase = base; + tsize = asize; + } + } + } + else { + /* Subtract out existing available top space from MORECORE request. */ + asize = granularity_align(nb - m->topsize + TOP_FOOT_SIZE + SIZE_T_ONE); + /* Use mem here only if it did continuously extend old space */ + if (asize < HALF_MAX_SIZE_T && + (br = (char*)(CALL_MORECORE(asize))) == ss->base+ss->size) { + tbase = br; + tsize = asize; + } + } + + if (tbase == CMFAIL) { /* Cope with partial failure */ + if (br != CMFAIL) { /* Try to use/extend the space we did get */ + if (asize < HALF_MAX_SIZE_T && + asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) { + size_t esize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE - asize); + if (esize < HALF_MAX_SIZE_T) { + char* end = (char*)CALL_MORECORE(esize); + if (end != CMFAIL) + asize += esize; + else { /* Can't use; try to release */ + (void)CALL_MORECORE(-asize); + br = CMFAIL; + } + } + } + } + if (br != CMFAIL) { /* Use the space we did get */ + tbase = br; + tsize = asize; + } + else + disable_contiguous(m); /* Don't try contiguous path in the future */ + } + + RELEASE_MORECORE_LOCK(); + } + + if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */ + size_t req = nb + TOP_FOOT_SIZE + SIZE_T_ONE; + size_t rsize = granularity_align(req); + if (rsize > nb) { /* Fail if wraps around zero */ + char* mp = (char*)(CALL_MMAP(rsize)); + if (mp != CMFAIL) { + tbase = mp; + tsize = rsize; + mmap_flag = IS_MMAPPED_BIT; + } + } + } + + if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */ + size_t asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE); + if (asize < HALF_MAX_SIZE_T) { + char* br = CMFAIL; + char* end = CMFAIL; + ACQUIRE_MORECORE_LOCK(); + br = (char*)(CALL_MORECORE(asize)); + end = (char*)(CALL_MORECORE(0)); + RELEASE_MORECORE_LOCK(); + if (br != CMFAIL && end != CMFAIL && br < end) { + size_t ssize = end - br; + if (ssize > nb + TOP_FOOT_SIZE) { + tbase = br; + tsize = ssize; + } + } + } + } + + if (tbase != CMFAIL) { + + if ((m->footprint += tsize) > m->max_footprint) + m->max_footprint = m->footprint; + + if (!is_initialized(m)) { /* first-time initialization */ + m->seg.base = m->least_addr = tbase; + m->seg.size = tsize; + (void)set_segment_flags(&m->seg, mmap_flag); + m->magic = mparams.magic; + init_bins(m); + if (is_global(m)) + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + else { + /* Offset top by embedded malloc_state */ + mchunkptr mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE); + } + } + + else { + /* Try to merge with an existing segment */ + msegmentptr sp = &m->seg; + while (sp != 0 && tbase != sp->base + sp->size) + sp = sp->next; + if (sp != 0 && + !is_extern_segment(sp) && + check_segment_merge(sp, tbase, tsize) && + (get_segment_flags(sp) & IS_MMAPPED_BIT) == mmap_flag && + segment_holds(sp, m->top)) { /* append */ + sp->size += tsize; + init_top(m, m->top, m->topsize + tsize); + } + else { + if (tbase < m->least_addr) + m->least_addr = tbase; + sp = &m->seg; + while (sp != 0 && sp->base != tbase + tsize) + sp = sp->next; + if (sp != 0 && + !is_extern_segment(sp) && + check_segment_merge(sp, tbase, tsize) && + (get_segment_flags(sp) & IS_MMAPPED_BIT) == mmap_flag) { + char* oldbase = sp->base; + sp->base = tbase; + sp->size += tsize; + return prepend_alloc(m, tbase, oldbase, nb); + } + else + add_segment(m, tbase, tsize, mmap_flag); + } + } + + if (nb < m->topsize) { /* Allocate from new or extended top space */ + size_t rsize = m->topsize -= nb; + mchunkptr p = m->top; + mchunkptr r = m->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + check_top_chunk(m, m->top); + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); + } + } + + MALLOC_FAILURE_ACTION; + return 0; +} + +/* ----------------------- system deallocation -------------------------- */ + +/* Unmap and unlink any mmapped segments that don't contain used chunks */ +static size_t release_unused_segments(mstate m) { + size_t released = 0; + msegmentptr pred = &m->seg; + msegmentptr sp = pred->next; + while (sp != 0) { + char* base = sp->base; + size_t size = sp->size; + msegmentptr next = sp->next; + if (is_mmapped_segment(sp) && !is_extern_segment(sp)) { + mchunkptr p = align_as_chunk(base); + size_t psize = chunksize(p); + /* Can unmap if first chunk holds entire segment and not pinned */ + if (!cinuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) { + tchunkptr tp = (tchunkptr)p; + assert(segment_holds(sp, (char*)sp)); + if (p == m->dv) { + m->dv = 0; + m->dvsize = 0; + } + else { + unlink_large_chunk(m, tp); + } + if (CALL_MUNMAP(base, size) == 0) { + released += size; + m->footprint -= size; + /* unlink obsoleted record */ + sp = pred; + sp->next = next; + } + else { /* back out if cannot unmap */ + insert_large_chunk(m, tp, psize); + } + } + } + pred = sp; + sp = next; + } + return released; +} + +static int sys_trim(mstate m, size_t pad) { + size_t released = 0; + if (pad < MAX_REQUEST && is_initialized(m)) { + pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ + + if (m->topsize > pad) { + /* Shrink top space in granularity-size units, keeping at least one */ + size_t unit = mparams.granularity; + size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit - + SIZE_T_ONE) * unit; + msegmentptr sp = segment_holding(m, (char*)m->top); + + if (!is_extern_segment(sp)) { + if (is_mmapped_segment(sp)) { + if (HAVE_MMAP && + sp->size >= extra && + !has_segment_link(m, sp)) { /* can't shrink if pinned */ + size_t newsize = sp->size - extra; + /* Prefer mremap, fall back to munmap */ + if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) || + (CALL_MUNMAP(sp->base + newsize, extra) == 0)) { + released = extra; + } + } + } + else if (HAVE_MORECORE) { + if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */ + extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit; + ACQUIRE_MORECORE_LOCK(); + { + /* Make sure end of memory is where we last set it. */ + char* old_br = (char*)(CALL_MORECORE(0)); + if (old_br == sp->base + sp->size) { + char* rel_br = (char*)(CALL_MORECORE(-extra)); + char* new_br = (char*)(CALL_MORECORE(0)); + if (rel_br != CMFAIL && new_br < old_br) + released = old_br - new_br; + } + } + RELEASE_MORECORE_LOCK(); + } + } + + if (released != 0) { + sp->size -= released; + m->footprint -= released; + init_top(m, m->top, m->topsize - released); + check_top_chunk(m, m->top); + } + } + + /* Unmap any unused mmapped segments */ + if (HAVE_MMAP) + released += release_unused_segments(m); + + /* On failure, disable autotrim to avoid repeated failed future calls */ + if (released == 0) + m->trim_check = MAX_SIZE_T; + } + + return (released != 0)? 1 : 0; +} + +/* ---------------------------- malloc support --------------------------- */ + +/* allocate a large request from the best fitting chunk in a treebin */ +static void* tmalloc_large(mstate m, size_t nb) { + tchunkptr v = 0; + size_t rsize = -nb; /* Unsigned negation */ + tchunkptr t; + bindex_t idx; + compute_tree_index(nb, idx); + + if ((t = *treebin_at(m, idx)) != 0) { + /* Traverse tree for this bin looking for node with size == nb */ + size_t sizebits = nb << leftshift_for_tree_index(idx); + tchunkptr rst = 0; /* The deepest untaken right subtree */ + for (;;) { + tchunkptr rt; + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + v = t; + if ((rsize = trem) == 0) + break; + } + rt = t->child[1]; + t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; + if (rt != 0 && rt != t) + rst = rt; + if (t == 0) { + t = rst; /* set t to least subtree holding sizes > nb */ + break; + } + sizebits <<= 1; + } + } + + if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */ + binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; + if (leftbits != 0) { + bindex_t i; + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + t = *treebin_at(m, i); + } + } + + while (t != 0) { /* find smallest of tree or subtree */ + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } + t = leftmost_child(t); + } + + /* If dv is a better fit, return 0 so malloc will use it */ + if (v != 0 && rsize < (size_t)(m->dvsize - nb)) { + if (RTCHECK(ok_address(m, v))) { /* split */ + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + insert_chunk(m, r, rsize); + } + return chunk2mem(v); + } + } + CORRUPTION_ERROR_ACTION(m); + } + return 0; +} + +/* allocate a small request from the best fitting chunk in a treebin */ +static void* tmalloc_small(mstate m, size_t nb) { + tchunkptr t, v; + size_t rsize; + bindex_t i; + binmap_t leastbit = least_bit(m->treemap); + compute_bit2idx(leastbit, i); + + v = t = *treebin_at(m, i); + rsize = chunksize(t) - nb; + + while ((t = leftmost_child(t)) != 0) { + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } + } + + if (RTCHECK(ok_address(m, v))) { + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(m, r, rsize); + } + return chunk2mem(v); + } + } + + CORRUPTION_ERROR_ACTION(m); + return 0; +} + +/* --------------------------- realloc support --------------------------- */ + +static void* internal_realloc(mstate m, void* oldmem, size_t bytes) { + if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + return 0; + } + if (!PREACTION(m)) { + mchunkptr oldp = mem2chunk(oldmem); + size_t oldsize = chunksize(oldp); + mchunkptr next = chunk_plus_offset(oldp, oldsize); + mchunkptr newp = 0; + void* extra = 0; + + /* Try to either shrink or extend into top. Else malloc-copy-free */ + + if (RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) && + ok_next(oldp, next) && ok_pinuse(next))) { + size_t nb = request2size(bytes); + if (is_mmapped(oldp)) + newp = mmap_resize(m, oldp, nb); + else if (oldsize >= nb) { /* already big enough */ + size_t rsize = oldsize - nb; + newp = oldp; + if (rsize >= MIN_CHUNK_SIZE) { + mchunkptr remainder = chunk_plus_offset(newp, nb); + set_inuse(m, newp, nb); + set_inuse(m, remainder, rsize); + extra = chunk2mem(remainder); + } + } + else if (next == m->top && oldsize + m->topsize > nb) { + /* Expand into top */ + size_t newsize = oldsize + m->topsize; + size_t newtopsize = newsize - nb; + mchunkptr newtop = chunk_plus_offset(oldp, nb); + set_inuse(m, oldp, nb); + newtop->head = newtopsize |PINUSE_BIT; + m->top = newtop; + m->topsize = newtopsize; + newp = oldp; + } + } + else { + USAGE_ERROR_ACTION(m, oldmem); + POSTACTION(m); + return 0; + } + + POSTACTION(m); + + if (newp != 0) { + if (extra != 0) { + internal_free(m, extra); + } + check_inuse_chunk(m, newp); + return chunk2mem(newp); + } + else { + void* newmem = internal_malloc(m, bytes); + if (newmem != 0) { + size_t oc = oldsize - overhead_for(oldp); + memcpy(newmem, oldmem, (oc < bytes)? oc : bytes); + internal_free(m, oldmem); + } + return newmem; + } + } + return 0; +} + +/* --------------------------- memalign support -------------------------- */ + +static void* internal_memalign(mstate m, size_t alignment, size_t bytes) { + if (alignment <= MALLOC_ALIGNMENT) /* Can just use malloc */ + return internal_malloc(m, bytes); + if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */ + alignment = MIN_CHUNK_SIZE; + if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */ + size_t a = MALLOC_ALIGNMENT << 1; + while (a < alignment) a <<= 1; + alignment = a; + } + + if (bytes >= MAX_REQUEST - alignment) { + if (m != 0) { /* Test isn't needed but avoids compiler warning */ + MALLOC_FAILURE_ACTION; + } + } + else { + size_t nb = request2size(bytes); + size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; + char* mem = (char*)internal_malloc(m, req); + if (mem != 0) { + void* leader = 0; + void* trailer = 0; + mchunkptr p = mem2chunk(mem); + + if (PREACTION(m)) return 0; + if ((((size_t)(mem)) % alignment) != 0) { /* misaligned */ + /* + Find an aligned spot inside chunk. Since we need to give + back leading space in a chunk of at least MIN_CHUNK_SIZE, if + the first calculation places us at a spot with less than + MIN_CHUNK_SIZE leader, we can move to the next aligned spot. + We've allocated enough total room so that this is always + possible. + */ + char* br = (char*)mem2chunk((size_t)(((size_t)(mem + + alignment - + SIZE_T_ONE)) & + -alignment)); + char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)? + br : br+alignment; + mchunkptr newp = (mchunkptr)pos; + size_t leadsize = pos - (char*)(p); + size_t newsize = chunksize(p) - leadsize; + + if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */ + newp->prev_foot = p->prev_foot + leadsize; + newp->head = (newsize|CINUSE_BIT); + } + else { /* Otherwise, give back leader, use the rest */ + set_inuse(m, newp, newsize); + set_inuse(m, p, leadsize); + leader = chunk2mem(p); + } + p = newp; + } + + /* Give back spare room at the end */ + if (!is_mmapped(p)) { + size_t size = chunksize(p); + if (size > nb + MIN_CHUNK_SIZE) { + size_t remainder_size = size - nb; + mchunkptr remainder = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, remainder, remainder_size); + trailer = chunk2mem(remainder); + } + } + + assert (chunksize(p) >= nb); + assert((((size_t)(chunk2mem(p))) % alignment) == 0); + check_inuse_chunk(m, p); + POSTACTION(m); + if (leader != 0) { + internal_free(m, leader); + } + if (trailer != 0) { + internal_free(m, trailer); + } + return chunk2mem(p); + } + } + return 0; +} + +/* ------------------------ comalloc/coalloc support --------------------- */ + +static void** ialloc(mstate m, + size_t n_elements, + size_t* sizes, + int opts, + void* chunks[]) { + /* + This provides common support for independent_X routines, handling + all of the combinations that can result. + + The opts arg has: + bit 0 set if all elements are same size (using sizes[0]) + bit 1 set if elements should be zeroed + */ + + size_t element_size; /* chunksize of each element, if all same */ + size_t contents_size; /* total size of elements */ + size_t array_size; /* request size of pointer array */ + void* mem; /* malloced aggregate space */ + mchunkptr p; /* corresponding chunk */ + size_t remainder_size; /* remaining bytes while splitting */ + void** marray; /* either "chunks" or malloced ptr array */ + mchunkptr array_chunk; /* chunk for malloced ptr array */ + flag_t was_enabled; /* to disable mmap */ + size_t size; + size_t i; + + /* compute array length, if needed */ + if (chunks != 0) { + if (n_elements == 0) + return chunks; /* nothing to do */ + marray = chunks; + array_size = 0; + } + else { + /* if empty req, must still return chunk representing empty array */ + if (n_elements == 0) + return (void**)internal_malloc(m, 0); + marray = 0; + array_size = request2size(n_elements * (sizeof(void*))); + } + + /* compute total element size */ + if (opts & 0x1) { /* all-same-size */ + element_size = request2size(*sizes); + contents_size = n_elements * element_size; + } + else { /* add up all the sizes */ + element_size = 0; + contents_size = 0; + for (i = 0; i != n_elements; ++i) + contents_size += request2size(sizes[i]); + } + + size = contents_size + array_size; + + /* + Allocate the aggregate chunk. First disable direct-mmapping so + malloc won't use it, since we would not be able to later + free/realloc space internal to a segregated mmap region. + */ + was_enabled = use_mmap(m); + disable_mmap(m); + mem = internal_malloc(m, size - CHUNK_OVERHEAD); + if (was_enabled) + enable_mmap(m); + if (mem == 0) + return 0; + + if (PREACTION(m)) return 0; + p = mem2chunk(mem); + remainder_size = chunksize(p); + + assert(!is_mmapped(p)); + + if (opts & 0x2) { /* optionally clear the elements */ + memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size); + } + + /* If not provided, allocate the pointer array as final part of chunk */ + if (marray == 0) { + size_t array_chunk_size; + array_chunk = chunk_plus_offset(p, contents_size); + array_chunk_size = remainder_size - contents_size; + marray = (void**) (chunk2mem(array_chunk)); + set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size); + remainder_size = contents_size; + } + + /* split out elements */ + for (i = 0; ; ++i) { + marray[i] = chunk2mem(p); + if (i != n_elements-1) { + if (element_size != 0) + size = element_size; + else + size = request2size(sizes[i]); + remainder_size -= size; + set_size_and_pinuse_of_inuse_chunk(m, p, size); + p = chunk_plus_offset(p, size); + } + else { /* the final element absorbs any overallocation slop */ + set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); + break; + } + } + +#if DEBUG + if (marray != chunks) { + /* final element must have exactly exhausted chunk */ + if (element_size != 0) { + assert(remainder_size == element_size); + } + else { + assert(remainder_size == request2size(sizes[i])); + } + check_inuse_chunk(m, mem2chunk(marray)); + } + for (i = 0; i != n_elements; ++i) + check_inuse_chunk(m, mem2chunk(marray[i])); + +#endif /* DEBUG */ + + POSTACTION(m); + return marray; +} + + +/* -------------------------- public routines ---------------------------- */ + +#if !ONLY_MSPACES + +void* dlmalloc(size_t bytes) { + /* + Basic algorithm: + If a small request (< 256 bytes minus per-chunk overhead): + 1. If one exists, use a remainderless chunk in associated smallbin. + (Remainderless means that there are too few excess bytes to + represent as a chunk.) + 2. If it is big enough, use the dv chunk, which is normally the + chunk adjacent to the one used for the most recent small request. + 3. If one exists, split the smallest available chunk in a bin, + saving remainder in dv. + 4. If it is big enough, use the top chunk. + 5. If available, get memory from system and use it + Otherwise, for a large request: + 1. Find the smallest available binned chunk that fits, and use it + if it is better fitting than dv chunk, splitting if necessary. + 2. If better fitting than any binned chunk, use the dv chunk. + 3. If it is big enough, use the top chunk. + 4. If request size >= mmap threshold, try to directly mmap this chunk. + 5. If available, get memory from system and use it + + The ugly goto's here ensure that postaction occurs along all paths. + */ + + if (!PREACTION(gm)) { + void* mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = gm->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(gm, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(gm, b, p, idx); + set_inuse_and_pinuse(gm, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (nb > gm->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(gm, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(gm, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(gm, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(gm, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + } + else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + + if (nb <= gm->dvsize) { + size_t rsize = gm->dvsize - nb; + mchunkptr p = gm->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = gm->dv = chunk_plus_offset(p, nb); + gm->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + } + else { /* exhaust dv */ + size_t dvs = gm->dvsize; + gm->dvsize = 0; + gm->dv = 0; + set_inuse_and_pinuse(gm, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (nb < gm->topsize) { /* Split top */ + size_t rsize = gm->topsize -= nb; + mchunkptr p = gm->top; + mchunkptr r = gm->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + mem = chunk2mem(p); + check_top_chunk(gm, gm->top); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + mem = sys_alloc(gm, nb); + + postaction: + POSTACTION(gm); + return mem; + } + + return 0; +} + +void dlfree(void* mem) { + /* + Consolidate freed chunks with preceding or succeeding bordering + free chunks, if they exist, and then place in a bin. Intermixed + with special cases for top, dv, mmapped chunks, and usage errors. + */ + + if (mem != 0) { + mchunkptr p = mem2chunk(mem); +#if FOOTERS + mstate fm = get_mstate_for(p); + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } +#else /* FOOTERS */ +#define fm gm +#endif /* FOOTERS */ + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if ((prevsize & IS_MMAPPED_BIT) != 0) { + prevsize &= ~IS_MMAPPED_BIT; + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } + else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } + else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } + else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } + else + set_free_with_pinuse(p, psize, next); + insert_chunk(fm, p, psize); + check_free_chunk(fm, p); + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } +#if !FOOTERS +#undef fm +#endif /* FOOTERS */ +} + +void* dlcalloc(size_t n_elements, size_t elem_size) { + void* mem; + size_t req = 0; + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t)0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = dlmalloc(req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; +} + +void* dlrealloc(void* oldmem, size_t bytes) { + if (oldmem == 0) + return dlmalloc(bytes); +#ifdef REALLOC_ZERO_BYTES_FREES + if (bytes == 0) { + dlfree(oldmem); + return 0; + } +#endif /* REALLOC_ZERO_BYTES_FREES */ + else { +#if ! FOOTERS + mstate m = gm; +#else /* FOOTERS */ + mstate m = get_mstate_for(mem2chunk(oldmem)); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + return internal_realloc(m, oldmem, bytes); + } +} + +void* dlmemalign(size_t alignment, size_t bytes) { + return internal_memalign(gm, alignment, bytes); +} + +void** dlindependent_calloc(size_t n_elements, size_t elem_size, + void* chunks[]) { + size_t sz = elem_size; /* serves as 1-element array */ + return ialloc(gm, n_elements, &sz, 3, chunks); +} + +void** dlindependent_comalloc(size_t n_elements, size_t sizes[], + void* chunks[]) { + return ialloc(gm, n_elements, sizes, 0, chunks); +} + +void* dlvalloc(size_t bytes) { + size_t pagesz; + init_mparams(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, bytes); +} + +void* dlpvalloc(size_t bytes) { + size_t pagesz; + init_mparams(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE)); +} + +int dlmalloc_trim(size_t pad) { + int result = 0; + if (!PREACTION(gm)) { + result = sys_trim(gm, pad); + POSTACTION(gm); + } + return result; +} + +size_t dlmalloc_footprint(void) { + return gm->footprint; +} + +size_t dlmalloc_max_footprint(void) { + return gm->max_footprint; +} + +#if !NO_MALLINFO +struct mallinfo dlmallinfo(void) { + return internal_mallinfo(gm); +} +#endif /* NO_MALLINFO */ + +void dlmalloc_stats() { + internal_malloc_stats(gm); +} + +size_t dlmalloc_usable_size(void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (cinuse(p)) + return chunksize(p) - overhead_for(p); + } + return 0; +} + +int dlmallopt(int param_number, int value) { + return change_mparam(param_number, value); +} + +#endif /* !ONLY_MSPACES */ + +/* ----------------------------- user mspaces ---------------------------- */ + +#if MSPACES + +static mstate init_user_mstate(char* tbase, size_t tsize) { + size_t msize = pad_request(sizeof(struct malloc_state)); + mchunkptr mn; + mchunkptr msp = align_as_chunk(tbase); + mstate m = (mstate)(chunk2mem(msp)); + memset(m, 0, msize); + INITIAL_LOCK(&m->mutex); + msp->head = (msize|PINUSE_BIT|CINUSE_BIT); + m->seg.base = m->least_addr = tbase; + m->seg.size = m->footprint = m->max_footprint = tsize; + m->magic = mparams.magic; + m->mflags = mparams.default_mflags; + disable_contiguous(m); + init_bins(m); + mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE); + check_top_chunk(m, m->top); + return m; +} + +mspace create_mspace(size_t capacity, int locked) { + mstate m = 0; + size_t msize = pad_request(sizeof(struct malloc_state)); + init_mparams(); /* Ensure pagesize etc initialized */ + + if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { + size_t rs = ((capacity == 0)? mparams.granularity : + (capacity + TOP_FOOT_SIZE + msize)); + size_t tsize = granularity_align(rs); + char* tbase = (char*)(CALL_MMAP(tsize)); + if (tbase != CMFAIL) { + m = init_user_mstate(tbase, tsize); + set_segment_flags(&m->seg, IS_MMAPPED_BIT); + set_lock(m, locked); + } + } + return (mspace)m; +} + +mspace create_mspace_with_base(void* base, size_t capacity, int locked) { + mstate m = 0; + size_t msize = pad_request(sizeof(struct malloc_state)); + init_mparams(); /* Ensure pagesize etc initialized */ + + if (capacity > msize + TOP_FOOT_SIZE && + capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { + m = init_user_mstate((char*)base, capacity); + set_segment_flags(&m->seg, EXTERN_BIT); + set_lock(m, locked); + } + return (mspace)m; +} + +size_t destroy_mspace(mspace msp) { + size_t freed = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + msegmentptr sp = &ms->seg; + while (sp != 0) { + char* base = sp->base; + size_t size = sp->size; + flag_t flag = get_segment_flags(sp); + sp = sp->next; + if ((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) && + CALL_MUNMAP(base, size) == 0) + freed += size; + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return freed; +} + +/* + mspace versions of routines are near-clones of the global + versions. This is not so nice but better than the alternatives. +*/ + + +void* mspace_malloc(mspace msp, size_t bytes) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (!PREACTION(ms)) { + void* mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = ms->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(ms, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(ms, b, p, idx); + set_inuse_and_pinuse(ms, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb > ms->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(ms, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(ms, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(ms, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(ms, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + } + else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + + if (nb <= ms->dvsize) { + size_t rsize = ms->dvsize - nb; + mchunkptr p = ms->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = ms->dv = chunk_plus_offset(p, nb); + ms->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + } + else { /* exhaust dv */ + size_t dvs = ms->dvsize; + ms->dvsize = 0; + ms->dv = 0; + set_inuse_and_pinuse(ms, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb < ms->topsize) { /* Split top */ + size_t rsize = ms->topsize -= nb; + mchunkptr p = ms->top; + mchunkptr r = ms->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + mem = chunk2mem(p); + check_top_chunk(ms, ms->top); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + mem = sys_alloc(ms, nb); + + postaction: + POSTACTION(ms); + return mem; + } + + return 0; +} + +void mspace_free(mspace msp, void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); +#if FOOTERS + mstate fm = get_mstate_for(p); +#else /* FOOTERS */ + mstate fm = (mstate)msp; +#endif /* FOOTERS */ + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if ((prevsize & IS_MMAPPED_BIT) != 0) { + prevsize &= ~IS_MMAPPED_BIT; + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } + else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } + else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } + else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } + else + set_free_with_pinuse(p, psize, next); + insert_chunk(fm, p, psize); + check_free_chunk(fm, p); + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } +} + +void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) { + void* mem; + size_t req = 0; + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t)0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = internal_malloc(ms, req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; +} + +void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) { + if (oldmem == 0) + return mspace_malloc(msp, bytes); +#ifdef REALLOC_ZERO_BYTES_FREES + if (bytes == 0) { + mspace_free(msp, oldmem); + return 0; + } +#endif /* REALLOC_ZERO_BYTES_FREES */ + else { +#if FOOTERS + mchunkptr p = mem2chunk(oldmem); + mstate ms = get_mstate_for(p); +#else /* FOOTERS */ + mstate ms = (mstate)msp; +#endif /* FOOTERS */ + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return internal_realloc(ms, oldmem, bytes); + } +} + +void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return internal_memalign(ms, alignment, bytes); +} + +void** mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void* chunks[]) { + size_t sz = elem_size; /* serves as 1-element array */ + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return ialloc(ms, n_elements, &sz, 3, chunks); +} + +void** mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void* chunks[]) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return ialloc(ms, n_elements, sizes, 0, chunks); +} + +int mspace_trim(mspace msp, size_t pad) { + int result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (!PREACTION(ms)) { + result = sys_trim(ms, pad); + POSTACTION(ms); + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +void mspace_malloc_stats(mspace msp) { + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + internal_malloc_stats(ms); + } + else { + USAGE_ERROR_ACTION(ms,ms); + } +} + +size_t mspace_footprint(mspace msp) { + size_t result; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + result = ms->footprint; + } + USAGE_ERROR_ACTION(ms,ms); + return result; +} + + +size_t mspace_max_footprint(mspace msp) { + size_t result; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + result = ms->max_footprint; + } + USAGE_ERROR_ACTION(ms,ms); + return result; +} + + +#if !NO_MALLINFO +struct mallinfo mspace_mallinfo(mspace msp) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + } + return internal_mallinfo(ms); +} +#endif /* NO_MALLINFO */ + +int mspace_mallopt(int param_number, int value) { + return change_mparam(param_number, value); +} + +#endif /* MSPACES */ + +/* -------------------- Alternative MORECORE functions ------------------- */ + +/* + Guidelines for creating a custom version of MORECORE: + + * For best performance, MORECORE should allocate in multiples of pagesize. + * MORECORE may allocate more memory than requested. (Or even less, + but this will usually result in a malloc failure.) + * MORECORE must not allocate memory when given argument zero, but + instead return one past the end address of memory from previous + nonzero call. + * For best performance, consecutive calls to MORECORE with positive + arguments should return increasing addresses, indicating that + space has been contiguously extended. + * Even though consecutive calls to MORECORE need not return contiguous + addresses, it must be OK for malloc'ed chunks to span multiple + regions in those cases where they do happen to be contiguous. + * MORECORE need not handle negative arguments -- it may instead + just return MFAIL when given negative arguments. + Negative arguments are always multiples of pagesize. MORECORE + must not misinterpret negative args as large positive unsigned + args. You can suppress all such calls from even occurring by defining + MORECORE_CANNOT_TRIM, + + As an example alternative MORECORE, here is a custom allocator + kindly contributed for pre-OSX macOS. It uses virtually but not + necessarily physically contiguous non-paged memory (locked in, + present and won't get swapped out). You can use it by uncommenting + this section, adding some #includes, and setting up the appropriate + defines above: + + #define MORECORE osMoreCore + + There is also a shutdown routine that should somehow be called for + cleanup upon program exit. + + #define MAX_POOL_ENTRIES 100 + #define MINIMUM_MORECORE_SIZE (64 * 1024U) + static int next_os_pool; + void *our_os_pools[MAX_POOL_ENTRIES]; + + void *osMoreCore(int size) + { + void *ptr = 0; + static void *sbrk_top = 0; + + if (size > 0) + { + if (size < MINIMUM_MORECORE_SIZE) + size = MINIMUM_MORECORE_SIZE; + if (CurrentExecutionLevel() == kTaskLevel) + ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0); + if (ptr == 0) + { + return (void *) MFAIL; + } + // save ptrs so they can be freed during cleanup + our_os_pools[next_os_pool] = ptr; + next_os_pool++; + ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK); + sbrk_top = (char *) ptr + size; + return ptr; + } + else if (size < 0) + { + // we don't currently support shrink behavior + return (void *) MFAIL; + } + else + { + return sbrk_top; + } + } + + // cleanup any allocated memory pools + // called as last thing before shutting down driver + + void osCleanupMem(void) + { + void **ptr; + + for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++) + if (*ptr) + { + PoolDeallocate(*ptr); + *ptr = 0; + } + } + +*/ + + +/* ----------------------------------------------------------------------- +History: + V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee) + * Add max_footprint functions + * Ensure all appropriate literals are size_t + * Fix conditional compilation problem for some #define settings + * Avoid concatenating segments with the one provided + in create_mspace_with_base + * Rename some variables to avoid compiler shadowing warnings + * Use explicit lock initialization. + * Better handling of sbrk interference. + * Simplify and fix segment insertion, trimming and mspace_destroy + * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x + * Thanks especially to Dennis Flanagan for help on these. + + V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee) + * Fix memalign brace error. + + V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee) + * Fix improper #endif nesting in C++ + * Add explicit casts needed for C++ + + V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee) + * Use trees for large bins + * Support mspaces + * Use segments to unify sbrk-based and mmap-based system allocation, + removing need for emulation on most platforms without sbrk. + * Default safety checks + * Optional footer checks. Thanks to William Robertson for the idea. + * Internal code refactoring + * Incorporate suggestions and platform-specific changes. + Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas, + Aaron Bachmann, Emery Berger, and others. + * Speed up non-fastbin processing enough to remove fastbins. + * Remove useless cfree() to avoid conflicts with other apps. + * Remove internal memcpy, memset. Compilers handle builtins better. + * Remove some options that no one ever used and rename others. + + V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee) + * Fix malloc_state bitmap array misdeclaration + + V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee) + * Allow tuning of FIRST_SORTED_BIN_SIZE + * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte. + * Better detection and support for non-contiguousness of MORECORE. + Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger + * Bypass most of malloc if no frees. Thanks To Emery Berger. + * Fix freeing of old top non-contiguous chunk im sysmalloc. + * Raised default trim and map thresholds to 256K. + * Fix mmap-related #defines. Thanks to Lubos Lunak. + * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield. + * Branch-free bin calculation + * Default trim and mmap thresholds now 256K. + + V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee) + * Introduce independent_comalloc and independent_calloc. + Thanks to Michael Pachos for motivation and help. + * Make optional .h file available + * Allow > 2GB requests on 32bit systems. + * new WIN32 sbrk, mmap, munmap, lock code from . + Thanks also to Andreas Mueller , + and Anonymous. + * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for + helping test this.) + * memalign: check alignment arg + * realloc: don't try to shift chunks backwards, since this + leads to more fragmentation in some programs and doesn't + seem to help in any others. + * Collect all cases in malloc requiring system memory into sysmalloc + * Use mmap as backup to sbrk + * Place all internal state in malloc_state + * Introduce fastbins (although similar to 2.5.1) + * Many minor tunings and cosmetic improvements + * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK + * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS + Thanks to Tony E. Bennett and others. + * Include errno.h to support default failure action. + + V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee) + * return null for negative arguments + * Added Several WIN32 cleanups from Martin C. Fong + * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h' + (e.g. WIN32 platforms) + * Cleanup header file inclusion for WIN32 platforms + * Cleanup code to avoid Microsoft Visual C++ compiler complaints + * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing + memory allocation routines + * Set 'malloc_getpagesize' for WIN32 platforms (needs more work) + * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to + usage of 'assert' in non-WIN32 code + * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to + avoid infinite loop + * Always call 'fREe()' rather than 'free()' + + V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee) + * Fixed ordering problem with boundary-stamping + + V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee) + * Added pvalloc, as recommended by H.J. Liu + * Added 64bit pointer support mainly from Wolfram Gloger + * Added anonymously donated WIN32 sbrk emulation + * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen + * malloc_extend_top: fix mask error that caused wastage after + foreign sbrks + * Add linux mremap support code from HJ Liu + + V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee) + * Integrated most documentation with the code. + * Add support for mmap, with help from + Wolfram Gloger (Gloger@lrz.uni-muenchen.de). + * Use last_remainder in more cases. + * Pack bins using idea from colin@nyx10.cs.du.edu + * Use ordered bins instead of best-fit threshold + * Eliminate block-local decls to simplify tracing and debugging. + * Support another case of realloc via move into top + * Fix error occurring when initial sbrk_base not word-aligned. + * Rely on page size for units instead of SBRK_UNIT to + avoid surprises about sbrk alignment conventions. + * Add mallinfo, mallopt. Thanks to Raymond Nijssen + (raymond@es.ele.tue.nl) for the suggestion. + * Add `pad' argument to malloc_trim and top_pad mallopt parameter. + * More precautions for cases where other routines call sbrk, + courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de). + * Added macros etc., allowing use in linux libc from + H.J. Lu (hjl@gnu.ai.mit.edu) + * Inverted this history list + + V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee) + * Re-tuned and fixed to behave more nicely with V2.6.0 changes. + * Removed all preallocation code since under current scheme + the work required to undo bad preallocations exceeds + the work saved in good cases for most test programs. + * No longer use return list or unconsolidated bins since + no scheme using them consistently outperforms those that don't + given above changes. + * Use best fit for very large chunks to prevent some worst-cases. + * Added some support for debugging + + V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee) + * Removed footers when chunks are in use. Thanks to + Paul Wilson (wilson@cs.texas.edu) for the suggestion. + + V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee) + * Added malloc_trim, with help from Wolfram Gloger + (wmglo@Dent.MED.Uni-Muenchen.DE). + + V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g) + + V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g) + * realloc: try to expand in both directions + * malloc: swap order of clean-bin strategy; + * realloc: only conditionally expand backwards + * Try not to scavenge used bins + * Use bin counts as a guide to preallocation + * Occasionally bin return list chunks in first scan + * Add a few optimizations from colin@nyx10.cs.du.edu + + V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g) + * faster bin computation & slightly different binning + * merged all consolidations to one part of malloc proper + (eliminating old malloc_find_space & malloc_clean_bin) + * Scan 2 returns chunks (not just 1) + * Propagate failure in realloc if malloc returns 0 + * Add stuff to allow compilation on non-ANSI compilers + from kpv@research.att.com + + V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu) + * removed potential for odd address access in prev_chunk + * removed dependency on getpagesize.h + * misc cosmetics and a bit more internal documentation + * anticosmetics: mangled names in macros to evade debugger strangeness + * tested on sparc, hp-700, dec-mips, rs6000 + with gcc & native cc (hp, dec only) allowing + Detlefs & Zorn comparison study (in SIGPLAN Notices.) + + Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu) + * Based loosely on libg++-1.2X malloc. (It retains some of the overall + structure of old version, but most details differ.) + +*/ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/frv/eabi.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/frv/eabi.S new file mode 100644 index 0000000..379ea4b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/frv/eabi.S @@ -0,0 +1,128 @@ +/* ----------------------------------------------------------------------- + eabi.S - Copyright (c) 2004 Anthony Green + + FR-V Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + + .globl ffi_prep_args_EABI + + .text + .p2align 4 + .globl ffi_call_EABI + .type ffi_call_EABI, @function + + # gr8 : ffi_prep_args + # gr9 : &ecif + # gr10: cif->bytes + # gr11: fig->flags + # gr12: ecif.rvalue + # gr13: fn + +ffi_call_EABI: + addi sp, #-80, sp + sti fp, @(sp, #24) + addi sp, #24, fp + movsg lr, gr5 + + /* Make room for the new arguments. */ + /* subi sp, fp, gr10 */ + + /* Store return address and incoming args on stack. */ + sti gr5, @(fp, #8) + sti gr8, @(fp, #-4) + sti gr9, @(fp, #-8) + sti gr10, @(fp, #-12) + sti gr11, @(fp, #-16) + sti gr12, @(fp, #-20) + sti gr13, @(fp, #-24) + + sub sp, gr10, sp + + /* Call ffi_prep_args. */ + ldi @(fp, #-4), gr4 + addi sp, #0, gr8 + ldi @(fp, #-8), gr9 +#ifdef __FRV_FDPIC__ + ldd @(gr4, gr0), gr14 + calll @(gr14, gr0) +#else + calll @(gr4, gr0) +#endif + + /* ffi_prep_args returns the new stack pointer. */ + mov gr8, gr4 + + ldi @(sp, #0), gr8 + ldi @(sp, #4), gr9 + ldi @(sp, #8), gr10 + ldi @(sp, #12), gr11 + ldi @(sp, #16), gr12 + ldi @(sp, #20), gr13 + + /* Always copy the return value pointer into the hidden + parameter register. This is only strictly necessary + when we're returning an aggregate type, but it doesn't + hurt to do this all the time, and it saves a branch. */ + ldi @(fp, #-20), gr3 + + /* Use the ffi_prep_args return value for the new sp. */ + mov gr4, sp + + /* Call the target function. */ + ldi @(fp, -24), gr4 +#ifdef __FRV_FDPIC__ + ldd @(gr4, gr0), gr14 + calll @(gr14, gr0) +#else + calll @(gr4, gr0) +#endif + + /* Store the result. */ + ldi @(fp, #-16), gr10 /* fig->flags */ + ldi @(fp, #-20), gr4 /* ecif.rvalue */ + + /* Is the return value stored in two registers? */ + cmpi gr10, #8, icc0 + bne icc0, 0, .L2 + /* Yes, save them. */ + sti gr8, @(gr4, #0) + sti gr9, @(gr4, #4) + bra .L3 +.L2: + /* Is the return value a structure? */ + cmpi gr10, #-1, icc0 + beq icc0, 0, .L3 + /* No, save a 4 byte return value. */ + sti gr8, @(gr4, #0) +.L3: + + /* Restore the stack, and return. */ + ldi @(fp, 8), gr5 + ld @(fp, gr0), fp + addi sp,#80,sp + jmpl @(gr5,gr0) + .size ffi_call_EABI, .-ffi_call_EABI + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/frv/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/frv/ffi.c new file mode 100644 index 0000000..ed1c65a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/frv/ffi.c @@ -0,0 +1,292 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (C) 2004 Anthony Green + Copyright (C) 2007 Free Software Foundation, Inc. + Copyright (C) 2008 Red Hat, Inc. + + FR-V Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments */ + +void *ffi_prep_args(char *stack, extended_cif *ecif) +{ + register unsigned int i; + register void **p_argv; + register char *argp; + register ffi_type **p_arg; + register int count = 0; + + p_argv = ecif->avalue; + argp = stack; + + for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; + (i != 0); + i--, p_arg++) + { + size_t z; + + z = (*p_arg)->size; + + if ((*p_arg)->type == FFI_TYPE_STRUCT) + { + z = sizeof(void*); + *(void **) argp = *p_argv; + } + /* if ((*p_arg)->type == FFI_TYPE_FLOAT) + { + if (count > 24) + { + // This is going on the stack. Turn it into a double. + *(double *) argp = (double) *(float*)(* p_argv); + z = sizeof(double); + } + else + *(void **) argp = *(void **)(* p_argv); + } */ + else if (z < sizeof(int)) + { + z = sizeof(int); + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); + break; + + default: + FFI_ASSERT(0); + } + } + else if (z == sizeof(int)) + { + *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); + } + else + { + memcpy(argp, *p_argv, z); + } + p_argv++; + argp += z; + count += z; + } + + return (stack + ((count > 24) ? 24 : FFI_ALIGN_DOWN(count, 8))); +} + +/* Perform machine dependent cif processing */ +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + if (cif->rtype->type == FFI_TYPE_STRUCT) + cif->flags = -1; + else + cif->flags = cif->rtype->size; + + cif->bytes = FFI_ALIGN (cif->bytes, 8); + + return FFI_OK; +} + +extern void ffi_call_EABI(void *(*)(char *, extended_cif *), + extended_cif *, + unsigned, unsigned, + unsigned *, + void (*fn)(void)); + +void ffi_call(ffi_cif *cif, + void (*fn)(void), + void *rvalue, + void **avalue) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return */ + /* value address then we need to make one */ + + if ((rvalue == NULL) && + (cif->rtype->type == FFI_TYPE_STRUCT)) + { + ecif.rvalue = alloca(cif->rtype->size); + } + else + ecif.rvalue = rvalue; + + + switch (cif->abi) + { + case FFI_EABI: + ffi_call_EABI(ffi_prep_args, &ecif, cif->bytes, + cif->flags, ecif.rvalue, fn); + break; + default: + FFI_ASSERT(0); + break; + } +} + +void ffi_closure_eabi (unsigned arg1, unsigned arg2, unsigned arg3, + unsigned arg4, unsigned arg5, unsigned arg6) +{ + /* This function is called by a trampoline. The trampoline stows a + pointer to the ffi_closure object in gr7. We must save this + pointer in a place that will persist while we do our work. */ + register ffi_closure *creg __asm__ ("gr7"); + ffi_closure *closure = creg; + + /* Arguments that don't fit in registers are found on the stack + at a fixed offset above the current frame pointer. */ + register char *frame_pointer __asm__ ("fp"); + char *stack_args = frame_pointer + 16; + + /* Lay the register arguments down in a continuous chunk of memory. */ + unsigned register_args[6] = + { arg1, arg2, arg3, arg4, arg5, arg6 }; + + ffi_cif *cif = closure->cif; + ffi_type **arg_types = cif->arg_types; + void **avalue = alloca (cif->nargs * sizeof(void *)); + char *ptr = (char *) register_args; + int i; + + /* Find the address of each argument. */ + for (i = 0; i < cif->nargs; i++) + { + switch (arg_types[i]->type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + avalue[i] = ptr + 3; + break; + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + avalue[i] = ptr + 2; + break; + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_FLOAT: + avalue[i] = ptr; + break; + case FFI_TYPE_STRUCT: + avalue[i] = *(void**)ptr; + break; + default: + /* This is an 8-byte value. */ + avalue[i] = ptr; + ptr += 4; + break; + } + ptr += 4; + + /* If we've handled more arguments than fit in registers, + start looking at the those passed on the stack. */ + if (ptr == ((char *)register_args + (6*4))) + ptr = stack_args; + } + + /* Invoke the closure. */ + if (cif->rtype->type == FFI_TYPE_STRUCT) + { + /* The caller allocates space for the return structure, and + passes a pointer to this space in gr3. Use this value directly + as the return value. */ + register void *return_struct_ptr __asm__("gr3"); + (closure->fun) (cif, return_struct_ptr, avalue, closure->user_data); + } + else + { + /* Allocate space for the return value and call the function. */ + long long rvalue; + (closure->fun) (cif, &rvalue, avalue, closure->user_data); + + /* Functions return 4-byte or smaller results in gr8. 8-byte + values also use gr9. We fill the both, even for small return + values, just to avoid a branch. */ + asm ("ldi @(%0, #0), gr8" : : "r" (&rvalue)); + asm ("ldi @(%0, #0), gr9" : : "r" (&((int *) &rvalue)[1])); + } +} + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + unsigned int *tramp = (unsigned int *) &closure->tramp[0]; + unsigned long fn = (long) ffi_closure_eabi; + unsigned long cls = (long) codeloc; +#ifdef __FRV_FDPIC__ + register void *got __asm__("gr15"); +#endif + int i; + + fn = (unsigned long) ffi_closure_eabi; + +#ifdef __FRV_FDPIC__ + tramp[0] = &((unsigned int *)codeloc)[2]; + tramp[1] = got; + tramp[2] = 0x8cfc0000 + (fn & 0xffff); /* setlos lo(fn), gr6 */ + tramp[3] = 0x8efc0000 + (cls & 0xffff); /* setlos lo(cls), gr7 */ + tramp[4] = 0x8cf80000 + (fn >> 16); /* sethi hi(fn), gr6 */ + tramp[5] = 0x8ef80000 + (cls >> 16); /* sethi hi(cls), gr7 */ + tramp[6] = 0x9cc86000; /* ldi @(gr6, #0), gr14 */ + tramp[7] = 0x8030e000; /* jmpl @(gr14, gr0) */ +#else + tramp[0] = 0x8cfc0000 + (fn & 0xffff); /* setlos lo(fn), gr6 */ + tramp[1] = 0x8efc0000 + (cls & 0xffff); /* setlos lo(cls), gr7 */ + tramp[2] = 0x8cf80000 + (fn >> 16); /* sethi hi(fn), gr6 */ + tramp[3] = 0x8ef80000 + (cls >> 16); /* sethi hi(cls), gr7 */ + tramp[4] = 0x80300006; /* jmpl @(gr0, gr6) */ +#endif + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + /* Cache flushing. */ + for (i = 0; i < FFI_TRAMPOLINE_SIZE; i++) + __asm__ volatile ("dcf @(%0,%1)\n\tici @(%2,%1)" :: "r" (tramp), "r" (i), + "r" (codeloc)); + + return FFI_OK; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/frv/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/frv/ffitarget.h new file mode 100644 index 0000000..d42540e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/frv/ffitarget.h @@ -0,0 +1,62 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 1996-2004 Red Hat, Inc. + Target configuration macros for FR-V + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +/* ---- System specific configurations ----------------------------------- */ + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_EABI, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_EABI +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 + +#ifdef __FRV_FDPIC__ +/* Trampolines are 8 4-byte instructions long. */ +#define FFI_TRAMPOLINE_SIZE (8*4) +#else +/* Trampolines are 5 4-byte instructions long. */ +#define FFI_TRAMPOLINE_SIZE (5*4) +#endif + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/ffi.c new file mode 100644 index 0000000..b1d04c3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/ffi.c @@ -0,0 +1,604 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 1998, 2007, 2008, 2012 Red Hat, Inc. + Copyright (c) 2000 Hewlett Packard Company + Copyright (c) 2011 Anthony Green + + IA64 Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include +#include +#include + +#include "ia64_flags.h" + +/* A 64-bit pointer value. In LP64 mode, this is effectively a plain + pointer. In ILP32 mode, it's a pointer that's been extended to + 64 bits by "addp4". */ +typedef void *PTR64 __attribute__((mode(DI))); + +/* Memory image of fp register contents. This is the implementation + specific format used by ldf.fill/stf.spill. All we care about is + that it wants a 16 byte aligned slot. */ +typedef struct +{ + UINT64 x[2] __attribute__((aligned(16))); +} fpreg; + + +/* The stack layout given to ffi_call_unix and ffi_closure_unix_inner. */ + +struct ia64_args +{ + fpreg fp_regs[8]; /* Contents of 8 fp arg registers. */ + UINT64 gp_regs[8]; /* Contents of 8 gp arg registers. */ + UINT64 other_args[]; /* Arguments passed on stack, variable size. */ +}; + + +/* Adjust ADDR, a pointer to an 8 byte slot, to point to the low LEN bytes. */ + +static inline void * +endian_adjust (void *addr, size_t len) +{ +#ifdef __BIG_ENDIAN__ + return addr + (8 - len); +#else + return addr; +#endif +} + +/* Store VALUE to ADDR in the current cpu implementation's fp spill format. + This is a macro instead of a function, so that it works for all 3 floating + point types without type conversions. Type conversion to long double breaks + the denorm support. */ + +#define stf_spill(addr, value) \ + asm ("stf.spill %0 = %1%P0" : "=m" (*addr) : "f"(value)); + +/* Load a value from ADDR, which is in the current cpu implementation's + fp spill format. As above, this must also be a macro. */ + +#define ldf_fill(result, addr) \ + asm ("ldf.fill %0 = %1%P1" : "=f"(result) : "m"(*addr)); + +/* Return the size of the C type associated with with TYPE. Which will + be one of the FFI_IA64_TYPE_HFA_* values. */ + +static size_t +hfa_type_size (int type) +{ + switch (type) + { + case FFI_IA64_TYPE_HFA_FLOAT: + return sizeof(float); + case FFI_IA64_TYPE_HFA_DOUBLE: + return sizeof(double); + case FFI_IA64_TYPE_HFA_LDOUBLE: + return sizeof(__float80); + default: + abort (); + } +} + +/* Load from ADDR a value indicated by TYPE. Which will be one of + the FFI_IA64_TYPE_HFA_* values. */ + +static void +hfa_type_load (fpreg *fpaddr, int type, void *addr) +{ + switch (type) + { + case FFI_IA64_TYPE_HFA_FLOAT: + stf_spill (fpaddr, *(float *) addr); + return; + case FFI_IA64_TYPE_HFA_DOUBLE: + stf_spill (fpaddr, *(double *) addr); + return; + case FFI_IA64_TYPE_HFA_LDOUBLE: + stf_spill (fpaddr, *(__float80 *) addr); + return; + default: + abort (); + } +} + +/* Load VALUE into ADDR as indicated by TYPE. Which will be one of + the FFI_IA64_TYPE_HFA_* values. */ + +static void +hfa_type_store (int type, void *addr, fpreg *fpaddr) +{ + switch (type) + { + case FFI_IA64_TYPE_HFA_FLOAT: + { + float result; + ldf_fill (result, fpaddr); + *(float *) addr = result; + break; + } + case FFI_IA64_TYPE_HFA_DOUBLE: + { + double result; + ldf_fill (result, fpaddr); + *(double *) addr = result; + break; + } + case FFI_IA64_TYPE_HFA_LDOUBLE: + { + __float80 result; + ldf_fill (result, fpaddr); + *(__float80 *) addr = result; + break; + } + default: + abort (); + } +} + +/* Is TYPE a struct containing floats, doubles, or extended doubles, + all of the same fp type? If so, return the element type. Return + FFI_TYPE_VOID if not. */ + +static int +hfa_element_type (ffi_type *type, int nested) +{ + int element = FFI_TYPE_VOID; + + switch (type->type) + { + case FFI_TYPE_FLOAT: + /* We want to return VOID for raw floating-point types, but the + synthetic HFA type if we're nested within an aggregate. */ + if (nested) + element = FFI_IA64_TYPE_HFA_FLOAT; + break; + + case FFI_TYPE_DOUBLE: + /* Similarly. */ + if (nested) + element = FFI_IA64_TYPE_HFA_DOUBLE; + break; + + case FFI_TYPE_LONGDOUBLE: + /* Similarly, except that that HFA is true for double extended, + but not quad precision. Both have sizeof == 16, so tell the + difference based on the precision. */ + if (LDBL_MANT_DIG == 64 && nested) + element = FFI_IA64_TYPE_HFA_LDOUBLE; + break; + + case FFI_TYPE_STRUCT: + { + ffi_type **ptr = &type->elements[0]; + + for (ptr = &type->elements[0]; *ptr ; ptr++) + { + int sub_element = hfa_element_type (*ptr, 1); + if (sub_element == FFI_TYPE_VOID) + return FFI_TYPE_VOID; + + if (element == FFI_TYPE_VOID) + element = sub_element; + else if (element != sub_element) + return FFI_TYPE_VOID; + } + } + break; + + default: + return FFI_TYPE_VOID; + } + + return element; +} + + +/* Perform machine dependent cif processing. */ + +static ffi_status +ffi_prep_cif_machdep_core(ffi_cif *cif) +{ + int flags; + + /* Adjust cif->bytes to include space for the bits of the ia64_args frame + that precedes the integer register portion. The estimate that the + generic bits did for the argument space required is good enough for the + integer component. */ + cif->bytes += offsetof(struct ia64_args, gp_regs[0]); + if (cif->bytes < sizeof(struct ia64_args)) + cif->bytes = sizeof(struct ia64_args); + + /* Set the return type flag. */ + flags = cif->rtype->type; + switch (cif->rtype->type) + { + case FFI_TYPE_LONGDOUBLE: + /* Leave FFI_TYPE_LONGDOUBLE as meaning double extended precision, + and encode quad precision as a two-word integer structure. */ + if (LDBL_MANT_DIG != 64) + flags = FFI_IA64_TYPE_SMALL_STRUCT | (16 << 8); + break; + + case FFI_TYPE_STRUCT: + { + size_t size = cif->rtype->size; + int hfa_type = hfa_element_type (cif->rtype, 0); + + if (hfa_type != FFI_TYPE_VOID) + { + size_t nelts = size / hfa_type_size (hfa_type); + if (nelts <= 8) + flags = hfa_type | (size << 8); + } + else + { + if (size <= 32) + flags = FFI_IA64_TYPE_SMALL_STRUCT | (size << 8); + } + } + break; + + default: + break; + } + cif->flags = flags; + + return FFI_OK; +} + +ffi_status +ffi_prep_cif_machdep(ffi_cif *cif) +{ + cif->nfixedargs = cif->nargs; + return ffi_prep_cif_machdep_core(cif); +} + +ffi_status +ffi_prep_cif_machdep_var(ffi_cif *cif, + unsigned int nfixedargs, + unsigned int ntotalargs MAYBE_UNUSED) +{ + cif->nfixedargs = nfixedargs; + return ffi_prep_cif_machdep_core(cif); +} + +extern int ffi_call_unix (struct ia64_args *, PTR64, void (*)(void), UINT64); + +void +ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + struct ia64_args *stack; + long i, avn, gpcount, fpcount; + ffi_type **p_arg; + + FFI_ASSERT (cif->abi == FFI_UNIX); + + /* If we have no spot for a return value, make one. */ + if (rvalue == NULL && cif->rtype->type != FFI_TYPE_VOID) + rvalue = alloca (cif->rtype->size); + + /* Allocate the stack frame. */ + stack = alloca (cif->bytes); + + gpcount = fpcount = 0; + avn = cif->nargs; + for (i = 0, p_arg = cif->arg_types; i < avn; i++, p_arg++) + { + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + stack->gp_regs[gpcount++] = *(SINT8 *)avalue[i]; + break; + case FFI_TYPE_UINT8: + stack->gp_regs[gpcount++] = *(UINT8 *)avalue[i]; + break; + case FFI_TYPE_SINT16: + stack->gp_regs[gpcount++] = *(SINT16 *)avalue[i]; + break; + case FFI_TYPE_UINT16: + stack->gp_regs[gpcount++] = *(UINT16 *)avalue[i]; + break; + case FFI_TYPE_SINT32: + stack->gp_regs[gpcount++] = *(SINT32 *)avalue[i]; + break; + case FFI_TYPE_UINT32: + stack->gp_regs[gpcount++] = *(UINT32 *)avalue[i]; + break; + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + stack->gp_regs[gpcount++] = *(UINT64 *)avalue[i]; + break; + + case FFI_TYPE_POINTER: + stack->gp_regs[gpcount++] = (UINT64)(PTR64) *(void **)avalue[i]; + break; + + case FFI_TYPE_FLOAT: + if (gpcount < 8 && fpcount < 8) + stf_spill (&stack->fp_regs[fpcount++], *(float *)avalue[i]); + { + UINT32 tmp; + memcpy (&tmp, avalue[i], sizeof (UINT32)); + stack->gp_regs[gpcount++] = tmp; + } + break; + + case FFI_TYPE_DOUBLE: + if (gpcount < 8 && fpcount < 8) + stf_spill (&stack->fp_regs[fpcount++], *(double *)avalue[i]); + memcpy (&stack->gp_regs[gpcount++], avalue[i], sizeof (UINT64)); + break; + + case FFI_TYPE_LONGDOUBLE: + if (gpcount & 1) + gpcount++; + if (LDBL_MANT_DIG == 64 && gpcount < 8 && fpcount < 8) + stf_spill (&stack->fp_regs[fpcount++], *(__float80 *)avalue[i]); + memcpy (&stack->gp_regs[gpcount], avalue[i], 16); + gpcount += 2; + break; + + case FFI_TYPE_STRUCT: + { + size_t size = (*p_arg)->size; + size_t align = (*p_arg)->alignment; + int hfa_type = hfa_element_type (*p_arg, 0); + + FFI_ASSERT (align <= 16); + if (align == 16 && (gpcount & 1)) + gpcount++; + + if (hfa_type != FFI_TYPE_VOID) + { + size_t hfa_size = hfa_type_size (hfa_type); + size_t offset = 0; + size_t gp_offset = gpcount * 8; + + while (fpcount < 8 + && offset < size + && gp_offset < 8 * 8) + { + hfa_type_load (&stack->fp_regs[fpcount], hfa_type, + avalue[i] + offset); + offset += hfa_size; + gp_offset += hfa_size; + fpcount += 1; + } + } + + memcpy (&stack->gp_regs[gpcount], avalue[i], size); + gpcount += (size + 7) / 8; + } + break; + + default: + abort (); + } + } + + ffi_call_unix (stack, rvalue, fn, cif->flags); +} + +/* Closures represent a pair consisting of a function pointer, and + some user data. A closure is invoked by reinterpreting the closure + as a function pointer, and branching to it. Thus we can make an + interpreted function callable as a C function: We turn the + interpreter itself, together with a pointer specifying the + interpreted procedure, into a closure. + + For IA64, function pointer are already pairs consisting of a code + pointer, and a gp pointer. The latter is needed to access global + variables. Here we set up such a pair as the first two words of + the closure (in the "trampoline" area), but we replace the gp + pointer with a pointer to the closure itself. We also add the real + gp pointer to the closure. This allows the function entry code to + both retrieve the user data, and to restore the correct gp pointer. */ + +extern void ffi_closure_unix (); + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + /* The layout of a function descriptor. A C function pointer really + points to one of these. */ + struct ia64_fd + { + UINT64 code_pointer; + UINT64 gp; + }; + + struct ffi_ia64_trampoline_struct + { + UINT64 code_pointer; /* Pointer to ffi_closure_unix. */ + UINT64 fake_gp; /* Pointer to closure, installed as gp. */ + UINT64 real_gp; /* Real gp value. */ + }; + + struct ffi_ia64_trampoline_struct *tramp; + struct ia64_fd *fd; + + if (cif->abi != FFI_UNIX) + return FFI_BAD_ABI; + + tramp = (struct ffi_ia64_trampoline_struct *)closure->tramp; + fd = (struct ia64_fd *)(void *)ffi_closure_unix; + + tramp->code_pointer = fd->code_pointer; + tramp->real_gp = fd->gp; + tramp->fake_gp = (UINT64)(PTR64)codeloc; + closure->cif = cif; + closure->user_data = user_data; + closure->fun = fun; + + return FFI_OK; +} + + +UINT64 +ffi_closure_unix_inner (ffi_closure *closure, struct ia64_args *stack, + void *rvalue, void *r8) +{ + ffi_cif *cif; + void **avalue; + ffi_type **p_arg; + long i, avn, gpcount, fpcount, nfixedargs; + + cif = closure->cif; + avn = cif->nargs; + nfixedargs = cif->nfixedargs; + avalue = alloca (avn * sizeof (void *)); + + /* If the structure return value is passed in memory get that location + from r8 so as to pass the value directly back to the caller. */ + if (cif->flags == FFI_TYPE_STRUCT) + rvalue = r8; + + gpcount = fpcount = 0; + for (i = 0, p_arg = cif->arg_types; i < avn; i++, p_arg++) + { + int named = i < nfixedargs; + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + avalue[i] = endian_adjust(&stack->gp_regs[gpcount++], 1); + break; + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + avalue[i] = endian_adjust(&stack->gp_regs[gpcount++], 2); + break; + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + avalue[i] = endian_adjust(&stack->gp_regs[gpcount++], 4); + break; + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + avalue[i] = &stack->gp_regs[gpcount++]; + break; + case FFI_TYPE_POINTER: + avalue[i] = endian_adjust(&stack->gp_regs[gpcount++], sizeof(void*)); + break; + + case FFI_TYPE_FLOAT: + if (named && gpcount < 8 && fpcount < 8) + { + fpreg *addr = &stack->fp_regs[fpcount++]; + float result; + avalue[i] = addr; + ldf_fill (result, addr); + *(float *)addr = result; + } + else + avalue[i] = endian_adjust(&stack->gp_regs[gpcount], 4); + gpcount++; + break; + + case FFI_TYPE_DOUBLE: + if (named && gpcount < 8 && fpcount < 8) + { + fpreg *addr = &stack->fp_regs[fpcount++]; + double result; + avalue[i] = addr; + ldf_fill (result, addr); + *(double *)addr = result; + } + else + avalue[i] = &stack->gp_regs[gpcount]; + gpcount++; + break; + + case FFI_TYPE_LONGDOUBLE: + if (gpcount & 1) + gpcount++; + if (LDBL_MANT_DIG == 64 && named && gpcount < 8 && fpcount < 8) + { + fpreg *addr = &stack->fp_regs[fpcount++]; + __float80 result; + avalue[i] = addr; + ldf_fill (result, addr); + *(__float80 *)addr = result; + } + else + avalue[i] = &stack->gp_regs[gpcount]; + gpcount += 2; + break; + + case FFI_TYPE_STRUCT: + { + size_t size = (*p_arg)->size; + size_t align = (*p_arg)->alignment; + int hfa_type = hfa_element_type (*p_arg, 0); + + FFI_ASSERT (align <= 16); + if (align == 16 && (gpcount & 1)) + gpcount++; + + if (hfa_type != FFI_TYPE_VOID) + { + size_t hfa_size = hfa_type_size (hfa_type); + size_t offset = 0; + size_t gp_offset = gpcount * 8; + void *addr = alloca (size); + + avalue[i] = addr; + + while (fpcount < 8 + && offset < size + && gp_offset < 8 * 8) + { + hfa_type_store (hfa_type, addr + offset, + &stack->fp_regs[fpcount]); + offset += hfa_size; + gp_offset += hfa_size; + fpcount += 1; + } + + if (offset < size) + memcpy (addr + offset, (char *)stack->gp_regs + gp_offset, + size - offset); + } + else + avalue[i] = &stack->gp_regs[gpcount]; + + gpcount += (size + 7) / 8; + } + break; + + default: + abort (); + } + } + + closure->fun (cif, rvalue, avalue, closure->user_data); + + return cif->flags; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/ffitarget.h new file mode 100644 index 0000000..fd5b9a0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/ffitarget.h @@ -0,0 +1,56 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 1996-2003 Red Hat, Inc. + Target configuration macros for IA-64. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long long ffi_arg; +typedef signed long long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_UNIX, /* Linux and all Unix variants use the same conventions */ + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_UNIX +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 24 /* Really the following struct, which */ + /* can be interpreted as a C function */ + /* descriptor: */ +#define FFI_TARGET_SPECIFIC_VARIADIC 1 +#define FFI_EXTRA_CIF_FIELDS unsigned nfixedargs + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/ia64_flags.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/ia64_flags.h new file mode 100644 index 0000000..9d652ce --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/ia64_flags.h @@ -0,0 +1,40 @@ +/* ----------------------------------------------------------------------- + ia64_flags.h - Copyright (c) 2000 Hewlett Packard Company + + IA64/unix Foreign Function Interface + + Original author: Hans Boehm, HP Labs + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +/* "Type" codes used between assembly and C. When used as a part of + a cfi->flags value, the low byte will be these extra type codes, + and bits 8-31 will be the actual size of the type. */ + +/* Small structures containing N words in integer registers. */ +#define FFI_IA64_TYPE_SMALL_STRUCT (FFI_TYPE_LAST + 1) + +/* Homogeneous Floating Point Aggregates (HFAs) which are returned + in FP registers. */ +#define FFI_IA64_TYPE_HFA_FLOAT (FFI_TYPE_LAST + 2) +#define FFI_IA64_TYPE_HFA_DOUBLE (FFI_TYPE_LAST + 3) +#define FFI_IA64_TYPE_HFA_LDOUBLE (FFI_TYPE_LAST + 4) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/unix.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/unix.S new file mode 100644 index 0000000..e2547e0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/ia64/unix.S @@ -0,0 +1,567 @@ +/* ----------------------------------------------------------------------- + unix.S - Copyright (c) 1998, 2008 Red Hat, Inc. + Copyright (c) 2000 Hewlett Packard Company + + IA64/unix Foreign Function Interface + + Primary author: Hans Boehm, HP Labs + + Loosely modeled on Cygnus code for other platforms. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include +#include "ia64_flags.h" + + .pred.safe_across_calls p1-p5,p16-p63 +.text + +/* int ffi_call_unix (struct ia64_args *stack, PTR64 rvalue, + void (*fn)(void), int flags); + */ + + .align 16 + .global ffi_call_unix + .proc ffi_call_unix +ffi_call_unix: + .prologue + /* Bit o trickiness. We actually share a stack frame with ffi_call. + Rely on the fact that ffi_call uses a vframe and don't bother + tracking one here at all. */ + .fframe 0 + .save ar.pfs, r36 // loc0 + alloc loc0 = ar.pfs, 4, 3, 8, 0 + .save rp, loc1 + mov loc1 = b0 + .body + add r16 = 16, in0 + mov loc2 = gp + mov r8 = in1 + ;; + + /* Load up all of the argument registers. */ + ldf.fill f8 = [in0], 32 + ldf.fill f9 = [r16], 32 + ;; + ldf.fill f10 = [in0], 32 + ldf.fill f11 = [r16], 32 + ;; + ldf.fill f12 = [in0], 32 + ldf.fill f13 = [r16], 32 + ;; + ldf.fill f14 = [in0], 32 + ldf.fill f15 = [r16], 24 + ;; + ld8 out0 = [in0], 16 + ld8 out1 = [r16], 16 + ;; + ld8 out2 = [in0], 16 + ld8 out3 = [r16], 16 + ;; + ld8 out4 = [in0], 16 + ld8 out5 = [r16], 16 + ;; + ld8 out6 = [in0] + ld8 out7 = [r16] + ;; + + /* Deallocate the register save area from the stack frame. */ + mov sp = in0 + + /* Call the target function. */ + ld8 r16 = [in2], 8 + ;; + ld8 gp = [in2] + mov b6 = r16 + br.call.sptk.many b0 = b6 + ;; + + /* Dispatch to handle return value. */ + mov gp = loc2 + zxt1 r16 = in3 + ;; + mov ar.pfs = loc0 + addl r18 = @ltoffx(.Lst_table), gp + ;; + ld8.mov r18 = [r18], .Lst_table + mov b0 = loc1 + ;; + shladd r18 = r16, 3, r18 + ;; + ld8 r17 = [r18] + shr in3 = in3, 8 + ;; + add r17 = r17, r18 + ;; + mov b6 = r17 + br b6 + ;; + +.Lst_void: + br.ret.sptk.many b0 + ;; +.Lst_uint8: + zxt1 r8 = r8 + ;; + st8 [in1] = r8 + br.ret.sptk.many b0 + ;; +.Lst_sint8: + sxt1 r8 = r8 + ;; + st8 [in1] = r8 + br.ret.sptk.many b0 + ;; +.Lst_uint16: + zxt2 r8 = r8 + ;; + st8 [in1] = r8 + br.ret.sptk.many b0 + ;; +.Lst_sint16: + sxt2 r8 = r8 + ;; + st8 [in1] = r8 + br.ret.sptk.many b0 + ;; +.Lst_uint32: + zxt4 r8 = r8 + ;; + st8 [in1] = r8 + br.ret.sptk.many b0 + ;; +.Lst_sint32: + sxt4 r8 = r8 + ;; + st8 [in1] = r8 + br.ret.sptk.many b0 + ;; +.Lst_int64: + st8 [in1] = r8 + br.ret.sptk.many b0 + ;; +.Lst_float: + stfs [in1] = f8 + br.ret.sptk.many b0 + ;; +.Lst_double: + stfd [in1] = f8 + br.ret.sptk.many b0 + ;; +.Lst_ldouble: + stfe [in1] = f8 + br.ret.sptk.many b0 + ;; + +.Lst_small_struct: + cmp.lt p6, p0 = 8, in3 + cmp.lt p7, p0 = 16, in3 + cmp.lt p8, p0 = 24, in3 + ;; + add r16 = 8, sp + add r17 = 16, sp + add r18 = 24, sp + ;; + st8 [sp] = r8 +(p6) st8 [r16] = r9 + mov out0 = in1 +(p7) st8 [r17] = r10 +(p8) st8 [r18] = r11 + mov out1 = sp + mov out2 = in3 + ;; + // ia64 software calling convention requires + // top 16 bytes of stack to be scratch space + // PLT resolver uses that scratch space at + // 'memcpy' symbol reolution time + add sp = -16, sp + br.call.sptk.many b0 = memcpy# + ;; + mov ar.pfs = loc0 + mov b0 = loc1 + mov gp = loc2 + br.ret.sptk.many b0 + +.Lst_hfa_float: + add r16 = 4, in1 + cmp.lt p6, p0 = 4, in3 + ;; + stfs [in1] = f8, 8 +(p6) stfs [r16] = f9, 8 + cmp.lt p7, p0 = 8, in3 + cmp.lt p8, p0 = 12, in3 + ;; +(p7) stfs [in1] = f10, 8 +(p8) stfs [r16] = f11, 8 + cmp.lt p9, p0 = 16, in3 + cmp.lt p10, p0 = 20, in3 + ;; +(p9) stfs [in1] = f12, 8 +(p10) stfs [r16] = f13, 8 + cmp.lt p6, p0 = 24, in3 + cmp.lt p7, p0 = 28, in3 + ;; +(p6) stfs [in1] = f14 +(p7) stfs [r16] = f15 + br.ret.sptk.many b0 + ;; + +.Lst_hfa_double: + add r16 = 8, in1 + cmp.lt p6, p0 = 8, in3 + ;; + stfd [in1] = f8, 16 +(p6) stfd [r16] = f9, 16 + cmp.lt p7, p0 = 16, in3 + cmp.lt p8, p0 = 24, in3 + ;; +(p7) stfd [in1] = f10, 16 +(p8) stfd [r16] = f11, 16 + cmp.lt p9, p0 = 32, in3 + cmp.lt p10, p0 = 40, in3 + ;; +(p9) stfd [in1] = f12, 16 +(p10) stfd [r16] = f13, 16 + cmp.lt p6, p0 = 48, in3 + cmp.lt p7, p0 = 56, in3 + ;; +(p6) stfd [in1] = f14 +(p7) stfd [r16] = f15 + br.ret.sptk.many b0 + ;; + +.Lst_hfa_ldouble: + add r16 = 16, in1 + cmp.lt p6, p0 = 16, in3 + ;; + stfe [in1] = f8, 32 +(p6) stfe [r16] = f9, 32 + cmp.lt p7, p0 = 32, in3 + cmp.lt p8, p0 = 48, in3 + ;; +(p7) stfe [in1] = f10, 32 +(p8) stfe [r16] = f11, 32 + cmp.lt p9, p0 = 64, in3 + cmp.lt p10, p0 = 80, in3 + ;; +(p9) stfe [in1] = f12, 32 +(p10) stfe [r16] = f13, 32 + cmp.lt p6, p0 = 96, in3 + cmp.lt p7, p0 = 112, in3 + ;; +(p6) stfe [in1] = f14 +(p7) stfe [r16] = f15 + br.ret.sptk.many b0 + ;; + + .endp ffi_call_unix + + .align 16 + .global ffi_closure_unix + .proc ffi_closure_unix + +#define FRAME_SIZE (8*16 + 8*8 + 8*16) + +ffi_closure_unix: + .prologue + .save ar.pfs, r40 // loc0 + alloc loc0 = ar.pfs, 8, 4, 4, 0 + .fframe FRAME_SIZE + add r12 = -FRAME_SIZE, r12 + .save rp, loc1 + mov loc1 = b0 + .save ar.unat, loc2 + mov loc2 = ar.unat + .body + + /* Retrieve closure pointer and real gp. */ +#ifdef _ILP32 + addp4 out0 = 0, gp + addp4 gp = 16, gp +#else + mov out0 = gp + add gp = 16, gp +#endif + ;; + ld8 gp = [gp] + + /* Spill all of the possible argument registers. */ + add r16 = 16 + 8*16, sp + add r17 = 16 + 8*16 + 16, sp + ;; + stf.spill [r16] = f8, 32 + stf.spill [r17] = f9, 32 + mov loc3 = gp + ;; + stf.spill [r16] = f10, 32 + stf.spill [r17] = f11, 32 + ;; + stf.spill [r16] = f12, 32 + stf.spill [r17] = f13, 32 + ;; + stf.spill [r16] = f14, 32 + stf.spill [r17] = f15, 24 + ;; + .mem.offset 0, 0 + st8.spill [r16] = in0, 16 + .mem.offset 8, 0 + st8.spill [r17] = in1, 16 + add out1 = 16 + 8*16, sp + ;; + .mem.offset 0, 0 + st8.spill [r16] = in2, 16 + .mem.offset 8, 0 + st8.spill [r17] = in3, 16 + add out2 = 16, sp + ;; + .mem.offset 0, 0 + st8.spill [r16] = in4, 16 + .mem.offset 8, 0 + st8.spill [r17] = in5, 16 + mov out3 = r8 + ;; + .mem.offset 0, 0 + st8.spill [r16] = in6 + .mem.offset 8, 0 + st8.spill [r17] = in7 + + /* Invoke ffi_closure_unix_inner for the hard work. */ + br.call.sptk.many b0 = ffi_closure_unix_inner + ;; + + /* Dispatch to handle return value. */ + mov gp = loc3 + zxt1 r16 = r8 + ;; + addl r18 = @ltoffx(.Lld_table), gp + mov ar.pfs = loc0 + ;; + ld8.mov r18 = [r18], .Lld_table + mov b0 = loc1 + ;; + shladd r18 = r16, 3, r18 + mov ar.unat = loc2 + ;; + ld8 r17 = [r18] + shr r8 = r8, 8 + ;; + add r17 = r17, r18 + add r16 = 16, sp + ;; + mov b6 = r17 + br b6 + ;; + .label_state 1 + +.Lld_void: + .restore sp + add sp = FRAME_SIZE, sp + br.ret.sptk.many b0 + ;; +.Lld_int: + .body + .copy_state 1 + ld8 r8 = [r16] + .restore sp + add sp = FRAME_SIZE, sp + br.ret.sptk.many b0 + ;; +.Lld_float: + .body + .copy_state 1 + ldfs f8 = [r16] + .restore sp + add sp = FRAME_SIZE, sp + br.ret.sptk.many b0 + ;; +.Lld_double: + .body + .copy_state 1 + ldfd f8 = [r16] + .restore sp + add sp = FRAME_SIZE, sp + br.ret.sptk.many b0 + ;; +.Lld_ldouble: + .body + .copy_state 1 + ldfe f8 = [r16] + .restore sp + add sp = FRAME_SIZE, sp + br.ret.sptk.many b0 + ;; + +.Lld_small_struct: + .body + .copy_state 1 + add r17 = 8, r16 + cmp.lt p6, p0 = 8, r8 + cmp.lt p7, p0 = 16, r8 + cmp.lt p8, p0 = 24, r8 + ;; + ld8 r8 = [r16], 16 +(p6) ld8 r9 = [r17], 16 + ;; +(p7) ld8 r10 = [r16] +(p8) ld8 r11 = [r17] + .restore sp + add sp = FRAME_SIZE, sp + br.ret.sptk.many b0 + ;; + +.Lld_hfa_float: + .body + .copy_state 1 + add r17 = 4, r16 + cmp.lt p6, p0 = 4, r8 + ;; + ldfs f8 = [r16], 8 +(p6) ldfs f9 = [r17], 8 + cmp.lt p7, p0 = 8, r8 + cmp.lt p8, p0 = 12, r8 + ;; +(p7) ldfs f10 = [r16], 8 +(p8) ldfs f11 = [r17], 8 + cmp.lt p9, p0 = 16, r8 + cmp.lt p10, p0 = 20, r8 + ;; +(p9) ldfs f12 = [r16], 8 +(p10) ldfs f13 = [r17], 8 + cmp.lt p6, p0 = 24, r8 + cmp.lt p7, p0 = 28, r8 + ;; +(p6) ldfs f14 = [r16] +(p7) ldfs f15 = [r17] + .restore sp + add sp = FRAME_SIZE, sp + br.ret.sptk.many b0 + ;; + +.Lld_hfa_double: + .body + .copy_state 1 + add r17 = 8, r16 + cmp.lt p6, p0 = 8, r8 + ;; + ldfd f8 = [r16], 16 +(p6) ldfd f9 = [r17], 16 + cmp.lt p7, p0 = 16, r8 + cmp.lt p8, p0 = 24, r8 + ;; +(p7) ldfd f10 = [r16], 16 +(p8) ldfd f11 = [r17], 16 + cmp.lt p9, p0 = 32, r8 + cmp.lt p10, p0 = 40, r8 + ;; +(p9) ldfd f12 = [r16], 16 +(p10) ldfd f13 = [r17], 16 + cmp.lt p6, p0 = 48, r8 + cmp.lt p7, p0 = 56, r8 + ;; +(p6) ldfd f14 = [r16] +(p7) ldfd f15 = [r17] + .restore sp + add sp = FRAME_SIZE, sp + br.ret.sptk.many b0 + ;; + +.Lld_hfa_ldouble: + .body + .copy_state 1 + add r17 = 16, r16 + cmp.lt p6, p0 = 16, r8 + ;; + ldfe f8 = [r16], 32 +(p6) ldfe f9 = [r17], 32 + cmp.lt p7, p0 = 32, r8 + cmp.lt p8, p0 = 48, r8 + ;; +(p7) ldfe f10 = [r16], 32 +(p8) ldfe f11 = [r17], 32 + cmp.lt p9, p0 = 64, r8 + cmp.lt p10, p0 = 80, r8 + ;; +(p9) ldfe f12 = [r16], 32 +(p10) ldfe f13 = [r17], 32 + cmp.lt p6, p0 = 96, r8 + cmp.lt p7, p0 = 112, r8 + ;; +(p6) ldfe f14 = [r16] +(p7) ldfe f15 = [r17] + .restore sp + add sp = FRAME_SIZE, sp + br.ret.sptk.many b0 + ;; + + .endp ffi_closure_unix + + .section .rodata + .align 8 +.Lst_table: + data8 @pcrel(.Lst_void) // FFI_TYPE_VOID + data8 @pcrel(.Lst_sint32) // FFI_TYPE_INT + data8 @pcrel(.Lst_float) // FFI_TYPE_FLOAT + data8 @pcrel(.Lst_double) // FFI_TYPE_DOUBLE + data8 @pcrel(.Lst_ldouble) // FFI_TYPE_LONGDOUBLE + data8 @pcrel(.Lst_uint8) // FFI_TYPE_UINT8 + data8 @pcrel(.Lst_sint8) // FFI_TYPE_SINT8 + data8 @pcrel(.Lst_uint16) // FFI_TYPE_UINT16 + data8 @pcrel(.Lst_sint16) // FFI_TYPE_SINT16 + data8 @pcrel(.Lst_uint32) // FFI_TYPE_UINT32 + data8 @pcrel(.Lst_sint32) // FFI_TYPE_SINT32 + data8 @pcrel(.Lst_int64) // FFI_TYPE_UINT64 + data8 @pcrel(.Lst_int64) // FFI_TYPE_SINT64 + data8 @pcrel(.Lst_void) // FFI_TYPE_STRUCT + data8 @pcrel(.Lst_int64) // FFI_TYPE_POINTER + data8 @pcrel(.Lst_void) // FFI_TYPE_COMPLEX (not implemented) + data8 @pcrel(.Lst_small_struct) // FFI_IA64_TYPE_SMALL_STRUCT + data8 @pcrel(.Lst_hfa_float) // FFI_IA64_TYPE_HFA_FLOAT + data8 @pcrel(.Lst_hfa_double) // FFI_IA64_TYPE_HFA_DOUBLE + data8 @pcrel(.Lst_hfa_ldouble) // FFI_IA64_TYPE_HFA_LDOUBLE + +.Lld_table: + data8 @pcrel(.Lld_void) // FFI_TYPE_VOID + data8 @pcrel(.Lld_int) // FFI_TYPE_INT + data8 @pcrel(.Lld_float) // FFI_TYPE_FLOAT + data8 @pcrel(.Lld_double) // FFI_TYPE_DOUBLE + data8 @pcrel(.Lld_ldouble) // FFI_TYPE_LONGDOUBLE + data8 @pcrel(.Lld_int) // FFI_TYPE_UINT8 + data8 @pcrel(.Lld_int) // FFI_TYPE_SINT8 + data8 @pcrel(.Lld_int) // FFI_TYPE_UINT16 + data8 @pcrel(.Lld_int) // FFI_TYPE_SINT16 + data8 @pcrel(.Lld_int) // FFI_TYPE_UINT32 + data8 @pcrel(.Lld_int) // FFI_TYPE_SINT32 + data8 @pcrel(.Lld_int) // FFI_TYPE_UINT64 + data8 @pcrel(.Lld_int) // FFI_TYPE_SINT64 + data8 @pcrel(.Lld_void) // FFI_TYPE_STRUCT + data8 @pcrel(.Lld_int) // FFI_TYPE_POINTER + data8 @pcrel(.Lld_void) // FFI_TYPE_COMPLEX (not implemented) + data8 @pcrel(.Lld_small_struct) // FFI_IA64_TYPE_SMALL_STRUCT + data8 @pcrel(.Lld_hfa_float) // FFI_IA64_TYPE_HFA_FLOAT + data8 @pcrel(.Lld_hfa_double) // FFI_IA64_TYPE_HFA_DOUBLE + data8 @pcrel(.Lld_hfa_ldouble) // FFI_IA64_TYPE_HFA_LDOUBLE + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/java_raw_api.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/java_raw_api.c new file mode 100644 index 0000000..114d3e4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/java_raw_api.c @@ -0,0 +1,374 @@ +/* ----------------------------------------------------------------------- + java_raw_api.c - Copyright (c) 1999, 2007, 2008 Red Hat, Inc. + + Cloned from raw_api.c + + Raw_api.c author: Kresten Krab Thorup + Java_raw_api.c author: Hans-J. Boehm + + $Id $ + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +/* This defines a Java- and 64-bit specific variant of the raw API. */ +/* It assumes that "raw" argument blocks look like Java stacks on a */ +/* 64-bit machine. Arguments that can be stored in a single stack */ +/* stack slots (longs, doubles) occupy 128 bits, but only the first */ +/* 64 bits are actually used. */ + +#include +#include +#include + +#if !defined(NO_JAVA_RAW_API) + +size_t +ffi_java_raw_size (ffi_cif *cif) +{ + size_t result = 0; + int i; + + ffi_type **at = cif->arg_types; + + for (i = cif->nargs-1; i >= 0; i--, at++) + { + switch((*at) -> type) { + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_DOUBLE: + result += 2 * FFI_SIZEOF_JAVA_RAW; + break; + case FFI_TYPE_STRUCT: + /* No structure parameters in Java. */ + abort(); + case FFI_TYPE_COMPLEX: + /* Not supported yet. */ + abort(); + default: + result += FFI_SIZEOF_JAVA_RAW; + } + } + + return result; +} + + +void +ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) +{ + unsigned i; + ffi_type **tp = cif->arg_types; + +#if WORDS_BIGENDIAN + + for (i = 0; i < cif->nargs; i++, tp++, args++) + { + switch ((*tp)->type) + { + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + *args = (void*) ((char*)(raw++) + 3); + break; + + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + *args = (void*) ((char*)(raw++) + 2); + break; + +#if FFI_SIZEOF_JAVA_RAW == 8 + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_DOUBLE: + *args = (void *)raw; + raw += 2; + break; +#endif + + case FFI_TYPE_POINTER: + *args = (void*) &(raw++)->ptr; + break; + + case FFI_TYPE_COMPLEX: + /* Not supported yet. */ + abort(); + + default: + *args = raw; + raw += + FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw); + } + } + +#else /* WORDS_BIGENDIAN */ + +#if !PDP + + /* then assume little endian */ + for (i = 0; i < cif->nargs; i++, tp++, args++) + { +#if FFI_SIZEOF_JAVA_RAW == 8 + switch((*tp)->type) { + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_DOUBLE: + *args = (void*) raw; + raw += 2; + break; + case FFI_TYPE_COMPLEX: + /* Not supported yet. */ + abort(); + default: + *args = (void*) raw++; + } +#else /* FFI_SIZEOF_JAVA_RAW != 8 */ + *args = (void*) raw; + raw += + FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw); +#endif /* FFI_SIZEOF_JAVA_RAW == 8 */ + } + +#else +#error "pdp endian not supported" +#endif /* ! PDP */ + +#endif /* WORDS_BIGENDIAN */ +} + +void +ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) +{ + unsigned i; + ffi_type **tp = cif->arg_types; + + for (i = 0; i < cif->nargs; i++, tp++, args++) + { + switch ((*tp)->type) + { + case FFI_TYPE_UINT8: +#if WORDS_BIGENDIAN + *(UINT32*)(raw++) = *(UINT8*) (*args); +#else + (raw++)->uint = *(UINT8*) (*args); +#endif + break; + + case FFI_TYPE_SINT8: +#if WORDS_BIGENDIAN + *(SINT32*)(raw++) = *(SINT8*) (*args); +#else + (raw++)->sint = *(SINT8*) (*args); +#endif + break; + + case FFI_TYPE_UINT16: +#if WORDS_BIGENDIAN + *(UINT32*)(raw++) = *(UINT16*) (*args); +#else + (raw++)->uint = *(UINT16*) (*args); +#endif + break; + + case FFI_TYPE_SINT16: +#if WORDS_BIGENDIAN + *(SINT32*)(raw++) = *(SINT16*) (*args); +#else + (raw++)->sint = *(SINT16*) (*args); +#endif + break; + + case FFI_TYPE_UINT32: +#if WORDS_BIGENDIAN + *(UINT32*)(raw++) = *(UINT32*) (*args); +#else + (raw++)->uint = *(UINT32*) (*args); +#endif + break; + + case FFI_TYPE_SINT32: +#if WORDS_BIGENDIAN + *(SINT32*)(raw++) = *(SINT32*) (*args); +#else + (raw++)->sint = *(SINT32*) (*args); +#endif + break; + + case FFI_TYPE_FLOAT: + (raw++)->flt = *(FLOAT32*) (*args); + break; + +#if FFI_SIZEOF_JAVA_RAW == 8 + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_DOUBLE: + raw->uint = *(UINT64*) (*args); + raw += 2; + break; +#endif + + case FFI_TYPE_POINTER: + (raw++)->ptr = **(void***) args; + break; + + default: +#if FFI_SIZEOF_JAVA_RAW == 8 + FFI_ASSERT(0); /* Should have covered all cases */ +#else + memcpy ((void*) raw->data, (void*)*args, (*tp)->size); + raw += + FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw); +#endif + } + } +} + +#if !FFI_NATIVE_RAW_API + +static void +ffi_java_rvalue_to_raw (ffi_cif *cif, void *rvalue) +{ +#if WORDS_BIGENDIAN && FFI_SIZEOF_ARG == 8 + switch (cif->rtype->type) + { + case FFI_TYPE_UINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_UINT32: + *(UINT64 *)rvalue <<= 32; + break; + + case FFI_TYPE_SINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_SINT32: + case FFI_TYPE_INT: +#if FFI_SIZEOF_JAVA_RAW == 4 + case FFI_TYPE_POINTER: +#endif + *(SINT64 *)rvalue <<= 32; + break; + + case FFI_TYPE_COMPLEX: + /* Not supported yet. */ + abort(); + + default: + break; + } +#endif +} + +static void +ffi_java_raw_to_rvalue (ffi_cif *cif, void *rvalue) +{ +#if WORDS_BIGENDIAN && FFI_SIZEOF_ARG == 8 + switch (cif->rtype->type) + { + case FFI_TYPE_UINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_UINT32: + *(UINT64 *)rvalue >>= 32; + break; + + case FFI_TYPE_SINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_SINT32: + case FFI_TYPE_INT: + *(SINT64 *)rvalue >>= 32; + break; + + case FFI_TYPE_COMPLEX: + /* Not supported yet. */ + abort(); + + default: + break; + } +#endif +} + +/* This is a generic definition of ffi_raw_call, to be used if the + * native system does not provide a machine-specific implementation. + * Having this, allows code to be written for the raw API, without + * the need for system-specific code to handle input in that format; + * these following couple of functions will handle the translation forth + * and back automatically. */ + +void ffi_java_raw_call (ffi_cif *cif, void (*fn)(void), void *rvalue, + ffi_java_raw *raw) +{ + void **avalue = (void**) alloca (cif->nargs * sizeof (void*)); + ffi_java_raw_to_ptrarray (cif, raw, avalue); + ffi_call (cif, fn, rvalue, avalue); + ffi_java_rvalue_to_raw (cif, rvalue); +} + +#if FFI_CLOSURES /* base system provides closures */ + +static void +ffi_java_translate_args (ffi_cif *cif, void *rvalue, + void **avalue, void *user_data) +{ + ffi_java_raw *raw = (ffi_java_raw*)alloca (ffi_java_raw_size (cif)); + ffi_raw_closure *cl = (ffi_raw_closure*)user_data; + + ffi_java_ptrarray_to_raw (cif, avalue, raw); + (*cl->fun) (cif, rvalue, (ffi_raw*)raw, cl->user_data); + ffi_java_raw_to_rvalue (cif, rvalue); +} + +ffi_status +ffi_prep_java_raw_closure_loc (ffi_java_raw_closure* cl, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), + void *user_data, + void *codeloc) +{ + ffi_status status; + + status = ffi_prep_closure_loc ((ffi_closure*) cl, + cif, + &ffi_java_translate_args, + codeloc, + codeloc); + if (status == FFI_OK) + { + cl->fun = fun; + cl->user_data = user_data; + } + + return status; +} + +/* Again, here is the generic version of ffi_prep_raw_closure, which + * will install an intermediate "hub" for translation of arguments from + * the pointer-array format, to the raw format */ + +ffi_status +ffi_prep_java_raw_closure (ffi_java_raw_closure* cl, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), + void *user_data) +{ + return ffi_prep_java_raw_closure_loc (cl, cif, fun, user_data, cl); +} + +#endif /* FFI_CLOSURES */ +#endif /* !FFI_NATIVE_RAW_API */ +#endif /* !NO_JAVA_RAW_API */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/asm.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/asm.h new file mode 100644 index 0000000..4edba41 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/asm.h @@ -0,0 +1,5 @@ +/* args are passed on registers from r0 up to r11 => 12*8 bytes */ +#define REG_ARGS_SIZE (12*8) +#define KVX_REGISTER_SIZE (8) +#define KVX_ABI_SLOT_SIZE (KVX_REGISTER_SIZE) +#define KVX_ABI_MAX_AGGREGATE_IN_REG_SIZE (4*KVX_ABI_SLOT_SIZE) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/ffi.c new file mode 100644 index 0000000..58f6aef --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/ffi.c @@ -0,0 +1,273 @@ +/* Copyright (c) 2020 Kalray + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + +#if defined(__kvx__) +#include +#include +#include +#include +#include +#include "ffi_common.h" +#include "asm.h" + +#define ALIGN(x, a) ALIGN_MASK(x, (typeof(x))(a) - 1) +#define ALIGN_MASK(x, mask) (((x) + (mask)) & ~(mask)) +#define KVX_ABI_STACK_ALIGNMENT (32) +#define KVX_ABI_STACK_ARG_ALIGNMENT (8) +#define max(a,b) ((a) > (b) ? (a) : (b)) + +#ifdef FFI_DEBUG +#define DEBUG_PRINT(...) do{ fprintf( stderr, __VA_ARGS__ ); } while(0) +#else +#define DEBUG_PRINT(...) +#endif + +struct ret_value { + unsigned long int r0; + unsigned long int r1; + unsigned long int r2; + unsigned long int r3; +}; + +extern struct ret_value ffi_call_SYSV(unsigned total_size, + unsigned size, + extended_cif *ecif, + unsigned *rvalue_addr, + void *fn, + unsigned int_ext_method); + +/* Perform machine dependent cif processing */ +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + cif->flags = cif->rtype->size; + return FFI_OK; +} + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments */ + +void *ffi_prep_args(char *stack, unsigned int arg_slots_size, extended_cif *ecif) +{ + char *stacktemp = stack; + char *current_arg_passed_by_value = stack + arg_slots_size; + int i, s; + ffi_type **arg; + int count = 0; + ffi_cif *cif = ecif->cif; + void **argv = ecif->avalue; + + arg = cif->arg_types; + + DEBUG_PRINT("stack: %p\n", stack); + DEBUG_PRINT("arg_slots_size: %u\n", arg_slots_size); + DEBUG_PRINT("current_arg_passed_by_value: %p\n", current_arg_passed_by_value); + DEBUG_PRINT("ecif: %p\n", ecif); + DEBUG_PRINT("ecif->avalue: %p\n", ecif->avalue); + + for (i = 0; i < cif->nargs; i++) { + + s = KVX_ABI_SLOT_SIZE; + switch((*arg)->type) { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_POINTER: + DEBUG_PRINT("INT64/32/16/8/FLOAT/DOUBLE or POINTER @%p\n", stack); + *(uint64_t *) stack = *(uint64_t *)(* argv); + break; + + case FFI_TYPE_COMPLEX: + if ((*arg)->size == 8) + *(_Complex float *) stack = *(_Complex float *)(* argv); + else if ((*arg)->size == 16) { + *(_Complex double *) stack = *(_Complex double *)(* argv); + s = 16; + } else + abort(); + break; + case FFI_TYPE_STRUCT: { + char *value; + unsigned int written_size = 0; + DEBUG_PRINT("struct by value @%p\n", stack); + if ((*arg)->size > KVX_ABI_MAX_AGGREGATE_IN_REG_SIZE) { + DEBUG_PRINT("big struct\n"); + *(uint64_t *) stack = (uintptr_t)current_arg_passed_by_value; + value = current_arg_passed_by_value; + current_arg_passed_by_value += (*arg)->size; + written_size = KVX_ABI_SLOT_SIZE; + } else { + value = stack; + written_size = (*arg)->size; + } + memcpy(value, *argv, (*arg)->size); + s = ALIGN(written_size, KVX_ABI_STACK_ARG_ALIGNMENT); + break; + } + default: + printf("Error: unsupported arg type %d\n", (*arg)->type); + abort(); + break; + + } + stack += s; + count += s; + argv++; + arg++; + } +#ifdef FFI_DEBUG + FFI_ASSERT(((intptr_t)(stacktemp + REG_ARGS_SIZE) & (KVX_ABI_STACK_ALIGNMENT-1)) == 0); +#endif + return stacktemp + REG_ARGS_SIZE; +} + +/* Perform machine dependent cif processing when we have a variadic function */ + +ffi_status ffi_prep_cif_machdep_var(ffi_cif *cif, unsigned int nfixedargs, + unsigned int ntotalargs) +{ + cif->flags = cif->rtype->size; + return FFI_OK; +} + +static unsigned long handle_small_int_ext(kvx_intext_method *int_ext_method, + const ffi_type *rtype) +{ + switch (rtype->type) { + case FFI_TYPE_SINT8: + *int_ext_method = KVX_RET_SXBD; + return KVX_REGISTER_SIZE; + + case FFI_TYPE_SINT16: + *int_ext_method = KVX_RET_SXHD; + return KVX_REGISTER_SIZE; + + case FFI_TYPE_SINT32: + *int_ext_method = KVX_RET_SXWD; + return KVX_REGISTER_SIZE; + + case FFI_TYPE_UINT8: + *int_ext_method = KVX_RET_ZXBD; + return KVX_REGISTER_SIZE; + + case FFI_TYPE_UINT16: + *int_ext_method = KVX_RET_ZXHD; + return KVX_REGISTER_SIZE; + + case FFI_TYPE_UINT32: + *int_ext_method = KVX_RET_ZXWD; + return KVX_REGISTER_SIZE; + + default: + *int_ext_method = KVX_RET_NONE; + return rtype->size; + } +} + +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + int i; + unsigned long int slot_fitting_args_size = 0; + unsigned long int total_size = 0; + unsigned long int big_struct_size = 0; + kvx_intext_method int_extension_method; + ffi_type **arg; + struct ret_value local_rvalue = {0}; + size_t wb_size; + + + /* Calculate size to allocate on stack */ + for (i = 0, arg = cif->arg_types; i < cif->nargs; i++, arg++) { + DEBUG_PRINT("argument %d, type %d, size %lu\n", i, (*arg)->type, (*arg)->size); + if (((*arg)->type == FFI_TYPE_STRUCT) || ((*arg)->type == FFI_TYPE_COMPLEX)) { + if ((*arg)->size <= KVX_ABI_MAX_AGGREGATE_IN_REG_SIZE) { + slot_fitting_args_size += ALIGN((*arg)->size, KVX_ABI_SLOT_SIZE); + } else { + slot_fitting_args_size += KVX_ABI_SLOT_SIZE; /* aggregate passed by reference */ + big_struct_size += ALIGN((*arg)->size, KVX_ABI_SLOT_SIZE); + } + } else if ((*arg)->size <= KVX_ABI_SLOT_SIZE) { + slot_fitting_args_size += KVX_ABI_SLOT_SIZE; + } else { + printf("Error: unsupported arg size %ld arg type %d\n", (*arg)->size, (*arg)->type); + abort(); /* should never happen? */ + } + } + + extended_cif ecif; + ecif.cif = cif; + ecif.avalue = avalue; + ecif.rvalue = rvalue; + + /* This implementation allocates anyway for all register based args */ + slot_fitting_args_size = max(slot_fitting_args_size, REG_ARGS_SIZE); + total_size = slot_fitting_args_size + big_struct_size; + total_size = ALIGN(total_size, KVX_ABI_STACK_ALIGNMENT); + + /* wb_size: write back size, the size we will need to write back to user + * provided buffer. In theory it should always be cif->flags which is + * cif->rtype->size. But libffi API mandates that for integral types + * of size <= system register size, then we *MUST* write back + * the size of system register size. + * in our case, if size <= 8 bytes we must write back 8 bytes. + * floats, complex and structs are not affected, only integrals. + */ + wb_size = handle_small_int_ext(&int_extension_method, cif->rtype); + + switch (cif->abi) { + case FFI_SYSV: + DEBUG_PRINT("total_size: %lu\n", total_size); + DEBUG_PRINT("slot fitting args size: %lu\n", slot_fitting_args_size); + DEBUG_PRINT("rvalue: %p\n", rvalue); + DEBUG_PRINT("fn: %p\n", fn); + DEBUG_PRINT("rsize: %u\n", cif->flags); + DEBUG_PRINT("wb_size: %u\n", wb_size); + DEBUG_PRINT("int_extension_method: %u\n", int_extension_method); + local_rvalue = ffi_call_SYSV(total_size, slot_fitting_args_size, + &ecif, rvalue, fn, int_extension_method); + if ((cif->flags <= KVX_ABI_MAX_AGGREGATE_IN_REG_SIZE) + && (cif->rtype->type != FFI_TYPE_VOID)) + memcpy(rvalue, &local_rvalue, wb_size); + break; + default: + abort(); + break; + } +} + +/* Closures not supported yet */ +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + return FFI_BAD_ABI; +} + +#endif /* (__kvx__) */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/ffitarget.h new file mode 100644 index 0000000..8df8735 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/ffitarget.h @@ -0,0 +1,75 @@ +/* ----------------------------------------------------------------------- + ffitarget.h - Copyright (c) 2020 Kalray + + KVX Target configuration macros + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +/* ---- System specific configurations ----------------------------------- */ + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; + +/* Those values are set depending on return type + * they are used in the assembly code in sysv.S + */ +typedef enum kvx_intext_method { + KVX_RET_NONE = 0, + KVX_RET_SXBD = 1, + KVX_RET_SXHD = 2, + KVX_RET_SXWD = 3, + KVX_RET_ZXBD = 4, + KVX_RET_ZXHD = 5, + KVX_RET_ZXWD = 6 +} kvx_intext_method; + +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +/* This is only to allow Python to compile + * but closures are not supported yet + */ +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 0 + +#define FFI_NATIVE_RAW_API 0 +#define FFI_TARGET_SPECIFIC_VARIADIC 1 +#define FFI_TARGET_HAS_COMPLEX_TYPE + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/sysv.S new file mode 100644 index 0000000..952afc7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/kvx/sysv.S @@ -0,0 +1,127 @@ +/* Copyright (c) 2020 Kalray + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + +#if defined(__kvx__) +#define LIBFFI_ASM +#include +#include +#include +#include + +.text +.global ffi_call_SYSV +.type ffi_call_SYSV, @function +.type ffi_prep_args, @function +.align 8 + +/* ffi_call_SYSV + + r0: total size to allocate on stack + r1: size of arg slots + r2: extended cif structure, DO NOT REMOVE: it is used by ffi_prep_args() + r3: return value address + r4: function to call + r5: integer sign extension method to be used +*/ +ffi_call_SYSV: + addd $r12 = $r12, -64 + so (-32)[$r12] = $r20r21r22r23 + ;; + sd (0)[$r12] = $r24 + ;; + get $r23 = $ra + copyd $r20 = $r12 + sbfd $r12 = $r0, $r12 + ;; + copyd $r0 = $r12 + copyd $r21 = $r3 + copyd $r22 = $r4 + copyd $r24 = $r5 + call ffi_prep_args + ;; + lo $r8r9r10r11 = (64)[$r12] + ;; + lo $r4r5r6r7 = (32)[$r12] + ;; + lo $r0r1r2r3 = (0)[$r12] + copyd $r12 = $r0 + /* $r15 is the register used by the ABI to return big (>32 bytes) + * structs by value. + * It is also referred to as the "struct register" in the ABI. + */ + copyd $r15 = $r21 + icall $r22 + ;; + pcrel $r4 = @pcrel(.Ltable) + cb.deqz $r24 ? .Lend + ;; + addx8d $r24 = $r24, $r4 + ;; + igoto $r24 + ;; +.Ltable: +0: /* we should never arrive here */ + goto .Lerror + nop + ;; +1: /* Sign extend byte to double */ + sxbd $r0 = $r0 + goto .Lend + ;; +2: /* Sign extend half to double */ + sxhd $r0 = $r0 + goto .Lend + ;; +3: /* Sign extend word to double */ + sxwd $r0 = $r0 + goto .Lend + ;; +4: /* Zero extend byte to double */ + zxbd $r0 = $r0 + goto .Lend + ;; +5: /* Zero extend half to double */ + zxhd $r0 = $r0 + goto .Lend + ;; +6: /* Zero extend word to double */ + zxwd $r0 = $r0 + /* Fallthrough to .Lend */ + ;; +.Lend: + ld $r24 = (0)[$r12] + ;; + set $ra = $r23 + lo $r20r21r22r23 = (32)[$r20] + addd $r12 = $r20, 64 + ;; + ret + ;; +.Lerror: + errop + ;; + +#endif /* __kvx__ */ + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",%progbits +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m32r/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m32r/ffi.c new file mode 100644 index 0000000..ab8fc4e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m32r/ffi.c @@ -0,0 +1,232 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2004 Renesas Technology + Copyright (c) 2008 Red Hat, Inc. + + M32R Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL RENESAS TECHNOLOGY BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include + +/* ffi_prep_args is called by the assembly routine once stack + space has been allocated for the function's arguments. */ + +void ffi_prep_args(char *stack, extended_cif *ecif) +{ + unsigned int i; + int tmp; + unsigned int avn; + void **p_argv; + char *argp; + ffi_type **p_arg; + + tmp = 0; + argp = stack; + + if (ecif->cif->rtype->type == FFI_TYPE_STRUCT && ecif->cif->rtype->size > 8) + { + *(void **) argp = ecif->rvalue; + argp += 4; + } + + avn = ecif->cif->nargs; + p_argv = ecif->avalue; + + for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; + (i != 0) && (avn != 0); + i--, p_arg++) + { + size_t z; + + /* Align if necessary. */ + if (((*p_arg)->alignment - 1) & (unsigned) argp) + argp = (char *) FFI_ALIGN (argp, (*p_arg)->alignment); + + if (avn != 0) + { + avn--; + z = (*p_arg)->size; + if (z < sizeof (int)) + { + z = sizeof (int); + + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); + break; + + case FFI_TYPE_STRUCT: + z = (*p_arg)->size; + if ((*p_arg)->alignment != 1) + memcpy (argp, *p_argv, z); + else + memcpy (argp + 4 - z, *p_argv, z); + z = sizeof (int); + break; + + default: + FFI_ASSERT(0); + } + } + else if (z == sizeof (int)) + { + *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); + } + else + { + if ((*p_arg)->type == FFI_TYPE_STRUCT) + { + if (z > 8) + { + *(unsigned int *) argp = (unsigned int)(void *)(* p_argv); + z = sizeof(void *); + } + else + { + memcpy(argp, *p_argv, z); + z = 8; + } + } + else + { + /* Double or long long 64bit. */ + memcpy (argp, *p_argv, z); + } + } + p_argv++; + argp += z; + } + } + + return; +} + +/* Perform machine dependent cif processing. */ +ffi_status +ffi_prep_cif_machdep(ffi_cif *cif) +{ + /* Set the return type flag. */ + switch (cif->rtype->type) + { + case FFI_TYPE_VOID: + cif->flags = (unsigned) cif->rtype->type; + break; + + case FFI_TYPE_STRUCT: + if (cif->rtype->size <= 4) + cif->flags = FFI_TYPE_INT; + + else if (cif->rtype->size <= 8) + cif->flags = FFI_TYPE_DOUBLE; + + else + cif->flags = (unsigned) cif->rtype->type; + break; + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_DOUBLE: + cif->flags = FFI_TYPE_DOUBLE; + break; + + case FFI_TYPE_FLOAT: + default: + cif->flags = FFI_TYPE_INT; + break; + } + + return FFI_OK; +} + +extern void ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *, + unsigned, unsigned, unsigned *, void (*fn)(void)); + +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have + a return value address then we need to make one. */ + if ((rvalue == NULL) && + (cif->rtype->type == FFI_TYPE_STRUCT)) + { + ecif.rvalue = alloca (cif->rtype->size); + } + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_SYSV: + ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, + cif->flags, ecif.rvalue, fn); + if (cif->rtype->type == FFI_TYPE_STRUCT) + { + int size = cif->rtype->size; + int align = cif->rtype->alignment; + + if (size < 4) + { + if (align == 1) + *(unsigned long *)(ecif.rvalue) <<= (4 - size) * 8; + } + else if (4 < size && size < 8) + { + if (align == 1) + { + memcpy (ecif.rvalue, ecif.rvalue + 8-size, size); + } + else if (align == 2) + { + if (size & 1) + size += 1; + + if (size != 8) + memcpy (ecif.rvalue, ecif.rvalue + 8-size, size); + } + } + } + break; + + default: + FFI_ASSERT(0); + break; + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m32r/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m32r/ffitarget.h new file mode 100644 index 0000000..6c34801 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m32r/ffitarget.h @@ -0,0 +1,53 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 2004 Renesas Technology. + Target configuration macros for M32R. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL RENESAS TECHNOLOGY BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +/* ---- Generic type definitions ----------------------------------------- */ + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi + { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV + } ffi_abi; +#endif + +#define FFI_CLOSURES 0 +#define FFI_TRAMPOLINE_SIZE 24 +#define FFI_NATIVE_RAW_API 0 + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m32r/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m32r/sysv.S new file mode 100644 index 0000000..06b75c2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m32r/sysv.S @@ -0,0 +1,121 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2004 Renesas Technology + + M32R Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL RENESAS TECHNOLOGY BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include +#ifdef HAVE_MACHINE_ASM_H +#include +#else +/* XXX these lose for some platforms, I'm sure. */ +#define CNAME(x) x +#define ENTRY(x) .globl CNAME(x)! .type CNAME(x),%function! CNAME(x): +#endif + +.text + + /* R0: ffi_prep_args */ + /* R1: &ecif */ + /* R2: cif->bytes */ + /* R3: fig->flags */ + /* sp+0: ecif.rvalue */ + /* sp+4: fn */ + + /* This assumes we are using gas. */ +ENTRY(ffi_call_SYSV) + /* Save registers. */ + push fp + push lr + push r3 + push r2 + push r1 + push r0 + mv fp, sp + + /* Make room for all of the new args. */ + sub sp, r2 + + /* Place all of the ffi_prep_args in position. */ + mv lr, r0 + mv r0, sp + /* R1 already set. */ + + /* And call. */ + jl lr + + /* Move first 4 parameters in registers... */ + ld r0, @(0,sp) + ld r1, @(4,sp) + ld r2, @(8,sp) + ld r3, @(12,sp) + + /* ...and adjust the stack. */ + ld lr, @(8,fp) + cmpi lr, #16 + bc adjust_stack + ldi lr, #16 +adjust_stack: + add sp, lr + + /* Call the function. */ + ld lr, @(28,fp) + jl lr + + /* Remove the space we pushed for the args. */ + mv sp, fp + + /* Load R2 with the pointer to storage for the return value. */ + ld r2, @(24,sp) + + /* Load R3 with the return type code. */ + ld r3, @(12,sp) + + /* If the return value pointer is NULL, assume no return value. */ + beqz r2, epilogue + + /* Return INT. */ + ldi r4, #FFI_TYPE_INT + bne r3, r4, return_double + st r0, @r2 + bra epilogue + +return_double: + /* Return DOUBLE or LONGDOUBLE. */ + ldi r4, #FFI_TYPE_DOUBLE + bne r3, r4, epilogue + st r0, @r2 + st r1, @(4,r2) + +epilogue: + pop r0 + pop r1 + pop r2 + pop r3 + pop lr + pop fp + jmp lr + +.ffi_call_SYSV_end: + .size CNAME(ffi_call_SYSV),.ffi_call_SYSV_end-CNAME(ffi_call_SYSV) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m68k/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m68k/ffi.c new file mode 100644 index 0000000..0330184 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m68k/ffi.c @@ -0,0 +1,362 @@ +/* ----------------------------------------------------------------------- + ffi.c + + m68k Foreign Function Interface + ----------------------------------------------------------------------- */ + +#include +#include + +#include +#include +#ifdef __rtems__ +void rtems_cache_flush_multiple_data_lines( const void *, size_t ); +#else +#include +#ifdef __MINT__ +#include +#include +#else +#include +#endif +#endif + +void ffi_call_SYSV (extended_cif *, + unsigned, unsigned, + void *, void (*fn) ()); +void *ffi_prep_args (void *stack, extended_cif *ecif); +void ffi_closure_SYSV (ffi_closure *); +void ffi_closure_struct_SYSV (ffi_closure *); +unsigned int ffi_closure_SYSV_inner (ffi_closure *closure, + void *resp, void *args); + +/* ffi_prep_args is called by the assembly routine once stack space has + been allocated for the function's arguments. */ + +void * +ffi_prep_args (void *stack, extended_cif *ecif) +{ + unsigned int i; + void **p_argv; + char *argp; + ffi_type **p_arg; + void *struct_value_ptr; + + argp = stack; + + if ( +#ifdef __MINT__ + (ecif->cif->rtype->type == FFI_TYPE_LONGDOUBLE) || +#endif + (((ecif->cif->rtype->type == FFI_TYPE_STRUCT) + && !ecif->cif->flags))) + struct_value_ptr = ecif->rvalue; + else + struct_value_ptr = NULL; + + p_argv = ecif->avalue; + + for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; + i != 0; + i--, p_arg++) + { + size_t z = (*p_arg)->size; + int type = (*p_arg)->type; + + if (z < sizeof (int)) + { + switch (type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int) *(SINT8 *) *p_argv; + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int) *(UINT8 *) *p_argv; + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int) *(SINT16 *) *p_argv; + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int) *(UINT16 *) *p_argv; + break; + + case FFI_TYPE_STRUCT: +#ifdef __MINT__ + if (z == 1 || z == 2) + memcpy (argp + 2, *p_argv, z); + else + memcpy (argp, *p_argv, z); +#else + memcpy (argp + sizeof (int) - z, *p_argv, z); +#endif + break; + + default: + FFI_ASSERT (0); + } + z = sizeof (int); + } + else + { + memcpy (argp, *p_argv, z); + + /* Align if necessary. */ + if ((sizeof(int) - 1) & z) + z = FFI_ALIGN(z, sizeof(int)); + } + + p_argv++; + argp += z; + } + + return struct_value_ptr; +} + +#define CIF_FLAGS_INT 1 +#define CIF_FLAGS_DINT 2 +#define CIF_FLAGS_FLOAT 4 +#define CIF_FLAGS_DOUBLE 8 +#define CIF_FLAGS_LDOUBLE 16 +#define CIF_FLAGS_POINTER 32 +#define CIF_FLAGS_STRUCT1 64 +#define CIF_FLAGS_STRUCT2 128 +#define CIF_FLAGS_SINT8 256 +#define CIF_FLAGS_SINT16 512 + +/* Perform machine dependent cif processing */ +ffi_status +ffi_prep_cif_machdep (ffi_cif *cif) +{ + /* Set the return type flag */ + switch (cif->rtype->type) + { + case FFI_TYPE_VOID: + cif->flags = 0; + break; + + case FFI_TYPE_STRUCT: + if (cif->rtype->elements[0]->type == FFI_TYPE_STRUCT && + cif->rtype->elements[1]) + { + cif->flags = 0; + break; + } + + switch (cif->rtype->size) + { + case 1: +#ifdef __MINT__ + cif->flags = CIF_FLAGS_STRUCT2; +#else + cif->flags = CIF_FLAGS_STRUCT1; +#endif + break; + case 2: + cif->flags = CIF_FLAGS_STRUCT2; + break; +#ifdef __MINT__ + case 3: +#endif + case 4: + cif->flags = CIF_FLAGS_INT; + break; +#ifdef __MINT__ + case 7: +#endif + case 8: + cif->flags = CIF_FLAGS_DINT; + break; + default: + cif->flags = 0; + break; + } + break; + + case FFI_TYPE_FLOAT: + cif->flags = CIF_FLAGS_FLOAT; + break; + + case FFI_TYPE_DOUBLE: + cif->flags = CIF_FLAGS_DOUBLE; + break; + +#if (FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE) + case FFI_TYPE_LONGDOUBLE: +#ifdef __MINT__ + cif->flags = 0; +#else + cif->flags = CIF_FLAGS_LDOUBLE; +#endif + break; +#endif + + case FFI_TYPE_POINTER: + cif->flags = CIF_FLAGS_POINTER; + break; + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + cif->flags = CIF_FLAGS_DINT; + break; + + case FFI_TYPE_SINT16: + cif->flags = CIF_FLAGS_SINT16; + break; + + case FFI_TYPE_SINT8: + cif->flags = CIF_FLAGS_SINT8; + break; + + default: + cif->flags = CIF_FLAGS_INT; + break; + } + + return FFI_OK; +} + +void +ffi_call (ffi_cif *cif, void (*fn) (), void *rvalue, void **avalue) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return value + address then we need to make one. */ + + if (rvalue == NULL + && cif->rtype->type == FFI_TYPE_STRUCT + && cif->rtype->size > 8) + ecif.rvalue = alloca (cif->rtype->size); + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_SYSV: + ffi_call_SYSV (&ecif, cif->bytes, cif->flags, + ecif.rvalue, fn); + break; + + default: + FFI_ASSERT (0); + break; + } +} + +static void +ffi_prep_incoming_args_SYSV (char *stack, void **avalue, ffi_cif *cif) +{ + unsigned int i; + void **p_argv; + char *argp; + ffi_type **p_arg; + + argp = stack; + p_argv = avalue; + + for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) + { + size_t z; + + z = (*p_arg)->size; +#ifdef __MINT__ + if (cif->flags && + cif->rtype->type == FFI_TYPE_STRUCT && + (z == 1 || z == 2)) + { + *p_argv = (void *) (argp + 2); + + z = 4; + } + else + if (cif->flags && + cif->rtype->type == FFI_TYPE_STRUCT && + (z == 3 || z == 4)) + { + *p_argv = (void *) (argp); + + z = 4; + } + else +#endif + if (z <= 4) + { + *p_argv = (void *) (argp + 4 - z); + + z = 4; + } + else + { + *p_argv = (void *) argp; + + /* Align if necessary */ + if ((sizeof(int) - 1) & z) + z = FFI_ALIGN(z, sizeof(int)); + } + + p_argv++; + argp += z; + } +} + +unsigned int +ffi_closure_SYSV_inner (ffi_closure *closure, void *resp, void *args) +{ + ffi_cif *cif; + void **arg_area; + + cif = closure->cif; + arg_area = (void**) alloca (cif->nargs * sizeof (void *)); + + ffi_prep_incoming_args_SYSV(args, arg_area, cif); + + (closure->fun) (cif, resp, arg_area, closure->user_data); + + return cif->flags; +} + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + *(unsigned short *)closure->tramp = 0x207c; + *(void **)(closure->tramp + 2) = codeloc; + *(unsigned short *)(closure->tramp + 6) = 0x4ef9; + + if ( +#ifdef __MINT__ + (cif->rtype->type == FFI_TYPE_LONGDOUBLE) || +#endif + (((cif->rtype->type == FFI_TYPE_STRUCT) + && !cif->flags))) + *(void **)(closure->tramp + 8) = ffi_closure_struct_SYSV; + else + *(void **)(closure->tramp + 8) = ffi_closure_SYSV; + +#ifdef __rtems__ + rtems_cache_flush_multiple_data_lines( codeloc, FFI_TRAMPOLINE_SIZE ); +#elif defined(__MINT__) + Ssystem(S_FLUSHCACHE, codeloc, FFI_TRAMPOLINE_SIZE); +#else + syscall(SYS_cacheflush, codeloc, FLUSH_SCOPE_LINE, + FLUSH_CACHE_BOTH, FFI_TRAMPOLINE_SIZE); +#endif + + closure->cif = cif; + closure->user_data = user_data; + closure->fun = fun; + + return FFI_OK; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m68k/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m68k/ffitarget.h new file mode 100644 index 0000000..e81dde2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m68k/ffitarget.h @@ -0,0 +1,54 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 1996-2003 Red Hat, Inc. + Target configuration macros for Motorola 68K. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 16 +#define FFI_NATIVE_RAW_API 0 + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m68k/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m68k/sysv.S new file mode 100644 index 0000000..ea40f11 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m68k/sysv.S @@ -0,0 +1,357 @@ +/* ----------------------------------------------------------------------- + + sysv.S - Copyright (c) 2012 Alan Hourihane + Copyright (c) 1998, 2012 Andreas Schwab + Copyright (c) 2008 Red Hat, Inc. + Copyright (c) 2012, 2016 Thorsten Glaser + + m68k Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + +#ifdef HAVE_AS_CFI_PSEUDO_OP +#define CFI_STARTPROC() .cfi_startproc +#define CFI_OFFSET(reg,off) .cfi_offset reg,off +#define CFI_DEF_CFA(reg,off) .cfi_def_cfa reg,off +#define CFI_ENDPROC() .cfi_endproc +#else +#define CFI_STARTPROC() +#define CFI_OFFSET(reg,off) +#define CFI_DEF_CFA(reg,off) +#define CFI_ENDPROC() +#endif + +#ifdef __MINT__ +#define CALLFUNC(funcname) _ ## funcname +#else +#define CALLFUNC(funcname) funcname +#endif + + .text + + .globl CALLFUNC(ffi_call_SYSV) + .type CALLFUNC(ffi_call_SYSV),@function + .align 4 + +CALLFUNC(ffi_call_SYSV): + CFI_STARTPROC() + link %fp,#0 + CFI_OFFSET(14,-8) + CFI_DEF_CFA(14,8) + move.l %d2,-(%sp) + CFI_OFFSET(2,-12) + + | Make room for all of the new args. + sub.l 12(%fp),%sp + + | Call ffi_prep_args + move.l 8(%fp),-(%sp) + pea 4(%sp) +#if !defined __PIC__ + jsr CALLFUNC(ffi_prep_args) +#elif defined(__uClinux__) && defined(__ID_SHARED_LIBRARY__) + move.l _current_shared_library_a5_offset_(%a5),%a0 + move.l CALLFUNC(ffi_prep_args@GOT)(%a0),%a0 + jsr (%a0) +#elif defined(__mcoldfire__) && !defined(__mcfisab__) && !defined(__mcfisac__) + move.l #_GLOBAL_OFFSET_TABLE_@GOTPC,%a0 + lea (-6,%pc,%a0),%a0 + move.l CALLFUNC(ffi_prep_args@GOT)(%a0),%a0 + jsr (%a0) +#else + bsr.l CALLFUNC(ffi_prep_args@PLTPC) +#endif + addq.l #8,%sp + + | Pass pointer to struct value, if any +#ifdef __MINT__ + move.l %d0,%a1 +#else + move.l %a0,%a1 +#endif + + | Call the function + move.l 24(%fp),%a0 + jsr (%a0) + + | Remove the space we pushed for the args + add.l 12(%fp),%sp + + | Load the pointer to storage for the return value + move.l 20(%fp),%a1 + + | Load the return type code + move.l 16(%fp),%d2 + + | If the return value pointer is NULL, assume no return value. + | NOTE: On the mc68000, tst on an address register is not supported. +#if !defined(__mc68020__) && !defined(__mc68030__) && !defined(__mc68040__) && !defined(__mc68060__) && !defined(__mcoldfire__) + cmp.w #0, %a1 +#else + tst.l %a1 +#endif + jbeq noretval + + btst #0,%d2 + jbeq retlongint + move.l %d0,(%a1) + jbra epilogue + +retlongint: + btst #1,%d2 + jbeq retfloat + move.l %d0,(%a1) + move.l %d1,4(%a1) + jbra epilogue + +retfloat: + btst #2,%d2 + jbeq retdouble +#if defined(__MC68881__) || defined(__HAVE_68881__) + fmove.s %fp0,(%a1) +#else + move.l %d0,(%a1) +#endif + jbra epilogue + +retdouble: + btst #3,%d2 + jbeq retlongdouble +#if defined(__MC68881__) || defined(__HAVE_68881__) + fmove.d %fp0,(%a1) +#else + move.l %d0,(%a1)+ + move.l %d1,(%a1) +#endif + jbra epilogue + +retlongdouble: + btst #4,%d2 + jbeq retpointer +#if defined(__MC68881__) || defined(__HAVE_68881__) + fmove.x %fp0,(%a1) +#else + move.l %d0,(%a1)+ + move.l %d1,(%a1)+ + move.l %d2,(%a1) +#endif + jbra epilogue + +retpointer: + btst #5,%d2 + jbeq retstruct1 +#ifdef __MINT__ + move.l %d0,(%a1) +#else + move.l %a0,(%a1) +#endif + jbra epilogue + +retstruct1: + btst #6,%d2 + jbeq retstruct2 + move.b %d0,(%a1) + jbra epilogue + +retstruct2: + btst #7,%d2 + jbeq retsint8 + move.w %d0,(%a1) + jbra epilogue + +retsint8: + btst #8,%d2 + jbeq retsint16 + | NOTE: On the mc68000, extb is not supported. 8->16, then 16->32. +#if !defined(__mc68020__) && !defined(__mc68030__) && !defined(__mc68040__) && !defined(__mc68060__) && !defined(__mcoldfire__) + ext.w %d0 + ext.l %d0 +#else + extb.l %d0 +#endif + move.l %d0,(%a1) + jbra epilogue + +retsint16: + btst #9,%d2 + jbeq noretval + ext.l %d0 + move.l %d0,(%a1) + +noretval: +epilogue: + move.l (%sp)+,%d2 + unlk %fp + rts + CFI_ENDPROC() + .size CALLFUNC(ffi_call_SYSV),.-CALLFUNC(ffi_call_SYSV) + + .globl CALLFUNC(ffi_closure_SYSV) + .type CALLFUNC(ffi_closure_SYSV), @function + .align 4 + +CALLFUNC(ffi_closure_SYSV): + CFI_STARTPROC() + link %fp,#-12 + CFI_OFFSET(14,-8) + CFI_DEF_CFA(14,8) + move.l %sp,-12(%fp) + pea 8(%fp) + pea -12(%fp) + move.l %a0,-(%sp) +#if !defined __PIC__ + jsr CALLFUNC(ffi_closure_SYSV_inner) +#elif defined(__uClinux__) && defined(__ID_SHARED_LIBRARY__) + move.l _current_shared_library_a5_offset_(%a5),%a0 + move.l CALLFUNC(ffi_closure_SYSV_inner@GOT)(%a0),%a0 + jsr (%a0) +#elif defined(__mcoldfire__) && !defined(__mcfisab__) && !defined(__mcfisac__) + move.l #_GLOBAL_OFFSET_TABLE_@GOTPC,%a0 + lea (-6,%pc,%a0),%a0 + move.l CALLFUNC(ffi_closure_SYSV_inner@GOT)(%a0),%a0 + jsr (%a0) +#else + bsr.l CALLFUNC(ffi_closure_SYSV_inner@PLTPC) +#endif + + lsr.l #1,%d0 + jne 1f + jcc .Lcls_epilogue + | CIF_FLAGS_INT + move.l -12(%fp),%d0 +.Lcls_epilogue: + | no CIF_FLAGS_* + unlk %fp + rts +1: + lea -12(%fp),%a0 + lsr.l #2,%d0 + jne 1f + jcs .Lcls_ret_float + | CIF_FLAGS_DINT + move.l (%a0)+,%d0 + move.l (%a0),%d1 + jra .Lcls_epilogue +.Lcls_ret_float: +#if defined(__MC68881__) || defined(__HAVE_68881__) + fmove.s (%a0),%fp0 +#else + move.l (%a0),%d0 +#endif + jra .Lcls_epilogue +1: + lsr.l #2,%d0 + jne 1f + jcs .Lcls_ret_ldouble + | CIF_FLAGS_DOUBLE +#if defined(__MC68881__) || defined(__HAVE_68881__) + fmove.d (%a0),%fp0 +#else + move.l (%a0)+,%d0 + move.l (%a0),%d1 +#endif + jra .Lcls_epilogue +.Lcls_ret_ldouble: +#if defined(__MC68881__) || defined(__HAVE_68881__) + fmove.x (%a0),%fp0 +#else + move.l (%a0)+,%d0 + move.l (%a0)+,%d1 + move.l (%a0),%d2 +#endif + jra .Lcls_epilogue +1: + lsr.l #2,%d0 + jne 1f + jcs .Lcls_ret_struct1 + | CIF_FLAGS_POINTER + move.l (%a0),%a0 + move.l %a0,%d0 + jra .Lcls_epilogue +.Lcls_ret_struct1: + move.b (%a0),%d0 + jra .Lcls_epilogue +1: + lsr.l #2,%d0 + jne 1f + jcs .Lcls_ret_sint8 + | CIF_FLAGS_STRUCT2 + move.w (%a0),%d0 + jra .Lcls_epilogue +.Lcls_ret_sint8: + move.l (%a0),%d0 + | NOTE: On the mc68000, extb is not supported. 8->16, then 16->32. +#if !defined(__mc68020__) && !defined(__mc68030__) && !defined(__mc68040__) && !defined(__mc68060__) && !defined(__mcoldfire__) + ext.w %d0 + ext.l %d0 +#else + extb.l %d0 +#endif + jra .Lcls_epilogue +1: + | CIF_FLAGS_SINT16 + move.l (%a0),%d0 + ext.l %d0 + jra .Lcls_epilogue + CFI_ENDPROC() + + .size CALLFUNC(ffi_closure_SYSV),.-CALLFUNC(ffi_closure_SYSV) + + .globl CALLFUNC(ffi_closure_struct_SYSV) + .type CALLFUNC(ffi_closure_struct_SYSV), @function + .align 4 + +CALLFUNC(ffi_closure_struct_SYSV): + CFI_STARTPROC() + link %fp,#0 + CFI_OFFSET(14,-8) + CFI_DEF_CFA(14,8) + move.l %sp,-12(%fp) + pea 8(%fp) + move.l %a1,-(%sp) + move.l %a0,-(%sp) +#if !defined __PIC__ + jsr CALLFUNC(ffi_closure_SYSV_inner) +#elif defined(__uClinux__) && defined(__ID_SHARED_LIBRARY__) + move.l _current_shared_library_a5_offset_(%a5),%a0 + move.l CALLFUNC(ffi_closure_SYSV_inner@GOT)(%a0),%a0 + jsr (%a0) +#elif defined(__mcoldfire__) && !defined(__mcfisab__) && !defined(__mcfisac__) + move.l #_GLOBAL_OFFSET_TABLE_@GOTPC,%a0 + lea (-6,%pc,%a0),%a0 + move.l CALLFUNC(ffi_closure_SYSV_inner@GOT)(%a0),%a0 + jsr (%a0) +#else + bsr.l CALLFUNC(ffi_closure_SYSV_inner@PLTPC) +#endif + unlk %fp + rts + CFI_ENDPROC() + .size CALLFUNC(ffi_closure_struct_SYSV),.-CALLFUNC(ffi_closure_struct_SYSV) + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m88k/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m88k/ffi.c new file mode 100644 index 0000000..57b344f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m88k/ffi.c @@ -0,0 +1,400 @@ +/* + * Copyright (c) 2013 Miodrag Vallat. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * ``Software''), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * m88k Foreign Function Interface + * + * This file attempts to provide all the FFI entry points which can reliably + * be implemented in C. + * + * Only OpenBSD/m88k is currently supported; other platforms (such as + * Motorola's SysV/m88k) could be supported with the following tweaks: + * + * - non-OpenBSD systems use an `outgoing parameter area' as part of the + * 88BCS calling convention, which is not supported under OpenBSD from + * release 3.6 onwards. Supporting it should be as easy as taking it + * into account when adjusting the stack, in the assembly code. + * + * - the logic deciding whether a function argument gets passed through + * registers, or on the stack, has changed several times in OpenBSD in + * edge cases (especially for structs larger than 32 bytes being passed + * by value). The code below attemps to match the logic used by the + * system compiler of OpenBSD 5.3, i.e. gcc 3.3.6 with many m88k backend + * fixes. + */ + +#include +#include + +#include +#include + +void ffi_call_OBSD (unsigned int, extended_cif *, unsigned int, void *, + void (*fn) ()); +void *ffi_prep_args (void *, extended_cif *); +void ffi_closure_OBSD (ffi_closure *); +void ffi_closure_struct_OBSD (ffi_closure *); +unsigned int ffi_closure_OBSD_inner (ffi_closure *, void *, unsigned int *, + char *); +void ffi_cacheflush_OBSD (unsigned int, unsigned int); + +#define CIF_FLAGS_INT (1 << 0) +#define CIF_FLAGS_DINT (1 << 1) + +/* + * Foreign Function Interface API + */ + +/* ffi_prep_args is called by the assembly routine once stack space has + been allocated for the function's arguments. */ + +void * +ffi_prep_args (void *stack, extended_cif *ecif) +{ + unsigned int i; + void **p_argv; + char *argp, *stackp; + unsigned int *regp; + unsigned int regused; + ffi_type **p_arg; + void *struct_value_ptr; + + regp = (unsigned int *)stack; + stackp = (char *)(regp + 8); + regused = 0; + + if (ecif->cif->rtype->type == FFI_TYPE_STRUCT + && !ecif->cif->flags) + struct_value_ptr = ecif->rvalue; + else + struct_value_ptr = NULL; + + p_argv = ecif->avalue; + + for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; i != 0; i--, p_arg++) + { + size_t z; + unsigned short t, a; + + z = (*p_arg)->size; + t = (*p_arg)->type; + a = (*p_arg)->alignment; + + /* + * Figure out whether the argument can be passed through registers + * or on the stack. + * The rule is that registers can only receive simple types not larger + * than 64 bits, or structs the exact size of a register and aligned to + * the size of a register. + */ + if (t == FFI_TYPE_STRUCT) + { + if (z == sizeof (int) && a == sizeof (int) && regused < 8) + argp = (char *)regp; + else + argp = stackp; + } + else + { + if (z > sizeof (int) && regused < 8 - 1) + { + /* align to an even register pair */ + if (regused & 1) + { + regp++; + regused++; + } + } + if (regused < 8) + argp = (char *)regp; + else + argp = stackp; + } + + /* Enforce proper stack alignment of 64-bit types */ + if (argp == stackp && a > sizeof (int)) + { + stackp = (char *) FFI_ALIGN(stackp, a); + argp = stackp; + } + + switch (t) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int) *(SINT8 *) *p_argv; + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int) *(UINT8 *) *p_argv; + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int) *(SINT16 *) *p_argv; + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int) *(UINT16 *) *p_argv; + break; + + case FFI_TYPE_INT: + case FFI_TYPE_FLOAT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_POINTER: + *(unsigned int *) argp = *(unsigned int *) *p_argv; + break; + + case FFI_TYPE_DOUBLE: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_STRUCT: + memcpy (argp, *p_argv, z); + break; + + default: + FFI_ASSERT (0); + } + + /* Align if necessary. */ + if ((sizeof (int) - 1) & z) + z = FFI_ALIGN(z, sizeof (int)); + + p_argv++; + + /* Be careful, once all registers are filled, and about to continue + on stack, regp == stackp. Therefore the check for regused as well. */ + if (argp == (char *)regp && regused < 8) + { + regp += z / sizeof (int); + regused += z / sizeof (int); + } + else + stackp += z; + } + + return struct_value_ptr; +} + +/* Perform machine dependent cif processing */ +ffi_status +ffi_prep_cif_machdep (ffi_cif *cif) +{ + /* Set the return type flag */ + switch (cif->rtype->type) + { + case FFI_TYPE_VOID: + cif->flags = 0; + break; + + case FFI_TYPE_STRUCT: + if (cif->rtype->size == sizeof (int) && + cif->rtype->alignment == sizeof (int)) + cif->flags = CIF_FLAGS_INT; + else + cif->flags = 0; + break; + + case FFI_TYPE_DOUBLE: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + cif->flags = CIF_FLAGS_DINT; + break; + + default: + cif->flags = CIF_FLAGS_INT; + break; + } + + return FFI_OK; +} + +void +ffi_call (ffi_cif *cif, void (*fn) (), void *rvalue, void **avalue) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return value + address then we need to make one. */ + + if (rvalue == NULL + && cif->rtype->type == FFI_TYPE_STRUCT + && (cif->rtype->size != sizeof (int) + || cif->rtype->alignment != sizeof (int))) + ecif.rvalue = alloca (cif->rtype->size); + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_OBSD: + ffi_call_OBSD (cif->bytes, &ecif, cif->flags, ecif.rvalue, fn); + break; + + default: + FFI_ASSERT (0); + break; + } +} + +/* + * Closure API + */ + +static void +ffi_prep_closure_args_OBSD (ffi_cif *cif, void **avalue, unsigned int *regp, + char *stackp) +{ + unsigned int i; + void **p_argv; + char *argp; + unsigned int regused; + ffi_type **p_arg; + + regused = 0; + + p_argv = avalue; + + for (i = cif->nargs, p_arg = cif->arg_types; i != 0; i--, p_arg++) + { + size_t z; + unsigned short t, a; + + z = (*p_arg)->size; + t = (*p_arg)->type; + a = (*p_arg)->alignment; + + /* + * Figure out whether the argument has been passed through registers + * or on the stack. + * The rule is that registers can only receive simple types not larger + * than 64 bits, or structs the exact size of a register and aligned to + * the size of a register. + */ + if (t == FFI_TYPE_STRUCT) + { + if (z == sizeof (int) && a == sizeof (int) && regused < 8) + argp = (char *)regp; + else + argp = stackp; + } + else + { + if (z > sizeof (int) && regused < 8 - 1) + { + /* align to an even register pair */ + if (regused & 1) + { + regp++; + regused++; + } + } + if (regused < 8) + argp = (char *)regp; + else + argp = stackp; + } + + /* Enforce proper stack alignment of 64-bit types */ + if (argp == stackp && a > sizeof (int)) + { + stackp = (char *) FFI_ALIGN(stackp, a); + argp = stackp; + } + + if (z < sizeof (int) && t != FFI_TYPE_STRUCT) + *p_argv = (void *) (argp + sizeof (int) - z); + else + *p_argv = (void *) argp; + + /* Align if necessary */ + if ((sizeof (int) - 1) & z) + z = FFI_ALIGN(z, sizeof (int)); + + p_argv++; + + /* Be careful, once all registers are exhausted, and about to fetch from + stack, regp == stackp. Therefore the check for regused as well. */ + if (argp == (char *)regp && regused < 8) + { + regp += z / sizeof (int); + regused += z / sizeof (int); + } + else + stackp += z; + } +} + +unsigned int +ffi_closure_OBSD_inner (ffi_closure *closure, void *resp, unsigned int *regp, + char *stackp) +{ + ffi_cif *cif; + void **arg_area; + + cif = closure->cif; + arg_area = (void**) alloca (cif->nargs * sizeof (void *)); + + ffi_prep_closure_args_OBSD(cif, arg_area, regp, stackp); + + (closure->fun) (cif, resp, arg_area, closure->user_data); + + return cif->flags; +} + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, void *codeloc) +{ + unsigned int *tramp = (unsigned int *) codeloc; + void *fn; + + FFI_ASSERT (cif->abi == FFI_OBSD); + + if (cif->rtype->type == FFI_TYPE_STRUCT && !cif->flags) + fn = &ffi_closure_struct_OBSD; + else + fn = &ffi_closure_OBSD; + + /* or.u %r10, %r0, %hi16(fn) */ + tramp[0] = 0x5d400000 | (((unsigned int)fn) >> 16); + /* or.u %r13, %r0, %hi16(closure) */ + tramp[1] = 0x5da00000 | ((unsigned int)closure >> 16); + /* or %r10, %r10, %lo16(fn) */ + tramp[2] = 0x594a0000 | (((unsigned int)fn) & 0xffff); + /* jmp.n %r10 */ + tramp[3] = 0xf400c40a; + /* or %r13, %r13, %lo16(closure) */ + tramp[4] = 0x59ad0000 | ((unsigned int)closure & 0xffff); + + ffi_cacheflush_OBSD((unsigned int)codeloc, FFI_TRAMPOLINE_SIZE); + + closure->cif = cif; + closure->user_data = user_data; + closure->fun = fun; + + return FFI_OK; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m88k/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m88k/ffitarget.h new file mode 100644 index 0000000..e52bf9f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m88k/ffitarget.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2013 Miodrag Vallat. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * ``Software''), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * m88k Foreign Function Interface + */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_OBSD, + FFI_DEFAULT_ABI = FFI_OBSD, + FFI_LAST_ABI = FFI_DEFAULT_ABI + 1 +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 0x14 +#define FFI_NATIVE_RAW_API 0 + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m88k/obsd.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m88k/obsd.S new file mode 100644 index 0000000..1944a23 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/m88k/obsd.S @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2013 Miodrag Vallat. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * ``Software''), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * m88k Foreign Function Interface + */ + +#define LIBFFI_ASM +#include +#include + + .text + +/* + * ffi_cacheflush_OBSD(unsigned int addr, %r2 + * unsigned int size); %r3 + */ + .align 4 + .globl ffi_cacheflush_OBSD + .type ffi_cacheflush_OBSD,@function +ffi_cacheflush_OBSD: + tb0 0, %r0, 451 + or %r0, %r0, %r0 + jmp %r1 + .size ffi_cacheflush_OBSD, . - ffi_cacheflush_OBSD + +/* + * ffi_call_OBSD(unsigned bytes, %r2 + * extended_cif *ecif, %r3 + * unsigned flags, %r4 + * void *rvalue, %r5 + * void (*fn)()); %r6 + */ + .align 4 + .globl ffi_call_OBSD + .type ffi_call_OBSD,@function +ffi_call_OBSD: + subu %r31, %r31, 32 + st %r30, %r31, 4 + st %r1, %r31, 0 + addu %r30, %r31, 32 + + | Save the few arguments we'll need after ffi_prep_args() + st.d %r4, %r31, 8 + st %r6, %r31, 16 + + | Allocate room for the image of r2-r9, and the stack space for + | the args (rounded to a 16-byte boundary) + addu %r2, %r2, (8 * 4) + 15 + clr %r2, %r2, 4<0> + subu %r31, %r31, %r2 + + | Fill register and stack image + or %r2, %r31, %r0 +#ifdef PIC + bsr ffi_prep_args#plt +#else + bsr ffi_prep_args +#endif + + | Save pointer to return struct address, if any + or %r12, %r2, %r0 + + | Get function pointer + subu %r4, %r30, 32 + ld %r1, %r4, 16 + + | Fetch the register arguments + ld.d %r2, %r31, (0 * 4) + ld.d %r4, %r31, (2 * 4) + ld.d %r6, %r31, (4 * 4) + ld.d %r8, %r31, (6 * 4) + addu %r31, %r31, (8 * 4) + + | Invoke the function + jsr %r1 + + | Restore stack now that we don't need the args anymore + subu %r31, %r30, 32 + + | Figure out what to return as the function's return value + ld %r5, %r31, 12 | rvalue + ld %r4, %r31, 8 | flags + + bcnd eq0, %r5, 9f + + bb0 0, %r4, 1f | CIF_FLAGS_INT + st %r2, %r5, 0 + br 9f + +1: + bb0 1, %r4, 1f | CIF_FLAGS_DINT + st.d %r2, %r5, 0 + br 9f + +1: +9: + ld %r1, %r31, 0 + ld %r30, %r31, 4 + jmp.n %r1 + addu %r31, %r31, 32 + .size ffi_call_OBSD, . - ffi_call_OBSD + +/* + * ffi_closure_OBSD(ffi_closure *closure); %r13 + */ + .align 4 + .globl ffi_closure_OBSD + .type ffi_closure_OBSD, @function +ffi_closure_OBSD: + subu %r31, %r31, 16 + st %r30, %r31, 4 + st %r1, %r31, 0 + addu %r30, %r31, 16 + + | Make room on the stack for saved register arguments and return + | value + subu %r31, %r31, (8 * 4) + (2 * 4) + st.d %r2, %r31, (0 * 4) + st.d %r4, %r31, (2 * 4) + st.d %r6, %r31, (4 * 4) + st.d %r8, %r31, (6 * 4) + + | Invoke the closure function + or %r5, %r30, 0 | calling stack + addu %r4, %r31, 0 | saved registers + addu %r3, %r31, (8 * 4) | return value + or %r2, %r13, %r0 | closure +#ifdef PIC + bsr ffi_closure_OBSD_inner#plt +#else + bsr ffi_closure_OBSD_inner +#endif + + | Figure out what to return as the function's return value + bb0 0, %r2, 1f | CIF_FLAGS_INT + ld %r2, %r31, (8 * 4) + br 9f + +1: + bb0 1, %r2, 1f | CIF_FLAGS_DINT + ld.d %r2, %r31, (8 * 4) + br 9f + +1: +9: + subu %r31, %r30, 16 + ld %r1, %r31, 0 + ld %r30, %r31, 4 + jmp.n %r1 + addu %r31, %r31, 16 + .size ffi_closure_OBSD,.-ffi_closure_OBSD + +/* + * ffi_closure_struct_OBSD(ffi_closure *closure); %r13 + */ + .align 4 + .globl ffi_closure_struct_OBSD + .type ffi_closure_struct_OBSD, @function +ffi_closure_struct_OBSD: + subu %r31, %r31, 16 + st %r30, %r31, 4 + st %r1, %r31, 0 + addu %r30, %r31, 16 + + | Make room on the stack for saved register arguments + subu %r31, %r31, (8 * 4) + st.d %r2, %r31, (0 * 4) + st.d %r4, %r31, (2 * 4) + st.d %r6, %r31, (4 * 4) + st.d %r8, %r31, (6 * 4) + + | Invoke the closure function + or %r5, %r30, 0 | calling stack + addu %r4, %r31, 0 | saved registers + or %r3, %r12, 0 | return value + or %r2, %r13, %r0 | closure +#ifdef PIC + bsr ffi_closure_OBSD_inner#plt +#else + bsr ffi_closure_OBSD_inner +#endif + + subu %r31, %r30, 16 + ld %r1, %r31, 0 + ld %r30, %r31, 4 + jmp.n %r1 + addu %r31, %r31, 16 + .size ffi_closure_struct_OBSD,.-ffi_closure_struct_OBSD diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/metag/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/metag/ffi.c new file mode 100644 index 0000000..3aecb0b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/metag/ffi.c @@ -0,0 +1,330 @@ +/* ---------------------------------------------------------------------- + ffi.c - Copyright (c) 2013 Imagination Technologies + + Meta Foreign Function Interface + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + `Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED `AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL SIMON POSNJAK BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. +----------------------------------------------------------------------- */ + +#include +#include + +#include + +#define MIN(a,b) (((a) < (b)) ? (a) : (b)) + +/* + * ffi_prep_args is called by the assembly routine once stack space has been + * allocated for the function's arguments + */ + +unsigned int ffi_prep_args(char *stack, extended_cif *ecif) +{ + register unsigned int i; + register void **p_argv; + register char *argp; + register ffi_type **p_arg; + + argp = stack; + + /* Store return value */ + if ( ecif->cif->flags == FFI_TYPE_STRUCT ) { + argp -= 4; + *(void **) argp = ecif->rvalue; + } + + p_argv = ecif->avalue; + + /* point to next location */ + for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; (i != 0); i--, p_arg++, p_argv++) + { + size_t z; + + /* Move argp to address of argument */ + z = (*p_arg)->size; + argp -= z; + + /* Align if necessary */ + argp = (char *) FFI_ALIGN_DOWN(FFI_ALIGN_DOWN(argp, (*p_arg)->alignment), 4); + + if (z < sizeof(int)) { + z = sizeof(int); + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); + break; + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); + break; + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); + break; + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); + case FFI_TYPE_STRUCT: + memcpy(argp, *p_argv, (*p_arg)->size); + break; + default: + FFI_ASSERT(0); + } + } else if ( z == sizeof(int)) { + *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); + } else { + memcpy(argp, *p_argv, z); + } + } + + /* return the size of the arguments to be passed in registers, + padded to an 8 byte boundary to preserve stack alignment */ + return FFI_ALIGN(MIN(stack - argp, 6*4), 8); +} + +/* Perform machine dependent cif processing */ +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + ffi_type **ptr; + unsigned i, bytes = 0; + + for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) { + if ((*ptr)->size == 0) + return FFI_BAD_TYPEDEF; + + /* Perform a sanity check on the argument type, do this + check after the initialization. */ + FFI_ASSERT_VALID_TYPE(*ptr); + + /* Add any padding if necessary */ + if (((*ptr)->alignment - 1) & bytes) + bytes = FFI_ALIGN(bytes, (*ptr)->alignment); + + bytes += FFI_ALIGN((*ptr)->size, 4); + } + + /* Ensure arg space is aligned to an 8-byte boundary */ + bytes = FFI_ALIGN(bytes, 8); + + /* Make space for the return structure pointer */ + if (cif->rtype->type == FFI_TYPE_STRUCT) { + bytes += sizeof(void*); + + /* Ensure stack is aligned to an 8-byte boundary */ + bytes = FFI_ALIGN(bytes, 8); + } + + cif->bytes = bytes; + + /* Set the return type flag */ + switch (cif->rtype->type) { + case FFI_TYPE_VOID: + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + cif->flags = (unsigned) cif->rtype->type; + break; + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + cif->flags = (unsigned) FFI_TYPE_SINT64; + break; + case FFI_TYPE_STRUCT: + /* Meta can store return values which are <= 64 bits */ + if (cif->rtype->size <= 4) + /* Returned to D0Re0 as 32-bit value */ + cif->flags = (unsigned)FFI_TYPE_INT; + else if ((cif->rtype->size > 4) && (cif->rtype->size <= 8)) + /* Returned valued is stored to D1Re0|R0Re0 */ + cif->flags = (unsigned)FFI_TYPE_DOUBLE; + else + /* value stored in memory */ + cif->flags = (unsigned)FFI_TYPE_STRUCT; + break; + default: + cif->flags = (unsigned)FFI_TYPE_INT; + break; + } + return FFI_OK; +} + +extern void ffi_call_SYSV(void (*fn)(void), extended_cif *, unsigned, unsigned, double *); + +/* + * Exported in API. Entry point + * cif -> ffi_cif object + * fn -> function pointer + * rvalue -> pointer to return value + * avalue -> vector of void * pointers pointing to memory locations holding the + * arguments + */ +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + extended_cif ecif; + + int small_struct = (((cif->flags == FFI_TYPE_INT) || (cif->flags == FFI_TYPE_DOUBLE)) && (cif->rtype->type == FFI_TYPE_STRUCT)); + ecif.cif = cif; + ecif.avalue = avalue; + + double temp; + + /* + * If the return value is a struct and we don't have a return value address + * then we need to make one + */ + + if ((rvalue == NULL ) && (cif->flags == FFI_TYPE_STRUCT)) + ecif.rvalue = alloca(cif->rtype->size); + else if (small_struct) + ecif.rvalue = &temp; + else + ecif.rvalue = rvalue; + + switch (cif->abi) { + case FFI_SYSV: + ffi_call_SYSV(fn, &ecif, cif->bytes, cif->flags, ecif.rvalue); + break; + default: + FFI_ASSERT(0); + break; + } + + if (small_struct) + memcpy (rvalue, &temp, cif->rtype->size); +} + +/* private members */ + +static void ffi_prep_incoming_args_SYSV (char *, void **, void **, + ffi_cif*, float *); + +void ffi_closure_SYSV (ffi_closure *); + +/* Do NOT change that without changing the FFI_TRAMPOLINE_SIZE */ +extern unsigned int ffi_metag_trampoline[10]; /* 10 instructions */ + +/* end of private members */ + +/* + * __tramp: trampoline memory location + * __fun: assembly routine + * __ctx: memory location for wrapper + * + * At this point, tramp[0] == __ctx ! + */ +void ffi_init_trampoline(unsigned char *__tramp, unsigned int __fun, unsigned int __ctx) { + memcpy (__tramp, ffi_metag_trampoline, sizeof(ffi_metag_trampoline)); + *(unsigned int*) &__tramp[40] = __ctx; + *(unsigned int*) &__tramp[44] = __fun; + /* This will flush the instruction cache */ + __builtin_meta2_cachewd(&__tramp[0], 1); + __builtin_meta2_cachewd(&__tramp[47], 1); +} + + + +/* the cif must already be prepared */ + +ffi_status +ffi_prep_closure_loc (ffi_closure *closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + void (*closure_func)(ffi_closure*) = NULL; + + if (cif->abi == FFI_SYSV) + closure_func = &ffi_closure_SYSV; + else + return FFI_BAD_ABI; + + ffi_init_trampoline( + (unsigned char*)&closure->tramp[0], + (unsigned int)closure_func, + (unsigned int)codeloc); + + closure->cif = cif; + closure->user_data = user_data; + closure->fun = fun; + + return FFI_OK; +} + + +/* This function is jumped to by the trampoline */ +unsigned int ffi_closure_SYSV_inner (closure, respp, args, vfp_args) + ffi_closure *closure; + void **respp; + void *args; + void *vfp_args; +{ + ffi_cif *cif; + void **arg_area; + + cif = closure->cif; + arg_area = (void**) alloca (cif->nargs * sizeof (void*)); + + /* + * This call will initialize ARG_AREA, such that each + * element in that array points to the corresponding + * value on the stack; and if the function returns + * a structure, it will re-set RESP to point to the + * structure return address. + */ + ffi_prep_incoming_args_SYSV(args, respp, arg_area, cif, vfp_args); + + (closure->fun) ( cif, *respp, arg_area, closure->user_data); + + return cif->flags; +} + +static void ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, + void **avalue, ffi_cif *cif, + float *vfp_stack) +{ + register unsigned int i; + register void **p_argv; + register char *argp; + register ffi_type **p_arg; + + /* stack points to original arguments */ + argp = stack; + + /* Store return value */ + if ( cif->flags == FFI_TYPE_STRUCT ) { + argp -= 4; + *rvalue = *(void **) argp; + } + + p_argv = avalue; + + for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) { + size_t z; + size_t alignment; + + alignment = (*p_arg)->alignment; + if (alignment < 4) + alignment = 4; + if ((alignment - 1) & (unsigned)argp) + argp = (char *) FFI_ALIGN(argp, alignment); + + z = (*p_arg)->size; + *p_argv = (void*) argp; + p_argv++; + argp -= z; + } + return; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/metag/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/metag/ffitarget.h new file mode 100644 index 0000000..7b9dbeb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/metag/ffitarget.h @@ -0,0 +1,53 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2013 Imagination Technologies Ltd. + Target configuration macros for Meta + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_DEFAULT_ABI = FFI_SYSV, + FFI_LAST_ABI = FFI_DEFAULT_ABI + 1, +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 48 +#define FFI_NATIVE_RAW_API 0 + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/metag/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/metag/sysv.S new file mode 100644 index 0000000..b4b2a3b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/metag/sysv.S @@ -0,0 +1,311 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2013 Imagination Technologies Ltd. + + Meta Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include +#ifdef HAVE_MACHINE_ASM_H +#include +#else +#ifdef __USER_LABEL_PREFIX__ +#define CONCAT1(a, b) CONCAT2(a, b) +#define CONCAT2(a, b) a ## b + +/* Use the right prefix for global labels. */ +#define CNAME(x) CONCAT1 (__USER_LABEL_PREFIX__, x) +#else +#define CNAME(x) x +#endif +#define ENTRY(x) .globl CNAME(x); .type CNAME(x), %function; CNAME(x): +#endif + +#ifdef __ELF__ +#define LSYM(x) .x +#else +#define LSYM(x) x +#endif + +.macro call_reg x= + .text + .balign 4 + mov D1RtP, \x + swap D1RtP, PC +.endm + +! Save register arguments +.macro SAVE_ARGS + .text + .balign 4 + setl [A0StP++], D0Ar6, D1Ar5 + setl [A0StP++], D0Ar4, D1Ar3 + setl [A0StP++], D0Ar2, D1Ar1 +.endm + +! Save retrun, frame pointer and other regs +.macro SAVE_REGS regs= + .text + .balign 4 + setl [A0StP++], D0FrT, D1RtP + ! Needs to be a pair of regs + .ifnc "\regs","" + setl [A0StP++], \regs + .endif +.endm + +! Declare a global function +.macro METAG_FUNC_START name + .text + .balign 4 + ENTRY(\name) +.endm + +! Return registers from the stack. Reverse SAVE_REGS operation +.macro RET_REGS regs=, cond= + .ifnc "\regs", "" + getl \regs, [--A0StP] + .endif + getl D0FrT, D1RtP, [--A0StP] +.endm + +! Return arguments +.macro RET_ARGS + getl D0Ar2, D1Ar1, [--A0StP] + getl D0Ar4, D1Ar3, [--A0StP] + getl D0Ar6, D1Ar5, [--A0StP] +.endm + + + ! D1Ar1: fn + ! D0Ar2: &ecif + ! D1Ar3: cif->bytes + ! D0Ar4: fig->flags + ! D1Ar5: ecif.rvalue + + ! This assumes we are using GNU as +METAG_FUNC_START ffi_call_SYSV + ! Save argument registers + + SAVE_ARGS + + ! new frame + mov D0FrT, A0FrP + add A0FrP, A0StP, #0 + + ! Preserve the old frame pointer + SAVE_REGS "D1.5, D0.5" + + ! Make room for new args. cifs->bytes is the total space for input + ! and return arguments + + add A0StP, A0StP, D1Ar3 + + ! Preserve cifs->bytes & fn + mov D0.5, D1Ar3 + mov D1.5, D1Ar1 + + ! Place all of the ffi_prep_args in position + mov D1Ar1, A0StP + + ! Call ffi_prep_args(stack, &ecif) +#ifdef __PIC__ + callr D1RtP, CNAME(ffi_prep_args@PLT) +#else + callr D1RtP, CNAME(ffi_prep_args) +#endif + + ! Restore fn pointer + + ! The foreign stack should look like this + ! XXXXX XXXXXX <--- stack pointer + ! FnArgN rvalue + ! FnArgN+2 FnArgN+1 + ! FnArgN+4 FnArgN+3 + ! .... + ! + + ! A0StP now points to the first (or return) argument + 4 + + ! Preserve cif->bytes + getl D0Ar2, D1Ar1, [--A0StP] + getl D0Ar4, D1Ar3, [--A0StP] + getl D0Ar6, D1Ar5, [--A0StP] + + ! Place A0StP to the first argument again + add A0StP, A0StP, #24 ! That's because we loaded 6 regs x 4 byte each + + ! A0FrP points to the initial stack without the reserved space for the + ! cifs->bytes, whilst A0StP points to the stack after the space allocation + + ! fn was the first argument of ffi_call_SYSV. + ! The stack at this point looks like this: + ! + ! A0StP(on entry to _SYSV) -> Arg6 Arg5 | low + ! Arg4 Arg3 | + ! Arg2 Arg1 | + ! A0FrP ----> D0FrtP D1RtP | + ! D1.5 D0.5 | + ! A0StP(bf prep_args) -> FnArgn FnArgn-1 | + ! FnArgn-2FnArgn-3 | + ! ................ | <= cifs->bytes + ! FnArg4 FnArg3 | + ! A0StP (prv_A0StP+cifs->bytes) FnArg2 FnArg1 | high + ! + ! fn was in Arg1 so it's located in in A0FrP+#-0xC + ! + + ! D0Re0 contains the size of arguments stored in registers + sub A0StP, A0StP, D0Re0 + + ! Arg1 is the function pointer for the foreign call. This has been + ! preserved in D1.5 + + ! Time to call (fn). Arguments should be like this: + ! Arg1-Arg6 are loaded to regs + ! The rest of the arguments are stored in stack pointed by A0StP + + call_reg D1.5 + + ! Reset stack. + + mov A0StP, A0FrP + + ! Load Arg1 with the pointer to storage for the return type + ! This was stored in Arg5 + + getd D1Ar1, [A0FrP+#-20] + + ! Load D0Ar2 with the return type code. This was stored in Arg4 (flags) + + getd D0Ar2, [A0FrP+#-16] + + ! We are ready to start processing the return value + ! D0Re0 (and D1Re0) hold the return value + + ! If the return value is NULL, assume no return value + cmp D1Ar1, #0 + beq LSYM(Lepilogue) + + ! return INT + cmp D0Ar2, #FFI_TYPE_INT + ! Sadly, there is no setd{cc} instruction so we need to workaround that + bne .INT64 + setd [D1Ar1], D0Re0 + b LSYM(Lepilogue) + + ! return INT64 +.INT64: + cmp D0Ar2, #FFI_TYPE_SINT64 + setleq [D1Ar1], D0Re0, D1Re0 + + ! return DOUBLE + cmp D0Ar2, #FFI_TYPE_DOUBLE + setl [D1AR1++], D0Re0, D1Re0 + +LSYM(Lepilogue): + ! At this point, the stack pointer points right after the argument + ! saved area. We need to restore 4 regs, therefore we need to move + ! 16 bytes ahead. + add A0StP, A0StP, #16 + RET_REGS "D1.5, D0.5" + RET_ARGS + getd D0Re0, [A0StP] + mov A0FrP, D0FrT + swap D1RtP, PC + +.ffi_call_SYSV_end: + .size CNAME(ffi_call_SYSV),.ffi_call_SYSV_end-CNAME(ffi_call_SYSV) + + +/* + (called by ffi_metag_trampoline) + void ffi_closure_SYSV (ffi_closure*) + + (called by ffi_closure_SYSV) + unsigned int FFI_HIDDEN + ffi_closure_SYSV_inner (closure,respp, args) + ffi_closure *closure; + void **respp; + void *args; +*/ + +METAG_FUNC_START ffi_closure_SYSV + ! We assume that D1Ar1 holds the address of the + ! ffi_closure struct. We will use that to fetch the + ! arguments. The stack pointer points to an empty space + ! and it is ready to store more data. + + ! D1Ar1 is ready + ! Allocate stack space for return value + add A0StP, A0StP, #8 + ! Store it to D0Ar2 + sub D0Ar2, A0StP, #8 + + sub D1Ar3, A0FrP, #4 + + ! D1Ar3 contains the address of the original D1Ar1 argument + ! We need to subtract #4 later on + + ! Preverve D0Ar2 + mov D0.5, D0Ar2 + +#ifdef __PIC__ + callr D1RtP, CNAME(ffi_closure_SYSV_inner@PLT) +#else + callr D1RtP, CNAME(ffi_closure_SYSV_inner) +#endif + + ! Check the return value and store it to D0.5 + cmp D0Re0, #FFI_TYPE_INT + beq .Lretint + cmp D0Re0, #FFI_TYPE_DOUBLE + beq .Lretdouble +.Lclosure_epilogue: + sub A0StP, A0StP, #8 + RET_REGS "D1.5, D0.5" + RET_ARGS + swap D1RtP, PC + +.Lretint: + setd [D0.5], D0Re0 + b .Lclosure_epilogue +.Lretdouble: + setl [D0.5++], D0Re0, D1Re0 + b .Lclosure_epilogue +.ffi_closure_SYSV_end: +.size CNAME(ffi_closure_SYSV),.ffi_closure_SYSV_end-CNAME(ffi_closure_SYSV) + + +ENTRY(ffi_metag_trampoline) + SAVE_ARGS + ! New frame + mov A0FrP, A0StP + SAVE_REGS "D1.5, D0.5" + mov D0.5, PC + ! Load D1Ar1 the value of ffi_metag_trampoline + getd D1Ar1, [D0.5 + #8] + ! Jump to ffi_closure_SYSV + getd PC, [D0.5 + #12] diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/microblaze/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/microblaze/ffi.c new file mode 100644 index 0000000..df6e33c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/microblaze/ffi.c @@ -0,0 +1,321 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2012, 2013 Xilinx, Inc + + MicroBlaze Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +extern void ffi_call_SYSV(void (*)(void*, extended_cif*), extended_cif*, + unsigned int, unsigned int, unsigned int*, void (*fn)(void), + unsigned int, unsigned int); + +extern void ffi_closure_SYSV(void); + +#define WORD_SIZE sizeof(unsigned int) +#define ARGS_REGISTER_SIZE (WORD_SIZE * 6) +#define WORD_FFI_ALIGN(x) FFI_ALIGN(x, WORD_SIZE) + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments */ +void ffi_prep_args(void* stack, extended_cif* ecif) +{ + unsigned int i; + ffi_type** p_arg; + void** p_argv; + void* stack_args_p = stack; + + if (ecif == NULL || ecif->cif == NULL) { + return; /* no description to prepare */ + } + + p_argv = ecif->avalue; + + if ((ecif->cif->rtype != NULL) && + (ecif->cif->rtype->type == FFI_TYPE_STRUCT)) + { + /* if return type is a struct which is referenced on the stack/reg5, + * by a pointer. Stored the return value pointer in r5. + */ + char* addr = stack_args_p; + memcpy(addr, &(ecif->rvalue), WORD_SIZE); + stack_args_p += WORD_SIZE; + } + + if (ecif->avalue == NULL) { + return; /* no arguments to prepare */ + } + + for (i = 0, p_arg = ecif->cif->arg_types; i < ecif->cif->nargs; + i++, p_arg++) + { + size_t size = (*p_arg)->size; + int type = (*p_arg)->type; + void* value = p_argv[i]; + char* addr = stack_args_p; + int aligned_size = WORD_FFI_ALIGN(size); + + /* force word alignment on the stack */ + stack_args_p += aligned_size; + + switch (type) + { + case FFI_TYPE_UINT8: + *(unsigned int *)addr = (unsigned int)*(UINT8*)(value); + break; + case FFI_TYPE_SINT8: + *(signed int *)addr = (signed int)*(SINT8*)(value); + break; + case FFI_TYPE_UINT16: + *(unsigned int *)addr = (unsigned int)*(UINT16*)(value); + break; + case FFI_TYPE_SINT16: + *(signed int *)addr = (signed int)*(SINT16*)(value); + break; + case FFI_TYPE_STRUCT: +#if __BIG_ENDIAN__ + /* + * MicroBlaze toolchain appears to emit: + * bsrli r5, r5, 8 (caller) + * ... + * + * ... + * bslli r5, r5, 8 (callee) + * + * For structs like "struct a { uint8_t a[3]; };", when passed + * by value. + * + * Structs like "struct b { uint16_t a; };" are also expected + * to be packed strangely in registers. + * + * This appears to be because the microblaze toolchain expects + * "struct b == uint16_t", which is only any issue for big + * endian. + * + * The following is a work around for big-endian only, for the + * above mentioned case, it will re-align the contents of a + * <= 3-byte struct value. + */ + if (size < WORD_SIZE) + { + memcpy (addr + (WORD_SIZE - size), value, size); + break; + } +#endif + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_FLOAT: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_DOUBLE: + default: + memcpy(addr, value, aligned_size); + } + } +} + +ffi_status ffi_prep_cif_machdep(ffi_cif* cif) +{ + /* check ABI */ + switch (cif->abi) + { + case FFI_SYSV: + break; + default: + return FFI_BAD_ABI; + } + return FFI_OK; +} + +void ffi_call(ffi_cif* cif, void (*fn)(void), void* rvalue, void** avalue) +{ + extended_cif ecif; + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return */ + /* value address then we need to make one */ + if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { + ecif.rvalue = alloca(cif->rtype->size); + } else { + ecif.rvalue = rvalue; + } + + switch (cif->abi) + { + case FFI_SYSV: + ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, cif->flags, + ecif.rvalue, fn, cif->rtype->type, cif->rtype->size); + break; + default: + FFI_ASSERT(0); + break; + } +} + +void ffi_closure_call_SYSV(void* register_args, void* stack_args, + ffi_closure* closure, void* rvalue, + unsigned int* rtype, unsigned int* rsize) +{ + /* prepare arguments for closure call */ + ffi_cif* cif = closure->cif; + ffi_type** arg_types = cif->arg_types; + + /* re-allocate data for the args. This needs to be done in order to keep + * multi-word objects (e.g. structs) in contiguous memory. Callers are not + * required to store the value of args in the lower 6 words in the stack + * (although they are allocated in the stack). + */ + char* stackclone = alloca(cif->bytes); + void** avalue = alloca(cif->nargs * sizeof(void*)); + void* struct_rvalue = NULL; + char* ptr = stackclone; + int i; + + /* copy registers into stack clone */ + int registers_used = cif->bytes; + if (registers_used > ARGS_REGISTER_SIZE) { + registers_used = ARGS_REGISTER_SIZE; + } + memcpy(stackclone, register_args, registers_used); + + /* copy stack allocated args into stack clone */ + if (cif->bytes > ARGS_REGISTER_SIZE) { + int stack_used = cif->bytes - ARGS_REGISTER_SIZE; + memcpy(stackclone + ARGS_REGISTER_SIZE, stack_args, stack_used); + } + + /* preserve struct type return pointer passing */ + if ((cif->rtype != NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { + struct_rvalue = *((void**)ptr); + ptr += WORD_SIZE; + } + + /* populate arg pointer list */ + for (i = 0; i < cif->nargs; i++) + { + switch (arg_types[i]->type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: +#ifdef __BIG_ENDIAN__ + avalue[i] = ptr + 3; +#else + avalue[i] = ptr; +#endif + break; + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: +#ifdef __BIG_ENDIAN__ + avalue[i] = ptr + 2; +#else + avalue[i] = ptr; +#endif + break; + case FFI_TYPE_STRUCT: +#if __BIG_ENDIAN__ + /* + * Work around strange ABI behaviour. + * (see info in ffi_prep_args) + */ + if (arg_types[i]->size < WORD_SIZE) + { + memcpy (ptr, ptr + (WORD_SIZE - arg_types[i]->size), arg_types[i]->size); + } +#endif + avalue[i] = (void*)ptr; + break; + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_DOUBLE: + avalue[i] = ptr; + break; + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_FLOAT: + default: + /* default 4-byte argument */ + avalue[i] = ptr; + break; + } + ptr += WORD_FFI_ALIGN(arg_types[i]->size); + } + + /* set the return type info passed back to the wrapper */ + *rsize = cif->rtype->size; + *rtype = cif->rtype->type; + if (struct_rvalue != NULL) { + closure->fun(cif, struct_rvalue, avalue, closure->user_data); + /* copy struct return pointer value into function return value */ + *((void**)rvalue) = struct_rvalue; + } else { + closure->fun(cif, rvalue, avalue, closure->user_data); + } +} + +ffi_status ffi_prep_closure_loc( + ffi_closure* closure, ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void* user_data, void* codeloc) +{ + unsigned long* tramp = (unsigned long*)&(closure->tramp[0]); + unsigned long cls = (unsigned long)codeloc; + unsigned long fn = 0; + unsigned long fn_closure_call_sysv = (unsigned long)ffi_closure_call_SYSV; + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + switch (cif->abi) + { + case FFI_SYSV: + fn = (unsigned long)ffi_closure_SYSV; + + /* load r11 (temp) with fn */ + /* imm fn(upper) */ + tramp[0] = 0xb0000000 | ((fn >> 16) & 0xffff); + /* addik r11, r0, fn(lower) */ + tramp[1] = 0x31600000 | (fn & 0xffff); + + /* load r12 (temp) with cls */ + /* imm cls(upper) */ + tramp[2] = 0xb0000000 | ((cls >> 16) & 0xffff); + /* addik r12, r0, cls(lower) */ + tramp[3] = 0x31800000 | (cls & 0xffff); + + /* load r3 (temp) with ffi_closure_call_SYSV */ + /* imm fn_closure_call_sysv(upper) */ + tramp[4] = 0xb0000000 | ((fn_closure_call_sysv >> 16) & 0xffff); + /* addik r3, r0, fn_closure_call_sysv(lower) */ + tramp[5] = 0x30600000 | (fn_closure_call_sysv & 0xffff); + /* branch/jump to address stored in r11 (fn) */ + tramp[6] = 0x98085800; /* bra r11 */ + + break; + default: + return FFI_BAD_ABI; + } + return FFI_OK; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/microblaze/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/microblaze/ffitarget.h new file mode 100644 index 0000000..c6fa5a4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/microblaze/ffitarget.h @@ -0,0 +1,53 @@ +/* ----------------------------------------------------------------------- + ffitarget.h - Copyright (c) 2012, 2013 Xilinx, Inc + + Target configuration macros for MicroBlaze. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; +#endif + +/* Definitions for closures */ + +#define FFI_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 + +#define FFI_TRAMPOLINE_SIZE (4*8) + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/microblaze/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/microblaze/sysv.S new file mode 100644 index 0000000..ea43e9d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/microblaze/sysv.S @@ -0,0 +1,302 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2012, 2013 Xilinx, Inc + + MicroBlaze Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + + /* + * arg[0] (r5) = ffi_prep_args, + * arg[1] (r6) = &ecif, + * arg[2] (r7) = cif->bytes, + * arg[3] (r8) = cif->flags, + * arg[4] (r9) = ecif.rvalue, + * arg[5] (r10) = fn + * arg[6] (sp[0]) = cif->rtype->type + * arg[7] (sp[4]) = cif->rtype->size + */ + .text + .globl ffi_call_SYSV + .type ffi_call_SYSV, @function +ffi_call_SYSV: + /* push callee saves */ + addik r1, r1, -20 + swi r19, r1, 0 /* Frame Pointer */ + swi r20, r1, 4 /* PIC register */ + swi r21, r1, 8 /* PIC register */ + swi r22, r1, 12 /* save for locals */ + swi r23, r1, 16 /* save for locals */ + + /* save the r5-r10 registers in the stack */ + addik r1, r1, -24 /* increment sp to store 6x 32-bit words */ + swi r5, r1, 0 + swi r6, r1, 4 + swi r7, r1, 8 + swi r8, r1, 12 + swi r9, r1, 16 + swi r10, r1, 20 + + /* save function pointer */ + addik r3, r5, 0 /* copy ffi_prep_args into r3 */ + addik r22, r1, 0 /* save sp for unallocated args into r22 (callee-saved) */ + addik r23, r10, 0 /* save function address into r23 (callee-saved) */ + + /* prepare stack with allocation for n (bytes = r7) args */ + rsub r1, r7, r1 /* subtract bytes from sp */ + + /* prep args for ffi_prep_args call */ + addik r5, r1, 0 /* store stack pointer into arg[0] */ + /* r6 still holds ecif for arg[1] */ + + /* Call ffi_prep_args(stack, &ecif). */ + addik r1, r1, -4 + swi r15, r1, 0 /* store the link register in the frame */ + brald r15, r3 + nop /* branch has delay slot */ + lwi r15, r1, 0 + addik r1, r1, 4 /* restore the link register from the frame */ + /* returns calling stack pointer location */ + + /* prepare args for fn call, prep_args populates them onto the stack */ + lwi r5, r1, 0 /* arg[0] */ + lwi r6, r1, 4 /* arg[1] */ + lwi r7, r1, 8 /* arg[2] */ + lwi r8, r1, 12 /* arg[3] */ + lwi r9, r1, 16 /* arg[4] */ + lwi r10, r1, 20 /* arg[5] */ + + /* call (fn) (...). */ + addik r1, r1, -4 + swi r15, r1, 0 /* store the link register in the frame */ + brald r15, r23 + nop /* branch has delay slot */ + lwi r15, r1, 0 + addik r1, r1, 4 /* restore the link register from the frame */ + + /* Remove the space we pushed for the args. */ + addik r1, r22, 0 /* restore old SP */ + + /* restore this functions parameters */ + lwi r5, r1, 0 /* arg[0] */ + lwi r6, r1, 4 /* arg[1] */ + lwi r7, r1, 8 /* arg[2] */ + lwi r8, r1, 12 /* arg[3] */ + lwi r9, r1, 16 /* arg[4] */ + lwi r10, r1, 20 /* arg[5] */ + addik r1, r1, 24 /* decrement sp to de-allocate 6x 32-bit words */ + + /* If the return value pointer is NULL, assume no return value. */ + beqi r9, ffi_call_SYSV_end + + lwi r22, r1, 48 /* get return type (20 for locals + 28 for arg[6]) */ + lwi r23, r1, 52 /* get return size (20 for locals + 32 for arg[7]) */ + + /* Check if return type is actually a struct, do nothing */ + rsubi r11, r22, FFI_TYPE_STRUCT + beqi r11, ffi_call_SYSV_end + + /* Return 8bit */ + rsubi r11, r23, 1 + beqi r11, ffi_call_SYSV_store8 + + /* Return 16bit */ + rsubi r11, r23, 2 + beqi r11, ffi_call_SYSV_store16 + + /* Return 32bit */ + rsubi r11, r23, 4 + beqi r11, ffi_call_SYSV_store32 + + /* Return 64bit */ + rsubi r11, r23, 8 + beqi r11, ffi_call_SYSV_store64 + + /* Didn't match anything */ + bri ffi_call_SYSV_end + +ffi_call_SYSV_store64: + swi r3, r9, 0 /* store word r3 into return value */ + swi r4, r9, 4 /* store word r4 into return value */ + bri ffi_call_SYSV_end + +ffi_call_SYSV_store32: + swi r3, r9, 0 /* store word r3 into return value */ + bri ffi_call_SYSV_end + +ffi_call_SYSV_store16: +#ifdef __BIG_ENDIAN__ + shi r3, r9, 2 /* store half-word r3 into return value */ +#else + shi r3, r9, 0 /* store half-word r3 into return value */ +#endif + bri ffi_call_SYSV_end + +ffi_call_SYSV_store8: +#ifdef __BIG_ENDIAN__ + sbi r3, r9, 3 /* store byte r3 into return value */ +#else + sbi r3, r9, 0 /* store byte r3 into return value */ +#endif + bri ffi_call_SYSV_end + +ffi_call_SYSV_end: + /* callee restores */ + lwi r19, r1, 0 /* frame pointer */ + lwi r20, r1, 4 /* PIC register */ + lwi r21, r1, 8 /* PIC register */ + lwi r22, r1, 12 + lwi r23, r1, 16 + addik r1, r1, 20 + + /* return from sub-routine (with delay slot) */ + rtsd r15, 8 + nop + + .size ffi_call_SYSV, . - ffi_call_SYSV + +/* ------------------------------------------------------------------------- */ + + /* + * args passed into this function, are passed down to the callee. + * this function is the target of the closure trampoline, as such r12 is + * a pointer to the closure object. + */ + .text + .globl ffi_closure_SYSV + .type ffi_closure_SYSV, @function +ffi_closure_SYSV: + /* push callee saves */ + addik r11, r1, 28 /* save stack args start location (excluding regs/link) */ + addik r1, r1, -12 + swi r19, r1, 0 /* Frame Pointer */ + swi r20, r1, 4 /* PIC register */ + swi r21, r1, 8 /* PIC register */ + + /* store register args on stack */ + addik r1, r1, -24 + swi r5, r1, 0 + swi r6, r1, 4 + swi r7, r1, 8 + swi r8, r1, 12 + swi r9, r1, 16 + swi r10, r1, 20 + + /* setup args */ + addik r5, r1, 0 /* register_args */ + addik r6, r11, 0 /* stack_args */ + addik r7, r12, 0 /* closure object */ + addik r1, r1, -8 /* allocate return value */ + addik r8, r1, 0 /* void* rvalue */ + addik r1, r1, -8 /* allocate for return type/size values */ + addik r9, r1, 0 /* void* rtype */ + addik r10, r1, 4 /* void* rsize */ + + /* call the wrap_call function */ + addik r1, r1, -28 /* allocate args + link reg */ + swi r15, r1, 0 /* store the link register in the frame */ + brald r15, r3 + nop /* branch has delay slot */ + lwi r15, r1, 0 + addik r1, r1, 28 /* restore the link register from the frame */ + +ffi_closure_SYSV_prepare_return: + lwi r9, r1, 0 /* rtype */ + lwi r10, r1, 4 /* rsize */ + addik r1, r1, 8 /* de-allocate return info values */ + + /* Check if return type is actually a struct, store 4 bytes */ + rsubi r11, r9, FFI_TYPE_STRUCT + beqi r11, ffi_closure_SYSV_store32 + + /* Return 8bit */ + rsubi r11, r10, 1 + beqi r11, ffi_closure_SYSV_store8 + + /* Return 16bit */ + rsubi r11, r10, 2 + beqi r11, ffi_closure_SYSV_store16 + + /* Return 32bit */ + rsubi r11, r10, 4 + beqi r11, ffi_closure_SYSV_store32 + + /* Return 64bit */ + rsubi r11, r10, 8 + beqi r11, ffi_closure_SYSV_store64 + + /* Didn't match anything */ + bri ffi_closure_SYSV_end + +ffi_closure_SYSV_store64: + lwi r3, r1, 0 /* store word r3 into return value */ + lwi r4, r1, 4 /* store word r4 into return value */ + /* 64 bits == 2 words, no sign extend occurs */ + bri ffi_closure_SYSV_end + +ffi_closure_SYSV_store32: + lwi r3, r1, 0 /* store word r3 into return value */ + /* 32 bits == 1 word, no sign extend occurs */ + bri ffi_closure_SYSV_end + +ffi_closure_SYSV_store16: +#ifdef __BIG_ENDIAN__ + lhui r3, r1, 2 /* store half-word r3 into return value */ +#else + lhui r3, r1, 0 /* store half-word r3 into return value */ +#endif + rsubi r11, r9, FFI_TYPE_SINT16 + bnei r11, ffi_closure_SYSV_end + sext16 r3, r3 /* fix sign extend of sint8 */ + bri ffi_closure_SYSV_end + +ffi_closure_SYSV_store8: +#ifdef __BIG_ENDIAN__ + lbui r3, r1, 3 /* store byte r3 into return value */ +#else + lbui r3, r1, 0 /* store byte r3 into return value */ +#endif + rsubi r11, r9, FFI_TYPE_SINT8 + bnei r11, ffi_closure_SYSV_end + sext8 r3, r3 /* fix sign extend of sint8 */ + bri ffi_closure_SYSV_end + +ffi_closure_SYSV_end: + addik r1, r1, 8 /* de-allocate return value */ + + /* de-allocate stored args */ + addik r1, r1, 24 + + /* callee restores */ + lwi r19, r1, 0 /* frame pointer */ + lwi r20, r1, 4 /* PIC register */ + lwi r21, r1, 8 /* PIC register */ + addik r1, r1, 12 + + /* return from sub-routine (with delay slot) */ + rtsd r15, 8 + nop + + .size ffi_closure_SYSV, . - ffi_closure_SYSV diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/mips/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/mips/ffi.c new file mode 100644 index 0000000..979ca49 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/mips/ffi.c @@ -0,0 +1,1134 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2011 Anthony Green + Copyright (c) 2008 David Daney + Copyright (c) 1996, 2007, 2008, 2011 Red Hat, Inc. + + MIPS Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include +#include + +#ifdef __GNUC__ +# if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)) +# define USE__BUILTIN___CLEAR_CACHE 1 +# endif +#endif + +#ifndef USE__BUILTIN___CLEAR_CACHE +# if defined(__FreeBSD__) +# include +# elif defined(__OpenBSD__) +# include +# else +# include +# endif +#endif + +#ifdef FFI_DEBUG +# define FFI_MIPS_STOP_HERE() ffi_stop_here() +#else +# define FFI_MIPS_STOP_HERE() do {} while(0) +#endif + +#ifdef FFI_MIPS_N32 +#define FIX_ARGP \ +FFI_ASSERT(argp <= &stack[bytes]); \ +if (argp == &stack[bytes]) \ +{ \ + argp = stack; \ + FFI_MIPS_STOP_HERE(); \ +} +#else +#define FIX_ARGP +#endif + + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments */ + +static void ffi_prep_args(char *stack, + extended_cif *ecif, + int bytes, + int flags) +{ + int i; + void **p_argv; + char *argp; + ffi_type **p_arg; + +#ifdef FFI_MIPS_N32 + /* If more than 8 double words are used, the remainder go + on the stack. We reorder stuff on the stack here to + support this easily. */ + if (bytes > 8 * sizeof(ffi_arg)) + argp = &stack[bytes - (8 * sizeof(ffi_arg))]; + else + argp = stack; +#else + argp = stack; +#endif + + memset(stack, 0, bytes); + +#ifdef FFI_MIPS_N32 + if ( ecif->cif->rstruct_flag != 0 ) +#else + if ( ecif->cif->rtype->type == FFI_TYPE_STRUCT ) +#endif + { + *(ffi_arg *) argp = (ffi_arg) ecif->rvalue; + argp += sizeof(ffi_arg); + FIX_ARGP; + } + + p_argv = ecif->avalue; + + for (i = 0, p_arg = ecif->cif->arg_types; i < ecif->cif->nargs; i++, p_arg++) + { + size_t z; + unsigned int a; + + /* Align if necessary. */ + a = (*p_arg)->alignment; + if (a < sizeof(ffi_arg)) + a = sizeof(ffi_arg); + + if ((a - 1) & (unsigned long) argp) + { + argp = (char *) FFI_ALIGN(argp, a); + FIX_ARGP; + } + + z = (*p_arg)->size; + if (z <= sizeof(ffi_arg)) + { + int type = (*p_arg)->type; + z = sizeof(ffi_arg); + + /* The size of a pointer depends on the ABI */ + if (type == FFI_TYPE_POINTER) + type = (ecif->cif->abi == FFI_N64 + || ecif->cif->abi == FFI_N64_SOFT_FLOAT) + ? FFI_TYPE_SINT64 : FFI_TYPE_SINT32; + + if (i < 8 && (ecif->cif->abi == FFI_N32_SOFT_FLOAT + || ecif->cif->abi == FFI_N64_SOFT_FLOAT)) + { + switch (type) + { + case FFI_TYPE_FLOAT: + type = FFI_TYPE_UINT32; + break; + case FFI_TYPE_DOUBLE: + type = FFI_TYPE_UINT64; + break; + default: + break; + } + } + switch (type) + { + case FFI_TYPE_SINT8: + *(ffi_arg *)argp = *(SINT8 *)(* p_argv); + break; + + case FFI_TYPE_UINT8: + *(ffi_arg *)argp = *(UINT8 *)(* p_argv); + break; + + case FFI_TYPE_SINT16: + *(ffi_arg *)argp = *(SINT16 *)(* p_argv); + break; + + case FFI_TYPE_UINT16: + *(ffi_arg *)argp = *(UINT16 *)(* p_argv); + break; + + case FFI_TYPE_SINT32: + *(ffi_arg *)argp = *(SINT32 *)(* p_argv); + break; + + case FFI_TYPE_UINT32: +#ifdef FFI_MIPS_N32 + /* The N32 ABI requires that 32-bit integers + be sign-extended to 64-bits, regardless of + whether they are signed or unsigned. */ + *(ffi_arg *)argp = *(SINT32 *)(* p_argv); +#else + *(ffi_arg *)argp = *(UINT32 *)(* p_argv); +#endif + break; + + /* This can only happen with 64bit slots. */ + case FFI_TYPE_FLOAT: + *(float *) argp = *(float *)(* p_argv); + break; + + /* Handle structures. */ + default: + memcpy(argp, *p_argv, (*p_arg)->size); + break; + } + } + else + { +#ifdef FFI_MIPS_O32 + memcpy(argp, *p_argv, z); +#else + { + unsigned long end = (unsigned long) argp + z; + unsigned long cap = (unsigned long) stack + bytes; + + /* Check if the data will fit within the register space. + Handle it if it doesn't. */ + + if (end <= cap) + memcpy(argp, *p_argv, z); + else + { + unsigned long portion = cap - (unsigned long)argp; + + memcpy(argp, *p_argv, portion); + argp = stack; + z -= portion; + memcpy(argp, (void*)((unsigned long)(*p_argv) + portion), + z); + } + } +#endif + } + p_argv++; + argp += z; + FIX_ARGP; + } +} + +#ifdef FFI_MIPS_N32 + +/* The n32 spec says that if "a chunk consists solely of a double + float field (but not a double, which is part of a union), it + is passed in a floating point register. Any other chunk is + passed in an integer register". This code traverses structure + definitions and generates the appropriate flags. */ + +static unsigned +calc_n32_struct_flags(int soft_float, ffi_type *arg, + unsigned *loc, unsigned *arg_reg) +{ + unsigned flags = 0; + unsigned index = 0; + + ffi_type *e; + + if (soft_float) + return 0; + + while ((e = arg->elements[index])) + { + /* Align this object. */ + *loc = FFI_ALIGN(*loc, e->alignment); + if (e->type == FFI_TYPE_DOUBLE) + { + /* Already aligned to FFI_SIZEOF_ARG. */ + *arg_reg = *loc / FFI_SIZEOF_ARG; + if (*arg_reg > 7) + break; + flags += (FFI_TYPE_DOUBLE << (*arg_reg * FFI_FLAG_BITS)); + *loc += e->size; + } + else + *loc += e->size; + index++; + } + /* Next Argument register at alignment of FFI_SIZEOF_ARG. */ + *arg_reg = FFI_ALIGN(*loc, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; + + return flags; +} + +static unsigned +calc_n32_return_struct_flags(int soft_float, ffi_type *arg) +{ + unsigned flags = 0; + unsigned small = FFI_TYPE_SMALLSTRUCT; + ffi_type *e; + + /* Returning structures under n32 is a tricky thing. + A struct with only one or two floating point fields + is returned in $f0 (and $f2 if necessary). Any other + struct results at most 128 bits are returned in $2 + (the first 64 bits) and $3 (remainder, if necessary). + Larger structs are handled normally. */ + + if (arg->size > 16) + return 0; + + if (arg->size > 8) + small = FFI_TYPE_SMALLSTRUCT2; + + e = arg->elements[0]; + + if (e->type == FFI_TYPE_DOUBLE) + flags = FFI_TYPE_DOUBLE; + else if (e->type == FFI_TYPE_FLOAT) + flags = FFI_TYPE_FLOAT; + + if (flags && (e = arg->elements[1])) + { + if (e->type == FFI_TYPE_DOUBLE) + flags += FFI_TYPE_DOUBLE << FFI_FLAG_BITS; + else if (e->type == FFI_TYPE_FLOAT) + flags += FFI_TYPE_FLOAT << FFI_FLAG_BITS; + else + return small; + + if (flags && (arg->elements[2])) + { + /* There are three arguments and the first two are + floats! This must be passed the old way. */ + return small; + } + if (soft_float) + flags += FFI_TYPE_STRUCT_SOFT; + } + else + if (!flags) + return small; + + return flags; +} + +#endif + +/* Perform machine dependent cif processing */ +static ffi_status ffi_prep_cif_machdep_int(ffi_cif *cif, unsigned nfixedargs) +{ + cif->flags = 0; + cif->mips_nfixedargs = nfixedargs; + +#ifdef FFI_MIPS_O32 + /* Set the flags necessary for O32 processing. FFI_O32_SOFT_FLOAT + * does not have special handling for floating point args. + */ + + if (cif->rtype->type != FFI_TYPE_STRUCT && cif->abi == FFI_O32) + { + if (cif->nargs > 0 && cif->nargs == nfixedargs) + { + switch ((cif->arg_types)[0]->type) + { + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + cif->flags += (cif->arg_types)[0]->type; + break; + + default: + break; + } + + if (cif->nargs > 1) + { + /* Only handle the second argument if the first + is a float or double. */ + if (cif->flags) + { + switch ((cif->arg_types)[1]->type) + { + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + cif->flags += (cif->arg_types)[1]->type << FFI_FLAG_BITS; + break; + + default: + break; + } + } + } + } + } + + /* Set the return type flag */ + + if (cif->abi == FFI_O32_SOFT_FLOAT) + { + switch (cif->rtype->type) + { + case FFI_TYPE_VOID: + case FFI_TYPE_STRUCT: + cif->flags += cif->rtype->type << (FFI_FLAG_BITS * 2); + break; + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_DOUBLE: + cif->flags += FFI_TYPE_UINT64 << (FFI_FLAG_BITS * 2); + break; + + case FFI_TYPE_FLOAT: + default: + cif->flags += FFI_TYPE_INT << (FFI_FLAG_BITS * 2); + break; + } + } + else + { + /* FFI_O32 */ + switch (cif->rtype->type) + { + case FFI_TYPE_VOID: + case FFI_TYPE_STRUCT: + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + cif->flags += cif->rtype->type << (FFI_FLAG_BITS * 2); + break; + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + cif->flags += FFI_TYPE_UINT64 << (FFI_FLAG_BITS * 2); + break; + + default: + cif->flags += FFI_TYPE_INT << (FFI_FLAG_BITS * 2); + break; + } + } +#endif + +#ifdef FFI_MIPS_N32 + /* Set the flags necessary for N32 processing */ + { + int type; + unsigned arg_reg = 0; + unsigned loc = 0; + unsigned count = (cif->nargs < 8) ? cif->nargs : 8; + unsigned index = 0; + + unsigned struct_flags = 0; + int soft_float = (cif->abi == FFI_N32_SOFT_FLOAT + || cif->abi == FFI_N64_SOFT_FLOAT); + + if (cif->rtype->type == FFI_TYPE_STRUCT) + { + struct_flags = calc_n32_return_struct_flags(soft_float, cif->rtype); + + if (struct_flags == 0) + { + /* This means that the structure is being passed as + a hidden argument */ + + arg_reg = 1; + count = (cif->nargs < 7) ? cif->nargs : 7; + + cif->rstruct_flag = !0; + } + else + cif->rstruct_flag = 0; + } + else + cif->rstruct_flag = 0; + + while (count-- > 0 && arg_reg < 8) + { + type = (cif->arg_types)[index]->type; + + // Pass variadic arguments in integer registers even if they're floats + if (soft_float || index >= nfixedargs) + { + switch (type) + { + case FFI_TYPE_FLOAT: + type = FFI_TYPE_UINT32; + break; + case FFI_TYPE_DOUBLE: + type = FFI_TYPE_UINT64; + break; + default: + break; + } + } + switch (type) + { + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + cif->flags += + ((cif->arg_types)[index]->type << (arg_reg * FFI_FLAG_BITS)); + arg_reg++; + break; + case FFI_TYPE_LONGDOUBLE: + /* Align it. */ + arg_reg = FFI_ALIGN(arg_reg, 2); + /* Treat it as two adjacent doubles. */ + if (soft_float || index >= nfixedargs) + { + arg_reg += 2; + } + else + { + cif->flags += + (FFI_TYPE_DOUBLE << (arg_reg * FFI_FLAG_BITS)); + arg_reg++; + cif->flags += + (FFI_TYPE_DOUBLE << (arg_reg * FFI_FLAG_BITS)); + arg_reg++; + } + break; + + case FFI_TYPE_STRUCT: + loc = arg_reg * FFI_SIZEOF_ARG; + cif->flags += calc_n32_struct_flags(soft_float || index >= nfixedargs, + (cif->arg_types)[index], + &loc, &arg_reg); + break; + + default: + arg_reg++; + break; + } + + index++; + } + + /* Set the return type flag */ + switch (cif->rtype->type) + { + case FFI_TYPE_STRUCT: + { + if (struct_flags == 0) + { + /* The structure is returned through a hidden + first argument. Do nothing, 'cause FFI_TYPE_VOID + is 0 */ + } + else + { + /* The structure is returned via some tricky + mechanism */ + cif->flags += FFI_TYPE_STRUCT << (FFI_FLAG_BITS * 8); + cif->flags += struct_flags << (4 + (FFI_FLAG_BITS * 8)); + } + break; + } + + case FFI_TYPE_VOID: + /* Do nothing, 'cause FFI_TYPE_VOID is 0 */ + break; + + case FFI_TYPE_POINTER: + if (cif->abi == FFI_N32_SOFT_FLOAT || cif->abi == FFI_N32) + cif->flags += FFI_TYPE_SINT32 << (FFI_FLAG_BITS * 8); + else + cif->flags += FFI_TYPE_INT << (FFI_FLAG_BITS * 8); + break; + + case FFI_TYPE_FLOAT: + if (soft_float) + { + cif->flags += FFI_TYPE_SINT32 << (FFI_FLAG_BITS * 8); + break; + } + /* else fall through */ + case FFI_TYPE_DOUBLE: + if (soft_float) + cif->flags += FFI_TYPE_INT << (FFI_FLAG_BITS * 8); + else + cif->flags += cif->rtype->type << (FFI_FLAG_BITS * 8); + break; + + case FFI_TYPE_LONGDOUBLE: + /* Long double is returned as if it were a struct containing + two doubles. */ + if (soft_float) + { + cif->flags += FFI_TYPE_STRUCT << (FFI_FLAG_BITS * 8); + cif->flags += FFI_TYPE_SMALLSTRUCT2 << (4 + (FFI_FLAG_BITS * 8)); + } + else + { + cif->flags += FFI_TYPE_STRUCT << (FFI_FLAG_BITS * 8); + cif->flags += (FFI_TYPE_DOUBLE + + (FFI_TYPE_DOUBLE << FFI_FLAG_BITS)) + << (4 + (FFI_FLAG_BITS * 8)); + } + break; + default: + cif->flags += FFI_TYPE_INT << (FFI_FLAG_BITS * 8); + break; + } + } +#endif + + return FFI_OK; +} + +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + return ffi_prep_cif_machdep_int(cif, cif->nargs); +} + +ffi_status ffi_prep_cif_machdep_var(ffi_cif *cif, + unsigned nfixedargs, + unsigned ntotalargs MAYBE_UNUSED) +{ + return ffi_prep_cif_machdep_int(cif, nfixedargs); +} + +/* Low level routine for calling O32 functions */ +extern int ffi_call_O32(void (*)(char *, extended_cif *, int, int), + extended_cif *, unsigned, + unsigned, unsigned *, void (*)(void), void *closure); + +/* Low level routine for calling N32 functions */ +extern int ffi_call_N32(void (*)(char *, extended_cif *, int, int), + extended_cif *, unsigned, + unsigned, void *, void (*)(void), void *closure); + +void ffi_call_int(ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return */ + /* value address then we need to make one */ + + if ((rvalue == NULL) && + (cif->rtype->type == FFI_TYPE_STRUCT)) + ecif.rvalue = alloca(cif->rtype->size); + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { +#ifdef FFI_MIPS_O32 + case FFI_O32: + case FFI_O32_SOFT_FLOAT: + ffi_call_O32(ffi_prep_args, &ecif, cif->bytes, + cif->flags, ecif.rvalue, fn, closure); + break; +#endif + +#ifdef FFI_MIPS_N32 + case FFI_N32: + case FFI_N32_SOFT_FLOAT: + case FFI_N64: + case FFI_N64_SOFT_FLOAT: + { + int copy_rvalue = 0; + int copy_offset = 0; + char *rvalue_copy = ecif.rvalue; + if (cif->rtype->type == FFI_TYPE_STRUCT && cif->rtype->size < 16) + { + /* For structures smaller than 16 bytes we clobber memory + in 8 byte increments. Make a copy so we don't clobber + the callers memory outside of the struct bounds. */ + rvalue_copy = alloca(16); + copy_rvalue = 1; + } + else if (cif->rtype->type == FFI_TYPE_FLOAT + && (cif->abi == FFI_N64_SOFT_FLOAT + || cif->abi == FFI_N32_SOFT_FLOAT)) + { + rvalue_copy = alloca (8); + copy_rvalue = 1; +#if defined(__MIPSEB__) || defined(_MIPSEB) + copy_offset = 4; +#endif + } + ffi_call_N32(ffi_prep_args, &ecif, cif->bytes, + cif->flags, rvalue_copy, fn, closure); + if (copy_rvalue) + memcpy(ecif.rvalue, rvalue_copy + copy_offset, cif->rtype->size); + } + break; +#endif + + default: + FFI_ASSERT(0); + break; + } +} + +void +ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + ffi_call_int (cif, fn, rvalue, avalue, NULL); +} + +void +ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + ffi_call_int (cif, fn, rvalue, avalue, closure); +} + + +#if FFI_CLOSURES +#if defined(FFI_MIPS_O32) +extern void ffi_closure_O32(void); +extern void ffi_go_closure_O32(void); +#else +extern void ffi_closure_N32(void); +extern void ffi_go_closure_N32(void); +#endif /* FFI_MIPS_O32 */ + +ffi_status +ffi_prep_closure_loc (ffi_closure *closure, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + unsigned int *tramp = (unsigned int *) &closure->tramp[0]; + void * fn; + char *clear_location = (char *) codeloc; + +#if defined(FFI_MIPS_O32) + if (cif->abi != FFI_O32 && cif->abi != FFI_O32_SOFT_FLOAT) + return FFI_BAD_ABI; + fn = ffi_closure_O32; +#else +#if _MIPS_SIM ==_ABIN32 + if (cif->abi != FFI_N32 + && cif->abi != FFI_N32_SOFT_FLOAT) + return FFI_BAD_ABI; +#else + if (cif->abi != FFI_N64 + && cif->abi != FFI_N64_SOFT_FLOAT) + return FFI_BAD_ABI; +#endif + fn = ffi_closure_N32; +#endif /* FFI_MIPS_O32 */ + +#if defined(FFI_MIPS_O32) || (_MIPS_SIM ==_ABIN32) + /* lui $25,high(fn) */ + tramp[0] = 0x3c190000 | ((unsigned)fn >> 16); + /* ori $25,low(fn) */ + tramp[1] = 0x37390000 | ((unsigned)fn & 0xffff); + /* lui $12,high(codeloc) */ + tramp[2] = 0x3c0c0000 | ((unsigned)codeloc >> 16); + /* jr $25 */ +#if !defined(__mips_isa_rev) || (__mips_isa_rev<6) + tramp[3] = 0x03200008; +#else + tramp[3] = 0x03200009; +#endif + /* ori $12,low(codeloc) */ + tramp[4] = 0x358c0000 | ((unsigned)codeloc & 0xffff); +#else + /* N64 has a somewhat larger trampoline. */ + /* lui $25,high(fn) */ + tramp[0] = 0x3c190000 | ((unsigned long)fn >> 48); + /* lui $12,high(codeloc) */ + tramp[1] = 0x3c0c0000 | ((unsigned long)codeloc >> 48); + /* ori $25,mid-high(fn) */ + tramp[2] = 0x37390000 | (((unsigned long)fn >> 32 ) & 0xffff); + /* ori $12,mid-high(codeloc) */ + tramp[3] = 0x358c0000 | (((unsigned long)codeloc >> 32) & 0xffff); + /* dsll $25,$25,16 */ + tramp[4] = 0x0019cc38; + /* dsll $12,$12,16 */ + tramp[5] = 0x000c6438; + /* ori $25,mid-low(fn) */ + tramp[6] = 0x37390000 | (((unsigned long)fn >> 16 ) & 0xffff); + /* ori $12,mid-low(codeloc) */ + tramp[7] = 0x358c0000 | (((unsigned long)codeloc >> 16) & 0xffff); + /* dsll $25,$25,16 */ + tramp[8] = 0x0019cc38; + /* dsll $12,$12,16 */ + tramp[9] = 0x000c6438; + /* ori $25,low(fn) */ + tramp[10] = 0x37390000 | ((unsigned long)fn & 0xffff); + /* jr $25 */ +#if !defined(__mips_isa_rev) || (__mips_isa_rev<6) + tramp[11] = 0x03200008; +#else + tramp[11] = 0x03200009; +#endif + /* ori $12,low(codeloc) */ + tramp[12] = 0x358c0000 | ((unsigned long)codeloc & 0xffff); + +#endif + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + +#if !defined(__FreeBSD__) +#ifdef USE__BUILTIN___CLEAR_CACHE + __builtin___clear_cache(clear_location, clear_location + FFI_TRAMPOLINE_SIZE); +#else + cacheflush (clear_location, FFI_TRAMPOLINE_SIZE, ICACHE); +#endif +#endif /* ! __FreeBSD__ */ + return FFI_OK; +} + +/* + * Decodes the arguments to a function, which will be stored on the + * stack. AR is the pointer to the beginning of the integer arguments + * (and, depending upon the arguments, some floating-point arguments + * as well). FPR is a pointer to the area where floating point + * registers have been saved, if any. + * + * RVALUE is the location where the function return value will be + * stored. CLOSURE is the prepared closure to invoke. + * + * This function should only be called from assembly, which is in + * turn called from a trampoline. + * + * Returns the function return type. + * + * Based on the similar routine for sparc. + */ +int +ffi_closure_mips_inner_O32 (ffi_cif *cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *rvalue, ffi_arg *ar, + double *fpr) +{ + void **avaluep; + ffi_arg *avalue; + ffi_type **arg_types; + int i, avn, argn, seen_int; + + avalue = alloca (cif->nargs * sizeof (ffi_arg)); + avaluep = alloca (cif->nargs * sizeof (ffi_arg)); + + seen_int = (cif->abi == FFI_O32_SOFT_FLOAT) || (cif->mips_nfixedargs != cif->nargs); + argn = 0; + + if ((cif->flags >> (FFI_FLAG_BITS * 2)) == FFI_TYPE_STRUCT) + { + rvalue = (void *)(uintptr_t)ar[0]; + argn = 1; + seen_int = 1; + } + + i = 0; + avn = cif->nargs; + arg_types = cif->arg_types; + + while (i < avn) + { + if (arg_types[i]->alignment == 8 && (argn & 0x1)) + argn++; + if (i < 2 && !seen_int && + (arg_types[i]->type == FFI_TYPE_FLOAT || + arg_types[i]->type == FFI_TYPE_DOUBLE || + arg_types[i]->type == FFI_TYPE_LONGDOUBLE)) + { +#if defined(__MIPSEB__) || defined(_MIPSEB) + if (arg_types[i]->type == FFI_TYPE_FLOAT) + avaluep[i] = ((char *) &fpr[i]) + sizeof (float); + else +#endif + avaluep[i] = (char *) &fpr[i]; + } + else + { + switch (arg_types[i]->type) + { + case FFI_TYPE_SINT8: + avaluep[i] = &avalue[i]; + *(SINT8 *) &avalue[i] = (SINT8) ar[argn]; + break; + + case FFI_TYPE_UINT8: + avaluep[i] = &avalue[i]; + *(UINT8 *) &avalue[i] = (UINT8) ar[argn]; + break; + + case FFI_TYPE_SINT16: + avaluep[i] = &avalue[i]; + *(SINT16 *) &avalue[i] = (SINT16) ar[argn]; + break; + + case FFI_TYPE_UINT16: + avaluep[i] = &avalue[i]; + *(UINT16 *) &avalue[i] = (UINT16) ar[argn]; + break; + + default: + avaluep[i] = (char *) &ar[argn]; + break; + } + seen_int = 1; + } + argn += FFI_ALIGN(arg_types[i]->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; + i++; + } + + /* Invoke the closure. */ + fun(cif, rvalue, avaluep, user_data); + + if (cif->abi == FFI_O32_SOFT_FLOAT) + { + switch (cif->rtype->type) + { + case FFI_TYPE_FLOAT: + return FFI_TYPE_INT; + case FFI_TYPE_DOUBLE: + return FFI_TYPE_UINT64; + default: + return cif->rtype->type; + } + } + else + { + return cif->rtype->type; + } +} + +#if defined(FFI_MIPS_N32) + +static void +copy_struct_N32(char *target, unsigned offset, ffi_abi abi, ffi_type *type, + int argn, unsigned arg_offset, ffi_arg *ar, + ffi_arg *fpr, int soft_float) +{ + ffi_type **elt_typep = type->elements; + while(*elt_typep) + { + ffi_type *elt_type = *elt_typep; + unsigned o; + char *tp; + char *argp; + char *fpp; + + o = FFI_ALIGN(offset, elt_type->alignment); + arg_offset += o - offset; + offset = o; + argn += arg_offset / sizeof(ffi_arg); + arg_offset = arg_offset % sizeof(ffi_arg); + + argp = (char *)(ar + argn); + fpp = (char *)(argn >= 8 ? ar + argn : fpr + argn); + + tp = target + offset; + + if (elt_type->type == FFI_TYPE_DOUBLE && !soft_float) + *(double *)tp = *(double *)fpp; + else + memcpy(tp, argp + arg_offset, elt_type->size); + + offset += elt_type->size; + arg_offset += elt_type->size; + elt_typep++; + argn += arg_offset / sizeof(ffi_arg); + arg_offset = arg_offset % sizeof(ffi_arg); + } +} + +/* + * Decodes the arguments to a function, which will be stored on the + * stack. AR is the pointer to the beginning of the integer + * arguments. FPR is a pointer to the area where floating point + * registers have been saved. + * + * RVALUE is the location where the function return value will be + * stored. CLOSURE is the prepared closure to invoke. + * + * This function should only be called from assembly, which is in + * turn called from a trampoline. + * + * Returns the function return flags. + * + */ +int +ffi_closure_mips_inner_N32 (ffi_cif *cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *rvalue, ffi_arg *ar, + ffi_arg *fpr) +{ + void **avaluep; + ffi_arg *avalue; + ffi_type **arg_types; + int i, avn, argn; + int soft_float; + ffi_arg *argp; + + soft_float = cif->abi == FFI_N64_SOFT_FLOAT + || cif->abi == FFI_N32_SOFT_FLOAT; + avalue = alloca (cif->nargs * sizeof (ffi_arg)); + avaluep = alloca (cif->nargs * sizeof (ffi_arg)); + + argn = 0; + + if (cif->rstruct_flag) + { +#if _MIPS_SIM==_ABIN32 + rvalue = (void *)(UINT32)ar[0]; +#else /* N64 */ + rvalue = (void *)ar[0]; +#endif + argn = 1; + } + + i = 0; + avn = cif->nargs; + arg_types = cif->arg_types; + + while (i < avn) + { + if (arg_types[i]->type == FFI_TYPE_FLOAT + || arg_types[i]->type == FFI_TYPE_DOUBLE + || arg_types[i]->type == FFI_TYPE_LONGDOUBLE) + { + argp = (argn >= 8 || i >= cif->mips_nfixedargs || soft_float) ? ar + argn : fpr + argn; + if ((arg_types[i]->type == FFI_TYPE_LONGDOUBLE) && ((uintptr_t)argp & (arg_types[i]->alignment-1))) + { + argp=(ffi_arg*)FFI_ALIGN(argp,arg_types[i]->alignment); + argn++; + } +#if defined(__MIPSEB__) || defined(_MIPSEB) + if (arg_types[i]->type == FFI_TYPE_FLOAT && argn < 8) + avaluep[i] = ((char *) argp) + sizeof (float); + else +#endif + avaluep[i] = (char *) argp; + } + else + { + unsigned type = arg_types[i]->type; + + if (arg_types[i]->alignment > sizeof(ffi_arg)) + argn = FFI_ALIGN(argn, arg_types[i]->alignment / sizeof(ffi_arg)); + + argp = ar + argn; + + /* The size of a pointer depends on the ABI */ + if (type == FFI_TYPE_POINTER) + type = (cif->abi == FFI_N64 || cif->abi == FFI_N64_SOFT_FLOAT) + ? FFI_TYPE_SINT64 : FFI_TYPE_SINT32; + + if (soft_float && type == FFI_TYPE_FLOAT) + type = FFI_TYPE_UINT32; + + switch (type) + { + case FFI_TYPE_SINT8: + avaluep[i] = &avalue[i]; + *(SINT8 *) &avalue[i] = (SINT8) *argp; + break; + + case FFI_TYPE_UINT8: + avaluep[i] = &avalue[i]; + *(UINT8 *) &avalue[i] = (UINT8) *argp; + break; + + case FFI_TYPE_SINT16: + avaluep[i] = &avalue[i]; + *(SINT16 *) &avalue[i] = (SINT16) *argp; + break; + + case FFI_TYPE_UINT16: + avaluep[i] = &avalue[i]; + *(UINT16 *) &avalue[i] = (UINT16) *argp; + break; + + case FFI_TYPE_SINT32: + avaluep[i] = &avalue[i]; + *(SINT32 *) &avalue[i] = (SINT32) *argp; + break; + + case FFI_TYPE_UINT32: + avaluep[i] = &avalue[i]; + *(UINT32 *) &avalue[i] = (UINT32) *argp; + break; + + case FFI_TYPE_STRUCT: + if (argn < 8) + { + /* Allocate space for the struct as at least part of + it was passed in registers. */ + avaluep[i] = alloca(arg_types[i]->size); + copy_struct_N32(avaluep[i], 0, cif->abi, arg_types[i], + argn, 0, ar, fpr, i >= cif->mips_nfixedargs || soft_float); + + break; + } + /* Else fall through. */ + default: + avaluep[i] = (char *) argp; + break; + } + } + argn += FFI_ALIGN(arg_types[i]->size, sizeof(ffi_arg)) / sizeof(ffi_arg); + i++; + } + + /* Invoke the closure. */ + fun (cif, rvalue, avaluep, user_data); + + return cif->flags >> (FFI_FLAG_BITS * 8); +} + +#endif /* FFI_MIPS_N32 */ + +#if defined(FFI_MIPS_O32) +extern void ffi_closure_O32(void); +extern void ffi_go_closure_O32(void); +#else +extern void ffi_closure_N32(void); +extern void ffi_go_closure_N32(void); +#endif /* FFI_MIPS_O32 */ + +ffi_status +ffi_prep_go_closure (ffi_go_closure* closure, ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*)) +{ + void * fn; + +#if defined(FFI_MIPS_O32) + if (cif->abi != FFI_O32 && cif->abi != FFI_O32_SOFT_FLOAT) + return FFI_BAD_ABI; + fn = ffi_go_closure_O32; +#else +#if _MIPS_SIM ==_ABIN32 + if (cif->abi != FFI_N32 + && cif->abi != FFI_N32_SOFT_FLOAT) + return FFI_BAD_ABI; +#else + if (cif->abi != FFI_N64 + && cif->abi != FFI_N64_SOFT_FLOAT) + return FFI_BAD_ABI; +#endif + fn = ffi_go_closure_N32; +#endif /* FFI_MIPS_O32 */ + + closure->tramp = (void *)fn; + closure->cif = cif; + closure->fun = fun; + + return FFI_OK; +} + +#endif /* FFI_CLOSURES */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/mips/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/mips/ffitarget.h new file mode 100644 index 0000000..fdd5ca9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/mips/ffitarget.h @@ -0,0 +1,244 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 1996-2003 Red Hat, Inc. + Target configuration macros for MIPS. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifdef __linux__ +# include +#elif defined(__rtems__) +/* + * Subprogram calling convention - copied from sgidefs.h + */ +#define _MIPS_SIM_ABI32 1 +#define _MIPS_SIM_NABI32 2 +#define _MIPS_SIM_ABI64 3 +#elif !defined(__OpenBSD__) && !defined(__FreeBSD__) +# include +#endif + +# ifndef _ABIN32 +# define _ABIN32 _MIPS_SIM_NABI32 +# endif +# ifndef _ABI64 +# define _ABI64 _MIPS_SIM_ABI64 +# endif +# ifndef _ABIO32 +# define _ABIO32 _MIPS_SIM_ABI32 +# endif + +#if !defined(_MIPS_SIM) +# error -- something is very wrong -- +#else +# if (_MIPS_SIM==_ABIN32 && defined(_ABIN32)) || (_MIPS_SIM==_ABI64 && defined(_ABI64)) +# define FFI_MIPS_N32 +# else +# if (_MIPS_SIM==_ABIO32 && defined(_ABIO32)) +# define FFI_MIPS_O32 +# else +# error -- this is an unsupported platform -- +# endif +# endif +#endif + +#ifdef FFI_MIPS_O32 +/* O32 stack frames have 32bit integer args */ +# define FFI_SIZEOF_ARG 4 +#else +/* N32 and N64 frames have 64bit integer args */ +# define FFI_SIZEOF_ARG 8 +# if _MIPS_SIM == _ABIN32 +# define FFI_SIZEOF_JAVA_RAW 4 +# endif +#endif + +#define FFI_FLAG_BITS 2 + +/* SGI's strange assembler requires that we multiply by 4 rather + than shift left by FFI_FLAG_BITS */ + +#define FFI_ARGS_D FFI_TYPE_DOUBLE +#define FFI_ARGS_F FFI_TYPE_FLOAT +#define FFI_ARGS_DD FFI_TYPE_DOUBLE * 4 + FFI_TYPE_DOUBLE +#define FFI_ARGS_FF FFI_TYPE_FLOAT * 4 + FFI_TYPE_FLOAT +#define FFI_ARGS_FD FFI_TYPE_DOUBLE * 4 + FFI_TYPE_FLOAT +#define FFI_ARGS_DF FFI_TYPE_FLOAT * 4 + FFI_TYPE_DOUBLE + +/* Needed for N32 structure returns */ +#define FFI_TYPE_SMALLSTRUCT FFI_TYPE_UINT8 +#define FFI_TYPE_SMALLSTRUCT2 FFI_TYPE_SINT8 + +#if 0 +/* The SGI assembler can't handle this.. */ +#define FFI_TYPE_STRUCT_DD (( FFI_ARGS_DD ) << 4) + FFI_TYPE_STRUCT +/* (and so on) */ +#else +/* ...so we calculate these by hand! */ +#define FFI_TYPE_STRUCT_D 61 +#define FFI_TYPE_STRUCT_F 45 +#define FFI_TYPE_STRUCT_DD 253 +#define FFI_TYPE_STRUCT_FF 173 +#define FFI_TYPE_STRUCT_FD 237 +#define FFI_TYPE_STRUCT_DF 189 +#define FFI_TYPE_STRUCT_SMALL 93 +#define FFI_TYPE_STRUCT_SMALL2 109 + +/* and for n32 soft float, add 16 * 2^4 */ +#define FFI_TYPE_STRUCT_D_SOFT 317 +#define FFI_TYPE_STRUCT_F_SOFT 301 +#define FFI_TYPE_STRUCT_DD_SOFT 509 +#define FFI_TYPE_STRUCT_FF_SOFT 429 +#define FFI_TYPE_STRUCT_FD_SOFT 493 +#define FFI_TYPE_STRUCT_DF_SOFT 445 +#define FFI_TYPE_STRUCT_SOFT 16 +#endif + +#ifdef LIBFFI_ASM +#define v0 $2 +#define v1 $3 +#define a0 $4 +#define a1 $5 +#define a2 $6 +#define a3 $7 +#define a4 $8 +#define a5 $9 +#define a6 $10 +#define a7 $11 +#define t0 $8 +#define t1 $9 +#define t2 $10 +#define t3 $11 +#define t4 $12 +#define t5 $13 +#define t6 $14 +#define t7 $15 +#define t8 $24 +#define t9 $25 +#define ra $31 + +#ifdef FFI_MIPS_O32 +# define REG_L lw +# define REG_S sw +# define SUBU subu +# define ADDU addu +# define SRL srl +# define LI li +#else /* !FFI_MIPS_O32 */ +# define REG_L ld +# define REG_S sd +# define SUBU dsubu +# define ADDU daddu +# define SRL dsrl +# define LI dli +# if (_MIPS_SIM==_ABI64) +# define LA dla +# define EH_FRAME_ALIGN 3 +# define FDE_ADDR_BYTES .8byte +# else +# define LA la +# define EH_FRAME_ALIGN 2 +# define FDE_ADDR_BYTES .4byte +# endif /* _MIPS_SIM==_ABI64 */ +#endif /* !FFI_MIPS_O32 */ +#else /* !LIBFFI_ASM */ +# ifdef __GNUC__ +# ifdef FFI_MIPS_O32 +/* O32 stack frames have 32bit integer args */ +typedef unsigned int ffi_arg __attribute__((__mode__(__SI__))); +typedef signed int ffi_sarg __attribute__((__mode__(__SI__))); +#else +/* N32 and N64 frames have 64bit integer args */ +typedef unsigned int ffi_arg __attribute__((__mode__(__DI__))); +typedef signed int ffi_sarg __attribute__((__mode__(__DI__))); +# endif +# else +# ifdef FFI_MIPS_O32 +/* O32 stack frames have 32bit integer args */ +typedef __uint32_t ffi_arg; +typedef __int32_t ffi_sarg; +# else +/* N32 and N64 frames have 64bit integer args */ +typedef __uint64_t ffi_arg; +typedef __int64_t ffi_sarg; +# endif +# endif /* __GNUC__ */ + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_O32, + FFI_N32, + FFI_N64, + FFI_O32_SOFT_FLOAT, + FFI_N32_SOFT_FLOAT, + FFI_N64_SOFT_FLOAT, + FFI_LAST_ABI, + +#ifdef FFI_MIPS_O32 +#ifdef __mips_soft_float + FFI_DEFAULT_ABI = FFI_O32_SOFT_FLOAT +#else + FFI_DEFAULT_ABI = FFI_O32 +#endif +#else +# if _MIPS_SIM==_ABI64 +# ifdef __mips_soft_float + FFI_DEFAULT_ABI = FFI_N64_SOFT_FLOAT +# else + FFI_DEFAULT_ABI = FFI_N64 +# endif +# else +# ifdef __mips_soft_float + FFI_DEFAULT_ABI = FFI_N32_SOFT_FLOAT +# else + FFI_DEFAULT_ABI = FFI_N32 +# endif +# endif +#endif +} ffi_abi; + +#define FFI_EXTRA_CIF_FIELDS unsigned rstruct_flag; unsigned mips_nfixedargs +#define FFI_TARGET_SPECIFIC_VARIADIC +#endif /* !LIBFFI_ASM */ + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_GO_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 + +#if defined(FFI_MIPS_O32) || (_MIPS_SIM ==_ABIN32) +# define FFI_TRAMPOLINE_SIZE 20 +#else +# define FFI_TRAMPOLINE_SIZE 56 +#endif + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/mips/n32.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/mips/n32.S new file mode 100644 index 0000000..1a940b6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/mips/n32.S @@ -0,0 +1,663 @@ +/* ----------------------------------------------------------------------- + n32.S - Copyright (c) 1996, 1998, 2005, 2007, 2009, 2010 Red Hat, Inc. + + MIPS Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + +/* Only build this code if we are compiling for n32 */ + +#if defined(FFI_MIPS_N32) + +#define callback a0 +#define bytes a2 +#define flags a3 +#define raddr a4 +#define fn a5 +#define closure a6 + +/* Note: to keep stack 16 byte aligned we need even number slots + used 9 slots here +*/ +#define SIZEOF_FRAME ( 10 * FFI_SIZEOF_ARG ) + +#ifdef __GNUC__ + .abicalls +#endif +#if !defined(__mips_isa_rev) || (__mips_isa_rev<6) + .set mips4 +#endif + .text + .align 2 + .globl ffi_call_N32 + .ent ffi_call_N32 +ffi_call_N32: +.LFB0: + .frame $fp, SIZEOF_FRAME, ra + .mask 0xc0000000,-FFI_SIZEOF_ARG + .fmask 0x00000000,0 + + # Prologue + SUBU $sp, SIZEOF_FRAME # Frame size +.LCFI00: + REG_S $fp, SIZEOF_FRAME - 2*FFI_SIZEOF_ARG($sp) # Save frame pointer + REG_S ra, SIZEOF_FRAME - 1*FFI_SIZEOF_ARG($sp) # Save return address +.LCFI01: + move $fp, $sp +.LCFI02: + move t9, callback # callback function pointer + REG_S bytes, 2*FFI_SIZEOF_ARG($fp) # bytes + REG_S flags, 3*FFI_SIZEOF_ARG($fp) # flags + REG_S raddr, 4*FFI_SIZEOF_ARG($fp) # raddr + REG_S fn, 5*FFI_SIZEOF_ARG($fp) # fn + REG_S closure, 6*FFI_SIZEOF_ARG($fp) # closure + + # Allocate at least 4 words in the argstack + move v0, bytes + bge bytes, 4 * FFI_SIZEOF_ARG, bigger + LI v0, 4 * FFI_SIZEOF_ARG + b sixteen + + bigger: + ADDU t4, v0, 2 * FFI_SIZEOF_ARG -1 # make sure it is aligned + and v0, t4, -2 * FFI_SIZEOF_ARG # to a proper boundry. + +sixteen: + SUBU $sp, $sp, v0 # move the stack pointer to reflect the + # arg space + + move a0, $sp # 4 * FFI_SIZEOF_ARG + ADDU a3, $fp, 3 * FFI_SIZEOF_ARG + + # Call ffi_prep_args + jal t9 + + # Copy the stack pointer to t9 + move t9, $sp + + # Fix the stack if there are more than 8 64bit slots worth + # of arguments. + + # Load the number of bytes + REG_L t6, 2*FFI_SIZEOF_ARG($fp) + + # Is it bigger than 8 * FFI_SIZEOF_ARG? + daddiu t8, t6, -(8 * FFI_SIZEOF_ARG) + bltz t8, loadregs + + ADDU t9, t9, t8 + +loadregs: + + REG_L t6, 3*FFI_SIZEOF_ARG($fp) # load the flags word into t6. + +#ifdef __mips_soft_float + REG_L a0, 0*FFI_SIZEOF_ARG(t9) + REG_L a1, 1*FFI_SIZEOF_ARG(t9) + REG_L a2, 2*FFI_SIZEOF_ARG(t9) + REG_L a3, 3*FFI_SIZEOF_ARG(t9) + REG_L a4, 4*FFI_SIZEOF_ARG(t9) + REG_L a5, 5*FFI_SIZEOF_ARG(t9) + REG_L a6, 6*FFI_SIZEOF_ARG(t9) + REG_L a7, 7*FFI_SIZEOF_ARG(t9) +#else + and t4, t6, ((1< +#include + +/* Only build this code if we are compiling for o32 */ + +#if defined(FFI_MIPS_O32) + +#define callback a0 +#define bytes a2 +#define flags a3 + +#define SIZEOF_FRAME (4 * FFI_SIZEOF_ARG + 2 * FFI_SIZEOF_ARG) +#define A3_OFF (SIZEOF_FRAME + 3 * FFI_SIZEOF_ARG) +#define FP_OFF (SIZEOF_FRAME - 2 * FFI_SIZEOF_ARG) +#define RA_OFF (SIZEOF_FRAME - 1 * FFI_SIZEOF_ARG) + + .abicalls + .text + .align 2 + .globl ffi_call_O32 + .ent ffi_call_O32 +ffi_call_O32: +$LFB0: + # Prologue + SUBU $sp, SIZEOF_FRAME # Frame size +$LCFI00: + REG_S $fp, FP_OFF($sp) # Save frame pointer +$LCFI01: + REG_S ra, RA_OFF($sp) # Save return address +$LCFI02: + move $fp, $sp + +$LCFI03: + move t9, callback # callback function pointer + REG_S flags, A3_OFF($fp) # flags + + # Allocate at least 4 words in the argstack + LI v0, 4 * FFI_SIZEOF_ARG + blt bytes, v0, sixteen + + ADDU v0, bytes, 7 # make sure it is aligned + and v0, -8 # to an 8 byte boundry + +sixteen: + SUBU $sp, v0 # move the stack pointer to reflect the + # arg space + + ADDU a0, $sp, 4 * FFI_SIZEOF_ARG + + jalr t9 + + REG_L t0, A3_OFF($fp) # load the flags word + SRL t2, t0, 4 # shift our arg info + and t0, ((1<<4)-1) # mask out the return type + + ADDU $sp, 4 * FFI_SIZEOF_ARG # adjust $sp to new args + +#ifndef __mips_soft_float + bnez t0, pass_d # make it quick for int +#endif + REG_L a0, 0*FFI_SIZEOF_ARG($sp) # just go ahead and load the + REG_L a1, 1*FFI_SIZEOF_ARG($sp) # four regs. + REG_L a2, 2*FFI_SIZEOF_ARG($sp) + REG_L a3, 3*FFI_SIZEOF_ARG($sp) + b call_it + +#ifndef __mips_soft_float +pass_d: + bne t0, FFI_ARGS_D, pass_f + l.d $f12, 0*FFI_SIZEOF_ARG($sp) # load $fp regs from args + REG_L a2, 2*FFI_SIZEOF_ARG($sp) # passing a double + REG_L a3, 3*FFI_SIZEOF_ARG($sp) + b call_it + +pass_f: + bne t0, FFI_ARGS_F, pass_d_d + l.s $f12, 0*FFI_SIZEOF_ARG($sp) # load $fp regs from args + REG_L a1, 1*FFI_SIZEOF_ARG($sp) # passing a float + REG_L a2, 2*FFI_SIZEOF_ARG($sp) + REG_L a3, 3*FFI_SIZEOF_ARG($sp) + b call_it + +pass_d_d: + bne t0, FFI_ARGS_DD, pass_f_f + l.d $f12, 0*FFI_SIZEOF_ARG($sp) # load $fp regs from args + l.d $f14, 2*FFI_SIZEOF_ARG($sp) # passing two doubles + b call_it + +pass_f_f: + bne t0, FFI_ARGS_FF, pass_d_f + l.s $f12, 0*FFI_SIZEOF_ARG($sp) # load $fp regs from args + l.s $f14, 1*FFI_SIZEOF_ARG($sp) # passing two floats + REG_L a2, 2*FFI_SIZEOF_ARG($sp) + REG_L a3, 3*FFI_SIZEOF_ARG($sp) + b call_it + +pass_d_f: + bne t0, FFI_ARGS_DF, pass_f_d + l.d $f12, 0*FFI_SIZEOF_ARG($sp) # load $fp regs from args + l.s $f14, 2*FFI_SIZEOF_ARG($sp) # passing double and float + REG_L a3, 3*FFI_SIZEOF_ARG($sp) + b call_it + +pass_f_d: + # assume that the only other combination must be float then double + # bne t0, FFI_ARGS_F_D, call_it + l.s $f12, 0*FFI_SIZEOF_ARG($sp) # load $fp regs from args + l.d $f14, 2*FFI_SIZEOF_ARG($sp) # passing double and float +#endif + +call_it: + # Load the static chain pointer + REG_L t7, SIZEOF_FRAME + 6*FFI_SIZEOF_ARG($fp) + + # Load the function pointer + REG_L t9, SIZEOF_FRAME + 5*FFI_SIZEOF_ARG($fp) + + # If the return value pointer is NULL, assume no return value. + REG_L t1, SIZEOF_FRAME + 4*FFI_SIZEOF_ARG($fp) + beqz t1, noretval + + bne t2, FFI_TYPE_INT, retlonglong + jalr t9 + REG_L t0, SIZEOF_FRAME + 4*FFI_SIZEOF_ARG($fp) + REG_S v0, 0(t0) + b epilogue + +retlonglong: + # Really any 64-bit int, signed or not. + bne t2, FFI_TYPE_UINT64, retfloat + jalr t9 + REG_L t0, SIZEOF_FRAME + 4*FFI_SIZEOF_ARG($fp) + REG_S v1, 4(t0) + REG_S v0, 0(t0) + b epilogue + +retfloat: + bne t2, FFI_TYPE_FLOAT, retdouble + jalr t9 + REG_L t0, SIZEOF_FRAME + 4*FFI_SIZEOF_ARG($fp) +#ifndef __mips_soft_float + s.s $f0, 0(t0) +#else + REG_S v0, 0(t0) +#endif + b epilogue + +retdouble: + bne t2, FFI_TYPE_DOUBLE, noretval + jalr t9 + REG_L t0, SIZEOF_FRAME + 4*FFI_SIZEOF_ARG($fp) +#ifndef __mips_soft_float + s.d $f0, 0(t0) +#else + REG_S v1, 4(t0) + REG_S v0, 0(t0) +#endif + b epilogue + +noretval: + jalr t9 + + # Epilogue +epilogue: + move $sp, $fp + REG_L $fp, FP_OFF($sp) # Restore frame pointer + REG_L ra, RA_OFF($sp) # Restore return address + ADDU $sp, SIZEOF_FRAME # Fix stack pointer + j ra + +$LFE0: + .end ffi_call_O32 + + +/* ffi_closure_O32. Expects address of the passed-in ffi_closure + in t4 ($12). Stores any arguments passed in registers onto the + stack, then calls ffi_closure_mips_inner_O32, which + then decodes them. + + Stack layout: + + 3 - a3 save + 2 - a2 save + 1 - a1 save + 0 - a0 save, original sp + -1 - ra save + -2 - fp save + -3 - $16 (s0) save + -4 - cprestore + -5 - return value high (v1) + -6 - return value low (v0) + -7 - f14 (le high, be low) + -8 - f14 (le low, be high) + -9 - f12 (le high, be low) + -10 - f12 (le low, be high) + -11 - Called function a5 save + -12 - Called function a4 save + -13 - Called function a3 save + -14 - Called function a2 save + -15 - Called function a1 save + -16 - Called function a0 save, our sp and fp point here + */ + +#define SIZEOF_FRAME2 (16 * FFI_SIZEOF_ARG) +#define A3_OFF2 (SIZEOF_FRAME2 + 3 * FFI_SIZEOF_ARG) +#define A2_OFF2 (SIZEOF_FRAME2 + 2 * FFI_SIZEOF_ARG) +#define A1_OFF2 (SIZEOF_FRAME2 + 1 * FFI_SIZEOF_ARG) +#define A0_OFF2 (SIZEOF_FRAME2 + 0 * FFI_SIZEOF_ARG) +#define RA_OFF2 (SIZEOF_FRAME2 - 1 * FFI_SIZEOF_ARG) +#define FP_OFF2 (SIZEOF_FRAME2 - 2 * FFI_SIZEOF_ARG) +#define S0_OFF2 (SIZEOF_FRAME2 - 3 * FFI_SIZEOF_ARG) +#define GP_OFF2 (SIZEOF_FRAME2 - 4 * FFI_SIZEOF_ARG) +#define V1_OFF2 (SIZEOF_FRAME2 - 5 * FFI_SIZEOF_ARG) +#define V0_OFF2 (SIZEOF_FRAME2 - 6 * FFI_SIZEOF_ARG) +#define FA_1_1_OFF2 (SIZEOF_FRAME2 - 7 * FFI_SIZEOF_ARG) +#define FA_1_0_OFF2 (SIZEOF_FRAME2 - 8 * FFI_SIZEOF_ARG) +#define FA_0_1_OFF2 (SIZEOF_FRAME2 - 9 * FFI_SIZEOF_ARG) +#define FA_0_0_OFF2 (SIZEOF_FRAME2 - 10 * FFI_SIZEOF_ARG) +#define CALLED_A5_OFF2 (SIZEOF_FRAME2 - 11 * FFI_SIZEOF_ARG) +#define CALLED_A4_OFF2 (SIZEOF_FRAME2 - 12 * FFI_SIZEOF_ARG) + + .text + + .align 2 + .globl ffi_go_closure_O32 + .ent ffi_go_closure_O32 +ffi_go_closure_O32: +$LFB1: + # Prologue + .frame $fp, SIZEOF_FRAME2, ra + .set noreorder + .cpload t9 + .set reorder + SUBU $sp, SIZEOF_FRAME2 + .cprestore GP_OFF2 +$LCFI10: + + REG_S $16, S0_OFF2($sp) # Save s0 + REG_S $fp, FP_OFF2($sp) # Save frame pointer + REG_S ra, RA_OFF2($sp) # Save return address +$LCFI11: + + move $fp, $sp +$LCFI12: + + REG_S a0, A0_OFF2($fp) + REG_S a1, A1_OFF2($fp) + REG_S a2, A2_OFF2($fp) + REG_S a3, A3_OFF2($fp) + + # Load ABI enum to s0 + REG_L $16, 4($15) # cif + REG_L $16, 0($16) # abi is first member. + + li $13, 1 # FFI_O32 + bne $16, $13, 1f # Skip fp save if FFI_O32_SOFT_FLOAT + +#ifndef __mips_soft_float + # Store all possible float/double registers. + s.d $f12, FA_0_0_OFF2($fp) + s.d $f14, FA_1_0_OFF2($fp) +#endif +1: + # prepare arguments for ffi_closure_mips_inner_O32 + REG_L a0, 4($15) # cif + REG_L a1, 8($15) # fun + move a2, $15 # user_data = go closure + addu a3, $fp, V0_OFF2 # rvalue + + addu t9, $fp, A0_OFF2 # ar + REG_S t9, CALLED_A4_OFF2($fp) + + addu t9, $fp, FA_0_0_OFF2 #fpr + REG_S t9, CALLED_A5_OFF2($fp) + + b $do_closure + +$LFE1: + .end ffi_go_closure_O32 + + .align 2 + .globl ffi_closure_O32 + .ent ffi_closure_O32 +ffi_closure_O32: +$LFB2: + # Prologue + .frame $fp, SIZEOF_FRAME2, ra + .set noreorder + .cpload t9 + .set reorder + SUBU $sp, SIZEOF_FRAME2 + .cprestore GP_OFF2 +$LCFI20: + REG_S $16, S0_OFF2($sp) # Save s0 + REG_S $fp, FP_OFF2($sp) # Save frame pointer + REG_S ra, RA_OFF2($sp) # Save return address +$LCFI21: + move $fp, $sp + +$LCFI22: + # Store all possible argument registers. If there are more than + # four arguments, then they are stored above where we put a3. + REG_S a0, A0_OFF2($fp) + REG_S a1, A1_OFF2($fp) + REG_S a2, A2_OFF2($fp) + REG_S a3, A3_OFF2($fp) + + # Load ABI enum to s0 + REG_L $16, 20($12) # cif pointer follows tramp. + REG_L $16, 0($16) # abi is first member. + + li $13, 1 # FFI_O32 + bne $16, $13, 1f # Skip fp save if FFI_O32_SOFT_FLOAT + +#ifndef __mips_soft_float + # Store all possible float/double registers. + s.d $f12, FA_0_0_OFF2($fp) + s.d $f14, FA_1_0_OFF2($fp) +#endif +1: + # prepare arguments for ffi_closure_mips_inner_O32 + REG_L a0, 20($12) # cif pointer follows tramp. + REG_L a1, 24($12) # fun + REG_L a2, 28($12) # user_data + addu a3, $fp, V0_OFF2 # rvalue + + addu t9, $fp, A0_OFF2 # ar + REG_S t9, CALLED_A4_OFF2($fp) + + addu t9, $fp, FA_0_0_OFF2 #fpr + REG_S t9, CALLED_A5_OFF2($fp) + +$do_closure: + la t9, ffi_closure_mips_inner_O32 + # Call ffi_closure_mips_inner_O32 to do the work. + jalr t9 + + # Load the return value into the appropriate register. + move $8, $2 + li $9, FFI_TYPE_VOID + beq $8, $9, closure_done + + li $13, 1 # FFI_O32 + bne $16, $13, 1f # Skip fp restore if FFI_O32_SOFT_FLOAT + +#ifndef __mips_soft_float + li $9, FFI_TYPE_FLOAT + l.s $f0, V0_OFF2($fp) + beq $8, $9, closure_done + + li $9, FFI_TYPE_DOUBLE + l.d $f0, V0_OFF2($fp) + beq $8, $9, closure_done +#endif +1: + REG_L $3, V1_OFF2($fp) + REG_L $2, V0_OFF2($fp) + +closure_done: + # Epilogue + move $sp, $fp + REG_L $16, S0_OFF2($sp) # Restore s0 + REG_L $fp, FP_OFF2($sp) # Restore frame pointer + REG_L ra, RA_OFF2($sp) # Restore return address + ADDU $sp, SIZEOF_FRAME2 + j ra +$LFE2: + .end ffi_closure_O32 + +/* DWARF-2 unwind info. */ + + .section .eh_frame,"a",@progbits +$Lframe0: + .4byte $LECIE0-$LSCIE0 # Length of Common Information Entry +$LSCIE0: + .4byte 0x0 # CIE Identifier Tag + .byte 0x1 # CIE Version + .ascii "zR\0" # CIE Augmentation + .uleb128 0x1 # CIE Code Alignment Factor + .sleb128 4 # CIE Data Alignment Factor + .byte 0x1f # CIE RA Column + .uleb128 0x1 # Augmentation size + .byte 0x00 # FDE Encoding (absptr) + .byte 0xc # DW_CFA_def_cfa + .uleb128 0x1d + .uleb128 0x0 + .align 2 +$LECIE0: + +$LSFDE0: + .4byte $LEFDE0-$LASFDE0 # FDE Length +$LASFDE0: + .4byte $LASFDE0-$Lframe0 # FDE CIE offset + .4byte $LFB0 # FDE initial location + .4byte $LFE0-$LFB0 # FDE address range + .uleb128 0x0 # Augmentation size + .byte 0x4 # DW_CFA_advance_loc4 + .4byte $LCFI00-$LFB0 + .byte 0xe # DW_CFA_def_cfa_offset + .uleb128 0x18 + .byte 0x4 # DW_CFA_advance_loc4 + .4byte $LCFI01-$LCFI00 + .byte 0x11 # DW_CFA_offset_extended_sf + .uleb128 0x1e # $fp + .sleb128 -2 # SIZEOF_FRAME2 - 2*FFI_SIZEOF_ARG($sp) + .byte 0x11 # DW_CFA_offset_extended_sf + .uleb128 0x1f # $ra + .sleb128 -1 # SIZEOF_FRAME2 - 1*FFI_SIZEOF_ARG($sp) + .byte 0x4 # DW_CFA_advance_loc4 + .4byte $LCFI02-$LCFI01 + .byte 0xc # DW_CFA_def_cfa + .uleb128 0x1e + .uleb128 0x18 + .align 2 +$LEFDE0: + +$LSFDE1: + .4byte $LEFDE1-$LASFDE1 # FDE Length +$LASFDE1: + .4byte $LASFDE1-$Lframe0 # FDE CIE offset + .4byte $LFB1 # FDE initial location + .4byte $LFE1-$LFB1 # FDE address range + .uleb128 0x0 # Augmentation size + .byte 0x4 # DW_CFA_advance_loc4 + .4byte $LCFI10-$LFB1 + .byte 0xe # DW_CFA_def_cfa_offset + .uleb128 SIZEOF_FRAME2 + .byte 0x4 # DW_CFA_advance_loc4 + .4byte $LCFI11-$LCFI10 + .byte 0x11 # DW_CFA_offset_extended_sf + .uleb128 0x10 # $16 + .sleb128 -3 # SIZEOF_FRAME2 - 3*FFI_SIZEOF_ARG($sp) + .byte 0x11 # DW_CFA_offset_extended_sf + .uleb128 0x1e # $fp + .sleb128 -2 # SIZEOF_FRAME2 - 2*FFI_SIZEOF_ARG($sp) + .byte 0x11 # DW_CFA_offset_extended_sf + .uleb128 0x1f # $ra + .sleb128 -1 # SIZEOF_FRAME2 - 1*FFI_SIZEOF_ARG($sp) + .byte 0x4 # DW_CFA_advance_loc4 + .4byte $LCFI12-$LCFI11 + .byte 0xc # DW_CFA_def_cfa + .uleb128 0x1e + .uleb128 SIZEOF_FRAME2 + .align 2 +$LEFDE1: + +$LSFDE2: + .4byte $LEFDE2-$LASFDE2 # FDE Length +$LASFDE2: + .4byte $LASFDE2-$Lframe0 # FDE CIE offset + .4byte $LFB2 # FDE initial location + .4byte $LFE2-$LFB2 # FDE address range + .uleb128 0x0 # Augmentation size + .byte 0x4 # DW_CFA_advance_loc4 + .4byte $LCFI20-$LFB2 + .byte 0xe # DW_CFA_def_cfa_offset + .uleb128 SIZEOF_FRAME2 + .byte 0x4 # DW_CFA_advance_loc4 + .4byte $LCFI21-$LCFI20 + .byte 0x11 # DW_CFA_offset_extended_sf + .uleb128 0x10 # $16 + .sleb128 -3 # SIZEOF_FRAME2 - 3*FFI_SIZEOF_ARG($sp) + .byte 0x11 # DW_CFA_offset_extended_sf + .uleb128 0x1e # $fp + .sleb128 -2 # SIZEOF_FRAME2 - 2*FFI_SIZEOF_ARG($sp) + .byte 0x11 # DW_CFA_offset_extended_sf + .uleb128 0x1f # $ra + .sleb128 -1 # SIZEOF_FRAME2 - 1*FFI_SIZEOF_ARG($sp) + .byte 0x4 # DW_CFA_advance_loc4 + .4byte $LCFI22-$LCFI21 + .byte 0xc # DW_CFA_def_cfa + .uleb128 0x1e + .uleb128 SIZEOF_FRAME2 + .align 2 +$LEFDE2: + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/moxie/eabi.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/moxie/eabi.S new file mode 100644 index 0000000..10cfb04 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/moxie/eabi.S @@ -0,0 +1,101 @@ +/* ----------------------------------------------------------------------- + eabi.S - Copyright (c) 2012, 2013 Anthony Green + + Moxie Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + + .globl ffi_prep_args_EABI + + .text + .p2align 4 + .globl ffi_call_EABI + .type ffi_call_EABI, @function + + # $r0 : ffi_prep_args + # $r1 : &ecif + # $r2 : cif->bytes + # $r3 : fig->flags + # $r4 : ecif.rvalue + # $r5 : fn + +ffi_call_EABI: + push $sp, $r6 + push $sp, $r7 + push $sp, $r8 + dec $sp, 24 + + /* Store incoming args on stack. */ + sto.l 0($sp), $r0 /* ffi_prep_args */ + sto.l 4($sp), $r1 /* ecif */ + sto.l 8($sp), $r2 /* bytes */ + sto.l 12($sp), $r3 /* flags */ + sto.l 16($sp), $r4 /* &rvalue */ + sto.l 20($sp), $r5 /* fn */ + + /* Call ffi_prep_args. */ + mov $r6, $r4 /* Save result buffer */ + mov $r7, $r5 /* Save the target fn */ + mov $r8, $r3 /* Save the flags */ + sub $sp, $r2 /* Allocate stack space */ + mov $r0, $sp /* We can stomp over $r0 */ + /* $r1 is already set up */ + jsra ffi_prep_args + + /* Load register arguments. */ + ldo.l $r0, 0($sp) + ldo.l $r1, 4($sp) + ldo.l $r2, 8($sp) + ldo.l $r3, 12($sp) + ldo.l $r4, 16($sp) + ldo.l $r5, 20($sp) + + /* Call the target function. */ + jsr $r7 + + ldi.l $r7, 0xffffffff + cmp $r8, $r7 + beq retstruct + + ldi.l $r7, 4 + cmp $r8, $r7 + bgt ret2reg + + st.l ($r6), $r0 + jmpa retdone + +ret2reg: + st.l ($r6), $r0 + sto.l 4($r6), $r1 + +retstruct: +retdone: + /* Return. */ + ldo.l $r6, -4($fp) + ldo.l $r7, -8($fp) + ldo.l $r8, -12($fp) + ret + .size ffi_call_EABI, .-ffi_call_EABI + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/moxie/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/moxie/ffi.c new file mode 100644 index 0000000..16d2bb3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/moxie/ffi.c @@ -0,0 +1,285 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (C) 2012, 2013, 2018 Anthony Green + + Moxie Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments */ + +void *ffi_prep_args(char *stack, extended_cif *ecif) +{ + register unsigned int i; + register void **p_argv; + register char *argp; + register ffi_type **p_arg; + register int count = 0; + + p_argv = ecif->avalue; + argp = stack; + + if (ecif->cif->rtype->type == FFI_TYPE_STRUCT) + { + *(void **) argp = ecif->rvalue; + argp += 4; + } + + for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; + (i != 0); + i--, p_arg++) + { + size_t z; + + z = (*p_arg)->size; + + if ((*p_arg)->type == FFI_TYPE_STRUCT) + { + z = sizeof(void*); + *(void **) argp = *p_argv; + } + else if (z < sizeof(int)) + { + z = sizeof(int); + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); + break; + + default: + FFI_ASSERT(0); + } + } + else if (z == sizeof(int)) + { + *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); + } + else + { + memcpy(argp, *p_argv, z); + } + p_argv++; + argp += z; + count += z; + } + + return (stack + ((count > 24) ? 24 : FFI_ALIGN_DOWN(count, 8))); +} + +/* Perform machine dependent cif processing */ +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + if (cif->rtype->type == FFI_TYPE_STRUCT) + cif->flags = -1; + else + cif->flags = cif->rtype->size; + + cif->bytes = FFI_ALIGN (cif->bytes, 8); + + return FFI_OK; +} + +extern void ffi_call_EABI(void *(*)(char *, extended_cif *), + extended_cif *, + unsigned, unsigned, + unsigned *, + void (*fn)(void)); + +void ffi_call(ffi_cif *cif, + void (*fn)(void), + void *rvalue, + void **avalue) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return */ + /* value address then we need to make one */ + + if ((rvalue == NULL) && + (cif->rtype->type == FFI_TYPE_STRUCT)) + { + ecif.rvalue = alloca(cif->rtype->size); + } + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_EABI: + ffi_call_EABI(ffi_prep_args, &ecif, cif->bytes, + cif->flags, ecif.rvalue, fn); + break; + default: + FFI_ASSERT(0); + break; + } +} + +void ffi_closure_eabi (unsigned arg1, unsigned arg2, unsigned arg3, + unsigned arg4, unsigned arg5, unsigned arg6) +{ + /* This function is called by a trampoline. The trampoline stows a + pointer to the ffi_closure object in $r12. We must save this + pointer in a place that will persist while we do our work. */ + register ffi_closure *creg __asm__ ("$r12"); + ffi_closure *closure = creg; + + /* Arguments that don't fit in registers are found on the stack + at a fixed offset above the current frame pointer. */ + register char *frame_pointer __asm__ ("$fp"); + + /* Pointer to a struct return value. */ + void *struct_rvalue = (void *) arg1; + + /* 6 words reserved for register args + 3 words from jsr */ + char *stack_args = frame_pointer + 9*4; + + /* Lay the register arguments down in a continuous chunk of memory. */ + unsigned register_args[6] = + { arg1, arg2, arg3, arg4, arg5, arg6 }; + char *register_args_ptr = (char *) register_args; + + ffi_cif *cif = closure->cif; + ffi_type **arg_types = cif->arg_types; + void **avalue = alloca (cif->nargs * sizeof(void *)); + char *ptr = (char *) register_args; + int i; + + /* preserve struct type return pointer passing */ + if ((cif->rtype != NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { + ptr += 4; + register_args_ptr = (char *)®ister_args[1]; + } + + /* Find the address of each argument. */ + for (i = 0; i < cif->nargs; i++) + { + switch (arg_types[i]->type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + avalue[i] = ptr + 3; + break; + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + avalue[i] = ptr + 2; + break; + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_FLOAT: + case FFI_TYPE_POINTER: + avalue[i] = ptr; + break; + case FFI_TYPE_STRUCT: + avalue[i] = *(void**)ptr; + break; + default: + /* This is an 8-byte value. */ + if (ptr == (char *) ®ister_args[5]) + { + /* The value is split across two locations */ + unsigned *ip = alloca(8); + avalue[i] = ip; + ip[0] = *(unsigned *) ptr; + ip[1] = *(unsigned *) stack_args; + } + else + { + avalue[i] = ptr; + } + ptr += 4; + break; + } + ptr += 4; + + /* If we've handled more arguments than fit in registers, + start looking at the those passed on the stack. */ + if (ptr == (char *) ®ister_args[6]) + ptr = stack_args; + else if (ptr == (char *) ®ister_args[7]) + ptr = stack_args + 4; + } + + /* Invoke the closure. */ + if (cif->rtype && (cif->rtype->type == FFI_TYPE_STRUCT)) + { + (closure->fun) (cif, struct_rvalue, avalue, closure->user_data); + } + else + { + /* Allocate space for the return value and call the function. */ + long long rvalue; + (closure->fun) (cif, &rvalue, avalue, closure->user_data); + asm ("mov $r12, %0\n ld.l $r0, ($r12)\n ldo.l $r1, 4($r12)" : : "r" (&rvalue)); + } +} + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + unsigned short *tramp = (unsigned short *) &closure->tramp[0]; + unsigned long fn = (long) ffi_closure_eabi; + unsigned long cls = (long) codeloc; + + if (cif->abi != FFI_EABI) + return FFI_BAD_ABI; + + fn = (unsigned long) ffi_closure_eabi; + + tramp[0] = 0x01e0; /* ldi.l $r12, .... */ + tramp[1] = cls >> 16; + tramp[2] = cls & 0xffff; + tramp[3] = 0x1a00; /* jmpa .... */ + tramp[4] = fn >> 16; + tramp[5] = fn & 0xffff; + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + return FFI_OK; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/moxie/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/moxie/ffitarget.h new file mode 100644 index 0000000..623e3ec --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/moxie/ffitarget.h @@ -0,0 +1,52 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012, 2013 Anthony Green + Target configuration macros for Moxie + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +/* ---- System specific configurations ----------------------------------- */ + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_EABI, + FFI_DEFAULT_ABI = FFI_EABI, + FFI_LAST_ABI = FFI_DEFAULT_ABI + 1 +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 + +/* Trampolines are 12-bytes long. See ffi_prep_closure_loc. */ +#define FFI_TRAMPOLINE_SIZE (12) + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/nios2/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/nios2/ffi.c new file mode 100644 index 0000000..721080d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/nios2/ffi.c @@ -0,0 +1,304 @@ +/* libffi support for Altera Nios II. + + Copyright (c) 2013 Mentor Graphics. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + + +#include +#include + +#include + +/* The Nios II Processor Reference Handbook defines the procedure call + ABI as follows. + + Arguments are passed as if a structure containing the types of + the arguments were constructed. The first 16 bytes are passed in r4 + through r7, the remainder on the stack. The first 16 bytes of a function + taking variable arguments are passed in r4-r7 in the same way. + + Return values of types up to 8 bytes are returned in r2 and r3. For + return values greater than 8 bytes, the caller must allocate memory for + the result and pass the address as if it were argument 0. + + While this isn't specified explicitly in the ABI documentation, GCC + promotes integral arguments smaller than int size to 32 bits. + + Also of note, the ABI specifies that all structure objects are + aligned to 32 bits even if all their fields have a smaller natural + alignment. See FFI_AGGREGATE_ALIGNMENT. */ + + +/* Declare the assembly language hooks. */ + +extern UINT64 ffi_call_sysv (void (*) (char *, extended_cif *), + extended_cif *, + unsigned, + void (*fn) (void)); +extern void ffi_closure_sysv (void); + +/* Perform machine-dependent cif processing. */ + +ffi_status ffi_prep_cif_machdep (ffi_cif *cif) +{ + /* We always want at least 16 bytes in the parameter block since it + simplifies the low-level call function. Also round the parameter + block size up to a multiple of 4 bytes to preserve + 32-bit alignment of the stack pointer. */ + if (cif->bytes < 16) + cif->bytes = 16; + else + cif->bytes = (cif->bytes + 3) & ~3; + + return FFI_OK; +} + + +/* ffi_prep_args is called by the assembly routine to transfer arguments + to the stack using the pointers in the ecif array. + Note that the stack buffer is big enough to fit all the arguments, + but the first 16 bytes will be copied to registers for the actual + call. */ + +void ffi_prep_args (char *stack, extended_cif *ecif) +{ + char *argp = stack; + unsigned int i; + + /* The implicit return value pointer is passed as if it were a hidden + first argument. */ + if (ecif->cif->rtype->type == FFI_TYPE_STRUCT + && ecif->cif->rtype->size > 8) + { + (*(void **) argp) = ecif->rvalue; + argp += 4; + } + + for (i = 0; i < ecif->cif->nargs; i++) + { + void *avalue = ecif->avalue[i]; + ffi_type *atype = ecif->cif->arg_types[i]; + size_t size = atype->size; + size_t alignment = atype->alignment; + + /* Align argp as appropriate for the argument type. */ + if ((alignment - 1) & (unsigned) argp) + argp = (char *) FFI_ALIGN (argp, alignment); + + /* Copy the argument, promoting integral types smaller than a + word to word size. */ + if (size < sizeof (int)) + { + size = sizeof (int); + switch (atype->type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int) *(SINT8 *) avalue; + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int) *(UINT8 *) avalue; + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int) *(SINT16 *) avalue; + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int) *(UINT16 *) avalue; + break; + + case FFI_TYPE_STRUCT: + memcpy (argp, avalue, atype->size); + break; + + default: + FFI_ASSERT(0); + } + } + else if (size == sizeof (int)) + *(unsigned int *) argp = (unsigned int) *(UINT32 *) avalue; + else + memcpy (argp, avalue, size); + argp += size; + } +} + + +/* Call FN using the prepared CIF. RVALUE points to space allocated by + the caller for the return value, and AVALUE is an array of argument + pointers. */ + +void ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue) +{ + + extended_cif ecif; + UINT64 result; + + /* If bigret is true, this is the case where a return value of larger + than 8 bytes is handled by being passed by reference as an implicit + argument. */ + int bigret = (cif->rtype->type == FFI_TYPE_STRUCT + && cif->rtype->size > 8); + + ecif.cif = cif; + ecif.avalue = avalue; + + /* Allocate space for return value if this is the pass-by-reference case + and the caller did not provide a buffer. */ + if (rvalue == NULL && bigret) + ecif.rvalue = alloca (cif->rtype->size); + else + ecif.rvalue = rvalue; + + result = ffi_call_sysv (ffi_prep_args, &ecif, cif->bytes, fn); + + /* Now result contains the 64 bit contents returned from fn in + r2 and r3. Copy the value of the appropriate size to the user-provided + rvalue buffer. */ + if (rvalue && !bigret) + switch (cif->rtype->size) + { + case 1: + *(UINT8 *)rvalue = (UINT8) result; + break; + case 2: + *(UINT16 *)rvalue = (UINT16) result; + break; + case 4: + *(UINT32 *)rvalue = (UINT32) result; + break; + case 8: + *(UINT64 *)rvalue = (UINT64) result; + break; + default: + memcpy (rvalue, (void *)&result, cif->rtype->size); + break; + } +} + +/* This function is invoked from the closure trampoline to invoke + CLOSURE with argument block ARGS. Parse ARGS according to + CLOSURE->cfi and invoke CLOSURE->fun. */ + +static UINT64 +ffi_closure_helper (unsigned char *args, + ffi_closure *closure) +{ + ffi_cif *cif = closure->cif; + unsigned char *argp = args; + void **parsed_args = alloca (cif->nargs * sizeof (void *)); + UINT64 result; + void *retptr; + unsigned int i; + + /* First figure out what to do about the return type. If this is the + big-structure-return case, the first arg is the hidden return buffer + allocated by the caller. */ + if (cif->rtype->type == FFI_TYPE_STRUCT + && cif->rtype->size > 8) + { + retptr = *((void **) argp); + argp += 4; + } + else + retptr = (void *) &result; + + /* Fill in the array of argument pointers. */ + for (i = 0; i < cif->nargs; i++) + { + size_t size = cif->arg_types[i]->size; + size_t alignment = cif->arg_types[i]->alignment; + + /* Align argp as appropriate for the argument type. */ + if ((alignment - 1) & (unsigned) argp) + argp = (char *) FFI_ALIGN (argp, alignment); + + /* Arguments smaller than an int are promoted to int. */ + if (size < sizeof (int)) + size = sizeof (int); + + /* Store the pointer. */ + parsed_args[i] = argp; + argp += size; + } + + /* Call the user-supplied function. */ + (closure->fun) (cif, retptr, parsed_args, closure->user_data); + return result; +} + + +/* Initialize CLOSURE with a trampoline to call FUN with + CIF and USER_DATA. */ +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun) (ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + unsigned int *tramp = (unsigned int *) &closure->tramp[0]; + int i; + + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + /* The trampoline looks like: + movhi r8, %hi(ffi_closure_sysv) + ori r8, r8, %lo(ffi_closure_sysv) + movhi r9, %hi(ffi_closure_helper) + ori r0, r9, %lo(ffi_closure_helper) + movhi r10, %hi(closure) + ori r10, r10, %lo(closure) + jmp r8 + and then ffi_closure_sysv retrieves the closure pointer out of r10 + in addition to the arguments passed in the normal way for the call, + and invokes ffi_closure_helper. We encode the pointer to + ffi_closure_helper in the trampoline because making a PIC call + to it in ffi_closure_sysv would be messy (it would have to indirect + through the GOT). */ + +#define HI(x) ((((unsigned int) (x)) >> 16) & 0xffff) +#define LO(x) (((unsigned int) (x)) & 0xffff) + tramp[0] = (0 << 27) | (8 << 22) | (HI (ffi_closure_sysv) << 6) | 0x34; + tramp[1] = (8 << 27) | (8 << 22) | (LO (ffi_closure_sysv) << 6) | 0x14; + tramp[2] = (0 << 27) | (9 << 22) | (HI (ffi_closure_helper) << 6) | 0x34; + tramp[3] = (9 << 27) | (9 << 22) | (LO (ffi_closure_helper) << 6) | 0x14; + tramp[4] = (0 << 27) | (10 << 22) | (HI (closure) << 6) | 0x34; + tramp[5] = (10 << 27) | (10 << 22) | (LO (closure) << 6) | 0x14; + tramp[6] = (8 << 27) | (0x0d << 11) | 0x3a; +#undef HI +#undef LO + + /* Flush the caches. + See Example 9-4 in the Nios II Software Developer's Handbook. */ + for (i = 0; i < 7; i++) + asm volatile ("flushd 0(%0); flushi %0" :: "r"(tramp + i) : "memory"); + asm volatile ("flushp" ::: "memory"); + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + return FFI_OK; +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/nios2/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/nios2/ffitarget.h new file mode 100644 index 0000000..134d118 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/nios2/ffitarget.h @@ -0,0 +1,52 @@ +/* libffi target includes for Altera Nios II. + + Copyright (c) 2013 Mentor Graphics. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; +#endif + +/* Structures have a 4-byte alignment even if all the fields have lesser + alignment requirements. */ +#define FFI_AGGREGATE_ALIGNMENT 4 + +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 28 /* 7 instructions */ +#define FFI_NATIVE_RAW_API 0 + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/nios2/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/nios2/sysv.S new file mode 100644 index 0000000..75f442b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/nios2/sysv.S @@ -0,0 +1,136 @@ +/* Low-level libffi support for Altera Nios II. + + Copyright (c) 2013 Mentor Graphics. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + +/* This function is declared on the C side as + + extern UINT64 ffi_call_sysv (void (*arghook) (char *, extended_cif *), + extended_cif *ecif, + unsigned nbytes, + void (*fn) (void)); + + On input, the arguments appear as + r4 = arghook + r5 = ecif + r6 = nbytes + r7 = fn +*/ + + .section .text + .align 2 + .global ffi_call_sysv + .type ffi_call_sysv, @function + +ffi_call_sysv: + .cfi_startproc + + /* Create the stack frame, saving r16 so we can use it locally. */ + addi sp, sp, -12 + .cfi_def_cfa_offset 12 + stw ra, 8(sp) + stw fp, 4(sp) + stw r16, 0(sp) + .cfi_offset 31, -4 + .cfi_offset 28, -8 + .cfi_offset 16, -12 + mov fp, sp + .cfi_def_cfa_register 28 + mov r16, r7 + + /* Adjust the stack pointer to create the argument buffer + nbytes long. */ + sub sp, sp, r6 + + /* Call the arghook function. */ + mov r2, r4 /* fn */ + mov r4, sp /* argbuffer */ + callr r2 /* r5 already contains ecif */ + + /* Pop off the first 16 bytes of the argument buffer on the stack, + transferring the contents to the argument registers. */ + ldw r4, 0(sp) + ldw r5, 4(sp) + ldw r6, 8(sp) + ldw r7, 12(sp) + addi sp, sp, 16 + + /* Call the user function, which leaves its result in r2 and r3. */ + callr r16 + + /* Pop off the stack frame. */ + mov sp, fp + ldw ra, 8(sp) + ldw fp, 4(sp) + ldw r16, 0(sp) + addi sp, sp, 12 + ret + .cfi_endproc + .size ffi_call_sysv, .-ffi_call_sysv + + +/* Closure trampolines jump here after putting the C helper address + in r9 and the closure pointer in r10. The user-supplied arguments + to the closure are in the normal places, in r4-r7 and on the + stack. Push the register arguments on the stack too and then call the + C helper function to deal with them. */ + + .section .text + .align 2 + .global ffi_closure_sysv + .type ffi_closure_sysv, @function + +ffi_closure_sysv: + .cfi_startproc + + /* Create the stack frame, pushing the register args on the stack + just below the stack args. This is the same trick illustrated + in Figure 7-3 in the Nios II Processor Reference Handbook, used + for variable arguments and structures passed by value. */ + addi sp, sp, -20 + .cfi_def_cfa_offset 20 + stw ra, 0(sp) + .cfi_offset 31, -20 + stw r4, 4(sp) + .cfi_offset 4, -16 + stw r5, 8(sp) + .cfi_offset 5, -12 + stw r6, 12(sp) + .cfi_offset 6, -8 + stw r7, 16(sp) + .cfi_offset 7, -4 + + /* Call the helper. + r4 = pointer to arguments on stack + r5 = closure pointer (loaded in r10 by the trampoline) + r9 = address of helper function (loaded by trampoline) */ + addi r4, sp, 4 + mov r5, r10 + callr r9 + + /* Pop the stack and return. */ + ldw ra, 0(sp) + addi sp, sp, 20 + .cfi_def_cfa_offset -20 + ret + .cfi_endproc + .size ffi_closure_sysv, .-ffi_closure_sysv + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/or1k/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/or1k/ffi.c new file mode 100644 index 0000000..2bad938 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/or1k/ffi.c @@ -0,0 +1,328 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2014 Sebastian Macke + + OpenRISC Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include "ffi_common.h" + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments */ + +void* ffi_prep_args(char *stack, extended_cif *ecif) +{ + char *stacktemp = stack; + int i, s; + ffi_type **arg; + int count = 0; + int nfixedargs; + + nfixedargs = ecif->cif->nfixedargs; + arg = ecif->cif->arg_types; + void **argv = ecif->avalue; + + if (ecif->cif->rtype->type == FFI_TYPE_STRUCT) + { + *(void **) stack = ecif->rvalue; + stack += 4; + count = 4; + } + for(i=0; icif->nargs; i++) + { + + /* variadic args are saved on stack */ + if ((nfixedargs == 0) && (count < 24)) + { + count = 24; + stack = stacktemp + 24; + } + nfixedargs--; + + s = 4; + switch((*arg)->type) + { + case FFI_TYPE_STRUCT: + *(void **)stack = *argv; + break; + + case FFI_TYPE_SINT8: + *(signed int *) stack = (signed int)*(SINT8 *)(* argv); + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) stack = (unsigned int)*(UINT8 *)(* argv); + break; + + case FFI_TYPE_SINT16: + *(signed int *) stack = (signed int)*(SINT16 *)(* argv); + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) stack = (unsigned int)*(UINT16 *)(* argv); + break; + + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_FLOAT: + case FFI_TYPE_POINTER: + *(int *)stack = *(int*)(*argv); + break; + + default: /* 8 byte types */ + if (count == 20) /* never split arguments */ + { + stack += 4; + count += 4; + } + s = (*arg)->size; + memcpy(stack, *argv, s); + break; + } + + stack += s; + count += s; + argv++; + arg++; + } + return stacktemp + ((count>24)?24:0); +} + +extern void ffi_call_SYSV(unsigned, + extended_cif *, + void *(*)(int *, extended_cif *), + unsigned *, + void (*fn)(void), + unsigned); + + +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + int i; + int size; + ffi_type **arg; + + /* Calculate size to allocate on stack */ + + for(i = 0, arg = cif->arg_types, size=0; i < cif->nargs; i++, arg++) + { + if ((*arg)->type == FFI_TYPE_STRUCT) + size += 4; + else + if ((*arg)->size <= 4) + size += 4; + else + size += 8; + } + + /* for variadic functions more space is needed on the stack */ + if (cif->nargs != cif->nfixedargs) + size += 24; + + if (cif->rtype->type == FFI_TYPE_STRUCT) + size += 4; + + + extended_cif ecif; + ecif.cif = cif; + ecif.avalue = avalue; + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_SYSV: + ffi_call_SYSV(size, &ecif, ffi_prep_args, rvalue, fn, cif->flags); + break; + default: + FFI_ASSERT(0); + break; + } +} + + +void ffi_closure_SYSV(unsigned long r3, unsigned long r4, unsigned long r5, + unsigned long r6, unsigned long r7, unsigned long r8) +{ + register int *sp __asm__ ("r17"); + register int *r13 __asm__ ("r13"); + + ffi_closure* closure = (ffi_closure*) r13; + char *stack_args = sp; + + /* Lay the register arguments down in a continuous chunk of memory. */ + unsigned register_args[6] = + { r3, r4, r5, r6, r7, r8 }; + + /* Pointer to a struct return value. */ + void *struct_rvalue = (void *) r3; + + ffi_cif *cif = closure->cif; + ffi_type **arg_types = cif->arg_types; + void **avalue = alloca (cif->nargs * sizeof(void *)); + char *ptr = (char *) register_args; + int count = 0; + int nfixedargs = cif->nfixedargs; + int i; + + /* preserve struct type return pointer passing */ + + if ((cif->rtype != NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) + { + ptr += 4; + count = 4; + } + + /* Find the address of each argument. */ + for (i = 0; i < cif->nargs; i++) + { + + /* variadic args are saved on stack */ + if ((nfixedargs == 0) && (count < 24)) + { + ptr = stack_args; + count = 24; + } + nfixedargs--; + + switch (arg_types[i]->type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + avalue[i] = ptr + 3; + break; + + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + avalue[i] = ptr + 2; + break; + + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_FLOAT: + case FFI_TYPE_POINTER: + avalue[i] = ptr; + break; + + case FFI_TYPE_STRUCT: + avalue[i] = *(void**)ptr; + break; + + default: + /* 8-byte values */ + + /* arguments are never splitted */ + if (ptr == ®ister_args[5]) + ptr = stack_args; + avalue[i] = ptr; + ptr += 4; + count += 4; + break; + } + ptr += 4; + count += 4; + + /* If we've handled more arguments than fit in registers, + start looking at the those passed on the stack. */ + + if (count == 24) + ptr = stack_args; + } + + if (cif->rtype && (cif->rtype->type == FFI_TYPE_STRUCT)) + { + (closure->fun) (cif, struct_rvalue, avalue, closure->user_data); + } else + { + long long rvalue; + (closure->fun) (cif, &rvalue, avalue, closure->user_data); + if (cif->rtype) + asm ("l.ori r12, %0, 0x0\n l.lwz r11, 0(r12)\n l.lwz r12, 4(r12)" : : "r" (&rvalue)); + } +} + + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + unsigned short *tramp = (unsigned short *) closure->tramp; + unsigned long fn = (unsigned long) ffi_closure_SYSV; + unsigned long cls = (unsigned long) codeloc; + + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + closure->cif = cif; + closure->user_data = user_data; + closure->fun = fun; + + /* write pointers to temporary registers */ + tramp[0] = (0x6 << 10) | (13 << 5); /* l.movhi r13, ... */ + tramp[1] = cls >> 16; + tramp[2] = (0x2a << 10) | (13 << 5) | 13; /* l.ori r13, r13, ... */ + tramp[3] = cls & 0xFFFF; + + tramp[4] = (0x6 << 10) | (15 << 5); /* l.movhi r15, ... */ + tramp[5] = fn >> 16; + tramp[6] = (0x2a << 10) | (15 << 5) | 15; /* l.ori r15, r15 ... */ + tramp[7] = fn & 0xFFFF; + + tramp[8] = (0x11 << 10); /* l.jr r15 */ + tramp[9] = 15 << 11; + + tramp[10] = (0x2a << 10) | (17 << 5) | 1; /* l.ori r17, r1, ... */ + tramp[11] = 0x0; + + return FFI_OK; +} + + +ffi_status ffi_prep_cif_machdep (ffi_cif *cif) +{ + cif->flags = 0; + + /* structures are returned as pointers */ + if (cif->rtype->type == FFI_TYPE_STRUCT) + cif->flags = FFI_TYPE_STRUCT; + else + if (cif->rtype->size > 4) + cif->flags = FFI_TYPE_UINT64; + + cif->nfixedargs = cif->nargs; + + return FFI_OK; +} + + +ffi_status ffi_prep_cif_machdep_var(ffi_cif *cif, + unsigned int nfixedargs, unsigned int ntotalargs) +{ + ffi_status status; + + status = ffi_prep_cif_machdep (cif); + cif->nfixedargs = nfixedargs; + return status; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/or1k/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/or1k/ffitarget.h new file mode 100644 index 0000000..e55da28 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/or1k/ffitarget.h @@ -0,0 +1,58 @@ +/* ----------------------------------------------------------------------- + ffitarget.h - Copyright (c) 2014 Sebastian Macke + + OpenRISC Target configuration macros + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +/* ---- System specific configurations ----------------------------------- */ + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 +#define FFI_TRAMPOLINE_SIZE (24) + +#define FFI_TARGET_SPECIFIC_VARIADIC 1 +#define FFI_EXTRA_CIF_FIELDS unsigned nfixedargs; + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/or1k/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/or1k/sysv.S new file mode 100644 index 0000000..df6570b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/or1k/sysv.S @@ -0,0 +1,107 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2014 Sebastian Macke + + OpenRISC Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + +.text + .globl ffi_call_SYSV + .type ffi_call_SYSV, @function +/* + r3: size to allocate on stack + r4: extended cif structure + r5: function pointer ffi_prep_args + r6: ret address + r7: function to call + r8: flag for return type +*/ + +ffi_call_SYSV: + /* Store registers used on stack */ + l.sw -4(r1), r9 /* return address */ + l.sw -8(r1), r1 /* stack address */ + l.sw -12(r1), r14 /* callee saved registers */ + l.sw -16(r1), r16 + l.sw -20(r1), r18 + l.sw -24(r1), r20 + + l.ori r14, r1, 0x0 /* save stack pointer */ + l.addi r1, r1, -24 + + l.ori r16, r7, 0x0 /* save function address */ + l.ori r18, r6, 0x0 /* save ret address */ + l.ori r20, r8, 0x0 /* save flag */ + + l.sub r1, r1, r3 /* reserve space on stack */ + + /* Call ffi_prep_args */ + l.ori r3, r1, 0x0 /* first argument stack address, second already ecif */ + l.jalr r5 + l.nop + + /* Load register arguments and call*/ + + l.lwz r3, 0(r1) + l.lwz r4, 4(r1) + l.lwz r5, 8(r1) + l.lwz r6, 12(r1) + l.lwz r7, 16(r1) + l.lwz r8, 20(r1) + l.ori r1, r11, 0x0 /* new stack pointer */ + l.jalr r16 + l.nop + + /* handle return values */ + + l.sfeqi r20, FFI_TYPE_STRUCT + l.bf ret /* structs don't return an rvalue */ + l.nop + + /* copy ret address */ + + l.sfeqi r20, FFI_TYPE_UINT64 + l.bnf four_byte_ret /* 8 byte value is returned */ + l.nop + + l.sw 4(r18), r12 + +four_byte_ret: + l.sw 0(r18), r11 + +ret: + /* return */ + l.ori r1, r14, 0x0 /* reset stack pointer */ + l.lwz r9, -4(r1) + l.lwz r1, -8(r1) + l.lwz r14, -12(r1) + l.lwz r16, -16(r1) + l.lwz r18, -20(r1) + l.lwz r20, -24(r1) + l.jr r9 + l.nop + +.size ffi_call_SYSV, .-ffi_call_SYSV diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/ffi.c new file mode 100644 index 0000000..95e6694 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/ffi.c @@ -0,0 +1,674 @@ +/* ----------------------------------------------------------------------- + ffi.c - (c) 2011 Anthony Green + (c) 2008 Red Hat, Inc. + (c) 2006 Free Software Foundation, Inc. + (c) 2003-2004 Randolph Chung + + HPPA Foreign Function Interface + HP-UX PA ABI support + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include +#include + +#define ROUND_UP(v, a) (((size_t)(v) + (a) - 1) & ~((a) - 1)) + +#define MIN_STACK_SIZE 64 +#define FIRST_ARG_SLOT 9 +#define DEBUG_LEVEL 0 + +#define fldw(addr, fpreg) \ + __asm__ volatile ("fldw 0(%0), %%" #fpreg "L" : : "r"(addr) : #fpreg) +#define fstw(fpreg, addr) \ + __asm__ volatile ("fstw %%" #fpreg "L, 0(%0)" : : "r"(addr)) +#define fldd(addr, fpreg) \ + __asm__ volatile ("fldd 0(%0), %%" #fpreg : : "r"(addr) : #fpreg) +#define fstd(fpreg, addr) \ + __asm__ volatile ("fstd %%" #fpreg "L, 0(%0)" : : "r"(addr)) + +#define debug(lvl, x...) do { if (lvl <= DEBUG_LEVEL) { printf(x); } } while (0) + +static inline int ffi_struct_type(ffi_type *t) +{ + size_t sz = t->size; + + /* Small structure results are passed in registers, + larger ones are passed by pointer. Note that + small structures of size 2, 4 and 8 differ from + the corresponding integer types in that they have + different alignment requirements. */ + + if (sz <= 1) + return FFI_TYPE_UINT8; + else if (sz == 2) + return FFI_TYPE_SMALL_STRUCT2; + else if (sz == 3) + return FFI_TYPE_SMALL_STRUCT3; + else if (sz == 4) + return FFI_TYPE_SMALL_STRUCT4; + else if (sz == 5) + return FFI_TYPE_SMALL_STRUCT5; + else if (sz == 6) + return FFI_TYPE_SMALL_STRUCT6; + else if (sz == 7) + return FFI_TYPE_SMALL_STRUCT7; + else if (sz <= 8) + return FFI_TYPE_SMALL_STRUCT8; + else + return FFI_TYPE_STRUCT; /* else, we pass it by pointer. */ +} + +/* PA has a downward growing stack, which looks like this: + + Offset + [ Variable args ] + SP = (4*(n+9)) arg word N + ... + SP-52 arg word 4 + [ Fixed args ] + SP-48 arg word 3 + SP-44 arg word 2 + SP-40 arg word 1 + SP-36 arg word 0 + [ Frame marker ] + ... + SP-20 RP + SP-4 previous SP + + The first four argument words on the stack are reserved for use by + the callee. Instead, the general and floating registers replace + the first four argument slots. Non FP arguments are passed solely + in the general registers. FP arguments are passed in both general + and floating registers when using libffi. + + Non-FP 32-bit args are passed in gr26, gr25, gr24 and gr23. + Non-FP 64-bit args are passed in register pairs, starting + on an odd numbered register (i.e. r25+r26 and r23+r24). + FP 32-bit arguments are passed in fr4L, fr5L, fr6L and fr7L. + FP 64-bit arguments are passed in fr5 and fr7. + + The registers are allocated in the same manner as stack slots. + This allows the callee to save its arguments on the stack if + necessary: + + arg word 3 -> gr23 or fr7L + arg word 2 -> gr24 or fr6L or fr7R + arg word 1 -> gr25 or fr5L + arg word 0 -> gr26 or fr4L or fr5R + + Note that fr4R and fr6R are never used for arguments (i.e., + doubles are not passed in fr4 or fr6). + + The rest of the arguments are passed on the stack starting at SP-52, + but 64-bit arguments need to be aligned to an 8-byte boundary + + This means we can have holes either in the register allocation, + or in the stack. */ + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments + + The following code will put everything into the stack frame + (which was allocated by the asm routine), and on return + the asm routine will load the arguments that should be + passed by register into the appropriate registers + + NOTE: We load floating point args in this function... that means we + assume gcc will not mess with fp regs in here. */ + +void ffi_prep_args_pa32(UINT32 *stack, extended_cif *ecif, unsigned bytes) +{ + register unsigned int i; + register ffi_type **p_arg; + register void **p_argv; + unsigned int slot = FIRST_ARG_SLOT; + char *dest_cpy; + size_t len; + + debug(1, "%s: stack = %p, ecif = %p, bytes = %u\n", __FUNCTION__, stack, + ecif, bytes); + + p_arg = ecif->cif->arg_types; + p_argv = ecif->avalue; + + for (i = 0; i < ecif->cif->nargs; i++) + { + int type = (*p_arg)->type; + + switch (type) + { + case FFI_TYPE_SINT8: + *(SINT32 *)(stack - slot) = *(SINT8 *)(*p_argv); + break; + + case FFI_TYPE_UINT8: + *(UINT32 *)(stack - slot) = *(UINT8 *)(*p_argv); + break; + + case FFI_TYPE_SINT16: + *(SINT32 *)(stack - slot) = *(SINT16 *)(*p_argv); + break; + + case FFI_TYPE_UINT16: + *(UINT32 *)(stack - slot) = *(UINT16 *)(*p_argv); + break; + + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_POINTER: + debug(3, "Storing UINT32 %u in slot %u\n", *(UINT32 *)(*p_argv), + slot); + *(UINT32 *)(stack - slot) = *(UINT32 *)(*p_argv); + break; + + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + /* Align slot for 64-bit type. */ + slot += (slot & 1) ? 1 : 2; + *(UINT64 *)(stack - slot) = *(UINT64 *)(*p_argv); + break; + + case FFI_TYPE_FLOAT: + /* First 4 args go in fr4L - fr7L. */ + debug(3, "Storing UINT32(float) in slot %u\n", slot); + *(UINT32 *)(stack - slot) = *(UINT32 *)(*p_argv); + switch (slot - FIRST_ARG_SLOT) + { + /* First 4 args go in fr4L - fr7L. */ + case 0: fldw(stack - slot, fr4); break; + case 1: fldw(stack - slot, fr5); break; + case 2: fldw(stack - slot, fr6); break; + case 3: fldw(stack - slot, fr7); break; + } + break; + + case FFI_TYPE_DOUBLE: + /* Align slot for 64-bit type. */ + slot += (slot & 1) ? 1 : 2; + debug(3, "Storing UINT64(double) at slot %u\n", slot); + *(UINT64 *)(stack - slot) = *(UINT64 *)(*p_argv); + switch (slot - FIRST_ARG_SLOT) + { + /* First 2 args go in fr5, fr7. */ + case 1: fldd(stack - slot, fr5); break; + case 3: fldd(stack - slot, fr7); break; + } + break; + +#ifdef PA_HPUX + case FFI_TYPE_LONGDOUBLE: + /* Long doubles are passed in the same manner as structures + larger than 8 bytes. */ + *(UINT32 *)(stack - slot) = (UINT32)(*p_argv); + break; +#endif + + case FFI_TYPE_STRUCT: + + /* Structs smaller or equal than 4 bytes are passed in one + register. Structs smaller or equal 8 bytes are passed in two + registers. Larger structures are passed by pointer. */ + + len = (*p_arg)->size; + if (len <= 4) + { + dest_cpy = (char *)(stack - slot) + 4 - len; + memcpy(dest_cpy, (char *)*p_argv, len); + } + else if (len <= 8) + { + slot += (slot & 1) ? 1 : 2; + dest_cpy = (char *)(stack - slot) + 8 - len; + memcpy(dest_cpy, (char *)*p_argv, len); + } + else + *(UINT32 *)(stack - slot) = (UINT32)(*p_argv); + break; + + default: + FFI_ASSERT(0); + } + + slot++; + p_arg++; + p_argv++; + } + + /* Make sure we didn't mess up and scribble on the stack. */ + { + unsigned int n; + + debug(5, "Stack setup:\n"); + for (n = 0; n < (bytes + 3) / 4; n++) + { + if ((n%4) == 0) { debug(5, "\n%08x: ", (unsigned int)(stack - n)); } + debug(5, "%08x ", *(stack - n)); + } + debug(5, "\n"); + } + + FFI_ASSERT(slot * 4 <= bytes); + + return; +} + +static void ffi_size_stack_pa32(ffi_cif *cif) +{ + ffi_type **ptr; + int i; + int z = 0; /* # stack slots */ + + for (ptr = cif->arg_types, i = 0; i < cif->nargs; ptr++, i++) + { + int type = (*ptr)->type; + + switch (type) + { + case FFI_TYPE_DOUBLE: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + z += 2 + (z & 1); /* must start on even regs, so we may waste one */ + break; + +#ifdef PA_HPUX + case FFI_TYPE_LONGDOUBLE: +#endif + case FFI_TYPE_STRUCT: + z += 1; /* pass by ptr, callee will copy */ + break; + + default: /* <= 32-bit values */ + z++; + } + } + + /* We can fit up to 6 args in the default 64-byte stack frame, + if we need more, we need more stack. */ + if (z <= 6) + cif->bytes = MIN_STACK_SIZE; /* min stack size */ + else + cif->bytes = 64 + ROUND_UP((z - 6) * sizeof(UINT32), MIN_STACK_SIZE); + + debug(3, "Calculated stack size is %u bytes\n", cif->bytes); +} + +/* Perform machine dependent cif processing. */ +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + /* Set the return type flag */ + switch (cif->rtype->type) + { + case FFI_TYPE_VOID: + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + cif->flags = (unsigned) cif->rtype->type; + break; + +#ifdef PA_HPUX + case FFI_TYPE_LONGDOUBLE: + /* Long doubles are treated like a structure. */ + cif->flags = FFI_TYPE_STRUCT; + break; +#endif + + case FFI_TYPE_STRUCT: + /* For the return type we have to check the size of the structures. + If the size is smaller or equal 4 bytes, the result is given back + in one register. If the size is smaller or equal 8 bytes than we + return the result in two registers. But if the size is bigger than + 8 bytes, we work with pointers. */ + cif->flags = ffi_struct_type(cif->rtype); + break; + + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + cif->flags = FFI_TYPE_UINT64; + break; + + default: + cif->flags = FFI_TYPE_INT; + break; + } + + /* Lucky us, because of the unique PA ABI we get to do our + own stack sizing. */ + switch (cif->abi) + { + case FFI_PA32: + ffi_size_stack_pa32(cif); + break; + + default: + FFI_ASSERT(0); + break; + } + + return FFI_OK; +} + +extern void ffi_call_pa32(void (*)(UINT32 *, extended_cif *, unsigned), + extended_cif *, unsigned, unsigned, unsigned *, + void (*fn)(void)); + +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return + value address then we need to make one. */ + + if (rvalue == NULL +#ifdef PA_HPUX + && (cif->rtype->type == FFI_TYPE_STRUCT + || cif->rtype->type == FFI_TYPE_LONGDOUBLE)) +#else + && cif->rtype->type == FFI_TYPE_STRUCT) +#endif + { + ecif.rvalue = alloca(cif->rtype->size); + } + else + ecif.rvalue = rvalue; + + + switch (cif->abi) + { + case FFI_PA32: + debug(3, "Calling ffi_call_pa32: ecif=%p, bytes=%u, flags=%u, rvalue=%p, fn=%p\n", &ecif, cif->bytes, cif->flags, ecif.rvalue, (void *)fn); + ffi_call_pa32(ffi_prep_args_pa32, &ecif, cif->bytes, + cif->flags, ecif.rvalue, fn); + break; + + default: + FFI_ASSERT(0); + break; + } +} + +#if FFI_CLOSURES +/* This is more-or-less an inverse of ffi_call -- we have arguments on + the stack, and we need to fill them into a cif structure and invoke + the user function. This really ought to be in asm to make sure + the compiler doesn't do things we don't expect. */ +ffi_status ffi_closure_inner_pa32(ffi_closure *closure, UINT32 *stack) +{ + ffi_cif *cif; + void **avalue; + void *rvalue; + /* Functions can return up to 64-bits in registers. Return address + must be double word aligned. */ + union { double rd; UINT32 ret[2]; } u; + ffi_type **p_arg; + char *tmp; + int i, avn; + unsigned int slot = FIRST_ARG_SLOT; + register UINT32 r28 asm("r28"); + ffi_closure *c = (ffi_closure *)FFI_RESTORE_PTR (closure); + + cif = closure->cif; + + /* If returning via structure, callee will write to our pointer. */ + if (cif->flags == FFI_TYPE_STRUCT) + rvalue = (void *)r28; + else + rvalue = &u; + + avalue = (void **)alloca(cif->nargs * FFI_SIZEOF_ARG); + avn = cif->nargs; + p_arg = cif->arg_types; + + for (i = 0; i < avn; i++) + { + int type = (*p_arg)->type; + + switch (type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_POINTER: + avalue[i] = (char *)(stack - slot) + sizeof(UINT32) - (*p_arg)->size; + break; + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + slot += (slot & 1) ? 1 : 2; + avalue[i] = (void *)(stack - slot); + break; + + case FFI_TYPE_FLOAT: +#ifdef PA_LINUX + /* The closure call is indirect. In Linux, floating point + arguments in indirect calls with a prototype are passed + in the floating point registers instead of the general + registers. So, we need to replace what was previously + stored in the current slot with the value in the + corresponding floating point register. */ + switch (slot - FIRST_ARG_SLOT) + { + case 0: fstw(fr4, (void *)(stack - slot)); break; + case 1: fstw(fr5, (void *)(stack - slot)); break; + case 2: fstw(fr6, (void *)(stack - slot)); break; + case 3: fstw(fr7, (void *)(stack - slot)); break; + } +#endif + avalue[i] = (void *)(stack - slot); + break; + + case FFI_TYPE_DOUBLE: + slot += (slot & 1) ? 1 : 2; +#ifdef PA_LINUX + /* See previous comment for FFI_TYPE_FLOAT. */ + switch (slot - FIRST_ARG_SLOT) + { + case 1: fstd(fr5, (void *)(stack - slot)); break; + case 3: fstd(fr7, (void *)(stack - slot)); break; + } +#endif + avalue[i] = (void *)(stack - slot); + break; + +#ifdef PA_HPUX + case FFI_TYPE_LONGDOUBLE: + /* Long doubles are treated like a big structure. */ + avalue[i] = (void *) *(stack - slot); + break; +#endif + + case FFI_TYPE_STRUCT: + /* Structs smaller or equal than 4 bytes are passed in one + register. Structs smaller or equal 8 bytes are passed in two + registers. Larger structures are passed by pointer. */ + if((*p_arg)->size <= 4) + { + avalue[i] = (void *)(stack - slot) + sizeof(UINT32) - + (*p_arg)->size; + } + else if ((*p_arg)->size <= 8) + { + slot += (slot & 1) ? 1 : 2; + avalue[i] = (void *)(stack - slot) + sizeof(UINT64) - + (*p_arg)->size; + } + else + avalue[i] = (void *) *(stack - slot); + break; + + default: + FFI_ASSERT(0); + } + + slot++; + p_arg++; + } + + /* Invoke the closure. */ + (c->fun) (cif, rvalue, avalue, c->user_data); + + debug(3, "after calling function, ret[0] = %08x, ret[1] = %08x\n", u.ret[0], + u.ret[1]); + + /* Store the result using the lower 2 bytes of the flags. */ + switch (cif->flags) + { + case FFI_TYPE_UINT8: + *(stack - FIRST_ARG_SLOT) = (UINT8)(u.ret[0] >> 24); + break; + case FFI_TYPE_SINT8: + *(stack - FIRST_ARG_SLOT) = (SINT8)(u.ret[0] >> 24); + break; + case FFI_TYPE_UINT16: + *(stack - FIRST_ARG_SLOT) = (UINT16)(u.ret[0] >> 16); + break; + case FFI_TYPE_SINT16: + *(stack - FIRST_ARG_SLOT) = (SINT16)(u.ret[0] >> 16); + break; + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + *(stack - FIRST_ARG_SLOT) = u.ret[0]; + break; + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + *(stack - FIRST_ARG_SLOT) = u.ret[0]; + *(stack - FIRST_ARG_SLOT - 1) = u.ret[1]; + break; + + case FFI_TYPE_DOUBLE: + fldd(rvalue, fr4); + break; + + case FFI_TYPE_FLOAT: + fldw(rvalue, fr4); + break; + + case FFI_TYPE_STRUCT: + /* Don't need a return value, done by caller. */ + break; + + case FFI_TYPE_SMALL_STRUCT2: + case FFI_TYPE_SMALL_STRUCT3: + case FFI_TYPE_SMALL_STRUCT4: + tmp = (void*)(stack - FIRST_ARG_SLOT); + tmp += 4 - cif->rtype->size; + memcpy((void*)tmp, &u, cif->rtype->size); + break; + + case FFI_TYPE_SMALL_STRUCT5: + case FFI_TYPE_SMALL_STRUCT6: + case FFI_TYPE_SMALL_STRUCT7: + case FFI_TYPE_SMALL_STRUCT8: + { + unsigned int ret2[2]; + int off; + + /* Right justify ret[0] and ret[1] */ + switch (cif->flags) + { + case FFI_TYPE_SMALL_STRUCT5: off = 3; break; + case FFI_TYPE_SMALL_STRUCT6: off = 2; break; + case FFI_TYPE_SMALL_STRUCT7: off = 1; break; + default: off = 0; break; + } + + memset (ret2, 0, sizeof (ret2)); + memcpy ((char *)ret2 + off, &u, 8 - off); + + *(stack - FIRST_ARG_SLOT) = ret2[0]; + *(stack - FIRST_ARG_SLOT - 1) = ret2[1]; + } + break; + + case FFI_TYPE_POINTER: + case FFI_TYPE_VOID: + break; + + default: + debug(0, "assert with cif->flags: %d\n",cif->flags); + FFI_ASSERT(0); + break; + } + return FFI_OK; +} + +/* Fill in a closure to refer to the specified fun and user_data. + cif specifies the argument and result types for fun. + The cif must already be prep'ed. */ + +extern void ffi_closure_pa32(void); + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + ffi_closure *c = (ffi_closure *)FFI_RESTORE_PTR (closure); + + /* The layout of a function descriptor. A function pointer with the PLABEL + bit set points to a function descriptor. */ + struct pa32_fd + { + UINT32 code_pointer; + UINT32 gp; + }; + + struct ffi_pa32_trampoline_struct + { + UINT32 code_pointer; /* Pointer to ffi_closure_unix. */ + UINT32 fake_gp; /* Pointer to closure, installed as gp. */ + UINT32 real_gp; /* Real gp value. */ + }; + + struct ffi_pa32_trampoline_struct *tramp; + struct pa32_fd *fd; + + if (cif->abi != FFI_PA32) + return FFI_BAD_ABI; + + /* Get function descriptor address for ffi_closure_pa32. */ + fd = (struct pa32_fd *)((UINT32)ffi_closure_pa32 & ~3); + + /* Setup trampoline. */ + tramp = (struct ffi_pa32_trampoline_struct *)c->tramp; + tramp->code_pointer = fd->code_pointer; + tramp->fake_gp = (UINT32)codeloc & ~3; + tramp->real_gp = fd->gp; + + c->cif = cif; + c->user_data = user_data; + c->fun = fun; + + return FFI_OK; +} +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/ffitarget.h new file mode 100644 index 0000000..df1209e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/ffitarget.h @@ -0,0 +1,80 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 1996-2003 Red Hat, Inc. + Target configuration macros for hppa. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +/* ---- System specific configurations ----------------------------------- */ + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + +#ifdef PA_LINUX + FFI_PA32, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_PA32 +#endif + +#ifdef PA_HPUX + FFI_PA32, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_PA32 +#endif + +#ifdef PA64_HPUX +#error "PA64_HPUX FFI is not yet implemented" + FFI_PA64, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_PA64 +#endif +} ffi_abi; +#endif + +#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 +#define FFI_TRAMPOLINE_SIZE 12 + +#define FFI_TYPE_SMALL_STRUCT2 -1 +#define FFI_TYPE_SMALL_STRUCT3 -2 +#define FFI_TYPE_SMALL_STRUCT4 -3 +#define FFI_TYPE_SMALL_STRUCT5 -4 +#define FFI_TYPE_SMALL_STRUCT6 -5 +#define FFI_TYPE_SMALL_STRUCT7 -6 +#define FFI_TYPE_SMALL_STRUCT8 -7 +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/hpux32.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/hpux32.S new file mode 100644 index 0000000..d0e5f69 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/hpux32.S @@ -0,0 +1,370 @@ +/* ----------------------------------------------------------------------- + hpux32.S - Copyright (c) 2006 Free Software Foundation, Inc. + (c) 2008 Red Hat, Inc. + based on src/pa/linux.S + + HP-UX PA Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + + .LEVEL 1.1 + .SPACE $PRIVATE$ + .IMPORT $global$,DATA + .IMPORT $$dyncall,MILLICODE + .SUBSPA $DATA$ + .align 4 + + /* void ffi_call_pa32(void (*)(char *, extended_cif *), + extended_cif *ecif, + unsigned bytes, + unsigned flags, + unsigned *rvalue, + void (*fn)(void)); + */ + + .export ffi_call_pa32,ENTRY,PRIV_LEV=3 + .import ffi_prep_args_pa32,CODE + + .SPACE $TEXT$ + .SUBSPA $CODE$ + .align 4 + +L$FB1 +ffi_call_pa32 + .proc + .callinfo FRAME=64,CALLS,SAVE_RP,SAVE_SP,ENTRY_GR=4 + .entry + stw %rp, -20(%sp) + copy %r3, %r1 +L$CFI11 + copy %sp, %r3 +L$CFI12 + + /* Setup the stack for calling prep_args... + We want the stack to look like this: + + [ Previous stack ] <- %r3 + + [ 64-bytes register save area ] <- %r4 + + [ Stack space for actual call, passed as ] <- %arg0 + [ arg0 to ffi_prep_args_pa32 ] + + [ Stack for calling prep_args ] <- %sp + */ + + stwm %r1, 64(%sp) + stw %r4, 12(%r3) +L$CFI13 + copy %sp, %r4 + + addl %arg2, %r4, %arg0 ; arg stack + stw %arg3, -48(%r3) ; save flags we need it later + + /* Call prep_args: + %arg0(stack) -- set up above + %arg1(ecif) -- same as incoming param + %arg2(bytes) -- same as incoming param */ + bl ffi_prep_args_pa32,%r2 + ldo 64(%arg0), %sp + ldo -64(%sp), %sp + + /* now %sp should point where %arg0 was pointing. */ + + /* Load the arguments that should be passed in registers + The fp args are loaded by the prep_args function. */ + ldw -36(%sp), %arg0 + ldw -40(%sp), %arg1 + ldw -44(%sp), %arg2 + ldw -48(%sp), %arg3 + + /* in case the function is going to return a structure + we need to give it a place to put the result. */ + ldw -52(%r3), %ret0 ; %ret0 <- rvalue + ldw -56(%r3), %r22 ; %r22 <- function to call + bl $$dyncall, %r31 ; Call the user function + copy %r31, %rp + + /* Prepare to store the result; we need to recover flags and rvalue. */ + ldw -48(%r3), %r21 ; r21 <- flags + ldw -52(%r3), %r20 ; r20 <- rvalue + + /* Store the result according to the return type. The most + likely types should come first. */ + +L$checkint + comib,<>,n FFI_TYPE_INT, %r21, L$checkint8 + b L$done + stw %ret0, 0(%r20) + +L$checkint8 + comib,<>,n FFI_TYPE_UINT8, %r21, L$checkint16 + b L$done + stb %ret0, 0(%r20) + +L$checkint16 + comib,<>,n FFI_TYPE_UINT16, %r21, L$checkdbl + b L$done + sth %ret0, 0(%r20) + +L$checkdbl + comib,<>,n FFI_TYPE_DOUBLE, %r21, L$checkfloat + b L$done + fstd %fr4,0(%r20) + +L$checkfloat + comib,<>,n FFI_TYPE_FLOAT, %r21, L$checkll + b L$done + fstw %fr4L,0(%r20) + +L$checkll + comib,<>,n FFI_TYPE_UINT64, %r21, L$checksmst2 + stw %ret0, 0(%r20) + b L$done + stw %ret1, 4(%r20) + +L$checksmst2 + comib,<>,n FFI_TYPE_SMALL_STRUCT2, %r21, L$checksmst3 + /* 2-byte structs are returned in ret0 as ????xxyy. */ + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b L$done + stb %ret0, 0(%r20) + +L$checksmst3 + comib,<>,n FFI_TYPE_SMALL_STRUCT3, %r21, L$checksmst4 + /* 3-byte structs are returned in ret0 as ??xxyyzz. */ + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b L$done + stb %ret0, 0(%r20) + +L$checksmst4 + comib,<>,n FFI_TYPE_SMALL_STRUCT4, %r21, L$checksmst5 + /* 4-byte structs are returned in ret0 as wwxxyyzz. */ + extru %ret0, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b L$done + stb %ret0, 0(%r20) + +L$checksmst5 + comib,<>,n FFI_TYPE_SMALL_STRUCT5, %r21, L$checksmst6 + /* 5 byte values are returned right justified: + ret0 ret1 + 5: ??????aa bbccddee */ + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b L$done + stb %ret1, 0(%r20) + +L$checksmst6 + comib,<>,n FFI_TYPE_SMALL_STRUCT6, %r21, L$checksmst7 + /* 6 byte values are returned right justified: + ret0 ret1 + 6: ????aabb ccddeeff */ + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b L$done + stb %ret1, 0(%r20) + +L$checksmst7 + comib,<>,n FFI_TYPE_SMALL_STRUCT7, %r21, L$checksmst8 + /* 7 byte values are returned right justified: + ret0 ret1 + 7: ??aabbcc ddeeffgg */ + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b L$done + stb %ret1, 0(%r20) + +L$checksmst8 + comib,<>,n FFI_TYPE_SMALL_STRUCT8, %r21, L$done + /* 8 byte values are returned right justified: + ret0 ret1 + 8: aabbccdd eeffgghh */ + extru %ret0, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stb %ret1, 0(%r20) + +L$done + /* all done, return */ + copy %r4, %sp ; pop arg stack + ldw 12(%r3), %r4 + ldwm -64(%sp), %r3 ; .. and pop stack + ldw -20(%sp), %rp + bv %r0(%rp) + nop + .exit + .procend +L$FE1 + + /* void ffi_closure_pa32(void); + Called with closure argument in %r19 */ + + .SPACE $TEXT$ + .SUBSPA $CODE$ + .export ffi_closure_pa32,ENTRY,PRIV_LEV=3,RTNVAL=GR + .import ffi_closure_inner_pa32,CODE + .align 4 +L$FB2 +ffi_closure_pa32 + .proc + .callinfo FRAME=64,CALLS,SAVE_RP,SAVE_SP,ENTRY_GR=3 + .entry + + stw %rp, -20(%sp) + copy %r3, %r1 +L$CFI21 + copy %sp, %r3 +L$CFI22 + stwm %r1, 64(%sp) + + /* Put arguments onto the stack and call ffi_closure_inner. */ + stw %arg0, -36(%r3) + stw %arg1, -40(%r3) + stw %arg2, -44(%r3) + stw %arg3, -48(%r3) + + /* Retrieve closure pointer and real gp. */ + copy %r19, %arg0 + ldw 8(%r19), %r19 + bl ffi_closure_inner_pa32, %r2 + copy %r3, %arg1 + ldwm -64(%sp), %r3 + ldw -20(%sp), %rp + ldw -36(%sp), %ret0 + bv %r0(%rp) + ldw -40(%sp), %ret1 + .exit + .procend +L$FE2: + + .SPACE $PRIVATE$ + .SUBSPA $DATA$ + + .align 4 + .EXPORT _GLOBAL__F_ffi_call_pa32,DATA +_GLOBAL__F_ffi_call_pa32 +L$frame1: + .word L$ECIE1-L$SCIE1 ;# Length of Common Information Entry +L$SCIE1: + .word 0x0 ;# CIE Identifier Tag + .byte 0x1 ;# CIE Version + .ascii "\0" ;# CIE Augmentation + .uleb128 0x1 ;# CIE Code Alignment Factor + .sleb128 4 ;# CIE Data Alignment Factor + .byte 0x2 ;# CIE RA Column + .byte 0xc ;# DW_CFA_def_cfa + .uleb128 0x1e + .uleb128 0x0 + .align 4 +L$ECIE1: +L$SFDE1: + .word L$EFDE1-L$ASFDE1 ;# FDE Length +L$ASFDE1: + .word L$ASFDE1-L$frame1 ;# FDE CIE offset + .word L$FB1 ;# FDE initial location + .word L$FE1-L$FB1 ;# FDE address range + + .byte 0x4 ;# DW_CFA_advance_loc4 + .word L$CFI11-L$FB1 + .byte 0x83 ;# DW_CFA_offset, column 0x3 + .uleb128 0x0 + .byte 0x11 ;# DW_CFA_offset_extended_sf; save r2 at [r30-20] + .uleb128 0x2 + .sleb128 -5 + + .byte 0x4 ;# DW_CFA_advance_loc4 + .word L$CFI12-L$CFI11 + .byte 0xd ;# DW_CFA_def_cfa_register = r3 + .uleb128 0x3 + + .byte 0x4 ;# DW_CFA_advance_loc4 + .word L$CFI13-L$CFI12 + .byte 0x84 ;# DW_CFA_offset, column 0x4 + .uleb128 0x3 + + .align 4 +L$EFDE1: + +L$SFDE2: + .word L$EFDE2-L$ASFDE2 ;# FDE Length +L$ASFDE2: + .word L$ASFDE2-L$frame1 ;# FDE CIE offset + .word L$FB2 ;# FDE initial location + .word L$FE2-L$FB2 ;# FDE address range + .byte 0x4 ;# DW_CFA_advance_loc4 + .word L$CFI21-L$FB2 + .byte 0x83 ;# DW_CFA_offset, column 0x3 + .uleb128 0x0 + .byte 0x11 ;# DW_CFA_offset_extended_sf + .uleb128 0x2 + .sleb128 -5 + + .byte 0x4 ;# DW_CFA_advance_loc4 + .word L$CFI22-L$CFI21 + .byte 0xd ;# DW_CFA_def_cfa_register = r3 + .uleb128 0x3 + + .align 4 +L$EFDE2: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/linux.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/linux.S new file mode 100644 index 0000000..33ef0b1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/pa/linux.S @@ -0,0 +1,380 @@ +/* ----------------------------------------------------------------------- + linux.S - (c) 2003-2004 Randolph Chung + (c) 2008 Red Hat, Inc. + + HPPA Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL RENESAS TECHNOLOGY BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + + .text + .level 1.1 + .align 4 + + /* void ffi_call_pa32(void (*)(char *, extended_cif *), + extended_cif *ecif, + unsigned bytes, + unsigned flags, + unsigned *rvalue, + void (*fn)(void)); + */ + + .export ffi_call_pa32,code + .import ffi_prep_args_pa32,code + + .type ffi_call_pa32, @function +.LFB1: +ffi_call_pa32: + .proc + .callinfo FRAME=64,CALLS,SAVE_RP,SAVE_SP,ENTRY_GR=4 + .entry + stw %rp, -20(%sp) + copy %r3, %r1 +.LCFI11: + + copy %sp, %r3 +.LCFI12: + + /* Setup the stack for calling prep_args... + We want the stack to look like this: + + [ Previous stack ] <- %r3 + + [ 64-bytes register save area ] <- %r4 + + [ Stack space for actual call, passed as ] <- %arg0 + [ arg0 to ffi_prep_args_pa32 ] + + [ Stack for calling prep_args ] <- %sp + */ + + stwm %r1, 64(%sp) + stw %r4, 12(%r3) +.LCFI13: + copy %sp, %r4 + + addl %arg2, %r4, %arg0 /* arg stack */ + stw %arg3, -48(%r3) /* save flags; we need it later */ + + /* Call prep_args: + %arg0(stack) -- set up above + %arg1(ecif) -- same as incoming param + %arg2(bytes) -- same as incoming param */ + bl ffi_prep_args_pa32,%r2 + ldo 64(%arg0), %sp + ldo -64(%sp), %sp + + /* now %sp should point where %arg0 was pointing. */ + + /* Load the arguments that should be passed in registers + The fp args were loaded by the prep_args function. */ + ldw -36(%sp), %arg0 + ldw -40(%sp), %arg1 + ldw -44(%sp), %arg2 + ldw -48(%sp), %arg3 + + /* in case the function is going to return a structure + we need to give it a place to put the result. */ + ldw -52(%r3), %ret0 /* %ret0 <- rvalue */ + ldw -56(%r3), %r22 /* %r22 <- function to call */ + bl $$dyncall, %r31 /* Call the user function */ + copy %r31, %rp + + /* Prepare to store the result; we need to recover flags and rvalue. */ + ldw -48(%r3), %r21 /* r21 <- flags */ + ldw -52(%r3), %r20 /* r20 <- rvalue */ + + /* Store the result according to the return type. */ + +.Lcheckint: + comib,<>,n FFI_TYPE_INT, %r21, .Lcheckint8 + b .Ldone + stw %ret0, 0(%r20) + +.Lcheckint8: + comib,<>,n FFI_TYPE_UINT8, %r21, .Lcheckint16 + b .Ldone + stb %ret0, 0(%r20) + +.Lcheckint16: + comib,<>,n FFI_TYPE_UINT16, %r21, .Lcheckdbl + b .Ldone + sth %ret0, 0(%r20) + +.Lcheckdbl: + comib,<>,n FFI_TYPE_DOUBLE, %r21, .Lcheckfloat + b .Ldone + fstd %fr4,0(%r20) + +.Lcheckfloat: + comib,<>,n FFI_TYPE_FLOAT, %r21, .Lcheckll + b .Ldone + fstw %fr4L,0(%r20) + +.Lcheckll: + comib,<>,n FFI_TYPE_UINT64, %r21, .Lchecksmst2 + stw %ret0, 0(%r20) + b .Ldone + stw %ret1, 4(%r20) + +.Lchecksmst2: + comib,<>,n FFI_TYPE_SMALL_STRUCT2, %r21, .Lchecksmst3 + /* 2-byte structs are returned in ret0 as ????xxyy. */ + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret0, 0(%r20) + +.Lchecksmst3: + comib,<>,n FFI_TYPE_SMALL_STRUCT3, %r21, .Lchecksmst4 + /* 3-byte structs are returned in ret0 as ??xxyyzz. */ + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret0, 0(%r20) + +.Lchecksmst4: + comib,<>,n FFI_TYPE_SMALL_STRUCT4, %r21, .Lchecksmst5 + /* 4-byte structs are returned in ret0 as wwxxyyzz. */ + extru %ret0, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret0, 0(%r20) + +.Lchecksmst5: + comib,<>,n FFI_TYPE_SMALL_STRUCT5, %r21, .Lchecksmst6 + /* 5 byte values are returned right justified: + ret0 ret1 + 5: ??????aa bbccddee */ + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret1, 0(%r20) + +.Lchecksmst6: + comib,<>,n FFI_TYPE_SMALL_STRUCT6, %r21, .Lchecksmst7 + /* 6 byte values are returned right justified: + ret0 ret1 + 6: ????aabb ccddeeff */ + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret1, 0(%r20) + +.Lchecksmst7: + comib,<>,n FFI_TYPE_SMALL_STRUCT7, %r21, .Lchecksmst8 + /* 7 byte values are returned right justified: + ret0 ret1 + 7: ??aabbcc ddeeffgg */ + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + b .Ldone + stb %ret1, 0(%r20) + +.Lchecksmst8: + comib,<>,n FFI_TYPE_SMALL_STRUCT8, %r21, .Ldone + /* 8 byte values are returned right justified: + ret0 ret1 + 8: aabbccdd eeffgghh */ + extru %ret0, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret0, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stbs,ma %ret0, 1(%r20) + extru %ret1, 7, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 15, 8, %r22 + stbs,ma %r22, 1(%r20) + extru %ret1, 23, 8, %r22 + stbs,ma %r22, 1(%r20) + stb %ret1, 0(%r20) + +.Ldone: + /* all done, return */ + copy %r4, %sp /* pop arg stack */ + ldw 12(%r3), %r4 + ldwm -64(%sp), %r3 /* .. and pop stack */ + ldw -20(%sp), %rp + bv %r0(%rp) + nop + .exit + .procend +.LFE1: + + /* void ffi_closure_pa32(void); + Called with closure argument in %r19 */ + .export ffi_closure_pa32,code + .import ffi_closure_inner_pa32,code + + .type ffi_closure_pa32, @function +.LFB2: +ffi_closure_pa32: + .proc + .callinfo FRAME=64,CALLS,SAVE_RP,SAVE_SP,ENTRY_GR=3 + .entry + + stw %rp, -20(%sp) +.LCFI20: + copy %r3, %r1 +.LCFI21: + copy %sp, %r3 +.LCFI22: + stwm %r1, 64(%sp) + + /* Put arguments onto the stack and call ffi_closure_inner. */ + stw %arg0, -36(%r3) + stw %arg1, -40(%r3) + stw %arg2, -44(%r3) + stw %arg3, -48(%r3) + + /* Retrieve closure pointer and real gp. */ + copy %r19, %arg0 + ldw 8(%r19), %r19 + bl ffi_closure_inner_pa32, %r2 + copy %r3, %arg1 + + ldwm -64(%sp), %r3 + ldw -20(%sp), %rp + ldw -36(%sp), %ret0 + bv %r0(%r2) + ldw -40(%sp), %ret1 + + .exit + .procend +.LFE2: + + .section ".eh_frame",EH_FRAME_FLAGS,@progbits +.Lframe1: + .word .LECIE1-.LSCIE1 ;# Length of Common Information Entry +.LSCIE1: + .word 0x0 ;# CIE Identifier Tag + .byte 0x1 ;# CIE Version +#ifdef __PIC__ + .ascii "zR\0" ;# CIE Augmentation: 'z' - data, 'R' - DW_EH_PE_... data +#else + .ascii "\0" ;# CIE Augmentation +#endif + .uleb128 0x1 ;# CIE Code Alignment Factor + .sleb128 4 ;# CIE Data Alignment Factor + .byte 0x2 ;# CIE RA Column +#ifdef __PIC__ + .uleb128 0x1 ;# Augmentation size + .byte 0x1b ;# FDE Encoding (DW_EH_PE_pcrel|DW_EH_PE_sdata4) +#endif + .byte 0xc ;# DW_CFA_def_cfa + .uleb128 0x1e + .uleb128 0x0 + .align 4 +.LECIE1: +.LSFDE1: + .word .LEFDE1-.LASFDE1 ;# FDE Length +.LASFDE1: + .word .LASFDE1-.Lframe1 ;# FDE CIE offset +#ifdef __PIC__ + .word .LFB1-. ;# FDE initial location +#else + .word .LFB1 ;# FDE initial location +#endif + .word .LFE1-.LFB1 ;# FDE address range +#ifdef __PIC__ + .uleb128 0x0 ;# Augmentation size: no data +#endif + .byte 0x4 ;# DW_CFA_advance_loc4 + .word .LCFI11-.LFB1 + .byte 0x83 ;# DW_CFA_offset, column 0x3 + .uleb128 0x0 + .byte 0x11 ;# DW_CFA_offset_extended_sf; save r2 at [r30-20] + .uleb128 0x2 + .sleb128 -5 + + .byte 0x4 ;# DW_CFA_advance_loc4 + .word .LCFI12-.LCFI11 + .byte 0xd ;# DW_CFA_def_cfa_register = r3 + .uleb128 0x3 + + .byte 0x4 ;# DW_CFA_advance_loc4 + .word .LCFI13-.LCFI12 + .byte 0x84 ;# DW_CFA_offset, column 0x4 + .uleb128 0x3 + + .align 4 +.LEFDE1: + +.LSFDE2: + .word .LEFDE2-.LASFDE2 ;# FDE Length +.LASFDE2: + .word .LASFDE2-.Lframe1 ;# FDE CIE offset +#ifdef __PIC__ + .word .LFB2-. ;# FDE initial location +#else + .word .LFB2 ;# FDE initial location +#endif + .word .LFE2-.LFB2 ;# FDE address range +#ifdef __PIC__ + .uleb128 0x0 ;# Augmentation size: no data +#endif + .byte 0x4 ;# DW_CFA_advance_loc4 + .word .LCFI21-.LFB2 + .byte 0x83 ;# DW_CFA_offset, column 0x3 + .uleb128 0x0 + .byte 0x11 ;# DW_CFA_offset_extended_sf + .uleb128 0x2 + .sleb128 -5 + + .byte 0x4 ;# DW_CFA_advance_loc4 + .word .LCFI22-.LCFI21 + .byte 0xd ;# DW_CFA_def_cfa_register = r3 + .uleb128 0x3 + + .align 4 +.LEFDE2: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/aix.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/aix.S new file mode 100644 index 0000000..7ba5415 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/aix.S @@ -0,0 +1,566 @@ +/* ----------------------------------------------------------------------- + aix.S - Copyright (c) 2002, 2009 Free Software Foundation, Inc. + based on darwin.S by John Hornkvist + + PowerPC Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + + .set r0,0 + .set r1,1 + .set r2,2 + .set r3,3 + .set r4,4 + .set r5,5 + .set r6,6 + .set r7,7 + .set r8,8 + .set r9,9 + .set r10,10 + .set r11,11 + .set r12,12 + .set r13,13 + .set r14,14 + .set r15,15 + .set r16,16 + .set r17,17 + .set r18,18 + .set r19,19 + .set r20,20 + .set r21,21 + .set r22,22 + .set r23,23 + .set r24,24 + .set r25,25 + .set r26,26 + .set r27,27 + .set r28,28 + .set r29,29 + .set r30,30 + .set r31,31 + .set f0,0 + .set f1,1 + .set f2,2 + .set f3,3 + .set f4,4 + .set f5,5 + .set f6,6 + .set f7,7 + .set f8,8 + .set f9,9 + .set f10,10 + .set f11,11 + .set f12,12 + .set f13,13 + .set f14,14 + .set f15,15 + .set f16,16 + .set f17,17 + .set f18,18 + .set f19,19 + .set f20,20 + .set f21,21 + + .extern .ffi_prep_args + +#define LIBFFI_ASM +#include +#include +#define JUMPTARGET(name) name +#define L(x) x + .file "aix.S" + .toc + + /* void ffi_call_AIX(extended_cif *ecif, unsigned long bytes, + * unsigned int flags, unsigned int *rvalue, + * void (*fn)(), + * void (*prep_args)(extended_cif*, unsigned *const)); + * r3=ecif, r4=bytes, r5=flags, r6=rvalue, r7=fn, r8=prep_args + */ + +.csect .text[PR] + .align 2 + .globl ffi_call_AIX + .globl .ffi_call_AIX +.csect ffi_call_AIX[DS] +ffi_call_AIX: +#ifdef __64BIT__ + .llong .ffi_call_AIX, TOC[tc0], 0 + .csect .text[PR] +.ffi_call_AIX: + .function .ffi_call_AIX,.ffi_call_AIX,16,044,LFE..0-LFB..0 + .bf __LINE__ + .line 1 +LFB..0: + /* Save registers we use. */ + mflr r0 + + std r28,-32(r1) + std r29,-24(r1) + std r30,-16(r1) + std r31, -8(r1) + + std r0, 16(r1) +LCFI..0: + mr r28, r1 /* our AP. */ + stdux r1, r1, r4 +LCFI..1: + + /* Save arguments over call... */ + mr r31, r5 /* flags, */ + mr r30, r6 /* rvalue, */ + mr r29, r7 /* function address. */ + std r2, 40(r1) + + /* Call ffi_prep_args. */ + mr r4, r1 + bl .ffi_prep_args + nop + + /* Now do the call. */ + ld r0, 0(r29) + ld r2, 8(r29) + ld r11, 16(r29) + /* Set up cr1 with bits 4-7 of the flags. */ + mtcrf 0x40, r31 + mtctr r0 + /* Load all those argument registers. */ + /* We have set up a nice stack frame, just load it into registers. */ + ld r3, 40+(1*8)(r1) + ld r4, 40+(2*8)(r1) + ld r5, 40+(3*8)(r1) + ld r6, 40+(4*8)(r1) + nop + ld r7, 40+(5*8)(r1) + ld r8, 40+(6*8)(r1) + ld r9, 40+(7*8)(r1) + ld r10,40+(8*8)(r1) + +L1: + /* Load all the FP registers. */ + bf 6,L2 /* 2f + 0x18 */ + lfd f1,-32-(13*8)(r28) + lfd f2,-32-(12*8)(r28) + lfd f3,-32-(11*8)(r28) + lfd f4,-32-(10*8)(r28) + nop + lfd f5,-32-(9*8)(r28) + lfd f6,-32-(8*8)(r28) + lfd f7,-32-(7*8)(r28) + lfd f8,-32-(6*8)(r28) + nop + lfd f9,-32-(5*8)(r28) + lfd f10,-32-(4*8)(r28) + lfd f11,-32-(3*8)(r28) + lfd f12,-32-(2*8)(r28) + nop + lfd f13,-32-(1*8)(r28) + +L2: + /* Make the call. */ + bctrl + ld r2, 40(r1) + + /* Now, deal with the return value. */ + mtcrf 0x01, r31 + + bt 30, L(done_return_value) + bt 29, L(fp_return_value) + std r3, 0(r30) + + /* Fall through... */ + +L(done_return_value): + /* Restore the registers we used and return. */ + mr r1, r28 + ld r0, 16(r28) + ld r28, -32(r1) + mtlr r0 + ld r29, -24(r1) + ld r30, -16(r1) + ld r31, -8(r1) + blr + +L(fp_return_value): + bf 28, L(float_return_value) + stfd f1, 0(r30) + bf 31, L(done_return_value) + stfd f2, 8(r30) + b L(done_return_value) +L(float_return_value): + stfs f1, 0(r30) + b L(done_return_value) +LFE..0: +#else /* ! __64BIT__ */ + + .long .ffi_call_AIX, TOC[tc0], 0 + .csect .text[PR] +.ffi_call_AIX: + .function .ffi_call_AIX,.ffi_call_AIX,16,044,LFE..0-LFB..0 + .bf __LINE__ + .line 1 +LFB..0: + /* Save registers we use. */ + mflr r0 + + stw r28,-16(r1) + stw r29,-12(r1) + stw r30, -8(r1) + stw r31, -4(r1) + + stw r0, 8(r1) +LCFI..0: + mr r28, r1 /* out AP. */ + stwux r1, r1, r4 +LCFI..1: + + /* Save arguments over call... */ + mr r31, r5 /* flags, */ + mr r30, r6 /* rvalue, */ + mr r29, r7 /* function address, */ + stw r2, 20(r1) + + /* Call ffi_prep_args. */ + mr r4, r1 + bl .ffi_prep_args + nop + + /* Now do the call. */ + lwz r0, 0(r29) + lwz r2, 4(r29) + lwz r11, 8(r29) + /* Set up cr1 with bits 4-7 of the flags. */ + mtcrf 0x40, r31 + mtctr r0 + /* Load all those argument registers. */ + /* We have set up a nice stack frame, just load it into registers. */ + lwz r3, 20+(1*4)(r1) + lwz r4, 20+(2*4)(r1) + lwz r5, 20+(3*4)(r1) + lwz r6, 20+(4*4)(r1) + nop + lwz r7, 20+(5*4)(r1) + lwz r8, 20+(6*4)(r1) + lwz r9, 20+(7*4)(r1) + lwz r10,20+(8*4)(r1) + +L1: + /* Load all the FP registers. */ + bf 6,L2 /* 2f + 0x18 */ + lfd f1,-16-(13*8)(r28) + lfd f2,-16-(12*8)(r28) + lfd f3,-16-(11*8)(r28) + lfd f4,-16-(10*8)(r28) + nop + lfd f5,-16-(9*8)(r28) + lfd f6,-16-(8*8)(r28) + lfd f7,-16-(7*8)(r28) + lfd f8,-16-(6*8)(r28) + nop + lfd f9,-16-(5*8)(r28) + lfd f10,-16-(4*8)(r28) + lfd f11,-16-(3*8)(r28) + lfd f12,-16-(2*8)(r28) + nop + lfd f13,-16-(1*8)(r28) + +L2: + /* Make the call. */ + bctrl + lwz r2, 20(r1) + + /* Now, deal with the return value. */ + mtcrf 0x01, r31 + + bt 30, L(done_return_value) + bt 29, L(fp_return_value) + stw r3, 0(r30) + bf 28, L(done_return_value) + stw r4, 4(r30) + + /* Fall through... */ + +L(done_return_value): + /* Restore the registers we used and return. */ + mr r1, r28 + lwz r0, 8(r28) + lwz r28,-16(r1) + mtlr r0 + lwz r29,-12(r1) + lwz r30, -8(r1) + lwz r31, -4(r1) + blr + +L(fp_return_value): + bf 28, L(float_return_value) + stfd f1, 0(r30) + b L(done_return_value) +L(float_return_value): + stfs f1, 0(r30) + b L(done_return_value) +LFE..0: +#endif + .ef __LINE__ + .long 0 + .byte 0,0,0,1,128,4,0,0 +/* END(ffi_call_AIX) */ + + /* void ffi_call_go_AIX(extended_cif *ecif, unsigned long bytes, + * unsigned int flags, unsigned int *rvalue, + * void (*fn)(), + * void (*prep_args)(extended_cif*, unsigned *const), + * void *closure); + * r3=ecif, r4=bytes, r5=flags, r6=rvalue, r7=fn, r8=prep_args, r9=closure + */ + +.csect .text[PR] + .align 2 + .globl ffi_call_go_AIX + .globl .ffi_call_go_AIX +.csect ffi_call_go_AIX[DS] +ffi_call_go_AIX: +#ifdef __64BIT__ + .llong .ffi_call_go_AIX, TOC[tc0], 0 + .csect .text[PR] +.ffi_call_go_AIX: + .function .ffi_call_go_AIX,.ffi_call_go_AIX,16,044,LFE..1-LFB..1 + .bf __LINE__ + .line 1 +LFB..1: + /* Save registers we use. */ + mflr r0 + + std r28,-32(r1) + std r29,-24(r1) + std r30,-16(r1) + std r31, -8(r1) + + std r9, 8(r1) /* closure, saved in cr field. */ + std r0, 16(r1) +LCFI..2: + mr r28, r1 /* our AP. */ + stdux r1, r1, r4 +LCFI..3: + + /* Save arguments over call... */ + mr r31, r5 /* flags, */ + mr r30, r6 /* rvalue, */ + mr r29, r7 /* function address, */ + std r2, 40(r1) + + /* Call ffi_prep_args. */ + mr r4, r1 + bl .ffi_prep_args + nop + + /* Now do the call. */ + ld r0, 0(r29) + ld r2, 8(r29) + ld r11, 8(r28) /* closure */ + /* Set up cr1 with bits 4-7 of the flags. */ + mtcrf 0x40, r31 + mtctr r0 + /* Load all those argument registers. */ + /* We have set up a nice stack frame, just load it into registers. */ + ld r3, 40+(1*8)(r1) + ld r4, 40+(2*8)(r1) + ld r5, 40+(3*8)(r1) + ld r6, 40+(4*8)(r1) + nop + ld r7, 40+(5*8)(r1) + ld r8, 40+(6*8)(r1) + ld r9, 40+(7*8)(r1) + ld r10,40+(8*8)(r1) + + b L1 +LFE..1: +#else /* ! __64BIT__ */ + + .long .ffi_call_go_AIX, TOC[tc0], 0 + .csect .text[PR] +.ffi_call_go_AIX: + .function .ffi_call_go_AIX,.ffi_call_go_AIX,16,044,LFE..1-LFB..1 + .bf __LINE__ + .line 1 + /* Save registers we use. */ +LFB..1: + mflr r0 + + stw r28,-16(r1) + stw r29,-12(r1) + stw r30, -8(r1) + stw r31, -4(r1) + + stw r9, 4(r1) /* closure, saved in cr field. */ + stw r0, 8(r1) +LCFI..2: + mr r28, r1 /* out AP. */ + stwux r1, r1, r4 +LCFI..3: + + /* Save arguments over call... */ + mr r31, r5 /* flags, */ + mr r30, r6 /* rvalue, */ + mr r29, r7 /* function address, */ + stw r2, 20(r1) + + /* Call ffi_prep_args. */ + mr r4, r1 + bl .ffi_prep_args + nop + + /* Now do the call. */ + lwz r0, 0(r29) + lwz r2, 4(r29) + lwz r11, 4(r28) /* closure */ + /* Set up cr1 with bits 4-7 of the flags. */ + mtcrf 0x40, r31 + mtctr r0 + /* Load all those argument registers. */ + /* We have set up a nice stack frame, just load it into registers. */ + lwz r3, 20+(1*4)(r1) + lwz r4, 20+(2*4)(r1) + lwz r5, 20+(3*4)(r1) + lwz r6, 20+(4*4)(r1) + nop + lwz r7, 20+(5*4)(r1) + lwz r8, 20+(6*4)(r1) + lwz r9, 20+(7*4)(r1) + lwz r10,20+(8*4)(r1) + + b L1 +LFE..1: +#endif + .ef __LINE__ + .long 0 + .byte 0,0,0,1,128,4,0,0 +/* END(ffi_call_go_AIX) */ + +.csect .text[PR] + .align 2 + .globl ffi_call_DARWIN + .globl .ffi_call_DARWIN +.csect ffi_call_DARWIN[DS] +ffi_call_DARWIN: +#ifdef __64BIT__ + .llong .ffi_call_DARWIN, TOC[tc0], 0 +#else + .long .ffi_call_DARWIN, TOC[tc0], 0 +#endif + .csect .text[PR] +.ffi_call_DARWIN: + blr + .long 0 + .byte 0,0,0,0,0,0,0,0 +/* END(ffi_call_DARWIN) */ + +/* EH frame stuff. */ + +#define LR_REGNO 0x41 /* Link Register (65), see rs6000.md */ +#ifdef __64BIT__ +#define PTRSIZE 8 +#define LOG2_PTRSIZE 3 +#define FDE_ENCODING 0x1c /* DW_EH_PE_pcrel|DW_EH_PE_sdata8 */ +#define EH_DATA_ALIGN_FACT 0x78 /* LEB128 -8 */ +#else +#define PTRSIZE 4 +#define LOG2_PTRSIZE 2 +#define FDE_ENCODING 0x1b /* DW_EH_PE_pcrel|DW_EH_PE_sdata4 */ +#define EH_DATA_ALIGN_FACT 0x7c /* LEB128 -4 */ +#endif + .csect _unwind.ro_[RO],4 + .align LOG2_PTRSIZE + .globl _GLOBAL__F_libffi_src_powerpc_aix +_GLOBAL__F_libffi_src_powerpc_aix: +Lframe..1: + .vbyte 4,LECIE..1-LSCIE..1 /* CIE Length */ +LSCIE..1: + .vbyte 4,0 /* CIE Identifier Tag */ + .byte 0x3 /* CIE Version */ + .byte "zR" /* CIE Augmentation */ + .byte 0 + .byte 0x1 /* uleb128 0x1; CIE Code Alignment Factor */ + .byte EH_DATA_ALIGN_FACT /* leb128 -4/-8; CIE Data Alignment Factor */ + .byte 0x41 /* CIE RA Column */ + .byte 0x1 /* uleb128 0x1; Augmentation size */ + .byte FDE_ENCODING /* FDE Encoding (pcrel|sdata4/8) */ + .byte 0xc /* DW_CFA_def_cfa */ + .byte 0x1 /* uleb128 0x1; Register r1 */ + .byte 0 /* uleb128 0x0; Offset 0 */ + .align LOG2_PTRSIZE +LECIE..1: +LSFDE..1: + .vbyte 4,LEFDE..1-LASFDE..1 /* FDE Length */ +LASFDE..1: + .vbyte 4,LASFDE..1-Lframe..1 /* FDE CIE offset */ + .vbyte PTRSIZE,LFB..0-$ /* FDE initial location */ + .vbyte PTRSIZE,LFE..0-LFB..0 /* FDE address range */ + .byte 0 /* uleb128 0x0; Augmentation size */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .vbyte 4,LCFI..0-LFB..0 + .byte 0x11 /* DW_CFA_def_offset_extended_sf */ + .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */ + .byte 0x7e /* leb128 -2; Offset -2 (8/16) */ + .byte 0x9f /* DW_CFA_offset Register r31 */ + .byte 0x1 /* uleb128 0x1; Offset 1 (-4/-8) */ + .byte 0x9e /* DW_CFA_offset Register r30 */ + .byte 0x2 /* uleb128 0x2; Offset 2 (-8/-16) */ + .byte 0x9d /* DW_CFA_offset Register r29 */ + .byte 0x3 /* uleb128 0x3; Offset 3 (-12/-24) */ + .byte 0x9c /* DW_CFA_offset Register r28 */ + .byte 0x4 /* uleb128 0x4; Offset 4 (-16/-32) */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .vbyte 4,LCFI..1-LCFI..0 + .byte 0xd /* DW_CFA_def_cfa_register */ + .byte 0x1c /* uleb128 28; Register r28 */ + .align LOG2_PTRSIZE +LEFDE..1: +LSFDE..2: + .vbyte 4,LEFDE..2-LASFDE..2 /* FDE Length */ +LASFDE..2: + .vbyte 4,LASFDE..2-Lframe..1 /* FDE CIE offset */ + .vbyte PTRSIZE,LFB..1-$ /* FDE initial location */ + .vbyte PTRSIZE,LFE..1-LFB..1 /* FDE address range */ + .byte 0 /* uleb128 0x0; Augmentation size */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .vbyte 4,LCFI..2-LFB..1 + .byte 0x11 /* DW_CFA_def_offset_extended_sf */ + .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */ + .byte 0x7e /* leb128 -2; Offset -2 (8/16) */ + .byte 0x9f /* DW_CFA_offset Register r31 */ + .byte 0x1 /* uleb128 0x1; Offset 1 (-4/-8) */ + .byte 0x9e /* DW_CFA_offset Register r30 */ + .byte 0x2 /* uleb128 0x2; Offset 2 (-8/-16) */ + .byte 0x9d /* DW_CFA_offset Register r29 */ + .byte 0x3 /* uleb128 0x3; Offset 3 (-12/-24) */ + .byte 0x9c /* DW_CFA_offset Register r28 */ + .byte 0x4 /* uleb128 0x4; Offset 4 (-16/-32) */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .vbyte 4,LCFI..3-LCFI..2 + .byte 0xd /* DW_CFA_def_cfa_register */ + .byte 0x1c /* uleb128 28; Register r28 */ + .align LOG2_PTRSIZE +LEFDE..2: + .vbyte 4,0 /* End of FDEs */ + + .csect .text[PR] + .ref _GLOBAL__F_libffi_src_powerpc_aix /* Prevents garbage collection by AIX linker */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/aix_closure.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/aix_closure.S new file mode 100644 index 0000000..132c785 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/aix_closure.S @@ -0,0 +1,694 @@ +/* ----------------------------------------------------------------------- + aix_closure.S - Copyright (c) 2002, 2003, 2009 Free Software Foundation, Inc. + based on darwin_closure.S + + PowerPC Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + + .set r0,0 + .set r1,1 + .set r2,2 + .set r3,3 + .set r4,4 + .set r5,5 + .set r6,6 + .set r7,7 + .set r8,8 + .set r9,9 + .set r10,10 + .set r11,11 + .set r12,12 + .set r13,13 + .set r14,14 + .set r15,15 + .set r16,16 + .set r17,17 + .set r18,18 + .set r19,19 + .set r20,20 + .set r21,21 + .set r22,22 + .set r23,23 + .set r24,24 + .set r25,25 + .set r26,26 + .set r27,27 + .set r28,28 + .set r29,29 + .set r30,30 + .set r31,31 + .set f0,0 + .set f1,1 + .set f2,2 + .set f3,3 + .set f4,4 + .set f5,5 + .set f6,6 + .set f7,7 + .set f8,8 + .set f9,9 + .set f10,10 + .set f11,11 + .set f12,12 + .set f13,13 + .set f14,14 + .set f15,15 + .set f16,16 + .set f17,17 + .set f18,18 + .set f19,19 + .set f20,20 + .set f21,21 + + .extern .ffi_closure_helper_DARWIN + .extern .ffi_go_closure_helper_DARWIN + +#define LIBFFI_ASM +#define JUMPTARGET(name) name +#define L(x) x + .file "aix_closure.S" + .toc +LC..60: + .tc L..60[TC],L..60 + .csect .text[PR] + .align 2 + +.csect .text[PR] + .align 2 + .globl ffi_closure_ASM + .globl .ffi_closure_ASM +.csect ffi_closure_ASM[DS] +ffi_closure_ASM: +#ifdef __64BIT__ + .llong .ffi_closure_ASM, TOC[tc0], 0 + .csect .text[PR] +.ffi_closure_ASM: + .function .ffi_closure_ASM,.ffi_closure_ASM,16,044,LFE..0-LFB..0 + .bf __LINE__ + .line 1 +LFB..0: +/* we want to build up an area for the parameters passed */ +/* in registers (both floating point and integer) */ + + /* we store gpr 3 to gpr 10 (aligned to 4) + in the parents outgoing area */ + std r3, 48+(0*8)(r1) + std r4, 48+(1*8)(r1) + std r5, 48+(2*8)(r1) + std r6, 48+(3*8)(r1) + mflr r0 + + std r7, 48+(4*8)(r1) + std r8, 48+(5*8)(r1) + std r9, 48+(6*8)(r1) + std r10, 48+(7*8)(r1) + std r0, 16(r1) /* save the return address */ +LCFI..0: + /* 48 Bytes (Linkage Area) */ + /* 64 Bytes (params) */ + /* 16 Bytes (result) */ + /* 104 Bytes (13*8 from FPR) */ + /* 8 Bytes (alignment) */ + /* 240 Bytes */ + + stdu r1, -240(r1) /* skip over caller save area + keep stack aligned to 16 */ +LCFI..1: + + /* next save fpr 1 to fpr 13 (aligned to 8) */ + stfd f1, 128+(0*8)(r1) + stfd f2, 128+(1*8)(r1) + stfd f3, 128+(2*8)(r1) + stfd f4, 128+(3*8)(r1) + stfd f5, 128+(4*8)(r1) + stfd f6, 128+(5*8)(r1) + stfd f7, 128+(6*8)(r1) + stfd f8, 128+(7*8)(r1) + stfd f9, 128+(8*8)(r1) + stfd f10, 128+(9*8)(r1) + stfd f11, 128+(10*8)(r1) + stfd f12, 128+(11*8)(r1) + stfd f13, 128+(12*8)(r1) + + /* set up registers for the routine that actually does the work */ + /* get the context pointer from the trampoline */ + mr r3, r11 + + /* now load up the pointer to the result storage */ + addi r4, r1, 112 + + /* now load up the pointer to the saved gpr registers */ + addi r5, r1, 288 + + /* now load up the pointer to the saved fpr registers */ + addi r6, r1, 128 + + /* make the call */ + bl .ffi_closure_helper_DARWIN + nop + +.Ldoneclosure: + + /* now r3 contains the return type */ + /* so use it to look up in a table */ + /* so we know how to deal with each type */ + + /* look up the proper starting point in table */ + /* by using return type as offset */ + lhz r3, 10(r3) /* load type from return type */ + ld r4, LC..60(2) /* get address of jump table */ + sldi r3, r3, 4 /* now multiply return type by 16 */ + ld r0, 240+16(r1) /* load return address */ + add r3, r3, r4 /* add contents of table to table address */ + mtctr r3 + bctr /* jump to it */ + +/* Each fragment must be exactly 16 bytes long (4 instructions). + Align to 16 byte boundary for cache and dispatch efficiency. */ + .align 4 + +L..60: +/* case FFI_TYPE_VOID */ + mtlr r0 + addi r1, r1, 240 + blr + nop + +/* case FFI_TYPE_INT */ + lwa r3, 112+4(r1) + mtlr r0 + addi r1, r1, 240 + blr + +/* case FFI_TYPE_FLOAT */ + lfs f1, 112+0(r1) + mtlr r0 + addi r1, r1, 240 + blr + +/* case FFI_TYPE_DOUBLE */ + lfd f1, 112+0(r1) + mtlr r0 + addi r1, r1, 240 + blr + +/* case FFI_TYPE_LONGDOUBLE */ + lfd f1, 112+0(r1) + mtlr r0 + lfd f2, 112+8(r1) + b L..finish + +/* case FFI_TYPE_UINT8 */ + lbz r3, 112+7(r1) + mtlr r0 + addi r1, r1, 240 + blr + +/* case FFI_TYPE_SINT8 */ + lbz r3, 112+7(r1) + mtlr r0 + extsb r3, r3 + b L..finish + +/* case FFI_TYPE_UINT16 */ + lhz r3, 112+6(r1) + mtlr r0 +L..finish: + addi r1, r1, 240 + blr + +/* case FFI_TYPE_SINT16 */ + lha r3, 112+6(r1) + mtlr r0 + addi r1, r1, 240 + blr + +/* case FFI_TYPE_UINT32 */ + lwz r3, 112+4(r1) + mtlr r0 + addi r1, r1, 240 + blr + +/* case FFI_TYPE_SINT32 */ + lwa r3, 112+4(r1) + mtlr r0 + addi r1, r1, 240 + blr + +/* case FFI_TYPE_UINT64 */ + ld r3, 112+0(r1) + mtlr r0 + addi r1, r1, 240 + blr + +/* case FFI_TYPE_SINT64 */ + ld r3, 112+0(r1) + mtlr r0 + addi r1, r1, 240 + blr + +/* case FFI_TYPE_STRUCT */ + mtlr r0 + addi r1, r1, 240 + blr + nop + +/* case FFI_TYPE_POINTER */ + ld r3, 112+0(r1) + mtlr r0 + addi r1, r1, 240 + blr +LFE..0: + +#else /* ! __64BIT__ */ + + .long .ffi_closure_ASM, TOC[tc0], 0 + .csect .text[PR] +.ffi_closure_ASM: + .function .ffi_closure_ASM,.ffi_closure_ASM,16,044,LFE..0-LFB..0 + .bf __LINE__ + .line 1 +LFB..0: +/* we want to build up an area for the parameters passed */ +/* in registers (both floating point and integer) */ + + /* we store gpr 3 to gpr 10 (aligned to 4) + in the parents outgoing area */ + stw r3, 24+(0*4)(r1) + stw r4, 24+(1*4)(r1) + stw r5, 24+(2*4)(r1) + stw r6, 24+(3*4)(r1) + mflr r0 + + stw r7, 24+(4*4)(r1) + stw r8, 24+(5*4)(r1) + stw r9, 24+(6*4)(r1) + stw r10, 24+(7*4)(r1) + stw r0, 8(r1) +LCFI..0: + /* 24 Bytes (Linkage Area) */ + /* 32 Bytes (params) */ + /* 16 Bytes (result) */ + /* 104 Bytes (13*8 from FPR) */ + /* 176 Bytes */ + + stwu r1, -176(r1) /* skip over caller save area + keep stack aligned to 16 */ +LCFI..1: + + /* next save fpr 1 to fpr 13 (aligned to 8) */ + stfd f1, 72+(0*8)(r1) + stfd f2, 72+(1*8)(r1) + stfd f3, 72+(2*8)(r1) + stfd f4, 72+(3*8)(r1) + stfd f5, 72+(4*8)(r1) + stfd f6, 72+(5*8)(r1) + stfd f7, 72+(6*8)(r1) + stfd f8, 72+(7*8)(r1) + stfd f9, 72+(8*8)(r1) + stfd f10, 72+(9*8)(r1) + stfd f11, 72+(10*8)(r1) + stfd f12, 72+(11*8)(r1) + stfd f13, 72+(12*8)(r1) + + /* set up registers for the routine that actually does the work */ + /* get the context pointer from the trampoline */ + mr r3, r11 + + /* now load up the pointer to the result storage */ + addi r4, r1, 56 + + /* now load up the pointer to the saved gpr registers */ + addi r5, r1, 200 + + /* now load up the pointer to the saved fpr registers */ + addi r6, r1, 72 + + /* make the call */ + bl .ffi_closure_helper_DARWIN + nop + +.Ldoneclosure: + + /* now r3 contains the return type */ + /* so use it to look up in a table */ + /* so we know how to deal with each type */ + + /* look up the proper starting point in table */ + /* by using return type as offset */ + lhz r3, 6(r3) /* load type from return type */ + lwz r4, LC..60(2) /* get address of jump table */ + slwi r3, r3, 4 /* now multiply return type by 16 */ + lwz r0, 176+8(r1) /* load return address */ + add r3, r3, r4 /* add contents of table to table address */ + mtctr r3 + bctr /* jump to it */ + +/* Each fragment must be exactly 16 bytes long (4 instructions). + Align to 16 byte boundary for cache and dispatch efficiency. */ + .align 4 + +L..60: +/* case FFI_TYPE_VOID */ + mtlr r0 + addi r1, r1, 176 + blr + nop + +/* case FFI_TYPE_INT */ + lwz r3, 56+0(r1) + mtlr r0 + addi r1, r1, 176 + blr + +/* case FFI_TYPE_FLOAT */ + lfs f1, 56+0(r1) + mtlr r0 + addi r1, r1, 176 + blr + +/* case FFI_TYPE_DOUBLE */ + lfd f1, 56+0(r1) + mtlr r0 + addi r1, r1, 176 + blr + +/* case FFI_TYPE_LONGDOUBLE */ + lfd f1, 56+0(r1) + mtlr r0 + lfd f2, 56+8(r1) + b L..finish + +/* case FFI_TYPE_UINT8 */ + lbz r3, 56+3(r1) + mtlr r0 + addi r1, r1, 176 + blr + +/* case FFI_TYPE_SINT8 */ + lbz r3, 56+3(r1) + mtlr r0 + extsb r3, r3 + b L..finish + +/* case FFI_TYPE_UINT16 */ + lhz r3, 56+2(r1) + mtlr r0 + addi r1, r1, 176 + blr + +/* case FFI_TYPE_SINT16 */ + lha r3, 56+2(r1) + mtlr r0 + addi r1, r1, 176 + blr + +/* case FFI_TYPE_UINT32 */ + lwz r3, 56+0(r1) + mtlr r0 + addi r1, r1, 176 + blr + +/* case FFI_TYPE_SINT32 */ + lwz r3, 56+0(r1) + mtlr r0 + addi r1, r1, 176 + blr + +/* case FFI_TYPE_UINT64 */ + lwz r3, 56+0(r1) + mtlr r0 + lwz r4, 56+4(r1) + b L..finish + +/* case FFI_TYPE_SINT64 */ + lwz r3, 56+0(r1) + mtlr r0 + lwz r4, 56+4(r1) + b L..finish + +/* case FFI_TYPE_STRUCT */ + mtlr r0 + addi r1, r1, 176 + blr + nop + +/* case FFI_TYPE_POINTER */ + lwz r3, 56+0(r1) + mtlr r0 +L..finish: + addi r1, r1, 176 + blr +LFE..0: +#endif + .ef __LINE__ +/* END(ffi_closure_ASM) */ + + +.csect .text[PR] + .align 2 + .globl ffi_go_closure_ASM + .globl .ffi_go_closure_ASM +.csect ffi_go_closure_ASM[DS] +ffi_go_closure_ASM: +#ifdef __64BIT__ + .llong .ffi_go_closure_ASM, TOC[tc0], 0 + .csect .text[PR] +.ffi_go_closure_ASM: + .function .ffi_go_closure_ASM,.ffi_go_closure_ASM,16,044,LFE..1-LFB..1 + .bf __LINE__ + .line 1 +LFB..1: +/* we want to build up an area for the parameters passed */ +/* in registers (both floating point and integer) */ + + /* we store gpr 3 to gpr 10 (aligned to 4) + in the parents outgoing area */ + std r3, 48+(0*8)(r1) + std r4, 48+(1*8)(r1) + std r5, 48+(2*8)(r1) + std r6, 48+(3*8)(r1) + mflr r0 + + std r7, 48+(4*8)(r1) + std r8, 48+(5*8)(r1) + std r9, 48+(6*8)(r1) + std r10, 48+(7*8)(r1) + std r0, 16(r1) /* save the return address */ +LCFI..2: + /* 48 Bytes (Linkage Area) */ + /* 64 Bytes (params) */ + /* 16 Bytes (result) */ + /* 104 Bytes (13*8 from FPR) */ + /* 8 Bytes (alignment) */ + /* 240 Bytes */ + + stdu r1, -240(r1) /* skip over caller save area + keep stack aligned to 16 */ +LCFI..3: + + /* next save fpr 1 to fpr 13 (aligned to 8) */ + stfd f1, 128+(0*8)(r1) + stfd f2, 128+(1*8)(r1) + stfd f3, 128+(2*8)(r1) + stfd f4, 128+(3*8)(r1) + stfd f5, 128+(4*8)(r1) + stfd f6, 128+(5*8)(r1) + stfd f7, 128+(6*8)(r1) + stfd f8, 128+(7*8)(r1) + stfd f9, 128+(8*8)(r1) + stfd f10, 128+(9*8)(r1) + stfd f11, 128+(10*8)(r1) + stfd f12, 128+(11*8)(r1) + stfd f13, 128+(12*8)(r1) + + /* set up registers for the routine that actually does the work */ + mr r3, r11 /* go closure */ + + /* now load up the pointer to the result storage */ + addi r4, r1, 112 + + /* now load up the pointer to the saved gpr registers */ + addi r5, r1, 288 + + /* now load up the pointer to the saved fpr registers */ + addi r6, r1, 128 + + /* make the call */ + bl .ffi_go_closure_helper_DARWIN + nop + + b .Ldoneclosure +LFE..1: + +#else /* ! __64BIT__ */ + + .long .ffi_go_closure_ASM, TOC[tc0], 0 + .csect .text[PR] +.ffi_go_closure_ASM: + .function .ffi_go_closure_ASM,.ffi_go_closure_ASM,16,044,LFE..1-LFB..1 + .bf __LINE__ + .line 1 +LFB..1: +/* we want to build up an area for the parameters passed */ +/* in registers (both floating point and integer) */ + + /* we store gpr 3 to gpr 10 (aligned to 4) + in the parents outgoing area */ + stw r3, 24+(0*4)(r1) + stw r4, 24+(1*4)(r1) + stw r5, 24+(2*4)(r1) + stw r6, 24+(3*4)(r1) + mflr r0 + + stw r7, 24+(4*4)(r1) + stw r8, 24+(5*4)(r1) + stw r9, 24+(6*4)(r1) + stw r10, 24+(7*4)(r1) + stw r0, 8(r1) +LCFI..2: + /* 24 Bytes (Linkage Area) */ + /* 32 Bytes (params) */ + /* 16 Bytes (result) */ + /* 104 Bytes (13*8 from FPR) */ + /* 176 Bytes */ + + stwu r1, -176(r1) /* skip over caller save area + keep stack aligned to 16 */ +LCFI..3: + + /* next save fpr 1 to fpr 13 (aligned to 8) */ + stfd f1, 72+(0*8)(r1) + stfd f2, 72+(1*8)(r1) + stfd f3, 72+(2*8)(r1) + stfd f4, 72+(3*8)(r1) + stfd f5, 72+(4*8)(r1) + stfd f6, 72+(5*8)(r1) + stfd f7, 72+(6*8)(r1) + stfd f8, 72+(7*8)(r1) + stfd f9, 72+(8*8)(r1) + stfd f10, 72+(9*8)(r1) + stfd f11, 72+(10*8)(r1) + stfd f12, 72+(11*8)(r1) + stfd f13, 72+(12*8)(r1) + + /* set up registers for the routine that actually does the work */ + mr r3, 11 /* go closure */ + + /* now load up the pointer to the result storage */ + addi r4, r1, 56 + + /* now load up the pointer to the saved gpr registers */ + addi r5, r1, 200 + + /* now load up the pointer to the saved fpr registers */ + addi r6, r1, 72 + + /* make the call */ + bl .ffi_go_closure_helper_DARWIN + nop + + b .Ldoneclosure +LFE..1: +#endif + .ef __LINE__ +/* END(ffi_go_closure_ASM) */ + +/* EH frame stuff. */ + +#define LR_REGNO 0x41 /* Link Register (65), see rs6000.md */ +#ifdef __64BIT__ +#define PTRSIZE 8 +#define LOG2_PTRSIZE 3 +#define CFA_OFFSET 0xf0,0x01 /* LEB128 240 */ +#define FDE_ENCODING 0x1c /* DW_EH_PE_pcrel|DW_EH_PE_sdata8 */ +#define EH_DATA_ALIGN_FACT 0x78 /* LEB128 -8 */ +#else +#define PTRSIZE 4 +#define LOG2_PTRSIZE 2 +#define CFA_OFFSET 0xb0,0x01 /* LEB128 176 */ +#define FDE_ENCODING 0x1b /* DW_EH_PE_pcrel|DW_EH_PE_sdata4 */ +#define EH_DATA_ALIGN_FACT 0x7c /* LEB128 -4 */ +#endif + + .csect _unwind.ro_[RO],4 + .align LOG2_PTRSIZE + .globl _GLOBAL__F_libffi_src_powerpc_aix_closure +_GLOBAL__F_libffi_src_powerpc_aix_closure: +Lframe..1: + .vbyte 4,LECIE..1-LSCIE..1 /* CIE Length */ +LSCIE..1: + .vbyte 4,0 /* CIE Identifier Tag */ + .byte 0x3 /* CIE Version */ + .byte "zR" /* CIE Augmentation */ + .byte 0 + .byte 0x1 /* uleb128 0x1; CIE Code Alignment Factor */ + .byte EH_DATA_ALIGN_FACT /* leb128 -4/-8; CIE Data Alignment Factor */ + .byte LR_REGNO /* CIE RA Column */ + .byte 0x1 /* uleb128 0x1; Augmentation size */ + .byte FDE_ENCODING /* FDE Encoding (pcrel|sdata4/8) */ + .byte 0xc /* DW_CFA_def_cfa */ + .byte 0x1 /* uleb128 0x1; Register r1 */ + .byte 0 /* uleb128 0x0; Offset 0 */ + .align LOG2_PTRSIZE +LECIE..1: +LSFDE..1: + .vbyte 4,LEFDE..1-LASFDE..1 /* FDE Length */ +LASFDE..1: + .vbyte 4,LASFDE..1-Lframe..1 /* FDE CIE offset */ + .vbyte PTRSIZE,LFB..0-$ /* FDE initial location */ + .vbyte PTRSIZE,LFE..0-LFB..0 /* FDE address range */ + .byte 0 /* uleb128 0x0; Augmentation size */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .vbyte 4,LCFI..1-LCFI..0 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte CFA_OFFSET /* uleb128 176/240 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .vbyte 4,LCFI..0-LFB..0 + .byte 0x11 /* DW_CFA_offset_extended_sf */ + .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */ + .byte 0x7e /* leb128 -2; Offset -2 (8/16) */ + .align LOG2_PTRSIZE +LEFDE..1: +LSFDE..2: + .vbyte 4,LEFDE..2-LASFDE..2 /* FDE Length */ +LASFDE..2: + .vbyte 4,LASFDE..2-Lframe..1 /* FDE CIE offset */ + .vbyte PTRSIZE,LFB..1-$ /* FDE initial location */ + .vbyte PTRSIZE,LFE..1-LFB..1 /* FDE address range */ + .byte 0 /* uleb128 0x0; Augmentation size */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .vbyte 4,LCFI..3-LCFI..2 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte CFA_OFFSET /* uleb128 176/240 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .vbyte 4,LCFI..2-LFB..1 + .byte 0x11 /* DW_CFA_offset_extended_sf */ + .byte LR_REGNO /* uleb128 LR_REGNO; Register LR */ + .byte 0x7e /* leb128 -2; Offset -2 (8/16) */ + .align LOG2_PTRSIZE +LEFDE..2: + .vbyte 4,0 /* End of FDEs */ + + .csect .text[PR] + .ref _GLOBAL__F_libffi_src_powerpc_aix_closure /* Prevents garbage collection by AIX linker */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/asm.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/asm.h new file mode 100644 index 0000000..27b22f6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/asm.h @@ -0,0 +1,125 @@ +/* ----------------------------------------------------------------------- + asm.h - Copyright (c) 1998 Geoffrey Keating + + PowerPC Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define ASM_GLOBAL_DIRECTIVE .globl + + +#define C_SYMBOL_NAME(name) name +/* Macro for a label. */ +#ifdef __STDC__ +#define C_LABEL(name) name##: +#else +#define C_LABEL(name) name/**/: +#endif + +/* This seems to always be the case on PPC. */ +#define ALIGNARG(log2) log2 +/* For ELF we need the `.type' directive to make shared libs work right. */ +#define ASM_TYPE_DIRECTIVE(name,typearg) .type name,typearg; +#define ASM_SIZE_DIRECTIVE(name) .size name,.-name + +/* If compiled for profiling, call `_mcount' at the start of each function. */ +#ifdef PROF +/* The mcount code relies on the return address being on the stack + to locate our caller and so it can restore it; so store one just + for its benefit. */ +#ifdef PIC +#define CALL_MCOUNT \ + .pushsection; \ + .section ".data"; \ + .align ALIGNARG(2); \ +0:.long 0; \ + .previous; \ + mflr %r0; \ + stw %r0,4(%r1); \ + bl _GLOBAL_OFFSET_TABLE_@local-4; \ + mflr %r11; \ + lwz %r0,0b@got(%r11); \ + bl JUMPTARGET(_mcount); +#else /* PIC */ +#define CALL_MCOUNT \ + .section ".data"; \ + .align ALIGNARG(2); \ +0:.long 0; \ + .previous; \ + mflr %r0; \ + lis %r11,0b@ha; \ + stw %r0,4(%r1); \ + addi %r0,%r11,0b@l; \ + bl JUMPTARGET(_mcount); +#endif /* PIC */ +#else /* PROF */ +#define CALL_MCOUNT /* Do nothing. */ +#endif /* PROF */ + +#define ENTRY(name) \ + ASM_GLOBAL_DIRECTIVE C_SYMBOL_NAME(name); \ + ASM_TYPE_DIRECTIVE (C_SYMBOL_NAME(name),@function) \ + .align ALIGNARG(2); \ + C_LABEL(name) \ + CALL_MCOUNT + +#define EALIGN_W_0 /* No words to insert. */ +#define EALIGN_W_1 nop +#define EALIGN_W_2 nop;nop +#define EALIGN_W_3 nop;nop;nop +#define EALIGN_W_4 EALIGN_W_3;nop +#define EALIGN_W_5 EALIGN_W_4;nop +#define EALIGN_W_6 EALIGN_W_5;nop +#define EALIGN_W_7 EALIGN_W_6;nop + +/* EALIGN is like ENTRY, but does alignment to 'words'*4 bytes + past a 2^align boundary. */ +#ifdef PROF +#define EFFI_ALIGN(name, alignt, words) \ + ASM_GLOBAL_DIRECTIVE C_SYMBOL_NAME(name); \ + ASM_TYPE_DIRECTIVE (C_SYMBOL_NAME(name),@function) \ + .align ALIGNARG(2); \ + C_LABEL(name) \ + CALL_MCOUNT \ + b 0f; \ + .align ALIGNARG(alignt); \ + EALIGN_W_##words; \ + 0: +#else /* PROF */ +#define EFFI_ALIGN(name, alignt, words) \ + ASM_GLOBAL_DIRECTIVE C_SYMBOL_NAME(name); \ + ASM_TYPE_DIRECTIVE (C_SYMBOL_NAME(name),@function) \ + .align ALIGNARG(alignt); \ + EALIGN_W_##words; \ + C_LABEL(name) +#endif + +#define END(name) \ + ASM_SIZE_DIRECTIVE(name) + +#ifdef PIC +#define JUMPTARGET(name) name##@plt +#else +#define JUMPTARGET(name) name +#endif + +/* Local labels stripped out by the linker. */ +#define L(x) .L##x diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/darwin.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/darwin.S new file mode 100644 index 0000000..066eb82 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/darwin.S @@ -0,0 +1,378 @@ +/* ----------------------------------------------------------------------- + darwin.S - Copyright (c) 2000 John Hornkvist + Copyright (c) 2004, 2010 Free Software Foundation, Inc. + + PowerPC Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#if defined(__ppc64__) +#define MODE_CHOICE(x, y) y +#else +#define MODE_CHOICE(x, y) x +#endif + +#define machine_choice MODE_CHOICE(ppc7400,ppc64) + +; Define some pseudo-opcodes for size-independent load & store of GPRs ... +#define lgu MODE_CHOICE(lwzu, ldu) +#define lg MODE_CHOICE(lwz,ld) +#define sg MODE_CHOICE(stw,std) +#define sgu MODE_CHOICE(stwu,stdu) +#define sgux MODE_CHOICE(stwux,stdux) + +; ... and the size of GPRs and their storage indicator. +#define GPR_BYTES MODE_CHOICE(4,8) +#define LOG2_GPR_BYTES MODE_CHOICE(2,3) /* log2(GPR_BYTES) */ +#define g_long MODE_CHOICE(long, quad) /* usage is ".g_long" */ + +; From the ABI doc: "Mac OS X ABI Function Call Guide" Version 2009-02-04. +#define LINKAGE_SIZE MODE_CHOICE(24,48) +#define PARAM_AREA MODE_CHOICE(32,64) +#define SAVED_LR_OFFSET MODE_CHOICE(8,16) /* save position for lr */ + +/* If there is any FP stuff we make space for all of the regs. */ +#define SAVED_FPR_COUNT 13 +#define FPR_SIZE 8 +#define RESULT_BYTES 16 + +/* This should be kept in step with the same value in ffi_darwin.c. */ +#define ASM_NEEDS_REGISTERS 4 +#define SAVE_REGS_SIZE (ASM_NEEDS_REGISTERS * GPR_BYTES) + +#include +#include + +#define JUMPTARGET(name) name +#define L(x) x + + .text + .align 2 + .globl _ffi_prep_args + + .align 2 + .globl _ffi_call_DARWIN + + /* We arrive here with: + r3 = ptr to extended cif. + r4 = -bytes. + r5 = cif flags. + r6 = ptr to return value. + r7 = fn pointer (user func). + r8 = fn pointer (ffi_prep_args). + r9 = ffi_type* for the ret val. */ + +_ffi_call_DARWIN: +Lstartcode: + mr r12,r8 /* We only need r12 until the call, + so it does not have to be saved. */ +LFB1: + /* Save the old stack pointer as AP. */ + mr r8,r1 +LCFI0: + + /* Save the retval type in parents frame. */ + sg r9,(LINKAGE_SIZE+6*GPR_BYTES)(r8) + + /* Allocate the stack space we need. */ + sgux r1,r1,r4 + + /* Save registers we use. */ + mflr r9 + sg r9,SAVED_LR_OFFSET(r8) + + sg r28,-(4 * GPR_BYTES)(r8) + sg r29,-(3 * GPR_BYTES)(r8) + sg r30,-(2 * GPR_BYTES)(r8) + sg r31,-( GPR_BYTES)(r8) + +#if !defined(POWERPC_DARWIN) + /* The TOC slot is reserved in the Darwin ABI and r2 is volatile. */ + sg r2,(5 * GPR_BYTES)(r1) +#endif + +LCFI1: + + /* Save arguments over call. */ + mr r31,r5 /* flags, */ + mr r30,r6 /* rvalue, */ + mr r29,r7 /* function address, */ + mr r28,r8 /* our AP. */ +LCFI2: + /* Call ffi_prep_args. r3 = extended cif, r4 = stack ptr copy. */ + mr r4,r1 + li r9,0 + + mtctr r12 /* r12 holds address of _ffi_prep_args. */ + bctrl + +#if !defined(POWERPC_DARWIN) + /* The TOC slot is reserved in the Darwin ABI and r2 is volatile. */ + lg r2,(5 * GPR_BYTES)(r1) +#endif + /* Now do the call. + Set up cr1 with bits 4-7 of the flags. */ + mtcrf 0x40,r31 + /* Get the address to call into CTR. */ + mtctr r29 + /* Load all those argument registers. + We have set up a nice stack frame, just load it into registers. */ + lg r3, (LINKAGE_SIZE )(r1) + lg r4, (LINKAGE_SIZE + GPR_BYTES)(r1) + lg r5, (LINKAGE_SIZE + 2 * GPR_BYTES)(r1) + lg r6, (LINKAGE_SIZE + 3 * GPR_BYTES)(r1) + nop + lg r7, (LINKAGE_SIZE + 4 * GPR_BYTES)(r1) + lg r8, (LINKAGE_SIZE + 5 * GPR_BYTES)(r1) + lg r9, (LINKAGE_SIZE + 6 * GPR_BYTES)(r1) + lg r10,(LINKAGE_SIZE + 7 * GPR_BYTES)(r1) + +L1: + /* ... Load all the FP registers. */ + bf 6,L2 /* No floats to load. */ + lfd f1, -SAVE_REGS_SIZE-(13*FPR_SIZE)(r28) + lfd f2, -SAVE_REGS_SIZE-(12*FPR_SIZE)(r28) + lfd f3, -SAVE_REGS_SIZE-(11*FPR_SIZE)(r28) + lfd f4, -SAVE_REGS_SIZE-(10*FPR_SIZE)(r28) + nop + lfd f5, -SAVE_REGS_SIZE-( 9*FPR_SIZE)(r28) + lfd f6, -SAVE_REGS_SIZE-( 8*FPR_SIZE)(r28) + lfd f7, -SAVE_REGS_SIZE-( 7*FPR_SIZE)(r28) + lfd f8, -SAVE_REGS_SIZE-( 6*FPR_SIZE)(r28) + nop + lfd f9, -SAVE_REGS_SIZE-( 5*FPR_SIZE)(r28) + lfd f10,-SAVE_REGS_SIZE-( 4*FPR_SIZE)(r28) + lfd f11,-SAVE_REGS_SIZE-( 3*FPR_SIZE)(r28) + lfd f12,-SAVE_REGS_SIZE-( 2*FPR_SIZE)(r28) + nop + lfd f13,-SAVE_REGS_SIZE-( 1*FPR_SIZE)(r28) + +L2: + mr r12,r29 /* Put the target address in r12 as specified. */ + mtctr r12 + nop + nop + + /* Make the call. */ + bctrl + + /* Now, deal with the return value. */ + + /* m64 structure returns can occupy the same set of registers as + would be used to pass such a structure as arg0 - so take care + not to step on any possibly hot regs. */ + + /* Get the flags.. */ + mtcrf 0x03,r31 ; we need c6 & cr7 now. + ; FLAG_RETURNS_NOTHING also covers struct ret-by-ref. + bt 30,L(done_return_value) ; FLAG_RETURNS_NOTHING + bf 27,L(scalar_return_value) ; not FLAG_RETURNS_STRUCT + + /* OK, so we have a struct. */ +#if defined(__ppc64__) + bt 31,L(maybe_return_128) ; FLAG_RETURNS_128BITS, special case + + /* OK, we have to map the return back to a mem struct. + We are about to trample the parents param area, so recover the + return type. r29 is free, since the call is done. */ + lg r29,(LINKAGE_SIZE + 6 * GPR_BYTES)(r28) + + sg r3, (LINKAGE_SIZE )(r28) + sg r4, (LINKAGE_SIZE + GPR_BYTES)(r28) + sg r5, (LINKAGE_SIZE + 2 * GPR_BYTES)(r28) + sg r6, (LINKAGE_SIZE + 3 * GPR_BYTES)(r28) + nop + sg r7, (LINKAGE_SIZE + 4 * GPR_BYTES)(r28) + sg r8, (LINKAGE_SIZE + 5 * GPR_BYTES)(r28) + sg r9, (LINKAGE_SIZE + 6 * GPR_BYTES)(r28) + sg r10,(LINKAGE_SIZE + 7 * GPR_BYTES)(r28) + /* OK, so do the block move - we trust that memcpy will not trample + the fprs... */ + mr r3,r30 ; dest + addi r4,r28,LINKAGE_SIZE ; source + /* The size is a size_t, should be long. */ + lg r5,0(r29) + /* Figure out small structs */ + cmpi 0,r5,4 + bgt L3 ; 1, 2 and 4 bytes have special rules. + cmpi 0,r5,3 + beq L3 ; not 3 + addi r4,r4,8 + subf r4,r5,r4 +L3: + bl _memcpy + + /* ... do we need the FP registers? - recover the flags.. */ + mtcrf 0x03,r31 ; we need c6 & cr7 now. + bf 29,L(done_return_value) /* No floats in the struct. */ + stfd f1, -SAVE_REGS_SIZE-(13*FPR_SIZE)(r28) + stfd f2, -SAVE_REGS_SIZE-(12*FPR_SIZE)(r28) + stfd f3, -SAVE_REGS_SIZE-(11*FPR_SIZE)(r28) + stfd f4, -SAVE_REGS_SIZE-(10*FPR_SIZE)(r28) + nop + stfd f5, -SAVE_REGS_SIZE-( 9*FPR_SIZE)(r28) + stfd f6, -SAVE_REGS_SIZE-( 8*FPR_SIZE)(r28) + stfd f7, -SAVE_REGS_SIZE-( 7*FPR_SIZE)(r28) + stfd f8, -SAVE_REGS_SIZE-( 6*FPR_SIZE)(r28) + nop + stfd f9, -SAVE_REGS_SIZE-( 5*FPR_SIZE)(r28) + stfd f10,-SAVE_REGS_SIZE-( 4*FPR_SIZE)(r28) + stfd f11,-SAVE_REGS_SIZE-( 3*FPR_SIZE)(r28) + stfd f12,-SAVE_REGS_SIZE-( 2*FPR_SIZE)(r28) + nop + stfd f13,-SAVE_REGS_SIZE-( 1*FPR_SIZE)(r28) + + mr r3,r29 ; ffi_type * + mr r4,r30 ; dest + addi r5,r28,-SAVE_REGS_SIZE-(13*FPR_SIZE) ; fprs + xor r6,r6,r6 + sg r6,(LINKAGE_SIZE + 7 * GPR_BYTES)(r28) + addi r6,r28,(LINKAGE_SIZE + 7 * GPR_BYTES) ; point to a zeroed counter. + bl _darwin64_struct_floats_to_mem + + b L(done_return_value) +#else + stw r3,0(r30) ; m32 the only struct return in reg is 4 bytes. +#endif + b L(done_return_value) + +L(fp_return_value): + /* Do we have long double to store? */ + bf 31,L(fd_return_value) ; FLAG_RETURNS_128BITS + stfd f1,0(r30) + stfd f2,FPR_SIZE(r30) + b L(done_return_value) + +L(fd_return_value): + /* Do we have double to store? */ + bf 28,L(float_return_value) + stfd f1,0(r30) + b L(done_return_value) + +L(float_return_value): + /* We only have a float to store. */ + stfs f1,0(r30) + b L(done_return_value) + +L(scalar_return_value): + bt 29,L(fp_return_value) ; FLAG_RETURNS_FP + ; ffi_arg is defined as unsigned long. + sg r3,0(r30) ; Save the reg. + bf 28,L(done_return_value) ; not FLAG_RETURNS_64BITS + +#if defined(__ppc64__) +L(maybe_return_128): + std r3,0(r30) + bf 31,L(done_return_value) ; not FLAG_RETURNS_128BITS + std r4,8(r30) +#else + stw r4,4(r30) +#endif + + /* Fall through. */ + /* We want this at the end to simplify eh epilog computation. */ + +L(done_return_value): + /* Restore the registers we used and return. */ + lg r29,SAVED_LR_OFFSET(r28) + ; epilog + lg r31,-(1 * GPR_BYTES)(r28) + mtlr r29 + lg r30,-(2 * GPR_BYTES)(r28) + lg r29,-(3 * GPR_BYTES)(r28) + lg r28,-(4 * GPR_BYTES)(r28) + lg r1,0(r1) + blr +LFE1: + .align 1 +/* END(_ffi_call_DARWIN) */ + +/* Provide a null definition of _ffi_call_AIX. */ + .text + .globl _ffi_call_AIX + .align 2 +_ffi_call_AIX: + blr +/* END(_ffi_call_AIX) */ + +/* EH stuff. */ + +#define EH_DATA_ALIGN_FACT MODE_CHOICE(0x7c,0x78) + + .section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support +EH_frame1: + .set L$set$0,LECIE1-LSCIE1 + .long L$set$0 ; Length of Common Information Entry +LSCIE1: + .long 0x0 ; CIE Identifier Tag + .byte 0x1 ; CIE Version + .ascii "zR\0" ; CIE Augmentation + .byte 0x1 ; uleb128 0x1; CIE Code Alignment Factor + .byte EH_DATA_ALIGN_FACT ; sleb128 -4; CIE Data Alignment Factor + .byte 0x41 ; CIE RA Column + .byte 0x1 ; uleb128 0x1; Augmentation size + .byte 0x10 ; FDE Encoding (pcrel) + .byte 0xc ; DW_CFA_def_cfa + .byte 0x1 ; uleb128 0x1 + .byte 0x0 ; uleb128 0x0 + .align LOG2_GPR_BYTES +LECIE1: + + .globl _ffi_call_DARWIN.eh +_ffi_call_DARWIN.eh: +LSFDE1: + .set L$set$1,LEFDE1-LASFDE1 + .long L$set$1 ; FDE Length +LASFDE1: + .long LASFDE1-EH_frame1 ; FDE CIE offset + .g_long Lstartcode-. ; FDE initial location + .set L$set$3,LFE1-Lstartcode + .g_long L$set$3 ; FDE address range + .byte 0x0 ; uleb128 0x0; Augmentation size + .byte 0x4 ; DW_CFA_advance_loc4 + .set L$set$4,LCFI0-Lstartcode + .long L$set$4 + .byte 0xd ; DW_CFA_def_cfa_register + .byte 0x08 ; uleb128 0x08 + .byte 0x4 ; DW_CFA_advance_loc4 + .set L$set$5,LCFI1-LCFI0 + .long L$set$5 + .byte 0x11 ; DW_CFA_offset_extended_sf + .byte 0x41 ; uleb128 0x41 + .byte 0x7e ; sleb128 -2 + .byte 0x9f ; DW_CFA_offset, column 0x1f + .byte 0x1 ; uleb128 0x1 + .byte 0x9e ; DW_CFA_offset, column 0x1e + .byte 0x2 ; uleb128 0x2 + .byte 0x9d ; DW_CFA_offset, column 0x1d + .byte 0x3 ; uleb128 0x3 + .byte 0x9c ; DW_CFA_offset, column 0x1c + .byte 0x4 ; uleb128 0x4 + .byte 0x4 ; DW_CFA_advance_loc4 + .set L$set$6,LCFI2-LCFI1 + .long L$set$6 + .byte 0xd ; DW_CFA_def_cfa_register + .byte 0x1c ; uleb128 0x1c + .align LOG2_GPR_BYTES +LEFDE1: + .align 1 + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/darwin_closure.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/darwin_closure.S new file mode 100644 index 0000000..3121e6a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/darwin_closure.S @@ -0,0 +1,571 @@ +/* ----------------------------------------------------------------------- + darwin_closure.S - Copyright (c) 2002, 2003, 2004, 2010, + Free Software Foundation, Inc. + based on ppc_closure.S + + PowerPC Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#define L(x) x + +#if defined(__ppc64__) +#define MODE_CHOICE(x, y) y +#else +#define MODE_CHOICE(x, y) x +#endif + +#define machine_choice MODE_CHOICE(ppc7400,ppc64) + +; Define some pseudo-opcodes for size-independent load & store of GPRs ... +#define lgu MODE_CHOICE(lwzu, ldu) +#define lg MODE_CHOICE(lwz,ld) +#define sg MODE_CHOICE(stw,std) +#define sgu MODE_CHOICE(stwu,stdu) + +; ... and the size of GPRs and their storage indicator. +#define GPR_BYTES MODE_CHOICE(4,8) +#define LOG2_GPR_BYTES MODE_CHOICE(2,3) /* log2(GPR_BYTES) */ +#define g_long MODE_CHOICE(long, quad) /* usage is ".g_long" */ + +; From the ABI doc: "Mac OS X ABI Function Call Guide" Version 2009-02-04. +#define LINKAGE_SIZE MODE_CHOICE(24,48) +#define PARAM_AREA MODE_CHOICE(32,64) + +#define SAVED_CR_OFFSET MODE_CHOICE(4,8) /* save position for CR */ +#define SAVED_LR_OFFSET MODE_CHOICE(8,16) /* save position for lr */ + +/* WARNING: if ffi_type is changed... here be monsters. + Offsets of items within the result type. */ +#define FFI_TYPE_TYPE MODE_CHOICE(6,10) +#define FFI_TYPE_ELEM MODE_CHOICE(8,16) + +#define SAVED_FPR_COUNT 13 +#define FPR_SIZE 8 +/* biggest m64 struct ret is 8GPRS + 13FPRS = 168 bytes - rounded to 16bytes = 176. */ +#define RESULT_BYTES MODE_CHOICE(16,176) + +; The whole stack frame **MUST** be 16byte-aligned. +#define SAVE_SIZE (((LINKAGE_SIZE+PARAM_AREA+SAVED_FPR_COUNT*FPR_SIZE+RESULT_BYTES)+15) & -16LL) +#define PAD_SIZE (SAVE_SIZE-(LINKAGE_SIZE+PARAM_AREA+SAVED_FPR_COUNT*FPR_SIZE+RESULT_BYTES)) + +#define PARENT_PARM_BASE (SAVE_SIZE+LINKAGE_SIZE) +#define FP_SAVE_BASE (LINKAGE_SIZE+PARAM_AREA) + +#if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1050 +; We no longer need the pic symbol stub for Darwin >= 9. +#define BLCLS_HELP _ffi_closure_helper_DARWIN +#define STRUCT_RETVALUE_P _darwin64_struct_ret_by_value_p +#define PASS_STR_FLOATS _darwin64_pass_struct_floats +#undef WANT_STUB +#else +#define BLCLS_HELP L_ffi_closure_helper_DARWIN$stub +#define STRUCT_RETVALUE_P L_darwin64_struct_ret_by_value_p$stub +#define PASS_STR_FLOATS L_darwin64_pass_struct_floats$stub +#define WANT_STUB +#endif + +/* m32/m64 + + The stack layout looks like this: + + | Additional params... | | Higher address + ~ ~ ~ + | Parameters (at least 8*4/8=32/64) | | NUM_GPR_ARG_REGISTERS + |--------------------------------------------| | + | TOC=R2 (AIX) Reserved (Darwin) 4/8 | | + |--------------------------------------------| | + | Reserved 2*4/8 | | + |--------------------------------------------| | + | Space for callee`s LR 4/8 | | + |--------------------------------------------| | + | Saved CR [low word for m64] 4/8 | | + |--------------------------------------------| | + | Current backchain pointer 4/8 |-/ Parent`s frame. + |--------------------------------------------| <+ <<< on entry to + | Result Bytes 16/176 | | + |--------------------------------------------| | + ~ padding to 16-byte alignment ~ ~ + |--------------------------------------------| | + | NUM_FPR_ARG_REGISTERS slots | | + | here fp13 .. fp1 13*8 | | + |--------------------------------------------| | + | R3..R10 8*4/8=32/64 | | NUM_GPR_ARG_REGISTERS + |--------------------------------------------| | + | TOC=R2 (AIX) Reserved (Darwin) 4/8 | | + |--------------------------------------------| | stack | + | Reserved [compiler,binder] 2*4/8 | | grows | + |--------------------------------------------| | down V + | Space for callees LR 4/8 | | + |--------------------------------------------| | lower addresses + | Saved CR [low word for m64] 4/8 | | + |--------------------------------------------| | stack pointer here + | Current backchain pointer 4/8 |-/ during + |--------------------------------------------| <<< call. + +*/ + + .file "darwin_closure.S" + + .machine machine_choice + + .text + .globl _ffi_closure_ASM + .align LOG2_GPR_BYTES +_ffi_closure_ASM: +LFB1: +Lstartcode: + mflr r0 /* extract return address */ + sg r0,SAVED_LR_OFFSET(r1) /* save the return address */ +LCFI0: + sgu r1,-SAVE_SIZE(r1) /* skip over caller save area + keep stack aligned to 16. */ +LCFI1: + /* We want to build up an area for the parameters passed + in registers. (both floating point and integer) */ + + /* Put gpr 3 to gpr 10 in the parents outgoing area... + ... the remainder of any params that overflowed the regs will + follow here. */ + sg r3, (PARENT_PARM_BASE )(r1) + sg r4, (PARENT_PARM_BASE + GPR_BYTES )(r1) + sg r5, (PARENT_PARM_BASE + GPR_BYTES * 2)(r1) + sg r6, (PARENT_PARM_BASE + GPR_BYTES * 3)(r1) + sg r7, (PARENT_PARM_BASE + GPR_BYTES * 4)(r1) + sg r8, (PARENT_PARM_BASE + GPR_BYTES * 5)(r1) + sg r9, (PARENT_PARM_BASE + GPR_BYTES * 6)(r1) + sg r10,(PARENT_PARM_BASE + GPR_BYTES * 7)(r1) + + /* We save fpr 1 to fpr 14 in our own save frame. */ + stfd f1, (FP_SAVE_BASE )(r1) + stfd f2, (FP_SAVE_BASE + FPR_SIZE )(r1) + stfd f3, (FP_SAVE_BASE + FPR_SIZE * 2 )(r1) + stfd f4, (FP_SAVE_BASE + FPR_SIZE * 3 )(r1) + stfd f5, (FP_SAVE_BASE + FPR_SIZE * 4 )(r1) + stfd f6, (FP_SAVE_BASE + FPR_SIZE * 5 )(r1) + stfd f7, (FP_SAVE_BASE + FPR_SIZE * 6 )(r1) + stfd f8, (FP_SAVE_BASE + FPR_SIZE * 7 )(r1) + stfd f9, (FP_SAVE_BASE + FPR_SIZE * 8 )(r1) + stfd f10,(FP_SAVE_BASE + FPR_SIZE * 9 )(r1) + stfd f11,(FP_SAVE_BASE + FPR_SIZE * 10)(r1) + stfd f12,(FP_SAVE_BASE + FPR_SIZE * 11)(r1) + stfd f13,(FP_SAVE_BASE + FPR_SIZE * 12)(r1) + + /* Set up registers for the routine that actually does the work + get the context pointer from the trampoline. */ + mr r3,r11 + + /* Now load up the pointer to the result storage. */ + addi r4,r1,(SAVE_SIZE-RESULT_BYTES) + + /* Now load up the pointer to the saved gpr registers. */ + addi r5,r1,PARENT_PARM_BASE + + /* Now load up the pointer to the saved fpr registers. */ + addi r6,r1,FP_SAVE_BASE + + /* Make the call. */ + bl BLCLS_HELP + + /* r3 contains the rtype pointer... save it since we will need + it later. */ + sg r3,LINKAGE_SIZE(r1) ; ffi_type * result_type + lg r0,0(r3) ; size => r0 + lhz r3,FFI_TYPE_TYPE(r3) ; type => r3 + + /* The helper will have intercepted structure returns and inserted + the caller`s destination address for structs returned by ref. */ + + /* r3 contains the return type so use it to look up in a table + so we know how to deal with each type. */ + + addi r5,r1,(SAVE_SIZE-RESULT_BYTES) /* Otherwise, our return is here. */ + bl Lget_ret_type0_addr /* Get pointer to Lret_type0 into LR. */ + mflr r4 /* Move to r4. */ + slwi r3,r3,4 /* Now multiply return type by 16. */ + add r3,r3,r4 /* Add contents of table to table address. */ + mtctr r3 + bctr /* Jump to it. */ +LFE1: +/* Each of the ret_typeX code fragments has to be exactly 16 bytes long + (4 instructions). For cache effectiveness we align to a 16 byte boundary + first. */ + + .align 4 + + nop + nop + nop +Lget_ret_type0_addr: + blrl + +/* case FFI_TYPE_VOID */ +Lret_type0: + b Lfinish + nop + nop + nop + +/* case FFI_TYPE_INT */ +Lret_type1: + lg r3,0(r5) + b Lfinish + nop + nop + +/* case FFI_TYPE_FLOAT */ +Lret_type2: + lfs f1,0(r5) + b Lfinish + nop + nop + +/* case FFI_TYPE_DOUBLE */ +Lret_type3: + lfd f1,0(r5) + b Lfinish + nop + nop + +/* case FFI_TYPE_LONGDOUBLE */ +Lret_type4: + lfd f1,0(r5) + lfd f2,8(r5) + b Lfinish + nop + +/* case FFI_TYPE_UINT8 */ +Lret_type5: +#if defined(__ppc64__) + lbz r3,7(r5) +#else + lbz r3,3(r5) +#endif + b Lfinish + nop + nop + +/* case FFI_TYPE_SINT8 */ +Lret_type6: +#if defined(__ppc64__) + lbz r3,7(r5) +#else + lbz r3,3(r5) +#endif + extsb r3,r3 + b Lfinish + nop + +/* case FFI_TYPE_UINT16 */ +Lret_type7: +#if defined(__ppc64__) + lhz r3,6(r5) +#else + lhz r3,2(r5) +#endif + b Lfinish + nop + nop + +/* case FFI_TYPE_SINT16 */ +Lret_type8: +#if defined(__ppc64__) + lha r3,6(r5) +#else + lha r3,2(r5) +#endif + b Lfinish + nop + nop + +/* case FFI_TYPE_UINT32 */ +Lret_type9: +#if defined(__ppc64__) + lwz r3,4(r5) +#else + lwz r3,0(r5) +#endif + b Lfinish + nop + nop + +/* case FFI_TYPE_SINT32 */ +Lret_type10: +#if defined(__ppc64__) + lwz r3,4(r5) +#else + lwz r3,0(r5) +#endif + b Lfinish + nop + nop + +/* case FFI_TYPE_UINT64 */ +Lret_type11: +#if defined(__ppc64__) + lg r3,0(r5) + b Lfinish + nop +#else + lwz r3,0(r5) + lwz r4,4(r5) + b Lfinish +#endif + nop + +/* case FFI_TYPE_SINT64 */ +Lret_type12: +#if defined(__ppc64__) + lg r3,0(r5) + b Lfinish + nop +#else + lwz r3,0(r5) + lwz r4,4(r5) + b Lfinish +#endif + nop + +/* case FFI_TYPE_STRUCT */ +Lret_type13: +#if defined(__ppc64__) + lg r3,0(r5) ; we need at least this... + cmpi 0,r0,4 + bgt Lstructend ; not a special small case + b Lsmallstruct ; see if we need more. +#else + cmpwi 0,r0,4 + bgt Lfinish ; not by value + lg r3,0(r5) + b Lfinish +#endif +/* case FFI_TYPE_POINTER */ +Lret_type14: + lg r3,0(r5) + b Lfinish + nop + nop + +#if defined(__ppc64__) +Lsmallstruct: + beq Lfour ; continuation of Lret13. + cmpi 0,r0,3 + beq Lfinish ; don`t adjust this - can`t be any floats here... + srdi r3,r3,48 + cmpi 0,r0,2 + beq Lfinish ; .. or here .. + srdi r3,r3,8 + b Lfinish ; .. or here. + +Lfour: + lg r6,LINKAGE_SIZE(r1) ; get the result type + lg r6,FFI_TYPE_ELEM(r6) ; elements array pointer + lg r6,0(r6) ; first element + lhz r0,FFI_TYPE_TYPE(r6) ; OK go the type + cmpi 0,r0,2 ; FFI_TYPE_FLOAT + bne Lfourint + lfs f1,0(r5) ; just one float in the struct. + b Lfinish + +Lfourint: + srdi r3,r3,32 ; four bytes. + b Lfinish + +Lstructend: + lg r3,LINKAGE_SIZE(r1) ; get the result type + bl STRUCT_RETVALUE_P + cmpi 0,r3,0 + beq Lfinish ; nope. + /* Recover a pointer to the results. */ + addi r11,r1,(SAVE_SIZE-RESULT_BYTES) + lg r3,0(r11) ; we need at least this... + lg r4,8(r11) + cmpi 0,r0,16 + beq Lfinish ; special case 16 bytes we don't consider floats. + + /* OK, frustratingly, the process of saving the struct to mem might have + messed with the FPRs, so we have to re-load them :(. + We`ll use our FPRs space again - calling: + void darwin64_pass_struct_floats (ffi_type *s, char *src, + unsigned *nfpr, double **fprs) + We`ll temporarily pinch the first two slots of the param area for local + vars used by the routine. */ + xor r6,r6,r6 + addi r5,r1,PARENT_PARM_BASE ; some space + sg r6,0(r5) ; *nfpr zeroed. + addi r6,r5,8 ; **fprs + addi r3,r1,FP_SAVE_BASE ; pointer to FPRs space + sg r3,0(r6) + mr r4,r11 ; the struct is here... + lg r3,LINKAGE_SIZE(r1) ; ffi_type * result_type. + bl PASS_STR_FLOATS ; get struct floats into FPR save space. + /* See if we used any floats */ + lwz r0,(SAVE_SIZE-RESULT_BYTES)(r1) + cmpi 0,r0,0 + beq Lstructints ; nope. + /* OK load `em up... */ + lfd f1, (FP_SAVE_BASE )(r1) + lfd f2, (FP_SAVE_BASE + FPR_SIZE )(r1) + lfd f3, (FP_SAVE_BASE + FPR_SIZE * 2 )(r1) + lfd f4, (FP_SAVE_BASE + FPR_SIZE * 3 )(r1) + lfd f5, (FP_SAVE_BASE + FPR_SIZE * 4 )(r1) + lfd f6, (FP_SAVE_BASE + FPR_SIZE * 5 )(r1) + lfd f7, (FP_SAVE_BASE + FPR_SIZE * 6 )(r1) + lfd f8, (FP_SAVE_BASE + FPR_SIZE * 7 )(r1) + lfd f9, (FP_SAVE_BASE + FPR_SIZE * 8 )(r1) + lfd f10,(FP_SAVE_BASE + FPR_SIZE * 9 )(r1) + lfd f11,(FP_SAVE_BASE + FPR_SIZE * 10)(r1) + lfd f12,(FP_SAVE_BASE + FPR_SIZE * 11)(r1) + lfd f13,(FP_SAVE_BASE + FPR_SIZE * 12)(r1) + + /* point back at our saved struct. */ +Lstructints: + addi r11,r1,(SAVE_SIZE-RESULT_BYTES) + lg r3,0(r11) ; we end up picking the + lg r4,8(r11) ; first two again. + lg r5,16(r11) + lg r6,24(r11) + lg r7,32(r11) + lg r8,40(r11) + lg r9,48(r11) + lg r10,56(r11) +#endif + +/* case done */ +Lfinish: + addi r1,r1,SAVE_SIZE /* Restore stack pointer. */ + lg r0,SAVED_LR_OFFSET(r1) /* Get return address. */ + mtlr r0 /* Reset link register. */ + blr +Lendcode: + .align 1 + +/* END(ffi_closure_ASM) */ + +/* EH frame stuff. */ +#define EH_DATA_ALIGN_FACT MODE_CHOICE(0x7c,0x78) +/* 176, 400 */ +#define EH_FRAME_OFFSETA MODE_CHOICE(176,0x90) +#define EH_FRAME_OFFSETB MODE_CHOICE(1,3) + + .section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support +EH_frame1: + .set L$set$0,LECIE1-LSCIE1 + .long L$set$0 ; Length of Common Information Entry +LSCIE1: + .long 0x0 ; CIE Identifier Tag + .byte 0x1 ; CIE Version + .ascii "zR\0" ; CIE Augmentation + .byte 0x1 ; uleb128 0x1; CIE Code Alignment Factor + .byte EH_DATA_ALIGN_FACT ; sleb128 -4; CIE Data Alignment Factor + .byte 0x41 ; CIE RA Column + .byte 0x1 ; uleb128 0x1; Augmentation size + .byte 0x10 ; FDE Encoding (pcrel) + .byte 0xc ; DW_CFA_def_cfa + .byte 0x1 ; uleb128 0x1 + .byte 0x0 ; uleb128 0x0 + .align LOG2_GPR_BYTES +LECIE1: + .globl _ffi_closure_ASM.eh +_ffi_closure_ASM.eh: +LSFDE1: + .set L$set$1,LEFDE1-LASFDE1 + .long L$set$1 ; FDE Length + +LASFDE1: + .long LASFDE1-EH_frame1 ; FDE CIE offset + .g_long Lstartcode-. ; FDE initial location + .set L$set$2,LFE1-Lstartcode + .g_long L$set$2 ; FDE address range + .byte 0x0 ; uleb128 0x0; Augmentation size + .byte 0x4 ; DW_CFA_advance_loc4 + .set L$set$3,LCFI1-LCFI0 + .long L$set$3 + .byte 0xe ; DW_CFA_def_cfa_offset + .byte EH_FRAME_OFFSETA,EH_FRAME_OFFSETB ; uleb128 176,1/190,3 + .byte 0x4 ; DW_CFA_advance_loc4 + .set L$set$4,LCFI0-Lstartcode + .long L$set$4 + .byte 0x11 ; DW_CFA_offset_extended_sf + .byte 0x41 ; uleb128 0x41 + .byte 0x7e ; sleb128 -2 + .align LOG2_GPR_BYTES +LEFDE1: + .align 1 + +#ifdef WANT_STUB + .section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32 + .align 5 +L_ffi_closure_helper_DARWIN$stub: + .indirect_symbol _ffi_closure_helper_DARWIN + mflr r0 + bcl 20,31,"L1$spb" +"L1$spb": + mflr r11 + addis r11,r11,ha16(L_ffi_closure_helper_DARWIN$lazy_ptr-"L1$spb") + mtlr r0 + lwzu r12,lo16(L_ffi_closure_helper_DARWIN$lazy_ptr-"L1$spb")(r11) + mtctr r12 + bctr + .lazy_symbol_pointer +L_ffi_closure_helper_DARWIN$lazy_ptr: + .indirect_symbol _ffi_closure_helper_DARWIN + .g_long dyld_stub_binding_helper + +#if defined(__ppc64__) + .section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32 + .align 5 +L_darwin64_struct_ret_by_value_p$stub: + .indirect_symbol _darwin64_struct_ret_by_value_p + mflr r0 + bcl 20,31,"L2$spb" +"L2$spb": + mflr r11 + addis r11,r11,ha16(L_darwin64_struct_ret_by_value_p$lazy_ptr-"L2$spb") + mtlr r0 + lwzu r12,lo16(L_darwin64_struct_ret_by_value_p$lazy_ptr-"L2$spb")(r11) + mtctr r12 + bctr + .lazy_symbol_pointer +L_darwin64_struct_ret_by_value_p$lazy_ptr: + .indirect_symbol _darwin64_struct_ret_by_value_p + .g_long dyld_stub_binding_helper + + .section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32 + .align 5 +L_darwin64_pass_struct_floats$stub: + .indirect_symbol _darwin64_pass_struct_floats + mflr r0 + bcl 20,31,"L3$spb" +"L3$spb": + mflr r11 + addis r11,r11,ha16(L_darwin64_pass_struct_floats$lazy_ptr-"L3$spb") + mtlr r0 + lwzu r12,lo16(L_darwin64_pass_struct_floats$lazy_ptr-"L3$spb")(r11) + mtctr r12 + bctr + .lazy_symbol_pointer +L_darwin64_pass_struct_floats$lazy_ptr: + .indirect_symbol _darwin64_pass_struct_floats + .g_long dyld_stub_binding_helper +# endif +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi.c new file mode 100644 index 0000000..a19bcbb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi.c @@ -0,0 +1,175 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (C) 2013 IBM + Copyright (C) 2011 Anthony Green + Copyright (C) 2011 Kyle Moffett + Copyright (C) 2008 Red Hat, Inc + Copyright (C) 2007, 2008 Free Software Foundation, Inc + Copyright (c) 1998 Geoffrey Keating + + PowerPC Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include "ffi.h" +#include "ffi_common.h" +#include "ffi_powerpc.h" + +#if HAVE_LONG_DOUBLE_VARIANT +/* Adjust ffi_type_longdouble. */ +void FFI_HIDDEN +ffi_prep_types (ffi_abi abi) +{ +# if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE +# ifdef POWERPC64 + ffi_prep_types_linux64 (abi); +# else + ffi_prep_types_sysv (abi); +# endif +# endif +} +#endif + +/* Perform machine dependent cif processing */ +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep (ffi_cif *cif) +{ +#ifdef POWERPC64 + return ffi_prep_cif_linux64 (cif); +#else + return ffi_prep_cif_sysv (cif); +#endif +} + +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep_var (ffi_cif *cif, + unsigned int nfixedargs MAYBE_UNUSED, + unsigned int ntotalargs MAYBE_UNUSED) +{ +#ifdef POWERPC64 + return ffi_prep_cif_linux64_var (cif, nfixedargs, ntotalargs); +#else + return ffi_prep_cif_sysv (cif); +#endif +} + +static void +ffi_call_int (ffi_cif *cif, + void (*fn) (void), + void *rvalue, + void **avalue, + void *closure) +{ + /* The final SYSV ABI says that structures smaller or equal 8 bytes + are returned in r3/r4. A draft ABI used by linux instead returns + them in memory. + + We bounce-buffer SYSV small struct return values so that sysv.S + can write r3 and r4 to memory without worrying about struct size. + + For ELFv2 ABI, use a bounce buffer for homogeneous structs too, + for similar reasons. This bounce buffer must be aligned to 16 + bytes for use with homogeneous structs of vectors (float128). */ + float128 smst_buffer[8]; + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + ecif.rvalue = rvalue; + if ((cif->flags & FLAG_RETURNS_SMST) != 0) + ecif.rvalue = smst_buffer; + /* Ensure that we have a valid struct return value. + FIXME: Isn't this just papering over a user problem? */ + else if (!rvalue && cif->rtype->type == FFI_TYPE_STRUCT) + ecif.rvalue = alloca (cif->rtype->size); + +#ifdef POWERPC64 + ffi_call_LINUX64 (&ecif, fn, ecif.rvalue, cif->flags, closure, + -(long) cif->bytes); +#else + ffi_call_SYSV (&ecif, fn, ecif.rvalue, cif->flags, closure, -cif->bytes); +#endif + + /* Check for a bounce-buffered return value */ + if (rvalue && ecif.rvalue == smst_buffer) + { + unsigned int rsize = cif->rtype->size; +#ifndef __LITTLE_ENDIAN__ + /* The SYSV ABI returns a structure of up to 4 bytes in size + left-padded in r3. */ +# ifndef POWERPC64 + if (rsize <= 4) + memcpy (rvalue, (char *) smst_buffer + 4 - rsize, rsize); + else +# endif + /* The SYSV ABI returns a structure of up to 8 bytes in size + left-padded in r3/r4, and the ELFv2 ABI similarly returns a + structure of up to 8 bytes in size left-padded in r3. But + note that a structure of a single float is not paddded. */ + if (rsize <= 8 && (cif->flags & FLAG_RETURNS_FP) == 0) + memcpy (rvalue, (char *) smst_buffer + 8 - rsize, rsize); + else +#endif + memcpy (rvalue, smst_buffer, rsize); + } +} + +void +ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue) +{ + ffi_call_int (cif, fn, rvalue, avalue, NULL); +} + +void +ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue, + void *closure) +{ + ffi_call_int (cif, fn, rvalue, avalue, closure); +} + +ffi_status +ffi_prep_closure_loc (ffi_closure *closure, + ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + void *codeloc) +{ +#ifdef POWERPC64 + return ffi_prep_closure_loc_linux64 (closure, cif, fun, user_data, codeloc); +#else + return ffi_prep_closure_loc_sysv (closure, cif, fun, user_data, codeloc); +#endif +} + +ffi_status +ffi_prep_go_closure (ffi_go_closure *closure, + ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *)) +{ +#ifdef POWERPC64 + closure->tramp = ffi_go_closure_linux64; +#else + closure->tramp = ffi_go_closure_sysv; +#endif + closure->cif = cif; + closure->fun = fun; + return FFI_OK; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_darwin.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_darwin.c new file mode 100644 index 0000000..64bb94d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_darwin.c @@ -0,0 +1,1452 @@ +/* ----------------------------------------------------------------------- + ffi_darwin.c + + Copyright (C) 1998 Geoffrey Keating + Copyright (C) 2001 John Hornkvist + Copyright (C) 2002, 2006, 2007, 2009, 2010 Free Software Foundation, Inc. + + FFI support for Darwin and AIX. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include + +extern void ffi_closure_ASM (void); + +#if defined (FFI_GO_CLOSURES) +extern void ffi_go_closure_ASM (void); +#endif + +enum { + /* The assembly depends on these exact flags. + For Darwin64 (when FLAG_RETURNS_STRUCT is set): + FLAG_RETURNS_FP indicates that the structure embeds FP data. + FLAG_RETURNS_128BITS signals a special struct size that is not + expanded for float content. */ + FLAG_RETURNS_128BITS = 1 << (31-31), /* These go in cr7 */ + FLAG_RETURNS_NOTHING = 1 << (31-30), + FLAG_RETURNS_FP = 1 << (31-29), + FLAG_RETURNS_64BITS = 1 << (31-28), + + FLAG_RETURNS_STRUCT = 1 << (31-27), /* This goes in cr6 */ + + FLAG_ARG_NEEDS_COPY = 1 << (31- 7), + FLAG_FP_ARGUMENTS = 1 << (31- 6), /* cr1.eq; specified by ABI */ + FLAG_4_GPR_ARGUMENTS = 1 << (31- 5), + FLAG_RETVAL_REFERENCE = 1 << (31- 4) +}; + +/* About the DARWIN ABI. */ +enum { + NUM_GPR_ARG_REGISTERS = 8, + NUM_FPR_ARG_REGISTERS = 13, + LINKAGE_AREA_GPRS = 6 +}; + +enum { ASM_NEEDS_REGISTERS = 4 }; /* r28-r31 */ + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments. + + m32/m64 + + The stack layout we want looks like this: + + | Return address from ffi_call_DARWIN | higher addresses + |--------------------------------------------| + | Previous backchain pointer 4/8 | stack pointer here + |--------------------------------------------|<+ <<< on entry to + | ASM_NEEDS_REGISTERS=r28-r31 4*(4/8) | | ffi_call_DARWIN + |--------------------------------------------| | + | When we have any FP activity... the | | + | FPRs occupy NUM_FPR_ARG_REGISTERS slots | | + | here fp13 .. fp1 from high to low addr. | | + ~ ~ ~ + | Parameters (at least 8*4/8=32/64) | | NUM_GPR_ARG_REGISTERS + |--------------------------------------------| | + | TOC=R2 (AIX) Reserved (Darwin) 4/8 | | + |--------------------------------------------| | stack | + | Reserved 2*4/8 | | grows | + |--------------------------------------------| | down V + | Space for callee's LR 4/8 | | + |--------------------------------------------| | lower addresses + | Saved CR [low word for m64] 4/8 | | + |--------------------------------------------| | stack pointer here + | Current backchain pointer 4/8 |-/ during + |--------------------------------------------| <<< ffi_call_DARWIN + + */ + +#if defined(POWERPC_DARWIN64) +static void +darwin64_pass_struct_by_value + (ffi_type *, char *, unsigned, unsigned *, double **, unsigned long **); +#endif + +/* This depends on GPR_SIZE = sizeof (unsigned long) */ + +void +ffi_prep_args (extended_cif *ecif, unsigned long *const stack) +{ + const unsigned bytes = ecif->cif->bytes; + const unsigned flags = ecif->cif->flags; + const unsigned nargs = ecif->cif->nargs; +#if !defined(POWERPC_DARWIN64) + const ffi_abi abi = ecif->cif->abi; +#endif + + /* 'stacktop' points at the previous backchain pointer. */ + unsigned long *const stacktop = stack + (bytes / sizeof(unsigned long)); + + /* 'fpr_base' points at the space for fpr1, and grows upwards as + we use FPR registers. */ + double *fpr_base = (double *) (stacktop - ASM_NEEDS_REGISTERS) - NUM_FPR_ARG_REGISTERS; + int gp_count = 0, fparg_count = 0; + + /* 'next_arg' grows up as we put parameters in it. */ + unsigned long *next_arg = stack + LINKAGE_AREA_GPRS; /* 6 reserved positions. */ + + int i; + double double_tmp; + void **p_argv = ecif->avalue; + unsigned long gprvalue; + ffi_type** ptr = ecif->cif->arg_types; +#if !defined(POWERPC_DARWIN64) + char *dest_cpy; +#endif + unsigned size_al = 0; + + /* Check that everything starts aligned properly. */ + FFI_ASSERT(((unsigned) (char *) stack & 0xF) == 0); + FFI_ASSERT(((unsigned) (char *) stacktop & 0xF) == 0); + FFI_ASSERT((bytes & 0xF) == 0); + + /* Deal with return values that are actually pass-by-reference. + Rule: + Return values are referenced by r3, so r4 is the first parameter. */ + + if (flags & FLAG_RETVAL_REFERENCE) + *next_arg++ = (unsigned long) (char *) ecif->rvalue; + + /* Now for the arguments. */ + for (i = nargs; i > 0; i--, ptr++, p_argv++) + { + switch ((*ptr)->type) + { + /* If a floating-point parameter appears before all of the general- + purpose registers are filled, the corresponding GPRs that match + the size of the floating-point parameter are skipped. */ + case FFI_TYPE_FLOAT: + double_tmp = *(float *) *p_argv; + if (fparg_count < NUM_FPR_ARG_REGISTERS) + *fpr_base++ = double_tmp; +#if defined(POWERPC_DARWIN) + *(float *)next_arg = *(float *) *p_argv; +#else + *(double *)next_arg = double_tmp; +#endif + next_arg++; + gp_count++; + fparg_count++; + FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); + break; + + case FFI_TYPE_DOUBLE: + double_tmp = *(double *) *p_argv; + if (fparg_count < NUM_FPR_ARG_REGISTERS) + *fpr_base++ = double_tmp; + *(double *)next_arg = double_tmp; +#ifdef POWERPC64 + next_arg++; + gp_count++; +#else + next_arg += 2; + gp_count += 2; +#endif + fparg_count++; + FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); + break; + +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + + case FFI_TYPE_LONGDOUBLE: +# if defined(POWERPC64) && !defined(POWERPC_DARWIN64) + /* ??? This will exceed the regs count when the value starts at fp13 + and it will not put the extra bit on the stack. */ + if (fparg_count < NUM_FPR_ARG_REGISTERS) + *(long double *) fpr_base++ = *(long double *) *p_argv; + else + *(long double *) next_arg = *(long double *) *p_argv; + next_arg += 2; + fparg_count += 2; +# else + double_tmp = ((double *) *p_argv)[0]; + if (fparg_count < NUM_FPR_ARG_REGISTERS) + *fpr_base++ = double_tmp; + *(double *) next_arg = double_tmp; +# if defined(POWERPC_DARWIN64) + next_arg++; + gp_count++; +# else + next_arg += 2; + gp_count += 2; +# endif + fparg_count++; + double_tmp = ((double *) *p_argv)[1]; + if (fparg_count < NUM_FPR_ARG_REGISTERS) + *fpr_base++ = double_tmp; + *(double *) next_arg = double_tmp; +# if defined(POWERPC_DARWIN64) + next_arg++; + gp_count++; +# else + next_arg += 2; + gp_count += 2; +# endif + fparg_count++; +# endif + FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); + break; +#endif + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: +#ifdef POWERPC64 + gprvalue = *(long long *) *p_argv; + goto putgpr; +#else + *(long long *) next_arg = *(long long *) *p_argv; + next_arg += 2; + gp_count += 2; +#endif + break; + case FFI_TYPE_POINTER: + gprvalue = *(unsigned long *) *p_argv; + goto putgpr; + case FFI_TYPE_UINT8: + gprvalue = *(unsigned char *) *p_argv; + goto putgpr; + case FFI_TYPE_SINT8: + gprvalue = *(signed char *) *p_argv; + goto putgpr; + case FFI_TYPE_UINT16: + gprvalue = *(unsigned short *) *p_argv; + goto putgpr; + case FFI_TYPE_SINT16: + gprvalue = *(signed short *) *p_argv; + goto putgpr; + + case FFI_TYPE_STRUCT: + size_al = (*ptr)->size; +#if defined(POWERPC_DARWIN64) + next_arg = (unsigned long *)FFI_ALIGN((char *)next_arg, (*ptr)->alignment); + darwin64_pass_struct_by_value (*ptr, (char *) *p_argv, + (unsigned) size_al, + (unsigned int *) &fparg_count, + &fpr_base, &next_arg); +#else + dest_cpy = (char *) next_arg; + + /* If the first member of the struct is a double, then include enough + padding in the struct size to align it to double-word. */ + if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE) + size_al = FFI_ALIGN((*ptr)->size, 8); + +# if defined(POWERPC64) + FFI_ASSERT (abi != FFI_DARWIN); + memcpy ((char *) dest_cpy, (char *) *p_argv, size_al); + next_arg += (size_al + 7) / 8; +# else + /* Structures that match the basic modes (QI 1 byte, HI 2 bytes, + SI 4 bytes) are aligned as if they were those modes. + Structures with 3 byte in size are padded upwards. */ + if (size_al < 3 && abi == FFI_DARWIN) + dest_cpy += 4 - size_al; + + memcpy((char *) dest_cpy, (char *) *p_argv, size_al); + next_arg += (size_al + 3) / 4; +# endif +#endif + break; + + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + gprvalue = *(signed int *) *p_argv; + goto putgpr; + + case FFI_TYPE_UINT32: + gprvalue = *(unsigned int *) *p_argv; + putgpr: + *next_arg++ = gprvalue; + gp_count++; + break; + default: + break; + } + } + + /* Check that we didn't overrun the stack... */ + /* FFI_ASSERT(gpr_base <= stacktop - ASM_NEEDS_REGISTERS); + FFI_ASSERT((unsigned *)fpr_base + <= stacktop - ASM_NEEDS_REGISTERS - NUM_GPR_ARG_REGISTERS); + FFI_ASSERT(flags & FLAG_4_GPR_ARGUMENTS || intarg_count <= 4); */ +} + +#if defined(POWERPC_DARWIN64) + +/* See if we can put some of the struct into fprs. + This should not be called for structures of size 16 bytes, since these are not + broken out this way. */ +static void +darwin64_scan_struct_for_floats (ffi_type *s, unsigned *nfpr) +{ + int i; + + FFI_ASSERT (s->type == FFI_TYPE_STRUCT) + + for (i = 0; s->elements[i] != NULL; i++) + { + ffi_type *p = s->elements[i]; + switch (p->type) + { + case FFI_TYPE_STRUCT: + darwin64_scan_struct_for_floats (p, nfpr); + break; + case FFI_TYPE_LONGDOUBLE: + (*nfpr) += 2; + break; + case FFI_TYPE_DOUBLE: + case FFI_TYPE_FLOAT: + (*nfpr) += 1; + break; + default: + break; + } + } +} + +static int +darwin64_struct_size_exceeds_gprs_p (ffi_type *s, char *src, unsigned *nfpr) +{ + unsigned struct_offset=0, i; + + for (i = 0; s->elements[i] != NULL; i++) + { + char *item_base; + ffi_type *p = s->elements[i]; + /* Find the start of this item (0 for the first one). */ + if (i > 0) + struct_offset = FFI_ALIGN(struct_offset, p->alignment); + + item_base = src + struct_offset; + + switch (p->type) + { + case FFI_TYPE_STRUCT: + if (darwin64_struct_size_exceeds_gprs_p (p, item_base, nfpr)) + return 1; + break; + case FFI_TYPE_LONGDOUBLE: + if (*nfpr >= NUM_FPR_ARG_REGISTERS) + return 1; + (*nfpr) += 1; + item_base += 8; + /* FALL THROUGH */ + case FFI_TYPE_DOUBLE: + if (*nfpr >= NUM_FPR_ARG_REGISTERS) + return 1; + (*nfpr) += 1; + break; + case FFI_TYPE_FLOAT: + if (*nfpr >= NUM_FPR_ARG_REGISTERS) + return 1; + (*nfpr) += 1; + break; + default: + /* If we try and place any item, that is non-float, once we've + exceeded the 8 GPR mark, then we can't fit the struct. */ + if ((unsigned long)item_base >= 8*8) + return 1; + break; + } + /* now count the size of what we just used. */ + struct_offset += p->size; + } + return 0; +} + +/* Can this struct be returned by value? */ +int +darwin64_struct_ret_by_value_p (ffi_type *s) +{ + unsigned nfp = 0; + + FFI_ASSERT (s && s->type == FFI_TYPE_STRUCT); + + /* The largest structure we can return is 8long + 13 doubles. */ + if (s->size > 168) + return 0; + + /* We can't pass more than 13 floats. */ + darwin64_scan_struct_for_floats (s, &nfp); + if (nfp > 13) + return 0; + + /* If there are not too many floats, and the struct is + small enough to accommodate in the GPRs, then it must be OK. */ + if (s->size <= 64) + return 1; + + /* Well, we have to look harder. */ + nfp = 0; + if (darwin64_struct_size_exceeds_gprs_p (s, NULL, &nfp)) + return 0; + + return 1; +} + +void +darwin64_pass_struct_floats (ffi_type *s, char *src, + unsigned *nfpr, double **fprs) +{ + int i; + double *fpr_base = *fprs; + unsigned struct_offset = 0; + + /* We don't assume anything about the alignment of the source. */ + for (i = 0; s->elements[i] != NULL; i++) + { + char *item_base; + ffi_type *p = s->elements[i]; + /* Find the start of this item (0 for the first one). */ + if (i > 0) + struct_offset = FFI_ALIGN(struct_offset, p->alignment); + item_base = src + struct_offset; + + switch (p->type) + { + case FFI_TYPE_STRUCT: + darwin64_pass_struct_floats (p, item_base, nfpr, + &fpr_base); + break; + case FFI_TYPE_LONGDOUBLE: + if (*nfpr < NUM_FPR_ARG_REGISTERS) + *fpr_base++ = *(double *)item_base; + (*nfpr) += 1; + item_base += 8; + /* FALL THROUGH */ + case FFI_TYPE_DOUBLE: + if (*nfpr < NUM_FPR_ARG_REGISTERS) + *fpr_base++ = *(double *)item_base; + (*nfpr) += 1; + break; + case FFI_TYPE_FLOAT: + if (*nfpr < NUM_FPR_ARG_REGISTERS) + *fpr_base++ = (double) *(float *)item_base; + (*nfpr) += 1; + break; + default: + break; + } + /* now count the size of what we just used. */ + struct_offset += p->size; + } + /* Update the scores. */ + *fprs = fpr_base; +} + +/* Darwin64 special rules. + Break out a struct into params and float registers. */ +static void +darwin64_pass_struct_by_value (ffi_type *s, char *src, unsigned size, + unsigned *nfpr, double **fprs, unsigned long **arg) +{ + unsigned long *next_arg = *arg; + char *dest_cpy = (char *)next_arg; + + FFI_ASSERT (s->type == FFI_TYPE_STRUCT) + + if (!size) + return; + + /* First... special cases. */ + if (size < 3 + || (size == 4 + && s->elements[0] + && s->elements[0]->type != FFI_TYPE_FLOAT)) + { + /* Must be at least one GPR, padding is unspecified in value, + let's make it zero. */ + *next_arg = 0UL; + dest_cpy += 8 - size; + memcpy ((char *) dest_cpy, src, size); + next_arg++; + } + else if (size == 16) + { + memcpy ((char *) dest_cpy, src, size); + next_arg += 2; + } + else + { + /* now the general case, we consider embedded floats. */ + memcpy ((char *) dest_cpy, src, size); + darwin64_pass_struct_floats (s, src, nfpr, fprs); + next_arg += (size+7)/8; + } + + *arg = next_arg; +} + +double * +darwin64_struct_floats_to_mem (ffi_type *s, char *dest, double *fprs, unsigned *nf) +{ + int i; + unsigned struct_offset = 0; + + /* We don't assume anything about the alignment of the source. */ + for (i = 0; s->elements[i] != NULL; i++) + { + char *item_base; + ffi_type *p = s->elements[i]; + /* Find the start of this item (0 for the first one). */ + if (i > 0) + struct_offset = FFI_ALIGN(struct_offset, p->alignment); + item_base = dest + struct_offset; + + switch (p->type) + { + case FFI_TYPE_STRUCT: + fprs = darwin64_struct_floats_to_mem (p, item_base, fprs, nf); + break; + case FFI_TYPE_LONGDOUBLE: + if (*nf < NUM_FPR_ARG_REGISTERS) + { + *(double *)item_base = *fprs++ ; + (*nf) += 1; + } + item_base += 8; + /* FALL THROUGH */ + case FFI_TYPE_DOUBLE: + if (*nf < NUM_FPR_ARG_REGISTERS) + { + *(double *)item_base = *fprs++ ; + (*nf) += 1; + } + break; + case FFI_TYPE_FLOAT: + if (*nf < NUM_FPR_ARG_REGISTERS) + { + *(float *)item_base = (float) *fprs++ ; + (*nf) += 1; + } + break; + default: + break; + } + /* now count the size of what we just used. */ + struct_offset += p->size; + } + return fprs; +} + +#endif + +/* Adjust the size of S to be correct for Darwin. + On Darwin m32, the first field of a structure has natural alignment. + On Darwin m64, all fields have natural alignment. */ + +static void +darwin_adjust_aggregate_sizes (ffi_type *s) +{ + int i; + + if (s->type != FFI_TYPE_STRUCT) + return; + + s->size = 0; + for (i = 0; s->elements[i] != NULL; i++) + { + ffi_type *p; + int align; + + p = s->elements[i]; + if (p->type == FFI_TYPE_STRUCT) + darwin_adjust_aggregate_sizes (p); +#if defined(POWERPC_DARWIN64) + /* Natural alignment for all items. */ + align = p->alignment; +#else + /* Natural alignment for the first item... */ + if (i == 0) + align = p->alignment; + else if (p->alignment == 16 || p->alignment < 4) + /* .. subsequent items with vector or align < 4 have natural align. */ + align = p->alignment; + else + /* .. or align is 4. */ + align = 4; +#endif + /* Pad, if necessary, before adding the current item. */ + s->size = FFI_ALIGN(s->size, align) + p->size; + } + + s->size = FFI_ALIGN(s->size, s->alignment); + + /* This should not be necessary on m64, but harmless. */ + if (s->elements[0]->type == FFI_TYPE_UINT64 + || s->elements[0]->type == FFI_TYPE_SINT64 + || s->elements[0]->type == FFI_TYPE_DOUBLE + || s->elements[0]->alignment == 8) + s->alignment = s->alignment > 8 ? s->alignment : 8; + /* Do not add additional tail padding. */ +} + +/* Adjust the size of S to be correct for AIX. + Word-align double unless it is the first member of a structure. */ + +static void +aix_adjust_aggregate_sizes (ffi_type *s) +{ + int i; + + if (s->type != FFI_TYPE_STRUCT) + return; + + s->size = 0; + for (i = 0; s->elements[i] != NULL; i++) + { + ffi_type *p; + int align; + + p = s->elements[i]; + aix_adjust_aggregate_sizes (p); + align = p->alignment; + if (i != 0 && p->type == FFI_TYPE_DOUBLE) + align = 4; + s->size = FFI_ALIGN(s->size, align) + p->size; + } + + s->size = FFI_ALIGN(s->size, s->alignment); + + if (s->elements[0]->type == FFI_TYPE_UINT64 + || s->elements[0]->type == FFI_TYPE_SINT64 + || s->elements[0]->type == FFI_TYPE_DOUBLE + || s->elements[0]->alignment == 8) + s->alignment = s->alignment > 8 ? s->alignment : 8; + /* Do not add additional tail padding. */ +} + +/* Perform machine dependent cif processing. */ +ffi_status +ffi_prep_cif_machdep (ffi_cif *cif) +{ + /* All this is for the DARWIN ABI. */ + unsigned i; + ffi_type **ptr; + unsigned bytes; + unsigned fparg_count = 0, intarg_count = 0; + unsigned flags = 0; + unsigned size_al = 0; + + /* All the machine-independent calculation of cif->bytes will be wrong. + All the calculation of structure sizes will also be wrong. + Redo the calculation for DARWIN. */ + + if (cif->abi == FFI_DARWIN) + { + darwin_adjust_aggregate_sizes (cif->rtype); + for (i = 0; i < cif->nargs; i++) + darwin_adjust_aggregate_sizes (cif->arg_types[i]); + } + + if (cif->abi == FFI_AIX) + { + aix_adjust_aggregate_sizes (cif->rtype); + for (i = 0; i < cif->nargs; i++) + aix_adjust_aggregate_sizes (cif->arg_types[i]); + } + + /* Space for the frame pointer, callee's LR, CR, etc, and for + the asm's temp regs. */ + + bytes = (LINKAGE_AREA_GPRS + ASM_NEEDS_REGISTERS) * sizeof(unsigned long); + + /* Return value handling. + The rules m32 are as follows: + - 32-bit (or less) integer values are returned in gpr3; + - structures of size <= 4 bytes also returned in gpr3; + - 64-bit integer values [??? and structures between 5 and 8 bytes] are + returned in gpr3 and gpr4; + - Single/double FP values are returned in fpr1; + - Long double FP (if not equivalent to double) values are returned in + fpr1 and fpr2; + m64: + - 64-bit or smaller integral values are returned in GPR3 + - Single/double FP values are returned in fpr1; + - Long double FP values are returned in fpr1 and fpr2; + m64 Structures: + - If the structure could be accommodated in registers were it to be the + first argument to a routine, then it is returned in those registers. + m32/m64 structures otherwise: + - Larger structures values are allocated space and a pointer is passed + as the first argument. */ + switch (cif->rtype->type) + { + +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + flags |= FLAG_RETURNS_128BITS; + flags |= FLAG_RETURNS_FP; + break; +#endif + + case FFI_TYPE_DOUBLE: + flags |= FLAG_RETURNS_64BITS; + /* Fall through. */ + case FFI_TYPE_FLOAT: + flags |= FLAG_RETURNS_FP; + break; + + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: +#ifdef POWERPC64 + case FFI_TYPE_POINTER: +#endif + flags |= FLAG_RETURNS_64BITS; + break; + + case FFI_TYPE_STRUCT: +#if defined(POWERPC_DARWIN64) + { + /* Can we fit the struct into regs? */ + if (darwin64_struct_ret_by_value_p (cif->rtype)) + { + unsigned nfpr = 0; + flags |= FLAG_RETURNS_STRUCT; + if (cif->rtype->size != 16) + darwin64_scan_struct_for_floats (cif->rtype, &nfpr) ; + else + flags |= FLAG_RETURNS_128BITS; + /* Will be 0 for 16byte struct. */ + if (nfpr) + flags |= FLAG_RETURNS_FP; + } + else /* By ref. */ + { + flags |= FLAG_RETVAL_REFERENCE; + flags |= FLAG_RETURNS_NOTHING; + intarg_count++; + } + } +#elif defined(DARWIN_PPC) + if (cif->rtype->size <= 4) + flags |= FLAG_RETURNS_STRUCT; + else /* else by reference. */ + { + flags |= FLAG_RETVAL_REFERENCE; + flags |= FLAG_RETURNS_NOTHING; + intarg_count++; + } +#else /* assume we pass by ref. */ + flags |= FLAG_RETVAL_REFERENCE; + flags |= FLAG_RETURNS_NOTHING; + intarg_count++; +#endif + break; + case FFI_TYPE_VOID: + flags |= FLAG_RETURNS_NOTHING; + break; + + default: + /* Returns 32-bit integer, or similar. Nothing to do here. */ + break; + } + + /* The first NUM_GPR_ARG_REGISTERS words of integer arguments, and the + first NUM_FPR_ARG_REGISTERS fp arguments, go in registers; the rest + goes on the stack. + ??? Structures are passed as a pointer to a copy of the structure. + Stuff on the stack needs to keep proper alignment. + For m64 the count is effectively of half-GPRs. */ + for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) + { + unsigned align_words; + switch ((*ptr)->type) + { + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + fparg_count++; +#if !defined(POWERPC_DARWIN64) + /* If this FP arg is going on the stack, it must be + 8-byte-aligned. */ + if (fparg_count > NUM_FPR_ARG_REGISTERS + && (intarg_count & 0x01) != 0) + intarg_count++; +#endif + break; + +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + fparg_count += 2; + /* If this FP arg is going on the stack, it must be + 16-byte-aligned. */ + if (fparg_count >= NUM_FPR_ARG_REGISTERS) +#if defined (POWERPC64) + intarg_count = FFI_ALIGN(intarg_count, 2); +#else + intarg_count = FFI_ALIGN(intarg_count, 4); +#endif + break; +#endif + + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: +#if defined(POWERPC64) + intarg_count++; +#else + /* 'long long' arguments are passed as two words, but + either both words must fit in registers or both go + on the stack. If they go on the stack, they must + be 8-byte-aligned. */ + if (intarg_count == NUM_GPR_ARG_REGISTERS-1 + || (intarg_count >= NUM_GPR_ARG_REGISTERS + && (intarg_count & 0x01) != 0)) + intarg_count++; + intarg_count += 2; +#endif + break; + + case FFI_TYPE_STRUCT: + size_al = (*ptr)->size; +#if defined(POWERPC_DARWIN64) + align_words = (*ptr)->alignment >> 3; + if (align_words) + intarg_count = FFI_ALIGN(intarg_count, align_words); + /* Base size of the struct. */ + intarg_count += (size_al + 7) / 8; + /* If 16 bytes then don't worry about floats. */ + if (size_al != 16) + /* Scan through for floats to be placed in regs. */ + darwin64_scan_struct_for_floats (*ptr, &fparg_count) ; +#else + align_words = (*ptr)->alignment >> 2; + if (align_words) + intarg_count = FFI_ALIGN(intarg_count, align_words); + /* If the first member of the struct is a double, then align + the struct to double-word. + if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE) + size_al = FFI_ALIGN((*ptr)->size, 8); */ +# ifdef POWERPC64 + intarg_count += (size_al + 7) / 8; +# else + intarg_count += (size_al + 3) / 4; +# endif +#endif + break; + + default: + /* Everything else is passed as a 4-byte word in a GPR, either + the object itself or a pointer to it. */ + intarg_count++; + break; + } + } + + if (fparg_count != 0) + flags |= FLAG_FP_ARGUMENTS; + +#if defined(POWERPC_DARWIN64) + /* Space to image the FPR registers, if needed - which includes when they might be + used in a struct return. */ + if (fparg_count != 0 + || ((flags & FLAG_RETURNS_STRUCT) + && (flags & FLAG_RETURNS_FP))) + bytes += NUM_FPR_ARG_REGISTERS * sizeof(double); +#else + /* Space for the FPR registers, if needed. */ + if (fparg_count != 0) + bytes += NUM_FPR_ARG_REGISTERS * sizeof(double); +#endif + + /* Stack space. */ +#ifdef POWERPC64 + if ((intarg_count + fparg_count) > NUM_GPR_ARG_REGISTERS) + bytes += (intarg_count + fparg_count) * sizeof(long); +#else + if ((intarg_count + 2 * fparg_count) > NUM_GPR_ARG_REGISTERS) + bytes += (intarg_count + 2 * fparg_count) * sizeof(long); +#endif + else + bytes += NUM_GPR_ARG_REGISTERS * sizeof(long); + + /* The stack space allocated needs to be a multiple of 16 bytes. */ + bytes = FFI_ALIGN(bytes, 16) ; + + cif->flags = flags; + cif->bytes = bytes; + + return FFI_OK; +} + +extern void ffi_call_AIX(extended_cif *, long, unsigned, unsigned *, + void (*fn)(void), void (*fn2)(void)); + +#if defined (FFI_GO_CLOSURES) +extern void ffi_call_go_AIX(extended_cif *, long, unsigned, unsigned *, + void (*fn)(void), void (*fn2)(void), void *closure); +#endif + +extern void ffi_call_DARWIN(extended_cif *, long, unsigned, unsigned *, + void (*fn)(void), void (*fn2)(void), ffi_type*); + +void +ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return + value address then we need to make one. */ + + if ((rvalue == NULL) && + (cif->rtype->type == FFI_TYPE_STRUCT)) + { + ecif.rvalue = alloca (cif->rtype->size); + } + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_AIX: + ffi_call_AIX(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn, + FFI_FN(ffi_prep_args)); + break; + case FFI_DARWIN: + ffi_call_DARWIN(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn, + FFI_FN(ffi_prep_args), cif->rtype); + break; + default: + FFI_ASSERT(0); + break; + } +} + +#if defined (FFI_GO_CLOSURES) +void +ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue, + void *closure) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return + value address then we need to make one. */ + + if ((rvalue == NULL) && + (cif->rtype->type == FFI_TYPE_STRUCT)) + { + ecif.rvalue = alloca (cif->rtype->size); + } + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_AIX: + ffi_call_go_AIX(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn, + FFI_FN(ffi_prep_args), closure); + break; + default: + FFI_ASSERT(0); + break; + } +} +#endif + +static void flush_icache(char *); +static void flush_range(char *, int); + +/* The layout of a function descriptor. A C function pointer really + points to one of these. */ + +typedef struct aix_fd_struct { + void *code_pointer; + void *toc; +} aix_fd; + +/* here I'd like to add the stack frame layout we use in darwin_closure.S + and aix_closure.S + + m32/m64 + + The stack layout looks like this: + + | Additional params... | | Higher address + ~ ~ ~ + | Parameters (at least 8*4/8=32/64) | | NUM_GPR_ARG_REGISTERS + |--------------------------------------------| | + | TOC=R2 (AIX) Reserved (Darwin) 4/8 | | + |--------------------------------------------| | + | Reserved 2*4/8 | | + |--------------------------------------------| | + | Space for callee's LR 4/8 | | + |--------------------------------------------| | + | Saved CR [low word for m64] 4/8 | | + |--------------------------------------------| | + | Current backchain pointer 4/8 |-/ Parent's frame. + |--------------------------------------------| <+ <<< on entry to ffi_closure_ASM + | Result Bytes 16 | | + |--------------------------------------------| | + ~ padding to 16-byte alignment ~ ~ + |--------------------------------------------| | + | NUM_FPR_ARG_REGISTERS slots | | + | here fp13 .. fp1 13*8 | | + |--------------------------------------------| | + | R3..R10 8*4/8=32/64 | | NUM_GPR_ARG_REGISTERS + |--------------------------------------------| | + | TOC=R2 (AIX) Reserved (Darwin) 4/8 | | + |--------------------------------------------| | stack | + | Reserved [compiler,binder] 2*4/8 | | grows | + |--------------------------------------------| | down V + | Space for callee's LR 4/8 | | + |--------------------------------------------| | lower addresses + | Saved CR [low word for m64] 4/8 | | + |--------------------------------------------| | stack pointer here + | Current backchain pointer 4/8 |-/ during + |--------------------------------------------| <<< ffi_closure_ASM. + +*/ + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + unsigned int *tramp; + struct ffi_aix_trampoline_struct *tramp_aix; + aix_fd *fd; + + switch (cif->abi) + { + case FFI_DARWIN: + + FFI_ASSERT (cif->abi == FFI_DARWIN); + + tramp = (unsigned int *) &closure->tramp[0]; +#if defined(POWERPC_DARWIN64) + tramp[0] = 0x7c0802a6; /* mflr r0 */ + tramp[1] = 0x429f0015; /* bcl- 20,4*cr7+so, +0x18 (L1) */ + /* We put the addresses here. */ + tramp[6] = 0x7d6802a6; /*L1: mflr r11 */ + tramp[7] = 0xe98b0000; /* ld r12,0(r11) function address */ + tramp[8] = 0x7c0803a6; /* mtlr r0 */ + tramp[9] = 0x7d8903a6; /* mtctr r12 */ + tramp[10] = 0xe96b0008; /* lwz r11,8(r11) static chain */ + tramp[11] = 0x4e800420; /* bctr */ + + *((unsigned long *)&tramp[2]) = (unsigned long) ffi_closure_ASM; /* function */ + *((unsigned long *)&tramp[4]) = (unsigned long) codeloc; /* context */ +#else + tramp[0] = 0x7c0802a6; /* mflr r0 */ + tramp[1] = 0x429f000d; /* bcl- 20,4*cr7+so,0x10 */ + tramp[4] = 0x7d6802a6; /* mflr r11 */ + tramp[5] = 0x818b0000; /* lwz r12,0(r11) function address */ + tramp[6] = 0x7c0803a6; /* mtlr r0 */ + tramp[7] = 0x7d8903a6; /* mtctr r12 */ + tramp[8] = 0x816b0004; /* lwz r11,4(r11) static chain */ + tramp[9] = 0x4e800420; /* bctr */ + tramp[2] = (unsigned long) ffi_closure_ASM; /* function */ + tramp[3] = (unsigned long) codeloc; /* context */ +#endif + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + /* Flush the icache. Only necessary on Darwin. */ + flush_range(codeloc, FFI_TRAMPOLINE_SIZE); + + break; + + case FFI_AIX: + + tramp_aix = (struct ffi_aix_trampoline_struct *) (closure->tramp); + fd = (aix_fd *)(void *)ffi_closure_ASM; + + FFI_ASSERT (cif->abi == FFI_AIX); + + tramp_aix->code_pointer = fd->code_pointer; + tramp_aix->toc = fd->toc; + tramp_aix->static_chain = codeloc; + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + break; + + default: + return FFI_BAD_ABI; + break; + } + return FFI_OK; +} + +#if defined (FFI_GO_CLOSURES) +ffi_status +ffi_prep_go_closure (ffi_go_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*)) +{ + switch (cif->abi) + { + case FFI_AIX: + + FFI_ASSERT (cif->abi == FFI_AIX); + + closure->tramp = (void *)ffi_go_closure_ASM; + closure->cif = cif; + closure->fun = fun; + return FFI_OK; + + // For now, ffi_prep_go_closure is only implemented for AIX, not for Darwin + default: + return FFI_BAD_ABI; + break; + } + return FFI_OK; +} +#endif + +static void +flush_icache(char *addr) +{ +#ifndef _AIX + __asm__ volatile ( + "dcbf 0,%0\n" + "\tsync\n" + "\ticbi 0,%0\n" + "\tsync\n" + "\tisync" + : : "r"(addr) : "memory"); +#endif +} + +static void +flush_range(char * addr1, int size) +{ +#define MIN_LINE_SIZE 32 + int i; + for (i = 0; i < size; i += MIN_LINE_SIZE) + flush_icache(addr1+i); + flush_icache(addr1+size-1); +} + +typedef union +{ + float f; + double d; +} ffi_dblfl; + +ffi_type * +ffi_closure_helper_DARWIN (ffi_closure *, void *, + unsigned long *, ffi_dblfl *); + +#if defined (FFI_GO_CLOSURES) +ffi_type * +ffi_go_closure_helper_DARWIN (ffi_go_closure*, void *, + unsigned long *, ffi_dblfl *); +#endif + +/* Basically the trampoline invokes ffi_closure_ASM, and on + entry, r11 holds the address of the closure. + After storing the registers that could possibly contain + parameters to be passed into the stack frame and setting + up space for a return value, ffi_closure_ASM invokes the + following helper function to do most of the work. */ + +static ffi_type * +ffi_closure_helper_common (ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, void *rvalue, + unsigned long *pgr, ffi_dblfl *pfr) +{ + /* rvalue is the pointer to space for return value in closure assembly + pgr is the pointer to where r3-r10 are stored in ffi_closure_ASM + pfr is the pointer to where f1-f13 are stored in ffi_closure_ASM. */ + + typedef double ldbits[2]; + + union ldu + { + ldbits lb; + long double ld; + }; + + void ** avalue; + ffi_type ** arg_types; + long i, avn; + ffi_dblfl * end_pfr = pfr + NUM_FPR_ARG_REGISTERS; + unsigned size_al; +#if defined(POWERPC_DARWIN64) + unsigned fpsused = 0; +#endif + + avalue = alloca (cif->nargs * sizeof(void *)); + + if (cif->rtype->type == FFI_TYPE_STRUCT) + { +#if defined(POWERPC_DARWIN64) + if (!darwin64_struct_ret_by_value_p (cif->rtype)) + { + /* Won't fit into the regs - return by ref. */ + rvalue = (void *) *pgr; + pgr++; + } +#elif defined(DARWIN_PPC) + if (cif->rtype->size > 4) + { + rvalue = (void *) *pgr; + pgr++; + } +#else /* assume we return by ref. */ + rvalue = (void *) *pgr; + pgr++; +#endif + } + + i = 0; + avn = cif->nargs; + arg_types = cif->arg_types; + + /* Grab the addresses of the arguments from the stack frame. */ + while (i < avn) + { + switch (arg_types[i]->type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: +#if defined(POWERPC64) + avalue[i] = (char *) pgr + 7; +#else + avalue[i] = (char *) pgr + 3; +#endif + pgr++; + break; + + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: +#if defined(POWERPC64) + avalue[i] = (char *) pgr + 6; +#else + avalue[i] = (char *) pgr + 2; +#endif + pgr++; + break; + + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: +#if defined(POWERPC64) + avalue[i] = (char *) pgr + 4; +#else + case FFI_TYPE_POINTER: + avalue[i] = pgr; +#endif + pgr++; + break; + + case FFI_TYPE_STRUCT: + size_al = arg_types[i]->size; +#if defined(POWERPC_DARWIN64) + pgr = (unsigned long *)FFI_ALIGN((char *)pgr, arg_types[i]->alignment); + if (size_al < 3 || size_al == 4) + { + avalue[i] = ((char *)pgr)+8-size_al; + if (arg_types[i]->elements[0]->type == FFI_TYPE_FLOAT + && fpsused < NUM_FPR_ARG_REGISTERS) + { + *(float *)pgr = (float) *(double *)pfr; + pfr++; + fpsused++; + } + } + else + { + if (size_al != 16) + pfr = (ffi_dblfl *) + darwin64_struct_floats_to_mem (arg_types[i], (char *)pgr, + (double *)pfr, &fpsused); + avalue[i] = pgr; + } + pgr += (size_al + 7) / 8; +#else + /* If the first member of the struct is a double, then align + the struct to double-word. */ + if (arg_types[i]->elements[0]->type == FFI_TYPE_DOUBLE) + size_al = FFI_ALIGN(arg_types[i]->size, 8); +# if defined(POWERPC64) + FFI_ASSERT (cif->abi != FFI_DARWIN); + avalue[i] = pgr; + pgr += (size_al + 7) / 8; +# else + /* Structures that match the basic modes (QI 1 byte, HI 2 bytes, + SI 4 bytes) are aligned as if they were those modes. */ + if (size_al < 3 && cif->abi == FFI_DARWIN) + avalue[i] = (char*) pgr + 4 - size_al; + else + avalue[i] = pgr; + pgr += (size_al + 3) / 4; +# endif +#endif + break; + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: +#if defined(POWERPC64) + case FFI_TYPE_POINTER: + avalue[i] = pgr; + pgr++; + break; +#else + /* Long long ints are passed in two gpr's. */ + avalue[i] = pgr; + pgr += 2; + break; +#endif + + case FFI_TYPE_FLOAT: + /* A float value consumes a GPR. + There are 13 64bit floating point registers. */ + if (pfr < end_pfr) + { + double temp = pfr->d; + pfr->f = (float) temp; + avalue[i] = pfr; + pfr++; + } + else + { + avalue[i] = pgr; + } + pgr++; + break; + + case FFI_TYPE_DOUBLE: + /* A double value consumes two GPRs. + There are 13 64bit floating point registers. */ + if (pfr < end_pfr) + { + avalue[i] = pfr; + pfr++; + } + else + { + avalue[i] = pgr; + } +#ifdef POWERPC64 + pgr++; +#else + pgr += 2; +#endif + break; + +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + + case FFI_TYPE_LONGDOUBLE: +#ifdef POWERPC64 + if (pfr + 1 < end_pfr) + { + avalue[i] = pfr; + pfr += 2; + } + else + { + if (pfr < end_pfr) + { + *pgr = *(unsigned long *) pfr; + pfr++; + } + avalue[i] = pgr; + } + pgr += 2; +#else /* POWERPC64 */ + /* A long double value consumes four GPRs and two FPRs. + There are 13 64bit floating point registers. */ + if (pfr + 1 < end_pfr) + { + avalue[i] = pfr; + pfr += 2; + } + /* Here we have the situation where one part of the long double + is stored in fpr13 and the other part is already on the stack. + We use a union to pass the long double to avalue[i]. */ + else if (pfr + 1 == end_pfr) + { + union ldu temp_ld; + memcpy (&temp_ld.lb[0], pfr, sizeof(ldbits)); + memcpy (&temp_ld.lb[1], pgr + 2, sizeof(ldbits)); + avalue[i] = &temp_ld.ld; + pfr++; + } + else + { + avalue[i] = pgr; + } + pgr += 4; +#endif /* POWERPC64 */ + break; +#endif + default: + FFI_ASSERT(0); + } + i++; + } + + (fun) (cif, rvalue, avalue, user_data); + + /* Tell ffi_closure_ASM to perform return type promotions. */ + return cif->rtype; +} + +ffi_type * +ffi_closure_helper_DARWIN (ffi_closure *closure, void *rvalue, + unsigned long *pgr, ffi_dblfl *pfr) +{ + return ffi_closure_helper_common (closure->cif, closure->fun, + closure->user_data, rvalue, pgr, pfr); +} + +#if defined (FFI_GO_CLOSURES) +ffi_type * +ffi_go_closure_helper_DARWIN (ffi_go_closure *closure, void *rvalue, + unsigned long *pgr, ffi_dblfl *pfr) +{ + return ffi_closure_helper_common (closure->cif, closure->fun, + closure, rvalue, pgr, pfr); +} +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_linux64.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_linux64.c new file mode 100644 index 0000000..4d50878 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_linux64.c @@ -0,0 +1,1153 @@ +/* ----------------------------------------------------------------------- + ffi_linux64.c - Copyright (C) 2013 IBM + Copyright (C) 2011 Anthony Green + Copyright (C) 2011 Kyle Moffett + Copyright (C) 2008 Red Hat, Inc + Copyright (C) 2007, 2008 Free Software Foundation, Inc + Copyright (c) 1998 Geoffrey Keating + + PowerPC Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include "ffi.h" + +#ifdef POWERPC64 +#include "ffi_common.h" +#include "ffi_powerpc.h" + + +/* About the LINUX64 ABI. */ +enum { + NUM_GPR_ARG_REGISTERS64 = 8, + NUM_FPR_ARG_REGISTERS64 = 13, + NUM_VEC_ARG_REGISTERS64 = 12, +}; +enum { ASM_NEEDS_REGISTERS64 = 4 }; + + +#if HAVE_LONG_DOUBLE_VARIANT && FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE +/* Adjust size of ffi_type_longdouble. */ +void FFI_HIDDEN +ffi_prep_types_linux64 (ffi_abi abi) +{ + if ((abi & (FFI_LINUX | FFI_LINUX_LONG_DOUBLE_128)) == FFI_LINUX) + { + ffi_type_longdouble.size = 8; + ffi_type_longdouble.alignment = 8; + } + else + { + ffi_type_longdouble.size = 16; + ffi_type_longdouble.alignment = 16; + } +} +#endif + + +static unsigned int +discover_homogeneous_aggregate (ffi_abi abi, + const ffi_type *t, + unsigned int *elnum) +{ + switch (t->type) + { +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + /* 64-bit long doubles are equivalent to doubles. */ + if ((abi & FFI_LINUX_LONG_DOUBLE_128) == 0) + { + *elnum = 1; + return FFI_TYPE_DOUBLE; + } + /* IBM extended precision values use unaligned pairs + of FPRs, but according to the ABI must be considered + distinct from doubles. They are also limited to a + maximum of four members in a homogeneous aggregate. */ + else if ((abi & FFI_LINUX_LONG_DOUBLE_IEEE128) == 0) + { + *elnum = 2; + return FFI_TYPE_LONGDOUBLE; + } + /* Fall through. */ +#endif + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + *elnum = 1; + return (int) t->type; + + case FFI_TYPE_STRUCT:; + { + unsigned int base_elt = 0, total_elnum = 0; + ffi_type **el = t->elements; + while (*el) + { + unsigned int el_elt, el_elnum = 0; + el_elt = discover_homogeneous_aggregate (abi, *el, &el_elnum); + if (el_elt == 0 + || (base_elt && base_elt != el_elt)) + return 0; + base_elt = el_elt; + total_elnum += el_elnum; +#if _CALL_ELF == 2 + if (total_elnum > 8) + return 0; +#else + if (total_elnum > 1) + return 0; +#endif + el++; + } + *elnum = total_elnum; + return base_elt; + } + + default: + return 0; + } +} + + +/* Perform machine dependent cif processing */ +static ffi_status +ffi_prep_cif_linux64_core (ffi_cif *cif) +{ + ffi_type **ptr; + unsigned bytes; + unsigned i, fparg_count = 0, intarg_count = 0, vecarg_count = 0; + unsigned flags = cif->flags; + unsigned elt, elnum, rtype; + +#if FFI_TYPE_LONGDOUBLE == FFI_TYPE_DOUBLE + /* If compiled without long double support... */ + if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0 || + (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) + return FFI_BAD_ABI; +#elif !defined(__VEC__) + /* If compiled without vector register support (used by assembly)... */ + if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) + return FFI_BAD_ABI; +#else + /* If the IEEE128 flag is set, but long double is only 64 bits wide... */ + if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) == 0 && + (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) + return FFI_BAD_ABI; +#endif + + /* The machine-independent calculation of cif->bytes doesn't work + for us. Redo the calculation. */ +#if _CALL_ELF == 2 + /* Space for backchain, CR, LR, TOC and the asm's temp regs. */ + bytes = (4 + ASM_NEEDS_REGISTERS64) * sizeof (long); + + /* Space for the general registers. */ + bytes += NUM_GPR_ARG_REGISTERS64 * sizeof (long); +#else + /* Space for backchain, CR, LR, cc/ld doubleword, TOC and the asm's temp + regs. */ + bytes = (6 + ASM_NEEDS_REGISTERS64) * sizeof (long); + + /* Space for the mandatory parm save area and general registers. */ + bytes += 2 * NUM_GPR_ARG_REGISTERS64 * sizeof (long); +#endif + + /* Return value handling. */ + rtype = cif->rtype->type; +#if _CALL_ELF == 2 +homogeneous: +#endif + switch (rtype) + { +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) + { + flags |= FLAG_RETURNS_VEC; + break; + } + if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0) + flags |= FLAG_RETURNS_128BITS; + /* Fall through. */ +#endif + case FFI_TYPE_DOUBLE: + flags |= FLAG_RETURNS_64BITS; + /* Fall through. */ + case FFI_TYPE_FLOAT: + flags |= FLAG_RETURNS_FP; + break; + + case FFI_TYPE_UINT128: + flags |= FLAG_RETURNS_128BITS; + /* Fall through. */ + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_POINTER: + flags |= FLAG_RETURNS_64BITS; + break; + + case FFI_TYPE_STRUCT: +#if _CALL_ELF == 2 + elt = discover_homogeneous_aggregate (cif->abi, cif->rtype, &elnum); + if (elt) + { + flags |= FLAG_RETURNS_SMST; + rtype = elt; + goto homogeneous; + } + if (cif->rtype->size <= 16) + { + flags |= FLAG_RETURNS_SMST; + break; + } +#endif + intarg_count++; + flags |= FLAG_RETVAL_REFERENCE; + /* Fall through. */ + case FFI_TYPE_VOID: + flags |= FLAG_RETURNS_NOTHING; + break; + + default: + /* Returns 32-bit integer, or similar. Nothing to do here. */ + break; + } + + for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) + { + unsigned int align; + + switch ((*ptr)->type) + { +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) + { + vecarg_count++; + /* Align to 16 bytes, plus the 16-byte argument. */ + intarg_count = (intarg_count + 3) & ~0x1; + if (vecarg_count > NUM_VEC_ARG_REGISTERS64) + flags |= FLAG_ARG_NEEDS_PSAVE; + break; + } + if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0) + { + fparg_count++; + intarg_count++; + } + /* Fall through. */ +#endif + case FFI_TYPE_DOUBLE: + case FFI_TYPE_FLOAT: + fparg_count++; + intarg_count++; + if (fparg_count > NUM_FPR_ARG_REGISTERS64) + flags |= FLAG_ARG_NEEDS_PSAVE; + break; + + case FFI_TYPE_STRUCT: + if ((cif->abi & FFI_LINUX_STRUCT_ALIGN) != 0) + { + align = (*ptr)->alignment; + if (align > 16) + align = 16; + align = align / 8; + if (align > 1) + intarg_count = FFI_ALIGN (intarg_count, align); + } + intarg_count += ((*ptr)->size + 7) / 8; + elt = discover_homogeneous_aggregate (cif->abi, *ptr, &elnum); +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + if (elt == FFI_TYPE_LONGDOUBLE && + (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) + { + vecarg_count += elnum; + if (vecarg_count > NUM_VEC_ARG_REGISTERS64) + flags |= FLAG_ARG_NEEDS_PSAVE; + break; + } + else +#endif + if (elt) + { + fparg_count += elnum; + if (fparg_count > NUM_FPR_ARG_REGISTERS64) + flags |= FLAG_ARG_NEEDS_PSAVE; + } + else + { + if (intarg_count > NUM_GPR_ARG_REGISTERS64) + flags |= FLAG_ARG_NEEDS_PSAVE; + } + break; + + case FFI_TYPE_POINTER: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_INT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + /* Everything else is passed as a 8-byte word in a GPR, either + the object itself or a pointer to it. */ + intarg_count++; + if (intarg_count > NUM_GPR_ARG_REGISTERS64) + flags |= FLAG_ARG_NEEDS_PSAVE; + break; + default: + FFI_ASSERT (0); + } + } + + if (fparg_count != 0) + flags |= FLAG_FP_ARGUMENTS; + if (intarg_count > 4) + flags |= FLAG_4_GPR_ARGUMENTS; + if (vecarg_count != 0) + flags |= FLAG_VEC_ARGUMENTS; + + /* Space for the FPR registers, if needed. */ + if (fparg_count != 0) + bytes += NUM_FPR_ARG_REGISTERS64 * sizeof (double); + /* Space for the vector registers, if needed, aligned to 16 bytes. */ + if (vecarg_count != 0) { + bytes = (bytes + 15) & ~0xF; + bytes += NUM_VEC_ARG_REGISTERS64 * sizeof (float128); + } + + /* Stack space. */ +#if _CALL_ELF == 2 + if ((flags & FLAG_ARG_NEEDS_PSAVE) != 0) + bytes += intarg_count * sizeof (long); +#else + if (intarg_count > NUM_GPR_ARG_REGISTERS64) + bytes += (intarg_count - NUM_GPR_ARG_REGISTERS64) * sizeof (long); +#endif + + /* The stack space allocated needs to be a multiple of 16 bytes. */ + bytes = (bytes + 15) & ~0xF; + + cif->flags = flags; + cif->bytes = bytes; + + return FFI_OK; +} + +ffi_status FFI_HIDDEN +ffi_prep_cif_linux64 (ffi_cif *cif) +{ + if ((cif->abi & FFI_LINUX) != 0) + cif->nfixedargs = cif->nargs; +#if _CALL_ELF != 2 + else if (cif->abi == FFI_COMPAT_LINUX64) + { + /* This call is from old code. Don't touch cif->nfixedargs + since old code will be using a smaller cif. */ + cif->flags |= FLAG_COMPAT; + /* Translate to new abi value. */ + cif->abi = FFI_LINUX | FFI_LINUX_LONG_DOUBLE_128; + } +#endif + else + return FFI_BAD_ABI; + return ffi_prep_cif_linux64_core (cif); +} + +ffi_status FFI_HIDDEN +ffi_prep_cif_linux64_var (ffi_cif *cif, + unsigned int nfixedargs, + unsigned int ntotalargs MAYBE_UNUSED) +{ + if ((cif->abi & FFI_LINUX) != 0) + cif->nfixedargs = nfixedargs; +#if _CALL_ELF != 2 + else if (cif->abi == FFI_COMPAT_LINUX64) + { + /* This call is from old code. Don't touch cif->nfixedargs + since old code will be using a smaller cif. */ + cif->flags |= FLAG_COMPAT; + /* Translate to new abi value. */ + cif->abi = FFI_LINUX | FFI_LINUX_LONG_DOUBLE_128; + } +#endif + else + return FFI_BAD_ABI; +#if _CALL_ELF == 2 + cif->flags |= FLAG_ARG_NEEDS_PSAVE; +#endif + return ffi_prep_cif_linux64_core (cif); +} + + +/* ffi_prep_args64 is called by the assembly routine once stack space + has been allocated for the function's arguments. + + The stack layout we want looks like this: + + | Ret addr from ffi_call_LINUX64 8bytes | higher addresses + |--------------------------------------------| + | CR save area 8bytes | + |--------------------------------------------| + | Previous backchain pointer 8 | stack pointer here + |--------------------------------------------|<+ <<< on entry to + | Saved r28-r31 4*8 | | ffi_call_LINUX64 + |--------------------------------------------| | + | GPR registers r3-r10 8*8 | | + |--------------------------------------------| | + | FPR registers f1-f13 (optional) 13*8 | | + |--------------------------------------------| | + | VEC registers v2-v13 (optional) 12*16 | | + |--------------------------------------------| | + | Parameter save area | | + |--------------------------------------------| | + | TOC save area 8 | | + |--------------------------------------------| | stack | + | Linker doubleword 8 | | grows | + |--------------------------------------------| | down V + | Compiler doubleword 8 | | + |--------------------------------------------| | lower addresses + | Space for callee's LR 8 | | + |--------------------------------------------| | + | CR save area 8 | | + |--------------------------------------------| | stack pointer here + | Current backchain pointer 8 |-/ during + |--------------------------------------------| <<< ffi_call_LINUX64 + +*/ + +void FFI_HIDDEN +ffi_prep_args64 (extended_cif *ecif, unsigned long *const stack) +{ + const unsigned long bytes = ecif->cif->bytes; + const unsigned long flags = ecif->cif->flags; + + typedef union + { + char *c; + unsigned long *ul; + float *f; + double *d; + float128 *f128; + size_t p; + } valp; + + /* 'stacktop' points at the previous backchain pointer. */ + valp stacktop; + + /* 'next_arg' points at the space for gpr3, and grows upwards as + we use GPR registers, then continues at rest. */ + valp gpr_base; + valp gpr_end; + valp rest; + valp next_arg; + + /* 'fpr_base' points at the space for f1, and grows upwards as + we use FPR registers. */ + valp fpr_base; + unsigned int fparg_count; + + /* 'vec_base' points at the space for v2, and grows upwards as + we use vector registers. */ + valp vec_base; + unsigned int vecarg_count; + + unsigned int i, words, nargs, nfixedargs; + ffi_type **ptr; + double double_tmp; + union + { + void **v; + char **c; + signed char **sc; + unsigned char **uc; + signed short **ss; + unsigned short **us; + signed int **si; + unsigned int **ui; + unsigned long **ul; + float **f; + double **d; + float128 **f128; + } p_argv; + unsigned long gprvalue; + unsigned long align; + + stacktop.c = (char *) stack + bytes; + gpr_base.ul = stacktop.ul - ASM_NEEDS_REGISTERS64 - NUM_GPR_ARG_REGISTERS64; + gpr_end.ul = gpr_base.ul + NUM_GPR_ARG_REGISTERS64; +#if _CALL_ELF == 2 + rest.ul = stack + 4 + NUM_GPR_ARG_REGISTERS64; +#else + rest.ul = stack + 6 + NUM_GPR_ARG_REGISTERS64; +#endif + fpr_base.d = gpr_base.d - NUM_FPR_ARG_REGISTERS64; + fparg_count = 0; + /* Place the vector args below the FPRs, if used, else the GPRs. */ + if (ecif->cif->flags & FLAG_FP_ARGUMENTS) + vec_base.p = fpr_base.p & ~0xF; + else + vec_base.p = gpr_base.p; + vec_base.f128 -= NUM_VEC_ARG_REGISTERS64; + vecarg_count = 0; + next_arg.ul = gpr_base.ul; + + /* Check that everything starts aligned properly. */ + FFI_ASSERT (((unsigned long) (char *) stack & 0xF) == 0); + FFI_ASSERT (((unsigned long) stacktop.c & 0xF) == 0); + FFI_ASSERT (((unsigned long) gpr_base.c & 0xF) == 0); + FFI_ASSERT (((unsigned long) gpr_end.c & 0xF) == 0); + FFI_ASSERT (((unsigned long) vec_base.c & 0xF) == 0); + FFI_ASSERT ((bytes & 0xF) == 0); + + /* Deal with return values that are actually pass-by-reference. */ + if (flags & FLAG_RETVAL_REFERENCE) + *next_arg.ul++ = (unsigned long) (char *) ecif->rvalue; + + /* Now for the arguments. */ + p_argv.v = ecif->avalue; + nargs = ecif->cif->nargs; +#if _CALL_ELF != 2 + nfixedargs = (unsigned) -1; + if ((flags & FLAG_COMPAT) == 0) +#endif + nfixedargs = ecif->cif->nfixedargs; + for (ptr = ecif->cif->arg_types, i = 0; + i < nargs; + i++, ptr++, p_argv.v++) + { + unsigned int elt, elnum; + + switch ((*ptr)->type) + { +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + if ((ecif->cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) + { + next_arg.p = FFI_ALIGN (next_arg.p, 16); + if (next_arg.ul == gpr_end.ul) + next_arg.ul = rest.ul; + if (vecarg_count < NUM_VEC_ARG_REGISTERS64 && i < nfixedargs) + memcpy (vec_base.f128++, *p_argv.f128, sizeof (float128)); + else + memcpy (next_arg.f128, *p_argv.f128, sizeof (float128)); + if (++next_arg.f128 == gpr_end.f128) + next_arg.f128 = rest.f128; + vecarg_count++; + FFI_ASSERT (__LDBL_MANT_DIG__ == 113); + FFI_ASSERT (flags & FLAG_VEC_ARGUMENTS); + break; + } + if ((ecif->cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0) + { + double_tmp = (*p_argv.d)[0]; + if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs) + { + *fpr_base.d++ = double_tmp; +# if _CALL_ELF != 2 + if ((flags & FLAG_COMPAT) != 0) + *next_arg.d = double_tmp; +# endif + } + else + *next_arg.d = double_tmp; + if (++next_arg.ul == gpr_end.ul) + next_arg.ul = rest.ul; + fparg_count++; + double_tmp = (*p_argv.d)[1]; + if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs) + { + *fpr_base.d++ = double_tmp; +# if _CALL_ELF != 2 + if ((flags & FLAG_COMPAT) != 0) + *next_arg.d = double_tmp; +# endif + } + else + *next_arg.d = double_tmp; + if (++next_arg.ul == gpr_end.ul) + next_arg.ul = rest.ul; + fparg_count++; + FFI_ASSERT (__LDBL_MANT_DIG__ == 106); + FFI_ASSERT (flags & FLAG_FP_ARGUMENTS); + break; + } + /* Fall through. */ +#endif + case FFI_TYPE_DOUBLE: +#if _CALL_ELF != 2 + do_double: +#endif + double_tmp = **p_argv.d; + if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs) + { + *fpr_base.d++ = double_tmp; +#if _CALL_ELF != 2 + if ((flags & FLAG_COMPAT) != 0) + *next_arg.d = double_tmp; +#endif + } + else + *next_arg.d = double_tmp; + if (++next_arg.ul == gpr_end.ul) + next_arg.ul = rest.ul; + fparg_count++; + FFI_ASSERT (flags & FLAG_FP_ARGUMENTS); + break; + + case FFI_TYPE_FLOAT: +#if _CALL_ELF != 2 + do_float: +#endif + double_tmp = **p_argv.f; + if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs) + { + *fpr_base.d++ = double_tmp; +#if _CALL_ELF != 2 + if ((flags & FLAG_COMPAT) != 0) + { +# ifndef __LITTLE_ENDIAN__ + next_arg.f[1] = (float) double_tmp; +# else + next_arg.f[0] = (float) double_tmp; +# endif + } +#endif + } + else + { +# ifndef __LITTLE_ENDIAN__ + next_arg.f[1] = (float) double_tmp; +# else + next_arg.f[0] = (float) double_tmp; +# endif + } + if (++next_arg.ul == gpr_end.ul) + next_arg.ul = rest.ul; + fparg_count++; + FFI_ASSERT (flags & FLAG_FP_ARGUMENTS); + break; + + case FFI_TYPE_STRUCT: + if ((ecif->cif->abi & FFI_LINUX_STRUCT_ALIGN) != 0) + { + align = (*ptr)->alignment; + if (align > 16) + align = 16; + if (align > 1) + { + next_arg.p = FFI_ALIGN (next_arg.p, align); + if (next_arg.ul == gpr_end.ul) + next_arg.ul = rest.ul; + } + } + elt = discover_homogeneous_aggregate (ecif->cif->abi, *ptr, &elnum); + if (elt) + { +#if _CALL_ELF == 2 + union { + void *v; + float *f; + double *d; + float128 *f128; + } arg; + + arg.v = *p_argv.v; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + if (elt == FFI_TYPE_LONGDOUBLE && + (ecif->cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) + { + do + { + if (vecarg_count < NUM_VEC_ARG_REGISTERS64 + && i < nfixedargs) + memcpy (vec_base.f128++, arg.f128, sizeof (float128)); + else + memcpy (next_arg.f128, arg.f128++, sizeof (float128)); + if (++next_arg.f128 == gpr_end.f128) + next_arg.f128 = rest.f128; + vecarg_count++; + } + while (--elnum != 0); + } + else +#endif + if (elt == FFI_TYPE_FLOAT) + { + do + { + double_tmp = *arg.f++; + if (fparg_count < NUM_FPR_ARG_REGISTERS64 + && i < nfixedargs) + *fpr_base.d++ = double_tmp; + else + *next_arg.f = (float) double_tmp; + if (++next_arg.f == gpr_end.f) + next_arg.f = rest.f; + fparg_count++; + } + while (--elnum != 0); + if ((next_arg.p & 7) != 0) + if (++next_arg.f == gpr_end.f) + next_arg.f = rest.f; + } + else + do + { + double_tmp = *arg.d++; + if (fparg_count < NUM_FPR_ARG_REGISTERS64 && i < nfixedargs) + *fpr_base.d++ = double_tmp; + else + *next_arg.d = double_tmp; + if (++next_arg.d == gpr_end.d) + next_arg.d = rest.d; + fparg_count++; + } + while (--elnum != 0); +#else + if (elt == FFI_TYPE_FLOAT) + goto do_float; + else + goto do_double; +#endif + } + else + { + words = ((*ptr)->size + 7) / 8; + if (next_arg.ul >= gpr_base.ul && next_arg.ul + words > gpr_end.ul) + { + size_t first = gpr_end.c - next_arg.c; + memcpy (next_arg.c, *p_argv.c, first); + memcpy (rest.c, *p_argv.c + first, (*ptr)->size - first); + next_arg.c = rest.c + words * 8 - first; + } + else + { + char *where = next_arg.c; + +#ifndef __LITTLE_ENDIAN__ + /* Structures with size less than eight bytes are passed + left-padded. */ + if ((*ptr)->size < 8) + where += 8 - (*ptr)->size; +#endif + memcpy (where, *p_argv.c, (*ptr)->size); + next_arg.ul += words; + if (next_arg.ul == gpr_end.ul) + next_arg.ul = rest.ul; + } + } + break; + + case FFI_TYPE_UINT8: + gprvalue = **p_argv.uc; + goto putgpr; + case FFI_TYPE_SINT8: + gprvalue = **p_argv.sc; + goto putgpr; + case FFI_TYPE_UINT16: + gprvalue = **p_argv.us; + goto putgpr; + case FFI_TYPE_SINT16: + gprvalue = **p_argv.ss; + goto putgpr; + case FFI_TYPE_UINT32: + gprvalue = **p_argv.ui; + goto putgpr; + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + gprvalue = **p_argv.si; + goto putgpr; + + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_POINTER: + gprvalue = **p_argv.ul; + putgpr: + *next_arg.ul++ = gprvalue; + if (next_arg.ul == gpr_end.ul) + next_arg.ul = rest.ul; + break; + } + } + + FFI_ASSERT (flags & FLAG_4_GPR_ARGUMENTS + || (next_arg.ul >= gpr_base.ul + && next_arg.ul <= gpr_base.ul + 4)); +} + + +#if _CALL_ELF == 2 +#define MIN_CACHE_LINE_SIZE 8 + +static void +flush_icache (char *wraddr, char *xaddr, int size) +{ + int i; + for (i = 0; i < size; i += MIN_CACHE_LINE_SIZE) + __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;" + : : "r" (xaddr + i), "r" (wraddr + i) : "memory"); + __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;" "sync;" "isync;" + : : "r"(xaddr + size - 1), "r"(wraddr + size - 1) + : "memory"); +} +#endif + + +ffi_status FFI_HIDDEN +ffi_prep_closure_loc_linux64 (ffi_closure *closure, + ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + void *codeloc) +{ +#if _CALL_ELF == 2 + unsigned int *tramp = (unsigned int *) &closure->tramp[0]; + + if (cif->abi < FFI_LINUX || cif->abi >= FFI_LAST_ABI) + return FFI_BAD_ABI; + + tramp[0] = 0xe96c0018; /* 0: ld 11,2f-0b(12) */ + tramp[1] = 0xe98c0010; /* ld 12,1f-0b(12) */ + tramp[2] = 0x7d8903a6; /* mtctr 12 */ + tramp[3] = 0x4e800420; /* bctr */ + /* 1: .quad function_addr */ + /* 2: .quad context */ + *(void **) &tramp[4] = (void *) ffi_closure_LINUX64; + *(void **) &tramp[6] = codeloc; + flush_icache ((char *) tramp, (char *) codeloc, 4 * 4); +#else + void **tramp = (void **) &closure->tramp[0]; + + if (cif->abi < FFI_LINUX || cif->abi >= FFI_LAST_ABI) + return FFI_BAD_ABI; + + /* Copy function address and TOC from ffi_closure_LINUX64 OPD. */ + memcpy (&tramp[0], (void **) ffi_closure_LINUX64, sizeof (void *)); + tramp[1] = codeloc; + memcpy (&tramp[2], (void **) ffi_closure_LINUX64 + 1, sizeof (void *)); +#endif + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + return FFI_OK; +} + + +int FFI_HIDDEN +ffi_closure_helper_LINUX64 (ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + void *rvalue, + unsigned long *pst, + ffi_dblfl *pfr, + float128 *pvec) +{ + /* rvalue is the pointer to space for return value in closure assembly */ + /* pst is the pointer to parameter save area + (r3-r10 are stored into its first 8 slots by ffi_closure_LINUX64) */ + /* pfr is the pointer to where f1-f13 are stored in ffi_closure_LINUX64 */ + /* pvec is the pointer to where v2-v13 are stored in ffi_closure_LINUX64 */ + + void **avalue; + ffi_type **arg_types; + unsigned long i, avn, nfixedargs; + ffi_dblfl *end_pfr = pfr + NUM_FPR_ARG_REGISTERS64; + float128 *end_pvec = pvec + NUM_VEC_ARG_REGISTERS64; + unsigned long align; + + avalue = alloca (cif->nargs * sizeof (void *)); + + /* Copy the caller's structure return value address so that the + closure returns the data directly to the caller. */ + if (cif->rtype->type == FFI_TYPE_STRUCT + && (cif->flags & FLAG_RETURNS_SMST) == 0) + { + rvalue = (void *) *pst; + pst++; + } + + i = 0; + avn = cif->nargs; +#if _CALL_ELF != 2 + nfixedargs = (unsigned) -1; + if ((cif->flags & FLAG_COMPAT) == 0) +#endif + nfixedargs = cif->nfixedargs; + arg_types = cif->arg_types; + + /* Grab the addresses of the arguments from the stack frame. */ + while (i < avn) + { + unsigned int elt, elnum; + + switch (arg_types[i]->type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: +#ifndef __LITTLE_ENDIAN__ + avalue[i] = (char *) pst + 7; + pst++; + break; +#endif + + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: +#ifndef __LITTLE_ENDIAN__ + avalue[i] = (char *) pst + 6; + pst++; + break; +#endif + + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: +#ifndef __LITTLE_ENDIAN__ + avalue[i] = (char *) pst + 4; + pst++; + break; +#endif + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_POINTER: + avalue[i] = pst; + pst++; + break; + + case FFI_TYPE_STRUCT: + if ((cif->abi & FFI_LINUX_STRUCT_ALIGN) != 0) + { + align = arg_types[i]->alignment; + if (align > 16) + align = 16; + if (align > 1) + pst = (unsigned long *) FFI_ALIGN ((size_t) pst, align); + } + elt = discover_homogeneous_aggregate (cif->abi, arg_types[i], &elnum); + if (elt) + { +#if _CALL_ELF == 2 + union { + void *v; + unsigned long *ul; + float *f; + double *d; + float128 *f128; + size_t p; + } to, from; + + /* Repackage the aggregate from its parts. The + aggregate size is not greater than the space taken by + the registers so store back to the register/parameter + save arrays. */ +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + if (elt == FFI_TYPE_LONGDOUBLE && + (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) + { + if (pvec + elnum <= end_pvec) + to.v = pvec; + else + to.v = pst; + } + else +#endif + if (pfr + elnum <= end_pfr) + to.v = pfr; + else + to.v = pst; + + avalue[i] = to.v; + from.ul = pst; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + if (elt == FFI_TYPE_LONGDOUBLE && + (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) + { + do + { + if (pvec < end_pvec && i < nfixedargs) + memcpy (to.f128, pvec++, sizeof (float128)); + else + memcpy (to.f128, from.f128, sizeof (float128)); + to.f128++; + from.f128++; + } + while (--elnum != 0); + } + else +#endif + if (elt == FFI_TYPE_FLOAT) + { + do + { + if (pfr < end_pfr && i < nfixedargs) + { + *to.f = (float) pfr->d; + pfr++; + } + else + *to.f = *from.f; + to.f++; + from.f++; + } + while (--elnum != 0); + } + else + { + do + { + if (pfr < end_pfr && i < nfixedargs) + { + *to.d = pfr->d; + pfr++; + } + else + *to.d = *from.d; + to.d++; + from.d++; + } + while (--elnum != 0); + } +#else + if (elt == FFI_TYPE_FLOAT) + goto do_float; + else + goto do_double; +#endif + } + else + { +#ifndef __LITTLE_ENDIAN__ + /* Structures with size less than eight bytes are passed + left-padded. */ + if (arg_types[i]->size < 8) + avalue[i] = (char *) pst + 8 - arg_types[i]->size; + else +#endif + avalue[i] = pst; + } + pst += (arg_types[i]->size + 7) / 8; + break; + +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + if ((cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) + { + if (((unsigned long) pst & 0xF) != 0) + ++pst; + if (pvec < end_pvec && i < nfixedargs) + avalue[i] = pvec++; + else + avalue[i] = pst; + pst += 2; + break; + } + else if ((cif->abi & FFI_LINUX_LONG_DOUBLE_128) != 0) + { + if (pfr + 1 < end_pfr && i + 1 < nfixedargs) + { + avalue[i] = pfr; + pfr += 2; + } + else + { + if (pfr < end_pfr && i < nfixedargs) + { + /* Passed partly in f13 and partly on the stack. + Move it all to the stack. */ + *pst = *(unsigned long *) pfr; + pfr++; + } + avalue[i] = pst; + } + pst += 2; + break; + } + /* Fall through. */ +#endif + case FFI_TYPE_DOUBLE: +#if _CALL_ELF != 2 + do_double: +#endif + /* On the outgoing stack all values are aligned to 8 */ + /* there are 13 64bit floating point registers */ + + if (pfr < end_pfr && i < nfixedargs) + { + avalue[i] = pfr; + pfr++; + } + else + avalue[i] = pst; + pst++; + break; + + case FFI_TYPE_FLOAT: +#if _CALL_ELF != 2 + do_float: +#endif + if (pfr < end_pfr && i < nfixedargs) + { + /* Float values are stored as doubles in the + ffi_closure_LINUX64 code. Fix them here. */ + pfr->f = (float) pfr->d; + avalue[i] = pfr; + pfr++; + } + else + { +#ifndef __LITTLE_ENDIAN__ + avalue[i] = (char *) pst + 4; +#else + avalue[i] = pst; +#endif + } + pst++; + break; + + default: + FFI_ASSERT (0); + } + + i++; + } + + (*fun) (cif, rvalue, avalue, user_data); + + /* Tell ffi_closure_LINUX64 how to perform return type promotions. */ + if ((cif->flags & FLAG_RETURNS_SMST) != 0) + { + if ((cif->flags & (FLAG_RETURNS_FP | FLAG_RETURNS_VEC)) == 0) + return FFI_V2_TYPE_SMALL_STRUCT + cif->rtype->size - 1; + else if ((cif->flags & FLAG_RETURNS_VEC) != 0) + return FFI_V2_TYPE_VECTOR_HOMOG; + else if ((cif->flags & FLAG_RETURNS_64BITS) != 0) + return FFI_V2_TYPE_DOUBLE_HOMOG; + else + return FFI_V2_TYPE_FLOAT_HOMOG; + } + if ((cif->flags & FLAG_RETURNS_VEC) != 0) + return FFI_V2_TYPE_VECTOR; + return cif->rtype->type; +} +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_powerpc.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_powerpc.h new file mode 100644 index 0000000..960a5c4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_powerpc.h @@ -0,0 +1,105 @@ +/* ----------------------------------------------------------------------- + ffi_powerpc.h - Copyright (C) 2013 IBM + Copyright (C) 2011 Anthony Green + Copyright (C) 2011 Kyle Moffett + Copyright (C) 2008 Red Hat, Inc + Copyright (C) 2007, 2008 Free Software Foundation, Inc + Copyright (c) 1998 Geoffrey Keating + + PowerPC Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +enum { + /* The assembly depends on these exact flags. */ + /* These go in cr7 */ + FLAG_RETURNS_SMST = 1 << (31-31), /* Used for FFI_SYSV small structs. */ + FLAG_RETURNS_NOTHING = 1 << (31-30), + FLAG_RETURNS_FP = 1 << (31-29), + FLAG_RETURNS_VEC = 1 << (31-28), + + /* These go in cr6 */ + FLAG_RETURNS_64BITS = 1 << (31-27), + FLAG_RETURNS_128BITS = 1 << (31-26), + + FLAG_COMPAT = 1 << (31- 8), /* Not used by assembly */ + + /* These go in cr1 */ + FLAG_ARG_NEEDS_COPY = 1 << (31- 7), /* Used by sysv code */ + FLAG_ARG_NEEDS_PSAVE = FLAG_ARG_NEEDS_COPY, /* Used by linux64 code */ + FLAG_FP_ARGUMENTS = 1 << (31- 6), /* cr1.eq; specified by ABI */ + FLAG_4_GPR_ARGUMENTS = 1 << (31- 5), + FLAG_RETVAL_REFERENCE = 1 << (31- 4), + FLAG_VEC_ARGUMENTS = 1 << (31- 3), +}; + +typedef union +{ + float f; + double d; +} ffi_dblfl; + +#if defined(__FLOAT128_TYPE__) && defined(__HAVE_FLOAT128) +typedef _Float128 float128; +#elif defined(__FLOAT128__) +typedef __float128 float128; +#else +typedef char float128[16] __attribute__((aligned(16))); +#endif + +void FFI_HIDDEN ffi_closure_SYSV (void); +void FFI_HIDDEN ffi_go_closure_sysv (void); +void FFI_HIDDEN ffi_call_SYSV(extended_cif *, void (*)(void), void *, + unsigned, void *, int); + +void FFI_HIDDEN ffi_prep_types_sysv (ffi_abi); +ffi_status FFI_HIDDEN ffi_prep_cif_sysv (ffi_cif *); +ffi_status FFI_HIDDEN ffi_prep_closure_loc_sysv (ffi_closure *, + ffi_cif *, + void (*) (ffi_cif *, void *, + void **, void *), + void *, void *); +int FFI_HIDDEN ffi_closure_helper_SYSV (ffi_cif *, + void (*) (ffi_cif *, void *, + void **, void *), + void *, void *, unsigned long *, + ffi_dblfl *, unsigned long *); + +void FFI_HIDDEN ffi_call_LINUX64(extended_cif *, void (*) (void), void *, + unsigned long, void *, long); +void FFI_HIDDEN ffi_closure_LINUX64 (void); +void FFI_HIDDEN ffi_go_closure_linux64 (void); + +void FFI_HIDDEN ffi_prep_types_linux64 (ffi_abi); +ffi_status FFI_HIDDEN ffi_prep_cif_linux64 (ffi_cif *); +ffi_status FFI_HIDDEN ffi_prep_cif_linux64_var (ffi_cif *, unsigned int, + unsigned int); +void FFI_HIDDEN ffi_prep_args64 (extended_cif *, unsigned long *const); +ffi_status FFI_HIDDEN ffi_prep_closure_loc_linux64 (ffi_closure *, ffi_cif *, + void (*) (ffi_cif *, void *, + void **, void *), + void *, void *); +int FFI_HIDDEN ffi_closure_helper_LINUX64 (ffi_cif *, + void (*) (ffi_cif *, void *, + void **, void *), + void *, void *, + unsigned long *, ffi_dblfl *, + float128 *); diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_sysv.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_sysv.c new file mode 100644 index 0000000..4078e75 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffi_sysv.c @@ -0,0 +1,923 @@ +/* ----------------------------------------------------------------------- + ffi_sysv.c - Copyright (C) 2013 IBM + Copyright (C) 2011 Anthony Green + Copyright (C) 2011 Kyle Moffett + Copyright (C) 2008 Red Hat, Inc + Copyright (C) 2007, 2008 Free Software Foundation, Inc + Copyright (c) 1998 Geoffrey Keating + + PowerPC Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include "ffi.h" + +#ifndef POWERPC64 +#include "ffi_common.h" +#include "ffi_powerpc.h" + + +/* About the SYSV ABI. */ +#define ASM_NEEDS_REGISTERS 6 +#define NUM_GPR_ARG_REGISTERS 8 +#define NUM_FPR_ARG_REGISTERS 8 + + +#if HAVE_LONG_DOUBLE_VARIANT && FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE +/* Adjust size of ffi_type_longdouble. */ +void FFI_HIDDEN +ffi_prep_types_sysv (ffi_abi abi) +{ + if ((abi & (FFI_SYSV | FFI_SYSV_LONG_DOUBLE_128)) == FFI_SYSV) + { + ffi_type_longdouble.size = 8; + ffi_type_longdouble.alignment = 8; + } + else + { + ffi_type_longdouble.size = 16; + ffi_type_longdouble.alignment = 16; + } +} +#endif + +/* Transform long double, double and float to other types as per abi. */ +static int +translate_float (int abi, int type) +{ +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + if (type == FFI_TYPE_LONGDOUBLE + && (abi & FFI_SYSV_LONG_DOUBLE_128) == 0) + type = FFI_TYPE_DOUBLE; +#endif + if ((abi & FFI_SYSV_SOFT_FLOAT) != 0) + { + if (type == FFI_TYPE_FLOAT) + type = FFI_TYPE_UINT32; + else if (type == FFI_TYPE_DOUBLE) + type = FFI_TYPE_UINT64; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + else if (type == FFI_TYPE_LONGDOUBLE) + type = FFI_TYPE_UINT128; + } + else if ((abi & FFI_SYSV_IBM_LONG_DOUBLE) == 0) + { + if (type == FFI_TYPE_LONGDOUBLE) + type = FFI_TYPE_STRUCT; +#endif + } + return type; +} + +/* Perform machine dependent cif processing */ +static ffi_status +ffi_prep_cif_sysv_core (ffi_cif *cif) +{ + ffi_type **ptr; + unsigned bytes; + unsigned i, fpr_count = 0, gpr_count = 0, stack_count = 0; + unsigned flags = cif->flags; + unsigned struct_copy_size = 0; + unsigned type = cif->rtype->type; + unsigned size = cif->rtype->size; + + /* The machine-independent calculation of cif->bytes doesn't work + for us. Redo the calculation. */ + + /* Space for the frame pointer, callee's LR, and the asm's temp regs. */ + bytes = (2 + ASM_NEEDS_REGISTERS) * sizeof (int); + + /* Space for the GPR registers. */ + bytes += NUM_GPR_ARG_REGISTERS * sizeof (int); + + /* Return value handling. The rules for SYSV are as follows: + - 32-bit (or less) integer values are returned in gpr3; + - Structures of size <= 4 bytes also returned in gpr3; + - 64-bit integer values and structures between 5 and 8 bytes are returned + in gpr3 and gpr4; + - Larger structures are allocated space and a pointer is passed as + the first argument. + - Single/double FP values are returned in fpr1; + - long doubles (if not equivalent to double) are returned in + fpr1,fpr2 for Linux and as for large structs for SysV. */ + + type = translate_float (cif->abi, type); + + switch (type) + { +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + flags |= FLAG_RETURNS_128BITS; + /* Fall through. */ +#endif + case FFI_TYPE_DOUBLE: + flags |= FLAG_RETURNS_64BITS; + /* Fall through. */ + case FFI_TYPE_FLOAT: + flags |= FLAG_RETURNS_FP; +#ifdef __NO_FPRS__ + return FFI_BAD_ABI; +#endif + break; + + case FFI_TYPE_UINT128: + flags |= FLAG_RETURNS_128BITS; + /* Fall through. */ + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + flags |= FLAG_RETURNS_64BITS; + break; + + case FFI_TYPE_STRUCT: + /* The final SYSV ABI says that structures smaller or equal 8 bytes + are returned in r3/r4. A draft ABI used by linux instead + returns them in memory. */ + if ((cif->abi & FFI_SYSV_STRUCT_RET) != 0 && size <= 8) + { + flags |= FLAG_RETURNS_SMST; + break; + } + gpr_count++; + flags |= FLAG_RETVAL_REFERENCE; + /* Fall through. */ + case FFI_TYPE_VOID: + flags |= FLAG_RETURNS_NOTHING; + break; + + default: + /* Returns 32-bit integer, or similar. Nothing to do here. */ + break; + } + + /* The first NUM_GPR_ARG_REGISTERS words of integer arguments, and the + first NUM_FPR_ARG_REGISTERS fp arguments, go in registers; the rest + goes on the stack. Structures and long doubles (if not equivalent + to double) are passed as a pointer to a copy of the structure. + Stuff on the stack needs to keep proper alignment. */ + for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) + { + unsigned short typenum = (*ptr)->type; + + typenum = translate_float (cif->abi, typenum); + + switch (typenum) + { +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + if (fpr_count >= NUM_FPR_ARG_REGISTERS - 1) + { + fpr_count = NUM_FPR_ARG_REGISTERS; + /* 8-byte align long doubles. */ + stack_count += stack_count & 1; + stack_count += 4; + } + else + fpr_count += 2; +#ifdef __NO_FPRS__ + return FFI_BAD_ABI; +#endif + break; +#endif + + case FFI_TYPE_DOUBLE: + if (fpr_count >= NUM_FPR_ARG_REGISTERS) + { + /* 8-byte align doubles. */ + stack_count += stack_count & 1; + stack_count += 2; + } + else + fpr_count += 1; +#ifdef __NO_FPRS__ + return FFI_BAD_ABI; +#endif + break; + + case FFI_TYPE_FLOAT: + if (fpr_count >= NUM_FPR_ARG_REGISTERS) + /* Yes, we don't follow the ABI, but neither does gcc. */ + stack_count += 1; + else + fpr_count += 1; +#ifdef __NO_FPRS__ + return FFI_BAD_ABI; +#endif + break; + + case FFI_TYPE_UINT128: + /* A long double in FFI_LINUX_SOFT_FLOAT can use only a set + of four consecutive gprs. If we do not have enough, we + have to adjust the gpr_count value. */ + if (gpr_count >= NUM_GPR_ARG_REGISTERS - 3) + gpr_count = NUM_GPR_ARG_REGISTERS; + if (gpr_count >= NUM_GPR_ARG_REGISTERS) + stack_count += 4; + else + gpr_count += 4; + break; + + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + /* 'long long' arguments are passed as two words, but + either both words must fit in registers or both go + on the stack. If they go on the stack, they must + be 8-byte-aligned. + + Also, only certain register pairs can be used for + passing long long int -- specifically (r3,r4), (r5,r6), + (r7,r8), (r9,r10). */ + gpr_count += gpr_count & 1; + if (gpr_count >= NUM_GPR_ARG_REGISTERS) + { + stack_count += stack_count & 1; + stack_count += 2; + } + else + gpr_count += 2; + break; + + case FFI_TYPE_STRUCT: + /* We must allocate space for a copy of these to enforce + pass-by-value. Pad the space up to a multiple of 16 + bytes (the maximum alignment required for anything under + the SYSV ABI). */ + struct_copy_size += ((*ptr)->size + 15) & ~0xF; + /* Fall through (allocate space for the pointer). */ + + case FFI_TYPE_POINTER: + case FFI_TYPE_INT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + /* Everything else is passed as a 4-byte word in a GPR, either + the object itself or a pointer to it. */ + if (gpr_count >= NUM_GPR_ARG_REGISTERS) + stack_count += 1; + else + gpr_count += 1; + break; + + default: + FFI_ASSERT (0); + } + } + + if (fpr_count != 0) + flags |= FLAG_FP_ARGUMENTS; + if (gpr_count > 4) + flags |= FLAG_4_GPR_ARGUMENTS; + if (struct_copy_size != 0) + flags |= FLAG_ARG_NEEDS_COPY; + + /* Space for the FPR registers, if needed. */ + if (fpr_count != 0) + bytes += NUM_FPR_ARG_REGISTERS * sizeof (double); + + /* Stack space. */ + bytes += stack_count * sizeof (int); + + /* The stack space allocated needs to be a multiple of 16 bytes. */ + bytes = (bytes + 15) & ~0xF; + + /* Add in the space for the copied structures. */ + bytes += struct_copy_size; + + cif->flags = flags; + cif->bytes = bytes; + + return FFI_OK; +} + +ffi_status FFI_HIDDEN +ffi_prep_cif_sysv (ffi_cif *cif) +{ + if ((cif->abi & FFI_SYSV) == 0) + { + /* This call is from old code. Translate to new ABI values. */ + cif->flags |= FLAG_COMPAT; + switch (cif->abi) + { + default: + return FFI_BAD_ABI; + + case FFI_COMPAT_SYSV: + cif->abi = FFI_SYSV | FFI_SYSV_STRUCT_RET | FFI_SYSV_LONG_DOUBLE_128; + break; + + case FFI_COMPAT_GCC_SYSV: + cif->abi = FFI_SYSV | FFI_SYSV_LONG_DOUBLE_128; + break; + + case FFI_COMPAT_LINUX: + cif->abi = (FFI_SYSV | FFI_SYSV_IBM_LONG_DOUBLE + | FFI_SYSV_LONG_DOUBLE_128); + break; + + case FFI_COMPAT_LINUX_SOFT_FLOAT: + cif->abi = (FFI_SYSV | FFI_SYSV_SOFT_FLOAT | FFI_SYSV_IBM_LONG_DOUBLE + | FFI_SYSV_LONG_DOUBLE_128); + break; + } + } + return ffi_prep_cif_sysv_core (cif); +} + +/* ffi_prep_args_SYSV is called by the assembly routine once stack space + has been allocated for the function's arguments. + + The stack layout we want looks like this: + + | Return address from ffi_call_SYSV 4bytes | higher addresses + |--------------------------------------------| + | Previous backchain pointer 4 | stack pointer here + |--------------------------------------------|<+ <<< on entry to + | Saved r28-r31 4*4 | | ffi_call_SYSV + |--------------------------------------------| | + | GPR registers r3-r10 8*4 | | ffi_call_SYSV + |--------------------------------------------| | + | FPR registers f1-f8 (optional) 8*8 | | + |--------------------------------------------| | stack | + | Space for copied structures | | grows | + |--------------------------------------------| | down V + | Parameters that didn't fit in registers | | + |--------------------------------------------| | lower addresses + | Space for callee's LR 4 | | + |--------------------------------------------| | stack pointer here + | Current backchain pointer 4 |-/ during + |--------------------------------------------| <<< ffi_call_SYSV + +*/ + +void FFI_HIDDEN +ffi_prep_args_SYSV (extended_cif *ecif, unsigned *const stack) +{ + const unsigned bytes = ecif->cif->bytes; + const unsigned flags = ecif->cif->flags; + + typedef union + { + char *c; + unsigned *u; + long long *ll; + float *f; + double *d; + } valp; + + /* 'stacktop' points at the previous backchain pointer. */ + valp stacktop; + + /* 'gpr_base' points at the space for gpr3, and grows upwards as + we use GPR registers. */ + valp gpr_base; + valp gpr_end; + +#ifndef __NO_FPRS__ + /* 'fpr_base' points at the space for fpr1, and grows upwards as + we use FPR registers. */ + valp fpr_base; + valp fpr_end; +#endif + + /* 'copy_space' grows down as we put structures in it. It should + stay 16-byte aligned. */ + valp copy_space; + + /* 'next_arg' grows up as we put parameters in it. */ + valp next_arg; + + int i; + ffi_type **ptr; +#ifndef __NO_FPRS__ + double double_tmp; +#endif + union + { + void **v; + char **c; + signed char **sc; + unsigned char **uc; + signed short **ss; + unsigned short **us; + unsigned int **ui; + long long **ll; + float **f; + double **d; + } p_argv; + size_t struct_copy_size; + unsigned gprvalue; + + stacktop.c = (char *) stack + bytes; + gpr_end.u = stacktop.u - ASM_NEEDS_REGISTERS; + gpr_base.u = gpr_end.u - NUM_GPR_ARG_REGISTERS; +#ifndef __NO_FPRS__ + fpr_end.d = gpr_base.d; + fpr_base.d = fpr_end.d - NUM_FPR_ARG_REGISTERS; + copy_space.c = ((flags & FLAG_FP_ARGUMENTS) ? fpr_base.c : gpr_base.c); +#else + copy_space.c = gpr_base.c; +#endif + next_arg.u = stack + 2; + + /* Check that everything starts aligned properly. */ + FFI_ASSERT (((unsigned long) (char *) stack & 0xF) == 0); + FFI_ASSERT (((unsigned long) copy_space.c & 0xF) == 0); + FFI_ASSERT (((unsigned long) stacktop.c & 0xF) == 0); + FFI_ASSERT ((bytes & 0xF) == 0); + FFI_ASSERT (copy_space.c >= next_arg.c); + + /* Deal with return values that are actually pass-by-reference. */ + if (flags & FLAG_RETVAL_REFERENCE) + *gpr_base.u++ = (unsigned) (char *) ecif->rvalue; + + /* Now for the arguments. */ + p_argv.v = ecif->avalue; + for (ptr = ecif->cif->arg_types, i = ecif->cif->nargs; + i > 0; + i--, ptr++, p_argv.v++) + { + unsigned int typenum = (*ptr)->type; + + typenum = translate_float (ecif->cif->abi, typenum); + + /* Now test the translated value */ + switch (typenum) + { +#ifndef __NO_FPRS__ +# if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + double_tmp = (*p_argv.d)[0]; + + if (fpr_base.d >= fpr_end.d - 1) + { + fpr_base.d = fpr_end.d; + if (((next_arg.u - stack) & 1) != 0) + next_arg.u += 1; + *next_arg.d = double_tmp; + next_arg.u += 2; + double_tmp = (*p_argv.d)[1]; + *next_arg.d = double_tmp; + next_arg.u += 2; + } + else + { + *fpr_base.d++ = double_tmp; + double_tmp = (*p_argv.d)[1]; + *fpr_base.d++ = double_tmp; + } + FFI_ASSERT (flags & FLAG_FP_ARGUMENTS); + break; +# endif + case FFI_TYPE_DOUBLE: + double_tmp = **p_argv.d; + + if (fpr_base.d >= fpr_end.d) + { + if (((next_arg.u - stack) & 1) != 0) + next_arg.u += 1; + *next_arg.d = double_tmp; + next_arg.u += 2; + } + else + *fpr_base.d++ = double_tmp; + FFI_ASSERT (flags & FLAG_FP_ARGUMENTS); + break; + + case FFI_TYPE_FLOAT: + double_tmp = **p_argv.f; + if (fpr_base.d >= fpr_end.d) + { + *next_arg.f = (float) double_tmp; + next_arg.u += 1; + } + else + *fpr_base.d++ = double_tmp; + FFI_ASSERT (flags & FLAG_FP_ARGUMENTS); + break; +#endif /* have FPRs */ + + case FFI_TYPE_UINT128: + /* The soft float ABI for long doubles works like this, a long double + is passed in four consecutive GPRs if available. A maximum of 2 + long doubles can be passed in gprs. If we do not have 4 GPRs + left, the long double is passed on the stack, 4-byte aligned. */ + if (gpr_base.u >= gpr_end.u - 3) + { + unsigned int ii; + gpr_base.u = gpr_end.u; + for (ii = 0; ii < 4; ii++) + { + unsigned int int_tmp = (*p_argv.ui)[ii]; + *next_arg.u++ = int_tmp; + } + } + else + { + unsigned int ii; + for (ii = 0; ii < 4; ii++) + { + unsigned int int_tmp = (*p_argv.ui)[ii]; + *gpr_base.u++ = int_tmp; + } + } + break; + + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + if (gpr_base.u >= gpr_end.u - 1) + { + gpr_base.u = gpr_end.u; + if (((next_arg.u - stack) & 1) != 0) + next_arg.u++; + *next_arg.ll = **p_argv.ll; + next_arg.u += 2; + } + else + { + /* The abi states only certain register pairs can be + used for passing long long int specifically (r3,r4), + (r5,r6), (r7,r8), (r9,r10). If next arg is long long + but not correct starting register of pair then skip + until the proper starting register. */ + if (((gpr_end.u - gpr_base.u) & 1) != 0) + gpr_base.u++; + *gpr_base.ll++ = **p_argv.ll; + } + break; + + case FFI_TYPE_STRUCT: + struct_copy_size = ((*ptr)->size + 15) & ~0xF; + copy_space.c -= struct_copy_size; + memcpy (copy_space.c, *p_argv.c, (*ptr)->size); + + gprvalue = (unsigned long) copy_space.c; + + FFI_ASSERT (copy_space.c > next_arg.c); + FFI_ASSERT (flags & FLAG_ARG_NEEDS_COPY); + goto putgpr; + + case FFI_TYPE_UINT8: + gprvalue = **p_argv.uc; + goto putgpr; + case FFI_TYPE_SINT8: + gprvalue = **p_argv.sc; + goto putgpr; + case FFI_TYPE_UINT16: + gprvalue = **p_argv.us; + goto putgpr; + case FFI_TYPE_SINT16: + gprvalue = **p_argv.ss; + goto putgpr; + + case FFI_TYPE_INT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_POINTER: + + gprvalue = **p_argv.ui; + + putgpr: + if (gpr_base.u >= gpr_end.u) + *next_arg.u++ = gprvalue; + else + *gpr_base.u++ = gprvalue; + break; + } + } + + /* Check that we didn't overrun the stack... */ + FFI_ASSERT (copy_space.c >= next_arg.c); + FFI_ASSERT (gpr_base.u <= gpr_end.u); +#ifndef __NO_FPRS__ + FFI_ASSERT (fpr_base.u <= fpr_end.u); +#endif + FFI_ASSERT (((flags & FLAG_4_GPR_ARGUMENTS) != 0) + == (gpr_end.u - gpr_base.u < 4)); +} + +#define MIN_CACHE_LINE_SIZE 8 + +static void +flush_icache (char *wraddr, char *xaddr, int size) +{ + int i; + for (i = 0; i < size; i += MIN_CACHE_LINE_SIZE) + __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;" + : : "r" (xaddr + i), "r" (wraddr + i) : "memory"); + __asm__ volatile ("icbi 0,%0;" "dcbf 0,%1;" "sync;" "isync;" + : : "r"(xaddr + size - 1), "r"(wraddr + size - 1) + : "memory"); +} + +ffi_status FFI_HIDDEN +ffi_prep_closure_loc_sysv (ffi_closure *closure, + ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + void *codeloc) +{ + unsigned int *tramp; + + if (cif->abi < FFI_SYSV || cif->abi >= FFI_LAST_ABI) + return FFI_BAD_ABI; + + tramp = (unsigned int *) &closure->tramp[0]; + tramp[0] = 0x7c0802a6; /* mflr r0 */ + tramp[1] = 0x429f0005; /* bcl 20,31,.+4 */ + tramp[2] = 0x7d6802a6; /* mflr r11 */ + tramp[3] = 0x7c0803a6; /* mtlr r0 */ + tramp[4] = 0x800b0018; /* lwz r0,24(r11) */ + tramp[5] = 0x816b001c; /* lwz r11,28(r11) */ + tramp[6] = 0x7c0903a6; /* mtctr r0 */ + tramp[7] = 0x4e800420; /* bctr */ + *(void **) &tramp[8] = (void *) ffi_closure_SYSV; /* function */ + *(void **) &tramp[9] = codeloc; /* context */ + + /* Flush the icache. */ + flush_icache ((char *)tramp, (char *)codeloc, 8 * 4); + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + return FFI_OK; +} + +/* Basically the trampoline invokes ffi_closure_SYSV, and on + entry, r11 holds the address of the closure. + After storing the registers that could possibly contain + parameters to be passed into the stack frame and setting + up space for a return value, ffi_closure_SYSV invokes the + following helper function to do most of the work. */ + +int +ffi_closure_helper_SYSV (ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + void *rvalue, + unsigned long *pgr, + ffi_dblfl *pfr, + unsigned long *pst) +{ + /* rvalue is the pointer to space for return value in closure assembly */ + /* pgr is the pointer to where r3-r10 are stored in ffi_closure_SYSV */ + /* pfr is the pointer to where f1-f8 are stored in ffi_closure_SYSV */ + /* pst is the pointer to outgoing parameter stack in original caller */ + + void ** avalue; + ffi_type ** arg_types; + long i, avn; +#ifndef __NO_FPRS__ + long nf = 0; /* number of floating registers already used */ +#endif + long ng = 0; /* number of general registers already used */ + + unsigned size = cif->rtype->size; + unsigned short rtypenum = cif->rtype->type; + + avalue = alloca (cif->nargs * sizeof (void *)); + + /* First translate for softfloat/nonlinux */ + rtypenum = translate_float (cif->abi, rtypenum); + + /* Copy the caller's structure return value address so that the closure + returns the data directly to the caller. + For FFI_SYSV the result is passed in r3/r4 if the struct size is less + or equal 8 bytes. */ + if (rtypenum == FFI_TYPE_STRUCT + && !((cif->abi & FFI_SYSV_STRUCT_RET) != 0 && size <= 8)) + { + rvalue = (void *) *pgr; + ng++; + pgr++; + } + + i = 0; + avn = cif->nargs; + arg_types = cif->arg_types; + + /* Grab the addresses of the arguments from the stack frame. */ + while (i < avn) { + unsigned short typenum = arg_types[i]->type; + + /* We may need to handle some values depending on ABI. */ + typenum = translate_float (cif->abi, typenum); + + switch (typenum) + { +#ifndef __NO_FPRS__ + case FFI_TYPE_FLOAT: + /* Unfortunately float values are stored as doubles + in the ffi_closure_SYSV code (since we don't check + the type in that routine). */ + if (nf < NUM_FPR_ARG_REGISTERS) + { + /* FIXME? here we are really changing the values + stored in the original calling routines outgoing + parameter stack. This is probably a really + naughty thing to do but... */ + double temp = pfr->d; + pfr->f = (float) temp; + avalue[i] = pfr; + nf++; + pfr++; + } + else + { + avalue[i] = pst; + pst += 1; + } + break; + + case FFI_TYPE_DOUBLE: + if (nf < NUM_FPR_ARG_REGISTERS) + { + avalue[i] = pfr; + nf++; + pfr++; + } + else + { + if (((long) pst) & 4) + pst++; + avalue[i] = pst; + pst += 2; + } + break; + +# if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + if (nf < NUM_FPR_ARG_REGISTERS - 1) + { + avalue[i] = pfr; + pfr += 2; + nf += 2; + } + else + { + if (((long) pst) & 4) + pst++; + avalue[i] = pst; + pst += 4; + nf = 8; + } + break; +# endif +#endif + + case FFI_TYPE_UINT128: + /* Test if for the whole long double, 4 gprs are available. + otherwise the stuff ends up on the stack. */ + if (ng < NUM_GPR_ARG_REGISTERS - 3) + { + avalue[i] = pgr; + pgr += 4; + ng += 4; + } + else + { + avalue[i] = pst; + pst += 4; + ng = 8+4; + } + break; + + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: +#ifndef __LITTLE_ENDIAN__ + if (ng < NUM_GPR_ARG_REGISTERS) + { + avalue[i] = (char *) pgr + 3; + ng++; + pgr++; + } + else + { + avalue[i] = (char *) pst + 3; + pst++; + } + break; +#endif + + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: +#ifndef __LITTLE_ENDIAN__ + if (ng < NUM_GPR_ARG_REGISTERS) + { + avalue[i] = (char *) pgr + 2; + ng++; + pgr++; + } + else + { + avalue[i] = (char *) pst + 2; + pst++; + } + break; +#endif + + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_POINTER: + if (ng < NUM_GPR_ARG_REGISTERS) + { + avalue[i] = pgr; + ng++; + pgr++; + } + else + { + avalue[i] = pst; + pst++; + } + break; + + case FFI_TYPE_STRUCT: + /* Structs are passed by reference. The address will appear in a + gpr if it is one of the first 8 arguments. */ + if (ng < NUM_GPR_ARG_REGISTERS) + { + avalue[i] = (void *) *pgr; + ng++; + pgr++; + } + else + { + avalue[i] = (void *) *pst; + pst++; + } + break; + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + /* Passing long long ints are complex, they must + be passed in suitable register pairs such as + (r3,r4) or (r5,r6) or (r6,r7), or (r7,r8) or (r9,r10) + and if the entire pair aren't available then the outgoing + parameter stack is used for both but an alignment of 8 + must will be kept. So we must either look in pgr + or pst to find the correct address for this type + of parameter. */ + if (ng < NUM_GPR_ARG_REGISTERS - 1) + { + if (ng & 1) + { + /* skip r4, r6, r8 as starting points */ + ng++; + pgr++; + } + avalue[i] = pgr; + ng += 2; + pgr += 2; + } + else + { + if (((long) pst) & 4) + pst++; + avalue[i] = pst; + pst += 2; + ng = NUM_GPR_ARG_REGISTERS; + } + break; + + default: + FFI_ASSERT (0); + } + + i++; + } + + (*fun) (cif, rvalue, avalue, user_data); + + /* Tell ffi_closure_SYSV how to perform return type promotions. + Because the FFI_SYSV ABI returns the structures <= 8 bytes in + r3/r4 we have to tell ffi_closure_SYSV how to treat them. We + combine the base type FFI_SYSV_TYPE_SMALL_STRUCT with the size of + the struct less one. We never have a struct with size zero. + See the comment in ffitarget.h about ordering. */ + if (rtypenum == FFI_TYPE_STRUCT + && (cif->abi & FFI_SYSV_STRUCT_RET) != 0 && size <= 8) + return FFI_SYSV_TYPE_SMALL_STRUCT - 1 + size; + return rtypenum; +} +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffitarget.h new file mode 100644 index 0000000..7fb9a93 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ffitarget.h @@ -0,0 +1,204 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (C) 2007, 2008, 2010 Free Software Foundation, Inc + Copyright (c) 1996-2003 Red Hat, Inc. + + Target configuration macros for PowerPC. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +/* ---- System specific configurations ----------------------------------- */ + +#if defined (POWERPC) && defined (__powerpc64__) /* linux64 */ +#ifndef POWERPC64 +#define POWERPC64 +#endif +#elif defined (POWERPC_DARWIN) && defined (__ppc64__) /* Darwin64 */ +#ifndef POWERPC64 +#define POWERPC64 +#endif +#ifndef POWERPC_DARWIN64 +#define POWERPC_DARWIN64 +#endif +#elif defined (POWERPC_AIX) && defined (__64BIT__) /* AIX64 */ +#ifndef POWERPC64 +#define POWERPC64 +#endif +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + +#if defined (POWERPC_AIX) + FFI_AIX, + FFI_DARWIN, + FFI_DEFAULT_ABI = FFI_AIX, + FFI_LAST_ABI + +#elif defined (POWERPC_DARWIN) + FFI_AIX, + FFI_DARWIN, + FFI_DEFAULT_ABI = FFI_DARWIN, + FFI_LAST_ABI + +#else + /* The FFI_COMPAT values are used by old code. Since libffi may be + a shared library we have to support old values for backwards + compatibility. */ + FFI_COMPAT_SYSV, + FFI_COMPAT_GCC_SYSV, + FFI_COMPAT_LINUX64, + FFI_COMPAT_LINUX, + FFI_COMPAT_LINUX_SOFT_FLOAT, + +# if defined (POWERPC64) + /* This bit, always set in new code, must not be set in any of the + old FFI_COMPAT values that might be used for 64-bit linux. We + only need worry about FFI_COMPAT_LINUX64, but to be safe avoid + all old values. */ + FFI_LINUX = 8, + /* This and following bits can reuse FFI_COMPAT values. */ + FFI_LINUX_STRUCT_ALIGN = 1, + FFI_LINUX_LONG_DOUBLE_128 = 2, + FFI_LINUX_LONG_DOUBLE_IEEE128 = 4, + FFI_DEFAULT_ABI = (FFI_LINUX +# ifdef __STRUCT_PARM_ALIGN__ + | FFI_LINUX_STRUCT_ALIGN +# endif +# ifdef __LONG_DOUBLE_128__ + | FFI_LINUX_LONG_DOUBLE_128 +# ifdef __LONG_DOUBLE_IEEE128__ + | FFI_LINUX_LONG_DOUBLE_IEEE128 +# endif +# endif + ), + FFI_LAST_ABI = 16 + +# else + /* This bit, always set in new code, must not be set in any of the + old FFI_COMPAT values that might be used for 32-bit linux/sysv/bsd. */ + FFI_SYSV = 8, + /* This and following bits can reuse FFI_COMPAT values. */ + FFI_SYSV_SOFT_FLOAT = 1, + FFI_SYSV_STRUCT_RET = 2, + FFI_SYSV_IBM_LONG_DOUBLE = 4, + FFI_SYSV_LONG_DOUBLE_128 = 16, + + FFI_DEFAULT_ABI = (FFI_SYSV +# ifdef __NO_FPRS__ + | FFI_SYSV_SOFT_FLOAT +# endif +# if (defined (__SVR4_STRUCT_RETURN) \ + || defined (POWERPC_FREEBSD) && !defined (__AIX_STRUCT_RETURN)) + | FFI_SYSV_STRUCT_RET +# endif +# if __LDBL_MANT_DIG__ == 106 + | FFI_SYSV_IBM_LONG_DOUBLE +# endif +# ifdef __LONG_DOUBLE_128__ + | FFI_SYSV_LONG_DOUBLE_128 +# endif + ), + FFI_LAST_ABI = 32 +# endif +#endif + +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 +#if defined (POWERPC) || defined (POWERPC_FREEBSD) +# define FFI_GO_CLOSURES 1 +# define FFI_TARGET_SPECIFIC_VARIADIC 1 +# define FFI_EXTRA_CIF_FIELDS unsigned nfixedargs +#endif +#if defined (POWERPC_AIX) +# define FFI_GO_CLOSURES 1 +#endif + +/* ppc_closure.S and linux64_closure.S expect this. */ +#define FFI_PPC_TYPE_LAST FFI_TYPE_POINTER + +/* We define additional types below. If generic types are added that + must be supported by powerpc libffi then it is likely that + FFI_PPC_TYPE_LAST needs increasing *and* the jump tables in + ppc_closure.S and linux64_closure.S be extended. */ + +#if !(FFI_TYPE_LAST == FFI_PPC_TYPE_LAST \ + || (FFI_TYPE_LAST == FFI_TYPE_COMPLEX \ + && !defined FFI_TARGET_HAS_COMPLEX_TYPE)) +# error "You likely have a broken powerpc libffi" +#endif + +/* Needed for soft-float long-double-128 support. */ +#define FFI_TYPE_UINT128 (FFI_PPC_TYPE_LAST + 1) + +/* Needed for FFI_SYSV small structure returns. */ +#define FFI_SYSV_TYPE_SMALL_STRUCT (FFI_PPC_TYPE_LAST + 2) + +/* Used by ELFv2 for homogenous structure returns. */ +#define FFI_V2_TYPE_VECTOR (FFI_PPC_TYPE_LAST + 1) +#define FFI_V2_TYPE_VECTOR_HOMOG (FFI_PPC_TYPE_LAST + 2) +#define FFI_V2_TYPE_FLOAT_HOMOG (FFI_PPC_TYPE_LAST + 3) +#define FFI_V2_TYPE_DOUBLE_HOMOG (FFI_PPC_TYPE_LAST + 4) +#define FFI_V2_TYPE_SMALL_STRUCT (FFI_PPC_TYPE_LAST + 5) + +#if _CALL_ELF == 2 +# define FFI_TRAMPOLINE_SIZE 32 +#else +# if defined(POWERPC64) || defined(POWERPC_AIX) +# if defined(POWERPC_DARWIN64) +# define FFI_TRAMPOLINE_SIZE 48 +# else +# define FFI_TRAMPOLINE_SIZE 24 +# endif +# else /* POWERPC || POWERPC_AIX */ +# define FFI_TRAMPOLINE_SIZE 40 +# endif +#endif + +#ifndef LIBFFI_ASM +#if defined(POWERPC_DARWIN) || defined(POWERPC_AIX) +struct ffi_aix_trampoline_struct { + void * code_pointer; /* Pointer to ffi_closure_ASM */ + void * toc; /* TOC */ + void * static_chain; /* Pointer to closure */ +}; +#endif +#endif + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/linux64.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/linux64.S new file mode 100644 index 0000000..e92d64a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/linux64.S @@ -0,0 +1,291 @@ +/* ----------------------------------------------------------------------- + sysv.h - Copyright (c) 2003 Jakub Jelinek + Copyright (c) 2008 Red Hat, Inc. + + PowerPC64 Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + +#ifdef POWERPC64 + .hidden ffi_call_LINUX64 + .globl ffi_call_LINUX64 + .text + .cfi_startproc +# if _CALL_ELF == 2 +ffi_call_LINUX64: +# ifndef __PCREL__ + addis %r2, %r12, .TOC.-ffi_call_LINUX64@ha + addi %r2, %r2, .TOC.-ffi_call_LINUX64@l +# endif + .localentry ffi_call_LINUX64, . - ffi_call_LINUX64 +# else + .section ".opd","aw" + .align 3 +ffi_call_LINUX64: +# ifdef _CALL_LINUX + .quad .L.ffi_call_LINUX64,.TOC.@tocbase,0 + .type ffi_call_LINUX64,@function + .text +.L.ffi_call_LINUX64: +# else + .hidden .ffi_call_LINUX64 + .globl .ffi_call_LINUX64 + .quad .ffi_call_LINUX64,.TOC.@tocbase,0 + .size ffi_call_LINUX64,24 + .type .ffi_call_LINUX64,@function + .text +.ffi_call_LINUX64: +# endif +# endif + mflr %r0 + std %r28, -32(%r1) + std %r29, -24(%r1) + std %r30, -16(%r1) + std %r31, -8(%r1) + std %r7, 8(%r1) /* closure, saved in cr field. */ + std %r0, 16(%r1) + + mr %r28, %r1 /* our AP. */ + .cfi_def_cfa_register 28 + .cfi_offset 65, 16 + .cfi_offset 31, -8 + .cfi_offset 30, -16 + .cfi_offset 29, -24 + .cfi_offset 28, -32 + + stdux %r1, %r1, %r8 + mr %r31, %r6 /* flags, */ + mr %r30, %r5 /* rvalue, */ + mr %r29, %r4 /* function address. */ +/* Save toc pointer, not for the ffi_prep_args64 call, but for the later + bctrl function call. */ +# if _CALL_ELF == 2 + std %r2, 24(%r1) +# else + std %r2, 40(%r1) +# endif + + /* Call ffi_prep_args64. */ + mr %r4, %r1 +# if defined _CALL_LINUX || _CALL_ELF == 2 +# ifdef __PCREL__ + bl ffi_prep_args64@notoc +# else + bl ffi_prep_args64 + nop +# endif +# else + bl .ffi_prep_args64 + nop +# endif + +# if _CALL_ELF == 2 + mr %r12, %r29 +# else + ld %r12, 0(%r29) + ld %r2, 8(%r29) +# endif + /* Now do the call. */ + /* Set up cr1 with bits 3-7 of the flags. */ + mtcrf 0xc0, %r31 + + /* Get the address to call into CTR. */ + mtctr %r12 + /* Load all those argument registers. */ + addi %r29, %r28, -32-(8*8) + ld %r3, (0*8)(%r29) + ld %r4, (1*8)(%r29) + ld %r5, (2*8)(%r29) + ld %r6, (3*8)(%r29) + bf- 5, 1f + ld %r7, (4*8)(%r29) + ld %r8, (5*8)(%r29) + ld %r9, (6*8)(%r29) + ld %r10, (7*8)(%r29) +1: + + /* Load all the FP registers. */ + bf- 6, 2f + addi %r29, %r29, -(14*8) + lfd %f1, ( 1*8)(%r29) + lfd %f2, ( 2*8)(%r29) + lfd %f3, ( 3*8)(%r29) + lfd %f4, ( 4*8)(%r29) + lfd %f5, ( 5*8)(%r29) + lfd %f6, ( 6*8)(%r29) + lfd %f7, ( 7*8)(%r29) + lfd %f8, ( 8*8)(%r29) + lfd %f9, ( 9*8)(%r29) + lfd %f10, (10*8)(%r29) + lfd %f11, (11*8)(%r29) + lfd %f12, (12*8)(%r29) + lfd %f13, (13*8)(%r29) +2: + + /* Load all the vector registers. */ + bf- 3, 3f + addi %r29, %r29, -16 + lvx %v13, 0, %r29 + addi %r29, %r29, -16 + lvx %v12, 0, %r29 + addi %r29, %r29, -16 + lvx %v11, 0, %r29 + addi %r29, %r29, -16 + lvx %v10, 0, %r29 + addi %r29, %r29, -16 + lvx %v9, 0, %r29 + addi %r29, %r29, -16 + lvx %v8, 0, %r29 + addi %r29, %r29, -16 + lvx %v7, 0, %r29 + addi %r29, %r29, -16 + lvx %v6, 0, %r29 + addi %r29, %r29, -16 + lvx %v5, 0, %r29 + addi %r29, %r29, -16 + lvx %v4, 0, %r29 + addi %r29, %r29, -16 + lvx %v3, 0, %r29 + addi %r29, %r29, -16 + lvx %v2, 0, %r29 +3: + + /* Make the call. */ + ld %r11, 8(%r28) + bctrl + + /* This must follow the call immediately, the unwinder + uses this to find out if r2 has been saved or not. */ +# if _CALL_ELF == 2 + ld %r2, 24(%r1) +# else + ld %r2, 40(%r1) +# endif + + /* Now, deal with the return value. */ + mtcrf 0x01, %r31 + bt 31, .Lstruct_return_value + bt 30, .Ldone_return_value + bt 29, .Lfp_return_value + bt 28, .Lvec_return_value + std %r3, 0(%r30) + /* Fall through... */ + +.Ldone_return_value: + /* Restore the registers we used and return. */ + mr %r1, %r28 + .cfi_def_cfa_register 1 + ld %r0, 16(%r28) + ld %r28, -32(%r28) + mtlr %r0 + ld %r29, -24(%r1) + ld %r30, -16(%r1) + ld %r31, -8(%r1) + blr + +.Lvec_return_value: + stvx %v2, 0, %r30 + b .Ldone_return_value + +.Lfp_return_value: + .cfi_def_cfa_register 28 + mtcrf 0x02, %r31 /* cr6 */ + bf 27, .Lfloat_return_value + stfd %f1, 0(%r30) + bf 26, .Ldone_return_value + stfd %f2, 8(%r30) + b .Ldone_return_value +.Lfloat_return_value: + stfs %f1, 0(%r30) + b .Ldone_return_value + +.Lstruct_return_value: + bf 29, .Lvec_homog_or_small_struct + mtcrf 0x02, %r31 /* cr6 */ + bf 27, .Lfloat_homog_return_value + stfd %f1, 0(%r30) + stfd %f2, 8(%r30) + stfd %f3, 16(%r30) + stfd %f4, 24(%r30) + stfd %f5, 32(%r30) + stfd %f6, 40(%r30) + stfd %f7, 48(%r30) + stfd %f8, 56(%r30) + b .Ldone_return_value + +.Lfloat_homog_return_value: + stfs %f1, 0(%r30) + stfs %f2, 4(%r30) + stfs %f3, 8(%r30) + stfs %f4, 12(%r30) + stfs %f5, 16(%r30) + stfs %f6, 20(%r30) + stfs %f7, 24(%r30) + stfs %f8, 28(%r30) + b .Ldone_return_value + +.Lvec_homog_or_small_struct: + bf 28, .Lsmall_struct + stvx %v2, 0, %r30 + addi %r30, %r30, 16 + stvx %v3, 0, %r30 + addi %r30, %r30, 16 + stvx %v4, 0, %r30 + addi %r30, %r30, 16 + stvx %v5, 0, %r30 + addi %r30, %r30, 16 + stvx %v6, 0, %r30 + addi %r30, %r30, 16 + stvx %v7, 0, %r30 + addi %r30, %r30, 16 + stvx %v8, 0, %r30 + addi %r30, %r30, 16 + stvx %v9, 0, %r30 + b .Ldone_return_value + +.Lsmall_struct: + std %r3, 0(%r30) + std %r4, 8(%r30) + b .Ldone_return_value + + .cfi_endproc +# if _CALL_ELF == 2 + .size ffi_call_LINUX64,.-ffi_call_LINUX64 +# else +# ifdef _CALL_LINUX + .size ffi_call_LINUX64,.-.L.ffi_call_LINUX64 +# else + .long 0 + .byte 0,12,0,1,128,4,0,0 + .size .ffi_call_LINUX64,.-.ffi_call_LINUX64 +# endif +# endif + +#endif + +#if (defined __ELF__ && defined __linux__) || _CALL_ELF == 2 + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/linux64_closure.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/linux64_closure.S new file mode 100644 index 0000000..3469a2c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/linux64_closure.S @@ -0,0 +1,564 @@ +/* ----------------------------------------------------------------------- + sysv.h - Copyright (c) 2003 Jakub Jelinek + Copyright (c) 2008 Red Hat, Inc. + + PowerPC64 Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ +#define LIBFFI_ASM +#include +#include + + .file "linux64_closure.S" + +#ifdef POWERPC64 + FFI_HIDDEN (ffi_closure_LINUX64) + .globl ffi_closure_LINUX64 + .text + .cfi_startproc +# if _CALL_ELF == 2 +ffi_closure_LINUX64: +# ifndef __PCREL__ + addis %r2, %r12, .TOC.-ffi_closure_LINUX64@ha + addi %r2, %r2, .TOC.-ffi_closure_LINUX64@l +# endif + .localentry ffi_closure_LINUX64, . - ffi_closure_LINUX64 +# else + .section ".opd","aw" + .align 3 +ffi_closure_LINUX64: +# ifdef _CALL_LINUX + .quad .L.ffi_closure_LINUX64,.TOC.@tocbase,0 + .type ffi_closure_LINUX64,@function + .text +.L.ffi_closure_LINUX64: +# else + FFI_HIDDEN (.ffi_closure_LINUX64) + .globl .ffi_closure_LINUX64 + .quad .ffi_closure_LINUX64,.TOC.@tocbase,0 + .size ffi_closure_LINUX64,24 + .type .ffi_closure_LINUX64,@function + .text +.ffi_closure_LINUX64: +# endif +# endif + +# if _CALL_ELF == 2 +# ifdef __VEC__ +# 32 byte special reg save area + 64 byte parm save area +# + 128 byte retval area + 13*8 fpr save area + 12*16 vec save area + round to 16 +# define STACKFRAME 528 +# else +# 32 byte special reg save area + 64 byte parm save area +# + 64 byte retval area + 13*8 fpr save area + round to 16 +# define STACKFRAME 272 +# endif +# define PARMSAVE 32 +# define RETVAL PARMSAVE+64 +# else +# 48 bytes special reg save area + 64 bytes parm save area +# + 16 bytes retval area + 13*8 bytes fpr save area + round to 16 +# define STACKFRAME 240 +# define PARMSAVE 48 +# define RETVAL PARMSAVE+64 +# endif + +# if _CALL_ELF == 2 + ld %r12, FFI_TRAMPOLINE_SIZE(%r11) # closure->cif + mflr %r0 + lwz %r12, 28(%r12) # cif->flags + mtcrf 0x40, %r12 + addi %r12, %r1, PARMSAVE + bt 7, 0f + # Our caller has not allocated a parameter save area. + # We need to allocate one here and use it to pass gprs to + # ffi_closure_helper_LINUX64. + addi %r12, %r1, -STACKFRAME+PARMSAVE +0: + # Save general regs into parm save area + std %r3, 0(%r12) + std %r4, 8(%r12) + std %r5, 16(%r12) + std %r6, 24(%r12) + std %r7, 32(%r12) + std %r8, 40(%r12) + std %r9, 48(%r12) + std %r10, 56(%r12) + + # load up the pointer to the parm save area + mr %r7, %r12 +# else + # copy r2 to r11 and load TOC into r2 + mr %r11, %r2 + ld %r2, 16(%r2) + + mflr %r0 + # Save general regs into parm save area + # This is the parameter save area set up by our caller. + std %r3, PARMSAVE+0(%r1) + std %r4, PARMSAVE+8(%r1) + std %r5, PARMSAVE+16(%r1) + std %r6, PARMSAVE+24(%r1) + std %r7, PARMSAVE+32(%r1) + std %r8, PARMSAVE+40(%r1) + std %r9, PARMSAVE+48(%r1) + std %r10, PARMSAVE+56(%r1) + + # load up the pointer to the parm save area + addi %r7, %r1, PARMSAVE +# endif + std %r0, 16(%r1) + + # closure->cif + ld %r3, FFI_TRAMPOLINE_SIZE(%r11) + # closure->fun + ld %r4, FFI_TRAMPOLINE_SIZE+8(%r11) + # closure->user_data + ld %r5, FFI_TRAMPOLINE_SIZE+16(%r11) + +.Ldoclosure: + # next save fpr 1 to fpr 13 + stfd %f1, -104+(0*8)(%r1) + stfd %f2, -104+(1*8)(%r1) + stfd %f3, -104+(2*8)(%r1) + stfd %f4, -104+(3*8)(%r1) + stfd %f5, -104+(4*8)(%r1) + stfd %f6, -104+(5*8)(%r1) + stfd %f7, -104+(6*8)(%r1) + stfd %f8, -104+(7*8)(%r1) + stfd %f9, -104+(8*8)(%r1) + stfd %f10, -104+(9*8)(%r1) + stfd %f11, -104+(10*8)(%r1) + stfd %f12, -104+(11*8)(%r1) + stfd %f13, -104+(12*8)(%r1) + + # load up the pointer to the saved fpr registers + addi %r8, %r1, -104 + +# ifdef __VEC__ + # load up the pointer to the saved vector registers + # 8 bytes padding for 16-byte alignment at -112(%r1) + addi %r9, %r8, -24 + stvx %v13, 0, %r9 + addi %r9, %r9, -16 + stvx %v12, 0, %r9 + addi %r9, %r9, -16 + stvx %v11, 0, %r9 + addi %r9, %r9, -16 + stvx %v10, 0, %r9 + addi %r9, %r9, -16 + stvx %v9, 0, %r9 + addi %r9, %r9, -16 + stvx %v8, 0, %r9 + addi %r9, %r9, -16 + stvx %v7, 0, %r9 + addi %r9, %r9, -16 + stvx %v6, 0, %r9 + addi %r9, %r9, -16 + stvx %v5, 0, %r9 + addi %r9, %r9, -16 + stvx %v4, 0, %r9 + addi %r9, %r9, -16 + stvx %v3, 0, %r9 + addi %r9, %r9, -16 + stvx %v2, 0, %r9 +# endif + + # load up the pointer to the result storage + addi %r6, %r1, -STACKFRAME+RETVAL + + stdu %r1, -STACKFRAME(%r1) + .cfi_def_cfa_offset STACKFRAME + .cfi_offset 65, 16 + + # make the call +# if defined _CALL_LINUX || _CALL_ELF == 2 +# ifdef __PCREL__ + bl ffi_closure_helper_LINUX64@notoc +.Lret: +# else + bl ffi_closure_helper_LINUX64 +.Lret: + nop +# endif +# else + bl .ffi_closure_helper_LINUX64 +.Lret: + nop +# endif + + # now r3 contains the return type + # so use it to look up in a table + # so we know how to deal with each type + + # look up the proper starting point in table + # by using return type as offset + ld %r0, STACKFRAME+16(%r1) + cmpldi %r3, FFI_V2_TYPE_SMALL_STRUCT + bge .Lsmall + mflr %r4 # move address of .Lret to r4 + sldi %r3, %r3, 4 # now multiply return type by 16 + addi %r4, %r4, .Lret_type0 - .Lret + add %r3, %r3, %r4 # add contents of table to table address + mtctr %r3 + bctr # jump to it + +# Each of the ret_typeX code fragments has to be exactly 16 bytes long +# (4 instructions). For cache effectiveness we align to a 16 byte boundary +# first. + .align 4 + +.Lret_type0: +# case FFI_TYPE_VOID + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME + nop +# case FFI_TYPE_INT +# ifdef __LITTLE_ENDIAN__ + lwa %r3, RETVAL+0(%r1) +# else + lwa %r3, RETVAL+4(%r1) +# endif + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +# case FFI_TYPE_FLOAT + lfs %f1, RETVAL+0(%r1) + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +# case FFI_TYPE_DOUBLE + lfd %f1, RETVAL+0(%r1) + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +# case FFI_TYPE_LONGDOUBLE + lfd %f1, RETVAL+0(%r1) + mtlr %r0 + lfd %f2, RETVAL+8(%r1) + b .Lfinish +# case FFI_TYPE_UINT8 +# ifdef __LITTLE_ENDIAN__ + lbz %r3, RETVAL+0(%r1) +# else + lbz %r3, RETVAL+7(%r1) +# endif + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +# case FFI_TYPE_SINT8 +# ifdef __LITTLE_ENDIAN__ + lbz %r3, RETVAL+0(%r1) +# else + lbz %r3, RETVAL+7(%r1) +# endif + extsb %r3,%r3 + mtlr %r0 + b .Lfinish +# case FFI_TYPE_UINT16 +# ifdef __LITTLE_ENDIAN__ + lhz %r3, RETVAL+0(%r1) +# else + lhz %r3, RETVAL+6(%r1) +# endif + mtlr %r0 +.Lfinish: + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +# case FFI_TYPE_SINT16 +# ifdef __LITTLE_ENDIAN__ + lha %r3, RETVAL+0(%r1) +# else + lha %r3, RETVAL+6(%r1) +# endif + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +# case FFI_TYPE_UINT32 +# ifdef __LITTLE_ENDIAN__ + lwz %r3, RETVAL+0(%r1) +# else + lwz %r3, RETVAL+4(%r1) +# endif + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +# case FFI_TYPE_SINT32 +# ifdef __LITTLE_ENDIAN__ + lwa %r3, RETVAL+0(%r1) +# else + lwa %r3, RETVAL+4(%r1) +# endif + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +# case FFI_TYPE_UINT64 + ld %r3, RETVAL+0(%r1) + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +# case FFI_TYPE_SINT64 + ld %r3, RETVAL+0(%r1) + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +# case FFI_TYPE_STRUCT + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME + nop +# case FFI_TYPE_POINTER + ld %r3, RETVAL+0(%r1) + mtlr %r0 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +# case FFI_V2_TYPE_VECTOR + addi %r3, %r1, RETVAL + lvx %v2, 0, %r3 + mtlr %r0 + b .Lfinish +# case FFI_V2_TYPE_VECTOR_HOMOG + addi %r3, %r1, RETVAL + lvx %v2, 0, %r3 + addi %r3, %r3, 16 + b .Lmorevector +# case FFI_V2_TYPE_FLOAT_HOMOG + lfs %f1, RETVAL+0(%r1) + lfs %f2, RETVAL+4(%r1) + lfs %f3, RETVAL+8(%r1) + b .Lmorefloat +# case FFI_V2_TYPE_DOUBLE_HOMOG + lfd %f1, RETVAL+0(%r1) + lfd %f2, RETVAL+8(%r1) + lfd %f3, RETVAL+16(%r1) + lfd %f4, RETVAL+24(%r1) + mtlr %r0 + lfd %f5, RETVAL+32(%r1) + lfd %f6, RETVAL+40(%r1) + lfd %f7, RETVAL+48(%r1) + lfd %f8, RETVAL+56(%r1) + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +.Lmorevector: + lvx %v3, 0, %r3 + addi %r3, %r3, 16 + lvx %v4, 0, %r3 + addi %r3, %r3, 16 + lvx %v5, 0, %r3 + mtlr %r0 + addi %r3, %r3, 16 + lvx %v6, 0, %r3 + addi %r3, %r3, 16 + lvx %v7, 0, %r3 + addi %r3, %r3, 16 + lvx %v8, 0, %r3 + addi %r3, %r3, 16 + lvx %v9, 0, %r3 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +.Lmorefloat: + lfs %f4, RETVAL+12(%r1) + mtlr %r0 + lfs %f5, RETVAL+16(%r1) + lfs %f6, RETVAL+20(%r1) + lfs %f7, RETVAL+24(%r1) + lfs %f8, RETVAL+28(%r1) + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +.Lsmall: +# ifdef __LITTLE_ENDIAN__ + ld %r3,RETVAL+0(%r1) + mtlr %r0 + ld %r4,RETVAL+8(%r1) + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr +# else + # A struct smaller than a dword is returned in the low bits of r3 + # ie. right justified. Larger structs are passed left justified + # in r3 and r4. The return value area on the stack will have + # the structs as they are usually stored in memory. + cmpldi %r3, FFI_V2_TYPE_SMALL_STRUCT + 7 # size 8 bytes? + neg %r5, %r3 + ld %r3,RETVAL+0(%r1) + blt .Lsmalldown + mtlr %r0 + ld %r4,RETVAL+8(%r1) + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset STACKFRAME +.Lsmalldown: + addi %r5, %r5, FFI_V2_TYPE_SMALL_STRUCT + 7 + mtlr %r0 + sldi %r5, %r5, 3 + addi %r1, %r1, STACKFRAME + .cfi_def_cfa_offset 0 + srd %r3, %r3, %r5 + blr +# endif + + .cfi_endproc +# if _CALL_ELF == 2 + .size ffi_closure_LINUX64,.-ffi_closure_LINUX64 +# else +# ifdef _CALL_LINUX + .size ffi_closure_LINUX64,.-.L.ffi_closure_LINUX64 +# else + .long 0 + .byte 0,12,0,1,128,0,0,0 + .size .ffi_closure_LINUX64,.-.ffi_closure_LINUX64 +# endif +# endif + + + FFI_HIDDEN (ffi_go_closure_linux64) + .globl ffi_go_closure_linux64 + .text + .cfi_startproc +# if _CALL_ELF == 2 +ffi_go_closure_linux64: +# ifndef __PCREL__ + addis %r2, %r12, .TOC.-ffi_go_closure_linux64@ha + addi %r2, %r2, .TOC.-ffi_go_closure_linux64@l +# endif + .localentry ffi_go_closure_linux64, . - ffi_go_closure_linux64 +# else + .section ".opd","aw" + .align 3 +ffi_go_closure_linux64: +# ifdef _CALL_LINUX + .quad .L.ffi_go_closure_linux64,.TOC.@tocbase,0 + .type ffi_go_closure_linux64,@function + .text +.L.ffi_go_closure_linux64: +# else + FFI_HIDDEN (.ffi_go_closure_linux64) + .globl .ffi_go_closure_linux64 + .quad .ffi_go_closure_linux64,.TOC.@tocbase,0 + .size ffi_go_closure_linux64,24 + .type .ffi_go_closure_linux64,@function + .text +.ffi_go_closure_linux64: +# endif +# endif + +# if _CALL_ELF == 2 + ld %r12, 8(%r11) # closure->cif + mflr %r0 + lwz %r12, 28(%r12) # cif->flags + mtcrf 0x40, %r12 + addi %r12, %r1, PARMSAVE + bt 7, 0f + # Our caller has not allocated a parameter save area. + # We need to allocate one here and use it to pass gprs to + # ffi_closure_helper_LINUX64. + addi %r12, %r1, -STACKFRAME+PARMSAVE +0: + # Save general regs into parm save area + std %r3, 0(%r12) + std %r4, 8(%r12) + std %r5, 16(%r12) + std %r6, 24(%r12) + std %r7, 32(%r12) + std %r8, 40(%r12) + std %r9, 48(%r12) + std %r10, 56(%r12) + + # load up the pointer to the parm save area + mr %r7, %r12 +# else + mflr %r0 + # Save general regs into parm save area + # This is the parameter save area set up by our caller. + std %r3, PARMSAVE+0(%r1) + std %r4, PARMSAVE+8(%r1) + std %r5, PARMSAVE+16(%r1) + std %r6, PARMSAVE+24(%r1) + std %r7, PARMSAVE+32(%r1) + std %r8, PARMSAVE+40(%r1) + std %r9, PARMSAVE+48(%r1) + std %r10, PARMSAVE+56(%r1) + + # load up the pointer to the parm save area + addi %r7, %r1, PARMSAVE +# endif + std %r0, 16(%r1) + + # closure->cif + ld %r3, 8(%r11) + # closure->fun + ld %r4, 16(%r11) + # user_data + mr %r5, %r11 + b .Ldoclosure + + .cfi_endproc +# if _CALL_ELF == 2 + .size ffi_go_closure_linux64,.-ffi_go_closure_linux64 +# else +# ifdef _CALL_LINUX + .size ffi_go_closure_linux64,.-.L.ffi_go_closure_linux64 +# else + .long 0 + .byte 0,12,0,1,128,0,0,0 + .size .ffi_go_closure_linux64,.-.ffi_go_closure_linux64 +# endif +# endif +#endif + +#if (defined __ELF__ && defined __linux__) || _CALL_ELF == 2 + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ppc_closure.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ppc_closure.S new file mode 100644 index 0000000..b6d209d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/ppc_closure.S @@ -0,0 +1,397 @@ +/* ----------------------------------------------------------------------- + sysv.h - Copyright (c) 2003 Jakub Jelinek + Copyright (c) 2008 Red Hat, Inc. + + PowerPC Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ +#define LIBFFI_ASM +#include +#include +#include + + .file "ppc_closure.S" + +#ifndef POWERPC64 + +FFI_HIDDEN(ffi_closure_SYSV) +ENTRY(ffi_closure_SYSV) + .cfi_startproc + stwu %r1,-144(%r1) + .cfi_def_cfa_offset 144 + mflr %r0 + stw %r0,148(%r1) + .cfi_offset 65, 4 + +# we want to build up an areas for the parameters passed +# in registers (both floating point and integer) + + # so first save gpr 3 to gpr 10 (aligned to 4) + stw %r3, 16(%r1) + stw %r4, 20(%r1) + stw %r5, 24(%r1) + + # set up registers for the routine that does the work + + # closure->cif + lwz %r3,FFI_TRAMPOLINE_SIZE(%r11) + # closure->fun + lwz %r4,FFI_TRAMPOLINE_SIZE+4(%r11) + # closure->user_data + lwz %r5,FFI_TRAMPOLINE_SIZE+8(%r11) + +.Ldoclosure: + stw %r6, 28(%r1) + stw %r7, 32(%r1) + stw %r8, 36(%r1) + stw %r9, 40(%r1) + stw %r10,44(%r1) + +#ifndef __NO_FPRS__ + # next save fpr 1 to fpr 8 (aligned to 8) + stfd %f1, 48(%r1) + stfd %f2, 56(%r1) + stfd %f3, 64(%r1) + stfd %f4, 72(%r1) + stfd %f5, 80(%r1) + stfd %f6, 88(%r1) + stfd %f7, 96(%r1) + stfd %f8, 104(%r1) +#endif + + # pointer to the result storage + addi %r6,%r1,112 + + # pointer to the saved gpr registers + addi %r7,%r1,16 + + # pointer to the saved fpr registers + addi %r8,%r1,48 + + # pointer to the outgoing parameter save area in the previous frame + # i.e. the previous frame pointer + 8 + addi %r9,%r1,152 + + # make the call + bl ffi_closure_helper_SYSV@local +.Lret: + # now r3 contains the return type + # so use it to look up in a table + # so we know how to deal with each type + + # look up the proper starting point in table + # by using return type as offset + + mflr %r4 # move address of .Lret to r4 + slwi %r3,%r3,4 # now multiply return type by 16 + addi %r4, %r4, .Lret_type0 - .Lret + lwz %r0,148(%r1) + add %r3,%r3,%r4 # add contents of table to table address + mtctr %r3 + bctr # jump to it + +# Each of the ret_typeX code fragments has to be exactly 16 bytes long +# (4 instructions). For cache effectiveness we align to a 16 byte boundary +# first. + .align 4 +# case FFI_TYPE_VOID +.Lret_type0: + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + nop + +# case FFI_TYPE_INT + lwz %r3,112+0(%r1) + mtlr %r0 +.Lfinish: + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_TYPE_FLOAT +#ifndef __NO_FPRS__ + lfs %f1,112+0(%r1) +#else + nop +#endif + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_TYPE_DOUBLE +#ifndef __NO_FPRS__ + lfd %f1,112+0(%r1) +#else + nop +#endif + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_TYPE_LONGDOUBLE +#ifndef __NO_FPRS__ + lfd %f1,112+0(%r1) + lfd %f2,112+8(%r1) + mtlr %r0 + b .Lfinish +#else + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + nop +#endif + +# case FFI_TYPE_UINT8 +#ifdef __LITTLE_ENDIAN__ + lbz %r3,112+0(%r1) +#else + lbz %r3,112+3(%r1) +#endif + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_TYPE_SINT8 +#ifdef __LITTLE_ENDIAN__ + lbz %r3,112+0(%r1) +#else + lbz %r3,112+3(%r1) +#endif + extsb %r3,%r3 + mtlr %r0 + b .Lfinish + +# case FFI_TYPE_UINT16 +#ifdef __LITTLE_ENDIAN__ + lhz %r3,112+0(%r1) +#else + lhz %r3,112+2(%r1) +#endif + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_TYPE_SINT16 +#ifdef __LITTLE_ENDIAN__ + lha %r3,112+0(%r1) +#else + lha %r3,112+2(%r1) +#endif + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_TYPE_UINT32 + lwz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_TYPE_SINT32 + lwz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_TYPE_UINT64 + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) + mtlr %r0 + b .Lfinish + +# case FFI_TYPE_SINT64 + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) + mtlr %r0 + b .Lfinish + +# case FFI_TYPE_STRUCT + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + nop + +# case FFI_TYPE_POINTER + lwz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_TYPE_UINT128 + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) + lwz %r5,112+8(%r1) + b .Luint128 + +# The return types below are only used when the ABI type is FFI_SYSV. +# case FFI_SYSV_TYPE_SMALL_STRUCT + 1. One byte struct. + lbz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_SYSV_TYPE_SMALL_STRUCT + 2. Two byte struct. + lhz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_SYSV_TYPE_SMALL_STRUCT + 3. Three byte struct. + lwz %r3,112+0(%r1) +#ifdef __LITTLE_ENDIAN__ + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 +#else + srwi %r3,%r3,8 + mtlr %r0 + b .Lfinish +#endif + +# case FFI_SYSV_TYPE_SMALL_STRUCT + 4. Four byte struct. + lwz %r3,112+0(%r1) + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 + +# case FFI_SYSV_TYPE_SMALL_STRUCT + 5. Five byte struct. + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) +#ifdef __LITTLE_ENDIAN__ + mtlr %r0 + b .Lfinish +#else + li %r5,24 + b .Lstruct567 +#endif + +# case FFI_SYSV_TYPE_SMALL_STRUCT + 6. Six byte struct. + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) +#ifdef __LITTLE_ENDIAN__ + mtlr %r0 + b .Lfinish +#else + li %r5,16 + b .Lstruct567 +#endif + +# case FFI_SYSV_TYPE_SMALL_STRUCT + 7. Seven byte struct. + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) +#ifdef __LITTLE_ENDIAN__ + mtlr %r0 + b .Lfinish +#else + li %r5,8 + b .Lstruct567 +#endif + +# case FFI_SYSV_TYPE_SMALL_STRUCT + 8. Eight byte struct. + lwz %r3,112+0(%r1) + lwz %r4,112+4(%r1) + mtlr %r0 + b .Lfinish + +#ifndef __LITTLE_ENDIAN__ +.Lstruct567: + subfic %r6,%r5,32 + srw %r4,%r4,%r5 + slw %r6,%r3,%r6 + srw %r3,%r3,%r5 + or %r4,%r6,%r4 + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_def_cfa_offset 144 +#endif + +.Luint128: + lwz %r6,112+12(%r1) + mtlr %r0 + addi %r1,%r1,144 + .cfi_def_cfa_offset 0 + blr + .cfi_endproc +END(ffi_closure_SYSV) + + +FFI_HIDDEN(ffi_go_closure_sysv) +ENTRY(ffi_go_closure_sysv) + .cfi_startproc + stwu %r1,-144(%r1) + .cfi_def_cfa_offset 144 + mflr %r0 + stw %r0,148(%r1) + .cfi_offset 65, 4 + + stw %r3, 16(%r1) + stw %r4, 20(%r1) + stw %r5, 24(%r1) + + # closure->cif + lwz %r3,4(%r11) + # closure->fun + lwz %r4,8(%r11) + # user_data + mr %r5,%r11 + b .Ldoclosure + .cfi_endproc +END(ffi_go_closure_sysv) + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/sysv.S new file mode 100644 index 0000000..df97734 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/powerpc/sysv.S @@ -0,0 +1,173 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 1998 Geoffrey Keating + Copyright (C) 2007 Free Software Foundation, Inc + + PowerPC Assembly glue. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include +#include + +#ifndef POWERPC64 +FFI_HIDDEN(ffi_call_SYSV) +ENTRY(ffi_call_SYSV) + .cfi_startproc + /* Save the old stack pointer as AP. */ + mr %r10,%r1 + .cfi_def_cfa_register 10 + + /* Allocate the stack space we need. */ + stwux %r1,%r1,%r8 + /* Save registers we use. */ + mflr %r9 + stw %r28,-16(%r10) + stw %r29,-12(%r10) + stw %r30, -8(%r10) + stw %r31, -4(%r10) + stw %r9, 4(%r10) + .cfi_offset 65, 4 + .cfi_offset 31, -4 + .cfi_offset 30, -8 + .cfi_offset 29, -12 + .cfi_offset 28, -16 + + /* Save arguments over call... */ + stw %r7, -20(%r10) /* closure, */ + mr %r31,%r6 /* flags, */ + mr %r30,%r5 /* rvalue, */ + mr %r29,%r4 /* function address, */ + mr %r28,%r10 /* our AP. */ + .cfi_def_cfa_register 28 + + /* Call ffi_prep_args_SYSV. */ + mr %r4,%r1 + bl ffi_prep_args_SYSV@local + + /* Now do the call. */ + /* Set up cr1 with bits 4-7 of the flags. */ + mtcrf 0x40,%r31 + /* Get the address to call into CTR. */ + mtctr %r29 + /* Load all those argument registers. */ + lwz %r3,-24-(8*4)(%r28) + lwz %r4,-24-(7*4)(%r28) + lwz %r5,-24-(6*4)(%r28) + lwz %r6,-24-(5*4)(%r28) + bf- 5,1f + nop + lwz %r7,-24-(4*4)(%r28) + lwz %r8,-24-(3*4)(%r28) + lwz %r9,-24-(2*4)(%r28) + lwz %r10,-24-(1*4)(%r28) + nop +1: + +#ifndef __NO_FPRS__ + /* Load all the FP registers. */ + bf- 6,2f + lfd %f1,-24-(8*4)-(8*8)(%r28) + lfd %f2,-24-(8*4)-(7*8)(%r28) + lfd %f3,-24-(8*4)-(6*8)(%r28) + lfd %f4,-24-(8*4)-(5*8)(%r28) + nop + lfd %f5,-24-(8*4)-(4*8)(%r28) + lfd %f6,-24-(8*4)-(3*8)(%r28) + lfd %f7,-24-(8*4)-(2*8)(%r28) + lfd %f8,-24-(8*4)-(1*8)(%r28) +#endif +2: + + /* Make the call. */ + lwz %r11, -20(%r28) + bctrl + + /* Now, deal with the return value. */ + mtcrf 0x03,%r31 /* cr6-cr7 */ + bt- 31,L(small_struct_return_value) + bt- 30,L(done_return_value) +#ifndef __NO_FPRS__ + bt- 29,L(fp_return_value) +#endif + stw %r3,0(%r30) + bf+ 27,L(done_return_value) + stw %r4,4(%r30) + bf 26,L(done_return_value) + stw %r5,8(%r30) + stw %r6,12(%r30) + /* Fall through... */ + +L(done_return_value): + /* Restore the registers we used and return. */ + lwz %r9, 4(%r28) + lwz %r31, -4(%r28) + mtlr %r9 + lwz %r30, -8(%r28) + lwz %r29,-12(%r28) + lwz %r28,-16(%r28) + .cfi_remember_state + /* At this point we don't have a cfa register. Say all our + saved regs have been restored. */ + .cfi_same_value 65 + .cfi_same_value 31 + .cfi_same_value 30 + .cfi_same_value 29 + .cfi_same_value 28 + /* Hopefully this works.. */ + .cfi_def_cfa_register 1 + .cfi_offset 1, 0 + lwz %r1,0(%r1) + .cfi_same_value 1 + blr + +#ifndef __NO_FPRS__ +L(fp_return_value): + .cfi_restore_state + bf 27,L(float_return_value) + stfd %f1,0(%r30) + bf 26,L(done_return_value) + stfd %f2,8(%r30) + b L(done_return_value) +L(float_return_value): + stfs %f1,0(%r30) + b L(done_return_value) +#endif + +L(small_struct_return_value): + /* + * The C code always allocates a properly-aligned 8-byte bounce + * buffer to make this assembly code very simple. Just write out + * r3 and r4 to the buffer to allow the C code to handle the rest. + */ + stw %r3, 0(%r30) + stw %r4, 4(%r30) + b L(done_return_value) + .cfi_endproc + +END(ffi_call_SYSV) + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/prep_cif.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/prep_cif.c new file mode 100644 index 0000000..1db3804 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/prep_cif.c @@ -0,0 +1,263 @@ +/* ----------------------------------------------------------------------- + prep_cif.c - Copyright (c) 2011, 2012 Anthony Green + Copyright (c) 1996, 1998, 2007 Red Hat, Inc. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include +#include + +/* Round up to FFI_SIZEOF_ARG. */ + +#define STACK_ARG_SIZE(x) FFI_ALIGN(x, FFI_SIZEOF_ARG) + +/* Perform machine independent initialization of aggregate type + specifications. */ + +static ffi_status initialize_aggregate(ffi_type *arg, size_t *offsets) +{ + ffi_type **ptr; + + if (UNLIKELY(arg == NULL || arg->elements == NULL)) + return FFI_BAD_TYPEDEF; + + arg->size = 0; + arg->alignment = 0; + + ptr = &(arg->elements[0]); + + if (UNLIKELY(ptr == 0)) + return FFI_BAD_TYPEDEF; + + while ((*ptr) != NULL) + { + if (UNLIKELY(((*ptr)->size == 0) + && (initialize_aggregate((*ptr), NULL) != FFI_OK))) + return FFI_BAD_TYPEDEF; + + /* Perform a sanity check on the argument type */ + FFI_ASSERT_VALID_TYPE(*ptr); + + arg->size = FFI_ALIGN(arg->size, (*ptr)->alignment); + if (offsets) + *offsets++ = arg->size; + arg->size += (*ptr)->size; + + arg->alignment = (arg->alignment > (*ptr)->alignment) ? + arg->alignment : (*ptr)->alignment; + + ptr++; + } + + /* Structure size includes tail padding. This is important for + structures that fit in one register on ABIs like the PowerPC64 + Linux ABI that right justify small structs in a register. + It's also needed for nested structure layout, for example + struct A { long a; char b; }; struct B { struct A x; char y; }; + should find y at an offset of 2*sizeof(long) and result in a + total size of 3*sizeof(long). */ + arg->size = FFI_ALIGN (arg->size, arg->alignment); + + /* On some targets, the ABI defines that structures have an additional + alignment beyond the "natural" one based on their elements. */ +#ifdef FFI_AGGREGATE_ALIGNMENT + if (FFI_AGGREGATE_ALIGNMENT > arg->alignment) + arg->alignment = FFI_AGGREGATE_ALIGNMENT; +#endif + + if (arg->size == 0) + return FFI_BAD_TYPEDEF; + else + return FFI_OK; +} + +#ifndef __CRIS__ +/* The CRIS ABI specifies structure elements to have byte + alignment only, so it completely overrides this functions, + which assumes "natural" alignment and padding. */ + +/* Perform machine independent ffi_cif preparation, then call + machine dependent routine. */ + +/* For non variadic functions isvariadic should be 0 and + nfixedargs==ntotalargs. + + For variadic calls, isvariadic should be 1 and nfixedargs + and ntotalargs set as appropriate. nfixedargs must always be >=1 */ + + +ffi_status FFI_HIDDEN ffi_prep_cif_core(ffi_cif *cif, ffi_abi abi, + unsigned int isvariadic, + unsigned int nfixedargs, + unsigned int ntotalargs, + ffi_type *rtype, ffi_type **atypes) +{ + unsigned bytes = 0; + unsigned int i; + ffi_type **ptr; + + FFI_ASSERT(cif != NULL); + FFI_ASSERT((!isvariadic) || (nfixedargs >= 1)); + FFI_ASSERT(nfixedargs <= ntotalargs); + + if (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI)) + return FFI_BAD_ABI; + + cif->abi = abi; + cif->arg_types = atypes; + cif->nargs = ntotalargs; + cif->rtype = rtype; + + cif->flags = 0; +#if (defined(_M_ARM64) || defined(__aarch64__)) && defined(_WIN32) + cif->is_variadic = isvariadic; +#endif +#if HAVE_LONG_DOUBLE_VARIANT + ffi_prep_types (abi); +#endif + + /* Initialize the return type if necessary */ + if ((cif->rtype->size == 0) + && (initialize_aggregate(cif->rtype, NULL) != FFI_OK)) + return FFI_BAD_TYPEDEF; + +#ifndef FFI_TARGET_HAS_COMPLEX_TYPE + if (rtype->type == FFI_TYPE_COMPLEX) + abort(); +#endif + /* Perform a sanity check on the return type */ + FFI_ASSERT_VALID_TYPE(cif->rtype); + + /* x86, x86-64 and s390 stack space allocation is handled in prep_machdep. */ +#if !defined FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION + /* Make space for the return structure pointer */ + if (cif->rtype->type == FFI_TYPE_STRUCT +#ifdef TILE + && (cif->rtype->size > 10 * FFI_SIZEOF_ARG) +#endif +#ifdef XTENSA + && (cif->rtype->size > 16) +#endif +#ifdef NIOS2 + && (cif->rtype->size > 8) +#endif + ) + bytes = STACK_ARG_SIZE(sizeof(void*)); +#endif + + for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) + { + + /* Initialize any uninitialized aggregate type definitions */ + if (((*ptr)->size == 0) + && (initialize_aggregate((*ptr), NULL) != FFI_OK)) + return FFI_BAD_TYPEDEF; + +#ifndef FFI_TARGET_HAS_COMPLEX_TYPE + if ((*ptr)->type == FFI_TYPE_COMPLEX) + abort(); +#endif + /* Perform a sanity check on the argument type, do this + check after the initialization. */ + FFI_ASSERT_VALID_TYPE(*ptr); + +#if !defined FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION + { + /* Add any padding if necessary */ + if (((*ptr)->alignment - 1) & bytes) + bytes = (unsigned)FFI_ALIGN(bytes, (*ptr)->alignment); + +#ifdef TILE + if (bytes < 10 * FFI_SIZEOF_ARG && + bytes + STACK_ARG_SIZE((*ptr)->size) > 10 * FFI_SIZEOF_ARG) + { + /* An argument is never split between the 10 parameter + registers and the stack. */ + bytes = 10 * FFI_SIZEOF_ARG; + } +#endif +#ifdef XTENSA + if (bytes <= 6*4 && bytes + STACK_ARG_SIZE((*ptr)->size) > 6*4) + bytes = 6*4; +#endif + + bytes += (unsigned int)STACK_ARG_SIZE((*ptr)->size); + } +#endif + } + + cif->bytes = bytes; + + /* Perform machine dependent cif processing */ +#ifdef FFI_TARGET_SPECIFIC_VARIADIC + if (isvariadic) + return ffi_prep_cif_machdep_var(cif, nfixedargs, ntotalargs); +#endif + + return ffi_prep_cif_machdep(cif); +} +#endif /* not __CRIS__ */ + +ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, unsigned int nargs, + ffi_type *rtype, ffi_type **atypes) +{ + return ffi_prep_cif_core(cif, abi, 0, nargs, nargs, rtype, atypes); +} + +ffi_status ffi_prep_cif_var(ffi_cif *cif, + ffi_abi abi, + unsigned int nfixedargs, + unsigned int ntotalargs, + ffi_type *rtype, + ffi_type **atypes) +{ + return ffi_prep_cif_core(cif, abi, 1, nfixedargs, ntotalargs, rtype, atypes); +} + +#if FFI_CLOSURES + +ffi_status +ffi_prep_closure (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data) +{ + return ffi_prep_closure_loc (closure, cif, fun, user_data, closure); +} + +#endif + +ffi_status +ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type, size_t *offsets) +{ + if (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI)) + return FFI_BAD_ABI; + if (struct_type->type != FFI_TYPE_STRUCT) + return FFI_BAD_TYPEDEF; + +#if HAVE_LONG_DOUBLE_VARIANT + ffi_prep_types (abi); +#endif + + return initialize_aggregate(struct_type, offsets); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/raw_api.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/raw_api.c new file mode 100644 index 0000000..be15611 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/raw_api.c @@ -0,0 +1,267 @@ +/* ----------------------------------------------------------------------- + raw_api.c - Copyright (c) 1999, 2008 Red Hat, Inc. + + Author: Kresten Krab Thorup + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +/* This file defines generic functions for use with the raw api. */ + +#include +#include + +#if !FFI_NO_RAW_API + +size_t +ffi_raw_size (ffi_cif *cif) +{ + size_t result = 0; + int i; + + ffi_type **at = cif->arg_types; + + for (i = cif->nargs-1; i >= 0; i--, at++) + { +#if !FFI_NO_STRUCTS + if ((*at)->type == FFI_TYPE_STRUCT) + result += FFI_ALIGN (sizeof (void*), FFI_SIZEOF_ARG); + else +#endif + result += FFI_ALIGN ((*at)->size, FFI_SIZEOF_ARG); + } + + return result; +} + + +void +ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args) +{ + unsigned i; + ffi_type **tp = cif->arg_types; + +#if WORDS_BIGENDIAN + + for (i = 0; i < cif->nargs; i++, tp++, args++) + { + switch ((*tp)->type) + { + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + *args = (void*) ((char*)(raw++) + FFI_SIZEOF_ARG - 1); + break; + + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + *args = (void*) ((char*)(raw++) + FFI_SIZEOF_ARG - 2); + break; + +#if FFI_SIZEOF_ARG >= 4 + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + *args = (void*) ((char*)(raw++) + FFI_SIZEOF_ARG - 4); + break; +#endif + +#if !FFI_NO_STRUCTS + case FFI_TYPE_STRUCT: + *args = (raw++)->ptr; + break; +#endif + + case FFI_TYPE_COMPLEX: + *args = (raw++)->ptr; + break; + + case FFI_TYPE_POINTER: + *args = (void*) &(raw++)->ptr; + break; + + default: + *args = raw; + raw += FFI_ALIGN ((*tp)->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; + } + } + +#else /* WORDS_BIGENDIAN */ + +#if !PDP + + /* then assume little endian */ + for (i = 0; i < cif->nargs; i++, tp++, args++) + { +#if !FFI_NO_STRUCTS + if ((*tp)->type == FFI_TYPE_STRUCT) + { + *args = (raw++)->ptr; + } + else +#endif + if ((*tp)->type == FFI_TYPE_COMPLEX) + { + *args = (raw++)->ptr; + } + else + { + *args = (void*) raw; + raw += FFI_ALIGN ((*tp)->size, sizeof (void*)) / sizeof (void*); + } + } + +#else +#error "pdp endian not supported" +#endif /* ! PDP */ + +#endif /* WORDS_BIGENDIAN */ +} + +void +ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw) +{ + unsigned i; + ffi_type **tp = cif->arg_types; + + for (i = 0; i < cif->nargs; i++, tp++, args++) + { + switch ((*tp)->type) + { + case FFI_TYPE_UINT8: + (raw++)->uint = *(UINT8*) (*args); + break; + + case FFI_TYPE_SINT8: + (raw++)->sint = *(SINT8*) (*args); + break; + + case FFI_TYPE_UINT16: + (raw++)->uint = *(UINT16*) (*args); + break; + + case FFI_TYPE_SINT16: + (raw++)->sint = *(SINT16*) (*args); + break; + +#if FFI_SIZEOF_ARG >= 4 + case FFI_TYPE_UINT32: + (raw++)->uint = *(UINT32*) (*args); + break; + + case FFI_TYPE_SINT32: + (raw++)->sint = *(SINT32*) (*args); + break; +#endif + +#if !FFI_NO_STRUCTS + case FFI_TYPE_STRUCT: + (raw++)->ptr = *args; + break; +#endif + + case FFI_TYPE_COMPLEX: + (raw++)->ptr = *args; + break; + + case FFI_TYPE_POINTER: + (raw++)->ptr = **(void***) args; + break; + + default: + memcpy ((void*) raw->data, (void*)*args, (*tp)->size); + raw += FFI_ALIGN ((*tp)->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; + } + } +} + +#if !FFI_NATIVE_RAW_API + + +/* This is a generic definition of ffi_raw_call, to be used if the + * native system does not provide a machine-specific implementation. + * Having this, allows code to be written for the raw API, without + * the need for system-specific code to handle input in that format; + * these following couple of functions will handle the translation forth + * and back automatically. */ + +void ffi_raw_call (ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_raw *raw) +{ + void **avalue = (void**) alloca (cif->nargs * sizeof (void*)); + ffi_raw_to_ptrarray (cif, raw, avalue); + ffi_call (cif, fn, rvalue, avalue); +} + +#if FFI_CLOSURES /* base system provides closures */ + +static void +ffi_translate_args (ffi_cif *cif, void *rvalue, + void **avalue, void *user_data) +{ + ffi_raw *raw = (ffi_raw*)alloca (ffi_raw_size (cif)); + ffi_raw_closure *cl = (ffi_raw_closure*)user_data; + + ffi_ptrarray_to_raw (cif, avalue, raw); + (*cl->fun) (cif, rvalue, raw, cl->user_data); +} + +ffi_status +ffi_prep_raw_closure_loc (ffi_raw_closure* cl, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data, + void *codeloc) +{ + ffi_status status; + + status = ffi_prep_closure_loc ((ffi_closure*) cl, + cif, + &ffi_translate_args, + codeloc, + codeloc); + if (status == FFI_OK) + { + cl->fun = fun; + cl->user_data = user_data; + } + + return status; +} + +#endif /* FFI_CLOSURES */ +#endif /* !FFI_NATIVE_RAW_API */ + +#if FFI_CLOSURES + +/* Again, here is the generic version of ffi_prep_raw_closure, which + * will install an intermediate "hub" for translation of arguments from + * the pointer-array format, to the raw format */ + +ffi_status +ffi_prep_raw_closure (ffi_raw_closure* cl, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data) +{ + return ffi_prep_raw_closure_loc (cl, cif, fun, user_data, cl); +} + +#endif /* FFI_CLOSURES */ + +#endif /* !FFI_NO_RAW_API */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/riscv/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/riscv/ffi.c new file mode 100644 index 0000000..c910858 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/riscv/ffi.c @@ -0,0 +1,481 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2015 Michael Knyszek + 2015 Andrew Waterman + 2018 Stef O'Rear + Based on MIPS N32/64 port + + RISC-V Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include +#include + +#if __riscv_float_abi_double +#define ABI_FLEN 64 +#define ABI_FLOAT double +#elif __riscv_float_abi_single +#define ABI_FLEN 32 +#define ABI_FLOAT float +#endif + +#define NARGREG 8 +#define STKALIGN 16 +#define MAXCOPYARG (2 * sizeof(double)) + +typedef struct call_context +{ +#if ABI_FLEN + ABI_FLOAT fa[8]; +#endif + size_t a[8]; + /* used by the assembly code to in-place construct its own stack frame */ + char frame[16]; +} call_context; + +typedef struct call_builder +{ + call_context *aregs; + int used_integer; + int used_float; + size_t *used_stack; +} call_builder; + +/* integer (not pointer) less than ABI XLEN */ +/* FFI_TYPE_INT does not appear to be used */ +#if __SIZEOF_POINTER__ == 8 +#define IS_INT(type) ((type) >= FFI_TYPE_UINT8 && (type) <= FFI_TYPE_SINT64) +#else +#define IS_INT(type) ((type) >= FFI_TYPE_UINT8 && (type) <= FFI_TYPE_SINT32) +#endif + +#if ABI_FLEN +typedef struct { + char as_elements, type1, offset2, type2; +} float_struct_info; + +#if ABI_FLEN >= 64 +#define IS_FLOAT(type) ((type) >= FFI_TYPE_FLOAT && (type) <= FFI_TYPE_DOUBLE) +#else +#define IS_FLOAT(type) ((type) == FFI_TYPE_FLOAT) +#endif + +static ffi_type **flatten_struct(ffi_type *in, ffi_type **out, ffi_type **out_end) { + int i; + if (out == out_end) return out; + if (in->type != FFI_TYPE_STRUCT) { + *(out++) = in; + } else { + for (i = 0; in->elements[i]; i++) + out = flatten_struct(in->elements[i], out, out_end); + } + return out; +} + +/* Structs with at most two fields after flattening, one of which is of + floating point type, are passed in multiple registers if sufficient + registers are available. */ +static float_struct_info struct_passed_as_elements(call_builder *cb, ffi_type *top) { + float_struct_info ret = {0, 0, 0, 0}; + ffi_type *fields[3]; + int num_floats, num_ints; + int num_fields = flatten_struct(top, fields, fields + 3) - fields; + + if (num_fields == 1) { + if (IS_FLOAT(fields[0]->type)) { + ret.as_elements = 1; + ret.type1 = fields[0]->type; + } + } else if (num_fields == 2) { + num_floats = IS_FLOAT(fields[0]->type) + IS_FLOAT(fields[1]->type); + num_ints = IS_INT(fields[0]->type) + IS_INT(fields[1]->type); + if (num_floats == 0 || num_floats + num_ints != 2) + return ret; + if (cb->used_float + num_floats > NARGREG || cb->used_integer + (2 - num_floats) > NARGREG) + return ret; + if (!IS_FLOAT(fields[0]->type) && !IS_FLOAT(fields[1]->type)) + return ret; + + ret.type1 = fields[0]->type; + ret.type2 = fields[1]->type; + ret.offset2 = FFI_ALIGN(fields[0]->size, fields[1]->alignment); + ret.as_elements = 1; + } + + return ret; +} +#endif + +/* allocates a single register, float register, or XLEN-sized stack slot to a datum */ +static void marshal_atom(call_builder *cb, int type, void *data) { + size_t value = 0; + switch (type) { + case FFI_TYPE_UINT8: value = *(uint8_t *)data; break; + case FFI_TYPE_SINT8: value = *(int8_t *)data; break; + case FFI_TYPE_UINT16: value = *(uint16_t *)data; break; + case FFI_TYPE_SINT16: value = *(int16_t *)data; break; + /* 32-bit quantities are always sign-extended in the ABI */ + case FFI_TYPE_UINT32: value = *(int32_t *)data; break; + case FFI_TYPE_SINT32: value = *(int32_t *)data; break; +#if __SIZEOF_POINTER__ == 8 + case FFI_TYPE_UINT64: value = *(uint64_t *)data; break; + case FFI_TYPE_SINT64: value = *(int64_t *)data; break; +#endif + case FFI_TYPE_POINTER: value = *(size_t *)data; break; + + /* float values may be recoded in an implementation-defined way + by hardware conforming to 2.1 or earlier, so use asm to + reinterpret floats as doubles */ +#if ABI_FLEN >= 32 + case FFI_TYPE_FLOAT: + asm("" : "=f"(cb->aregs->fa[cb->used_float++]) : "0"(*(float *)data)); + return; +#endif +#if ABI_FLEN >= 64 + case FFI_TYPE_DOUBLE: + asm("" : "=f"(cb->aregs->fa[cb->used_float++]) : "0"(*(double *)data)); + return; +#endif + default: FFI_ASSERT(0); break; + } + + if (cb->used_integer == NARGREG) { + *cb->used_stack++ = value; + } else { + cb->aregs->a[cb->used_integer++] = value; + } +} + +static void unmarshal_atom(call_builder *cb, int type, void *data) { + size_t value; + switch (type) { +#if ABI_FLEN >= 32 + case FFI_TYPE_FLOAT: + asm("" : "=f"(*(float *)data) : "0"(cb->aregs->fa[cb->used_float++])); + return; +#endif +#if ABI_FLEN >= 64 + case FFI_TYPE_DOUBLE: + asm("" : "=f"(*(double *)data) : "0"(cb->aregs->fa[cb->used_float++])); + return; +#endif + } + + if (cb->used_integer == NARGREG) { + value = *cb->used_stack++; + } else { + value = cb->aregs->a[cb->used_integer++]; + } + + switch (type) { + case FFI_TYPE_UINT8: *(uint8_t *)data = value; break; + case FFI_TYPE_SINT8: *(uint8_t *)data = value; break; + case FFI_TYPE_UINT16: *(uint16_t *)data = value; break; + case FFI_TYPE_SINT16: *(uint16_t *)data = value; break; + case FFI_TYPE_UINT32: *(uint32_t *)data = value; break; + case FFI_TYPE_SINT32: *(uint32_t *)data = value; break; +#if __SIZEOF_POINTER__ == 8 + case FFI_TYPE_UINT64: *(uint64_t *)data = value; break; + case FFI_TYPE_SINT64: *(uint64_t *)data = value; break; +#endif + case FFI_TYPE_POINTER: *(size_t *)data = value; break; + default: FFI_ASSERT(0); break; + } +} + +/* adds an argument to a call, or a not by reference return value */ +static void marshal(call_builder *cb, ffi_type *type, int var, void *data) { + size_t realign[2]; + +#if ABI_FLEN + if (!var && type->type == FFI_TYPE_STRUCT) { + float_struct_info fsi = struct_passed_as_elements(cb, type); + if (fsi.as_elements) { + marshal_atom(cb, fsi.type1, data); + if (fsi.offset2) + marshal_atom(cb, fsi.type2, ((char*)data) + fsi.offset2); + return; + } + } + + if (!var && cb->used_float < NARGREG && IS_FLOAT(type->type)) { + marshal_atom(cb, type->type, data); + return; + } +#endif + + if (type->size > 2 * __SIZEOF_POINTER__) { + /* pass by reference */ + marshal_atom(cb, FFI_TYPE_POINTER, &data); + } else if (IS_INT(type->type) || type->type == FFI_TYPE_POINTER) { + marshal_atom(cb, type->type, data); + } else { + /* overlong integers, soft-float floats, and structs without special + float handling are treated identically from this point on */ + + /* variadics are aligned even in registers */ + if (type->alignment > __SIZEOF_POINTER__) { + if (var) + cb->used_integer = FFI_ALIGN(cb->used_integer, 2); + cb->used_stack = (size_t *)FFI_ALIGN(cb->used_stack, 2*__SIZEOF_POINTER__); + } + + memcpy(realign, data, type->size); + if (type->size > 0) + marshal_atom(cb, FFI_TYPE_POINTER, realign); + if (type->size > __SIZEOF_POINTER__) + marshal_atom(cb, FFI_TYPE_POINTER, realign + 1); + } +} + +/* for arguments passed by reference returns the pointer, otherwise the arg is copied (up to MAXCOPYARG bytes) */ +static void *unmarshal(call_builder *cb, ffi_type *type, int var, void *data) { + size_t realign[2]; + void *pointer; + +#if ABI_FLEN + if (!var && type->type == FFI_TYPE_STRUCT) { + float_struct_info fsi = struct_passed_as_elements(cb, type); + if (fsi.as_elements) { + unmarshal_atom(cb, fsi.type1, data); + if (fsi.offset2) + unmarshal_atom(cb, fsi.type2, ((char*)data) + fsi.offset2); + return data; + } + } + + if (!var && cb->used_float < NARGREG && IS_FLOAT(type->type)) { + unmarshal_atom(cb, type->type, data); + return data; + } +#endif + + if (type->size > 2 * __SIZEOF_POINTER__) { + /* pass by reference */ + unmarshal_atom(cb, FFI_TYPE_POINTER, (char*)&pointer); + return pointer; + } else if (IS_INT(type->type) || type->type == FFI_TYPE_POINTER) { + unmarshal_atom(cb, type->type, data); + return data; + } else { + /* overlong integers, soft-float floats, and structs without special + float handling are treated identically from this point on */ + + /* variadics are aligned even in registers */ + if (type->alignment > __SIZEOF_POINTER__) { + if (var) + cb->used_integer = FFI_ALIGN(cb->used_integer, 2); + cb->used_stack = (size_t *)FFI_ALIGN(cb->used_stack, 2*__SIZEOF_POINTER__); + } + + if (type->size > 0) + unmarshal_atom(cb, FFI_TYPE_POINTER, realign); + if (type->size > __SIZEOF_POINTER__) + unmarshal_atom(cb, FFI_TYPE_POINTER, realign + 1); + memcpy(data, realign, type->size); + return data; + } +} + +static int passed_by_ref(call_builder *cb, ffi_type *type, int var) { +#if ABI_FLEN + if (!var && type->type == FFI_TYPE_STRUCT) { + float_struct_info fsi = struct_passed_as_elements(cb, type); + if (fsi.as_elements) return 0; + } +#endif + + return type->size > 2 * __SIZEOF_POINTER__; +} + +/* Perform machine dependent cif processing */ +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) { + cif->riscv_nfixedargs = cif->nargs; + return FFI_OK; +} + +/* Perform machine dependent cif processing when we have a variadic function */ + +ffi_status ffi_prep_cif_machdep_var(ffi_cif *cif, unsigned int nfixedargs, unsigned int ntotalargs) { + cif->riscv_nfixedargs = nfixedargs; + return FFI_OK; +} + +/* Low level routine for calling functions */ +extern void ffi_call_asm (void *stack, struct call_context *regs, + void (*fn) (void), void *closure) FFI_HIDDEN; + +static void +ffi_call_int (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue, + void *closure) +{ + /* this is a conservative estimate, assuming a complex return value and + that all remaining arguments are long long / __int128 */ + size_t arg_bytes = cif->nargs <= 3 ? 0 : + FFI_ALIGN(2 * sizeof(size_t) * (cif->nargs - 3), STKALIGN); + size_t rval_bytes = 0; + if (rvalue == NULL && cif->rtype->size > 2*__SIZEOF_POINTER__) + rval_bytes = FFI_ALIGN(cif->rtype->size, STKALIGN); + size_t alloc_size = arg_bytes + rval_bytes + sizeof(call_context); + + /* the assembly code will deallocate all stack data at lower addresses + than the argument region, so we need to allocate the frame and the + return value after the arguments in a single allocation */ + size_t alloc_base; + /* Argument region must be 16-byte aligned */ + if (_Alignof(max_align_t) >= STKALIGN) { + /* since sizeof long double is normally 16, the compiler will + guarantee alloca alignment to at least that much */ + alloc_base = (size_t)alloca(alloc_size); + } else { + alloc_base = FFI_ALIGN(alloca(alloc_size + STKALIGN - 1), STKALIGN); + } + + if (rval_bytes) + rvalue = (void*)(alloc_base + arg_bytes); + + call_builder cb; + cb.used_float = cb.used_integer = 0; + cb.aregs = (call_context*)(alloc_base + arg_bytes + rval_bytes); + cb.used_stack = (void*)alloc_base; + + int return_by_ref = passed_by_ref(&cb, cif->rtype, 0); + if (return_by_ref) + marshal(&cb, &ffi_type_pointer, 0, &rvalue); + + int i; + for (i = 0; i < cif->nargs; i++) + marshal(&cb, cif->arg_types[i], i >= cif->riscv_nfixedargs, avalue[i]); + + ffi_call_asm ((void *) alloc_base, cb.aregs, fn, closure); + + cb.used_float = cb.used_integer = 0; + if (!return_by_ref && rvalue) + unmarshal(&cb, cif->rtype, 0, rvalue); +} + +void +ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue) +{ + ffi_call_int(cif, fn, rvalue, avalue, NULL); +} + +void +ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue, + void **avalue, void *closure) +{ + ffi_call_int(cif, fn, rvalue, avalue, closure); +} + +extern void ffi_closure_asm(void) FFI_HIDDEN; + +ffi_status ffi_prep_closure_loc(ffi_closure *closure, ffi_cif *cif, void (*fun)(ffi_cif*,void*,void**,void*), void *user_data, void *codeloc) +{ + uint32_t *tramp = (uint32_t *) &closure->tramp[0]; + uint64_t fn = (uint64_t) (uintptr_t) ffi_closure_asm; + + if (cif->abi <= FFI_FIRST_ABI || cif->abi >= FFI_LAST_ABI) + return FFI_BAD_ABI; + + /* we will call ffi_closure_inner with codeloc, not closure, but as long + as the memory is readable it should work */ + + tramp[0] = 0x00000317; /* auipc t1, 0 (i.e. t0 <- codeloc) */ +#if __SIZEOF_POINTER__ == 8 + tramp[1] = 0x01033383; /* ld t2, 16(t1) */ +#else + tramp[1] = 0x01032383; /* lw t2, 16(t1) */ +#endif + tramp[2] = 0x00038067; /* jr t2 */ + tramp[3] = 0x00000013; /* nop */ + tramp[4] = fn; + tramp[5] = fn >> 32; + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + __builtin___clear_cache(codeloc, codeloc + FFI_TRAMPOLINE_SIZE); + + return FFI_OK; +} + +extern void ffi_go_closure_asm (void) FFI_HIDDEN; + +ffi_status +ffi_prep_go_closure (ffi_go_closure *closure, ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *)) +{ + if (cif->abi <= FFI_FIRST_ABI || cif->abi >= FFI_LAST_ABI) + return FFI_BAD_ABI; + + closure->tramp = (void *) ffi_go_closure_asm; + closure->cif = cif; + closure->fun = fun; + + return FFI_OK; +} + +/* Called by the assembly code with aregs pointing to saved argument registers + and stack pointing to the stacked arguments. Return values passed in + registers will be reloaded from aregs. */ +void FFI_HIDDEN +ffi_closure_inner (ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + size_t *stack, call_context *aregs) +{ + void **avalue = alloca(cif->nargs * sizeof(void*)); + /* storage for arguments which will be copied by unmarshal(). We could + theoretically avoid the copies in many cases and use at most 128 bytes + of memory, but allocating disjoint storage for each argument is + simpler. */ + char *astorage = alloca(cif->nargs * MAXCOPYARG); + void *rvalue; + call_builder cb; + int return_by_ref; + int i; + + cb.aregs = aregs; + cb.used_integer = cb.used_float = 0; + cb.used_stack = stack; + + return_by_ref = passed_by_ref(&cb, cif->rtype, 0); + if (return_by_ref) + unmarshal(&cb, &ffi_type_pointer, 0, &rvalue); + else + rvalue = alloca(cif->rtype->size); + + for (i = 0; i < cif->nargs; i++) + avalue[i] = unmarshal(&cb, cif->arg_types[i], + i >= cif->riscv_nfixedargs, astorage + i*MAXCOPYARG); + + fun (cif, rvalue, avalue, user_data); + + if (!return_by_ref && cif->rtype->type != FFI_TYPE_VOID) { + cb.used_integer = cb.used_float = 0; + marshal(&cb, cif->rtype, 0, rvalue); + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/riscv/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/riscv/ffitarget.h new file mode 100644 index 0000000..75e6462 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/riscv/ffitarget.h @@ -0,0 +1,69 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - 2014 Michael Knyszek + + Target configuration macros for RISC-V. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef __riscv +#error "libffi was configured for a RISC-V target but this does not appear to be a RISC-V compiler." +#endif + +#ifndef LIBFFI_ASM + +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +/* FFI_UNUSED_NN and riscv_unused are to maintain ABI compatibility with a + distributed Berkeley patch from 2014, and can be removed at SONAME bump */ +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_UNUSED_1, + FFI_UNUSED_2, + FFI_UNUSED_3, + FFI_LAST_ABI, + + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; + +#endif /* LIBFFI_ASM */ + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_GO_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 24 +#define FFI_NATIVE_RAW_API 0 +#define FFI_EXTRA_CIF_FIELDS unsigned riscv_nfixedargs; unsigned riscv_unused; +#define FFI_TARGET_SPECIFIC_VARIADIC + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/riscv/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/riscv/sysv.S new file mode 100644 index 0000000..522d0b0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/riscv/sysv.S @@ -0,0 +1,293 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2015 Michael Knyszek + 2015 Andrew Waterman + 2018 Stef O'Rear + + RISC-V Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + +/* Define aliases so that we can handle all ABIs uniformly */ + +#if __SIZEOF_POINTER__ == 8 +#define PTRS 8 +#define LARG ld +#define SARG sd +#else +#define PTRS 4 +#define LARG lw +#define SARG sw +#endif + +#if __riscv_float_abi_double +#define FLTS 8 +#define FLARG fld +#define FSARG fsd +#elif __riscv_float_abi_single +#define FLTS 4 +#define FLARG flw +#define FSARG fsw +#else +#define FLTS 0 +#endif + +#define fp s0 + + .text + .globl ffi_call_asm + .type ffi_call_asm, @function + .hidden ffi_call_asm +/* + struct call_context { + floatreg fa[8]; + intreg a[8]; + intreg pad[rv32 ? 2 : 0]; + intreg save_fp, save_ra; + } + void ffi_call_asm (size_t *stackargs, struct call_context *regargs, + void (*fn) (void), void *closure); +*/ + +#define FRAME_LEN (8 * FLTS + 8 * PTRS + 16) + +ffi_call_asm: + .cfi_startproc + + /* + We are NOT going to set up an ordinary stack frame. In order to pass + the stacked args to the called function, we adjust our stack pointer to + a0, which is in the _caller's_ alloca area. We establish our own stack + frame at the end of the call_context. + + Anything below the arguments will be freed at this point, although we + preserve the call_context so that it can be read back in the caller. + */ + + .cfi_def_cfa 11, FRAME_LEN # interim CFA based on a1 + SARG fp, FRAME_LEN - 2*PTRS(a1) + .cfi_offset 8, -2*PTRS + SARG ra, FRAME_LEN - 1*PTRS(a1) + .cfi_offset 1, -1*PTRS + + addi fp, a1, FRAME_LEN + mv sp, a0 + .cfi_def_cfa 8, 0 # our frame is fully set up + + # Load arguments + mv t1, a2 + mv t2, a3 + +#if FLTS + FLARG fa0, -FRAME_LEN+0*FLTS(fp) + FLARG fa1, -FRAME_LEN+1*FLTS(fp) + FLARG fa2, -FRAME_LEN+2*FLTS(fp) + FLARG fa3, -FRAME_LEN+3*FLTS(fp) + FLARG fa4, -FRAME_LEN+4*FLTS(fp) + FLARG fa5, -FRAME_LEN+5*FLTS(fp) + FLARG fa6, -FRAME_LEN+6*FLTS(fp) + FLARG fa7, -FRAME_LEN+7*FLTS(fp) +#endif + + LARG a0, -FRAME_LEN+8*FLTS+0*PTRS(fp) + LARG a1, -FRAME_LEN+8*FLTS+1*PTRS(fp) + LARG a2, -FRAME_LEN+8*FLTS+2*PTRS(fp) + LARG a3, -FRAME_LEN+8*FLTS+3*PTRS(fp) + LARG a4, -FRAME_LEN+8*FLTS+4*PTRS(fp) + LARG a5, -FRAME_LEN+8*FLTS+5*PTRS(fp) + LARG a6, -FRAME_LEN+8*FLTS+6*PTRS(fp) + LARG a7, -FRAME_LEN+8*FLTS+7*PTRS(fp) + + /* Call */ + jalr t1 + + /* Save return values - only a0/a1 (fa0/fa1) are used */ +#if FLTS + FSARG fa0, -FRAME_LEN+0*FLTS(fp) + FSARG fa1, -FRAME_LEN+1*FLTS(fp) +#endif + + SARG a0, -FRAME_LEN+8*FLTS+0*PTRS(fp) + SARG a1, -FRAME_LEN+8*FLTS+1*PTRS(fp) + + /* Restore and return */ + addi sp, fp, -FRAME_LEN + .cfi_def_cfa 2, FRAME_LEN + LARG ra, -1*PTRS(fp) + .cfi_restore 1 + LARG fp, -2*PTRS(fp) + .cfi_restore 8 + ret + .cfi_endproc + .size ffi_call_asm, .-ffi_call_asm + + +/* + ffi_closure_asm. Expects address of the passed-in ffi_closure in t1. + void ffi_closure_inner (ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + size_t *stackargs, struct call_context *regargs) +*/ + + .globl ffi_closure_asm + .hidden ffi_closure_asm + .type ffi_closure_asm, @function +ffi_closure_asm: + .cfi_startproc + + addi sp, sp, -FRAME_LEN + .cfi_def_cfa_offset FRAME_LEN + + /* make a frame */ + SARG fp, FRAME_LEN - 2*PTRS(sp) + .cfi_offset 8, -2*PTRS + SARG ra, FRAME_LEN - 1*PTRS(sp) + .cfi_offset 1, -1*PTRS + addi fp, sp, FRAME_LEN + + /* save arguments */ +#if FLTS + FSARG fa0, 0*FLTS(sp) + FSARG fa1, 1*FLTS(sp) + FSARG fa2, 2*FLTS(sp) + FSARG fa3, 3*FLTS(sp) + FSARG fa4, 4*FLTS(sp) + FSARG fa5, 5*FLTS(sp) + FSARG fa6, 6*FLTS(sp) + FSARG fa7, 7*FLTS(sp) +#endif + + SARG a0, 8*FLTS+0*PTRS(sp) + SARG a1, 8*FLTS+1*PTRS(sp) + SARG a2, 8*FLTS+2*PTRS(sp) + SARG a3, 8*FLTS+3*PTRS(sp) + SARG a4, 8*FLTS+4*PTRS(sp) + SARG a5, 8*FLTS+5*PTRS(sp) + SARG a6, 8*FLTS+6*PTRS(sp) + SARG a7, 8*FLTS+7*PTRS(sp) + + /* enter C */ + LARG a0, FFI_TRAMPOLINE_SIZE+0*PTRS(t1) + LARG a1, FFI_TRAMPOLINE_SIZE+1*PTRS(t1) + LARG a2, FFI_TRAMPOLINE_SIZE+2*PTRS(t1) + addi a3, sp, FRAME_LEN + mv a4, sp + + call ffi_closure_inner + + /* return values */ +#if FLTS + FLARG fa0, 0*FLTS(sp) + FLARG fa1, 1*FLTS(sp) +#endif + + LARG a0, 8*FLTS+0*PTRS(sp) + LARG a1, 8*FLTS+1*PTRS(sp) + + /* restore and return */ + LARG ra, FRAME_LEN-1*PTRS(sp) + .cfi_restore 1 + LARG fp, FRAME_LEN-2*PTRS(sp) + .cfi_restore 8 + addi sp, sp, FRAME_LEN + .cfi_def_cfa_offset 0 + ret + .cfi_endproc + .size ffi_closure_asm, .-ffi_closure_asm + +/* + ffi_go_closure_asm. Expects address of the passed-in ffi_go_closure in t2. + void ffi_closure_inner (ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + size_t *stackargs, struct call_context *regargs) +*/ + + .globl ffi_go_closure_asm + .hidden ffi_go_closure_asm + .type ffi_go_closure_asm, @function +ffi_go_closure_asm: + .cfi_startproc + + addi sp, sp, -FRAME_LEN + .cfi_def_cfa_offset FRAME_LEN + + /* make a frame */ + SARG fp, FRAME_LEN - 2*PTRS(sp) + .cfi_offset 8, -2*PTRS + SARG ra, FRAME_LEN - 1*PTRS(sp) + .cfi_offset 1, -1*PTRS + addi fp, sp, FRAME_LEN + + /* save arguments */ +#if FLTS + FSARG fa0, 0*FLTS(sp) + FSARG fa1, 1*FLTS(sp) + FSARG fa2, 2*FLTS(sp) + FSARG fa3, 3*FLTS(sp) + FSARG fa4, 4*FLTS(sp) + FSARG fa5, 5*FLTS(sp) + FSARG fa6, 6*FLTS(sp) + FSARG fa7, 7*FLTS(sp) +#endif + + SARG a0, 8*FLTS+0*PTRS(sp) + SARG a1, 8*FLTS+1*PTRS(sp) + SARG a2, 8*FLTS+2*PTRS(sp) + SARG a3, 8*FLTS+3*PTRS(sp) + SARG a4, 8*FLTS+4*PTRS(sp) + SARG a5, 8*FLTS+5*PTRS(sp) + SARG a6, 8*FLTS+6*PTRS(sp) + SARG a7, 8*FLTS+7*PTRS(sp) + + /* enter C */ + LARG a0, 1*PTRS(t2) + LARG a1, 2*PTRS(t2) + mv a2, t2 + addi a3, sp, FRAME_LEN + mv a4, sp + + call ffi_closure_inner + + /* return values */ +#if FLTS + FLARG fa0, 0*FLTS(sp) + FLARG fa1, 1*FLTS(sp) +#endif + + LARG a0, 8*FLTS+0*PTRS(sp) + LARG a1, 8*FLTS+1*PTRS(sp) + + /* restore and return */ + LARG ra, FRAME_LEN-1*PTRS(sp) + .cfi_restore 1 + LARG fp, FRAME_LEN-2*PTRS(sp) + .cfi_restore 8 + addi sp, sp, FRAME_LEN + .cfi_def_cfa_offset 0 + ret + .cfi_endproc + .size ffi_go_closure_asm, .-ffi_go_closure_asm diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/ffi.c new file mode 100644 index 0000000..4035b6e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/ffi.c @@ -0,0 +1,756 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2000, 2007 Software AG + Copyright (c) 2008 Red Hat, Inc + + S390 Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ +/*====================================================================*/ +/* Includes */ +/* -------- */ +/*====================================================================*/ + +#include +#include +#include +#include "internal.h" + +/*====================== End of Includes =============================*/ + +/*====================================================================*/ +/* Defines */ +/* ------- */ +/*====================================================================*/ + +/* Maximum number of GPRs available for argument passing. */ +#define MAX_GPRARGS 5 + +/* Maximum number of FPRs available for argument passing. */ +#ifdef __s390x__ +#define MAX_FPRARGS 4 +#else +#define MAX_FPRARGS 2 +#endif + +/* Round to multiple of 16. */ +#define ROUND_SIZE(size) (((size) + 15) & ~15) + +/*===================== End of Defines ===============================*/ + +/*====================================================================*/ +/* Externals */ +/* --------- */ +/*====================================================================*/ + +struct call_frame +{ + void *back_chain; + void *eos; + unsigned long gpr_args[5]; + unsigned long gpr_save[9]; + unsigned long long fpr_args[4]; +}; + +extern void FFI_HIDDEN ffi_call_SYSV(struct call_frame *, unsigned, void *, + void (*fn)(void), void *); + +extern void ffi_closure_SYSV(void); +extern void ffi_go_closure_SYSV(void); + +/*====================== End of Externals ============================*/ + +/*====================================================================*/ +/* */ +/* Name - ffi_check_struct_type. */ +/* */ +/* Function - Determine if a structure can be passed within a */ +/* general purpose or floating point register. */ +/* */ +/*====================================================================*/ + +static int +ffi_check_struct_type (ffi_type *arg) +{ + size_t size = arg->size; + + /* If the struct has just one element, look at that element + to find out whether to consider the struct as floating point. */ + while (arg->type == FFI_TYPE_STRUCT + && arg->elements[0] && !arg->elements[1]) + arg = arg->elements[0]; + + /* Structs of size 1, 2, 4, and 8 are passed in registers, + just like the corresponding int/float types. */ + switch (size) + { + case 1: + return FFI_TYPE_UINT8; + + case 2: + return FFI_TYPE_UINT16; + + case 4: + if (arg->type == FFI_TYPE_FLOAT) + return FFI_TYPE_FLOAT; + else + return FFI_TYPE_UINT32; + + case 8: + if (arg->type == FFI_TYPE_DOUBLE) + return FFI_TYPE_DOUBLE; + else + return FFI_TYPE_UINT64; + + default: + break; + } + + /* Other structs are passed via a pointer to the data. */ + return FFI_TYPE_POINTER; +} + +/*======================== End of Routine ============================*/ + +/*====================================================================*/ +/* */ +/* Name - ffi_prep_cif_machdep. */ +/* */ +/* Function - Perform machine dependent CIF processing. */ +/* */ +/*====================================================================*/ + +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep(ffi_cif *cif) +{ + size_t struct_size = 0; + int n_gpr = 0; + int n_fpr = 0; + int n_ov = 0; + + ffi_type **ptr; + int i; + + /* Determine return value handling. */ + + switch (cif->rtype->type) + { + /* Void is easy. */ + case FFI_TYPE_VOID: + cif->flags = FFI390_RET_VOID; + break; + + /* Structures and complex are returned via a hidden pointer. */ + case FFI_TYPE_STRUCT: + case FFI_TYPE_COMPLEX: + cif->flags = FFI390_RET_STRUCT; + n_gpr++; /* We need one GPR to pass the pointer. */ + break; + + /* Floating point values are returned in fpr 0. */ + case FFI_TYPE_FLOAT: + cif->flags = FFI390_RET_FLOAT; + break; + + case FFI_TYPE_DOUBLE: + cif->flags = FFI390_RET_DOUBLE; + break; + +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + cif->flags = FFI390_RET_STRUCT; + n_gpr++; + break; +#endif + /* Integer values are returned in gpr 2 (and gpr 3 + for 64-bit values on 31-bit machines). */ + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + cif->flags = FFI390_RET_INT64; + break; + + case FFI_TYPE_POINTER: + case FFI_TYPE_INT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + /* These are to be extended to word size. */ +#ifdef __s390x__ + cif->flags = FFI390_RET_INT64; +#else + cif->flags = FFI390_RET_INT32; +#endif + break; + + default: + FFI_ASSERT (0); + break; + } + + /* Now for the arguments. */ + + for (ptr = cif->arg_types, i = cif->nargs; + i > 0; + i--, ptr++) + { + int type = (*ptr)->type; + +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + /* 16-byte long double is passed like a struct. */ + if (type == FFI_TYPE_LONGDOUBLE) + type = FFI_TYPE_STRUCT; +#endif + + /* Check how a structure type is passed. */ + if (type == FFI_TYPE_STRUCT || type == FFI_TYPE_COMPLEX) + { + if (type == FFI_TYPE_COMPLEX) + type = FFI_TYPE_POINTER; + else + type = ffi_check_struct_type (*ptr); + + /* If we pass the struct via pointer, we must reserve space + to copy its data for proper call-by-value semantics. */ + if (type == FFI_TYPE_POINTER) + struct_size += ROUND_SIZE ((*ptr)->size); + } + + /* Now handle all primitive int/float data types. */ + switch (type) + { + /* The first MAX_FPRARGS floating point arguments + go in FPRs, the rest overflow to the stack. */ + + case FFI_TYPE_DOUBLE: + if (n_fpr < MAX_FPRARGS) + n_fpr++; + else + n_ov += sizeof (double) / sizeof (long); + break; + + case FFI_TYPE_FLOAT: + if (n_fpr < MAX_FPRARGS) + n_fpr++; + else + n_ov++; + break; + + /* On 31-bit machines, 64-bit integers are passed in GPR pairs, + if one is still available, or else on the stack. If only one + register is free, skip the register (it won't be used for any + subsequent argument either). */ + +#ifndef __s390x__ + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + if (n_gpr == MAX_GPRARGS-1) + n_gpr = MAX_GPRARGS; + if (n_gpr < MAX_GPRARGS) + n_gpr += 2; + else + n_ov += 2; + break; +#endif + + /* Everything else is passed in GPRs (until MAX_GPRARGS + have been used) or overflows to the stack. */ + + default: + if (n_gpr < MAX_GPRARGS) + n_gpr++; + else + n_ov++; + break; + } + } + + /* Total stack space as required for overflow arguments + and temporary structure copies. */ + + cif->bytes = ROUND_SIZE (n_ov * sizeof (long)) + struct_size; + + return FFI_OK; +} + +/*======================== End of Routine ============================*/ + +/*====================================================================*/ +/* */ +/* Name - ffi_call. */ +/* */ +/* Function - Call the FFI routine. */ +/* */ +/*====================================================================*/ + +static void +ffi_call_int(ffi_cif *cif, + void (*fn)(void), + void *rvalue, + void **avalue, + void *closure) +{ + int ret_type = cif->flags; + size_t rsize = 0, bytes = cif->bytes; + unsigned char *stack, *p_struct; + struct call_frame *frame; + unsigned long *p_ov, *p_gpr; + unsigned long long *p_fpr; + int n_fpr, n_gpr, n_ov, i, n; + ffi_type **arg_types; + + FFI_ASSERT (cif->abi == FFI_SYSV); + + /* If we don't have a return value, we need to fake one. */ + if (rvalue == NULL) + { + if (ret_type & FFI390_RET_IN_MEM) + rsize = cif->rtype->size; + else + ret_type = FFI390_RET_VOID; + } + + /* The stack space will be filled with those areas: + + dummy structure return (highest addresses) + FPR argument register save area + GPR argument register save area + stack frame for ffi_call_SYSV + temporary struct copies + overflow argument area (lowest addresses) + + We set up the following pointers: + + p_fpr: bottom of the FPR area (growing upwards) + p_gpr: bottom of the GPR area (growing upwards) + p_ov: bottom of the overflow area (growing upwards) + p_struct: top of the struct copy area (growing downwards) + + All areas are kept aligned to twice the word size. + + Note that we're going to create the stack frame for both + ffi_call_SYSV _and_ the target function right here. This + works because we don't make any function calls with more + than 5 arguments (indeed only memcpy and ffi_call_SYSV), + and thus we don't have any stacked outgoing parameters. */ + + stack = alloca (bytes + sizeof(struct call_frame) + rsize); + frame = (struct call_frame *)(stack + bytes); + if (rsize) + rvalue = frame + 1; + + /* Link the new frame back to the one from this function. */ + frame->back_chain = __builtin_frame_address (0); + + /* Fill in all of the argument stuff. */ + p_ov = (unsigned long *)stack; + p_struct = (unsigned char *)frame; + p_gpr = frame->gpr_args; + p_fpr = frame->fpr_args; + n_fpr = n_gpr = n_ov = 0; + + /* If we returning a structure then we set the first parameter register + to the address of where we are returning this structure. */ + if (cif->flags & FFI390_RET_IN_MEM) + p_gpr[n_gpr++] = (uintptr_t) rvalue; + + /* Now for the arguments. */ + arg_types = cif->arg_types; + for (i = 0, n = cif->nargs; i < n; ++i) + { + ffi_type *ty = arg_types[i]; + void *arg = avalue[i]; + int type = ty->type; + ffi_arg val; + + restart: + switch (type) + { + case FFI_TYPE_SINT8: + val = *(SINT8 *)arg; + goto do_int; + case FFI_TYPE_UINT8: + val = *(UINT8 *)arg; + goto do_int; + case FFI_TYPE_SINT16: + val = *(SINT16 *)arg; + goto do_int; + case FFI_TYPE_UINT16: + val = *(UINT16 *)arg; + goto do_int; + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + val = *(SINT32 *)arg; + goto do_int; + case FFI_TYPE_UINT32: + val = *(UINT32 *)arg; + goto do_int; + case FFI_TYPE_POINTER: + val = *(uintptr_t *)arg; + do_int: + *(n_gpr < MAX_GPRARGS ? p_gpr + n_gpr++ : p_ov + n_ov++) = val; + break; + + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: +#ifdef __s390x__ + val = *(UINT64 *)arg; + goto do_int; +#else + if (n_gpr == MAX_GPRARGS-1) + n_gpr = MAX_GPRARGS; + if (n_gpr < MAX_GPRARGS) + p_gpr[n_gpr++] = ((UINT32 *) arg)[0], + p_gpr[n_gpr++] = ((UINT32 *) arg)[1]; + else + p_ov[n_ov++] = ((UINT32 *) arg)[0], + p_ov[n_ov++] = ((UINT32 *) arg)[1]; +#endif + break; + + case FFI_TYPE_DOUBLE: + if (n_fpr < MAX_FPRARGS) + p_fpr[n_fpr++] = *(UINT64 *) arg; + else + { +#ifdef __s390x__ + p_ov[n_ov++] = *(UINT64 *) arg; +#else + p_ov[n_ov++] = ((UINT32 *) arg)[0], + p_ov[n_ov++] = ((UINT32 *) arg)[1]; +#endif + } + break; + + case FFI_TYPE_FLOAT: + val = *(UINT32 *)arg; + if (n_fpr < MAX_FPRARGS) + p_fpr[n_fpr++] = (UINT64)val << 32; + else + p_ov[n_ov++] = val; + break; + + case FFI_TYPE_STRUCT: + /* Check how a structure type is passed. */ + type = ffi_check_struct_type (ty); + /* Some structures are passed via a type they contain. */ + if (type != FFI_TYPE_POINTER) + goto restart; + /* ... otherwise, passed by reference. fallthru. */ + +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + /* 16-byte long double is passed via reference. */ +#endif + case FFI_TYPE_COMPLEX: + /* Complex types are passed via reference. */ + p_struct -= ROUND_SIZE (ty->size); + memcpy (p_struct, arg, ty->size); + val = (uintptr_t)p_struct; + goto do_int; + + default: + FFI_ASSERT (0); + break; + } + } + + ffi_call_SYSV (frame, ret_type & FFI360_RET_MASK, rvalue, fn, closure); +} + +void +ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + ffi_call_int(cif, fn, rvalue, avalue, NULL); +} + +void +ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + ffi_call_int(cif, fn, rvalue, avalue, closure); +} + +/*======================== End of Routine ============================*/ + +/*====================================================================*/ +/* */ +/* Name - ffi_closure_helper_SYSV. */ +/* */ +/* Function - Call a FFI closure target function. */ +/* */ +/*====================================================================*/ + +void FFI_HIDDEN +ffi_closure_helper_SYSV (ffi_cif *cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + unsigned long *p_gpr, + unsigned long long *p_fpr, + unsigned long *p_ov) +{ + unsigned long long ret_buffer; + + void *rvalue = &ret_buffer; + void **avalue; + void **p_arg; + + int n_gpr = 0; + int n_fpr = 0; + int n_ov = 0; + + ffi_type **ptr; + int i; + + /* Allocate buffer for argument list pointers. */ + p_arg = avalue = alloca (cif->nargs * sizeof (void *)); + + /* If we returning a structure, pass the structure address + directly to the target function. Otherwise, have the target + function store the return value to the GPR save area. */ + if (cif->flags & FFI390_RET_IN_MEM) + rvalue = (void *) p_gpr[n_gpr++]; + + /* Now for the arguments. */ + for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, p_arg++, ptr++) + { + int deref_struct_pointer = 0; + int type = (*ptr)->type; + +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + /* 16-byte long double is passed like a struct. */ + if (type == FFI_TYPE_LONGDOUBLE) + type = FFI_TYPE_STRUCT; +#endif + + /* Check how a structure type is passed. */ + if (type == FFI_TYPE_STRUCT || type == FFI_TYPE_COMPLEX) + { + if (type == FFI_TYPE_COMPLEX) + type = FFI_TYPE_POINTER; + else + type = ffi_check_struct_type (*ptr); + + /* If we pass the struct via pointer, remember to + retrieve the pointer later. */ + if (type == FFI_TYPE_POINTER) + deref_struct_pointer = 1; + } + + /* Pointers are passed like UINTs of the same size. */ + if (type == FFI_TYPE_POINTER) + { +#ifdef __s390x__ + type = FFI_TYPE_UINT64; +#else + type = FFI_TYPE_UINT32; +#endif + } + + /* Now handle all primitive int/float data types. */ + switch (type) + { + case FFI_TYPE_DOUBLE: + if (n_fpr < MAX_FPRARGS) + *p_arg = &p_fpr[n_fpr++]; + else + *p_arg = &p_ov[n_ov], + n_ov += sizeof (double) / sizeof (long); + break; + + case FFI_TYPE_FLOAT: + if (n_fpr < MAX_FPRARGS) + *p_arg = &p_fpr[n_fpr++]; + else + *p_arg = (char *)&p_ov[n_ov++] + sizeof (long) - 4; + break; + + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: +#ifdef __s390x__ + if (n_gpr < MAX_GPRARGS) + *p_arg = &p_gpr[n_gpr++]; + else + *p_arg = &p_ov[n_ov++]; +#else + if (n_gpr == MAX_GPRARGS-1) + n_gpr = MAX_GPRARGS; + if (n_gpr < MAX_GPRARGS) + *p_arg = &p_gpr[n_gpr], n_gpr += 2; + else + *p_arg = &p_ov[n_ov], n_ov += 2; +#endif + break; + + case FFI_TYPE_INT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + if (n_gpr < MAX_GPRARGS) + *p_arg = (char *)&p_gpr[n_gpr++] + sizeof (long) - 4; + else + *p_arg = (char *)&p_ov[n_ov++] + sizeof (long) - 4; + break; + + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + if (n_gpr < MAX_GPRARGS) + *p_arg = (char *)&p_gpr[n_gpr++] + sizeof (long) - 2; + else + *p_arg = (char *)&p_ov[n_ov++] + sizeof (long) - 2; + break; + + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + if (n_gpr < MAX_GPRARGS) + *p_arg = (char *)&p_gpr[n_gpr++] + sizeof (long) - 1; + else + *p_arg = (char *)&p_ov[n_ov++] + sizeof (long) - 1; + break; + + default: + FFI_ASSERT (0); + break; + } + + /* If this is a struct passed via pointer, we need to + actually retrieve that pointer. */ + if (deref_struct_pointer) + *p_arg = *(void **)*p_arg; + } + + + /* Call the target function. */ + (fun) (cif, rvalue, avalue, user_data); + + /* Convert the return value. */ + switch (cif->rtype->type) + { + /* Void is easy, and so is struct. */ + case FFI_TYPE_VOID: + case FFI_TYPE_STRUCT: + case FFI_TYPE_COMPLEX: +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: +#endif + break; + + /* Floating point values are returned in fpr 0. */ + case FFI_TYPE_FLOAT: + p_fpr[0] = (long long) *(unsigned int *) rvalue << 32; + break; + + case FFI_TYPE_DOUBLE: + p_fpr[0] = *(unsigned long long *) rvalue; + break; + + /* Integer values are returned in gpr 2 (and gpr 3 + for 64-bit values on 31-bit machines). */ + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: +#ifdef __s390x__ + p_gpr[0] = *(unsigned long *) rvalue; +#else + p_gpr[0] = ((unsigned long *) rvalue)[0], + p_gpr[1] = ((unsigned long *) rvalue)[1]; +#endif + break; + + case FFI_TYPE_POINTER: + case FFI_TYPE_UINT32: + case FFI_TYPE_UINT16: + case FFI_TYPE_UINT8: + p_gpr[0] = *(unsigned long *) rvalue; + break; + + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + case FFI_TYPE_SINT16: + case FFI_TYPE_SINT8: + p_gpr[0] = *(signed long *) rvalue; + break; + + default: + FFI_ASSERT (0); + break; + } +} + +/*======================== End of Routine ============================*/ + +/*====================================================================*/ +/* */ +/* Name - ffi_prep_closure_loc. */ +/* */ +/* Function - Prepare a FFI closure. */ +/* */ +/*====================================================================*/ + +ffi_status +ffi_prep_closure_loc (ffi_closure *closure, + ffi_cif *cif, + void (*fun) (ffi_cif *, void *, void **, void *), + void *user_data, + void *codeloc) +{ + static unsigned short const template[] = { + 0x0d10, /* basr %r1,0 */ +#ifndef __s390x__ + 0x9801, 0x1006, /* lm %r0,%r1,6(%r1) */ +#else + 0xeb01, 0x100e, 0x0004, /* lmg %r0,%r1,14(%r1) */ +#endif + 0x07f1 /* br %r1 */ + }; + + unsigned long *tramp = (unsigned long *)&closure->tramp; + + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + memcpy (tramp, template, sizeof(template)); + tramp[2] = (unsigned long)codeloc; + tramp[3] = (unsigned long)&ffi_closure_SYSV; + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + return FFI_OK; +} + +/*======================== End of Routine ============================*/ + +/* Build a Go language closure. */ + +ffi_status +ffi_prep_go_closure (ffi_go_closure *closure, ffi_cif *cif, + void (*fun)(ffi_cif*,void*,void**,void*)) +{ + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + closure->tramp = ffi_go_closure_SYSV; + closure->cif = cif; + closure->fun = fun; + + return FFI_OK; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/ffitarget.h new file mode 100644 index 0000000..d8a4ee4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/ffitarget.h @@ -0,0 +1,70 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 1996-2003 Red Hat, Inc. + Target configuration macros for S390. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#if defined (__s390x__) +#ifndef S390X +#define S390X +#endif +#endif + +/* ---- System specific configurations ----------------------------------- */ + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; +#endif + +#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION +#define FFI_TARGET_HAS_COMPLEX_TYPE + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_GO_CLOSURES 1 +#ifdef S390X +#define FFI_TRAMPOLINE_SIZE 32 +#else +#define FFI_TRAMPOLINE_SIZE 16 +#endif +#define FFI_NATIVE_RAW_API 0 + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/internal.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/internal.h new file mode 100644 index 0000000..b875578 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/internal.h @@ -0,0 +1,11 @@ +/* If these values change, sysv.S must be adapted! */ +#define FFI390_RET_DOUBLE 0 +#define FFI390_RET_FLOAT 1 +#define FFI390_RET_INT64 2 +#define FFI390_RET_INT32 3 +#define FFI390_RET_VOID 4 + +#define FFI360_RET_MASK 7 +#define FFI390_RET_IN_MEM 8 + +#define FFI390_RET_STRUCT (FFI390_RET_VOID | FFI390_RET_IN_MEM) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/sysv.S new file mode 100644 index 0000000..c4b5006 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/s390/sysv.S @@ -0,0 +1,325 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2000 Software AG + Copyright (c) 2008 Red Hat, Inc. + + S390 Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + + .text + +#ifndef __s390x__ + + # r2: frame + # r3: ret_type + # r4: ret_addr + # r5: fun + # r6: closure + + # This assumes we are using gas. + .balign 8 + .globl ffi_call_SYSV + FFI_HIDDEN(ffi_call_SYSV) + .type ffi_call_SYSV,%function +ffi_call_SYSV: + .cfi_startproc + st %r6,44(%r2) # Save registers + stm %r12,%r14,48(%r2) + lr %r13,%r2 # Install frame pointer + .cfi_rel_offset r6, 44 + .cfi_rel_offset r12, 48 + .cfi_rel_offset r13, 52 + .cfi_rel_offset r14, 56 + .cfi_def_cfa_register r13 + st %r2,0(%r15) # Set up back chain + sla %r3,3 # ret_type *= 8 + lr %r12,%r4 # Save ret_addr + lr %r1,%r5 # Save fun + lr %r0,%r6 # Install static chain + + # Set return address, so that there is only one indirect jump. +#ifdef HAVE_AS_S390_ZARCH + larl %r14,.Ltable + ar %r14,%r3 +#else + basr %r14,0 +0: la %r14,.Ltable-0b(%r14,%r3) +#endif + + lm %r2,%r6,8(%r13) # Load arguments + ld %f0,64(%r13) + ld %f2,72(%r13) + br %r1 # ... and call function + + .balign 8 +.Ltable: +# FFI390_RET_DOUBLE + std %f0,0(%r12) + j .Ldone + + .balign 8 +# FFI390_RET_FLOAT + ste %f0,0(%r12) + j .Ldone + + .balign 8 +# FFI390_RET_INT64 + st %r3,4(%r12) + nop + # fallthru + + .balign 8 +# FFI390_RET_INT32 + st %r2,0(%r12) + nop + # fallthru + + .balign 8 +# FFI390_RET_VOID +.Ldone: + l %r14,56(%r13) + l %r12,48(%r13) + l %r6,44(%r13) + l %r13,52(%r13) + .cfi_restore 14 + .cfi_restore 13 + .cfi_restore 12 + .cfi_restore 6 + .cfi_def_cfa r15, 96 + br %r14 + .cfi_endproc + .size ffi_call_SYSV,.-ffi_call_SYSV + + + .balign 8 + .globl ffi_go_closure_SYSV + FFI_HIDDEN(ffi_go_closure_SYSV) + .type ffi_go_closure_SYSV,%function +ffi_go_closure_SYSV: + .cfi_startproc + stm %r2,%r6,8(%r15) # Save arguments + lr %r4,%r0 # Load closure -> user_data + l %r2,4(%r4) # ->cif + l %r3,8(%r4) # ->fun + j .Ldoclosure + .cfi_endproc + + .balign 8 + .globl ffi_closure_SYSV + FFI_HIDDEN(ffi_closure_SYSV) + .type ffi_closure_SYSV,%function +ffi_closure_SYSV: + .cfi_startproc + stm %r2,%r6,8(%r15) # Save arguments + lr %r4,%r0 # Closure + l %r2,16(%r4) # ->cif + l %r3,20(%r4) # ->fun + l %r4,24(%r4) # ->user_data +.Ldoclosure: + stm %r12,%r15,48(%r15) # Save registers + lr %r12,%r15 + .cfi_def_cfa_register r12 + .cfi_rel_offset r6, 24 + .cfi_rel_offset r12, 48 + .cfi_rel_offset r13, 52 + .cfi_rel_offset r14, 56 + .cfi_rel_offset r15, 60 +#ifndef HAVE_AS_S390_ZARCH + basr %r13,0 # Set up base register +.Lcbase: + l %r1,.Lchelper-.Lcbase(%r13) # Get helper function +#endif + ahi %r15,-96-8 # Set up stack frame + st %r12,0(%r15) # Set up back chain + + std %f0,64(%r12) # Save fp arguments + std %f2,72(%r12) + + la %r5,96(%r12) # Overflow + st %r5,96(%r15) + la %r6,64(%r12) # FPRs + la %r5,8(%r12) # GPRs +#ifdef HAVE_AS_S390_ZARCH + brasl %r14,ffi_closure_helper_SYSV +#else + bas %r14,0(%r1,%r13) # Call helper +#endif + + lr %r15,%r12 + .cfi_def_cfa_register r15 + lm %r12,%r14,48(%r12) # Restore saved registers + l %r6,24(%r15) + ld %f0,64(%r15) # Load return registers + lm %r2,%r3,8(%r15) + br %r14 + .cfi_endproc + +#ifndef HAVE_AS_S390_ZARCH + .align 4 +.Lchelper: + .long ffi_closure_helper_SYSV-.Lcbase +#endif + + .size ffi_closure_SYSV,.-ffi_closure_SYSV + +#else + + # r2: frame + # r3: ret_type + # r4: ret_addr + # r5: fun + # r6: closure + + # This assumes we are using gas. + .balign 8 + .globl ffi_call_SYSV + FFI_HIDDEN(ffi_call_SYSV) + .type ffi_call_SYSV,%function +ffi_call_SYSV: + .cfi_startproc + stg %r6,88(%r2) # Save registers + stmg %r12,%r14,96(%r2) + lgr %r13,%r2 # Install frame pointer + .cfi_rel_offset r6, 88 + .cfi_rel_offset r12, 96 + .cfi_rel_offset r13, 104 + .cfi_rel_offset r14, 112 + .cfi_def_cfa_register r13 + stg %r2,0(%r15) # Set up back chain + larl %r14,.Ltable # Set up return address + slag %r3,%r3,3 # ret_type *= 8 + lgr %r12,%r4 # Save ret_addr + lgr %r1,%r5 # Save fun + lgr %r0,%r6 # Install static chain + agr %r14,%r3 + lmg %r2,%r6,16(%r13) # Load arguments + ld %f0,128(%r13) + ld %f2,136(%r13) + ld %f4,144(%r13) + ld %f6,152(%r13) + br %r1 # ... and call function + + .balign 8 +.Ltable: +# FFI390_RET_DOUBLE + std %f0,0(%r12) + j .Ldone + + .balign 8 +# FFI390_RET_DOUBLE + ste %f0,0(%r12) + j .Ldone + + .balign 8 +# FFI390_RET_INT64 + stg %r2,0(%r12) + + .balign 8 +# FFI390_RET_INT32 + # Never used, as we always store type ffi_arg. + # But the stg above is 6 bytes and we cannot + # jump around this case, so fall through. + nop + nop + + .balign 8 +# FFI390_RET_VOID +.Ldone: + lg %r14,112(%r13) + lg %r12,96(%r13) + lg %r6,88(%r13) + lg %r13,104(%r13) + .cfi_restore r14 + .cfi_restore r13 + .cfi_restore r12 + .cfi_restore r6 + .cfi_def_cfa r15, 160 + br %r14 + .cfi_endproc + .size ffi_call_SYSV,.-ffi_call_SYSV + + + .balign 8 + .globl ffi_go_closure_SYSV + FFI_HIDDEN(ffi_go_closure_SYSV) + .type ffi_go_closure_SYSV,%function +ffi_go_closure_SYSV: + .cfi_startproc + stmg %r2,%r6,16(%r15) # Save arguments + lgr %r4,%r0 # Load closure -> user_data + lg %r2,8(%r4) # ->cif + lg %r3,16(%r4) # ->fun + j .Ldoclosure + .cfi_endproc + .size ffi_go_closure_SYSV,.-ffi_go_closure_SYSV + + + .balign 8 + .globl ffi_closure_SYSV + FFI_HIDDEN(ffi_closure_SYSV) + .type ffi_closure_SYSV,%function +ffi_closure_SYSV: + .cfi_startproc + stmg %r2,%r6,16(%r15) # Save arguments + lgr %r4,%r0 # Load closure + lg %r2,32(%r4) # ->cif + lg %r3,40(%r4) # ->fun + lg %r4,48(%r4) # ->user_data +.Ldoclosure: + stmg %r13,%r15,104(%r15) # Save registers + lgr %r13,%r15 + .cfi_def_cfa_register r13 + .cfi_rel_offset r6, 48 + .cfi_rel_offset r13, 104 + .cfi_rel_offset r14, 112 + .cfi_rel_offset r15, 120 + aghi %r15,-160-16 # Set up stack frame + stg %r13,0(%r15) # Set up back chain + + std %f0,128(%r13) # Save fp arguments + std %f2,136(%r13) + std %f4,144(%r13) + std %f6,152(%r13) + la %r5,160(%r13) # Overflow + stg %r5,160(%r15) + la %r6,128(%r13) # FPRs + la %r5,16(%r13) # GPRs + brasl %r14,ffi_closure_helper_SYSV # Call helper + + lgr %r15,%r13 + .cfi_def_cfa_register r15 + lmg %r13,%r14,104(%r13) # Restore saved registers + lg %r6,48(%r15) + ld %f0,128(%r15) # Load return registers + lg %r2,16(%r15) + br %r14 + .cfi_endproc + .size ffi_closure_SYSV,.-ffi_closure_SYSV +#endif /* !s390x */ + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh/ffi.c new file mode 100644 index 0000000..9ec86bf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh/ffi.c @@ -0,0 +1,717 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2002-2008, 2012 Kaz Kojima + Copyright (c) 2008 Red Hat, Inc. + + SuperH Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include + +#define NGREGARG 4 +#if defined(__SH4__) +#define NFREGARG 8 +#endif + +#if defined(__HITACHI__) +#define STRUCT_VALUE_ADDRESS_WITH_ARG 1 +#else +#define STRUCT_VALUE_ADDRESS_WITH_ARG 0 +#endif + +/* If the structure has essentially an unique element, return its type. */ +static int +simple_type (ffi_type *arg) +{ + if (arg->type != FFI_TYPE_STRUCT) + return arg->type; + else if (arg->elements[1]) + return FFI_TYPE_STRUCT; + + return simple_type (arg->elements[0]); +} + +static int +return_type (ffi_type *arg) +{ + unsigned short type; + + if (arg->type != FFI_TYPE_STRUCT) + return arg->type; + + type = simple_type (arg->elements[0]); + if (! arg->elements[1]) + { + switch (type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + return FFI_TYPE_INT; + + default: + return type; + } + } + + /* gcc uses r0/r1 pair for some kind of structures. */ + if (arg->size <= 2 * sizeof (int)) + { + int i = 0; + ffi_type *e; + + while ((e = arg->elements[i++])) + { + type = simple_type (e); + switch (type) + { + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_INT: + case FFI_TYPE_FLOAT: + return FFI_TYPE_UINT64; + + default: + break; + } + } + } + + return FFI_TYPE_STRUCT; +} + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments */ + +void ffi_prep_args(char *stack, extended_cif *ecif) +{ + register unsigned int i; + register int tmp; + register unsigned int avn; + register void **p_argv; + register char *argp; + register ffi_type **p_arg; + int greg, ireg; +#if defined(__SH4__) + int freg = 0; +#endif + + tmp = 0; + argp = stack; + + if (return_type (ecif->cif->rtype) == FFI_TYPE_STRUCT) + { + *(void **) argp = ecif->rvalue; + argp += 4; + ireg = STRUCT_VALUE_ADDRESS_WITH_ARG ? 1 : 0; + } + else + ireg = 0; + + /* Set arguments for registers. */ + greg = ireg; + avn = ecif->cif->nargs; + p_argv = ecif->avalue; + + for (i = 0, p_arg = ecif->cif->arg_types; i < avn; i++, p_arg++, p_argv++) + { + size_t z; + + z = (*p_arg)->size; + if (z < sizeof(int)) + { + if (greg++ >= NGREGARG) + continue; + + z = sizeof(int); + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); + break; + + case FFI_TYPE_STRUCT: + *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); + break; + + default: + FFI_ASSERT(0); + } + argp += z; + } + else if (z == sizeof(int)) + { +#if defined(__SH4__) + if ((*p_arg)->type == FFI_TYPE_FLOAT) + { + if (freg++ >= NFREGARG) + continue; + } + else +#endif + { + if (greg++ >= NGREGARG) + continue; + } + *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); + argp += z; + } +#if defined(__SH4__) + else if ((*p_arg)->type == FFI_TYPE_DOUBLE) + { + if (freg + 1 >= NFREGARG) + continue; + freg = (freg + 1) & ~1; + freg += 2; + memcpy (argp, *p_argv, z); + argp += z; + } +#endif + else + { + int n = (z + sizeof (int) - 1) / sizeof (int); +#if defined(__SH4__) + if (greg + n - 1 >= NGREGARG) + continue; +#else + if (greg >= NGREGARG) + continue; +#endif + greg += n; + memcpy (argp, *p_argv, z); + argp += n * sizeof (int); + } + } + + /* Set arguments on stack. */ + greg = ireg; +#if defined(__SH4__) + freg = 0; +#endif + p_argv = ecif->avalue; + + for (i = 0, p_arg = ecif->cif->arg_types; i < avn; i++, p_arg++, p_argv++) + { + size_t z; + + z = (*p_arg)->size; + if (z < sizeof(int)) + { + if (greg++ < NGREGARG) + continue; + + z = sizeof(int); + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); + break; + + case FFI_TYPE_STRUCT: + *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); + break; + + default: + FFI_ASSERT(0); + } + argp += z; + } + else if (z == sizeof(int)) + { +#if defined(__SH4__) + if ((*p_arg)->type == FFI_TYPE_FLOAT) + { + if (freg++ < NFREGARG) + continue; + } + else +#endif + { + if (greg++ < NGREGARG) + continue; + } + *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); + argp += z; + } +#if defined(__SH4__) + else if ((*p_arg)->type == FFI_TYPE_DOUBLE) + { + if (freg + 1 < NFREGARG) + { + freg = (freg + 1) & ~1; + freg += 2; + continue; + } + memcpy (argp, *p_argv, z); + argp += z; + } +#endif + else + { + int n = (z + sizeof (int) - 1) / sizeof (int); + if (greg + n - 1 < NGREGARG) + { + greg += n; + continue; + } +#if (! defined(__SH4__)) + else if (greg < NGREGARG) + { + greg = NGREGARG; + continue; + } +#endif + memcpy (argp, *p_argv, z); + argp += n * sizeof (int); + } + } + + return; +} + +/* Perform machine dependent cif processing */ +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + int i, j; + int size, type; + int n, m; + int greg; +#if defined(__SH4__) + int freg = 0; +#endif + + cif->flags = 0; + + greg = ((return_type (cif->rtype) == FFI_TYPE_STRUCT) && + STRUCT_VALUE_ADDRESS_WITH_ARG) ? 1 : 0; + +#if defined(__SH4__) + for (i = j = 0; i < cif->nargs && j < 12; i++) + { + type = (cif->arg_types)[i]->type; + switch (type) + { + case FFI_TYPE_FLOAT: + if (freg >= NFREGARG) + continue; + freg++; + cif->flags += ((cif->arg_types)[i]->type) << (2 * j); + j++; + break; + + case FFI_TYPE_DOUBLE: + if ((freg + 1) >= NFREGARG) + continue; + freg = (freg + 1) & ~1; + freg += 2; + cif->flags += ((cif->arg_types)[i]->type) << (2 * j); + j++; + break; + + default: + size = (cif->arg_types)[i]->size; + n = (size + sizeof (int) - 1) / sizeof (int); + if (greg + n - 1 >= NGREGARG) + continue; + greg += n; + for (m = 0; m < n; m++) + cif->flags += FFI_TYPE_INT << (2 * j++); + break; + } + } +#else + for (i = j = 0; i < cif->nargs && j < 4; i++) + { + size = (cif->arg_types)[i]->size; + n = (size + sizeof (int) - 1) / sizeof (int); + if (greg >= NGREGARG) + continue; + else if (greg + n - 1 >= NGREGARG) + n = NGREGARG - greg; + greg += n; + for (m = 0; m < n; m++) + cif->flags += FFI_TYPE_INT << (2 * j++); + } +#endif + + /* Set the return type flag */ + switch (cif->rtype->type) + { + case FFI_TYPE_STRUCT: + cif->flags += (unsigned) (return_type (cif->rtype)) << 24; + break; + + case FFI_TYPE_VOID: + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + cif->flags += (unsigned) cif->rtype->type << 24; + break; + + default: + cif->flags += FFI_TYPE_INT << 24; + break; + } + + return FFI_OK; +} + +extern void ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *, + unsigned, unsigned, unsigned *, void (*fn)(void)); + +void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + extended_cif ecif; + UINT64 trvalue; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return */ + /* value address then we need to make one */ + + if (cif->rtype->type == FFI_TYPE_STRUCT + && return_type (cif->rtype) != FFI_TYPE_STRUCT) + ecif.rvalue = &trvalue; + else if ((rvalue == NULL) && + (cif->rtype->type == FFI_TYPE_STRUCT)) + { + ecif.rvalue = alloca(cif->rtype->size); + } + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_SYSV: + ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, cif->flags, ecif.rvalue, + fn); + break; + default: + FFI_ASSERT(0); + break; + } + + if (rvalue + && cif->rtype->type == FFI_TYPE_STRUCT + && return_type (cif->rtype) != FFI_TYPE_STRUCT) + memcpy (rvalue, &trvalue, cif->rtype->size); +} + +extern void ffi_closure_SYSV (void); +#if defined(__SH4__) +extern void __ic_invalidate (void *line); +#endif + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + unsigned int *tramp; + unsigned int insn; + + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + tramp = (unsigned int *) &closure->tramp[0]; + /* Set T bit if the function returns a struct pointed with R2. */ + insn = (return_type (cif->rtype) == FFI_TYPE_STRUCT + ? 0x0018 /* sett */ + : 0x0008 /* clrt */); + +#ifdef __LITTLE_ENDIAN__ + tramp[0] = 0xd301d102; + tramp[1] = 0x0000412b | (insn << 16); +#else + tramp[0] = 0xd102d301; + tramp[1] = 0x412b0000 | insn; +#endif + *(void **) &tramp[2] = (void *)codeloc; /* ctx */ + *(void **) &tramp[3] = (void *)ffi_closure_SYSV; /* funaddr */ + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + +#if defined(__SH4__) + /* Flush the icache. */ + __ic_invalidate(codeloc); +#endif + + return FFI_OK; +} + +/* Basically the trampoline invokes ffi_closure_SYSV, and on + * entry, r3 holds the address of the closure. + * After storing the registers that could possibly contain + * parameters to be passed into the stack frame and setting + * up space for a return value, ffi_closure_SYSV invokes the + * following helper function to do most of the work. + */ + +#ifdef __LITTLE_ENDIAN__ +#define OFS_INT8 0 +#define OFS_INT16 0 +#else +#define OFS_INT8 3 +#define OFS_INT16 2 +#endif + +int +ffi_closure_helper_SYSV (ffi_closure *closure, void *rvalue, + unsigned long *pgr, unsigned long *pfr, + unsigned long *pst) +{ + void **avalue; + ffi_type **p_arg; + int i, avn; + int ireg, greg = 0; +#if defined(__SH4__) + int freg = 0; +#endif + ffi_cif *cif; + + cif = closure->cif; + avalue = alloca(cif->nargs * sizeof(void *)); + + /* Copy the caller's structure return value address so that the closure + returns the data directly to the caller. */ + if (cif->rtype->type == FFI_TYPE_STRUCT && STRUCT_VALUE_ADDRESS_WITH_ARG) + { + rvalue = (void *) *pgr++; + ireg = 1; + } + else + ireg = 0; + + cif = closure->cif; + greg = ireg; + avn = cif->nargs; + + /* Grab the addresses of the arguments from the stack frame. */ + for (i = 0, p_arg = cif->arg_types; i < avn; i++, p_arg++) + { + size_t z; + + z = (*p_arg)->size; + if (z < sizeof(int)) + { + if (greg++ >= NGREGARG) + continue; + + z = sizeof(int); + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + avalue[i] = (((char *)pgr) + OFS_INT8); + break; + + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + avalue[i] = (((char *)pgr) + OFS_INT16); + break; + + case FFI_TYPE_STRUCT: + avalue[i] = pgr; + break; + + default: + FFI_ASSERT(0); + } + pgr++; + } + else if (z == sizeof(int)) + { +#if defined(__SH4__) + if ((*p_arg)->type == FFI_TYPE_FLOAT) + { + if (freg++ >= NFREGARG) + continue; + avalue[i] = pfr; + pfr++; + } + else +#endif + { + if (greg++ >= NGREGARG) + continue; + avalue[i] = pgr; + pgr++; + } + } +#if defined(__SH4__) + else if ((*p_arg)->type == FFI_TYPE_DOUBLE) + { + if (freg + 1 >= NFREGARG) + continue; + if (freg & 1) + pfr++; + freg = (freg + 1) & ~1; + freg += 2; + avalue[i] = pfr; + pfr += 2; + } +#endif + else + { + int n = (z + sizeof (int) - 1) / sizeof (int); +#if defined(__SH4__) + if (greg + n - 1 >= NGREGARG) + continue; +#else + if (greg >= NGREGARG) + continue; +#endif + greg += n; + avalue[i] = pgr; + pgr += n; + } + } + + greg = ireg; +#if defined(__SH4__) + freg = 0; +#endif + + for (i = 0, p_arg = cif->arg_types; i < avn; i++, p_arg++) + { + size_t z; + + z = (*p_arg)->size; + if (z < sizeof(int)) + { + if (greg++ < NGREGARG) + continue; + + z = sizeof(int); + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + avalue[i] = (((char *)pst) + OFS_INT8); + break; + + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + avalue[i] = (((char *)pst) + OFS_INT16); + break; + + case FFI_TYPE_STRUCT: + avalue[i] = pst; + break; + + default: + FFI_ASSERT(0); + } + pst++; + } + else if (z == sizeof(int)) + { +#if defined(__SH4__) + if ((*p_arg)->type == FFI_TYPE_FLOAT) + { + if (freg++ < NFREGARG) + continue; + } + else +#endif + { + if (greg++ < NGREGARG) + continue; + } + avalue[i] = pst; + pst++; + } +#if defined(__SH4__) + else if ((*p_arg)->type == FFI_TYPE_DOUBLE) + { + if (freg + 1 < NFREGARG) + { + freg = (freg + 1) & ~1; + freg += 2; + continue; + } + avalue[i] = pst; + pst += 2; + } +#endif + else + { + int n = (z + sizeof (int) - 1) / sizeof (int); + if (greg + n - 1 < NGREGARG) + { + greg += n; + continue; + } +#if (! defined(__SH4__)) + else if (greg < NGREGARG) + { + greg += n; + pst += greg - NGREGARG; + continue; + } +#endif + avalue[i] = pst; + pst += n; + } + } + + (closure->fun) (cif, rvalue, avalue, closure->user_data); + + /* Tell ffi_closure_SYSV how to perform return type promotions. */ + return return_type (cif->rtype); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh/ffitarget.h new file mode 100644 index 0000000..a36bf42 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh/ffitarget.h @@ -0,0 +1,54 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 1996-2003 Red Hat, Inc. + Target configuration macros for SuperH. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +/* ---- Generic type definitions ----------------------------------------- */ + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; +#endif + +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 16 +#define FFI_NATIVE_RAW_API 0 + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh/sysv.S new file mode 100644 index 0000000..5be7516 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh/sysv.S @@ -0,0 +1,850 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2002, 2003, 2004, 2006, 2008 Kaz Kojima + + SuperH Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include +#ifdef HAVE_MACHINE_ASM_H +#include +#else +/* XXX these lose for some platforms, I'm sure. */ +#define CNAME(x) x +#define ENTRY(x) .globl CNAME(x); .type CNAME(x),%function; CNAME(x): +#endif + +#if defined(__HITACHI__) +#define STRUCT_VALUE_ADDRESS_WITH_ARG 1 +#else +#define STRUCT_VALUE_ADDRESS_WITH_ARG 0 +#endif + +.text + + # r4: ffi_prep_args + # r5: &ecif + # r6: bytes + # r7: flags + # sp+0: rvalue + # sp+4: fn + + # This assumes we are using gas. +ENTRY(ffi_call_SYSV) + # Save registers +.LFB1: + mov.l r8,@-r15 +.LCFI0: + mov.l r9,@-r15 +.LCFI1: + mov.l r10,@-r15 +.LCFI2: + mov.l r12,@-r15 +.LCFI3: + mov.l r14,@-r15 +.LCFI4: + sts.l pr,@-r15 +.LCFI5: + mov r15,r14 +.LCFI6: +#if defined(__SH4__) + mov r6,r8 + mov r7,r9 + + sub r6,r15 + add #-16,r15 + mov #~7,r0 + and r0,r15 + + mov r4,r0 + jsr @r0 + mov r15,r4 + + mov r9,r1 + shlr8 r9 + shlr8 r9 + shlr8 r9 + + mov #FFI_TYPE_STRUCT,r2 + cmp/eq r2,r9 + bf 1f +#if STRUCT_VALUE_ADDRESS_WITH_ARG + mov.l @r15+,r4 + bra 2f + mov #5,r2 +#else + mov.l @r15+,r10 +#endif +1: + mov #4,r2 +2: + mov #4,r3 + +L_pass: + cmp/pl r8 + bf L_call_it + + mov r1,r0 + and #3,r0 + +L_pass_d: + cmp/eq #FFI_TYPE_DOUBLE,r0 + bf L_pass_f + + mov r3,r0 + and #1,r0 + tst r0,r0 + bt 1f + add #1,r3 +1: + mov #12,r0 + cmp/hs r0,r3 + bt/s 3f + shlr2 r1 + bsr L_pop_d + nop +3: + add #2,r3 + bra L_pass + add #-8,r8 + +L_pop_d: + mov r3,r0 + add r0,r0 + add r3,r0 + add #-12,r0 + braf r0 + nop +#ifdef __LITTLE_ENDIAN__ + fmov.s @r15+,fr5 + rts + fmov.s @r15+,fr4 + fmov.s @r15+,fr7 + rts + fmov.s @r15+,fr6 + fmov.s @r15+,fr9 + rts + fmov.s @r15+,fr8 + fmov.s @r15+,fr11 + rts + fmov.s @r15+,fr10 +#else + fmov.s @r15+,fr4 + rts + fmov.s @r15+,fr5 + fmov.s @r15+,fr6 + rts + fmov.s @r15+,fr7 + fmov.s @r15+,fr8 + rts + fmov.s @r15+,fr9 + fmov.s @r15+,fr10 + rts + fmov.s @r15+,fr11 +#endif + +L_pass_f: + cmp/eq #FFI_TYPE_FLOAT,r0 + bf L_pass_i + + mov #12,r0 + cmp/hs r0,r3 + bt/s 2f + shlr2 r1 + bsr L_pop_f + nop +2: + add #1,r3 + bra L_pass + add #-4,r8 + +L_pop_f: + mov r3,r0 + shll2 r0 + add #-16,r0 + braf r0 + nop +#ifdef __LITTLE_ENDIAN__ + rts + fmov.s @r15+,fr5 + rts + fmov.s @r15+,fr4 + rts + fmov.s @r15+,fr7 + rts + fmov.s @r15+,fr6 + rts + fmov.s @r15+,fr9 + rts + fmov.s @r15+,fr8 + rts + fmov.s @r15+,fr11 + rts + fmov.s @r15+,fr10 +#else + rts + fmov.s @r15+,fr4 + rts + fmov.s @r15+,fr5 + rts + fmov.s @r15+,fr6 + rts + fmov.s @r15+,fr7 + rts + fmov.s @r15+,fr8 + rts + fmov.s @r15+,fr9 + rts + fmov.s @r15+,fr10 + rts + fmov.s @r15+,fr11 +#endif + +L_pass_i: + cmp/eq #FFI_TYPE_INT,r0 + bf L_call_it + + mov #8,r0 + cmp/hs r0,r2 + bt/s 2f + shlr2 r1 + bsr L_pop_i + nop +2: + add #1,r2 + bra L_pass + add #-4,r8 + +L_pop_i: + mov r2,r0 + shll2 r0 + add #-16,r0 + braf r0 + nop + rts + mov.l @r15+,r4 + rts + mov.l @r15+,r5 + rts + mov.l @r15+,r6 + rts + mov.l @r15+,r7 + +L_call_it: + # call function +#if (! STRUCT_VALUE_ADDRESS_WITH_ARG) + mov r10, r2 +#endif + mov.l @(28,r14),r1 + jsr @r1 + nop + +L_ret_d: + mov #FFI_TYPE_DOUBLE,r2 + cmp/eq r2,r9 + bf L_ret_ll + + mov.l @(24,r14),r1 +#ifdef __LITTLE_ENDIAN__ + fmov.s fr1,@r1 + add #4,r1 + bra L_epilogue + fmov.s fr0,@r1 +#else + fmov.s fr0,@r1 + add #4,r1 + bra L_epilogue + fmov.s fr1,@r1 +#endif + +L_ret_ll: + mov #FFI_TYPE_SINT64,r2 + cmp/eq r2,r9 + bt/s 1f + mov #FFI_TYPE_UINT64,r2 + cmp/eq r2,r9 + bf L_ret_f + +1: + mov.l @(24,r14),r2 + mov.l r0,@r2 + bra L_epilogue + mov.l r1,@(4,r2) + +L_ret_f: + mov #FFI_TYPE_FLOAT,r2 + cmp/eq r2,r9 + bf L_ret_i + + mov.l @(24,r14),r1 + bra L_epilogue + fmov.s fr0,@r1 + +L_ret_i: + mov #FFI_TYPE_INT,r2 + cmp/eq r2,r9 + bf L_epilogue + + mov.l @(24,r14),r1 + bra L_epilogue + mov.l r0,@r1 + +L_epilogue: + # Remove the space we pushed for the args + mov r14,r15 + + lds.l @r15+,pr + mov.l @r15+,r14 + mov.l @r15+,r12 + mov.l @r15+,r10 + mov.l @r15+,r9 + rts + mov.l @r15+,r8 +#else + mov r6,r8 + mov r7,r9 + + sub r6,r15 + add #-16,r15 + mov #~7,r0 + and r0,r15 + + mov r4,r0 + jsr @r0 + mov r15,r4 + + mov r9,r3 + shlr8 r9 + shlr8 r9 + shlr8 r9 + + mov #FFI_TYPE_STRUCT,r2 + cmp/eq r2,r9 + bf 1f +#if STRUCT_VALUE_ADDRESS_WITH_ARG + mov.l @r15+,r4 + bra 2f + mov #5,r2 +#else + mov.l @r15+,r10 +#endif +1: + mov #4,r2 +2: + +L_pass: + cmp/pl r8 + bf L_call_it + + mov r3,r0 + and #3,r0 + +L_pass_d: + cmp/eq #FFI_TYPE_DOUBLE,r0 + bf L_pass_i + + mov r15,r0 + and #7,r0 + tst r0,r0 + bt 1f + add #4,r15 +1: + mov #8,r0 + cmp/hs r0,r2 + bt/s 2f + shlr2 r3 + bsr L_pop_d + nop +2: + add #2,r2 + bra L_pass + add #-8,r8 + +L_pop_d: + mov r2,r0 + add r0,r0 + add r2,r0 + add #-12,r0 + add r0,r0 + braf r0 + nop + mov.l @r15+,r4 + rts + mov.l @r15+,r5 + mov.l @r15+,r5 + rts + mov.l @r15+,r6 + mov.l @r15+,r6 + rts + mov.l @r15+,r7 + rts + mov.l @r15+,r7 + +L_pass_i: + cmp/eq #FFI_TYPE_INT,r0 + bf L_call_it + + mov #8,r0 + cmp/hs r0,r2 + bt/s 2f + shlr2 r3 + bsr L_pop_i + nop +2: + add #1,r2 + bra L_pass + add #-4,r8 + +L_pop_i: + mov r2,r0 + shll2 r0 + add #-16,r0 + braf r0 + nop + rts + mov.l @r15+,r4 + rts + mov.l @r15+,r5 + rts + mov.l @r15+,r6 + rts + mov.l @r15+,r7 + +L_call_it: + # call function +#if (! STRUCT_VALUE_ADDRESS_WITH_ARG) + mov r10, r2 +#endif + mov.l @(28,r14),r1 + jsr @r1 + nop + +L_ret_d: + mov #FFI_TYPE_DOUBLE,r2 + cmp/eq r2,r9 + bf L_ret_ll + + mov.l @(24,r14),r2 + mov.l r0,@r2 + bra L_epilogue + mov.l r1,@(4,r2) + +L_ret_ll: + mov #FFI_TYPE_SINT64,r2 + cmp/eq r2,r9 + bt/s 1f + mov #FFI_TYPE_UINT64,r2 + cmp/eq r2,r9 + bf L_ret_i + +1: + mov.l @(24,r14),r2 + mov.l r0,@r2 + bra L_epilogue + mov.l r1,@(4,r2) + +L_ret_i: + mov #FFI_TYPE_FLOAT,r2 + cmp/eq r2,r9 + bt 1f + mov #FFI_TYPE_INT,r2 + cmp/eq r2,r9 + bf L_epilogue +1: + mov.l @(24,r14),r1 + bra L_epilogue + mov.l r0,@r1 + +L_epilogue: + # Remove the space we pushed for the args + mov r14,r15 + + lds.l @r15+,pr + mov.l @r15+,r14 + mov.l @r15+,r12 + mov.l @r15+,r10 + mov.l @r15+,r9 + rts + mov.l @r15+,r8 +#endif +.LFE1: +.ffi_call_SYSV_end: + .size CNAME(ffi_call_SYSV),.ffi_call_SYSV_end-CNAME(ffi_call_SYSV) + +.globl ffi_closure_helper_SYSV + +ENTRY(ffi_closure_SYSV) +.LFB2: + mov.l r7,@-r15 +.LCFI7: + mov.l r6,@-r15 +.LCFI8: + mov.l r5,@-r15 +.LCFI9: + mov.l r4,@-r15 +.LCFIA: + mov.l r14,@-r15 +.LCFIB: + sts.l pr,@-r15 + + /* Stack layout: + xx bytes (on stack parameters) + 16 bytes (register parameters) + 4 bytes (saved frame pointer) + 4 bytes (saved return address) + 32 bytes (floating register parameters, SH-4 only) + 8 bytes (result) + 4 bytes (pad) + 4 bytes (5th arg) + <- new stack pointer + */ +.LCFIC: +#if defined(__SH4__) + add #-48,r15 +#else + add #-16,r15 +#endif +.LCFID: + mov r15,r14 +.LCFIE: + +#if defined(__SH4__) + mov r14,r1 + add #48,r1 +#ifdef __LITTLE_ENDIAN__ + fmov.s fr10,@-r1 + fmov.s fr11,@-r1 + fmov.s fr8,@-r1 + fmov.s fr9,@-r1 + fmov.s fr6,@-r1 + fmov.s fr7,@-r1 + fmov.s fr4,@-r1 + fmov.s fr5,@-r1 +#else + fmov.s fr11,@-r1 + fmov.s fr10,@-r1 + fmov.s fr9,@-r1 + fmov.s fr8,@-r1 + fmov.s fr7,@-r1 + fmov.s fr6,@-r1 + fmov.s fr5,@-r1 + fmov.s fr4,@-r1 +#endif + mov r1,r7 + mov r14,r6 + add #56,r6 +#else + mov r14,r6 + add #24,r6 +#endif + + bt/s 10f + mov r2, r5 + mov r14,r1 + add #8,r1 + mov r1,r5 +10: + + mov r14,r1 +#if defined(__SH4__) + add #72,r1 +#else + add #40,r1 +#endif + mov.l r1,@r14 + +#ifdef PIC + mov.l L_got,r1 + mova L_got,r0 + add r0,r1 + mov.l L_helper,r0 + add r1,r0 +#else + mov.l L_helper,r0 +#endif + jsr @r0 + mov r3,r4 + + shll r0 + mov r0,r1 + mova L_table,r0 + add r1,r0 + mov.w @r0,r0 + mov r14,r2 + braf r0 + add #8,r2 +0: + .align 2 +#ifdef PIC +L_got: + .long _GLOBAL_OFFSET_TABLE_ +L_helper: + .long ffi_closure_helper_SYSV@GOTOFF +#else +L_helper: + .long ffi_closure_helper_SYSV +#endif +L_table: + .short L_case_v - 0b /* FFI_TYPE_VOID */ + .short L_case_i - 0b /* FFI_TYPE_INT */ +#if defined(__SH4__) + .short L_case_f - 0b /* FFI_TYPE_FLOAT */ + .short L_case_d - 0b /* FFI_TYPE_DOUBLE */ + .short L_case_d - 0b /* FFI_TYPE_LONGDOUBLE */ +#else + .short L_case_i - 0b /* FFI_TYPE_FLOAT */ + .short L_case_ll - 0b /* FFI_TYPE_DOUBLE */ + .short L_case_ll - 0b /* FFI_TYPE_LONGDOUBLE */ +#endif + .short L_case_uq - 0b /* FFI_TYPE_UINT8 */ + .short L_case_q - 0b /* FFI_TYPE_SINT8 */ + .short L_case_uh - 0b /* FFI_TYPE_UINT16 */ + .short L_case_h - 0b /* FFI_TYPE_SINT16 */ + .short L_case_i - 0b /* FFI_TYPE_UINT32 */ + .short L_case_i - 0b /* FFI_TYPE_SINT32 */ + .short L_case_ll - 0b /* FFI_TYPE_UINT64 */ + .short L_case_ll - 0b /* FFI_TYPE_SINT64 */ + .short L_case_v - 0b /* FFI_TYPE_STRUCT */ + .short L_case_i - 0b /* FFI_TYPE_POINTER */ + +#if defined(__SH4__) +L_case_d: +#ifdef __LITTLE_ENDIAN__ + fmov.s @r2+,fr1 + bra L_case_v + fmov.s @r2,fr0 +#else + fmov.s @r2+,fr0 + bra L_case_v + fmov.s @r2,fr1 +#endif + +L_case_f: + bra L_case_v + fmov.s @r2,fr0 +#endif + +L_case_ll: + mov.l @r2+,r0 + bra L_case_v + mov.l @r2,r1 + +L_case_i: + bra L_case_v + mov.l @r2,r0 + +L_case_q: +#ifdef __LITTLE_ENDIAN__ +#else + add #3,r2 +#endif + bra L_case_v + mov.b @r2,r0 + +L_case_uq: +#ifdef __LITTLE_ENDIAN__ +#else + add #3,r2 +#endif + mov.b @r2,r0 + bra L_case_v + extu.b r0,r0 + +L_case_h: +#ifdef __LITTLE_ENDIAN__ +#else + add #2,r2 +#endif + bra L_case_v + mov.w @r2,r0 + +L_case_uh: +#ifdef __LITTLE_ENDIAN__ +#else + add #2,r2 +#endif + mov.w @r2,r0 + extu.w r0,r0 + /* fall through */ + +L_case_v: +#if defined(__SH4__) + add #48,r15 +#else + add #16,r15 +#endif + lds.l @r15+,pr + mov.l @r15+,r14 + rts + add #16,r15 +.LFE2: +.ffi_closure_SYSV_end: + .size CNAME(ffi_closure_SYSV),.ffi_closure_SYSV_end-CNAME(ffi_closure_SYSV) + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif + + .section ".eh_frame","aw",@progbits +__FRAME_BEGIN__: + .4byte .LECIE1-.LSCIE1 /* Length of Common Information Entry */ +.LSCIE1: + .4byte 0x0 /* CIE Identifier Tag */ + .byte 0x1 /* CIE Version */ +#ifdef PIC + .ascii "zR\0" /* CIE Augmentation */ +#else + .byte 0x0 /* CIE Augmentation */ +#endif + .byte 0x1 /* uleb128 0x1; CIE Code Alignment Factor */ + .byte 0x7c /* sleb128 -4; CIE Data Alignment Factor */ + .byte 0x11 /* CIE RA Column */ +#ifdef PIC + .uleb128 0x1 /* Augmentation size */ + .byte 0x10 /* FDE Encoding (pcrel) */ +#endif + .byte 0xc /* DW_CFA_def_cfa */ + .byte 0xf /* uleb128 0xf */ + .byte 0x0 /* uleb128 0x0 */ + .align 2 +.LECIE1: +.LSFDE1: + .4byte .LEFDE1-.LASFDE1 /* FDE Length */ +.LASFDE1: + .4byte .LASFDE1-__FRAME_BEGIN__ /* FDE CIE offset */ +#ifdef PIC + .4byte .LFB1-. /* FDE initial location */ +#else + .4byte .LFB1 /* FDE initial location */ +#endif + .4byte .LFE1-.LFB1 /* FDE address range */ +#ifdef PIC + .uleb128 0x0 /* Augmentation size */ +#endif + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFI0-.LFB1 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0x4 /* uleb128 0x4 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFI1-.LCFI0 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0x8 /* uleb128 0x4 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFI2-.LCFI1 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0xc /* uleb128 0x4 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFI3-.LCFI2 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0x10 /* uleb128 0x4 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFI4-.LCFI3 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0x14 /* uleb128 0x4 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFI5-.LCFI4 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0x18 /* uleb128 0x4 */ + .byte 0x91 /* DW_CFA_offset, column 0x11 */ + .byte 0x6 /* uleb128 0x6 */ + .byte 0x8e /* DW_CFA_offset, column 0xe */ + .byte 0x5 /* uleb128 0x5 */ + .byte 0x8c /* DW_CFA_offset, column 0xc */ + .byte 0x4 /* uleb128 0x4 */ + .byte 0x8a /* DW_CFA_offset, column 0xa */ + .byte 0x3 /* uleb128 0x3 */ + .byte 0x89 /* DW_CFA_offset, column 0x9 */ + .byte 0x2 /* uleb128 0x2 */ + .byte 0x88 /* DW_CFA_offset, column 0x8 */ + .byte 0x1 /* uleb128 0x1 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFI6-.LCFI5 + .byte 0xd /* DW_CFA_def_cfa_register */ + .byte 0xe /* uleb128 0xe */ + .align 2 +.LEFDE1: + +.LSFDE3: + .4byte .LEFDE3-.LASFDE3 /* FDE Length */ +.LASFDE3: + .4byte .LASFDE3-__FRAME_BEGIN__ /* FDE CIE offset */ +#ifdef PIC + .4byte .LFB2-. /* FDE initial location */ +#else + .4byte .LFB2 /* FDE initial location */ +#endif + .4byte .LFE2-.LFB2 /* FDE address range */ +#ifdef PIC + .uleb128 0x0 /* Augmentation size */ +#endif + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFI7-.LFB2 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0x4 /* uleb128 0x4 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFI8-.LCFI7 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0x8 /* uleb128 0x4 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFI9-.LCFI8 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0xc /* uleb128 0x4 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFIA-.LCFI9 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0x10 /* uleb128 0x4 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFIB-.LCFIA + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0x14 /* uleb128 0x4 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFIC-.LCFIB + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte 0x18 /* uleb128 0x4 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFID-.LCFIC + .byte 0xe /* DW_CFA_def_cfa_offset */ +#if defined(__SH4__) + .byte 24+48 /* uleb128 24+48 */ +#else + .byte 24+16 /* uleb128 24+16 */ +#endif + .byte 0x91 /* DW_CFA_offset, column 0x11 */ + .byte 0x6 /* uleb128 0x6 */ + .byte 0x8e /* DW_CFA_offset, column 0xe */ + .byte 0x5 /* uleb128 0x5 */ + .byte 0x84 /* DW_CFA_offset, column 0x4 */ + .byte 0x4 /* uleb128 0x4 */ + .byte 0x85 /* DW_CFA_offset, column 0x5 */ + .byte 0x3 /* uleb128 0x3 */ + .byte 0x86 /* DW_CFA_offset, column 0x6 */ + .byte 0x2 /* uleb128 0x2 */ + .byte 0x87 /* DW_CFA_offset, column 0x7 */ + .byte 0x1 /* uleb128 0x1 */ + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte .LCFIE-.LCFID + .byte 0xd /* DW_CFA_def_cfa_register */ + .byte 0xe /* uleb128 0xe */ + .align 2 +.LEFDE3: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh64/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh64/ffi.c new file mode 100644 index 0000000..123b87a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh64/ffi.c @@ -0,0 +1,469 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2003, 2004, 2006, 2007, 2012 Kaz Kojima + Copyright (c) 2008 Anthony Green + + SuperH SHmedia Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include + +#define NGREGARG 8 +#define NFREGARG 12 + +static int +return_type (ffi_type *arg) +{ + + if (arg->type != FFI_TYPE_STRUCT) + return arg->type; + + /* gcc uses r2 if the result can be packed in on register. */ + if (arg->size <= sizeof (UINT8)) + return FFI_TYPE_UINT8; + else if (arg->size <= sizeof (UINT16)) + return FFI_TYPE_UINT16; + else if (arg->size <= sizeof (UINT32)) + return FFI_TYPE_UINT32; + else if (arg->size <= sizeof (UINT64)) + return FFI_TYPE_UINT64; + + return FFI_TYPE_STRUCT; +} + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments */ + +void ffi_prep_args(char *stack, extended_cif *ecif) +{ + register unsigned int i; + register unsigned int avn; + register void **p_argv; + register char *argp; + register ffi_type **p_arg; + + argp = stack; + + if (return_type (ecif->cif->rtype) == FFI_TYPE_STRUCT) + { + *(void **) argp = ecif->rvalue; + argp += sizeof (UINT64); + } + + avn = ecif->cif->nargs; + p_argv = ecif->avalue; + + for (i = 0, p_arg = ecif->cif->arg_types; i < avn; i++, p_arg++, p_argv++) + { + size_t z; + int align; + + z = (*p_arg)->size; + align = (*p_arg)->alignment; + if (z < sizeof (UINT32)) + { + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + *(SINT64 *) argp = (SINT64) *(SINT8 *)(*p_argv); + break; + + case FFI_TYPE_UINT8: + *(UINT64 *) argp = (UINT64) *(UINT8 *)(*p_argv); + break; + + case FFI_TYPE_SINT16: + *(SINT64 *) argp = (SINT64) *(SINT16 *)(*p_argv); + break; + + case FFI_TYPE_UINT16: + *(UINT64 *) argp = (UINT64) *(UINT16 *)(*p_argv); + break; + + case FFI_TYPE_STRUCT: + memcpy (argp, *p_argv, z); + break; + + default: + FFI_ASSERT(0); + } + argp += sizeof (UINT64); + } + else if (z == sizeof (UINT32) && align == sizeof (UINT32)) + { + switch ((*p_arg)->type) + { + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + *(SINT64 *) argp = (SINT64) *(SINT32 *) (*p_argv); + break; + + case FFI_TYPE_FLOAT: + case FFI_TYPE_POINTER: + case FFI_TYPE_UINT32: + case FFI_TYPE_STRUCT: + *(UINT64 *) argp = (UINT64) *(UINT32 *) (*p_argv); + break; + + default: + FFI_ASSERT(0); + break; + } + argp += sizeof (UINT64); + } + else if (z == sizeof (UINT64) + && align == sizeof (UINT64) + && ((int) *p_argv & (sizeof (UINT64) - 1)) == 0) + { + *(UINT64 *) argp = *(UINT64 *) (*p_argv); + argp += sizeof (UINT64); + } + else + { + int n = (z + sizeof (UINT64) - 1) / sizeof (UINT64); + + memcpy (argp, *p_argv, z); + argp += n * sizeof (UINT64); + } + } + + return; +} + +/* Perform machine dependent cif processing */ +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + int i, j; + int size, type; + int n, m; + int greg; + int freg; + int fpair = -1; + + greg = (return_type (cif->rtype) == FFI_TYPE_STRUCT ? 1 : 0); + freg = 0; + cif->flags2 = 0; + + for (i = j = 0; i < cif->nargs; i++) + { + type = (cif->arg_types)[i]->type; + switch (type) + { + case FFI_TYPE_FLOAT: + greg++; + cif->bytes += sizeof (UINT64) - sizeof (float); + if (freg >= NFREGARG - 1) + continue; + if (fpair < 0) + { + fpair = freg; + freg += 2; + } + else + fpair = -1; + cif->flags2 += ((cif->arg_types)[i]->type) << (2 * j++); + break; + + case FFI_TYPE_DOUBLE: + if (greg++ >= NGREGARG && (freg + 1) >= NFREGARG) + continue; + if ((freg + 1) < NFREGARG) + { + freg += 2; + cif->flags2 += ((cif->arg_types)[i]->type) << (2 * j++); + } + else + cif->flags2 += FFI_TYPE_INT << (2 * j++); + break; + + default: + size = (cif->arg_types)[i]->size; + if (size < sizeof (UINT64)) + cif->bytes += sizeof (UINT64) - size; + n = (size + sizeof (UINT64) - 1) / sizeof (UINT64); + if (greg >= NGREGARG) + continue; + else if (greg + n - 1 >= NGREGARG) + greg = NGREGARG; + else + greg += n; + for (m = 0; m < n; m++) + cif->flags2 += FFI_TYPE_INT << (2 * j++); + break; + } + } + + /* Set the return type flag */ + switch (cif->rtype->type) + { + case FFI_TYPE_STRUCT: + cif->flags = return_type (cif->rtype); + break; + + case FFI_TYPE_VOID: + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + cif->flags = cif->rtype->type; + break; + + default: + cif->flags = FFI_TYPE_INT; + break; + } + + return FFI_OK; +} + +/*@-declundef@*/ +/*@-exportheader@*/ +extern void ffi_call_SYSV(void (*)(char *, extended_cif *), + /*@out@*/ extended_cif *, + unsigned, unsigned, long long, + /*@out@*/ unsigned *, + void (*fn)(void)); +/*@=declundef@*/ +/*@=exportheader@*/ + +void ffi_call(/*@dependent@*/ ffi_cif *cif, + void (*fn)(void), + /*@out@*/ void *rvalue, + /*@dependent@*/ void **avalue) +{ + extended_cif ecif; + UINT64 trvalue; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return */ + /* value address then we need to make one */ + + if (cif->rtype->type == FFI_TYPE_STRUCT + && return_type (cif->rtype) != FFI_TYPE_STRUCT) + ecif.rvalue = &trvalue; + else if ((rvalue == NULL) && + (cif->rtype->type == FFI_TYPE_STRUCT)) + { + ecif.rvalue = alloca(cif->rtype->size); + } + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_SYSV: + ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, cif->flags, cif->flags2, + ecif.rvalue, fn); + break; + default: + FFI_ASSERT(0); + break; + } + + if (rvalue + && cif->rtype->type == FFI_TYPE_STRUCT + && return_type (cif->rtype) != FFI_TYPE_STRUCT) + memcpy (rvalue, &trvalue, cif->rtype->size); +} + +extern void ffi_closure_SYSV (void); +extern void __ic_invalidate (void *line); + +ffi_status +ffi_prep_closure_loc (ffi_closure *closure, + ffi_cif *cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + unsigned int *tramp; + + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + tramp = (unsigned int *) &closure->tramp[0]; + /* Since ffi_closure is an aligned object, the ffi trampoline is + called as an SHcompact code. Sigh. + SHcompact part: + mova @(1,pc),r0; add #1,r0; jmp @r0; nop; + SHmedia part: + movi fnaddr >> 16,r1; shori fnaddr,r1; ptabs/l r1,tr0 + movi cxt >> 16,r1; shori cxt,r1; blink tr0,r63 */ +#ifdef __LITTLE_ENDIAN__ + tramp[0] = 0x7001c701; + tramp[1] = 0x0009402b; +#else + tramp[0] = 0xc7017001; + tramp[1] = 0x402b0009; +#endif + tramp[2] = 0xcc000010 | (((UINT32) ffi_closure_SYSV) >> 16) << 10; + tramp[3] = 0xc8000010 | (((UINT32) ffi_closure_SYSV) & 0xffff) << 10; + tramp[4] = 0x6bf10600; + tramp[5] = 0xcc000010 | (((UINT32) codeloc) >> 16) << 10; + tramp[6] = 0xc8000010 | (((UINT32) codeloc) & 0xffff) << 10; + tramp[7] = 0x4401fff0; + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + /* Flush the icache. */ + asm volatile ("ocbwb %0,0; synco; icbi %1,0; synci" : : "r" (tramp), + "r"(codeloc)); + + return FFI_OK; +} + +/* Basically the trampoline invokes ffi_closure_SYSV, and on + * entry, r3 holds the address of the closure. + * After storing the registers that could possibly contain + * parameters to be passed into the stack frame and setting + * up space for a return value, ffi_closure_SYSV invokes the + * following helper function to do most of the work. + */ + +int +ffi_closure_helper_SYSV (ffi_closure *closure, UINT64 *rvalue, + UINT64 *pgr, UINT64 *pfr, UINT64 *pst) +{ + void **avalue; + ffi_type **p_arg; + int i, avn; + int greg, freg; + ffi_cif *cif; + int fpair = -1; + + cif = closure->cif; + avalue = alloca (cif->nargs * sizeof (void *)); + + /* Copy the caller's structure return value address so that the closure + returns the data directly to the caller. */ + if (return_type (cif->rtype) == FFI_TYPE_STRUCT) + { + rvalue = (UINT64 *) *pgr; + greg = 1; + } + else + greg = 0; + + freg = 0; + cif = closure->cif; + avn = cif->nargs; + + /* Grab the addresses of the arguments from the stack frame. */ + for (i = 0, p_arg = cif->arg_types; i < avn; i++, p_arg++) + { + size_t z; + void *p; + + z = (*p_arg)->size; + if (z < sizeof (UINT32)) + { + p = pgr + greg++; + + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + case FFI_TYPE_STRUCT: +#ifdef __LITTLE_ENDIAN__ + avalue[i] = p; +#else + avalue[i] = ((char *) p) + sizeof (UINT32) - z; +#endif + break; + + default: + FFI_ASSERT(0); + } + } + else if (z == sizeof (UINT32)) + { + if ((*p_arg)->type == FFI_TYPE_FLOAT) + { + if (freg < NFREGARG - 1) + { + if (fpair >= 0) + { + avalue[i] = (UINT32 *) pfr + fpair; + fpair = -1; + } + else + { +#ifdef __LITTLE_ENDIAN__ + fpair = freg; + avalue[i] = (UINT32 *) pfr + (1 ^ freg); +#else + fpair = 1 ^ freg; + avalue[i] = (UINT32 *) pfr + freg; +#endif + freg += 2; + } + } + else +#ifdef __LITTLE_ENDIAN__ + avalue[i] = pgr + greg; +#else + avalue[i] = (UINT32 *) (pgr + greg) + 1; +#endif + } + else +#ifdef __LITTLE_ENDIAN__ + avalue[i] = pgr + greg; +#else + avalue[i] = (UINT32 *) (pgr + greg) + 1; +#endif + greg++; + } + else if ((*p_arg)->type == FFI_TYPE_DOUBLE) + { + if (freg + 1 >= NFREGARG) + avalue[i] = pgr + greg; + else + { + avalue[i] = pfr + (freg >> 1); + freg += 2; + } + greg++; + } + else + { + int n = (z + sizeof (UINT64) - 1) / sizeof (UINT64); + + avalue[i] = pgr + greg; + greg += n; + } + } + + (closure->fun) (cif, rvalue, avalue, closure->user_data); + + /* Tell ffi_closure_SYSV how to perform return type promotions. */ + return return_type (cif->rtype); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh64/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh64/ffitarget.h new file mode 100644 index 0000000..08a6fe9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh64/ffitarget.h @@ -0,0 +1,58 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 1996-2003 Red Hat, Inc. + Target configuration macros for SuperH - SHmedia. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +/* ---- Generic type definitions ----------------------------------------- */ + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; + +#define FFI_EXTRA_CIF_FIELDS long long flags2 +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 32 +#define FFI_NATIVE_RAW_API 0 + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh64/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh64/sysv.S new file mode 100644 index 0000000..c4587d5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sh64/sysv.S @@ -0,0 +1,539 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2003, 2004, 2006, 2008 Kaz Kojima + + SuperH SHmedia Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include +#ifdef HAVE_MACHINE_ASM_H +#include +#else +/* XXX these lose for some platforms, I'm sure. */ +#define CNAME(x) x +#define ENTRY(x) .globl CNAME(x); .type CNAME(x),%function; CNAME(x): +#endif + +#ifdef __LITTLE_ENDIAN__ +#define OFS_FLT 0 +#else +#define OFS_FLT 4 +#endif + + .section .text..SHmedia32,"ax" + + # r2: ffi_prep_args + # r3: &ecif + # r4: bytes + # r5: flags + # r6: flags2 + # r7: rvalue + # r8: fn + + # This assumes we are using gas. + .align 5 +ENTRY(ffi_call_SYSV) + # Save registers +.LFB1: + addi.l r15, -48, r15 +.LCFI0: + st.q r15, 40, r32 + st.q r15, 32, r31 + st.q r15, 24, r30 + st.q r15, 16, r29 + st.q r15, 8, r28 + st.l r15, 4, r18 + st.l r15, 0, r14 +.LCFI1: + add.l r15, r63, r14 +.LCFI2: +# add r4, r63, r28 + add r5, r63, r29 + add r6, r63, r30 + add r7, r63, r31 + add r8, r63, r32 + + addi r4, (64 + 7), r4 + andi r4, ~7, r4 + sub.l r15, r4, r15 + + ptabs/l r2, tr0 + add r15, r63, r2 + blink tr0, r18 + + addi r15, 64, r22 + movi 0, r0 + movi 0, r1 + movi -1, r23 + + pt/l 1f, tr1 + bnei/l r29, FFI_TYPE_STRUCT, tr1 + ld.l r15, 0, r19 + addi r15, 8, r15 + addi r0, 1, r0 +1: + +.L_pass: + andi r30, 3, r20 + shlri r30, 2, r30 + + pt/l .L_call_it, tr0 + pt/l .L_pass_i, tr1 + pt/l .L_pass_f, tr2 + + beqi/l r20, FFI_TYPE_VOID, tr0 + beqi/l r20, FFI_TYPE_INT, tr1 + beqi/l r20, FFI_TYPE_FLOAT, tr2 + +.L_pass_d: + addi r0, 1, r0 + pt/l 3f, tr0 + movi 12, r20 + bge/l r1, r20, tr0 + + pt/l .L_pop_d, tr1 + pt/l 2f, tr0 + blink tr1, r63 +2: + addi.l r15, 8, r15 +3: + pt/l .L_pass, tr0 + addi r1, 2, r1 + blink tr0, r63 + +.L_pop_d: + pt/l .L_pop_d_tbl, tr1 + gettr tr1, r20 + shlli r1, 2, r21 + add r20, r21, r20 + ptabs/l r20, tr1 + blink tr1, r63 + +.L_pop_d_tbl: + fld.d r15, 0, dr0 + blink tr0, r63 + fld.d r15, 0, dr2 + blink tr0, r63 + fld.d r15, 0, dr4 + blink tr0, r63 + fld.d r15, 0, dr6 + blink tr0, r63 + fld.d r15, 0, dr8 + blink tr0, r63 + fld.d r15, 0, dr10 + blink tr0, r63 + +.L_pass_f: + addi r0, 1, r0 + pt/l 3f, tr0 + movi 12, r20 + bge/l r1, r20, tr0 + + pt/l .L_pop_f, tr1 + pt/l 2f, tr0 + blink tr1, r63 +2: + addi.l r15, 8, r15 +3: + pt/l .L_pass, tr0 + blink tr0, r63 + +.L_pop_f: + pt/l .L_pop_f_tbl, tr1 + pt/l 5f, tr2 + gettr tr1, r20 + bge/l r23, r63, tr2 + add r1, r63, r23 + shlli r1, 3, r21 + addi r1, 2, r1 + add r20, r21, r20 + ptabs/l r20, tr1 + blink tr1, r63 +5: + addi r23, 1, r21 + movi -1, r23 + shlli r21, 3, r21 + add r20, r21, r20 + ptabs/l r20, tr1 + blink tr1, r63 + +.L_pop_f_tbl: + fld.s r15, OFS_FLT, fr0 + blink tr0, r63 + fld.s r15, OFS_FLT, fr1 + blink tr0, r63 + fld.s r15, OFS_FLT, fr2 + blink tr0, r63 + fld.s r15, OFS_FLT, fr3 + blink tr0, r63 + fld.s r15, OFS_FLT, fr4 + blink tr0, r63 + fld.s r15, OFS_FLT, fr5 + blink tr0, r63 + fld.s r15, OFS_FLT, fr6 + blink tr0, r63 + fld.s r15, OFS_FLT, fr7 + blink tr0, r63 + fld.s r15, OFS_FLT, fr8 + blink tr0, r63 + fld.s r15, OFS_FLT, fr9 + blink tr0, r63 + fld.s r15, OFS_FLT, fr10 + blink tr0, r63 + fld.s r15, OFS_FLT, fr11 + blink tr0, r63 + +.L_pass_i: + pt/l 3f, tr0 + movi 8, r20 + bge/l r0, r20, tr0 + + pt/l .L_pop_i, tr1 + pt/l 2f, tr0 + blink tr1, r63 +2: + addi.l r15, 8, r15 +3: + pt/l .L_pass, tr0 + addi r0, 1, r0 + blink tr0, r63 + +.L_pop_i: + pt/l .L_pop_i_tbl, tr1 + gettr tr1, r20 + shlli r0, 3, r21 + add r20, r21, r20 + ptabs/l r20, tr1 + blink tr1, r63 + +.L_pop_i_tbl: + ld.q r15, 0, r2 + blink tr0, r63 + ld.q r15, 0, r3 + blink tr0, r63 + ld.q r15, 0, r4 + blink tr0, r63 + ld.q r15, 0, r5 + blink tr0, r63 + ld.q r15, 0, r6 + blink tr0, r63 + ld.q r15, 0, r7 + blink tr0, r63 + ld.q r15, 0, r8 + blink tr0, r63 + ld.q r15, 0, r9 + blink tr0, r63 + +.L_call_it: + # call function + pt/l 1f, tr1 + bnei/l r29, FFI_TYPE_STRUCT, tr1 + add r19, r63, r2 +1: + add r22, r63, r15 + ptabs/l r32, tr0 + blink tr0, r18 + + pt/l .L_ret_i, tr0 + pt/l .L_ret_ll, tr1 + pt/l .L_ret_d, tr2 + pt/l .L_ret_f, tr3 + pt/l .L_epilogue, tr4 + + beqi/l r29, FFI_TYPE_INT, tr0 + beqi/l r29, FFI_TYPE_UINT32, tr0 + beqi/l r29, FFI_TYPE_SINT64, tr1 + beqi/l r29, FFI_TYPE_UINT64, tr1 + beqi/l r29, FFI_TYPE_DOUBLE, tr2 + beqi/l r29, FFI_TYPE_FLOAT, tr3 + + pt/l .L_ret_q, tr0 + pt/l .L_ret_h, tr1 + + beqi/l r29, FFI_TYPE_UINT8, tr0 + beqi/l r29, FFI_TYPE_UINT16, tr1 + blink tr4, r63 + +.L_ret_d: + fst.d r31, 0, dr0 + blink tr4, r63 + +.L_ret_ll: + st.q r31, 0, r2 + blink tr4, r63 + +.L_ret_f: + fst.s r31, OFS_FLT, fr0 + blink tr4, r63 + +.L_ret_q: + st.b r31, 0, r2 + blink tr4, r63 + +.L_ret_h: + st.w r31, 0, r2 + blink tr4, r63 + +.L_ret_i: + st.l r31, 0, r2 + # Fall + +.L_epilogue: + # Remove the space we pushed for the args + add r14, r63, r15 + + ld.l r15, 0, r14 + ld.l r15, 4, r18 + ld.q r15, 8, r28 + ld.q r15, 16, r29 + ld.q r15, 24, r30 + ld.q r15, 32, r31 + ld.q r15, 40, r32 + addi.l r15, 48, r15 + ptabs r18, tr0 + blink tr0, r63 + +.LFE1: +.ffi_call_SYSV_end: + .size CNAME(ffi_call_SYSV),.ffi_call_SYSV_end-CNAME(ffi_call_SYSV) + + .align 5 +ENTRY(ffi_closure_SYSV) +.LFB2: + addi.l r15, -136, r15 +.LCFI3: + st.l r15, 12, r18 + st.l r15, 8, r14 + st.l r15, 4, r12 +.LCFI4: + add r15, r63, r14 +.LCFI5: + /* Stack layout: + ... + 64 bytes (register parameters) + 48 bytes (floating register parameters) + 8 bytes (result) + 4 bytes (r18) + 4 bytes (r14) + 4 bytes (r12) + 4 bytes (for align) + <- new stack pointer + */ + fst.d r14, 24, dr0 + fst.d r14, 32, dr2 + fst.d r14, 40, dr4 + fst.d r14, 48, dr6 + fst.d r14, 56, dr8 + fst.d r14, 64, dr10 + st.q r14, 72, r2 + st.q r14, 80, r3 + st.q r14, 88, r4 + st.q r14, 96, r5 + st.q r14, 104, r6 + st.q r14, 112, r7 + st.q r14, 120, r8 + st.q r14, 128, r9 + + add r1, r63, r2 + addi r14, 16, r3 + addi r14, 72, r4 + addi r14, 24, r5 + addi r14, 136, r6 +#ifdef PIC + movi (((datalabel _GLOBAL_OFFSET_TABLE_-(.LPCS0-.)) >> 16) & 65535), r12 + shori ((datalabel _GLOBAL_OFFSET_TABLE_-(.LPCS0-.)) & 65535), r12 +.LPCS0: ptrel/u r12, tr0 + movi ((ffi_closure_helper_SYSV@GOTPLT) & 65535), r1 + gettr tr0, r12 + ldx.l r1, r12, r1 + ptabs r1, tr0 +#else + pt/l ffi_closure_helper_SYSV, tr0 +#endif + blink tr0, r18 + + shlli r2, 1, r1 + movi (((datalabel .L_table) >> 16) & 65535), r2 + shori ((datalabel .L_table) & 65535), r2 + ldx.w r2, r1, r1 + add r1, r2, r1 + pt/l .L_case_v, tr1 + ptabs r1, tr0 + blink tr0, r63 + + .align 2 +.L_table: + .word .L_case_v - datalabel .L_table /* FFI_TYPE_VOID */ + .word .L_case_i - datalabel .L_table /* FFI_TYPE_INT */ + .word .L_case_f - datalabel .L_table /* FFI_TYPE_FLOAT */ + .word .L_case_d - datalabel .L_table /* FFI_TYPE_DOUBLE */ + .word .L_case_d - datalabel .L_table /* FFI_TYPE_LONGDOUBLE */ + .word .L_case_uq - datalabel .L_table /* FFI_TYPE_UINT8 */ + .word .L_case_q - datalabel .L_table /* FFI_TYPE_SINT8 */ + .word .L_case_uh - datalabel .L_table /* FFI_TYPE_UINT16 */ + .word .L_case_h - datalabel .L_table /* FFI_TYPE_SINT16 */ + .word .L_case_i - datalabel .L_table /* FFI_TYPE_UINT32 */ + .word .L_case_i - datalabel .L_table /* FFI_TYPE_SINT32 */ + .word .L_case_ll - datalabel .L_table /* FFI_TYPE_UINT64 */ + .word .L_case_ll - datalabel .L_table /* FFI_TYPE_SINT64 */ + .word .L_case_v - datalabel .L_table /* FFI_TYPE_STRUCT */ + .word .L_case_i - datalabel .L_table /* FFI_TYPE_POINTER */ + + .align 2 +.L_case_d: + fld.d r14, 16, dr0 + blink tr1, r63 +.L_case_f: + fld.s r14, 16, fr0 + blink tr1, r63 +.L_case_ll: + ld.q r14, 16, r2 + blink tr1, r63 +.L_case_i: + ld.l r14, 16, r2 + blink tr1, r63 +.L_case_q: + ld.b r14, 16, r2 + blink tr1, r63 +.L_case_uq: + ld.ub r14, 16, r2 + blink tr1, r63 +.L_case_h: + ld.w r14, 16, r2 + blink tr1, r63 +.L_case_uh: + ld.uw r14, 16, r2 + blink tr1, r63 +.L_case_v: + add.l r14, r63, r15 + ld.l r15, 4, r12 + ld.l r15, 8, r14 + ld.l r15, 12, r18 + addi.l r15, 136, r15 + ptabs r18, tr0 + blink tr0, r63 + +.LFE2: +.ffi_closure_SYSV_end: + .size CNAME(ffi_closure_SYSV),.ffi_closure_SYSV_end-CNAME(ffi_closure_SYSV) + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif + + .section ".eh_frame","aw",@progbits +__FRAME_BEGIN__: + .4byte .LECIE1-.LSCIE1 /* Length of Common Information Entry */ +.LSCIE1: + .4byte 0x0 /* CIE Identifier Tag */ + .byte 0x1 /* CIE Version */ +#ifdef PIC + .ascii "zR\0" /* CIE Augmentation */ +#else + .byte 0x0 /* CIE Augmentation */ +#endif + .uleb128 0x1 /* CIE Code Alignment Factor */ + .sleb128 -4 /* CIE Data Alignment Factor */ + .byte 0x12 /* CIE RA Column */ +#ifdef PIC + .uleb128 0x1 /* Augmentation size */ + .byte 0x10 /* FDE Encoding (pcrel) */ +#endif + .byte 0xc /* DW_CFA_def_cfa */ + .uleb128 0xf + .uleb128 0x0 + .align 2 +.LECIE1: +.LSFDE1: + .4byte datalabel .LEFDE1-datalabel .LASFDE1 /* FDE Length */ +.LASFDE1: + .4byte datalabel .LASFDE1-datalabel __FRAME_BEGIN__ +#ifdef PIC + .4byte .LFB1-. /* FDE initial location */ +#else + .4byte .LFB1 /* FDE initial location */ +#endif + .4byte datalabel .LFE1-datalabel .LFB1 /* FDE address range */ +#ifdef PIC + .uleb128 0x0 /* Augmentation size */ +#endif + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte datalabel .LCFI0-datalabel .LFB1 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .uleb128 0x30 + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte datalabel .LCFI1-datalabel .LCFI0 + .byte 0x8e /* DW_CFA_offset, column 0xe */ + .uleb128 0xc + .byte 0x92 /* DW_CFA_offset, column 0x12 */ + .uleb128 0xb + .byte 0x9c /* DW_CFA_offset, column 0x1c */ + .uleb128 0xa + .byte 0x9d /* DW_CFA_offset, column 0x1d */ + .uleb128 0x8 + .byte 0x9e /* DW_CFA_offset, column 0x1e */ + .uleb128 0x6 + .byte 0x9f /* DW_CFA_offset, column 0x1f */ + .uleb128 0x4 + .byte 0xa0 /* DW_CFA_offset, column 0x20 */ + .uleb128 0x2 + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte datalabel .LCFI2-datalabel .LCFI1 + .byte 0xd /* DW_CFA_def_cfa_register */ + .uleb128 0xe + .align 2 +.LEFDE1: + +.LSFDE3: + .4byte datalabel .LEFDE3-datalabel .LASFDE3 /* FDE Length */ +.LASFDE3: + .4byte datalabel .LASFDE3-datalabel __FRAME_BEGIN__ +#ifdef PIC + .4byte .LFB2-. /* FDE initial location */ +#else + .4byte .LFB2 /* FDE initial location */ +#endif + .4byte datalabel .LFE2-datalabel .LFB2 /* FDE address range */ +#ifdef PIC + .uleb128 0x0 /* Augmentation size */ +#endif + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte datalabel .LCFI3-datalabel .LFB2 + .byte 0xe /* DW_CFA_def_cfa_offset */ + .uleb128 0x88 + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte datalabel .LCFI4-datalabel .LCFI3 + .byte 0x8c /* DW_CFA_offset, column 0xc */ + .uleb128 0x21 + .byte 0x8e /* DW_CFA_offset, column 0xe */ + .uleb128 0x20 + .byte 0x92 /* DW_CFA_offset, column 0x12 */ + .uleb128 0x1f + .byte 0x4 /* DW_CFA_advance_loc4 */ + .4byte datalabel .LCFI5-datalabel .LCFI4 + .byte 0xd /* DW_CFA_def_cfa_register */ + .uleb128 0xe + .align 2 +.LEFDE3: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/ffi.c new file mode 100644 index 0000000..9e406d0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/ffi.c @@ -0,0 +1,468 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2011, 2013 Anthony Green + Copyright (c) 1996, 2003-2004, 2007-2008 Red Hat, Inc. + + SPARC Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include +#include +#include "internal.h" + +#ifndef SPARC64 + +/* Force FFI_TYPE_LONGDOUBLE to be different than FFI_TYPE_DOUBLE; + all further uses in this file will refer to the 128-bit type. */ +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE +# if FFI_TYPE_LONGDOUBLE != 4 +# error FFI_TYPE_LONGDOUBLE out of date +# endif +#else +# undef FFI_TYPE_LONGDOUBLE +# define FFI_TYPE_LONGDOUBLE 4 +#endif + +/* Perform machine dependent cif processing */ +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep(ffi_cif *cif) +{ + ffi_type *rtype = cif->rtype; + int rtt = rtype->type; + size_t bytes; + int i, n, flags; + + /* Set the return type flag */ + switch (rtt) + { + case FFI_TYPE_VOID: + flags = SPARC_RET_VOID; + break; + case FFI_TYPE_FLOAT: + flags = SPARC_RET_F_1; + break; + case FFI_TYPE_DOUBLE: + flags = SPARC_RET_F_2; + break; + case FFI_TYPE_LONGDOUBLE: + case FFI_TYPE_STRUCT: + flags = (rtype->size & 0xfff) << SPARC_SIZEMASK_SHIFT; + flags |= SPARC_RET_STRUCT; + break; + case FFI_TYPE_SINT8: + flags = SPARC_RET_SINT8; + break; + case FFI_TYPE_UINT8: + flags = SPARC_RET_UINT8; + break; + case FFI_TYPE_SINT16: + flags = SPARC_RET_SINT16; + break; + case FFI_TYPE_UINT16: + flags = SPARC_RET_UINT16; + break; + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_POINTER: + flags = SPARC_RET_UINT32; + break; + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + flags = SPARC_RET_INT64; + break; + case FFI_TYPE_COMPLEX: + rtt = rtype->elements[0]->type; + switch (rtt) + { + case FFI_TYPE_FLOAT: + flags = SPARC_RET_F_2; + break; + case FFI_TYPE_DOUBLE: + flags = SPARC_RET_F_4; + break; + case FFI_TYPE_LONGDOUBLE: + flags = SPARC_RET_F_8; + break; + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + flags = SPARC_RET_INT128; + break; + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + flags = SPARC_RET_INT64; + break; + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + flags = SP_V8_RET_CPLX16; + break; + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + flags = SP_V8_RET_CPLX8; + break; + default: + abort(); + } + break; + default: + abort(); + } + cif->flags = flags; + + bytes = 0; + for (i = 0, n = cif->nargs; i < n; ++i) + { + ffi_type *ty = cif->arg_types[i]; + size_t z = ty->size; + int tt = ty->type; + + switch (tt) + { + case FFI_TYPE_STRUCT: + case FFI_TYPE_LONGDOUBLE: + by_reference: + /* Passed by reference. */ + z = 4; + break; + + case FFI_TYPE_COMPLEX: + tt = ty->elements[0]->type; + if (tt == FFI_TYPE_FLOAT || z > 8) + goto by_reference; + /* FALLTHRU */ + + default: + z = FFI_ALIGN(z, 4); + } + bytes += z; + } + + /* Sparc call frames require that space is allocated for 6 args, + even if they aren't used. Make that space if necessary. */ + if (bytes < 6 * 4) + bytes = 6 * 4; + + /* The ABI always requires space for the struct return pointer. */ + bytes += 4; + + /* The stack must be 2 word aligned, so round bytes up appropriately. */ + bytes = FFI_ALIGN(bytes, 2 * 4); + + /* Include the call frame to prep_args. */ + bytes += 4*16 + 4*8; + cif->bytes = bytes; + + return FFI_OK; +} + +extern void ffi_call_v8(ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, size_t bytes, void *closure) FFI_HIDDEN; + +int FFI_HIDDEN +ffi_prep_args_v8(ffi_cif *cif, unsigned long *argp, void *rvalue, void **avalue) +{ + ffi_type **p_arg; + int flags = cif->flags; + int i, nargs; + + if (rvalue == NULL) + { + if ((flags & SPARC_FLAG_RET_MASK) == SPARC_RET_STRUCT) + { + /* Since we pass the pointer to the callee, we need a value. + We allowed for this space in ffi_call, before ffi_call_v8 + alloca'd the space. */ + rvalue = (char *)argp + cif->bytes; + } + else + { + /* Otherwise, we can ignore the return value. */ + flags = SPARC_RET_VOID; + } + } + + /* This could only really be done when we are returning a structure. + However, the space is reserved so we can do it unconditionally. */ + *argp++ = (unsigned long)rvalue; + +#ifdef USING_PURIFY + /* Purify will probably complain in our assembly routine, + unless we zero out this memory. */ + memset(argp, 0, 6*4); +#endif + + p_arg = cif->arg_types; + for (i = 0, nargs = cif->nargs; i < nargs; i++) + { + ffi_type *ty = p_arg[i]; + void *a = avalue[i]; + int tt = ty->type; + size_t z; + + switch (tt) + { + case FFI_TYPE_STRUCT: + case FFI_TYPE_LONGDOUBLE: + by_reference: + *argp++ = (unsigned long)a; + break; + + case FFI_TYPE_DOUBLE: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + memcpy(argp, a, 8); + argp += 2; + break; + + case FFI_TYPE_INT: + case FFI_TYPE_FLOAT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_POINTER: + *argp++ = *(unsigned *)a; + break; + + case FFI_TYPE_UINT8: + *argp++ = *(UINT8 *)a; + break; + case FFI_TYPE_SINT8: + *argp++ = *(SINT8 *)a; + break; + case FFI_TYPE_UINT16: + *argp++ = *(UINT16 *)a; + break; + case FFI_TYPE_SINT16: + *argp++ = *(SINT16 *)a; + break; + + case FFI_TYPE_COMPLEX: + tt = ty->elements[0]->type; + z = ty->size; + if (tt == FFI_TYPE_FLOAT || z > 8) + goto by_reference; + if (z < 4) + { + memcpy((char *)argp + 4 - z, a, z); + argp++; + } + else + { + memcpy(argp, a, z); + argp += z / 4; + } + break; + + default: + abort(); + } + } + + return flags; +} + +static void +ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + size_t bytes = cif->bytes; + + FFI_ASSERT (cif->abi == FFI_V8); + + /* If we've not got a return value, we need to create one if we've + got to pass the return value to the callee. Otherwise ignore it. */ + if (rvalue == NULL + && (cif->flags & SPARC_FLAG_RET_MASK) == SPARC_RET_STRUCT) + bytes += FFI_ALIGN (cif->rtype->size, 8); + + ffi_call_v8(cif, fn, rvalue, avalue, -bytes, closure); +} + +void +ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + ffi_call_int (cif, fn, rvalue, avalue, NULL); +} + +void +ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + ffi_call_int (cif, fn, rvalue, avalue, closure); +} + +#ifdef __GNUC__ +static inline void +ffi_flush_icache (void *p) +{ + /* SPARC v8 requires 5 instructions for flush to be visible */ + asm volatile ("iflush %0; iflush %0+8; nop; nop; nop; nop; nop" + : : "r" (p) : "memory"); +} +#else +extern void ffi_flush_icache (void *) FFI_HIDDEN; +#endif + +extern void ffi_closure_v8(void) FFI_HIDDEN; +extern void ffi_go_closure_v8(void) FFI_HIDDEN; + +ffi_status +ffi_prep_closure_loc (ffi_closure *closure, + ffi_cif *cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + unsigned int *tramp = (unsigned int *) &closure->tramp[0]; + unsigned long ctx = (unsigned long) closure; + unsigned long fn = (unsigned long) ffi_closure_v8; + + if (cif->abi != FFI_V8) + return FFI_BAD_ABI; + + tramp[0] = 0x03000000 | fn >> 10; /* sethi %hi(fn), %g1 */ + tramp[1] = 0x05000000 | ctx >> 10; /* sethi %hi(ctx), %g2 */ + tramp[2] = 0x81c06000 | (fn & 0x3ff); /* jmp %g1+%lo(fn) */ + tramp[3] = 0x8410a000 | (ctx & 0x3ff);/* or %g2, %lo(ctx) */ + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + ffi_flush_icache (closure); + + return FFI_OK; +} + +ffi_status +ffi_prep_go_closure (ffi_go_closure *closure, ffi_cif *cif, + void (*fun)(ffi_cif*, void*, void**, void*)) +{ + if (cif->abi != FFI_V8) + return FFI_BAD_ABI; + + closure->tramp = ffi_go_closure_v8; + closure->cif = cif; + closure->fun = fun; + + return FFI_OK; +} + +int FFI_HIDDEN +ffi_closure_sparc_inner_v8(ffi_cif *cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, void *rvalue, + unsigned long *argp) +{ + ffi_type **arg_types; + void **avalue; + int i, nargs, flags; + + arg_types = cif->arg_types; + nargs = cif->nargs; + flags = cif->flags; + avalue = alloca(nargs * sizeof(void *)); + + /* Copy the caller's structure return address so that the closure + returns the data directly to the caller. Also install it so we + can return the address in %o0. */ + if ((flags & SPARC_FLAG_RET_MASK) == SPARC_RET_STRUCT) + { + void *new_rvalue = (void *)*argp; + *(void **)rvalue = new_rvalue; + rvalue = new_rvalue; + } + + /* Always skip the structure return address. */ + argp++; + + /* Grab the addresses of the arguments from the stack frame. */ + for (i = 0; i < nargs; i++) + { + ffi_type *ty = arg_types[i]; + int tt = ty->type; + void *a = argp; + size_t z; + + switch (tt) + { + case FFI_TYPE_STRUCT: + case FFI_TYPE_LONGDOUBLE: + by_reference: + /* Straight copy of invisible reference. */ + a = (void *)*argp; + break; + + case FFI_TYPE_DOUBLE: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + if ((unsigned long)a & 7) + { + /* Align on a 8-byte boundary. */ + UINT64 *tmp = alloca(8); + *tmp = ((UINT64)argp[0] << 32) | argp[1]; + a = tmp; + } + argp++; + break; + + case FFI_TYPE_INT: + case FFI_TYPE_FLOAT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_POINTER: + break; + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + a += 2; + break; + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + a += 3; + break; + + case FFI_TYPE_COMPLEX: + tt = ty->elements[0]->type; + z = ty->size; + if (tt == FFI_TYPE_FLOAT || z > 8) + goto by_reference; + if (z < 4) + a += 4 - z; + else if (z > 4) + argp++; + break; + + default: + abort(); + } + argp++; + avalue[i] = a; + } + + /* Invoke the closure. */ + fun (cif, rvalue, avalue, user_data); + + /* Tell ffi_closure_sparc how to perform return type promotions. */ + return flags; +} +#endif /* !SPARC64 */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/ffi64.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/ffi64.c new file mode 100644 index 0000000..9e04061 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/ffi64.c @@ -0,0 +1,608 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2011, 2013 Anthony Green + Copyright (c) 1996, 2003-2004, 2007-2008 Red Hat, Inc. + + SPARC Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include +#include +#include "internal.h" + +/* Force FFI_TYPE_LONGDOUBLE to be different than FFI_TYPE_DOUBLE; + all further uses in this file will refer to the 128-bit type. */ +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE +# if FFI_TYPE_LONGDOUBLE != 4 +# error FFI_TYPE_LONGDOUBLE out of date +# endif +#else +# undef FFI_TYPE_LONGDOUBLE +# define FFI_TYPE_LONGDOUBLE 4 +#endif + +#ifdef SPARC64 + +/* Flatten the contents of a structure to the parts that are passed in + floating point registers. The return is a bit mask wherein bit N + set means bytes [4*n, 4*n+3] are passed in %fN. + + We encode both the (running) size (maximum 32) and mask (maxumum 255) + into one integer. The size is placed in the low byte, so that align + and addition work correctly. The mask is placed in the second byte. */ + +static int +ffi_struct_float_mask (ffi_type *outer_type, int size_mask) +{ + ffi_type **elts; + ffi_type *t; + + if (outer_type->type == FFI_TYPE_COMPLEX) + { + int m = 0, tt = outer_type->elements[0]->type; + size_t z = outer_type->size; + + if (tt == FFI_TYPE_FLOAT + || tt == FFI_TYPE_DOUBLE + || tt == FFI_TYPE_LONGDOUBLE) + m = (1 << (z / 4)) - 1; + return (m << 8) | z; + } + FFI_ASSERT (outer_type->type == FFI_TYPE_STRUCT); + + for (elts = outer_type->elements; (t = *elts) != NULL; elts++) + { + size_t z = t->size; + int o, m, tt; + + size_mask = FFI_ALIGN(size_mask, t->alignment); + switch (t->type) + { + case FFI_TYPE_STRUCT: + size_mask = ffi_struct_float_mask (t, size_mask); + continue; + case FFI_TYPE_COMPLEX: + tt = t->elements[0]->type; + if (tt != FFI_TYPE_FLOAT + && tt != FFI_TYPE_DOUBLE + && tt != FFI_TYPE_LONGDOUBLE) + break; + /* FALLTHRU */ + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_LONGDOUBLE: + m = (1 << (z / 4)) - 1; /* compute mask for type */ + o = (size_mask >> 2) & 0x3f; /* extract word offset */ + size_mask |= m << (o + 8); /* insert mask into place */ + break; + } + size_mask += z; + } + + size_mask = FFI_ALIGN(size_mask, outer_type->alignment); + FFI_ASSERT ((size_mask & 0xff) == outer_type->size); + + return size_mask; +} + +/* Merge floating point data into integer data. If the structure is + entirely floating point, simply return a pointer to the fp data. */ + +static void * +ffi_struct_float_merge (int size_mask, void *vi, void *vf) +{ + int size = size_mask & 0xff; + int mask = size_mask >> 8; + int n = size >> 2; + + if (mask == 0) + return vi; + else if (mask == (1 << n) - 1) + return vf; + else + { + unsigned int *wi = vi, *wf = vf; + int i; + + for (i = 0; i < n; ++i) + if ((mask >> i) & 1) + wi[i] = wf[i]; + + return vi; + } +} + +/* Similar, but place the data into VD in the end. */ + +void FFI_HIDDEN +ffi_struct_float_copy (int size_mask, void *vd, void *vi, void *vf) +{ + int size = size_mask & 0xff; + int mask = size_mask >> 8; + int n = size >> 2; + + if (mask == 0) + ; + else if (mask == (1 << n) - 1) + vi = vf; + else + { + unsigned int *wd = vd, *wi = vi, *wf = vf; + int i; + + for (i = 0; i < n; ++i) + wd[i] = ((mask >> i) & 1 ? wf : wi)[i]; + return; + } + memcpy (vd, vi, size); +} + +/* Perform machine dependent cif processing */ + +static ffi_status +ffi_prep_cif_machdep_core(ffi_cif *cif) +{ + ffi_type *rtype = cif->rtype; + int rtt = rtype->type; + size_t bytes = 0; + int i, n, flags; + + /* Set the return type flag */ + switch (rtt) + { + case FFI_TYPE_VOID: + flags = SPARC_RET_VOID; + break; + case FFI_TYPE_FLOAT: + flags = SPARC_RET_F_1; + break; + case FFI_TYPE_DOUBLE: + flags = SPARC_RET_F_2; + break; + case FFI_TYPE_LONGDOUBLE: + flags = SPARC_RET_F_4; + break; + + case FFI_TYPE_COMPLEX: + case FFI_TYPE_STRUCT: + if (rtype->size > 32) + { + flags = SPARC_RET_VOID | SPARC_FLAG_RET_IN_MEM; + bytes = 8; + } + else + { + int size_mask = ffi_struct_float_mask (rtype, 0); + int word_size = (size_mask >> 2) & 0x3f; + int all_mask = (1 << word_size) - 1; + int fp_mask = size_mask >> 8; + + flags = (size_mask << SPARC_SIZEMASK_SHIFT) | SPARC_RET_STRUCT; + + /* For special cases of all-int or all-fp, we can return + the value directly without popping through a struct copy. */ + if (fp_mask == 0) + { + if (rtype->alignment >= 8) + { + if (rtype->size == 8) + flags = SPARC_RET_INT64; + else if (rtype->size == 16) + flags = SPARC_RET_INT128; + } + } + else if (fp_mask == all_mask) + switch (word_size) + { + case 1: flags = SPARC_RET_F_1; break; + case 2: flags = SPARC_RET_F_2; break; + case 3: flags = SP_V9_RET_F_3; break; + case 4: flags = SPARC_RET_F_4; break; + /* 5 word structures skipped; handled via RET_STRUCT. */ + case 6: flags = SPARC_RET_F_6; break; + /* 7 word structures skipped; handled via RET_STRUCT. */ + case 8: flags = SPARC_RET_F_8; break; + } + } + break; + + case FFI_TYPE_SINT8: + flags = SPARC_RET_SINT8; + break; + case FFI_TYPE_UINT8: + flags = SPARC_RET_UINT8; + break; + case FFI_TYPE_SINT16: + flags = SPARC_RET_SINT16; + break; + case FFI_TYPE_UINT16: + flags = SPARC_RET_UINT16; + break; + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + flags = SP_V9_RET_SINT32; + break; + case FFI_TYPE_UINT32: + flags = SPARC_RET_UINT32; + break; + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_POINTER: + flags = SPARC_RET_INT64; + break; + + default: + abort(); + } + + bytes = 0; + for (i = 0, n = cif->nargs; i < n; ++i) + { + ffi_type *ty = cif->arg_types[i]; + size_t z = ty->size; + size_t a = ty->alignment; + + switch (ty->type) + { + case FFI_TYPE_COMPLEX: + case FFI_TYPE_STRUCT: + /* Large structs passed by reference. */ + if (z > 16) + { + a = z = 8; + break; + } + /* Small structs may be passed in integer or fp regs or both. */ + if (bytes >= 16*8) + break; + if ((ffi_struct_float_mask (ty, 0) & 0xff00) == 0) + break; + /* FALLTHRU */ + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_LONGDOUBLE: + flags |= SPARC_FLAG_FP_ARGS; + break; + } + bytes = FFI_ALIGN(bytes, a); + bytes += FFI_ALIGN(z, 8); + } + + /* Sparc call frames require that space is allocated for 6 args, + even if they aren't used. Make that space if necessary. */ + if (bytes < 6 * 8) + bytes = 6 * 8; + + /* The stack must be 2 word aligned, so round bytes up appropriately. */ + bytes = FFI_ALIGN(bytes, 16); + + /* Include the call frame to prep_args. */ + bytes += 8*16 + 8*8; + + cif->bytes = bytes; + cif->flags = flags; + return FFI_OK; +} + +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep(ffi_cif *cif) +{ + cif->nfixedargs = cif->nargs; + return ffi_prep_cif_machdep_core(cif); +} + +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep_var(ffi_cif *cif, unsigned nfixedargs, unsigned ntotalargs) +{ + cif->nfixedargs = nfixedargs; + return ffi_prep_cif_machdep_core(cif); +} + +extern void ffi_call_v9(ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, size_t bytes, void *closure) FFI_HIDDEN; + +/* ffi_prep_args is called by the assembly routine once stack space + has been allocated for the function's arguments */ + +int FFI_HIDDEN +ffi_prep_args_v9(ffi_cif *cif, unsigned long *argp, void *rvalue, void **avalue) +{ + ffi_type **p_arg; + int flags = cif->flags; + int i, nargs; + + if (rvalue == NULL) + { + if (flags & SPARC_FLAG_RET_IN_MEM) + { + /* Since we pass the pointer to the callee, we need a value. + We allowed for this space in ffi_call, before ffi_call_v8 + alloca'd the space. */ + rvalue = (char *)argp + cif->bytes; + } + else + { + /* Otherwise, we can ignore the return value. */ + flags = SPARC_RET_VOID; + } + } + +#ifdef USING_PURIFY + /* Purify will probably complain in our assembly routine, + unless we zero out this memory. */ + memset(argp, 0, 6*8); +#endif + + if (flags & SPARC_FLAG_RET_IN_MEM) + *argp++ = (unsigned long)rvalue; + + p_arg = cif->arg_types; + for (i = 0, nargs = cif->nargs; i < nargs; i++) + { + ffi_type *ty = p_arg[i]; + void *a = avalue[i]; + size_t z; + + switch (ty->type) + { + case FFI_TYPE_SINT8: + *argp++ = *(SINT8 *)a; + break; + case FFI_TYPE_UINT8: + *argp++ = *(UINT8 *)a; + break; + case FFI_TYPE_SINT16: + *argp++ = *(SINT16 *)a; + break; + case FFI_TYPE_UINT16: + *argp++ = *(UINT16 *)a; + break; + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + *argp++ = *(SINT32 *)a; + break; + case FFI_TYPE_UINT32: + case FFI_TYPE_FLOAT: + *argp++ = *(UINT32 *)a; + break; + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_POINTER: + case FFI_TYPE_DOUBLE: + *argp++ = *(UINT64 *)a; + break; + + case FFI_TYPE_LONGDOUBLE: + case FFI_TYPE_COMPLEX: + case FFI_TYPE_STRUCT: + z = ty->size; + if (z > 16) + { + /* For structures larger than 16 bytes we pass reference. */ + *argp++ = (unsigned long)a; + break; + } + if (((unsigned long)argp & 15) && ty->alignment > 8) + argp++; + memcpy(argp, a, z); + argp += FFI_ALIGN(z, 8) / 8; + break; + + default: + abort(); + } + } + + return flags; +} + +static void +ffi_call_int(ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + size_t bytes = cif->bytes; + + FFI_ASSERT (cif->abi == FFI_V9); + + if (rvalue == NULL && (cif->flags & SPARC_FLAG_RET_IN_MEM)) + bytes += FFI_ALIGN (cif->rtype->size, 16); + + ffi_call_v9(cif, fn, rvalue, avalue, -bytes, closure); +} + +void +ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + ffi_call_int(cif, fn, rvalue, avalue, NULL); +} + +void +ffi_call_go(ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + ffi_call_int(cif, fn, rvalue, avalue, closure); +} + +#ifdef __GNUC__ +static inline void +ffi_flush_icache (void *p) +{ + asm volatile ("flush %0; flush %0+8" : : "r" (p) : "memory"); +} +#else +extern void ffi_flush_icache (void *) FFI_HIDDEN; +#endif + +extern void ffi_closure_v9(void) FFI_HIDDEN; +extern void ffi_go_closure_v9(void) FFI_HIDDEN; + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + unsigned int *tramp = (unsigned int *) &closure->tramp[0]; + unsigned long fn; + + if (cif->abi != FFI_V9) + return FFI_BAD_ABI; + + /* Trampoline address is equal to the closure address. We take advantage + of that to reduce the trampoline size by 8 bytes. */ + fn = (unsigned long) ffi_closure_v9; + tramp[0] = 0x83414000; /* rd %pc, %g1 */ + tramp[1] = 0xca586010; /* ldx [%g1+16], %g5 */ + tramp[2] = 0x81c14000; /* jmp %g5 */ + tramp[3] = 0x01000000; /* nop */ + *((unsigned long *) &tramp[4]) = fn; + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + ffi_flush_icache (closure); + + return FFI_OK; +} + +ffi_status +ffi_prep_go_closure (ffi_go_closure* closure, ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*)) +{ + if (cif->abi != FFI_V9) + return FFI_BAD_ABI; + + closure->tramp = ffi_go_closure_v9; + closure->cif = cif; + closure->fun = fun; + + return FFI_OK; +} + +int FFI_HIDDEN +ffi_closure_sparc_inner_v9(ffi_cif *cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, void *rvalue, + unsigned long *gpr, unsigned long *fpr) +{ + ffi_type **arg_types; + void **avalue; + int i, argn, argx, nargs, flags, nfixedargs; + + arg_types = cif->arg_types; + nargs = cif->nargs; + flags = cif->flags; + nfixedargs = cif->nfixedargs; + + avalue = alloca(nargs * sizeof(void *)); + + /* Copy the caller's structure return address so that the closure + returns the data directly to the caller. */ + if (flags & SPARC_FLAG_RET_IN_MEM) + { + rvalue = (void *) gpr[0]; + /* Skip the structure return address. */ + argn = 1; + } + else + argn = 0; + + /* Grab the addresses of the arguments from the stack frame. */ + for (i = 0; i < nargs; i++, argn = argx) + { + int named = i < nfixedargs; + ffi_type *ty = arg_types[i]; + void *a = &gpr[argn]; + size_t z; + + argx = argn + 1; + switch (ty->type) + { + case FFI_TYPE_COMPLEX: + case FFI_TYPE_STRUCT: + z = ty->size; + if (z > 16) + a = *(void **)a; + else + { + argx = argn + FFI_ALIGN (z, 8) / 8; + if (named && argn < 16) + { + int size_mask = ffi_struct_float_mask (ty, 0); + int argn_mask = (0xffff00 >> argn) & 0xff00; + + /* Eliminate fp registers off the end. */ + size_mask = (size_mask & 0xff) | (size_mask & argn_mask); + a = ffi_struct_float_merge (size_mask, gpr+argn, fpr+argn); + } + } + break; + + case FFI_TYPE_LONGDOUBLE: + argn = FFI_ALIGN (argn, 2); + a = (named && argn < 16 ? fpr : gpr) + argn; + argx = argn + 2; + break; + case FFI_TYPE_DOUBLE: + if (named && argn < 16) + a = fpr + argn; + break; + case FFI_TYPE_FLOAT: + if (named && argn < 16) + a = fpr + argn; + a += 4; + break; + + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_POINTER: + break; + case FFI_TYPE_INT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + a += 4; + break; + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + a += 6; + break; + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + a += 7; + break; + + default: + abort(); + } + avalue[i] = a; + } + + /* Invoke the closure. */ + fun (cif, rvalue, avalue, user_data); + + /* Tell ffi_closure_sparc how to perform return type promotions. */ + return flags; +} +#endif /* SPARC64 */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/ffitarget.h new file mode 100644 index 0000000..2f4cd9a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/ffitarget.h @@ -0,0 +1,81 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Anthony Green + Copyright (c) 1996-2003 Red Hat, Inc. + Target configuration macros for SPARC. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +/* ---- System specific configurations ----------------------------------- */ + +#if defined(__arch64__) || defined(__sparcv9) +#ifndef SPARC64 +#define SPARC64 +#endif +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, +#ifdef SPARC64 + FFI_V9, + FFI_DEFAULT_ABI = FFI_V9, +#else + FFI_V8, + FFI_DEFAULT_ABI = FFI_V8, +#endif + FFI_LAST_ABI +} ffi_abi; +#endif + +#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION 1 +#define FFI_TARGET_HAS_COMPLEX_TYPE 1 + +#ifdef SPARC64 +# define FFI_TARGET_SPECIFIC_VARIADIC 1 +# define FFI_EXTRA_CIF_FIELDS unsigned int nfixedargs +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_GO_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 + +#ifdef SPARC64 +#define FFI_TRAMPOLINE_SIZE 24 +#else +#define FFI_TRAMPOLINE_SIZE 16 +#endif + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/internal.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/internal.h new file mode 100644 index 0000000..0a66472 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/internal.h @@ -0,0 +1,26 @@ +#define SPARC_RET_VOID 0 +#define SPARC_RET_STRUCT 1 +#define SPARC_RET_UINT8 2 +#define SPARC_RET_SINT8 3 +#define SPARC_RET_UINT16 4 +#define SPARC_RET_SINT16 5 +#define SPARC_RET_UINT32 6 +#define SP_V9_RET_SINT32 7 /* v9 only */ +#define SP_V8_RET_CPLX16 7 /* v8 only */ +#define SPARC_RET_INT64 8 +#define SPARC_RET_INT128 9 + +/* Note that F_7 is missing, and is handled by SPARC_RET_STRUCT. */ +#define SPARC_RET_F_8 10 +#define SPARC_RET_F_6 11 +#define SPARC_RET_F_4 12 +#define SPARC_RET_F_2 13 +#define SP_V9_RET_F_3 14 /* v9 only */ +#define SP_V8_RET_CPLX8 14 /* v8 only */ +#define SPARC_RET_F_1 15 + +#define SPARC_FLAG_RET_MASK 15 +#define SPARC_FLAG_RET_IN_MEM 32 +#define SPARC_FLAG_FP_ARGS 64 + +#define SPARC_SIZEMASK_SHIFT 8 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/v8.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/v8.S new file mode 100644 index 0000000..a2e4908 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/v8.S @@ -0,0 +1,443 @@ +/* ----------------------------------------------------------------------- + v8.S - Copyright (c) 2013 The Written Word, Inc. + Copyright (c) 1996, 1997, 2003, 2004, 2008 Red Hat, Inc. + + SPARC Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include +#include "internal.h" + +#ifndef SPARC64 + +#define C2(X, Y) X ## Y +#define C1(X, Y) C2(X, Y) + +#ifdef __USER_LABEL_PREFIX__ +# define C(Y) C1(__USER_LABEL_PREFIX__, Y) +#else +# define C(Y) Y +#endif +#define L(Y) C1(.L, Y) + + .text + +#ifndef __GNUC__ + .align 8 + .globl C(ffi_flush_icache) + .type C(ffi_flush_icache),#function + FFI_HIDDEN(C(ffi_flush_icache)) + +C(ffi_flush_icache): +1: iflush %o0 + iflush %o+8 + nop + nop + nop + nop + nop + retl + nop + .size C(ffi_flush_icache), . - C(ffi_flush_icache) +#endif + +#if defined(__sun__) && defined(__svr4__) +# define E(INDEX) .align 16 +#else +# define E(INDEX) .align 16; .org 2b + INDEX * 16 +#endif + + .align 8 + .globl C(ffi_call_v8) + .type C(ffi_call_v8),#function + FFI_HIDDEN(C(ffi_call_v8)) + +C(ffi_call_v8): +.LUW0: + ! Allocate a stack frame sized by ffi_call. + save %sp, %o4, %sp +.LUW1: + mov %i0, %o0 ! copy cif + add %sp, 64+32, %o1 ! load args area + mov %i2, %o2 ! copy rvalue + call C(ffi_prep_args_v8) + mov %i3, %o3 ! copy avalue + + add %sp, 32, %sp ! deallocate prep frame + and %o0, SPARC_FLAG_RET_MASK, %l0 ! save return type + srl %o0, SPARC_SIZEMASK_SHIFT, %l1 ! save return size + ld [%sp+64+4], %o0 ! load all argument registers + ld [%sp+64+8], %o1 + ld [%sp+64+12], %o2 + ld [%sp+64+16], %o3 + cmp %l0, SPARC_RET_STRUCT ! struct return needs an unimp 4 + ld [%sp+64+20], %o4 + be 8f + ld [%sp+64+24], %o5 + + ! Call foreign function + call %i1 + mov %i5, %g2 ! load static chain + +0: call 1f ! load pc in %o7 + sll %l0, 4, %l0 +1: add %o7, %l0, %o7 ! o7 = 0b + ret_type*16 + jmp %o7+(2f-0b) + nop + + ! Note that each entry is 4 insns, enforced by the E macro. + .align 16 +2: +E(SPARC_RET_VOID) + ret + restore +E(SPARC_RET_STRUCT) + unimp +E(SPARC_RET_UINT8) + and %o0, 0xff, %o0 + st %o0, [%i2] + ret + restore +E(SPARC_RET_SINT8) + sll %o0, 24, %o0 + b 7f + sra %o0, 24, %o0 +E(SPARC_RET_UINT16) + sll %o0, 16, %o0 + b 7f + srl %o0, 16, %o0 +E(SPARC_RET_SINT16) + sll %o0, 16, %o0 + b 7f + sra %o0, 16, %o0 +E(SPARC_RET_UINT32) +7: st %o0, [%i2] + ret + restore +E(SP_V8_RET_CPLX16) + sth %o0, [%i2+2] + b 9f + srl %o0, 16, %o0 +E(SPARC_RET_INT64) + st %o0, [%i2] + st %o1, [%i2+4] + ret + restore +E(SPARC_RET_INT128) + std %o0, [%i2] + std %o2, [%i2+8] + ret + restore +E(SPARC_RET_F_8) + st %f7, [%i2+7*4] + nop + st %f6, [%i2+6*4] + nop +E(SPARC_RET_F_6) + st %f5, [%i2+5*4] + nop + st %f4, [%i2+4*4] + nop +E(SPARC_RET_F_4) + st %f3, [%i2+3*4] + nop + st %f2, [%i2+2*4] + nop +E(SPARC_RET_F_2) + st %f1, [%i2+4] + st %f0, [%i2] + ret + restore +E(SP_V8_RET_CPLX8) + stb %o0, [%i2+1] + b 0f + srl %o0, 8, %o0 +E(SPARC_RET_F_1) + st %f0, [%i2] + ret + restore + + .align 8 +9: sth %o0, [%i2] + ret + restore + .align 8 +0: stb %o0, [%i2] + ret + restore + + ! Struct returning functions expect and skip the unimp here. + ! To make it worse, conforming callees examine the unimp and + ! make sure the low 12 bits of the unimp match the size of + ! the struct being returned. + .align 8 +8: call 1f ! load pc in %o7 + sll %l1, 2, %l0 ! size * 4 +1: sll %l1, 4, %l1 ! size * 16 + add %l0, %l1, %l0 ! size * 20 + add %o7, %l0, %o7 ! o7 = 8b + size*20 + jmp %o7+(2f-8b) + mov %i5, %g2 ! load static chain +2: + +/* The Sun assembler doesn't understand .rept 0x1000. */ +#define rept1 \ + call %i1; \ + nop; \ + unimp (. - 2b) / 20; \ + ret; \ + restore + +#define rept16 \ + rept1; rept1; rept1; rept1; \ + rept1; rept1; rept1; rept1; \ + rept1; rept1; rept1; rept1; \ + rept1; rept1; rept1; rept1 + +#define rept256 \ + rept16; rept16; rept16; rept16; \ + rept16; rept16; rept16; rept16; \ + rept16; rept16; rept16; rept16; \ + rept16; rept16; rept16; rept16 + + rept256; rept256; rept256; rept256 + rept256; rept256; rept256; rept256 + rept256; rept256; rept256; rept256 + rept256; rept256; rept256; rept256 + +.LUW2: + .size C(ffi_call_v8),. - C(ffi_call_v8) + + +/* 16*4 register window + 1*4 struct return + 6*4 args backing store + + 8*4 return storage + 1*4 alignment. */ +#define STACKFRAME (16*4 + 4 + 6*4 + 8*4 + 4) + +/* ffi_closure_v8(...) + + Receives the closure argument in %g2. */ + +#ifdef HAVE_AS_REGISTER_PSEUDO_OP + .register %g2, #scratch +#endif + + .align 8 + .globl C(ffi_go_closure_v8) + .type C(ffi_go_closure_v8),#function + FFI_HIDDEN(C(ffi_go_closure_v8)) + +C(ffi_go_closure_v8): +.LUW3: + save %sp, -STACKFRAME, %sp +.LUW4: + ld [%g2+4], %o0 ! load cif + ld [%g2+8], %o1 ! load fun + b 0f + mov %g2, %o2 ! load user_data +.LUW5: + .size C(ffi_go_closure_v8), . - C(ffi_go_closure_v8) + + .align 8 + .globl C(ffi_closure_v8) + .type C(ffi_closure_v8),#function + FFI_HIDDEN(C(ffi_closure_v8)) + +C(ffi_closure_v8): +.LUW6: + save %sp, -STACKFRAME, %sp +.LUW7: + ld [%g2+FFI_TRAMPOLINE_SIZE], %o0 ! load cif + ld [%g2+FFI_TRAMPOLINE_SIZE+4], %o1 ! load fun + ld [%g2+FFI_TRAMPOLINE_SIZE+8], %o2 ! load user_data +0: + ! Store all of the potential argument registers in va_list format. + st %i0, [%fp+68+0] + st %i1, [%fp+68+4] + st %i2, [%fp+68+8] + st %i3, [%fp+68+12] + st %i4, [%fp+68+16] + st %i5, [%fp+68+20] + + ! Call ffi_closure_sparc_inner to do the bulk of the work. + add %fp, -8*4, %o3 + call ffi_closure_sparc_inner_v8 + add %fp, 64, %o4 + +0: call 1f + and %o0, SPARC_FLAG_RET_MASK, %o0 +1: sll %o0, 4, %o0 ! o0 = o0 * 16 + add %o7, %o0, %o7 ! o7 = 0b + o0*16 + jmp %o7+(2f-0b) + add %fp, -8*4, %i2 + + ! Note that each entry is 4 insns, enforced by the E macro. + .align 16 +2: +E(SPARC_RET_VOID) + ret + restore +E(SPARC_RET_STRUCT) + ld [%i2], %i0 + jmp %i7+12 + restore +E(SPARC_RET_UINT8) + ldub [%i2+3], %i0 + ret + restore +E(SPARC_RET_SINT8) + ldsb [%i2+3], %i0 + ret + restore +E(SPARC_RET_UINT16) + lduh [%i2+2], %i0 + ret + restore +E(SPARC_RET_SINT16) + ldsh [%i2+2], %i0 + ret + restore +E(SPARC_RET_UINT32) + ld [%i2], %i0 + ret + restore +E(SP_V8_RET_CPLX16) + ld [%i2], %i0 + ret + restore +E(SPARC_RET_INT64) + ldd [%i2], %i0 + ret + restore +E(SPARC_RET_INT128) + ldd [%i2], %i0 + ldd [%i2+8], %i2 + ret + restore +E(SPARC_RET_F_8) + ld [%i2+7*4], %f7 + nop + ld [%i2+6*4], %f6 + nop +E(SPARC_RET_F_6) + ld [%i2+5*4], %f5 + nop + ld [%i2+4*4], %f4 + nop +E(SPARC_RET_F_4) + ld [%i2+3*4], %f3 + nop + ld [%i2+2*4], %f2 + nop +E(SPARC_RET_F_2) + ldd [%i2], %f0 + ret + restore +E(SP_V8_RET_CPLX8) + lduh [%i2], %i0 + ret + restore +E(SPARC_RET_F_1) + ld [%i2], %f0 + ret + restore + +.LUW8: + .size C(ffi_closure_v8), . - C(ffi_closure_v8) + +#ifdef HAVE_RO_EH_FRAME + .section ".eh_frame",#alloc +#else + .section ".eh_frame",#alloc,#write +#endif + +#ifdef HAVE_AS_SPARC_UA_PCREL +# define FDE_ADDR(X) %r_disp32(X) +#else +# define FDE_ADDR(X) X +#endif + + .align 4 +.LCIE: + .long .LECIE - .LSCIE ! CIE Length +.LSCIE: + .long 0 ! CIE Identifier Tag + .byte 1 ! CIE Version + .ascii "zR\0" ! CIE Augmentation + .byte 4 ! CIE Code Alignment Factor + .byte 0x7c ! CIE Data Alignment Factor + .byte 15 ! CIE RA Column + .byte 1 ! Augmentation size +#ifdef HAVE_AS_SPARC_UA_PCREL + .byte 0x1b ! FDE Encoding (pcrel sdata4) +#else + .byte 0x50 ! FDE Encoding (aligned absolute) +#endif + .byte 0xc, 14, 0 ! DW_CFA_def_cfa, %o6, offset 0 + .align 4 +.LECIE: + + .long .LEFDE1 - .LSFDE1 ! FDE Length +.LSFDE1: + .long .LSFDE1 - .LCIE ! FDE CIE offset + .long FDE_ADDR(.LUW0) ! Initial location + .long .LUW2 - .LUW0 ! Address range + .byte 0 ! Augmentation size + .byte 0x40+1 ! DW_CFA_advance_loc 4 + .byte 0xd, 30 ! DW_CFA_def_cfa_register, %i6 + .byte 0x2d ! DW_CFA_GNU_window_save + .byte 0x9, 15, 31 ! DW_CFA_register, %o7, %i7 + .align 4 +.LEFDE1: + + .long .LEFDE2 - .LSFDE2 ! FDE Length +.LSFDE2: + .long .LSFDE2 - .LCIE ! FDE CIE offset + .long FDE_ADDR(.LUW3) ! Initial location + .long .LUW5 - .LUW3 ! Address range + .byte 0 ! Augmentation size + .byte 0x40+1 ! DW_CFA_advance_loc 4 + .byte 0xd, 30 ! DW_CFA_def_cfa_register, %i6 + .byte 0x2d ! DW_CFA_GNU_window_save + .byte 0x9, 15, 31 ! DW_CFA_register, %o7, %i7 + .align 4 +.LEFDE2: + + .long .LEFDE3 - .LSFDE3 ! FDE Length +.LSFDE3: + .long .LSFDE3 - .LCIE ! FDE CIE offset + .long FDE_ADDR(.LUW6) ! Initial location + .long .LUW8 - .LUW6 ! Address range + .byte 0 ! Augmentation size + .byte 0x40+1 ! DW_CFA_advance_loc 4 + .byte 0xd, 30 ! DW_CFA_def_cfa_register, %i6 + .byte 0x2d ! DW_CFA_GNU_window_save + .byte 0x9, 15, 31 ! DW_CFA_register, %o7, %i7 + .align 4 +.LEFDE3: + +#endif /* !SPARC64 */ +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/v9.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/v9.S new file mode 100644 index 0000000..55f8f43 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/sparc/v9.S @@ -0,0 +1,440 @@ +/* ----------------------------------------------------------------------- + v9.S - Copyright (c) 2000, 2003, 2004, 2008 Red Hat, Inc. + + SPARC 64-bit Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include +#include "internal.h" + +#ifdef SPARC64 + +#define C2(X, Y) X ## Y +#define C1(X, Y) C2(X, Y) + +#ifdef __USER_LABEL_PREFIX__ +# define C(Y) C1(__USER_LABEL_PREFIX__, Y) +#else +# define C(Y) Y +#endif +#define L(Y) C1(.L, Y) + +#if defined(__sun__) && defined(__svr4__) +# define E(INDEX) .align 16 +#else +# define E(INDEX) .align 16; .org 2b + INDEX * 16 +#endif + +#define STACK_BIAS 2047 + + .text + .align 8 + .globl C(ffi_call_v9) + .type C(ffi_call_v9),#function + FFI_HIDDEN(C(ffi_call_v9)) + +C(ffi_call_v9): +.LUW0: + save %sp, %o4, %sp +.LUW1: + mov %i0, %o0 ! copy cif + add %sp, STACK_BIAS+128+48, %o1 ! load args area + mov %i2, %o2 ! copy rvalue + call C(ffi_prep_args_v9) + mov %i3, %o3 ! copy avalue + + andcc %o0, SPARC_FLAG_FP_ARGS, %g0 ! need fp regs? + add %sp, 48, %sp ! deallocate prep frame + be,pt %xcc, 1f + mov %o0, %l0 ! save flags + + ldd [%sp+STACK_BIAS+128], %f0 ! load all fp arg regs + ldd [%sp+STACK_BIAS+128+8], %f2 + ldd [%sp+STACK_BIAS+128+16], %f4 + ldd [%sp+STACK_BIAS+128+24], %f6 + ldd [%sp+STACK_BIAS+128+32], %f8 + ldd [%sp+STACK_BIAS+128+40], %f10 + ldd [%sp+STACK_BIAS+128+48], %f12 + ldd [%sp+STACK_BIAS+128+56], %f14 + ldd [%sp+STACK_BIAS+128+64], %f16 + ldd [%sp+STACK_BIAS+128+72], %f18 + ldd [%sp+STACK_BIAS+128+80], %f20 + ldd [%sp+STACK_BIAS+128+88], %f22 + ldd [%sp+STACK_BIAS+128+96], %f24 + ldd [%sp+STACK_BIAS+128+104], %f26 + ldd [%sp+STACK_BIAS+128+112], %f28 + ldd [%sp+STACK_BIAS+128+120], %f30 + +1: ldx [%sp+STACK_BIAS+128], %o0 ! load all int arg regs + ldx [%sp+STACK_BIAS+128+8], %o1 + ldx [%sp+STACK_BIAS+128+16], %o2 + ldx [%sp+STACK_BIAS+128+24], %o3 + ldx [%sp+STACK_BIAS+128+32], %o4 + ldx [%sp+STACK_BIAS+128+40], %o5 + call %i1 + mov %i5, %g5 ! load static chain + +0: call 1f ! load pc in %o7 + and %l0, SPARC_FLAG_RET_MASK, %l1 +1: sll %l1, 4, %l1 + add %o7, %l1, %o7 ! o7 = 0b + ret_type*16 + jmp %o7+(2f-0b) + nop + + .align 16 +2: +E(SPARC_RET_VOID) + return %i7+8 + nop +E(SPARC_RET_STRUCT) + add %sp, STACK_BIAS-64+128+48, %l2 + sub %sp, 64, %sp + b 8f + stx %o0, [%l2] +E(SPARC_RET_UINT8) + and %o0, 0xff, %i0 + return %i7+8 + stx %o0, [%o2] +E(SPARC_RET_SINT8) + sll %o0, 24, %o0 + sra %o0, 24, %i0 + return %i7+8 + stx %o0, [%o2] +E(SPARC_RET_UINT16) + sll %o0, 16, %o0 + srl %o0, 16, %i0 + return %i7+8 + stx %o0, [%o2] +E(SPARC_RET_SINT16) + sll %o0, 16, %o0 + sra %o0, 16, %i0 + return %i7+8 + stx %o0, [%o2] +E(SPARC_RET_UINT32) + srl %o0, 0, %i0 + return %i7+8 + stx %o0, [%o2] +E(SP_V9_RET_SINT32) + sra %o0, 0, %i0 + return %i7+8 + stx %o0, [%o2] +E(SPARC_RET_INT64) + stx %o0, [%i2] + return %i7+8 + nop +E(SPARC_RET_INT128) + stx %o0, [%i2] + stx %o1, [%i2+8] + return %i7+8 + nop +E(SPARC_RET_F_8) + st %f7, [%i2+7*4] + nop + st %f6, [%i2+6*4] + nop +E(SPARC_RET_F_6) + st %f5, [%i2+5*4] + nop + st %f4, [%i2+4*4] + nop +E(SPARC_RET_F_4) + std %f2, [%i2+2*4] + return %i7+8 + std %f0, [%o2] +E(SPARC_RET_F_2) + return %i7+8 + std %f0, [%o2] +E(SP_V9_RET_F_3) + st %f2, [%i2+2*4] + nop + st %f1, [%i2+1*4] + nop +E(SPARC_RET_F_1) + return %i7+8 + st %f0, [%o2] + + ! Finish the SPARC_RET_STRUCT sequence. + .align 8 +8: stx %o1, [%l2+8] + stx %o2, [%l2+16] + stx %o3, [%l2+24] + std %f0, [%l2+32] + std %f2, [%l2+40] + std %f4, [%l2+48] + std %f6, [%l2+56] + + ! Copy the structure into place. + srl %l0, SPARC_SIZEMASK_SHIFT, %o0 ! load size_mask + mov %i2, %o1 ! load dst + mov %l2, %o2 ! load src_gp + call C(ffi_struct_float_copy) + add %l2, 32, %o3 ! load src_fp + + return %i7+8 + nop + +.LUW2: + .size C(ffi_call_v9), . - C(ffi_call_v9) + + +#undef STACKFRAME +#define STACKFRAME 336 /* 16*8 register window + + 6*8 args backing store + + 20*8 locals */ +#define FP %fp+STACK_BIAS + +/* ffi_closure_v9(...) + + Receives the closure argument in %g1. */ + + .align 8 + .globl C(ffi_go_closure_v9) + .type C(ffi_go_closure_v9),#function + FFI_HIDDEN(C(ffi_go_closure_v9)) + +C(ffi_go_closure_v9): +.LUW3: + save %sp, -STACKFRAME, %sp +.LUW4: + ldx [%g5+8], %o0 + ldx [%g5+16], %o1 + b 0f + mov %g5, %o2 + +.LUW5: + .size C(ffi_go_closure_v9), . - C(ffi_go_closure_v9) + + .align 8 + .globl C(ffi_closure_v9) + .type C(ffi_closure_v9),#function + FFI_HIDDEN(C(ffi_closure_v9)) + +C(ffi_closure_v9): +.LUW6: + save %sp, -STACKFRAME, %sp +.LUW7: + ldx [%g1+FFI_TRAMPOLINE_SIZE], %o0 + ldx [%g1+FFI_TRAMPOLINE_SIZE+8], %o1 + ldx [%g1+FFI_TRAMPOLINE_SIZE+16], %o2 +0: + ! Store all of the potential argument registers in va_list format. + stx %i0, [FP+128+0] + stx %i1, [FP+128+8] + stx %i2, [FP+128+16] + stx %i3, [FP+128+24] + stx %i4, [FP+128+32] + stx %i5, [FP+128+40] + + ! Store possible floating point argument registers too. + std %f0, [FP-128] + std %f2, [FP-120] + std %f4, [FP-112] + std %f6, [FP-104] + std %f8, [FP-96] + std %f10, [FP-88] + std %f12, [FP-80] + std %f14, [FP-72] + std %f16, [FP-64] + std %f18, [FP-56] + std %f20, [FP-48] + std %f22, [FP-40] + std %f24, [FP-32] + std %f26, [FP-24] + std %f28, [FP-16] + std %f30, [FP-8] + + ! Call ffi_closure_sparc_inner to do the bulk of the work. + add %fp, STACK_BIAS-160, %o3 + add %fp, STACK_BIAS+128, %o4 + call C(ffi_closure_sparc_inner_v9) + add %fp, STACK_BIAS-128, %o5 + +0: call 1f ! load pc in %o7 + and %o0, SPARC_FLAG_RET_MASK, %o0 +1: sll %o0, 4, %o0 ! o2 = i2 * 16 + add %o7, %o0, %o7 ! o7 = 0b + i2*16 + jmp %o7+(2f-0b) + nop + + ! Note that we cannot load the data in the delay slot of + ! the return insn because the data is in the stack frame + ! that is deallocated by the return. + .align 16 +2: +E(SPARC_RET_VOID) + return %i7+8 + nop +E(SPARC_RET_STRUCT) + ldx [FP-160], %i0 + ldd [FP-160], %f0 + b 8f + ldx [FP-152], %i1 +E(SPARC_RET_UINT8) + ldub [FP-160+7], %i0 + return %i7+8 + nop +E(SPARC_RET_SINT8) + ldsb [FP-160+7], %i0 + return %i7+8 + nop +E(SPARC_RET_UINT16) + lduh [FP-160+6], %i0 + return %i7+8 + nop +E(SPARC_RET_SINT16) + ldsh [FP-160+6], %i0 + return %i7+8 + nop +E(SPARC_RET_UINT32) + lduw [FP-160+4], %i0 + return %i7+8 + nop +E(SP_V9_RET_SINT32) + ldsw [FP-160+4], %i0 + return %i7+8 + nop +E(SPARC_RET_INT64) + ldx [FP-160], %i0 + return %i7+8 + nop +E(SPARC_RET_INT128) + ldx [FP-160], %i0 + ldx [FP-160+8], %i1 + return %i7+8 + nop +E(SPARC_RET_F_8) + ld [FP-160+7*4], %f7 + nop + ld [FP-160+6*4], %f6 + nop +E(SPARC_RET_F_6) + ld [FP-160+5*4], %f5 + nop + ld [FP-160+4*4], %f4 + nop +E(SPARC_RET_F_4) + ldd [FP-160], %f0 + ldd [FP-160+8], %f2 + return %i7+8 + nop +E(SPARC_RET_F_2) + ldd [FP-160], %f0 + return %i7+8 + nop +E(SP_V9_RET_F_3) + ld [FP-160+2*4], %f2 + nop + ld [FP-160+1*4], %f1 + nop +E(SPARC_RET_F_1) + ld [FP-160], %f0 + return %i7+8 + nop + + ! Finish the SPARC_RET_STRUCT sequence. + .align 8 +8: ldd [FP-152], %f2 + ldx [FP-144], %i2 + ldd [FP-144], %f4 + ldx [FP-136], %i3 + ldd [FP-136], %f6 + return %i7+8 + nop + +.LUW8: + .size C(ffi_closure_v9), . - C(ffi_closure_v9) + +#ifdef HAVE_RO_EH_FRAME + .section ".eh_frame",#alloc +#else + .section ".eh_frame",#alloc,#write +#endif + +#ifdef HAVE_AS_SPARC_UA_PCREL +# define FDE_RANGE(B, E) .long %r_disp32(B), E - B +#else +# define FDE_RANGE(B, E) .align 8; .xword B, E - B +#endif + + .align 8 +.LCIE: + .long .LECIE - .LSCIE ! CIE Length +.LSCIE: + .long 0 ! CIE Identifier Tag + .byte 1 ! CIE Version + .ascii "zR\0" ! CIE Augmentation + .byte 4 ! CIE Code Alignment Factor + .byte 0x78 ! CIE Data Alignment Factor + .byte 15 ! CIE RA Column + .byte 1 ! Augmentation size +#ifdef HAVE_AS_SPARC_UA_PCREL + .byte 0x1b ! FDE Encoding (pcrel sdata4) +#else + .byte 0x50 ! FDE Encoding (aligned absolute) +#endif + .byte 0xc, 14, 0xff, 0xf ! DW_CFA_def_cfa, %o6, offset 0x7ff + .align 8 +.LECIE: + + .long .LEFDE1 - .LSFDE1 ! FDE Length +.LSFDE1: + .long .LSFDE1 - .LCIE ! FDE CIE offset + FDE_RANGE(.LUW0, .LUW2) + .byte 0 ! Augmentation size + .byte 0x40+1 ! DW_CFA_advance_loc 4 + .byte 0xd, 30 ! DW_CFA_def_cfa_register, %i6 + .byte 0x2d ! DW_CFA_GNU_window_save + .byte 0x9, 15, 31 ! DW_CFA_register, %o7, %i7 + .align 8 +.LEFDE1: + + .long .LEFDE2 - .LSFDE2 ! FDE Length +.LSFDE2: + .long .LSFDE2 - .LCIE ! FDE CIE offset + FDE_RANGE(.LUW3, .LUW5) + .byte 0 ! Augmentation size + .byte 0x40+1 ! DW_CFA_advance_loc 4 + .byte 0xd, 30 ! DW_CFA_def_cfa_register, %i6 + .byte 0x2d ! DW_CFA_GNU_window_save + .byte 0x9, 15, 31 ! DW_CFA_register, %o7, %i7 + .align 8 +.LEFDE2: + + .long .LEFDE3 - .LSFDE3 ! FDE Length +.LSFDE3: + .long .LSFDE3 - .LCIE ! FDE CIE offset + FDE_RANGE(.LUW6, .LUW8) + .byte 0 ! Augmentation size + .byte 0x40+1 ! DW_CFA_advance_loc 4 + .byte 0xd, 30 ! DW_CFA_def_cfa_register, %i6 + .byte 0x2d ! DW_CFA_GNU_window_save + .byte 0x9, 15, 31 ! DW_CFA_register, %o7, %i7 + .align 8 +.LEFDE3: + +#endif /* SPARC64 */ +#ifdef __linux__ + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/tile/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/tile/ffi.c new file mode 100644 index 0000000..3a94469 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/tile/ffi.c @@ -0,0 +1,355 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2012 Tilera Corp. + + TILE Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include +#include +#include +#include +#include +#include +#include + + +/* The first 10 registers are used to pass arguments and return values. */ +#define NUM_ARG_REGS 10 + +/* Performs a raw function call with the given NUM_ARG_REGS register arguments + and the specified additional stack arguments (if any). */ +extern void ffi_call_tile(ffi_sarg reg_args[NUM_ARG_REGS], + const ffi_sarg *stack_args, + size_t stack_args_bytes, + void (*fnaddr)(void)) + FFI_HIDDEN; + +/* This handles the raw call from the closure stub, cleaning up the + parameters and delegating to ffi_closure_tile_inner. */ +extern void ffi_closure_tile(void) FFI_HIDDEN; + + +ffi_status +ffi_prep_cif_machdep(ffi_cif *cif) +{ + /* We always allocate room for all registers. Even if we don't + use them as parameters, they get returned in the same array + as struct return values so we need to make room. */ + if (cif->bytes < NUM_ARG_REGS * FFI_SIZEOF_ARG) + cif->bytes = NUM_ARG_REGS * FFI_SIZEOF_ARG; + + if (cif->rtype->size > NUM_ARG_REGS * FFI_SIZEOF_ARG) + cif->flags = FFI_TYPE_STRUCT; + else + cif->flags = FFI_TYPE_INT; + + /* Nothing to do. */ + return FFI_OK; +} + + +static long +assign_to_ffi_arg(ffi_sarg *out, void *in, const ffi_type *type, + int write_to_reg) +{ + switch (type->type) + { + case FFI_TYPE_SINT8: + *out = *(SINT8 *)in; + return 1; + + case FFI_TYPE_UINT8: + *out = *(UINT8 *)in; + return 1; + + case FFI_TYPE_SINT16: + *out = *(SINT16 *)in; + return 1; + + case FFI_TYPE_UINT16: + *out = *(UINT16 *)in; + return 1; + + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: +#ifndef __LP64__ + case FFI_TYPE_POINTER: +#endif + /* Note that even unsigned 32-bit quantities are sign extended + on tilegx when stored in a register. */ + *out = *(SINT32 *)in; + return 1; + + case FFI_TYPE_FLOAT: +#ifdef __tilegx__ + if (write_to_reg) + { + /* Properly sign extend the value. */ + union { float f; SINT32 s32; } val; + val.f = *(float *)in; + *out = val.s32; + } + else +#endif + { + *(float *)out = *(float *)in; + } + return 1; + + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + case FFI_TYPE_DOUBLE: +#ifdef __LP64__ + case FFI_TYPE_POINTER: +#endif + *(UINT64 *)out = *(UINT64 *)in; + return sizeof(UINT64) / FFI_SIZEOF_ARG; + + case FFI_TYPE_STRUCT: + memcpy(out, in, type->size); + return (type->size + FFI_SIZEOF_ARG - 1) / FFI_SIZEOF_ARG; + + case FFI_TYPE_VOID: + /* Must be a return type. Nothing to do. */ + return 0; + + default: + FFI_ASSERT(0); + return -1; + } +} + + +void +ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + ffi_sarg * const arg_mem = alloca(cif->bytes); + ffi_sarg * const reg_args = arg_mem; + ffi_sarg * const stack_args = ®_args[NUM_ARG_REGS]; + ffi_sarg *argp = arg_mem; + ffi_type ** const arg_types = cif->arg_types; + const long num_args = cif->nargs; + long i; + + if (cif->flags == FFI_TYPE_STRUCT) + { + /* Pass a hidden pointer to the return value. We make sure there + is scratch space for the callee to store the return value even if + our caller doesn't care about it. */ + *argp++ = (intptr_t)(rvalue ? rvalue : alloca(cif->rtype->size)); + + /* No more work needed to return anything. */ + rvalue = NULL; + } + + for (i = 0; i < num_args; i++) + { + ffi_type *type = arg_types[i]; + void * const arg_in = avalue[i]; + ptrdiff_t arg_word = argp - arg_mem; + +#ifndef __tilegx__ + /* Doubleword-aligned values are always in an even-number register + pair, or doubleword-aligned stack slot if out of registers. */ + long align = arg_word & (type->alignment > FFI_SIZEOF_ARG); + argp += align; + arg_word += align; +#endif + + if (type->type == FFI_TYPE_STRUCT) + { + const size_t arg_size_in_words = + (type->size + FFI_SIZEOF_ARG - 1) / FFI_SIZEOF_ARG; + + if (arg_word < NUM_ARG_REGS && + arg_word + arg_size_in_words > NUM_ARG_REGS) + { + /* Args are not allowed to span registers and the stack. */ + argp = stack_args; + } + + memcpy(argp, arg_in, type->size); + argp += arg_size_in_words; + } + else + { + argp += assign_to_ffi_arg(argp, arg_in, arg_types[i], 1); + } + } + + /* Actually do the call. */ + ffi_call_tile(reg_args, stack_args, + cif->bytes - (NUM_ARG_REGS * FFI_SIZEOF_ARG), fn); + + if (rvalue != NULL) + assign_to_ffi_arg(rvalue, reg_args, cif->rtype, 0); +} + + +/* Template code for closure. */ +extern const UINT64 ffi_template_tramp_tile[] FFI_HIDDEN; + + +ffi_status +ffi_prep_closure_loc (ffi_closure *closure, + ffi_cif *cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ +#ifdef __tilegx__ + /* TILE-Gx */ + SINT64 c; + SINT64 h; + int s; + UINT64 *out; + + if (cif->abi != FFI_UNIX) + return FFI_BAD_ABI; + + out = (UINT64 *)closure->tramp; + + c = (intptr_t)closure; + h = (intptr_t)ffi_closure_tile; + s = 0; + + /* Find the smallest shift count that doesn't lose information + (i.e. no need to explicitly insert high bits of the address that + are just the sign extension of the low bits). */ + while ((c >> s) != (SINT16)(c >> s) || (h >> s) != (SINT16)(h >> s)) + s += 16; + +#define OPS(a, b, shift) \ + (create_Imm16_X0((a) >> (shift)) | create_Imm16_X1((b) >> (shift))) + + /* Emit the moveli. */ + *out++ = ffi_template_tramp_tile[0] | OPS(c, h, s); + for (s -= 16; s >= 0; s -= 16) + *out++ = ffi_template_tramp_tile[1] | OPS(c, h, s); + +#undef OPS + + *out++ = ffi_template_tramp_tile[2]; + +#else + /* TILEPro */ + UINT64 *out; + intptr_t delta; + + if (cif->abi != FFI_UNIX) + return FFI_BAD_ABI; + + out = (UINT64 *)closure->tramp; + delta = (intptr_t)ffi_closure_tile - (intptr_t)codeloc; + + *out++ = ffi_template_tramp_tile[0] | create_JOffLong_X1(delta >> 3); +#endif + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + invalidate_icache(closure->tramp, (char *)out - closure->tramp, + getpagesize()); + + return FFI_OK; +} + + +/* This is called by the assembly wrapper for closures. This does + all of the work. On entry reg_args[0] holds the values the registers + had when the closure was invoked. On return reg_args[1] holds the register + values to be returned to the caller (many of which may be garbage). */ +void FFI_HIDDEN +ffi_closure_tile_inner(ffi_closure *closure, + ffi_sarg reg_args[2][NUM_ARG_REGS], + ffi_sarg *stack_args) +{ + ffi_cif * const cif = closure->cif; + void ** const avalue = alloca(cif->nargs * sizeof(void *)); + void *rvalue; + ffi_type ** const arg_types = cif->arg_types; + ffi_sarg * const reg_args_in = reg_args[0]; + ffi_sarg * const reg_args_out = reg_args[1]; + ffi_sarg * argp; + long i, arg_word, nargs = cif->nargs; + /* Use a union to guarantee proper alignment for double. */ + union { ffi_sarg arg[NUM_ARG_REGS]; double d; UINT64 u64; } closure_ret; + + /* Start out reading register arguments. */ + argp = reg_args_in; + + /* Copy the caller's structure return address to that the closure + returns the data directly to the caller. */ + if (cif->flags == FFI_TYPE_STRUCT) + { + /* Return by reference via hidden pointer. */ + rvalue = (void *)(intptr_t)*argp++; + arg_word = 1; + } + else + { + /* Return the value in registers. */ + rvalue = &closure_ret; + arg_word = 0; + } + + /* Grab the addresses of the arguments. */ + for (i = 0; i < nargs; i++) + { + ffi_type * const type = arg_types[i]; + const size_t arg_size_in_words = + (type->size + FFI_SIZEOF_ARG - 1) / FFI_SIZEOF_ARG; + +#ifndef __tilegx__ + /* Doubleword-aligned values are always in an even-number register + pair, or doubleword-aligned stack slot if out of registers. */ + long align = arg_word & (type->alignment > FFI_SIZEOF_ARG); + argp += align; + arg_word += align; +#endif + + if (arg_word == NUM_ARG_REGS || + (arg_word < NUM_ARG_REGS && + arg_word + arg_size_in_words > NUM_ARG_REGS)) + { + /* Switch to reading arguments from the stack. */ + argp = stack_args; + arg_word = NUM_ARG_REGS; + } + + avalue[i] = argp; + argp += arg_size_in_words; + arg_word += arg_size_in_words; + } + + /* Invoke the closure. */ + closure->fun(cif, rvalue, avalue, closure->user_data); + + if (cif->flags != FFI_TYPE_STRUCT) + { + /* Canonicalize for register representation. */ + assign_to_ffi_arg(reg_args_out, &closure_ret, cif->rtype, 1); + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/tile/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/tile/ffitarget.h new file mode 100644 index 0000000..679fb5d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/tile/ffitarget.h @@ -0,0 +1,65 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012 Tilera Corp. + Target configuration macros for TILE. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM + +#include + +typedef uint_reg_t ffi_arg; +typedef int_reg_t ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_UNIX, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_UNIX +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ +#define FFI_CLOSURES 1 + +#ifdef __tilegx__ +/* We always pass 8-byte values, even in -m32 mode. */ +# define FFI_SIZEOF_ARG 8 +# ifdef __LP64__ +# define FFI_TRAMPOLINE_SIZE (8 * 5) /* 5 bundles */ +# else +# define FFI_TRAMPOLINE_SIZE (8 * 3) /* 3 bundles */ +# endif +#else +# define FFI_SIZEOF_ARG 4 +# define FFI_TRAMPOLINE_SIZE 8 /* 1 bundle */ +#endif +#define FFI_NATIVE_RAW_API 0 + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/tile/tile.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/tile/tile.S new file mode 100644 index 0000000..d1f82cb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/tile/tile.S @@ -0,0 +1,360 @@ +/* ----------------------------------------------------------------------- + tile.S - Copyright (c) 2011 Tilera Corp. + + Tilera TILEPro and TILE-Gx Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + +/* Number of bytes in a register. */ +#define REG_SIZE FFI_SIZEOF_ARG + +/* Number of bytes in stack linkage area for backtracing. + + A note about the ABI: on entry to a procedure, sp points to a stack + slot where it must spill the return address if it's not a leaf. + REG_SIZE bytes beyond that is a slot owned by the caller which + contains the sp value that the caller had when it was originally + entered (i.e. the caller's frame pointer). */ +#define LINKAGE_SIZE (2 * REG_SIZE) + +/* The first 10 registers are used to pass arguments and return values. */ +#define NUM_ARG_REGS 10 + +#ifdef __tilegx__ +#define SW st +#define LW ld +#define BGZT bgtzt +#else +#define SW sw +#define LW lw +#define BGZT bgzt +#endif + + +/* void ffi_call_tile (int_reg_t reg_args[NUM_ARG_REGS], + const int_reg_t *stack_args, + unsigned long stack_args_bytes, + void (*fnaddr)(void)); + + On entry, REG_ARGS contain the outgoing register values, + and STACK_ARGS contains STACK_ARG_BYTES of additional values + to be passed on the stack. If STACK_ARG_BYTES is zero, then + STACK_ARGS is ignored. + + When the invoked function returns, the values of r0-r9 are + blindly stored back into REG_ARGS for the caller to examine. */ + + .section .text.ffi_call_tile, "ax", @progbits + .align 8 + .globl ffi_call_tile + FFI_HIDDEN(ffi_call_tile) +ffi_call_tile: + +/* Incoming arguments. */ +#define REG_ARGS r0 +#define INCOMING_STACK_ARGS r1 +#define STACK_ARG_BYTES r2 +#define ORIG_FNADDR r3 + +/* Temporary values. */ +#define FRAME_SIZE r10 +#define TMP r11 +#define TMP2 r12 +#define OUTGOING_STACK_ARGS r13 +#define REG_ADDR_PTR r14 +#define RETURN_REG_ADDR r15 +#define FNADDR r16 + + .cfi_startproc + { + /* Save return address. */ + SW sp, lr + .cfi_offset lr, 0 + /* Prepare to spill incoming r52. */ + addi TMP, sp, -REG_SIZE + /* Increase frame size to have room to spill r52 and REG_ARGS. + The +7 is to round up mod 8. */ + addi FRAME_SIZE, STACK_ARG_BYTES, \ + REG_SIZE + REG_SIZE + LINKAGE_SIZE + 7 + } + { + /* Round stack frame size to a multiple of 8 to satisfy ABI. */ + andi FRAME_SIZE, FRAME_SIZE, -8 + /* Compute where to spill REG_ARGS value. */ + addi TMP2, sp, -(REG_SIZE * 2) + } + { + /* Spill incoming r52. */ + SW TMP, r52 + .cfi_offset r52, -REG_SIZE + /* Set up our frame pointer. */ + move r52, sp + .cfi_def_cfa_register r52 + /* Push stack frame. */ + sub sp, sp, FRAME_SIZE + } + { + /* Prepare to set up stack linkage. */ + addi TMP, sp, REG_SIZE + /* Prepare to memcpy stack args. */ + addi OUTGOING_STACK_ARGS, sp, LINKAGE_SIZE + /* Save REG_ARGS which we will need after we call the subroutine. */ + SW TMP2, REG_ARGS + } + { + /* Set up linkage info to hold incoming stack pointer. */ + SW TMP, r52 + } + { + /* Skip stack args memcpy if we don't have any stack args (common). */ + blezt STACK_ARG_BYTES, .Ldone_stack_args_memcpy + } + +.Lmemcpy_stack_args: + { + /* Load incoming argument from stack_args. */ + LW TMP, INCOMING_STACK_ARGS + addi INCOMING_STACK_ARGS, INCOMING_STACK_ARGS, REG_SIZE + } + { + /* Store stack argument into outgoing stack argument area. */ + SW OUTGOING_STACK_ARGS, TMP + addi OUTGOING_STACK_ARGS, OUTGOING_STACK_ARGS, REG_SIZE + addi STACK_ARG_BYTES, STACK_ARG_BYTES, -REG_SIZE + } + { + BGZT STACK_ARG_BYTES, .Lmemcpy_stack_args + } +.Ldone_stack_args_memcpy: + + { + /* Copy aside ORIG_FNADDR so we can overwrite its register. */ + move FNADDR, ORIG_FNADDR + /* Prepare to load argument registers. */ + addi REG_ADDR_PTR, r0, REG_SIZE + /* Load outgoing r0. */ + LW r0, r0 + } + + /* Load up argument registers from the REG_ARGS array. */ +#define LOAD_REG(REG, PTR) \ + { \ + LW REG, PTR ; \ + addi PTR, PTR, REG_SIZE \ + } + + LOAD_REG(r1, REG_ADDR_PTR) + LOAD_REG(r2, REG_ADDR_PTR) + LOAD_REG(r3, REG_ADDR_PTR) + LOAD_REG(r4, REG_ADDR_PTR) + LOAD_REG(r5, REG_ADDR_PTR) + LOAD_REG(r6, REG_ADDR_PTR) + LOAD_REG(r7, REG_ADDR_PTR) + LOAD_REG(r8, REG_ADDR_PTR) + LOAD_REG(r9, REG_ADDR_PTR) + + { + /* Call the subroutine. */ + jalr FNADDR + } + + { + /* Restore original lr. */ + LW lr, r52 + /* Prepare to recover ARGS, which we spilled earlier. */ + addi TMP, r52, -(2 * REG_SIZE) + } + { + /* Restore ARGS, so we can fill it in with the return regs r0-r9. */ + LW RETURN_REG_ADDR, TMP + /* Prepare to restore original r52. */ + addi TMP, r52, -REG_SIZE + } + + { + /* Pop stack frame. */ + move sp, r52 + /* Restore original r52. */ + LW r52, TMP + } + +#define STORE_REG(REG, PTR) \ + { \ + SW PTR, REG ; \ + addi PTR, PTR, REG_SIZE \ + } + + /* Return all register values by reference. */ + STORE_REG(r0, RETURN_REG_ADDR) + STORE_REG(r1, RETURN_REG_ADDR) + STORE_REG(r2, RETURN_REG_ADDR) + STORE_REG(r3, RETURN_REG_ADDR) + STORE_REG(r4, RETURN_REG_ADDR) + STORE_REG(r5, RETURN_REG_ADDR) + STORE_REG(r6, RETURN_REG_ADDR) + STORE_REG(r7, RETURN_REG_ADDR) + STORE_REG(r8, RETURN_REG_ADDR) + STORE_REG(r9, RETURN_REG_ADDR) + + { + jrp lr + } + + .cfi_endproc + .size ffi_call_tile, .-ffi_call_tile + +/* ffi_closure_tile(...) + + On entry, lr points to the closure plus 8 bytes, and r10 + contains the actual return address. + + This function simply dumps all register parameters into a stack array + and passes the closure, the registers array, and the stack arguments + to C code that does all of the actual closure processing. */ + + .section .text.ffi_closure_tile, "ax", @progbits + .align 8 + .globl ffi_closure_tile + FFI_HIDDEN(ffi_closure_tile) + + .cfi_startproc +/* Room to spill all NUM_ARG_REGS incoming registers, plus frame linkage. */ +#define CLOSURE_FRAME_SIZE (((NUM_ARG_REGS * REG_SIZE * 2 + LINKAGE_SIZE) + 7) & -8) +ffi_closure_tile: + { +#ifdef __tilegx__ + st sp, lr + .cfi_offset lr, 0 +#else + /* Save return address (in r10 due to closure stub wrapper). */ + SW sp, r10 + .cfi_return_column r10 + .cfi_offset r10, 0 +#endif + /* Compute address for stack frame linkage. */ + addli r10, sp, -(CLOSURE_FRAME_SIZE - REG_SIZE) + } + { + /* Save incoming stack pointer in linkage area. */ + SW r10, sp + .cfi_offset sp, -(CLOSURE_FRAME_SIZE - REG_SIZE) + /* Push a new stack frame. */ + addli sp, sp, -CLOSURE_FRAME_SIZE + .cfi_adjust_cfa_offset CLOSURE_FRAME_SIZE + } + + { + /* Create pointer to where to start spilling registers. */ + addi r10, sp, LINKAGE_SIZE + } + + /* Spill all the incoming registers. */ + STORE_REG(r0, r10) + STORE_REG(r1, r10) + STORE_REG(r2, r10) + STORE_REG(r3, r10) + STORE_REG(r4, r10) + STORE_REG(r5, r10) + STORE_REG(r6, r10) + STORE_REG(r7, r10) + STORE_REG(r8, r10) + { + /* Save r9. */ + SW r10, r9 +#ifdef __tilegx__ + /* Pointer to closure is passed in r11. */ + move r0, r11 +#else + /* Compute pointer to the closure object. Because the closure + starts with a "jal ffi_closure_tile", we can just take the + value of lr (a phony return address pointing into the closure) + and subtract 8. */ + addi r0, lr, -8 +#endif + /* Compute a pointer to the register arguments we just spilled. */ + addi r1, sp, LINKAGE_SIZE + } + { + /* Compute a pointer to the extra stack arguments (if any). */ + addli r2, sp, CLOSURE_FRAME_SIZE + LINKAGE_SIZE + /* Call C code to deal with all of the grotty details. */ + jal ffi_closure_tile_inner + } + { + addli r10, sp, CLOSURE_FRAME_SIZE + } + { + /* Restore the return address. */ + LW lr, r10 + /* Compute pointer to registers array. */ + addli r10, sp, LINKAGE_SIZE + (NUM_ARG_REGS * REG_SIZE) + } + /* Return all the register values, which C code may have set. */ + LOAD_REG(r0, r10) + LOAD_REG(r1, r10) + LOAD_REG(r2, r10) + LOAD_REG(r3, r10) + LOAD_REG(r4, r10) + LOAD_REG(r5, r10) + LOAD_REG(r6, r10) + LOAD_REG(r7, r10) + LOAD_REG(r8, r10) + LOAD_REG(r9, r10) + { + /* Pop the frame. */ + addli sp, sp, CLOSURE_FRAME_SIZE + jrp lr + } + + .cfi_endproc + .size ffi_closure_tile, . - ffi_closure_tile + + +/* What follows are code template instructions that get copied to the + closure trampoline by ffi_prep_closure_loc. The zeroed operands + get replaced by their proper values at runtime. */ + + .section .text.ffi_template_tramp_tile, "ax", @progbits + .align 8 + .globl ffi_template_tramp_tile + FFI_HIDDEN(ffi_template_tramp_tile) +ffi_template_tramp_tile: +#ifdef __tilegx__ + { + moveli r11, 0 /* backpatched to address of containing closure. */ + moveli r10, 0 /* backpatched to ffi_closure_tile. */ + } + /* Note: the following bundle gets generated multiple times + depending on the pointer value (esp. useful for -m32 mode). */ + { shl16insli r11, r11, 0 ; shl16insli r10, r10, 0 } + { info 2+8 /* for backtracer: -> pc in lr, frame size 0 */ ; jr r10 } +#else + /* 'jal .' yields a PC-relative offset of zero so we can OR in the + right offset at runtime. */ + { move r10, lr ; jal . /* ffi_closure_tile */ } +#endif + + .size ffi_template_tramp_tile, . - ffi_template_tramp_tile diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/types.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/types.c new file mode 100644 index 0000000..9ec27f6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/types.c @@ -0,0 +1,108 @@ +/* ----------------------------------------------------------------------- + types.c - Copyright (c) 1996, 1998 Red Hat, Inc. + + Predefined ffi_types needed by libffi. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +/* Hide the basic type definitions from the header file, so that we + can redefine them here as "const". */ +#define LIBFFI_HIDE_BASIC_TYPES + +#include +#include + +/* Type definitions */ + +#define FFI_TYPEDEF(name, type, id, maybe_const)\ +struct struct_align_##name { \ + char c; \ + type x; \ +}; \ +FFI_EXTERN \ +maybe_const ffi_type ffi_type_##name = { \ + sizeof(type), \ + offsetof(struct struct_align_##name, x), \ + id, NULL \ +} + +#define FFI_COMPLEX_TYPEDEF(name, type, maybe_const) \ +static ffi_type *ffi_elements_complex_##name [2] = { \ + (ffi_type *)(&ffi_type_##name), NULL \ +}; \ +struct struct_align_complex_##name { \ + char c; \ + _Complex type x; \ +}; \ +FFI_EXTERN \ +maybe_const ffi_type ffi_type_complex_##name = { \ + sizeof(_Complex type), \ + offsetof(struct struct_align_complex_##name, x), \ + FFI_TYPE_COMPLEX, \ + (ffi_type **)ffi_elements_complex_##name \ +} + +/* Size and alignment are fake here. They must not be 0. */ +FFI_EXTERN const ffi_type ffi_type_void = { + 1, 1, FFI_TYPE_VOID, NULL +}; + +FFI_TYPEDEF(uint8, UINT8, FFI_TYPE_UINT8, const); +FFI_TYPEDEF(sint8, SINT8, FFI_TYPE_SINT8, const); +FFI_TYPEDEF(uint16, UINT16, FFI_TYPE_UINT16, const); +FFI_TYPEDEF(sint16, SINT16, FFI_TYPE_SINT16, const); +FFI_TYPEDEF(uint32, UINT32, FFI_TYPE_UINT32, const); +FFI_TYPEDEF(sint32, SINT32, FFI_TYPE_SINT32, const); +FFI_TYPEDEF(uint64, UINT64, FFI_TYPE_UINT64, const); +FFI_TYPEDEF(sint64, SINT64, FFI_TYPE_SINT64, const); + +FFI_TYPEDEF(pointer, void*, FFI_TYPE_POINTER, const); + +FFI_TYPEDEF(float, float, FFI_TYPE_FLOAT, const); +FFI_TYPEDEF(double, double, FFI_TYPE_DOUBLE, const); + +#if !defined HAVE_LONG_DOUBLE_VARIANT || defined __alpha__ +#define FFI_LDBL_CONST const +#else +#define FFI_LDBL_CONST +#endif + +#ifdef __alpha__ +/* Even if we're not configured to default to 128-bit long double, + maintain binary compatibility, as -mlong-double-128 can be used + at any time. */ +/* Validate the hard-coded number below. */ +# if defined(__LONG_DOUBLE_128__) && FFI_TYPE_LONGDOUBLE != 4 +# error FFI_TYPE_LONGDOUBLE out of date +# endif +const ffi_type ffi_type_longdouble = { 16, 16, 4, NULL }; +#elif FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE +FFI_TYPEDEF(longdouble, long double, FFI_TYPE_LONGDOUBLE, FFI_LDBL_CONST); +#endif + +#ifdef FFI_TARGET_HAS_COMPLEX_TYPE +FFI_COMPLEX_TYPEDEF(float, float, const); +FFI_COMPLEX_TYPEDEF(double, double, const); +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE +FFI_COMPLEX_TYPEDEF(longdouble, long double, FFI_LDBL_CONST); +#endif +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/vax/elfbsd.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/vax/elfbsd.S new file mode 100644 index 0000000..01ca313 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/vax/elfbsd.S @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2013 Miodrag Vallat. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * ``Software''), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * vax Foreign Function Interface + */ + +#define LIBFFI_ASM +#include +#include + + .text + +/* + * void * %r0 + * ffi_call_elfbsd(extended_cif *ecif, 4(%ap) + * unsigned bytes, 8(%ap) + * unsigned flags, 12(%ap) + * void *rvalue, 16(%ap) + * void (*fn)()); 20(%ap) + */ + .globl ffi_call_elfbsd + .type ffi_call_elfbsd,@function + .align 2 +ffi_call_elfbsd: + .word 0x00c # save R2 and R3 + + # Allocate stack space for the args + subl2 8(%ap), %sp + + # Call ffi_prep_args + pushl %sp + pushl 4(%ap) + calls $2, ffi_prep_args + + # Get function pointer + movl 20(%ap), %r1 + + # Build a CALLS frame + ashl $-2, 8(%ap), %r0 + pushl %r0 # argument stack usage + movl %sp, %r0 # future %ap + # saved registers + bbc $11, 0(%r1), 1f + pushl %r11 +1: bbc $10, 0(%r1), 1f + pushl %r10 +1: bbc $9, 0(%r1), 1f + pushl %r9 +1: bbc $8, 0(%r1), 1f + pushl %r8 +1: bbc $7, 0(%r1), 1f + pushl %r7 +1: bbc $6, 0(%r1), 1f + pushl %r6 +1: bbc $5, 0(%r1), 1f + pushl %r5 +1: bbc $4, 0(%r1), 1f + pushl %r4 +1: bbc $3, 0(%r1), 1f + pushl %r3 +1: bbc $2, 0(%r1), 1f + pushl %r2 +1: + pushal 9f + pushl %fp + pushl %ap + movl 16(%ap), %r3 # struct return address, if needed + movl %r0, %ap + movzwl 4(%fp), %r0 # previous PSW, without the saved registers mask + bisl2 $0x20000000, %r0 # calls frame + movzwl 0(%r1), %r2 + bicw2 $0xf003, %r2 # only keep R11-R2 + ashl $16, %r2, %r2 + bisl2 %r2, %r0 # saved register mask of the called function + pushl %r0 + pushl $0 + movl %sp, %fp + + # Invoke the function + pushal 2(%r1) # skip procedure entry mask + movl %r3, %r1 + bicpsw $0x000f + rsb + +9: + # Copy return value if necessary + tstl 16(%ap) + jeql 9f + movl 16(%ap), %r2 + + bbc $0, 12(%ap), 1f # CIF_FLAGS_CHAR + movb %r0, 0(%r2) + brb 9f +1: + bbc $1, 12(%ap), 1f # CIF_FLAGS_SHORT + movw %r0, 0(%r2) + brb 9f +1: + bbc $2, 12(%ap), 1f # CIF_FLAGS_INT + movl %r0, 0(%r2) + brb 9f +1: + bbc $3, 12(%ap), 1f # CIF_FLAGS_DINT + movq %r0, 0(%r2) + brb 9f +1: + movl %r1, %r0 # might have been a struct + #brb 9f + +9: + ret + +/* + * ffi_closure_elfbsd(void); + * invoked with %r0: ffi_closure *closure + */ + .globl ffi_closure_elfbsd + .type ffi_closure_elfbsd, @function + .align 2 +ffi_closure_elfbsd: + .word 0 + + # Allocate room on stack for return value + subl2 $8, %sp + + # Invoke the closure function + pushal 4(%ap) # calling stack + pushal 4(%sp) # return value + pushl %r0 # closure + calls $3, ffi_closure_elfbsd_inner + + # Copy return value if necessary + bitb $1, %r0 # CIF_FLAGS_CHAR + beql 1f + movb 0(%sp), %r0 + brb 9f +1: + bitb $2, %r0 # CIF_FLAGS_SHORT + beql 1f + movw 0(%sp), %r0 + brb 9f +1: + bitb $4, %r0 # CIF_FLAGS_INT + beql 1f + movl 0(%sp), %r0 + brb 9f +1: + bitb $8, %r0 # CIF_FLAGS_DINT + beql 1f + movq 0(%sp), %r0 + #brb 9f +1: + +9: + ret + +/* + * ffi_closure_struct_elfbsd(void); + * invoked with %r0: ffi_closure *closure + * %r1: struct return address + */ + .globl ffi_closure_struct_elfbsd + .type ffi_closure_struct_elfbsd, @function + .align 2 +ffi_closure_struct_elfbsd: + .word 0 + + # Invoke the closure function + pushal 4(%ap) # calling stack + pushl %r1 # return value + pushl %r0 # closure + calls $3, ffi_closure_elfbsd_inner + + ret diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/vax/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/vax/ffi.c new file mode 100644 index 0000000..e52caec --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/vax/ffi.c @@ -0,0 +1,276 @@ +/* + * Copyright (c) 2013 Miodrag Vallat. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * ``Software''), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * vax Foreign Function Interface + * + * This file attempts to provide all the FFI entry points which can reliably + * be implemented in C. + */ + +#include +#include + +#include +#include + +#define CIF_FLAGS_CHAR 1 /* for struct only */ +#define CIF_FLAGS_SHORT 2 /* for struct only */ +#define CIF_FLAGS_INT 4 +#define CIF_FLAGS_DINT 8 + +/* + * Foreign Function Interface API + */ + +void ffi_call_elfbsd (extended_cif *, unsigned, unsigned, void *, + void (*) ()); +void *ffi_prep_args (extended_cif *ecif, void *stack); + +void * +ffi_prep_args (extended_cif *ecif, void *stack) +{ + unsigned int i; + void **p_argv; + char *argp; + ffi_type **p_arg; + void *struct_value_ptr; + + argp = stack; + + if (ecif->cif->rtype->type == FFI_TYPE_STRUCT + && !ecif->cif->flags) + struct_value_ptr = ecif->rvalue; + else + struct_value_ptr = NULL; + + p_argv = ecif->avalue; + + for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; + i != 0; + i--, p_arg++) + { + size_t z; + + z = (*p_arg)->size; + if (z < sizeof (int)) + { + switch ((*p_arg)->type) + { + case FFI_TYPE_SINT8: + *(signed int *) argp = (signed int) *(SINT8 *) *p_argv; + break; + + case FFI_TYPE_UINT8: + *(unsigned int *) argp = (unsigned int) *(UINT8 *) *p_argv; + break; + + case FFI_TYPE_SINT16: + *(signed int *) argp = (signed int) *(SINT16 *) *p_argv; + break; + + case FFI_TYPE_UINT16: + *(unsigned int *) argp = (unsigned int) *(UINT16 *) *p_argv; + break; + + case FFI_TYPE_STRUCT: + memcpy (argp, *p_argv, z); + break; + + default: + FFI_ASSERT (0); + } + z = sizeof (int); + } + else + { + memcpy (argp, *p_argv, z); + + /* Align if necessary. */ + if ((sizeof(int) - 1) & z) + z = FFI_ALIGN(z, sizeof(int)); + } + + p_argv++; + argp += z; + } + + return struct_value_ptr; +} + +ffi_status +ffi_prep_cif_machdep (ffi_cif *cif) +{ + /* Set the return type flag */ + switch (cif->rtype->type) + { + case FFI_TYPE_VOID: + cif->flags = 0; + break; + + case FFI_TYPE_STRUCT: + if (cif->rtype->elements[0]->type == FFI_TYPE_STRUCT && + cif->rtype->elements[1]) + { + cif->flags = 0; + break; + } + + if (cif->rtype->size == sizeof (char)) + cif->flags = CIF_FLAGS_CHAR; + else if (cif->rtype->size == sizeof (short)) + cif->flags = CIF_FLAGS_SHORT; + else if (cif->rtype->size == sizeof (int)) + cif->flags = CIF_FLAGS_INT; + else if (cif->rtype->size == 2 * sizeof (int)) + cif->flags = CIF_FLAGS_DINT; + else + cif->flags = 0; + break; + + default: + if (cif->rtype->size <= sizeof (int)) + cif->flags = CIF_FLAGS_INT; + else + cif->flags = CIF_FLAGS_DINT; + break; + } + + return FFI_OK; +} + +void +ffi_call (ffi_cif *cif, void (*fn) (), void *rvalue, void **avalue) +{ + extended_cif ecif; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* If the return value is a struct and we don't have a return value + address then we need to make one. */ + + if (rvalue == NULL + && cif->rtype->type == FFI_TYPE_STRUCT + && cif->flags == 0) + ecif.rvalue = alloca (cif->rtype->size); + else + ecif.rvalue = rvalue; + + switch (cif->abi) + { + case FFI_ELFBSD: + ffi_call_elfbsd (&ecif, cif->bytes, cif->flags, ecif.rvalue, fn); + break; + + default: + FFI_ASSERT (0); + break; + } +} + +/* + * Closure API + */ + +void ffi_closure_elfbsd (void); +void ffi_closure_struct_elfbsd (void); +unsigned int ffi_closure_elfbsd_inner (ffi_closure *, void *, char *); + +static void +ffi_prep_closure_elfbsd (ffi_cif *cif, void **avalue, char *stackp) +{ + unsigned int i; + void **p_argv; + ffi_type **p_arg; + + p_argv = avalue; + + for (i = cif->nargs, p_arg = cif->arg_types; i != 0; i--, p_arg++) + { + size_t z; + + z = (*p_arg)->size; + *p_argv = stackp; + + /* Align if necessary */ + if ((sizeof (int) - 1) & z) + z = FFI_ALIGN(z, sizeof (int)); + + p_argv++; + stackp += z; + } +} + +unsigned int +ffi_closure_elfbsd_inner (ffi_closure *closure, void *resp, char *stack) +{ + ffi_cif *cif; + void **arg_area; + + cif = closure->cif; + arg_area = (void **) alloca (cif->nargs * sizeof (void *)); + + ffi_prep_closure_elfbsd (cif, arg_area, stack); + + (closure->fun) (cif, resp, arg_area, closure->user_data); + + return cif->flags; +} + +ffi_status +ffi_prep_closure_loc (ffi_closure *closure, ffi_cif *cif, + void (*fun)(ffi_cif *, void *, void **, void *), + void *user_data, void *codeloc) +{ + char *tramp = (char *) codeloc; + void *fn; + + FFI_ASSERT (cif->abi == FFI_ELFBSD); + + /* entry mask */ + *(unsigned short *)(tramp + 0) = 0x0000; + /* movl #closure, r0 */ + tramp[2] = 0xd0; + tramp[3] = 0x8f; + *(unsigned int *)(tramp + 4) = (unsigned int) closure; + tramp[8] = 0x50; + + if (cif->rtype->type == FFI_TYPE_STRUCT + && !cif->flags) + fn = &ffi_closure_struct_elfbsd; + else + fn = &ffi_closure_elfbsd; + + /* jmpl #fn */ + tramp[9] = 0x17; + tramp[10] = 0xef; + *(unsigned int *)(tramp + 11) = (unsigned int)fn + 2 - + (unsigned int)tramp - 9 - 6; + + closure->cif = cif; + closure->user_data = user_data; + closure->fun = fun; + + return FFI_OK; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/vax/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/vax/ffitarget.h new file mode 100644 index 0000000..2fc9488 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/vax/ffitarget.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2013 Miodrag Vallat. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * ``Software''), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * vax Foreign Function Interface + */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_ELFBSD, + FFI_DEFAULT_ABI = FFI_ELFBSD, + FFI_LAST_ABI = FFI_DEFAULT_ABI + 1 +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_TRAMPOLINE_SIZE 15 +#define FFI_NATIVE_RAW_API 0 + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/asmnames.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/asmnames.h new file mode 100644 index 0000000..7551021 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/asmnames.h @@ -0,0 +1,30 @@ +#ifndef ASMNAMES_H +#define ASMNAMES_H + +#define C2(X, Y) X ## Y +#define C1(X, Y) C2(X, Y) +#ifdef __USER_LABEL_PREFIX__ +# define C(X) C1(__USER_LABEL_PREFIX__, X) +#else +# define C(X) X +#endif + +#ifdef __APPLE__ +# define L(X) C1(L, X) +#else +# define L(X) C1(.L, X) +#endif + +#if defined(__ELF__) && defined(__PIC__) +# define PLT(X) X@PLT +#else +# define PLT(X) X +#endif + +#ifdef __ELF__ +# define ENDF(X) .type X,@function; .size X, . - X +#else +# define ENDF(X) +#endif + +#endif /* ASMNAMES_H */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffi.c new file mode 100644 index 0000000..5f7fd81 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffi.c @@ -0,0 +1,770 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2017 Anthony Green + Copyright (c) 1996, 1998, 1999, 2001, 2007, 2008 Red Hat, Inc. + Copyright (c) 2002 Ranjit Mathew + Copyright (c) 2002 Bo Thorsen + Copyright (c) 2002 Roger Sayle + Copyright (C) 2008, 2010 Free Software Foundation, Inc. + + x86 Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#if defined(__i386__) || defined(_M_IX86) +#include +#include +#include +#include +#include "internal.h" + +/* Force FFI_TYPE_LONGDOUBLE to be different than FFI_TYPE_DOUBLE; + all further uses in this file will refer to the 80-bit type. */ +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE +# if FFI_TYPE_LONGDOUBLE != 4 +# error FFI_TYPE_LONGDOUBLE out of date +# endif +#else +# undef FFI_TYPE_LONGDOUBLE +# define FFI_TYPE_LONGDOUBLE 4 +#endif + +#if defined(__GNUC__) && !defined(__declspec) +# define __declspec(x) __attribute__((x)) +#endif + +#if defined(_MSC_VER) && defined(_M_IX86) +/* Stack is not 16-byte aligned on Windows. */ +#define STACK_ALIGN(bytes) (bytes) +#else +#define STACK_ALIGN(bytes) FFI_ALIGN (bytes, 16) +#endif + +/* Perform machine dependent cif processing. */ +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep(ffi_cif *cif) +{ + size_t bytes = 0; + int i, n, flags, cabi = cif->abi; + + switch (cabi) + { + case FFI_SYSV: + case FFI_STDCALL: + case FFI_THISCALL: + case FFI_FASTCALL: + case FFI_MS_CDECL: + case FFI_PASCAL: + case FFI_REGISTER: + break; + default: + return FFI_BAD_ABI; + } + + switch (cif->rtype->type) + { + case FFI_TYPE_VOID: + flags = X86_RET_VOID; + break; + case FFI_TYPE_FLOAT: + flags = X86_RET_FLOAT; + break; + case FFI_TYPE_DOUBLE: + flags = X86_RET_DOUBLE; + break; + case FFI_TYPE_LONGDOUBLE: + flags = X86_RET_LDOUBLE; + break; + case FFI_TYPE_UINT8: + flags = X86_RET_UINT8; + break; + case FFI_TYPE_UINT16: + flags = X86_RET_UINT16; + break; + case FFI_TYPE_SINT8: + flags = X86_RET_SINT8; + break; + case FFI_TYPE_SINT16: + flags = X86_RET_SINT16; + break; + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_POINTER: + flags = X86_RET_INT32; + break; + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + flags = X86_RET_INT64; + break; + case FFI_TYPE_STRUCT: +#ifndef X86 + /* ??? This should be a different ABI rather than an ifdef. */ + if (cif->rtype->size == 1) + flags = X86_RET_STRUCT_1B; + else if (cif->rtype->size == 2) + flags = X86_RET_STRUCT_2B; + else if (cif->rtype->size == 4) + flags = X86_RET_INT32; + else if (cif->rtype->size == 8) + flags = X86_RET_INT64; + else +#endif + { + do_struct: + switch (cabi) + { + case FFI_THISCALL: + case FFI_FASTCALL: + case FFI_STDCALL: + case FFI_MS_CDECL: + flags = X86_RET_STRUCTARG; + break; + default: + flags = X86_RET_STRUCTPOP; + break; + } + /* Allocate space for return value pointer. */ + bytes += FFI_ALIGN (sizeof(void*), FFI_SIZEOF_ARG); + } + break; + case FFI_TYPE_COMPLEX: + switch (cif->rtype->elements[0]->type) + { + case FFI_TYPE_DOUBLE: + case FFI_TYPE_LONGDOUBLE: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + goto do_struct; + case FFI_TYPE_FLOAT: + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + flags = X86_RET_INT64; + break; + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + flags = X86_RET_INT32; + break; + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + flags = X86_RET_STRUCT_2B; + break; + default: + return FFI_BAD_TYPEDEF; + } + break; + default: + return FFI_BAD_TYPEDEF; + } + cif->flags = flags; + + for (i = 0, n = cif->nargs; i < n; i++) + { + ffi_type *t = cif->arg_types[i]; + + bytes = FFI_ALIGN (bytes, t->alignment); + bytes += FFI_ALIGN (t->size, FFI_SIZEOF_ARG); + } + cif->bytes = bytes; + + return FFI_OK; +} + +static ffi_arg +extend_basic_type(void *arg, int type) +{ + switch (type) + { + case FFI_TYPE_SINT8: + return *(SINT8 *)arg; + case FFI_TYPE_UINT8: + return *(UINT8 *)arg; + case FFI_TYPE_SINT16: + return *(SINT16 *)arg; + case FFI_TYPE_UINT16: + return *(UINT16 *)arg; + + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT32: + case FFI_TYPE_POINTER: + case FFI_TYPE_FLOAT: + return *(UINT32 *)arg; + + default: + abort(); + } +} + +struct call_frame +{ + void *ebp; /* 0 */ + void *retaddr; /* 4 */ + void (*fn)(void); /* 8 */ + int flags; /* 12 */ + void *rvalue; /* 16 */ + unsigned regs[3]; /* 20-28 */ +}; + +struct abi_params +{ + int dir; /* parameter growth direction */ + int static_chain; /* the static chain register used by gcc */ + int nregs; /* number of register parameters */ + int regs[3]; +}; + +static const struct abi_params abi_params[FFI_LAST_ABI] = { + [FFI_SYSV] = { 1, R_ECX, 0 }, + [FFI_THISCALL] = { 1, R_EAX, 1, { R_ECX } }, + [FFI_FASTCALL] = { 1, R_EAX, 2, { R_ECX, R_EDX } }, + [FFI_STDCALL] = { 1, R_ECX, 0 }, + [FFI_PASCAL] = { -1, R_ECX, 0 }, + /* ??? No defined static chain; gcc does not support REGISTER. */ + [FFI_REGISTER] = { -1, R_ECX, 3, { R_EAX, R_EDX, R_ECX } }, + [FFI_MS_CDECL] = { 1, R_ECX, 0 } +}; + +#ifdef HAVE_FASTCALL + #ifdef _MSC_VER + #define FFI_DECLARE_FASTCALL __fastcall + #else + #define FFI_DECLARE_FASTCALL __declspec(fastcall) + #endif +#else + #define FFI_DECLARE_FASTCALL +#endif + +extern void FFI_DECLARE_FASTCALL ffi_call_i386(struct call_frame *, char *) FFI_HIDDEN; + +static void +ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + size_t rsize, bytes; + struct call_frame *frame; + char *stack, *argp; + ffi_type **arg_types; + int flags, cabi, i, n, dir, narg_reg; + const struct abi_params *pabi; + + flags = cif->flags; + cabi = cif->abi; + pabi = &abi_params[cabi]; + dir = pabi->dir; + + rsize = 0; + if (rvalue == NULL) + { + switch (flags) + { + case X86_RET_FLOAT: + case X86_RET_DOUBLE: + case X86_RET_LDOUBLE: + case X86_RET_STRUCTPOP: + case X86_RET_STRUCTARG: + /* The float cases need to pop the 387 stack. + The struct cases need to pass a valid pointer to the callee. */ + rsize = cif->rtype->size; + break; + default: + /* We can pretend that the callee returns nothing. */ + flags = X86_RET_VOID; + break; + } + } + + bytes = STACK_ALIGN (cif->bytes); + stack = alloca(bytes + sizeof(*frame) + rsize); + argp = (dir < 0 ? stack + bytes : stack); + frame = (struct call_frame *)(stack + bytes); + if (rsize) + rvalue = frame + 1; + + frame->fn = fn; + frame->flags = flags; + frame->rvalue = rvalue; + frame->regs[pabi->static_chain] = (unsigned)closure; + + narg_reg = 0; + switch (flags) + { + case X86_RET_STRUCTARG: + /* The pointer is passed as the first argument. */ + if (pabi->nregs > 0) + { + frame->regs[pabi->regs[0]] = (unsigned)rvalue; + narg_reg = 1; + break; + } + /* fallthru */ + case X86_RET_STRUCTPOP: + *(void **)argp = rvalue; + argp += sizeof(void *); + break; + } + + arg_types = cif->arg_types; + for (i = 0, n = cif->nargs; i < n; i++) + { + ffi_type *ty = arg_types[i]; + void *valp = avalue[i]; + size_t z = ty->size; + int t = ty->type; + + if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT) + { + ffi_arg val = extend_basic_type (valp, t); + + if (t != FFI_TYPE_FLOAT && narg_reg < pabi->nregs) + frame->regs[pabi->regs[narg_reg++]] = val; + else if (dir < 0) + { + argp -= 4; + *(ffi_arg *)argp = val; + } + else + { + *(ffi_arg *)argp = val; + argp += 4; + } + } + else + { + size_t za = FFI_ALIGN (z, FFI_SIZEOF_ARG); + size_t align = FFI_SIZEOF_ARG; + + /* Issue 434: For thiscall and fastcall, if the paramter passed + as 64-bit integer or struct, all following integer parameters + will be passed on stack. */ + if ((cabi == FFI_THISCALL || cabi == FFI_FASTCALL) + && (t == FFI_TYPE_SINT64 + || t == FFI_TYPE_UINT64 + || t == FFI_TYPE_STRUCT)) + narg_reg = 2; + + /* Alignment rules for arguments are quite complex. Vectors and + structures with 16 byte alignment get it. Note that long double + on Darwin does have 16 byte alignment, and does not get this + alignment if passed directly; a structure with a long double + inside, however, would get 16 byte alignment. Since libffi does + not support vectors, we need non concern ourselves with other + cases. */ + if (t == FFI_TYPE_STRUCT && ty->alignment >= 16) + align = 16; + + if (dir < 0) + { + /* ??? These reverse argument ABIs are probably too old + to have cared about alignment. Someone should check. */ + argp -= za; + memcpy (argp, valp, z); + } + else + { + argp = (char *)FFI_ALIGN (argp, align); + memcpy (argp, valp, z); + argp += za; + } + } + } + FFI_ASSERT (dir > 0 || argp == stack); + + ffi_call_i386 (frame, stack); +} + +void +ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + ffi_call_int (cif, fn, rvalue, avalue, NULL); +} + +#ifdef FFI_GO_CLOSURES +void +ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + ffi_call_int (cif, fn, rvalue, avalue, closure); +} +#endif + +/** private members **/ + +void FFI_HIDDEN ffi_closure_i386(void); +void FFI_HIDDEN ffi_closure_STDCALL(void); +void FFI_HIDDEN ffi_closure_REGISTER(void); + +struct closure_frame +{ + unsigned rettemp[4]; /* 0 */ + unsigned regs[3]; /* 16-24 */ + ffi_cif *cif; /* 28 */ + void (*fun)(ffi_cif*,void*,void**,void*); /* 32 */ + void *user_data; /* 36 */ +}; + +int FFI_HIDDEN FFI_DECLARE_FASTCALL +ffi_closure_inner (struct closure_frame *frame, char *stack) +{ + ffi_cif *cif = frame->cif; + int cabi, i, n, flags, dir, narg_reg; + const struct abi_params *pabi; + ffi_type **arg_types; + char *argp; + void *rvalue; + void **avalue; + + cabi = cif->abi; + flags = cif->flags; + narg_reg = 0; + rvalue = frame->rettemp; + pabi = &abi_params[cabi]; + dir = pabi->dir; + argp = (dir < 0 ? stack + STACK_ALIGN (cif->bytes) : stack); + + switch (flags) + { + case X86_RET_STRUCTARG: + if (pabi->nregs > 0) + { + rvalue = (void *)frame->regs[pabi->regs[0]]; + narg_reg = 1; + frame->rettemp[0] = (unsigned)rvalue; + break; + } + /* fallthru */ + case X86_RET_STRUCTPOP: + rvalue = *(void **)argp; + argp += sizeof(void *); + frame->rettemp[0] = (unsigned)rvalue; + break; + } + + n = cif->nargs; + avalue = alloca(sizeof(void *) * n); + + arg_types = cif->arg_types; + for (i = 0; i < n; ++i) + { + ffi_type *ty = arg_types[i]; + size_t z = ty->size; + int t = ty->type; + void *valp; + + if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT) + { + if (t != FFI_TYPE_FLOAT && narg_reg < pabi->nregs) + valp = &frame->regs[pabi->regs[narg_reg++]]; + else if (dir < 0) + { + argp -= 4; + valp = argp; + } + else + { + valp = argp; + argp += 4; + } + } + else + { + size_t za = FFI_ALIGN (z, FFI_SIZEOF_ARG); + size_t align = FFI_SIZEOF_ARG; + + /* See the comment in ffi_call_int. */ + if (t == FFI_TYPE_STRUCT && ty->alignment >= 16) + align = 16; + + /* Issue 434: For thiscall and fastcall, if the paramter passed + as 64-bit integer or struct, all following integer parameters + will be passed on stack. */ + if ((cabi == FFI_THISCALL || cabi == FFI_FASTCALL) + && (t == FFI_TYPE_SINT64 + || t == FFI_TYPE_UINT64 + || t == FFI_TYPE_STRUCT)) + narg_reg = 2; + + if (dir < 0) + { + /* ??? These reverse argument ABIs are probably too old + to have cared about alignment. Someone should check. */ + argp -= za; + valp = argp; + } + else + { + argp = (char *)FFI_ALIGN (argp, align); + valp = argp; + argp += za; + } + } + + avalue[i] = valp; + } + + frame->fun (cif, rvalue, avalue, frame->user_data); + + if (cabi == FFI_STDCALL) + return flags + (cif->bytes << X86_RET_POP_SHIFT); + else + return flags; +} + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void *codeloc) +{ + char *tramp = closure->tramp; + void (*dest)(void); + int op = 0xb8; /* movl imm, %eax */ + + switch (cif->abi) + { + case FFI_SYSV: + case FFI_THISCALL: + case FFI_FASTCALL: + case FFI_MS_CDECL: + dest = ffi_closure_i386; + break; + case FFI_STDCALL: + case FFI_PASCAL: + dest = ffi_closure_STDCALL; + break; + case FFI_REGISTER: + dest = ffi_closure_REGISTER; + op = 0x68; /* pushl imm */ + break; + default: + return FFI_BAD_ABI; + } + + /* endbr32. */ + *(UINT32 *) tramp = 0xfb1e0ff3; + + /* movl or pushl immediate. */ + tramp[4] = op; + *(void **)(tramp + 5) = codeloc; + + /* jmp dest */ + tramp[9] = 0xe9; + *(unsigned *)(tramp + 10) = (unsigned)dest - ((unsigned)codeloc + 14); + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + return FFI_OK; +} + +#ifdef FFI_GO_CLOSURES + +void FFI_HIDDEN ffi_go_closure_EAX(void); +void FFI_HIDDEN ffi_go_closure_ECX(void); +void FFI_HIDDEN ffi_go_closure_STDCALL(void); + +ffi_status +ffi_prep_go_closure (ffi_go_closure* closure, ffi_cif* cif, + void (*fun)(ffi_cif*,void*,void**,void*)) +{ + void (*dest)(void); + + switch (cif->abi) + { + case FFI_SYSV: + case FFI_MS_CDECL: + dest = ffi_go_closure_ECX; + break; + case FFI_THISCALL: + case FFI_FASTCALL: + dest = ffi_go_closure_EAX; + break; + case FFI_STDCALL: + case FFI_PASCAL: + dest = ffi_go_closure_STDCALL; + break; + case FFI_REGISTER: + default: + return FFI_BAD_ABI; + } + + closure->tramp = dest; + closure->cif = cif; + closure->fun = fun; + + return FFI_OK; +} + +#endif /* FFI_GO_CLOSURES */ + +/* ------- Native raw API support -------------------------------- */ + +#if !FFI_NO_RAW_API + +void FFI_HIDDEN ffi_closure_raw_SYSV(void); +void FFI_HIDDEN ffi_closure_raw_THISCALL(void); + +ffi_status +ffi_prep_raw_closure_loc (ffi_raw_closure *closure, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data, + void *codeloc) +{ + char *tramp = closure->tramp; + void (*dest)(void); + int i; + + /* We currently don't support certain kinds of arguments for raw + closures. This should be implemented by a separate assembly + language routine, since it would require argument processing, + something we don't do now for performance. */ + for (i = cif->nargs-1; i >= 0; i--) + switch (cif->arg_types[i]->type) + { + case FFI_TYPE_STRUCT: + case FFI_TYPE_LONGDOUBLE: + return FFI_BAD_TYPEDEF; + } + + switch (cif->abi) + { + case FFI_THISCALL: + dest = ffi_closure_raw_THISCALL; + break; + case FFI_SYSV: + dest = ffi_closure_raw_SYSV; + break; + default: + return FFI_BAD_ABI; + } + + /* movl imm, %eax. */ + tramp[0] = 0xb8; + *(void **)(tramp + 1) = codeloc; + + /* jmp dest */ + tramp[5] = 0xe9; + *(unsigned *)(tramp + 6) = (unsigned)dest - ((unsigned)codeloc + 10); + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + return FFI_OK; +} + +void +ffi_raw_call(ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_raw *avalue) +{ + size_t rsize, bytes; + struct call_frame *frame; + char *stack, *argp; + ffi_type **arg_types; + int flags, cabi, i, n, narg_reg; + const struct abi_params *pabi; + + flags = cif->flags; + cabi = cif->abi; + pabi = &abi_params[cabi]; + + rsize = 0; + if (rvalue == NULL) + { + switch (flags) + { + case X86_RET_FLOAT: + case X86_RET_DOUBLE: + case X86_RET_LDOUBLE: + case X86_RET_STRUCTPOP: + case X86_RET_STRUCTARG: + /* The float cases need to pop the 387 stack. + The struct cases need to pass a valid pointer to the callee. */ + rsize = cif->rtype->size; + break; + default: + /* We can pretend that the callee returns nothing. */ + flags = X86_RET_VOID; + break; + } + } + + bytes = STACK_ALIGN (cif->bytes); + argp = stack = + (void *)((uintptr_t)alloca(bytes + sizeof(*frame) + rsize + 15) & ~16); + frame = (struct call_frame *)(stack + bytes); + if (rsize) + rvalue = frame + 1; + + frame->fn = fn; + frame->flags = flags; + frame->rvalue = rvalue; + + narg_reg = 0; + switch (flags) + { + case X86_RET_STRUCTARG: + /* The pointer is passed as the first argument. */ + if (pabi->nregs > 0) + { + frame->regs[pabi->regs[0]] = (unsigned)rvalue; + narg_reg = 1; + break; + } + /* fallthru */ + case X86_RET_STRUCTPOP: + *(void **)argp = rvalue; + argp += sizeof(void *); + bytes -= sizeof(void *); + break; + } + + arg_types = cif->arg_types; + for (i = 0, n = cif->nargs; narg_reg < pabi->nregs && i < n; i++) + { + ffi_type *ty = arg_types[i]; + size_t z = ty->size; + int t = ty->type; + + if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT && t != FFI_TYPE_FLOAT) + { + ffi_arg val = extend_basic_type (avalue, t); + frame->regs[pabi->regs[narg_reg++]] = val; + z = FFI_SIZEOF_ARG; + } + else + { + memcpy (argp, avalue, z); + z = FFI_ALIGN (z, FFI_SIZEOF_ARG); + argp += z; + } + avalue += z; + bytes -= z; + } + if (i < n) + memcpy (argp, avalue, bytes); + + ffi_call_i386 (frame, stack); +} +#endif /* !FFI_NO_RAW_API */ +#endif /* __i386__ */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffi64.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffi64.c new file mode 100644 index 0000000..39f9598 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffi64.c @@ -0,0 +1,895 @@ +/* ----------------------------------------------------------------------- + ffi64.c - Copyright (c) 2011, 2018 Anthony Green + Copyright (c) 2013 The Written Word, Inc. + Copyright (c) 2008, 2010 Red Hat, Inc. + Copyright (c) 2002, 2007 Bo Thorsen + + x86-64 Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include +#include +#include +#include "internal64.h" + +#ifdef __x86_64__ + +#define MAX_GPR_REGS 6 +#define MAX_SSE_REGS 8 + +#if defined(__INTEL_COMPILER) +#include "xmmintrin.h" +#define UINT128 __m128 +#else +#if defined(__SUNPRO_C) +#include +#define UINT128 __m128i +#else +#define UINT128 __int128_t +#endif +#endif + +union big_int_union +{ + UINT32 i32; + UINT64 i64; + UINT128 i128; +}; + +struct register_args +{ + /* Registers for argument passing. */ + UINT64 gpr[MAX_GPR_REGS]; + union big_int_union sse[MAX_SSE_REGS]; + UINT64 rax; /* ssecount */ + UINT64 r10; /* static chain */ +}; + +extern void ffi_call_unix64 (void *args, unsigned long bytes, unsigned flags, + void *raddr, void (*fnaddr)(void)) FFI_HIDDEN; + +/* All reference to register classes here is identical to the code in + gcc/config/i386/i386.c. Do *not* change one without the other. */ + +/* Register class used for passing given 64bit part of the argument. + These represent classes as documented by the PS ABI, with the + exception of SSESF, SSEDF classes, that are basically SSE class, + just gcc will use SF or DFmode move instead of DImode to avoid + reformatting penalties. + + Similary we play games with INTEGERSI_CLASS to use cheaper SImode moves + whenever possible (upper half does contain padding). */ +enum x86_64_reg_class + { + X86_64_NO_CLASS, + X86_64_INTEGER_CLASS, + X86_64_INTEGERSI_CLASS, + X86_64_SSE_CLASS, + X86_64_SSESF_CLASS, + X86_64_SSEDF_CLASS, + X86_64_SSEUP_CLASS, + X86_64_X87_CLASS, + X86_64_X87UP_CLASS, + X86_64_COMPLEX_X87_CLASS, + X86_64_MEMORY_CLASS + }; + +#define MAX_CLASSES 4 + +#define SSE_CLASS_P(X) ((X) >= X86_64_SSE_CLASS && X <= X86_64_SSEUP_CLASS) + +/* x86-64 register passing implementation. See x86-64 ABI for details. Goal + of this code is to classify each 8bytes of incoming argument by the register + class and assign registers accordingly. */ + +/* Return the union class of CLASS1 and CLASS2. + See the x86-64 PS ABI for details. */ + +static enum x86_64_reg_class +merge_classes (enum x86_64_reg_class class1, enum x86_64_reg_class class2) +{ + /* Rule #1: If both classes are equal, this is the resulting class. */ + if (class1 == class2) + return class1; + + /* Rule #2: If one of the classes is NO_CLASS, the resulting class is + the other class. */ + if (class1 == X86_64_NO_CLASS) + return class2; + if (class2 == X86_64_NO_CLASS) + return class1; + + /* Rule #3: If one of the classes is MEMORY, the result is MEMORY. */ + if (class1 == X86_64_MEMORY_CLASS || class2 == X86_64_MEMORY_CLASS) + return X86_64_MEMORY_CLASS; + + /* Rule #4: If one of the classes is INTEGER, the result is INTEGER. */ + if ((class1 == X86_64_INTEGERSI_CLASS && class2 == X86_64_SSESF_CLASS) + || (class2 == X86_64_INTEGERSI_CLASS && class1 == X86_64_SSESF_CLASS)) + return X86_64_INTEGERSI_CLASS; + if (class1 == X86_64_INTEGER_CLASS || class1 == X86_64_INTEGERSI_CLASS + || class2 == X86_64_INTEGER_CLASS || class2 == X86_64_INTEGERSI_CLASS) + return X86_64_INTEGER_CLASS; + + /* Rule #5: If one of the classes is X87, X87UP, or COMPLEX_X87 class, + MEMORY is used. */ + if (class1 == X86_64_X87_CLASS + || class1 == X86_64_X87UP_CLASS + || class1 == X86_64_COMPLEX_X87_CLASS + || class2 == X86_64_X87_CLASS + || class2 == X86_64_X87UP_CLASS + || class2 == X86_64_COMPLEX_X87_CLASS) + return X86_64_MEMORY_CLASS; + + /* Rule #6: Otherwise class SSE is used. */ + return X86_64_SSE_CLASS; +} + +/* Classify the argument of type TYPE and mode MODE. + CLASSES will be filled by the register class used to pass each word + of the operand. The number of words is returned. In case the parameter + should be passed in memory, 0 is returned. As a special case for zero + sized containers, classes[0] will be NO_CLASS and 1 is returned. + + See the x86-64 PS ABI for details. +*/ +static size_t +classify_argument (ffi_type *type, enum x86_64_reg_class classes[], + size_t byte_offset) +{ + switch (type->type) + { + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + case FFI_TYPE_POINTER: + do_integer: + { + size_t size = byte_offset + type->size; + + if (size <= 4) + { + classes[0] = X86_64_INTEGERSI_CLASS; + return 1; + } + else if (size <= 8) + { + classes[0] = X86_64_INTEGER_CLASS; + return 1; + } + else if (size <= 12) + { + classes[0] = X86_64_INTEGER_CLASS; + classes[1] = X86_64_INTEGERSI_CLASS; + return 2; + } + else if (size <= 16) + { + classes[0] = classes[1] = X86_64_INTEGER_CLASS; + return 2; + } + else + FFI_ASSERT (0); + } + case FFI_TYPE_FLOAT: + if (!(byte_offset % 8)) + classes[0] = X86_64_SSESF_CLASS; + else + classes[0] = X86_64_SSE_CLASS; + return 1; + case FFI_TYPE_DOUBLE: + classes[0] = X86_64_SSEDF_CLASS; + return 1; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + classes[0] = X86_64_X87_CLASS; + classes[1] = X86_64_X87UP_CLASS; + return 2; +#endif + case FFI_TYPE_STRUCT: + { + const size_t UNITS_PER_WORD = 8; + size_t words = (type->size + UNITS_PER_WORD - 1) / UNITS_PER_WORD; + ffi_type **ptr; + unsigned int i; + enum x86_64_reg_class subclasses[MAX_CLASSES]; + + /* If the struct is larger than 32 bytes, pass it on the stack. */ + if (type->size > 32) + return 0; + + for (i = 0; i < words; i++) + classes[i] = X86_64_NO_CLASS; + + /* Zero sized arrays or structures are NO_CLASS. We return 0 to + signalize memory class, so handle it as special case. */ + if (!words) + { + case FFI_TYPE_VOID: + classes[0] = X86_64_NO_CLASS; + return 1; + } + + /* Merge the fields of structure. */ + for (ptr = type->elements; *ptr != NULL; ptr++) + { + size_t num; + + byte_offset = FFI_ALIGN (byte_offset, (*ptr)->alignment); + + num = classify_argument (*ptr, subclasses, byte_offset % 8); + if (num == 0) + return 0; + for (i = 0; i < num; i++) + { + size_t pos = byte_offset / 8; + classes[i + pos] = + merge_classes (subclasses[i], classes[i + pos]); + } + + byte_offset += (*ptr)->size; + } + + if (words > 2) + { + /* When size > 16 bytes, if the first one isn't + X86_64_SSE_CLASS or any other ones aren't + X86_64_SSEUP_CLASS, everything should be passed in + memory. */ + if (classes[0] != X86_64_SSE_CLASS) + return 0; + + for (i = 1; i < words; i++) + if (classes[i] != X86_64_SSEUP_CLASS) + return 0; + } + + /* Final merger cleanup. */ + for (i = 0; i < words; i++) + { + /* If one class is MEMORY, everything should be passed in + memory. */ + if (classes[i] == X86_64_MEMORY_CLASS) + return 0; + + /* The X86_64_SSEUP_CLASS should be always preceded by + X86_64_SSE_CLASS or X86_64_SSEUP_CLASS. */ + if (i > 1 && classes[i] == X86_64_SSEUP_CLASS + && classes[i - 1] != X86_64_SSE_CLASS + && classes[i - 1] != X86_64_SSEUP_CLASS) + { + /* The first one should never be X86_64_SSEUP_CLASS. */ + FFI_ASSERT (i != 0); + classes[i] = X86_64_SSE_CLASS; + } + + /* If X86_64_X87UP_CLASS isn't preceded by X86_64_X87_CLASS, + everything should be passed in memory. */ + if (i > 1 && classes[i] == X86_64_X87UP_CLASS + && (classes[i - 1] != X86_64_X87_CLASS)) + { + /* The first one should never be X86_64_X87UP_CLASS. */ + FFI_ASSERT (i != 0); + return 0; + } + } + return words; + } + case FFI_TYPE_COMPLEX: + { + ffi_type *inner = type->elements[0]; + switch (inner->type) + { + case FFI_TYPE_INT: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + goto do_integer; + + case FFI_TYPE_FLOAT: + classes[0] = X86_64_SSE_CLASS; + if (byte_offset % 8) + { + classes[1] = X86_64_SSESF_CLASS; + return 2; + } + return 1; + case FFI_TYPE_DOUBLE: + classes[0] = classes[1] = X86_64_SSEDF_CLASS; + return 2; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + classes[0] = X86_64_COMPLEX_X87_CLASS; + return 1; +#endif + } + } + } + abort(); +} + +/* Examine the argument and return set number of register required in each + class. Return zero iff parameter should be passed in memory, otherwise + the number of registers. */ + +static size_t +examine_argument (ffi_type *type, enum x86_64_reg_class classes[MAX_CLASSES], + _Bool in_return, int *pngpr, int *pnsse) +{ + size_t n; + unsigned int i; + int ngpr, nsse; + + n = classify_argument (type, classes, 0); + if (n == 0) + return 0; + + ngpr = nsse = 0; + for (i = 0; i < n; ++i) + switch (classes[i]) + { + case X86_64_INTEGER_CLASS: + case X86_64_INTEGERSI_CLASS: + ngpr++; + break; + case X86_64_SSE_CLASS: + case X86_64_SSESF_CLASS: + case X86_64_SSEDF_CLASS: + nsse++; + break; + case X86_64_NO_CLASS: + case X86_64_SSEUP_CLASS: + break; + case X86_64_X87_CLASS: + case X86_64_X87UP_CLASS: + case X86_64_COMPLEX_X87_CLASS: + return in_return != 0; + default: + abort (); + } + + *pngpr = ngpr; + *pnsse = nsse; + + return n; +} + +/* Perform machine dependent cif processing. */ + +#ifndef __ILP32__ +extern ffi_status +ffi_prep_cif_machdep_efi64(ffi_cif *cif); +#endif + +ffi_status FFI_HIDDEN +ffi_prep_cif_machdep (ffi_cif *cif) +{ + int gprcount, ssecount, i, avn, ngpr, nsse; + unsigned flags; + enum x86_64_reg_class classes[MAX_CLASSES]; + size_t bytes, n, rtype_size; + ffi_type *rtype; + +#ifndef __ILP32__ + if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64) + return ffi_prep_cif_machdep_efi64(cif); +#endif + if (cif->abi != FFI_UNIX64) + return FFI_BAD_ABI; + + gprcount = ssecount = 0; + + rtype = cif->rtype; + rtype_size = rtype->size; + switch (rtype->type) + { + case FFI_TYPE_VOID: + flags = UNIX64_RET_VOID; + break; + case FFI_TYPE_UINT8: + flags = UNIX64_RET_UINT8; + break; + case FFI_TYPE_SINT8: + flags = UNIX64_RET_SINT8; + break; + case FFI_TYPE_UINT16: + flags = UNIX64_RET_UINT16; + break; + case FFI_TYPE_SINT16: + flags = UNIX64_RET_SINT16; + break; + case FFI_TYPE_UINT32: + flags = UNIX64_RET_UINT32; + break; + case FFI_TYPE_INT: + case FFI_TYPE_SINT32: + flags = UNIX64_RET_SINT32; + break; + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + flags = UNIX64_RET_INT64; + break; + case FFI_TYPE_POINTER: + flags = (sizeof(void *) == 4 ? UNIX64_RET_UINT32 : UNIX64_RET_INT64); + break; + case FFI_TYPE_FLOAT: + flags = UNIX64_RET_XMM32; + break; + case FFI_TYPE_DOUBLE: + flags = UNIX64_RET_XMM64; + break; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + flags = UNIX64_RET_X87; + break; +#endif + case FFI_TYPE_STRUCT: + n = examine_argument (cif->rtype, classes, 1, &ngpr, &nsse); + if (n == 0) + { + /* The return value is passed in memory. A pointer to that + memory is the first argument. Allocate a register for it. */ + gprcount++; + /* We don't have to do anything in asm for the return. */ + flags = UNIX64_RET_VOID | UNIX64_FLAG_RET_IN_MEM; + } + else + { + _Bool sse0 = SSE_CLASS_P (classes[0]); + + if (rtype_size == 4 && sse0) + flags = UNIX64_RET_XMM32; + else if (rtype_size == 8) + flags = sse0 ? UNIX64_RET_XMM64 : UNIX64_RET_INT64; + else + { + _Bool sse1 = n == 2 && SSE_CLASS_P (classes[1]); + if (sse0 && sse1) + flags = UNIX64_RET_ST_XMM0_XMM1; + else if (sse0) + flags = UNIX64_RET_ST_XMM0_RAX; + else if (sse1) + flags = UNIX64_RET_ST_RAX_XMM0; + else + flags = UNIX64_RET_ST_RAX_RDX; + flags |= rtype_size << UNIX64_SIZE_SHIFT; + } + } + break; + case FFI_TYPE_COMPLEX: + switch (rtype->elements[0]->type) + { + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_SINT16: + case FFI_TYPE_INT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + flags = UNIX64_RET_ST_RAX_RDX | ((unsigned) rtype_size << UNIX64_SIZE_SHIFT); + break; + case FFI_TYPE_FLOAT: + flags = UNIX64_RET_XMM64; + break; + case FFI_TYPE_DOUBLE: + flags = UNIX64_RET_ST_XMM0_XMM1 | (16 << UNIX64_SIZE_SHIFT); + break; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + case FFI_TYPE_LONGDOUBLE: + flags = UNIX64_RET_X87_2; + break; +#endif + default: + return FFI_BAD_TYPEDEF; + } + break; + default: + return FFI_BAD_TYPEDEF; + } + + /* Go over all arguments and determine the way they should be passed. + If it's in a register and there is space for it, let that be so. If + not, add it's size to the stack byte count. */ + for (bytes = 0, i = 0, avn = cif->nargs; i < avn; i++) + { + if (examine_argument (cif->arg_types[i], classes, 0, &ngpr, &nsse) == 0 + || gprcount + ngpr > MAX_GPR_REGS + || ssecount + nsse > MAX_SSE_REGS) + { + long align = cif->arg_types[i]->alignment; + + if (align < 8) + align = 8; + + bytes = FFI_ALIGN (bytes, align); + bytes += cif->arg_types[i]->size; + } + else + { + gprcount += ngpr; + ssecount += nsse; + } + } + if (ssecount) + flags |= UNIX64_FLAG_XMM_ARGS; + + cif->flags = flags; + cif->bytes = (unsigned) FFI_ALIGN (bytes, 8); + + return FFI_OK; +} + +static void +ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + enum x86_64_reg_class classes[MAX_CLASSES]; + char *stack, *argp; + ffi_type **arg_types; + int gprcount, ssecount, ngpr, nsse, i, avn, flags; + struct register_args *reg_args; + + /* Can't call 32-bit mode from 64-bit mode. */ + FFI_ASSERT (cif->abi == FFI_UNIX64); + + /* If the return value is a struct and we don't have a return value + address then we need to make one. Otherwise we can ignore it. */ + flags = cif->flags; + if (rvalue == NULL) + { + if (flags & UNIX64_FLAG_RET_IN_MEM) + rvalue = alloca (cif->rtype->size); + else + flags = UNIX64_RET_VOID; + } + + /* Allocate the space for the arguments, plus 4 words of temp space. */ + stack = alloca (sizeof (struct register_args) + cif->bytes + 4*8); + reg_args = (struct register_args *) stack; + argp = stack + sizeof (struct register_args); + + reg_args->r10 = (uintptr_t) closure; + + gprcount = ssecount = 0; + + /* If the return value is passed in memory, add the pointer as the + first integer argument. */ + if (flags & UNIX64_FLAG_RET_IN_MEM) + reg_args->gpr[gprcount++] = (unsigned long) rvalue; + + avn = cif->nargs; + arg_types = cif->arg_types; + + for (i = 0; i < avn; ++i) + { + size_t n, size = arg_types[i]->size; + + n = examine_argument (arg_types[i], classes, 0, &ngpr, &nsse); + if (n == 0 + || gprcount + ngpr > MAX_GPR_REGS + || ssecount + nsse > MAX_SSE_REGS) + { + long align = arg_types[i]->alignment; + + /* Stack arguments are *always* at least 8 byte aligned. */ + if (align < 8) + align = 8; + + /* Pass this argument in memory. */ + argp = (void *) FFI_ALIGN (argp, align); + memcpy (argp, avalue[i], size); + argp += size; + } + else + { + /* The argument is passed entirely in registers. */ + char *a = (char *) avalue[i]; + unsigned int j; + + for (j = 0; j < n; j++, a += 8, size -= 8) + { + switch (classes[j]) + { + case X86_64_NO_CLASS: + case X86_64_SSEUP_CLASS: + break; + case X86_64_INTEGER_CLASS: + case X86_64_INTEGERSI_CLASS: + /* Sign-extend integer arguments passed in general + purpose registers, to cope with the fact that + LLVM incorrectly assumes that this will be done + (the x86-64 PS ABI does not specify this). */ + switch (arg_types[i]->type) + { + case FFI_TYPE_SINT8: + reg_args->gpr[gprcount] = (SINT64) *((SINT8 *) a); + break; + case FFI_TYPE_SINT16: + reg_args->gpr[gprcount] = (SINT64) *((SINT16 *) a); + break; + case FFI_TYPE_SINT32: + reg_args->gpr[gprcount] = (SINT64) *((SINT32 *) a); + break; + default: + reg_args->gpr[gprcount] = 0; + memcpy (®_args->gpr[gprcount], a, size); + } + gprcount++; + break; + case X86_64_SSE_CLASS: + case X86_64_SSEDF_CLASS: + memcpy (®_args->sse[ssecount++].i64, a, sizeof(UINT64)); + break; + case X86_64_SSESF_CLASS: + memcpy (®_args->sse[ssecount++].i32, a, sizeof(UINT32)); + break; + default: + abort(); + } + } + } + } + reg_args->rax = ssecount; + + ffi_call_unix64 (stack, cif->bytes + sizeof (struct register_args), + flags, rvalue, fn); +} + +#ifndef __ILP32__ +extern void +ffi_call_efi64(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue); +#endif + +void +ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ +#ifndef __ILP32__ + if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64) + { + ffi_call_efi64(cif, fn, rvalue, avalue); + return; + } +#endif + ffi_call_int (cif, fn, rvalue, avalue, NULL); +} + +#ifdef FFI_GO_CLOSURES + +#ifndef __ILP32__ +extern void +ffi_call_go_efi64(ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure); +#endif + +void +ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ +#ifndef __ILP32__ + if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64) + { + ffi_call_go_efi64(cif, fn, rvalue, avalue, closure); + return; + } +#endif + ffi_call_int (cif, fn, rvalue, avalue, closure); +} + +#endif /* FFI_GO_CLOSURES */ + +extern void ffi_closure_unix64(void) FFI_HIDDEN; +extern void ffi_closure_unix64_sse(void) FFI_HIDDEN; + +#ifndef __ILP32__ +extern ffi_status +ffi_prep_closure_loc_efi64(ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc); +#endif + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + static const unsigned char trampoline[24] = { + /* endbr64 */ + 0xf3, 0x0f, 0x1e, 0xfa, + /* leaq -0xb(%rip),%r10 # 0x0 */ + 0x4c, 0x8d, 0x15, 0xf5, 0xff, 0xff, 0xff, + /* jmpq *0x7(%rip) # 0x18 */ + 0xff, 0x25, 0x07, 0x00, 0x00, 0x00, + /* nopl 0(%rax) */ + 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00 + }; + void (*dest)(void); + char *tramp = closure->tramp; + +#ifndef __ILP32__ + if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64) + return ffi_prep_closure_loc_efi64(closure, cif, fun, user_data, codeloc); +#endif + if (cif->abi != FFI_UNIX64) + return FFI_BAD_ABI; + + if (cif->flags & UNIX64_FLAG_XMM_ARGS) + dest = ffi_closure_unix64_sse; + else + dest = ffi_closure_unix64; + + memcpy (tramp, trampoline, sizeof(trampoline)); + *(UINT64 *)(tramp + sizeof (trampoline)) = (uintptr_t)dest; + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + return FFI_OK; +} + +int FFI_HIDDEN +ffi_closure_unix64_inner(ffi_cif *cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *rvalue, + struct register_args *reg_args, + char *argp) +{ + void **avalue; + ffi_type **arg_types; + long i, avn; + int gprcount, ssecount, ngpr, nsse; + int flags; + + avn = cif->nargs; + flags = cif->flags; + avalue = alloca(avn * sizeof(void *)); + gprcount = ssecount = 0; + + if (flags & UNIX64_FLAG_RET_IN_MEM) + { + /* On return, %rax will contain the address that was passed + by the caller in %rdi. */ + void *r = (void *)(uintptr_t)reg_args->gpr[gprcount++]; + *(void **)rvalue = r; + rvalue = r; + flags = (sizeof(void *) == 4 ? UNIX64_RET_UINT32 : UNIX64_RET_INT64); + } + + arg_types = cif->arg_types; + for (i = 0; i < avn; ++i) + { + enum x86_64_reg_class classes[MAX_CLASSES]; + size_t n; + + n = examine_argument (arg_types[i], classes, 0, &ngpr, &nsse); + if (n == 0 + || gprcount + ngpr > MAX_GPR_REGS + || ssecount + nsse > MAX_SSE_REGS) + { + long align = arg_types[i]->alignment; + + /* Stack arguments are *always* at least 8 byte aligned. */ + if (align < 8) + align = 8; + + /* Pass this argument in memory. */ + argp = (void *) FFI_ALIGN (argp, align); + avalue[i] = argp; + argp += arg_types[i]->size; + } + /* If the argument is in a single register, or two consecutive + integer registers, then we can use that address directly. */ + else if (n == 1 + || (n == 2 && !(SSE_CLASS_P (classes[0]) + || SSE_CLASS_P (classes[1])))) + { + /* The argument is in a single register. */ + if (SSE_CLASS_P (classes[0])) + { + avalue[i] = ®_args->sse[ssecount]; + ssecount += n; + } + else + { + avalue[i] = ®_args->gpr[gprcount]; + gprcount += n; + } + } + /* Otherwise, allocate space to make them consecutive. */ + else + { + char *a = alloca (16); + unsigned int j; + + avalue[i] = a; + for (j = 0; j < n; j++, a += 8) + { + if (SSE_CLASS_P (classes[j])) + memcpy (a, ®_args->sse[ssecount++], 8); + else + memcpy (a, ®_args->gpr[gprcount++], 8); + } + } + } + + /* Invoke the closure. */ + fun (cif, rvalue, avalue, user_data); + + /* Tell assembly how to perform return type promotions. */ + return flags; +} + +#ifdef FFI_GO_CLOSURES + +extern void ffi_go_closure_unix64(void) FFI_HIDDEN; +extern void ffi_go_closure_unix64_sse(void) FFI_HIDDEN; + +#ifndef __ILP32__ +extern ffi_status +ffi_prep_go_closure_efi64(ffi_go_closure* closure, ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*)); +#endif + +ffi_status +ffi_prep_go_closure (ffi_go_closure* closure, ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*)) +{ +#ifndef __ILP32__ + if (cif->abi == FFI_EFI64 || cif->abi == FFI_GNUW64) + return ffi_prep_go_closure_efi64(closure, cif, fun); +#endif + if (cif->abi != FFI_UNIX64) + return FFI_BAD_ABI; + + closure->tramp = (cif->flags & UNIX64_FLAG_XMM_ARGS + ? ffi_go_closure_unix64_sse + : ffi_go_closure_unix64); + closure->cif = cif; + closure->fun = fun; + + return FFI_OK; +} + +#endif /* FFI_GO_CLOSURES */ + +#endif /* __x86_64__ */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffitarget.h new file mode 100644 index 0000000..a34f3e5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffitarget.h @@ -0,0 +1,160 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green + Copyright (c) 1996-2003, 2010 Red Hat, Inc. + Copyright (C) 2008 Free Software Foundation, Inc. + + Target configuration macros for x86 and x86-64. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +/* ---- System specific configurations ----------------------------------- */ + +/* For code common to all platforms on x86 and x86_64. */ +#define X86_ANY + +#if defined (X86_64) && defined (__i386__) +#undef X86_64 +#define X86 +#endif + +#ifdef X86_WIN64 +#define FFI_SIZEOF_ARG 8 +#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */ +#endif + +#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION +#ifndef _MSC_VER +#define FFI_TARGET_HAS_COMPLEX_TYPE +#endif + +/* ---- Generic type definitions ----------------------------------------- */ + +#ifndef LIBFFI_ASM +#ifdef X86_WIN64 +#ifdef _MSC_VER +typedef unsigned __int64 ffi_arg; +typedef __int64 ffi_sarg; +#else +typedef unsigned long long ffi_arg; +typedef long long ffi_sarg; +#endif +#else +#if defined __x86_64__ && defined __ILP32__ +#define FFI_SIZEOF_ARG 8 +#define FFI_SIZEOF_JAVA_RAW 4 +typedef unsigned long long ffi_arg; +typedef long long ffi_sarg; +#else +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; +#endif +#endif + +typedef enum ffi_abi { +#if defined(X86_WIN64) + FFI_FIRST_ABI = 0, + FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */ + FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */ + FFI_LAST_ABI, +#ifdef __GNUC__ + FFI_DEFAULT_ABI = FFI_GNUW64 +#else + FFI_DEFAULT_ABI = FFI_WIN64 +#endif + +#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN)) + FFI_FIRST_ABI = 1, + FFI_UNIX64, + FFI_WIN64, + FFI_EFI64 = FFI_WIN64, + FFI_GNUW64, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_UNIX64 + +#elif defined(X86_WIN32) + FFI_FIRST_ABI = 0, + FFI_SYSV = 1, + FFI_STDCALL = 2, + FFI_THISCALL = 3, + FFI_FASTCALL = 4, + FFI_MS_CDECL = 5, + FFI_PASCAL = 6, + FFI_REGISTER = 7, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_MS_CDECL +#else + FFI_FIRST_ABI = 0, + FFI_SYSV = 1, + FFI_THISCALL = 3, + FFI_FASTCALL = 4, + FFI_STDCALL = 5, + FFI_PASCAL = 6, + FFI_REGISTER = 7, + FFI_MS_CDECL = 8, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +#endif +} ffi_abi; +#endif + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_GO_CLOSURES 1 + +#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1) +#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2) +#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3) +#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4) + +#if defined (X86_64) || defined(X86_WIN64) \ + || (defined (__x86_64__) && defined (X86_DARWIN)) +/* 4 bytes of ENDBR64 + 7 bytes of LEA + 6 bytes of JMP + 7 bytes of NOP + + 8 bytes of pointer. */ +# define FFI_TRAMPOLINE_SIZE 32 +# define FFI_NATIVE_RAW_API 0 +#else +/* 4 bytes of ENDBR32 + 5 bytes of MOV + 5 bytes of JMP + 2 unused + bytes. */ +# define FFI_TRAMPOLINE_SIZE 16 +# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */ +#endif + +#if !defined(GENERATE_LIBFFI_MAP) && defined(__ASSEMBLER__) \ + && defined(__CET__) +# include +# define _CET_NOTRACK notrack +#else +# define _CET_ENDBR +# define _CET_NOTRACK +#endif + +#endif + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffiw64.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffiw64.c new file mode 100644 index 0000000..a43a9eb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/ffiw64.c @@ -0,0 +1,318 @@ +/* ----------------------------------------------------------------------- + ffiw64.c - Copyright (c) 2018 Anthony Green + Copyright (c) 2014 Red Hat, Inc. + + x86 win64 Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#if defined(__x86_64__) || defined(_M_AMD64) +#include +#include +#include +#include + +#ifdef X86_WIN64 +#define EFI64(name) name +#else +#define EFI64(name) FFI_HIDDEN name##_efi64 +#endif + +struct win64_call_frame +{ + UINT64 rbp; /* 0 */ + UINT64 retaddr; /* 8 */ + UINT64 fn; /* 16 */ + UINT64 flags; /* 24 */ + UINT64 rvalue; /* 32 */ +}; + +extern void ffi_call_win64 (void *stack, struct win64_call_frame *, + void *closure) FFI_HIDDEN; + +ffi_status FFI_HIDDEN +EFI64(ffi_prep_cif_machdep)(ffi_cif *cif) +{ + int flags, n; + + switch (cif->abi) + { + case FFI_WIN64: + case FFI_GNUW64: + break; + default: + return FFI_BAD_ABI; + } + + flags = cif->rtype->type; + switch (flags) + { + default: + break; + case FFI_TYPE_LONGDOUBLE: + /* GCC returns long double values by reference, like a struct */ + if (cif->abi == FFI_GNUW64) + flags = FFI_TYPE_STRUCT; + break; + case FFI_TYPE_COMPLEX: + flags = FFI_TYPE_STRUCT; + /* FALLTHRU */ + case FFI_TYPE_STRUCT: + switch (cif->rtype->size) + { + case 8: + flags = FFI_TYPE_UINT64; + break; + case 4: + flags = FFI_TYPE_SMALL_STRUCT_4B; + break; + case 2: + flags = FFI_TYPE_SMALL_STRUCT_2B; + break; + case 1: + flags = FFI_TYPE_SMALL_STRUCT_1B; + break; + } + break; + } + cif->flags = flags; + + /* Each argument either fits in a register, an 8 byte slot, or is + passed by reference with the pointer in the 8 byte slot. */ + n = cif->nargs; + n += (flags == FFI_TYPE_STRUCT); + if (n < 4) + n = 4; + cif->bytes = n * 8; + + return FFI_OK; +} + +static void +ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + int i, j, n, flags; + UINT64 *stack; + size_t rsize; + struct win64_call_frame *frame; + + FFI_ASSERT(cif->abi == FFI_GNUW64 || cif->abi == FFI_WIN64); + + flags = cif->flags; + rsize = 0; + + /* If we have no return value for a structure, we need to create one. + Otherwise we can ignore the return type entirely. */ + if (rvalue == NULL) + { + if (flags == FFI_TYPE_STRUCT) + rsize = cif->rtype->size; + else + flags = FFI_TYPE_VOID; + } + + stack = alloca(cif->bytes + sizeof(struct win64_call_frame) + rsize); + frame = (struct win64_call_frame *)((char *)stack + cif->bytes); + if (rsize) + rvalue = frame + 1; + + frame->fn = (uintptr_t)fn; + frame->flags = flags; + frame->rvalue = (uintptr_t)rvalue; + + j = 0; + if (flags == FFI_TYPE_STRUCT) + { + stack[0] = (uintptr_t)rvalue; + j = 1; + } + + for (i = 0, n = cif->nargs; i < n; ++i, ++j) + { + switch (cif->arg_types[i]->size) + { + case 8: + stack[j] = *(UINT64 *)avalue[i]; + break; + case 4: + stack[j] = *(UINT32 *)avalue[i]; + break; + case 2: + stack[j] = *(UINT16 *)avalue[i]; + break; + case 1: + stack[j] = *(UINT8 *)avalue[i]; + break; + default: + stack[j] = (uintptr_t)avalue[i]; + break; + } + } + + ffi_call_win64 (stack, frame, closure); +} + +void +EFI64(ffi_call)(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) +{ + ffi_call_int (cif, fn, rvalue, avalue, NULL); +} + +void +EFI64(ffi_call_go)(ffi_cif *cif, void (*fn)(void), void *rvalue, + void **avalue, void *closure) +{ + ffi_call_int (cif, fn, rvalue, avalue, closure); +} + + +extern void ffi_closure_win64(void) FFI_HIDDEN; + +#ifdef FFI_GO_CLOSURES +extern void ffi_go_closure_win64(void) FFI_HIDDEN; +#endif + +ffi_status +EFI64(ffi_prep_closure_loc)(ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + static const unsigned char trampoline[FFI_TRAMPOLINE_SIZE - 8] = { + /* endbr64 */ + 0xf3, 0x0f, 0x1e, 0xfa, + /* leaq -0xb(%rip),%r10 # 0x0 */ + 0x4c, 0x8d, 0x15, 0xf5, 0xff, 0xff, 0xff, + /* jmpq *0x7(%rip) # 0x18 */ + 0xff, 0x25, 0x07, 0x00, 0x00, 0x00, + /* nopl 0(%rax) */ + 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00 + }; + char *tramp = closure->tramp; + + switch (cif->abi) + { + case FFI_WIN64: + case FFI_GNUW64: + break; + default: + return FFI_BAD_ABI; + } + + memcpy (tramp, trampoline, sizeof(trampoline)); + *(UINT64 *)(tramp + sizeof (trampoline)) = (uintptr_t)ffi_closure_win64; + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + + return FFI_OK; +} + +#ifdef FFI_GO_CLOSURES +ffi_status +EFI64(ffi_prep_go_closure)(ffi_go_closure* closure, ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*)) +{ + switch (cif->abi) + { + case FFI_WIN64: + case FFI_GNUW64: + break; + default: + return FFI_BAD_ABI; + } + + closure->tramp = ffi_go_closure_win64; + closure->cif = cif; + closure->fun = fun; + + return FFI_OK; +} +#endif + +struct win64_closure_frame +{ + UINT64 rvalue[2]; + UINT64 fargs[4]; + UINT64 retaddr; + UINT64 args[]; +}; + +/* Force the inner function to use the MS ABI. When compiling on win64 + this is a nop. When compiling on unix, this simplifies the assembly, + and places the burden of saving the extra call-saved registers on + the compiler. */ +int FFI_HIDDEN __attribute__((ms_abi)) +ffi_closure_win64_inner(ffi_cif *cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + struct win64_closure_frame *frame) +{ + void **avalue; + void *rvalue; + int i, n, nreg, flags; + + avalue = alloca(cif->nargs * sizeof(void *)); + rvalue = frame->rvalue; + nreg = 0; + + /* When returning a structure, the address is in the first argument. + We must also be prepared to return the same address in eax, so + install that address in the frame and pretend we return a pointer. */ + flags = cif->flags; + if (flags == FFI_TYPE_STRUCT) + { + rvalue = (void *)(uintptr_t)frame->args[0]; + frame->rvalue[0] = frame->args[0]; + nreg = 1; + } + + for (i = 0, n = cif->nargs; i < n; ++i, ++nreg) + { + size_t size = cif->arg_types[i]->size; + size_t type = cif->arg_types[i]->type; + void *a; + + if (type == FFI_TYPE_DOUBLE || type == FFI_TYPE_FLOAT) + { + if (nreg < 4) + a = &frame->fargs[nreg]; + else + a = &frame->args[nreg]; + } + else if (size == 1 || size == 2 || size == 4 || size == 8) + a = &frame->args[nreg]; + else + a = (void *)(uintptr_t)frame->args[nreg]; + + avalue[i] = a; + } + + /* Invoke the closure. */ + fun (cif, rvalue, avalue, user_data); + return flags; +} + +#endif /* __x86_64__ */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/internal.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/internal.h new file mode 100644 index 0000000..09771ba --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/internal.h @@ -0,0 +1,29 @@ +#define X86_RET_FLOAT 0 +#define X86_RET_DOUBLE 1 +#define X86_RET_LDOUBLE 2 +#define X86_RET_SINT8 3 +#define X86_RET_SINT16 4 +#define X86_RET_UINT8 5 +#define X86_RET_UINT16 6 +#define X86_RET_INT64 7 +#define X86_RET_INT32 8 +#define X86_RET_VOID 9 +#define X86_RET_STRUCTPOP 10 +#define X86_RET_STRUCTARG 11 +#define X86_RET_STRUCT_1B 12 +#define X86_RET_STRUCT_2B 13 +#define X86_RET_UNUSED14 14 +#define X86_RET_UNUSED15 15 + +#define X86_RET_TYPE_MASK 15 +#define X86_RET_POP_SHIFT 4 + +#define R_EAX 0 +#define R_EDX 1 +#define R_ECX 2 + +#ifdef __PCC__ +# define HAVE_FASTCALL 0 +#else +# define HAVE_FASTCALL 1 +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/internal64.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/internal64.h new file mode 100644 index 0000000..512e955 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/internal64.h @@ -0,0 +1,22 @@ +#define UNIX64_RET_VOID 0 +#define UNIX64_RET_UINT8 1 +#define UNIX64_RET_UINT16 2 +#define UNIX64_RET_UINT32 3 +#define UNIX64_RET_SINT8 4 +#define UNIX64_RET_SINT16 5 +#define UNIX64_RET_SINT32 6 +#define UNIX64_RET_INT64 7 +#define UNIX64_RET_XMM32 8 +#define UNIX64_RET_XMM64 9 +#define UNIX64_RET_X87 10 +#define UNIX64_RET_X87_2 11 +#define UNIX64_RET_ST_XMM0_RAX 12 +#define UNIX64_RET_ST_RAX_XMM0 13 +#define UNIX64_RET_ST_XMM0_XMM1 14 +#define UNIX64_RET_ST_RAX_RDX 15 + +#define UNIX64_RET_LAST 15 + +#define UNIX64_FLAG_RET_IN_MEM (1 << 10) +#define UNIX64_FLAG_XMM_ARGS (1 << 11) +#define UNIX64_SIZE_SHIFT 12 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/sysv.S new file mode 100644 index 0000000..d8ab4b0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/sysv.S @@ -0,0 +1,1138 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2017 Anthony Green + - Copyright (c) 2013 The Written Word, Inc. + - Copyright (c) 1996,1998,2001-2003,2005,2008,2010 Red Hat, Inc. + + X86 Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#ifdef __i386__ +#ifndef _MSC_VER + +#define LIBFFI_ASM +#include +#include +#include "internal.h" + +#define C2(X, Y) X ## Y +#define C1(X, Y) C2(X, Y) +#ifdef __USER_LABEL_PREFIX__ +# define C(X) C1(__USER_LABEL_PREFIX__, X) +#else +# define C(X) X +#endif + +#ifdef X86_DARWIN +# define L(X) C1(L, X) +#else +# define L(X) C1(.L, X) +#endif + +#ifdef __ELF__ +# define ENDF(X) .type X,@function; .size X, . - X +#else +# define ENDF(X) +#endif + +/* Handle win32 fastcall name mangling. */ +#ifdef X86_WIN32 +# define ffi_call_i386 "@ffi_call_i386@8" +# define ffi_closure_inner "@ffi_closure_inner@8" +#else +# define ffi_call_i386 C(ffi_call_i386) +# define ffi_closure_inner C(ffi_closure_inner) +#endif + +/* This macro allows the safe creation of jump tables without an + actual table. The entry points into the table are all 8 bytes. + The use of ORG asserts that we're at the correct location. */ +/* ??? The clang assembler doesn't handle .org with symbolic expressions. */ +#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__)) +# define E(BASE, X) .balign 8 +#else +# define E(BASE, X) .balign 8; .org BASE + X * 8 +#endif + + .text + .balign 16 + .globl ffi_call_i386 + FFI_HIDDEN(ffi_call_i386) + +/* This is declared as + + void ffi_call_i386(struct call_frame *frame, char *argp) + __attribute__((fastcall)); + + Thus the arguments are present in + + ecx: frame + edx: argp +*/ + +ffi_call_i386: +L(UW0): + # cfi_startproc + _CET_ENDBR +#if !HAVE_FASTCALL + movl 4(%esp), %ecx + movl 8(%esp), %edx +#endif + movl (%esp), %eax /* move the return address */ + movl %ebp, (%ecx) /* store %ebp into local frame */ + movl %eax, 4(%ecx) /* store retaddr into local frame */ + + /* New stack frame based off ebp. This is a itty bit of unwind + trickery in that the CFA *has* changed. There is no easy way + to describe it correctly on entry to the function. Fortunately, + it doesn't matter too much since at all points we can correctly + unwind back to ffi_call. Note that the location to which we + moved the return address is (the new) CFA-4, so from the + perspective of the unwind info, it hasn't moved. */ + movl %ecx, %ebp +L(UW1): + # cfi_def_cfa(%ebp, 8) + # cfi_rel_offset(%ebp, 0) + + movl %edx, %esp /* set outgoing argument stack */ + movl 20+R_EAX*4(%ebp), %eax /* set register arguments */ + movl 20+R_EDX*4(%ebp), %edx + movl 20+R_ECX*4(%ebp), %ecx + + call *8(%ebp) + + movl 12(%ebp), %ecx /* load return type code */ + movl %ebx, 8(%ebp) /* preserve %ebx */ +L(UW2): + # cfi_rel_offset(%ebx, 8) + + andl $X86_RET_TYPE_MASK, %ecx +#ifdef __PIC__ + call C(__x86.get_pc_thunk.bx) +L(pc1): + leal L(store_table)-L(pc1)(%ebx, %ecx, 8), %ebx +#else + leal L(store_table)(,%ecx, 8), %ebx +#endif + movl 16(%ebp), %ecx /* load result address */ + _CET_NOTRACK jmp *%ebx + + .balign 8 +L(store_table): +E(L(store_table), X86_RET_FLOAT) + fstps (%ecx) + jmp L(e1) +E(L(store_table), X86_RET_DOUBLE) + fstpl (%ecx) + jmp L(e1) +E(L(store_table), X86_RET_LDOUBLE) + fstpt (%ecx) + jmp L(e1) +E(L(store_table), X86_RET_SINT8) + movsbl %al, %eax + mov %eax, (%ecx) + jmp L(e1) +E(L(store_table), X86_RET_SINT16) + movswl %ax, %eax + mov %eax, (%ecx) + jmp L(e1) +E(L(store_table), X86_RET_UINT8) + movzbl %al, %eax + mov %eax, (%ecx) + jmp L(e1) +E(L(store_table), X86_RET_UINT16) + movzwl %ax, %eax + mov %eax, (%ecx) + jmp L(e1) +E(L(store_table), X86_RET_INT64) + movl %edx, 4(%ecx) + /* fallthru */ +E(L(store_table), X86_RET_INT32) + movl %eax, (%ecx) + /* fallthru */ +E(L(store_table), X86_RET_VOID) +L(e1): + movl 8(%ebp), %ebx + movl %ebp, %esp + popl %ebp +L(UW3): + # cfi_remember_state + # cfi_def_cfa(%esp, 4) + # cfi_restore(%ebx) + # cfi_restore(%ebp) + ret +L(UW4): + # cfi_restore_state + +E(L(store_table), X86_RET_STRUCTPOP) + jmp L(e1) +E(L(store_table), X86_RET_STRUCTARG) + jmp L(e1) +E(L(store_table), X86_RET_STRUCT_1B) + movb %al, (%ecx) + jmp L(e1) +E(L(store_table), X86_RET_STRUCT_2B) + movw %ax, (%ecx) + jmp L(e1) + + /* Fill out the table so that bad values are predictable. */ +E(L(store_table), X86_RET_UNUSED14) + ud2 +E(L(store_table), X86_RET_UNUSED15) + ud2 + +L(UW5): + # cfi_endproc +ENDF(ffi_call_i386) + +/* The inner helper is declared as + + void ffi_closure_inner(struct closure_frame *frame, char *argp) + __attribute_((fastcall)) + + Thus the arguments are placed in + + ecx: frame + edx: argp +*/ + +/* Macros to help setting up the closure_data structure. */ + +#if HAVE_FASTCALL +# define closure_FS (40 + 4) +# define closure_CF 0 +#else +# define closure_FS (8 + 40 + 12) +# define closure_CF 8 +#endif + +#define FFI_CLOSURE_SAVE_REGS \ + movl %eax, closure_CF+16+R_EAX*4(%esp); \ + movl %edx, closure_CF+16+R_EDX*4(%esp); \ + movl %ecx, closure_CF+16+R_ECX*4(%esp) + +#define FFI_CLOSURE_COPY_TRAMP_DATA \ + movl FFI_TRAMPOLINE_SIZE(%eax), %edx; /* copy cif */ \ + movl FFI_TRAMPOLINE_SIZE+4(%eax), %ecx; /* copy fun */ \ + movl FFI_TRAMPOLINE_SIZE+8(%eax), %eax; /* copy user_data */ \ + movl %edx, closure_CF+28(%esp); \ + movl %ecx, closure_CF+32(%esp); \ + movl %eax, closure_CF+36(%esp) + +#if HAVE_FASTCALL +# define FFI_CLOSURE_PREP_CALL \ + movl %esp, %ecx; /* load closure_data */ \ + leal closure_FS+4(%esp), %edx; /* load incoming stack */ +#else +# define FFI_CLOSURE_PREP_CALL \ + leal closure_CF(%esp), %ecx; /* load closure_data */ \ + leal closure_FS+4(%esp), %edx; /* load incoming stack */ \ + movl %ecx, (%esp); \ + movl %edx, 4(%esp) +#endif + +#define FFI_CLOSURE_CALL_INNER(UWN) \ + call ffi_closure_inner + +#define FFI_CLOSURE_MASK_AND_JUMP(N, UW) \ + andl $X86_RET_TYPE_MASK, %eax; \ + leal L(C1(load_table,N))(, %eax, 8), %edx; \ + movl closure_CF(%esp), %eax; /* optimiztic load */ \ + _CET_NOTRACK jmp *%edx + +#ifdef __PIC__ +# if defined X86_DARWIN || defined HAVE_HIDDEN_VISIBILITY_ATTRIBUTE +# undef FFI_CLOSURE_MASK_AND_JUMP +# define FFI_CLOSURE_MASK_AND_JUMP(N, UW) \ + andl $X86_RET_TYPE_MASK, %eax; \ + call C(__x86.get_pc_thunk.dx); \ +L(C1(pc,N)): \ + leal L(C1(load_table,N))-L(C1(pc,N))(%edx, %eax, 8), %edx; \ + movl closure_CF(%esp), %eax; /* optimiztic load */ \ + _CET_NOTRACK jmp *%edx +# else +# define FFI_CLOSURE_CALL_INNER_SAVE_EBX +# undef FFI_CLOSURE_CALL_INNER +# define FFI_CLOSURE_CALL_INNER(UWN) \ + movl %ebx, 40(%esp); /* save ebx */ \ +L(C1(UW,UWN)): \ + /* cfi_rel_offset(%ebx, 40); */ \ + call C(__x86.get_pc_thunk.bx); /* load got register */ \ + addl $C(_GLOBAL_OFFSET_TABLE_), %ebx; \ + call ffi_closure_inner@PLT +# undef FFI_CLOSURE_MASK_AND_JUMP +# define FFI_CLOSURE_MASK_AND_JUMP(N, UWN) \ + andl $X86_RET_TYPE_MASK, %eax; \ + leal L(C1(load_table,N))@GOTOFF(%ebx, %eax, 8), %edx; \ + movl 40(%esp), %ebx; /* restore ebx */ \ +L(C1(UW,UWN)): \ + /* cfi_restore(%ebx); */ \ + movl closure_CF(%esp), %eax; /* optimiztic load */ \ + _CET_NOTRACK jmp *%edx +# endif /* DARWIN || HIDDEN */ +#endif /* __PIC__ */ + + .balign 16 + .globl C(ffi_go_closure_EAX) + FFI_HIDDEN(C(ffi_go_closure_EAX)) +C(ffi_go_closure_EAX): +L(UW6): + # cfi_startproc + _CET_ENDBR + subl $closure_FS, %esp +L(UW7): + # cfi_def_cfa_offset(closure_FS + 4) + FFI_CLOSURE_SAVE_REGS + movl 4(%eax), %edx /* copy cif */ + movl 8(%eax), %ecx /* copy fun */ + movl %edx, closure_CF+28(%esp) + movl %ecx, closure_CF+32(%esp) + movl %eax, closure_CF+36(%esp) /* closure is user_data */ + jmp L(do_closure_i386) +L(UW8): + # cfi_endproc +ENDF(C(ffi_go_closure_EAX)) + + .balign 16 + .globl C(ffi_go_closure_ECX) + FFI_HIDDEN(C(ffi_go_closure_ECX)) +C(ffi_go_closure_ECX): +L(UW9): + # cfi_startproc + _CET_ENDBR + subl $closure_FS, %esp +L(UW10): + # cfi_def_cfa_offset(closure_FS + 4) + FFI_CLOSURE_SAVE_REGS + movl 4(%ecx), %edx /* copy cif */ + movl 8(%ecx), %eax /* copy fun */ + movl %edx, closure_CF+28(%esp) + movl %eax, closure_CF+32(%esp) + movl %ecx, closure_CF+36(%esp) /* closure is user_data */ + jmp L(do_closure_i386) +L(UW11): + # cfi_endproc +ENDF(C(ffi_go_closure_ECX)) + +/* The closure entry points are reached from the ffi_closure trampoline. + On entry, %eax contains the address of the ffi_closure. */ + + .balign 16 + .globl C(ffi_closure_i386) + FFI_HIDDEN(C(ffi_closure_i386)) + +C(ffi_closure_i386): +L(UW12): + # cfi_startproc + _CET_ENDBR + subl $closure_FS, %esp +L(UW13): + # cfi_def_cfa_offset(closure_FS + 4) + + FFI_CLOSURE_SAVE_REGS + FFI_CLOSURE_COPY_TRAMP_DATA + + /* Entry point from preceeding Go closures. */ +L(do_closure_i386): + + FFI_CLOSURE_PREP_CALL + FFI_CLOSURE_CALL_INNER(14) + FFI_CLOSURE_MASK_AND_JUMP(2, 15) + + .balign 8 +L(load_table2): +E(L(load_table2), X86_RET_FLOAT) + flds closure_CF(%esp) + jmp L(e2) +E(L(load_table2), X86_RET_DOUBLE) + fldl closure_CF(%esp) + jmp L(e2) +E(L(load_table2), X86_RET_LDOUBLE) + fldt closure_CF(%esp) + jmp L(e2) +E(L(load_table2), X86_RET_SINT8) + movsbl %al, %eax + jmp L(e2) +E(L(load_table2), X86_RET_SINT16) + movswl %ax, %eax + jmp L(e2) +E(L(load_table2), X86_RET_UINT8) + movzbl %al, %eax + jmp L(e2) +E(L(load_table2), X86_RET_UINT16) + movzwl %ax, %eax + jmp L(e2) +E(L(load_table2), X86_RET_INT64) + movl closure_CF+4(%esp), %edx + jmp L(e2) +E(L(load_table2), X86_RET_INT32) + nop + /* fallthru */ +E(L(load_table2), X86_RET_VOID) +L(e2): + addl $closure_FS, %esp +L(UW16): + # cfi_adjust_cfa_offset(-closure_FS) + ret +L(UW17): + # cfi_adjust_cfa_offset(closure_FS) +E(L(load_table2), X86_RET_STRUCTPOP) + addl $closure_FS, %esp +L(UW18): + # cfi_adjust_cfa_offset(-closure_FS) + ret $4 +L(UW19): + # cfi_adjust_cfa_offset(closure_FS) +E(L(load_table2), X86_RET_STRUCTARG) + jmp L(e2) +E(L(load_table2), X86_RET_STRUCT_1B) + movzbl %al, %eax + jmp L(e2) +E(L(load_table2), X86_RET_STRUCT_2B) + movzwl %ax, %eax + jmp L(e2) + + /* Fill out the table so that bad values are predictable. */ +E(L(load_table2), X86_RET_UNUSED14) + ud2 +E(L(load_table2), X86_RET_UNUSED15) + ud2 + +L(UW20): + # cfi_endproc +ENDF(C(ffi_closure_i386)) + + .balign 16 + .globl C(ffi_go_closure_STDCALL) + FFI_HIDDEN(C(ffi_go_closure_STDCALL)) +C(ffi_go_closure_STDCALL): +L(UW21): + # cfi_startproc + _CET_ENDBR + subl $closure_FS, %esp +L(UW22): + # cfi_def_cfa_offset(closure_FS + 4) + FFI_CLOSURE_SAVE_REGS + movl 4(%ecx), %edx /* copy cif */ + movl 8(%ecx), %eax /* copy fun */ + movl %edx, closure_CF+28(%esp) + movl %eax, closure_CF+32(%esp) + movl %ecx, closure_CF+36(%esp) /* closure is user_data */ + jmp L(do_closure_STDCALL) +L(UW23): + # cfi_endproc +ENDF(C(ffi_go_closure_STDCALL)) + +/* For REGISTER, we have no available parameter registers, and so we + enter here having pushed the closure onto the stack. */ + + .balign 16 + .globl C(ffi_closure_REGISTER) + FFI_HIDDEN(C(ffi_closure_REGISTER)) +C(ffi_closure_REGISTER): +L(UW24): + # cfi_startproc + # cfi_def_cfa(%esp, 8) + # cfi_offset(%eip, -8) + _CET_ENDBR + subl $closure_FS-4, %esp +L(UW25): + # cfi_def_cfa_offset(closure_FS + 4) + FFI_CLOSURE_SAVE_REGS + movl closure_FS-4(%esp), %ecx /* load retaddr */ + movl closure_FS(%esp), %eax /* load closure */ + movl %ecx, closure_FS(%esp) /* move retaddr */ + jmp L(do_closure_REGISTER) +L(UW26): + # cfi_endproc +ENDF(C(ffi_closure_REGISTER)) + +/* For STDCALL (and others), we need to pop N bytes of arguments off + the stack following the closure. The amount needing to be popped + is returned to us from ffi_closure_inner. */ + + .balign 16 + .globl C(ffi_closure_STDCALL) + FFI_HIDDEN(C(ffi_closure_STDCALL)) +C(ffi_closure_STDCALL): +L(UW27): + # cfi_startproc + _CET_ENDBR + subl $closure_FS, %esp +L(UW28): + # cfi_def_cfa_offset(closure_FS + 4) + + FFI_CLOSURE_SAVE_REGS + + /* Entry point from ffi_closure_REGISTER. */ +L(do_closure_REGISTER): + + FFI_CLOSURE_COPY_TRAMP_DATA + + /* Entry point from preceeding Go closure. */ +L(do_closure_STDCALL): + + FFI_CLOSURE_PREP_CALL + FFI_CLOSURE_CALL_INNER(29) + + movl %eax, %ecx + shrl $X86_RET_POP_SHIFT, %ecx /* isolate pop count */ + leal closure_FS(%esp, %ecx), %ecx /* compute popped esp */ + movl closure_FS(%esp), %edx /* move return address */ + movl %edx, (%ecx) + + /* From this point on, the value of %esp upon return is %ecx+4, + and we've copied the return address to %ecx to make return easy. + There's no point in representing this in the unwind info, as + there is always a window between the mov and the ret which + will be wrong from one point of view or another. */ + + FFI_CLOSURE_MASK_AND_JUMP(3, 30) + + .balign 8 +L(load_table3): +E(L(load_table3), X86_RET_FLOAT) + flds closure_CF(%esp) + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_DOUBLE) + fldl closure_CF(%esp) + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_LDOUBLE) + fldt closure_CF(%esp) + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_SINT8) + movsbl %al, %eax + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_SINT16) + movswl %ax, %eax + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_UINT8) + movzbl %al, %eax + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_UINT16) + movzwl %ax, %eax + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_INT64) + movl closure_CF+4(%esp), %edx + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_INT32) + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_VOID) + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_STRUCTPOP) + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_STRUCTARG) + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_STRUCT_1B) + movzbl %al, %eax + movl %ecx, %esp + ret +E(L(load_table3), X86_RET_STRUCT_2B) + movzwl %ax, %eax + movl %ecx, %esp + ret + + /* Fill out the table so that bad values are predictable. */ +E(L(load_table3), X86_RET_UNUSED14) + ud2 +E(L(load_table3), X86_RET_UNUSED15) + ud2 + +L(UW31): + # cfi_endproc +ENDF(C(ffi_closure_STDCALL)) + +#if !FFI_NO_RAW_API + +#define raw_closure_S_FS (16+16+12) + + .balign 16 + .globl C(ffi_closure_raw_SYSV) + FFI_HIDDEN(C(ffi_closure_raw_SYSV)) +C(ffi_closure_raw_SYSV): +L(UW32): + # cfi_startproc + _CET_ENDBR + subl $raw_closure_S_FS, %esp +L(UW33): + # cfi_def_cfa_offset(raw_closure_S_FS + 4) + movl %ebx, raw_closure_S_FS-4(%esp) +L(UW34): + # cfi_rel_offset(%ebx, raw_closure_S_FS-4) + + movl FFI_TRAMPOLINE_SIZE+8(%eax), %edx /* load cl->user_data */ + movl %edx, 12(%esp) + leal raw_closure_S_FS+4(%esp), %edx /* load raw_args */ + movl %edx, 8(%esp) + leal 16(%esp), %edx /* load &res */ + movl %edx, 4(%esp) + movl FFI_TRAMPOLINE_SIZE(%eax), %ebx /* load cl->cif */ + movl %ebx, (%esp) + call *FFI_TRAMPOLINE_SIZE+4(%eax) /* call cl->fun */ + + movl 20(%ebx), %eax /* load cif->flags */ + andl $X86_RET_TYPE_MASK, %eax +#ifdef __PIC__ + call C(__x86.get_pc_thunk.bx) +L(pc4): + leal L(load_table4)-L(pc4)(%ebx, %eax, 8), %ecx +#else + leal L(load_table4)(,%eax, 8), %ecx +#endif + movl raw_closure_S_FS-4(%esp), %ebx +L(UW35): + # cfi_restore(%ebx) + movl 16(%esp), %eax /* Optimistic load */ + jmp *%ecx + + .balign 8 +L(load_table4): +E(L(load_table4), X86_RET_FLOAT) + flds 16(%esp) + jmp L(e4) +E(L(load_table4), X86_RET_DOUBLE) + fldl 16(%esp) + jmp L(e4) +E(L(load_table4), X86_RET_LDOUBLE) + fldt 16(%esp) + jmp L(e4) +E(L(load_table4), X86_RET_SINT8) + movsbl %al, %eax + jmp L(e4) +E(L(load_table4), X86_RET_SINT16) + movswl %ax, %eax + jmp L(e4) +E(L(load_table4), X86_RET_UINT8) + movzbl %al, %eax + jmp L(e4) +E(L(load_table4), X86_RET_UINT16) + movzwl %ax, %eax + jmp L(e4) +E(L(load_table4), X86_RET_INT64) + movl 16+4(%esp), %edx + jmp L(e4) +E(L(load_table4), X86_RET_INT32) + nop + /* fallthru */ +E(L(load_table4), X86_RET_VOID) +L(e4): + addl $raw_closure_S_FS, %esp +L(UW36): + # cfi_adjust_cfa_offset(-raw_closure_S_FS) + ret +L(UW37): + # cfi_adjust_cfa_offset(raw_closure_S_FS) +E(L(load_table4), X86_RET_STRUCTPOP) + addl $raw_closure_S_FS, %esp +L(UW38): + # cfi_adjust_cfa_offset(-raw_closure_S_FS) + ret $4 +L(UW39): + # cfi_adjust_cfa_offset(raw_closure_S_FS) +E(L(load_table4), X86_RET_STRUCTARG) + jmp L(e4) +E(L(load_table4), X86_RET_STRUCT_1B) + movzbl %al, %eax + jmp L(e4) +E(L(load_table4), X86_RET_STRUCT_2B) + movzwl %ax, %eax + jmp L(e4) + + /* Fill out the table so that bad values are predictable. */ +E(L(load_table4), X86_RET_UNUSED14) + ud2 +E(L(load_table4), X86_RET_UNUSED15) + ud2 + +L(UW40): + # cfi_endproc +ENDF(C(ffi_closure_raw_SYSV)) + +#define raw_closure_T_FS (16+16+8) + + .balign 16 + .globl C(ffi_closure_raw_THISCALL) + FFI_HIDDEN(C(ffi_closure_raw_THISCALL)) +C(ffi_closure_raw_THISCALL): +L(UW41): + # cfi_startproc + _CET_ENDBR + /* Rearrange the stack such that %ecx is the first argument. + This means moving the return address. */ + popl %edx +L(UW42): + # cfi_def_cfa_offset(0) + # cfi_register(%eip, %edx) + pushl %ecx +L(UW43): + # cfi_adjust_cfa_offset(4) + pushl %edx +L(UW44): + # cfi_adjust_cfa_offset(4) + # cfi_rel_offset(%eip, 0) + subl $raw_closure_T_FS, %esp +L(UW45): + # cfi_adjust_cfa_offset(raw_closure_T_FS) + movl %ebx, raw_closure_T_FS-4(%esp) +L(UW46): + # cfi_rel_offset(%ebx, raw_closure_T_FS-4) + + movl FFI_TRAMPOLINE_SIZE+8(%eax), %edx /* load cl->user_data */ + movl %edx, 12(%esp) + leal raw_closure_T_FS+4(%esp), %edx /* load raw_args */ + movl %edx, 8(%esp) + leal 16(%esp), %edx /* load &res */ + movl %edx, 4(%esp) + movl FFI_TRAMPOLINE_SIZE(%eax), %ebx /* load cl->cif */ + movl %ebx, (%esp) + call *FFI_TRAMPOLINE_SIZE+4(%eax) /* call cl->fun */ + + movl 20(%ebx), %eax /* load cif->flags */ + andl $X86_RET_TYPE_MASK, %eax +#ifdef __PIC__ + call C(__x86.get_pc_thunk.bx) +L(pc5): + leal L(load_table5)-L(pc5)(%ebx, %eax, 8), %ecx +#else + leal L(load_table5)(,%eax, 8), %ecx +#endif + movl raw_closure_T_FS-4(%esp), %ebx +L(UW47): + # cfi_restore(%ebx) + movl 16(%esp), %eax /* Optimistic load */ + jmp *%ecx + + .balign 8 +L(load_table5): +E(L(load_table5), X86_RET_FLOAT) + flds 16(%esp) + jmp L(e5) +E(L(load_table5), X86_RET_DOUBLE) + fldl 16(%esp) + jmp L(e5) +E(L(load_table5), X86_RET_LDOUBLE) + fldt 16(%esp) + jmp L(e5) +E(L(load_table5), X86_RET_SINT8) + movsbl %al, %eax + jmp L(e5) +E(L(load_table5), X86_RET_SINT16) + movswl %ax, %eax + jmp L(e5) +E(L(load_table5), X86_RET_UINT8) + movzbl %al, %eax + jmp L(e5) +E(L(load_table5), X86_RET_UINT16) + movzwl %ax, %eax + jmp L(e5) +E(L(load_table5), X86_RET_INT64) + movl 16+4(%esp), %edx + jmp L(e5) +E(L(load_table5), X86_RET_INT32) + nop + /* fallthru */ +E(L(load_table5), X86_RET_VOID) +L(e5): + addl $raw_closure_T_FS, %esp +L(UW48): + # cfi_adjust_cfa_offset(-raw_closure_T_FS) + /* Remove the extra %ecx argument we pushed. */ + ret $4 +L(UW49): + # cfi_adjust_cfa_offset(raw_closure_T_FS) +E(L(load_table5), X86_RET_STRUCTPOP) + addl $raw_closure_T_FS, %esp +L(UW50): + # cfi_adjust_cfa_offset(-raw_closure_T_FS) + ret $8 +L(UW51): + # cfi_adjust_cfa_offset(raw_closure_T_FS) +E(L(load_table5), X86_RET_STRUCTARG) + jmp L(e5) +E(L(load_table5), X86_RET_STRUCT_1B) + movzbl %al, %eax + jmp L(e5) +E(L(load_table5), X86_RET_STRUCT_2B) + movzwl %ax, %eax + jmp L(e5) + + /* Fill out the table so that bad values are predictable. */ +E(L(load_table5), X86_RET_UNUSED14) + ud2 +E(L(load_table5), X86_RET_UNUSED15) + ud2 + +L(UW52): + # cfi_endproc +ENDF(C(ffi_closure_raw_THISCALL)) + +#endif /* !FFI_NO_RAW_API */ + +#ifdef X86_DARWIN +# define COMDAT(X) \ + .section __TEXT,__text,coalesced,pure_instructions; \ + .weak_definition X; \ + FFI_HIDDEN(X) +#elif defined __ELF__ && !(defined(__sun__) && defined(__svr4__)) +# define COMDAT(X) \ + .section .text.X,"axG",@progbits,X,comdat; \ + .globl X; \ + FFI_HIDDEN(X) +#else +# define COMDAT(X) +#endif + +#if defined(__PIC__) + COMDAT(C(__x86.get_pc_thunk.bx)) +C(__x86.get_pc_thunk.bx): + movl (%esp), %ebx + ret +ENDF(C(__x86.get_pc_thunk.bx)) +# if defined X86_DARWIN || defined HAVE_HIDDEN_VISIBILITY_ATTRIBUTE + COMDAT(C(__x86.get_pc_thunk.dx)) +C(__x86.get_pc_thunk.dx): + movl (%esp), %edx + ret +ENDF(C(__x86.get_pc_thunk.dx)) +#endif /* DARWIN || HIDDEN */ +#endif /* __PIC__ */ + +/* Sadly, OSX cctools-as doesn't understand .cfi directives at all. */ + +#ifdef __APPLE__ +.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support +EHFrame0: +#elif defined(X86_WIN32) +.section .eh_frame,"r" +#elif defined(HAVE_AS_X86_64_UNWIND_SECTION_TYPE) +.section .eh_frame,EH_FRAME_FLAGS,@unwind +#else +.section .eh_frame,EH_FRAME_FLAGS,@progbits +#endif + +#ifdef HAVE_AS_X86_PCREL +# define PCREL(X) X - . +#else +# define PCREL(X) X@rel +#endif + +/* Simplify advancing between labels. Assume DW_CFA_advance_loc1 fits. */ +#define ADV(N, P) .byte 2, L(N)-L(P) + + .balign 4 +L(CIE): + .set L(set0),L(ECIE)-L(SCIE) + .long L(set0) /* CIE Length */ +L(SCIE): + .long 0 /* CIE Identifier Tag */ + .byte 1 /* CIE Version */ + .ascii "zR\0" /* CIE Augmentation */ + .byte 1 /* CIE Code Alignment Factor */ + .byte 0x7c /* CIE Data Alignment Factor */ + .byte 0x8 /* CIE RA Column */ + .byte 1 /* Augmentation size */ + .byte 0x1b /* FDE Encoding (pcrel sdata4) */ + .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp offset 4 */ + .byte 0x80+8, 1 /* DW_CFA_offset, %eip offset 1*-4 */ + .balign 4 +L(ECIE): + + .set L(set1),L(EFDE1)-L(SFDE1) + .long L(set1) /* FDE Length */ +L(SFDE1): + .long L(SFDE1)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW0)) /* Initial location */ + .long L(UW5)-L(UW0) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW1, UW0) + .byte 0xc, 5, 8 /* DW_CFA_def_cfa, %ebp 8 */ + .byte 0x80+5, 2 /* DW_CFA_offset, %ebp 2*-4 */ + ADV(UW2, UW1) + .byte 0x80+3, 0 /* DW_CFA_offset, %ebx 0*-4 */ + ADV(UW3, UW2) + .byte 0xa /* DW_CFA_remember_state */ + .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp 4 */ + .byte 0xc0+3 /* DW_CFA_restore, %ebx */ + .byte 0xc0+5 /* DW_CFA_restore, %ebp */ + ADV(UW4, UW3) + .byte 0xb /* DW_CFA_restore_state */ + .balign 4 +L(EFDE1): + + .set L(set2),L(EFDE2)-L(SFDE2) + .long L(set2) /* FDE Length */ +L(SFDE2): + .long L(SFDE2)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW6)) /* Initial location */ + .long L(UW8)-L(UW6) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW7, UW6) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE2): + + .set L(set3),L(EFDE3)-L(SFDE3) + .long L(set3) /* FDE Length */ +L(SFDE3): + .long L(SFDE3)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW9)) /* Initial location */ + .long L(UW11)-L(UW9) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW10, UW9) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE3): + + .set L(set4),L(EFDE4)-L(SFDE4) + .long L(set4) /* FDE Length */ +L(SFDE4): + .long L(SFDE4)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW12)) /* Initial location */ + .long L(UW20)-L(UW12) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW13, UW12) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ +#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX + ADV(UW14, UW13) + .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */ + ADV(UW15, UW14) + .byte 0xc0+3 /* DW_CFA_restore %ebx */ + ADV(UW16, UW15) +#else + ADV(UW16, UW13) +#endif + .byte 0xe, 4 /* DW_CFA_def_cfa_offset */ + ADV(UW17, UW16) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + ADV(UW18, UW17) + .byte 0xe, 4 /* DW_CFA_def_cfa_offset */ + ADV(UW19, UW18) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE4): + + .set L(set5),L(EFDE5)-L(SFDE5) + .long L(set5) /* FDE Length */ +L(SFDE5): + .long L(SFDE5)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW21)) /* Initial location */ + .long L(UW23)-L(UW21) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW22, UW21) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE5): + + .set L(set6),L(EFDE6)-L(SFDE6) + .long L(set6) /* FDE Length */ +L(SFDE6): + .long L(SFDE6)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW24)) /* Initial location */ + .long L(UW26)-L(UW24) /* Address range */ + .byte 0 /* Augmentation size */ + .byte 0xe, 8 /* DW_CFA_def_cfa_offset */ + .byte 0x80+8, 2 /* DW_CFA_offset %eip, 2*-4 */ + ADV(UW25, UW24) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE6): + + .set L(set7),L(EFDE7)-L(SFDE7) + .long L(set7) /* FDE Length */ +L(SFDE7): + .long L(SFDE7)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW27)) /* Initial location */ + .long L(UW31)-L(UW27) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW28, UW27) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ +#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX + ADV(UW29, UW28) + .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */ + ADV(UW30, UW29) + .byte 0xc0+3 /* DW_CFA_restore %ebx */ +#endif + .balign 4 +L(EFDE7): + +#if !FFI_NO_RAW_API + .set L(set8),L(EFDE8)-L(SFDE8) + .long L(set8) /* FDE Length */ +L(SFDE8): + .long L(SFDE8)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW32)) /* Initial location */ + .long L(UW40)-L(UW32) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW33, UW32) + .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */ + ADV(UW34, UW33) + .byte 0x80+3, 2 /* DW_CFA_offset %ebx 2*-4 */ + ADV(UW35, UW34) + .byte 0xc0+3 /* DW_CFA_restore %ebx */ + ADV(UW36, UW35) + .byte 0xe, 4 /* DW_CFA_def_cfa_offset */ + ADV(UW37, UW36) + .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */ + ADV(UW38, UW37) + .byte 0xe, 4 /* DW_CFA_def_cfa_offset */ + ADV(UW39, UW38) + .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE8): + + .set L(set9),L(EFDE9)-L(SFDE9) + .long L(set9) /* FDE Length */ +L(SFDE9): + .long L(SFDE9)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW41)) /* Initial location */ + .long L(UW52)-L(UW41) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW42, UW41) + .byte 0xe, 0 /* DW_CFA_def_cfa_offset */ + .byte 0x9, 8, 2 /* DW_CFA_register %eip, %edx */ + ADV(UW43, UW42) + .byte 0xe, 4 /* DW_CFA_def_cfa_offset */ + ADV(UW44, UW43) + .byte 0xe, 8 /* DW_CFA_def_cfa_offset */ + .byte 0x80+8, 2 /* DW_CFA_offset %eip 2*-4 */ + ADV(UW45, UW44) + .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */ + ADV(UW46, UW45) + .byte 0x80+3, 3 /* DW_CFA_offset %ebx 3*-4 */ + ADV(UW47, UW46) + .byte 0xc0+3 /* DW_CFA_restore %ebx */ + ADV(UW48, UW47) + .byte 0xe, 8 /* DW_CFA_def_cfa_offset */ + ADV(UW49, UW48) + .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */ + ADV(UW50, UW49) + .byte 0xe, 8 /* DW_CFA_def_cfa_offset */ + ADV(UW51, UW50) + .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE9): +#endif /* !FFI_NO_RAW_API */ + +#ifdef _WIN32 + .def @feat.00; + .scl 3; + .type 0; + .endef + .globl @feat.00 +@feat.00 = 1 +#endif + +#ifdef __APPLE__ + .subsections_via_symbols + .section __LD,__compact_unwind,regular,debug + + /* compact unwind for ffi_call_i386 */ + .long C(ffi_call_i386) + .set L1,L(UW5)-L(UW0) + .long L1 + .long 0x04000000 /* use dwarf unwind info */ + .long 0 + .long 0 + + /* compact unwind for ffi_go_closure_EAX */ + .long C(ffi_go_closure_EAX) + .set L2,L(UW8)-L(UW6) + .long L2 + .long 0x04000000 /* use dwarf unwind info */ + .long 0 + .long 0 + + /* compact unwind for ffi_go_closure_ECX */ + .long C(ffi_go_closure_ECX) + .set L3,L(UW11)-L(UW9) + .long L3 + .long 0x04000000 /* use dwarf unwind info */ + .long 0 + .long 0 + + /* compact unwind for ffi_closure_i386 */ + .long C(ffi_closure_i386) + .set L4,L(UW20)-L(UW12) + .long L4 + .long 0x04000000 /* use dwarf unwind info */ + .long 0 + .long 0 + + /* compact unwind for ffi_go_closure_STDCALL */ + .long C(ffi_go_closure_STDCALL) + .set L5,L(UW23)-L(UW21) + .long L5 + .long 0x04000000 /* use dwarf unwind info */ + .long 0 + .long 0 + + /* compact unwind for ffi_closure_REGISTER */ + .long C(ffi_closure_REGISTER) + .set L6,L(UW26)-L(UW24) + .long L6 + .long 0x04000000 /* use dwarf unwind info */ + .long 0 + .long 0 + + /* compact unwind for ffi_closure_STDCALL */ + .long C(ffi_closure_STDCALL) + .set L7,L(UW31)-L(UW27) + .long L7 + .long 0x04000000 /* use dwarf unwind info */ + .long 0 + .long 0 + + /* compact unwind for ffi_closure_raw_SYSV */ + .long C(ffi_closure_raw_SYSV) + .set L8,L(UW40)-L(UW32) + .long L8 + .long 0x04000000 /* use dwarf unwind info */ + .long 0 + .long 0 + + /* compact unwind for ffi_closure_raw_THISCALL */ + .long C(ffi_closure_raw_THISCALL) + .set L9,L(UW52)-L(UW41) + .long L9 + .long 0x04000000 /* use dwarf unwind info */ + .long 0 + .long 0 +#endif /* __APPLE__ */ + +#endif /* ifndef _MSC_VER */ +#endif /* ifdef __i386__ */ + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/sysv_intel.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/sysv_intel.S new file mode 100644 index 0000000..3cafd71 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/sysv_intel.S @@ -0,0 +1,995 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2017 Anthony Green + - Copyright (c) 2013 The Written Word, Inc. + - Copyright (c) 1996,1998,2001-2003,2005,2008,2010 Red Hat, Inc. + + X86 Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#ifndef __x86_64__ +#ifdef _MSC_VER + +#define LIBFFI_ASM +#include +#include +#include +#include "internal.h" + +#define C2(X, Y) X ## Y +#define C1(X, Y) C2(X, Y) +#define L(X) C1(L, X) +# define ENDF(X) X ENDP + +/* This macro allows the safe creation of jump tables without an + actual table. The entry points into the table are all 8 bytes. + The use of ORG asserts that we're at the correct location. */ +/* ??? The clang assembler doesn't handle .org with symbolic expressions. */ +#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__)) +# define E(BASE, X) ALIGN 8 +#else +# define E(BASE, X) ALIGN 8; ORG BASE + X * 8 +#endif + + .686P + .MODEL FLAT + +EXTRN @ffi_closure_inner@8:PROC +_TEXT SEGMENT + +/* This is declared as + + void ffi_call_i386(struct call_frame *frame, char *argp) + __attribute__((fastcall)); + + Thus the arguments are present in + + ecx: frame + edx: argp +*/ + +ALIGN 16 +PUBLIC @ffi_call_i386@8 +@ffi_call_i386@8 PROC +L(UW0): + cfi_startproc + #if !HAVE_FASTCALL + mov ecx, [esp+4] + mov edx, [esp+8] + #endif + mov eax, [esp] /* move the return address */ + mov [ecx], ebp /* store ebp into local frame */ + mov [ecx+4], eax /* store retaddr into local frame */ + + /* New stack frame based off ebp. This is a itty bit of unwind + trickery in that the CFA *has* changed. There is no easy way + to describe it correctly on entry to the function. Fortunately, + it doesn't matter too much since at all points we can correctly + unwind back to ffi_call. Note that the location to which we + moved the return address is (the new) CFA-4, so from the + perspective of the unwind info, it hasn't moved. */ + mov ebp, ecx +L(UW1): + // cfi_def_cfa(%ebp, 8) + // cfi_rel_offset(%ebp, 0) + + mov esp, edx /* set outgoing argument stack */ + mov eax, [20+R_EAX*4+ebp] /* set register arguments */ + mov edx, [20+R_EDX*4+ebp] + mov ecx, [20+R_ECX*4+ebp] + + call dword ptr [ebp+8] + + mov ecx, [12+ebp] /* load return type code */ + mov [ebp+8], ebx /* preserve %ebx */ +L(UW2): + // cfi_rel_offset(%ebx, 8) + + and ecx, X86_RET_TYPE_MASK + lea ebx, [L(store_table) + ecx * 8] + mov ecx, [ebp+16] /* load result address */ + jmp ebx + + ALIGN 8 +L(store_table): +E(L(store_table), X86_RET_FLOAT) + fstp DWORD PTR [ecx] + jmp L(e1) +E(L(store_table), X86_RET_DOUBLE) + fstp QWORD PTR [ecx] + jmp L(e1) +E(L(store_table), X86_RET_LDOUBLE) + fstp QWORD PTR [ecx] + jmp L(e1) +E(L(store_table), X86_RET_SINT8) + movsx eax, al + mov [ecx], eax + jmp L(e1) +E(L(store_table), X86_RET_SINT16) + movsx eax, ax + mov [ecx], eax + jmp L(e1) +E(L(store_table), X86_RET_UINT8) + movzx eax, al + mov [ecx], eax + jmp L(e1) +E(L(store_table), X86_RET_UINT16) + movzx eax, ax + mov [ecx], eax + jmp L(e1) +E(L(store_table), X86_RET_INT64) + mov [ecx+4], edx + /* fallthru */ +E(L(store_table), X86_RET_int 32) + mov [ecx], eax + /* fallthru */ +E(L(store_table), X86_RET_VOID) +L(e1): + mov ebx, [ebp+8] + mov esp, ebp + pop ebp +L(UW3): + // cfi_remember_state + // cfi_def_cfa(%esp, 4) + // cfi_restore(%ebx) + // cfi_restore(%ebp) + ret +L(UW4): + // cfi_restore_state + +E(L(store_table), X86_RET_STRUCTPOP) + jmp L(e1) +E(L(store_table), X86_RET_STRUCTARG) + jmp L(e1) +E(L(store_table), X86_RET_STRUCT_1B) + mov [ecx], al + jmp L(e1) +E(L(store_table), X86_RET_STRUCT_2B) + mov [ecx], ax + jmp L(e1) + + /* Fill out the table so that bad values are predictable. */ +E(L(store_table), X86_RET_UNUSED14) + int 3 +E(L(store_table), X86_RET_UNUSED15) + int 3 + +L(UW5): + // cfi_endproc +ENDF(@ffi_call_i386@8) + +/* The inner helper is declared as + + void ffi_closure_inner(struct closure_frame *frame, char *argp) + __attribute_((fastcall)) + + Thus the arguments are placed in + + ecx: frame + edx: argp +*/ + +/* Macros to help setting up the closure_data structure. */ + +#if HAVE_FASTCALL +# define closure_FS (40 + 4) +# define closure_CF 0 +#else +# define closure_FS (8 + 40 + 12) +# define closure_CF 8 +#endif + +FFI_CLOSURE_SAVE_REGS MACRO + mov [esp + closure_CF+16+R_EAX*4], eax + mov [esp + closure_CF+16+R_EDX*4], edx + mov [esp + closure_CF+16+R_ECX*4], ecx +ENDM + +FFI_CLOSURE_COPY_TRAMP_DATA MACRO + mov edx, [eax+FFI_TRAMPOLINE_SIZE] /* copy cif */ + mov ecx, [eax+FFI_TRAMPOLINE_SIZE+4] /* copy fun */ + mov eax, [eax+FFI_TRAMPOLINE_SIZE+8]; /* copy user_data */ + mov [esp+closure_CF+28], edx + mov [esp+closure_CF+32], ecx + mov [esp+closure_CF+36], eax +ENDM + +#if HAVE_FASTCALL +FFI_CLOSURE_PREP_CALL MACRO + mov ecx, esp /* load closure_data */ + lea edx, [esp+closure_FS+4] /* load incoming stack */ +ENDM +#else +FFI_CLOSURE_PREP_CALL MACRO + lea ecx, [esp+closure_CF] /* load closure_data */ + lea edx, [esp+closure_FS+4] /* load incoming stack */ + mov [esp], ecx + mov [esp+4], edx +ENDM +#endif + +FFI_CLOSURE_CALL_INNER MACRO UWN + call @ffi_closure_inner@8 +ENDM + +FFI_CLOSURE_MASK_AND_JUMP MACRO LABEL + and eax, X86_RET_TYPE_MASK + lea edx, [LABEL+eax*8] + mov eax, [esp+closure_CF] /* optimiztic load */ + jmp edx +ENDM + +ALIGN 16 +PUBLIC ffi_go_closure_EAX +ffi_go_closure_EAX PROC C +L(UW6): + // cfi_startproc + sub esp, closure_FS +L(UW7): + // cfi_def_cfa_offset(closure_FS + 4) + FFI_CLOSURE_SAVE_REGS + mov edx, [eax+4] /* copy cif */ + mov ecx, [eax +8] /* copy fun */ + mov [esp+closure_CF+28], edx + mov [esp+closure_CF+32], ecx + mov [esp+closure_CF+36], eax /* closure is user_data */ + jmp L(do_closure_i386) +L(UW8): + // cfi_endproc +ENDF(ffi_go_closure_EAX) + +ALIGN 16 +PUBLIC ffi_go_closure_ECX +ffi_go_closure_ECX PROC C +L(UW9): + // cfi_startproc + sub esp, closure_FS +L(UW10): + // cfi_def_cfa_offset(closure_FS + 4) + FFI_CLOSURE_SAVE_REGS + mov edx, [ecx+4] /* copy cif */ + mov eax, [ecx+8] /* copy fun */ + mov [esp+closure_CF+28], edx + mov [esp+closure_CF+32], eax + mov [esp+closure_CF+36], ecx /* closure is user_data */ + jmp L(do_closure_i386) +L(UW11): + // cfi_endproc +ENDF(ffi_go_closure_ECX) + +/* The closure entry points are reached from the ffi_closure trampoline. + On entry, %eax contains the address of the ffi_closure. */ + +ALIGN 16 +PUBLIC ffi_closure_i386 +ffi_closure_i386 PROC C +L(UW12): + // cfi_startproc + sub esp, closure_FS +L(UW13): + // cfi_def_cfa_offset(closure_FS + 4) + + FFI_CLOSURE_SAVE_REGS + FFI_CLOSURE_COPY_TRAMP_DATA + + /* Entry point from preceeding Go closures. */ +L(do_closure_i386):: + + FFI_CLOSURE_PREP_CALL + FFI_CLOSURE_CALL_INNER(14) + FFI_CLOSURE_MASK_AND_JUMP L(C1(load_table,2)) + + ALIGN 8 +L(load_table2): +E(L(load_table2), X86_RET_FLOAT) + fld dword ptr [esp+closure_CF] + jmp L(e2) +E(L(load_table2), X86_RET_DOUBLE) + fld qword ptr [esp+closure_CF] + jmp L(e2) +E(L(load_table2), X86_RET_LDOUBLE) + fld qword ptr [esp+closure_CF] + jmp L(e2) +E(L(load_table2), X86_RET_SINT8) + movsx eax, al + jmp L(e2) +E(L(load_table2), X86_RET_SINT16) + movsx eax, ax + jmp L(e2) +E(L(load_table2), X86_RET_UINT8) + movzx eax, al + jmp L(e2) +E(L(load_table2), X86_RET_UINT16) + movzx eax, ax + jmp L(e2) +E(L(load_table2), X86_RET_INT64) + mov edx, [esp+closure_CF+4] + jmp L(e2) +E(L(load_table2), X86_RET_INT32) + nop + /* fallthru */ +E(L(load_table2), X86_RET_VOID) +L(e2): + add esp, closure_FS +L(UW16): + // cfi_adjust_cfa_offset(-closure_FS) + ret +L(UW17): + // cfi_adjust_cfa_offset(closure_FS) +E(L(load_table2), X86_RET_STRUCTPOP) + add esp, closure_FS +L(UW18): + // cfi_adjust_cfa_offset(-closure_FS) + ret 4 +L(UW19): + // cfi_adjust_cfa_offset(closure_FS) +E(L(load_table2), X86_RET_STRUCTARG) + jmp L(e2) +E(L(load_table2), X86_RET_STRUCT_1B) + movzx eax, al + jmp L(e2) +E(L(load_table2), X86_RET_STRUCT_2B) + movzx eax, ax + jmp L(e2) + + /* Fill out the table so that bad values are predictable. */ +E(L(load_table2), X86_RET_UNUSED14) + int 3 +E(L(load_table2), X86_RET_UNUSED15) + int 3 + +L(UW20): + // cfi_endproc +ENDF(ffi_closure_i386) + +ALIGN 16 +PUBLIC ffi_go_closure_STDCALL +ffi_go_closure_STDCALL PROC C +L(UW21): + // cfi_startproc + sub esp, closure_FS +L(UW22): + // cfi_def_cfa_offset(closure_FS + 4) + FFI_CLOSURE_SAVE_REGS + mov edx, [ecx+4] /* copy cif */ + mov eax, [ecx+8] /* copy fun */ + mov [esp+closure_CF+28], edx + mov [esp+closure_CF+32], eax + mov [esp+closure_CF+36], ecx /* closure is user_data */ + jmp L(do_closure_STDCALL) +L(UW23): + // cfi_endproc +ENDF(ffi_go_closure_STDCALL) + +/* For REGISTER, we have no available parameter registers, and so we + enter here having pushed the closure onto the stack. */ + +ALIGN 16 +PUBLIC ffi_closure_REGISTER +ffi_closure_REGISTER PROC C +L(UW24): + // cfi_startproc + // cfi_def_cfa(%esp, 8) + // cfi_offset(%eip, -8) + sub esp, closure_FS-4 +L(UW25): + // cfi_def_cfa_offset(closure_FS + 4) + FFI_CLOSURE_SAVE_REGS + mov ecx, [esp+closure_FS-4] /* load retaddr */ + mov eax, [esp+closure_FS] /* load closure */ + mov [esp+closure_FS], ecx /* move retaddr */ + jmp L(do_closure_REGISTER) +L(UW26): + // cfi_endproc +ENDF(ffi_closure_REGISTER) + +/* For STDCALL (and others), we need to pop N bytes of arguments off + the stack following the closure. The amount needing to be popped + is returned to us from ffi_closure_inner. */ + +ALIGN 16 +PUBLIC ffi_closure_STDCALL +ffi_closure_STDCALL PROC C +L(UW27): + // cfi_startproc + sub esp, closure_FS +L(UW28): + // cfi_def_cfa_offset(closure_FS + 4) + + FFI_CLOSURE_SAVE_REGS + + /* Entry point from ffi_closure_REGISTER. */ +L(do_closure_REGISTER):: + + FFI_CLOSURE_COPY_TRAMP_DATA + + /* Entry point from preceeding Go closure. */ +L(do_closure_STDCALL):: + + FFI_CLOSURE_PREP_CALL + FFI_CLOSURE_CALL_INNER(29) + + mov ecx, eax + shr ecx, X86_RET_POP_SHIFT /* isolate pop count */ + lea ecx, [esp+closure_FS+ecx] /* compute popped esp */ + mov edx, [esp+closure_FS] /* move return address */ + mov [ecx], edx + + /* From this point on, the value of %esp upon return is %ecx+4, + and we've copied the return address to %ecx to make return easy. + There's no point in representing this in the unwind info, as + there is always a window between the mov and the ret which + will be wrong from one point of view or another. */ + + FFI_CLOSURE_MASK_AND_JUMP L(C1(load_table,3)) + + ALIGN 8 +L(load_table3): +E(L(load_table3), X86_RET_FLOAT) + fld DWORD PTR [esp+closure_CF] + mov esp, ecx + ret +E(L(load_table3), X86_RET_DOUBLE) + fld QWORD PTR [esp+closure_CF] + mov esp, ecx + ret +E(L(load_table3), X86_RET_LDOUBLE) + fld QWORD PTR [esp+closure_CF] + mov esp, ecx + ret +E(L(load_table3), X86_RET_SINT8) + movsx eax, al + mov esp, ecx + ret +E(L(load_table3), X86_RET_SINT16) + movsx eax, ax + mov esp, ecx + ret +E(L(load_table3), X86_RET_UINT8) + movzx eax, al + mov esp, ecx + ret +E(L(load_table3), X86_RET_UINT16) + movzx eax, ax + mov esp, ecx + ret +E(L(load_table3), X86_RET_INT64) + mov edx, [esp+closure_CF+4] + mov esp, ecx + ret +E(L(load_table3), X86_RET_int 32) + mov esp, ecx + ret +E(L(load_table3), X86_RET_VOID) + mov esp, ecx + ret +E(L(load_table3), X86_RET_STRUCTPOP) + mov esp, ecx + ret +E(L(load_table3), X86_RET_STRUCTARG) + mov esp, ecx + ret +E(L(load_table3), X86_RET_STRUCT_1B) + movzx eax, al + mov esp, ecx + ret +E(L(load_table3), X86_RET_STRUCT_2B) + movzx eax, ax + mov esp, ecx + ret + + /* Fill out the table so that bad values are predictable. */ +E(L(load_table3), X86_RET_UNUSED14) + int 3 +E(L(load_table3), X86_RET_UNUSED15) + int 3 + +L(UW31): + // cfi_endproc +ENDF(ffi_closure_STDCALL) + +#if !FFI_NO_RAW_API + +#define raw_closure_S_FS (16+16+12) + +ALIGN 16 +PUBLIC ffi_closure_raw_SYSV +ffi_closure_raw_SYSV PROC C +L(UW32): + // cfi_startproc + sub esp, raw_closure_S_FS +L(UW33): + // cfi_def_cfa_offset(raw_closure_S_FS + 4) + mov [esp+raw_closure_S_FS-4], ebx +L(UW34): + // cfi_rel_offset(%ebx, raw_closure_S_FS-4) + + mov edx, [eax+FFI_TRAMPOLINE_SIZE+8] /* load cl->user_data */ + mov [esp+12], edx + lea edx, [esp+raw_closure_S_FS+4] /* load raw_args */ + mov [esp+8], edx + lea edx, [esp+16] /* load &res */ + mov [esp+4], edx + mov ebx, [eax+FFI_TRAMPOLINE_SIZE] /* load cl->cif */ + mov [esp], ebx + call DWORD PTR [eax+FFI_TRAMPOLINE_SIZE+4] /* call cl->fun */ + + mov eax, [ebx+20] /* load cif->flags */ + and eax, X86_RET_TYPE_MASK +// #ifdef __PIC__ +// call __x86.get_pc_thunk.bx +// L(pc4): +// lea ecx, L(load_table4)-L(pc4)(%ebx, %eax, 8), %ecx +// #else + lea ecx, [L(load_table4)+eax+8] +// #endif + mov ebx, [esp+raw_closure_S_FS-4] +L(UW35): + // cfi_restore(%ebx) + mov eax, [esp+16] /* Optimistic load */ + jmp dword ptr [ecx] + + ALIGN 8 +L(load_table4): +E(L(load_table4), X86_RET_FLOAT) + fld DWORD PTR [esp +16] + jmp L(e4) +E(L(load_table4), X86_RET_DOUBLE) + fld QWORD PTR [esp +16] + jmp L(e4) +E(L(load_table4), X86_RET_LDOUBLE) + fld QWORD PTR [esp +16] + jmp L(e4) +E(L(load_table4), X86_RET_SINT8) + movsx eax, al + jmp L(e4) +E(L(load_table4), X86_RET_SINT16) + movsx eax, ax + jmp L(e4) +E(L(load_table4), X86_RET_UINT8) + movzx eax, al + jmp L(e4) +E(L(load_table4), X86_RET_UINT16) + movzx eax, ax + jmp L(e4) +E(L(load_table4), X86_RET_INT64) + mov edx, [esp+16+4] + jmp L(e4) +E(L(load_table4), X86_RET_int 32) + nop + /* fallthru */ +E(L(load_table4), X86_RET_VOID) +L(e4): + add esp, raw_closure_S_FS +L(UW36): + // cfi_adjust_cfa_offset(-raw_closure_S_FS) + ret +L(UW37): + // cfi_adjust_cfa_offset(raw_closure_S_FS) +E(L(load_table4), X86_RET_STRUCTPOP) + add esp, raw_closure_S_FS +L(UW38): + // cfi_adjust_cfa_offset(-raw_closure_S_FS) + ret 4 +L(UW39): + // cfi_adjust_cfa_offset(raw_closure_S_FS) +E(L(load_table4), X86_RET_STRUCTARG) + jmp L(e4) +E(L(load_table4), X86_RET_STRUCT_1B) + movzx eax, al + jmp L(e4) +E(L(load_table4), X86_RET_STRUCT_2B) + movzx eax, ax + jmp L(e4) + + /* Fill out the table so that bad values are predictable. */ +E(L(load_table4), X86_RET_UNUSED14) + int 3 +E(L(load_table4), X86_RET_UNUSED15) + int 3 + +L(UW40): + // cfi_endproc +ENDF(ffi_closure_raw_SYSV) + +#define raw_closure_T_FS (16+16+8) + +ALIGN 16 +PUBLIC ffi_closure_raw_THISCALL +ffi_closure_raw_THISCALL PROC C +L(UW41): + // cfi_startproc + /* Rearrange the stack such that %ecx is the first argument. + This means moving the return address. */ + pop edx +L(UW42): + // cfi_def_cfa_offset(0) + // cfi_register(%eip, %edx) + push ecx +L(UW43): + // cfi_adjust_cfa_offset(4) + push edx +L(UW44): + // cfi_adjust_cfa_offset(4) + // cfi_rel_offset(%eip, 0) + sub esp, raw_closure_T_FS +L(UW45): + // cfi_adjust_cfa_offset(raw_closure_T_FS) + mov [esp+raw_closure_T_FS-4], ebx +L(UW46): + // cfi_rel_offset(%ebx, raw_closure_T_FS-4) + + mov edx, [eax+FFI_TRAMPOLINE_SIZE+8] /* load cl->user_data */ + mov [esp+12], edx + lea edx, [esp+raw_closure_T_FS+4] /* load raw_args */ + mov [esp+8], edx + lea edx, [esp+16] /* load &res */ + mov [esp+4], edx + mov ebx, [eax+FFI_TRAMPOLINE_SIZE] /* load cl->cif */ + mov [esp], ebx + call DWORD PTR [eax+FFI_TRAMPOLINE_SIZE+4] /* call cl->fun */ + + mov eax, [ebx+20] /* load cif->flags */ + and eax, X86_RET_TYPE_MASK +// #ifdef __PIC__ +// call __x86.get_pc_thunk.bx +// L(pc5): +// leal L(load_table5)-L(pc5)(%ebx, %eax, 8), %ecx +// #else + lea ecx, [L(load_table5)+eax*8] +//#endif + mov ebx, [esp+raw_closure_T_FS-4] +L(UW47): + // cfi_restore(%ebx) + mov eax, [esp+16] /* Optimistic load */ + jmp DWORD PTR [ecx] + + AlIGN 4 +L(load_table5): +E(L(load_table5), X86_RET_FLOAT) + fld DWORD PTR [esp +16] + jmp L(e5) +E(L(load_table5), X86_RET_DOUBLE) + fld QWORD PTR [esp +16] + jmp L(e5) +E(L(load_table5), X86_RET_LDOUBLE) + fld QWORD PTR [esp+16] + jmp L(e5) +E(L(load_table5), X86_RET_SINT8) + movsx eax, al + jmp L(e5) +E(L(load_table5), X86_RET_SINT16) + movsx eax, ax + jmp L(e5) +E(L(load_table5), X86_RET_UINT8) + movzx eax, al + jmp L(e5) +E(L(load_table5), X86_RET_UINT16) + movzx eax, ax + jmp L(e5) +E(L(load_table5), X86_RET_INT64) + mov edx, [esp+16+4] + jmp L(e5) +E(L(load_table5), X86_RET_int 32) + nop + /* fallthru */ +E(L(load_table5), X86_RET_VOID) +L(e5): + add esp, raw_closure_T_FS +L(UW48): + // cfi_adjust_cfa_offset(-raw_closure_T_FS) + /* Remove the extra %ecx argument we pushed. */ + ret 4 +L(UW49): + // cfi_adjust_cfa_offset(raw_closure_T_FS) +E(L(load_table5), X86_RET_STRUCTPOP) + add esp, raw_closure_T_FS +L(UW50): + // cfi_adjust_cfa_offset(-raw_closure_T_FS) + ret 8 +L(UW51): + // cfi_adjust_cfa_offset(raw_closure_T_FS) +E(L(load_table5), X86_RET_STRUCTARG) + jmp L(e5) +E(L(load_table5), X86_RET_STRUCT_1B) + movzx eax, al + jmp L(e5) +E(L(load_table5), X86_RET_STRUCT_2B) + movzx eax, ax + jmp L(e5) + + /* Fill out the table so that bad values are predictable. */ +E(L(load_table5), X86_RET_UNUSED14) + int 3 +E(L(load_table5), X86_RET_UNUSED15) + int 3 + +L(UW52): + // cfi_endproc +ENDF(ffi_closure_raw_THISCALL) + +#endif /* !FFI_NO_RAW_API */ + +#ifdef X86_DARWIN +# define COMDAT(X) \ + .section __TEXT,__text,coalesced,pure_instructions; \ + .weak_definition X; \ + FFI_HIDDEN(X) +#elif defined __ELF__ && !(defined(__sun__) && defined(__svr4__)) +# define COMDAT(X) \ + .section .text.X,"axG",@progbits,X,comdat; \ + PUBLIC X; \ + FFI_HIDDEN(X) +#else +# define COMDAT(X) +#endif + +// #if defined(__PIC__) +// COMDAT(C(__x86.get_pc_thunk.bx)) +// C(__x86.get_pc_thunk.bx): +// movl (%esp), %ebx +// ret +// ENDF(C(__x86.get_pc_thunk.bx)) +// # if defined X86_DARWIN || defined HAVE_HIDDEN_VISIBILITY_ATTRIBUTE +// COMDAT(C(__x86.get_pc_thunk.dx)) +// C(__x86.get_pc_thunk.dx): +// movl (%esp), %edx +// ret +// ENDF(C(__x86.get_pc_thunk.dx)) +// #endif /* DARWIN || HIDDEN */ +// #endif /* __PIC__ */ + +#if 0 +/* Sadly, OSX cctools-as doesn't understand .cfi directives at all. */ + +#ifdef __APPLE__ +.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support +EHFrame0: +#elif defined(X86_WIN32) +.section .eh_frame,"r" +#elif defined(HAVE_AS_X86_64_UNWIND_SECTION_TYPE) +.section .eh_frame,EH_FRAME_FLAGS,@unwind +#else +.section .eh_frame,EH_FRAME_FLAGS,@progbits +#endif + +#ifdef HAVE_AS_X86_PCREL +# define PCREL(X) X - . +#else +# define PCREL(X) X@rel +#endif + +/* Simplify advancing between labels. Assume DW_CFA_advance_loc1 fits. */ +#define ADV(N, P) .byte 2, L(N)-L(P) + + .balign 4 +L(CIE): + .set L(set0),L(ECIE)-L(SCIE) + .long L(set0) /* CIE Length */ +L(SCIE): + .long 0 /* CIE Identifier Tag */ + .byte 1 /* CIE Version */ + .ascii "zR\0" /* CIE Augmentation */ + .byte 1 /* CIE Code Alignment Factor */ + .byte 0x7c /* CIE Data Alignment Factor */ + .byte 0x8 /* CIE RA Column */ + .byte 1 /* Augmentation size */ + .byte 0x1b /* FDE Encoding (pcrel sdata4) */ + .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp offset 4 */ + .byte 0x80+8, 1 /* DW_CFA_offset, %eip offset 1*-4 */ + .balign 4 +L(ECIE): + + .set L(set1),L(EFDE1)-L(SFDE1) + .long L(set1) /* FDE Length */ +L(SFDE1): + .long L(SFDE1)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW0)) /* Initial location */ + .long L(UW5)-L(UW0) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW1, UW0) + .byte 0xc, 5, 8 /* DW_CFA_def_cfa, %ebp 8 */ + .byte 0x80+5, 2 /* DW_CFA_offset, %ebp 2*-4 */ + ADV(UW2, UW1) + .byte 0x80+3, 0 /* DW_CFA_offset, %ebx 0*-4 */ + ADV(UW3, UW2) + .byte 0xa /* DW_CFA_remember_state */ + .byte 0xc, 4, 4 /* DW_CFA_def_cfa, %esp 4 */ + .byte 0xc0+3 /* DW_CFA_restore, %ebx */ + .byte 0xc0+5 /* DW_CFA_restore, %ebp */ + ADV(UW4, UW3) + .byte 0xb /* DW_CFA_restore_state */ + .balign 4 +L(EFDE1): + + .set L(set2),L(EFDE2)-L(SFDE2) + .long L(set2) /* FDE Length */ +L(SFDE2): + .long L(SFDE2)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW6)) /* Initial location */ + .long L(UW8)-L(UW6) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW7, UW6) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE2): + + .set L(set3),L(EFDE3)-L(SFDE3) + .long L(set3) /* FDE Length */ +L(SFDE3): + .long L(SFDE3)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW9)) /* Initial location */ + .long L(UW11)-L(UW9) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW10, UW9) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE3): + + .set L(set4),L(EFDE4)-L(SFDE4) + .long L(set4) /* FDE Length */ +L(SFDE4): + .long L(SFDE4)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW12)) /* Initial location */ + .long L(UW20)-L(UW12) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW13, UW12) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ +#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX + ADV(UW14, UW13) + .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */ + ADV(UW15, UW14) + .byte 0xc0+3 /* DW_CFA_restore %ebx */ + ADV(UW16, UW15) +#else + ADV(UW16, UW13) +#endif + .byte 0xe, 4 /* DW_CFA_def_cfa_offset */ + ADV(UW17, UW16) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + ADV(UW18, UW17) + .byte 0xe, 4 /* DW_CFA_def_cfa_offset */ + ADV(UW19, UW18) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE4): + + .set L(set5),L(EFDE5)-L(SFDE5) + .long L(set5) /* FDE Length */ +L(SFDE5): + .long L(SFDE5)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW21)) /* Initial location */ + .long L(UW23)-L(UW21) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW22, UW21) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE5): + + .set L(set6),L(EFDE6)-L(SFDE6) + .long L(set6) /* FDE Length */ +L(SFDE6): + .long L(SFDE6)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW24)) /* Initial location */ + .long L(UW26)-L(UW24) /* Address range */ + .byte 0 /* Augmentation size */ + .byte 0xe, 8 /* DW_CFA_def_cfa_offset */ + .byte 0x80+8, 2 /* DW_CFA_offset %eip, 2*-4 */ + ADV(UW25, UW24) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE6): + + .set L(set7),L(EFDE7)-L(SFDE7) + .long L(set7) /* FDE Length */ +L(SFDE7): + .long L(SFDE7)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW27)) /* Initial location */ + .long L(UW31)-L(UW27) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW28, UW27) + .byte 0xe, closure_FS+4 /* DW_CFA_def_cfa_offset */ +#ifdef FFI_CLOSURE_CALL_INNER_SAVE_EBX + ADV(UW29, UW28) + .byte 0x80+3, (40-(closure_FS+4))/-4 /* DW_CFA_offset %ebx */ + ADV(UW30, UW29) + .byte 0xc0+3 /* DW_CFA_restore %ebx */ +#endif + .balign 4 +L(EFDE7): + +#if !FFI_NO_RAW_API + .set L(set8),L(EFDE8)-L(SFDE8) + .long L(set8) /* FDE Length */ +L(SFDE8): + .long L(SFDE8)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW32)) /* Initial location */ + .long L(UW40)-L(UW32) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW33, UW32) + .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */ + ADV(UW34, UW33) + .byte 0x80+3, 2 /* DW_CFA_offset %ebx 2*-4 */ + ADV(UW35, UW34) + .byte 0xc0+3 /* DW_CFA_restore %ebx */ + ADV(UW36, UW35) + .byte 0xe, 4 /* DW_CFA_def_cfa_offset */ + ADV(UW37, UW36) + .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */ + ADV(UW38, UW37) + .byte 0xe, 4 /* DW_CFA_def_cfa_offset */ + ADV(UW39, UW38) + .byte 0xe, raw_closure_S_FS+4 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE8): + + .set L(set9),L(EFDE9)-L(SFDE9) + .long L(set9) /* FDE Length */ +L(SFDE9): + .long L(SFDE9)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW41)) /* Initial location */ + .long L(UW52)-L(UW41) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW42, UW41) + .byte 0xe, 0 /* DW_CFA_def_cfa_offset */ + .byte 0x9, 8, 2 /* DW_CFA_register %eip, %edx */ + ADV(UW43, UW42) + .byte 0xe, 4 /* DW_CFA_def_cfa_offset */ + ADV(UW44, UW43) + .byte 0xe, 8 /* DW_CFA_def_cfa_offset */ + .byte 0x80+8, 2 /* DW_CFA_offset %eip 2*-4 */ + ADV(UW45, UW44) + .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */ + ADV(UW46, UW45) + .byte 0x80+3, 3 /* DW_CFA_offset %ebx 3*-4 */ + ADV(UW47, UW46) + .byte 0xc0+3 /* DW_CFA_restore %ebx */ + ADV(UW48, UW47) + .byte 0xe, 8 /* DW_CFA_def_cfa_offset */ + ADV(UW49, UW48) + .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */ + ADV(UW50, UW49) + .byte 0xe, 8 /* DW_CFA_def_cfa_offset */ + ADV(UW51, UW50) + .byte 0xe, raw_closure_T_FS+8 /* DW_CFA_def_cfa_offset */ + .balign 4 +L(EFDE9): +#endif /* !FFI_NO_RAW_API */ + +#ifdef _WIN32 + .def @feat.00; + .scl 3; + .type 0; + .endef + PUBLIC @feat.00 +@feat.00 = 1 +#endif + +#endif /* ifndef _MSC_VER */ +#endif /* ifndef __x86_64__ */ + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif +#endif + +END \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/unix64.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/unix64.S new file mode 100644 index 0000000..89d7db1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/unix64.S @@ -0,0 +1,621 @@ +/* ----------------------------------------------------------------------- + unix64.S - Copyright (c) 2013 The Written Word, Inc. + - Copyright (c) 2008 Red Hat, Inc + - Copyright (c) 2002 Bo Thorsen + + x86-64 Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#ifdef __x86_64__ +#define LIBFFI_ASM +#include +#include +#include "internal64.h" +#include "asmnames.h" + + .text + +/* This macro allows the safe creation of jump tables without an + actual table. The entry points into the table are all 8 bytes. + The use of ORG asserts that we're at the correct location. */ +/* ??? The clang assembler doesn't handle .org with symbolic expressions. */ +#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__)) +# define E(BASE, X) .balign 8 +#else +# ifdef __CET__ +# define E(BASE, X) .balign 8; .org BASE + X * 16 +# else +# define E(BASE, X) .balign 8; .org BASE + X * 8 +# endif +#endif + +/* ffi_call_unix64 (void *args, unsigned long bytes, unsigned flags, + void *raddr, void (*fnaddr)(void)); + + Bit o trickiness here -- ARGS+BYTES is the base of the stack frame + for this function. This has been allocated by ffi_call. We also + deallocate some of the stack that has been alloca'd. */ + + .balign 8 + .globl C(ffi_call_unix64) + FFI_HIDDEN(C(ffi_call_unix64)) + +C(ffi_call_unix64): +L(UW0): + _CET_ENDBR + movq (%rsp), %r10 /* Load return address. */ + leaq (%rdi, %rsi), %rax /* Find local stack base. */ + movq %rdx, (%rax) /* Save flags. */ + movq %rcx, 8(%rax) /* Save raddr. */ + movq %rbp, 16(%rax) /* Save old frame pointer. */ + movq %r10, 24(%rax) /* Relocate return address. */ + movq %rax, %rbp /* Finalize local stack frame. */ + + /* New stack frame based off rbp. This is a itty bit of unwind + trickery in that the CFA *has* changed. There is no easy way + to describe it correctly on entry to the function. Fortunately, + it doesn't matter too much since at all points we can correctly + unwind back to ffi_call. Note that the location to which we + moved the return address is (the new) CFA-8, so from the + perspective of the unwind info, it hasn't moved. */ +L(UW1): + /* cfi_def_cfa(%rbp, 32) */ + /* cfi_rel_offset(%rbp, 16) */ + + movq %rdi, %r10 /* Save a copy of the register area. */ + movq %r8, %r11 /* Save a copy of the target fn. */ + + /* Load up all argument registers. */ + movq (%r10), %rdi + movq 0x08(%r10), %rsi + movq 0x10(%r10), %rdx + movq 0x18(%r10), %rcx + movq 0x20(%r10), %r8 + movq 0x28(%r10), %r9 + movl 0xb0(%r10), %eax /* Set number of SSE registers. */ + testl %eax, %eax + jnz L(load_sse) +L(ret_from_load_sse): + + /* Deallocate the reg arg area, except for r10, then load via pop. */ + leaq 0xb8(%r10), %rsp + popq %r10 + + /* Call the user function. */ + call *%r11 + + /* Deallocate stack arg area; local stack frame in redzone. */ + leaq 24(%rbp), %rsp + + movq 0(%rbp), %rcx /* Reload flags. */ + movq 8(%rbp), %rdi /* Reload raddr. */ + movq 16(%rbp), %rbp /* Reload old frame pointer. */ +L(UW2): + /* cfi_remember_state */ + /* cfi_def_cfa(%rsp, 8) */ + /* cfi_restore(%rbp) */ + + /* The first byte of the flags contains the FFI_TYPE. */ + cmpb $UNIX64_RET_LAST, %cl + movzbl %cl, %r10d + leaq L(store_table)(%rip), %r11 + ja L(sa) +#ifdef __CET__ + /* NB: Originally, each slot is 8 byte. 4 bytes of ENDBR64 + + 4 bytes NOP padding double slot size to 16 bytes. */ + addl %r10d, %r10d +#endif + leaq (%r11, %r10, 8), %r10 + + /* Prep for the structure cases: scratch area in redzone. */ + leaq -20(%rsp), %rsi + jmp *%r10 + + .balign 8 +L(store_table): +E(L(store_table), UNIX64_RET_VOID) + _CET_ENDBR + ret +E(L(store_table), UNIX64_RET_UINT8) + _CET_ENDBR + movzbl %al, %eax + movq %rax, (%rdi) + ret +E(L(store_table), UNIX64_RET_UINT16) + _CET_ENDBR + movzwl %ax, %eax + movq %rax, (%rdi) + ret +E(L(store_table), UNIX64_RET_UINT32) + _CET_ENDBR + movl %eax, %eax + movq %rax, (%rdi) + ret +E(L(store_table), UNIX64_RET_SINT8) + _CET_ENDBR + movsbq %al, %rax + movq %rax, (%rdi) + ret +E(L(store_table), UNIX64_RET_SINT16) + _CET_ENDBR + movswq %ax, %rax + movq %rax, (%rdi) + ret +E(L(store_table), UNIX64_RET_SINT32) + _CET_ENDBR + cltq + movq %rax, (%rdi) + ret +E(L(store_table), UNIX64_RET_INT64) + _CET_ENDBR + movq %rax, (%rdi) + ret +E(L(store_table), UNIX64_RET_XMM32) + _CET_ENDBR + movd %xmm0, (%rdi) + ret +E(L(store_table), UNIX64_RET_XMM64) + _CET_ENDBR + movq %xmm0, (%rdi) + ret +E(L(store_table), UNIX64_RET_X87) + _CET_ENDBR + fstpt (%rdi) + ret +E(L(store_table), UNIX64_RET_X87_2) + _CET_ENDBR + fstpt (%rdi) + fstpt 16(%rdi) + ret +E(L(store_table), UNIX64_RET_ST_XMM0_RAX) + _CET_ENDBR + movq %rax, 8(%rsi) + jmp L(s3) +E(L(store_table), UNIX64_RET_ST_RAX_XMM0) + _CET_ENDBR + movq %xmm0, 8(%rsi) + jmp L(s2) +E(L(store_table), UNIX64_RET_ST_XMM0_XMM1) + _CET_ENDBR + movq %xmm1, 8(%rsi) + jmp L(s3) +E(L(store_table), UNIX64_RET_ST_RAX_RDX) + _CET_ENDBR + movq %rdx, 8(%rsi) +L(s2): + movq %rax, (%rsi) + shrl $UNIX64_SIZE_SHIFT, %ecx + rep movsb + ret + .balign 8 +L(s3): + movq %xmm0, (%rsi) + shrl $UNIX64_SIZE_SHIFT, %ecx + rep movsb + ret + +L(sa): call PLT(C(abort)) + + /* Many times we can avoid loading any SSE registers at all. + It's not worth an indirect jump to load the exact set of + SSE registers needed; zero or all is a good compromise. */ + .balign 2 +L(UW3): + /* cfi_restore_state */ +L(load_sse): + movdqa 0x30(%r10), %xmm0 + movdqa 0x40(%r10), %xmm1 + movdqa 0x50(%r10), %xmm2 + movdqa 0x60(%r10), %xmm3 + movdqa 0x70(%r10), %xmm4 + movdqa 0x80(%r10), %xmm5 + movdqa 0x90(%r10), %xmm6 + movdqa 0xa0(%r10), %xmm7 + jmp L(ret_from_load_sse) + +L(UW4): +ENDF(C(ffi_call_unix64)) + +/* 6 general registers, 8 vector registers, + 32 bytes of rvalue, 8 bytes of alignment. */ +#define ffi_closure_OFS_G 0 +#define ffi_closure_OFS_V (6*8) +#define ffi_closure_OFS_RVALUE (ffi_closure_OFS_V + 8*16) +#define ffi_closure_FS (ffi_closure_OFS_RVALUE + 32 + 8) + +/* The location of rvalue within the red zone after deallocating the frame. */ +#define ffi_closure_RED_RVALUE (ffi_closure_OFS_RVALUE - ffi_closure_FS) + + .balign 2 + .globl C(ffi_closure_unix64_sse) + FFI_HIDDEN(C(ffi_closure_unix64_sse)) + +C(ffi_closure_unix64_sse): +L(UW5): + _CET_ENDBR + subq $ffi_closure_FS, %rsp +L(UW6): + /* cfi_adjust_cfa_offset(ffi_closure_FS) */ + + movdqa %xmm0, ffi_closure_OFS_V+0x00(%rsp) + movdqa %xmm1, ffi_closure_OFS_V+0x10(%rsp) + movdqa %xmm2, ffi_closure_OFS_V+0x20(%rsp) + movdqa %xmm3, ffi_closure_OFS_V+0x30(%rsp) + movdqa %xmm4, ffi_closure_OFS_V+0x40(%rsp) + movdqa %xmm5, ffi_closure_OFS_V+0x50(%rsp) + movdqa %xmm6, ffi_closure_OFS_V+0x60(%rsp) + movdqa %xmm7, ffi_closure_OFS_V+0x70(%rsp) + jmp L(sse_entry1) + +L(UW7): +ENDF(C(ffi_closure_unix64_sse)) + + .balign 2 + .globl C(ffi_closure_unix64) + FFI_HIDDEN(C(ffi_closure_unix64)) + +C(ffi_closure_unix64): +L(UW8): + _CET_ENDBR + subq $ffi_closure_FS, %rsp +L(UW9): + /* cfi_adjust_cfa_offset(ffi_closure_FS) */ +L(sse_entry1): + movq %rdi, ffi_closure_OFS_G+0x00(%rsp) + movq %rsi, ffi_closure_OFS_G+0x08(%rsp) + movq %rdx, ffi_closure_OFS_G+0x10(%rsp) + movq %rcx, ffi_closure_OFS_G+0x18(%rsp) + movq %r8, ffi_closure_OFS_G+0x20(%rsp) + movq %r9, ffi_closure_OFS_G+0x28(%rsp) + +#ifdef __ILP32__ + movl FFI_TRAMPOLINE_SIZE(%r10), %edi /* Load cif */ + movl FFI_TRAMPOLINE_SIZE+4(%r10), %esi /* Load fun */ + movl FFI_TRAMPOLINE_SIZE+8(%r10), %edx /* Load user_data */ +#else + movq FFI_TRAMPOLINE_SIZE(%r10), %rdi /* Load cif */ + movq FFI_TRAMPOLINE_SIZE+8(%r10), %rsi /* Load fun */ + movq FFI_TRAMPOLINE_SIZE+16(%r10), %rdx /* Load user_data */ +#endif +L(do_closure): + leaq ffi_closure_OFS_RVALUE(%rsp), %rcx /* Load rvalue */ + movq %rsp, %r8 /* Load reg_args */ + leaq ffi_closure_FS+8(%rsp), %r9 /* Load argp */ + call PLT(C(ffi_closure_unix64_inner)) + + /* Deallocate stack frame early; return value is now in redzone. */ + addq $ffi_closure_FS, %rsp +L(UW10): + /* cfi_adjust_cfa_offset(-ffi_closure_FS) */ + + /* The first byte of the return value contains the FFI_TYPE. */ + cmpb $UNIX64_RET_LAST, %al + movzbl %al, %r10d + leaq L(load_table)(%rip), %r11 + ja L(la) +#ifdef __CET__ + /* NB: Originally, each slot is 8 byte. 4 bytes of ENDBR64 + + 4 bytes NOP padding double slot size to 16 bytes. */ + addl %r10d, %r10d +#endif + leaq (%r11, %r10, 8), %r10 + leaq ffi_closure_RED_RVALUE(%rsp), %rsi + jmp *%r10 + + .balign 8 +L(load_table): +E(L(load_table), UNIX64_RET_VOID) + _CET_ENDBR + ret +E(L(load_table), UNIX64_RET_UINT8) + _CET_ENDBR + movzbl (%rsi), %eax + ret +E(L(load_table), UNIX64_RET_UINT16) + _CET_ENDBR + movzwl (%rsi), %eax + ret +E(L(load_table), UNIX64_RET_UINT32) + _CET_ENDBR + movl (%rsi), %eax + ret +E(L(load_table), UNIX64_RET_SINT8) + _CET_ENDBR + movsbl (%rsi), %eax + ret +E(L(load_table), UNIX64_RET_SINT16) + _CET_ENDBR + movswl (%rsi), %eax + ret +E(L(load_table), UNIX64_RET_SINT32) + _CET_ENDBR + movl (%rsi), %eax + ret +E(L(load_table), UNIX64_RET_INT64) + _CET_ENDBR + movq (%rsi), %rax + ret +E(L(load_table), UNIX64_RET_XMM32) + _CET_ENDBR + movd (%rsi), %xmm0 + ret +E(L(load_table), UNIX64_RET_XMM64) + _CET_ENDBR + movq (%rsi), %xmm0 + ret +E(L(load_table), UNIX64_RET_X87) + _CET_ENDBR + fldt (%rsi) + ret +E(L(load_table), UNIX64_RET_X87_2) + _CET_ENDBR + fldt 16(%rsi) + fldt (%rsi) + ret +E(L(load_table), UNIX64_RET_ST_XMM0_RAX) + _CET_ENDBR + movq 8(%rsi), %rax + jmp L(l3) +E(L(load_table), UNIX64_RET_ST_RAX_XMM0) + _CET_ENDBR + movq 8(%rsi), %xmm0 + jmp L(l2) +E(L(load_table), UNIX64_RET_ST_XMM0_XMM1) + _CET_ENDBR + movq 8(%rsi), %xmm1 + jmp L(l3) +E(L(load_table), UNIX64_RET_ST_RAX_RDX) + _CET_ENDBR + movq 8(%rsi), %rdx +L(l2): + movq (%rsi), %rax + ret + .balign 8 +L(l3): + movq (%rsi), %xmm0 + ret + +L(la): call PLT(C(abort)) + +L(UW11): +ENDF(C(ffi_closure_unix64)) + + .balign 2 + .globl C(ffi_go_closure_unix64_sse) + FFI_HIDDEN(C(ffi_go_closure_unix64_sse)) + +C(ffi_go_closure_unix64_sse): +L(UW12): + _CET_ENDBR + subq $ffi_closure_FS, %rsp +L(UW13): + /* cfi_adjust_cfa_offset(ffi_closure_FS) */ + + movdqa %xmm0, ffi_closure_OFS_V+0x00(%rsp) + movdqa %xmm1, ffi_closure_OFS_V+0x10(%rsp) + movdqa %xmm2, ffi_closure_OFS_V+0x20(%rsp) + movdqa %xmm3, ffi_closure_OFS_V+0x30(%rsp) + movdqa %xmm4, ffi_closure_OFS_V+0x40(%rsp) + movdqa %xmm5, ffi_closure_OFS_V+0x50(%rsp) + movdqa %xmm6, ffi_closure_OFS_V+0x60(%rsp) + movdqa %xmm7, ffi_closure_OFS_V+0x70(%rsp) + jmp L(sse_entry2) + +L(UW14): +ENDF(C(ffi_go_closure_unix64_sse)) + + .balign 2 + .globl C(ffi_go_closure_unix64) + FFI_HIDDEN(C(ffi_go_closure_unix64)) + +C(ffi_go_closure_unix64): +L(UW15): + _CET_ENDBR + subq $ffi_closure_FS, %rsp +L(UW16): + /* cfi_adjust_cfa_offset(ffi_closure_FS) */ +L(sse_entry2): + movq %rdi, ffi_closure_OFS_G+0x00(%rsp) + movq %rsi, ffi_closure_OFS_G+0x08(%rsp) + movq %rdx, ffi_closure_OFS_G+0x10(%rsp) + movq %rcx, ffi_closure_OFS_G+0x18(%rsp) + movq %r8, ffi_closure_OFS_G+0x20(%rsp) + movq %r9, ffi_closure_OFS_G+0x28(%rsp) + +#ifdef __ILP32__ + movl 4(%r10), %edi /* Load cif */ + movl 8(%r10), %esi /* Load fun */ + movl %r10d, %edx /* Load closure (user_data) */ +#else + movq 8(%r10), %rdi /* Load cif */ + movq 16(%r10), %rsi /* Load fun */ + movq %r10, %rdx /* Load closure (user_data) */ +#endif + jmp L(do_closure) + +L(UW17): +ENDF(C(ffi_go_closure_unix64)) + +/* Sadly, OSX cctools-as doesn't understand .cfi directives at all. */ + +#ifdef __APPLE__ +.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support +EHFrame0: +#elif defined(HAVE_AS_X86_64_UNWIND_SECTION_TYPE) +.section .eh_frame,"a",@unwind +#else +.section .eh_frame,"a",@progbits +#endif + +#ifdef HAVE_AS_X86_PCREL +# define PCREL(X) X - . +#else +# define PCREL(X) X@rel +#endif + +/* Simplify advancing between labels. Assume DW_CFA_advance_loc1 fits. */ +#ifdef __CET__ +/* Use DW_CFA_advance_loc2 when IBT is enabled. */ +# define ADV(N, P) .byte 3; .2byte L(N)-L(P) +#else +# define ADV(N, P) .byte 2, L(N)-L(P) +#endif + + .balign 8 +L(CIE): + .set L(set0),L(ECIE)-L(SCIE) + .long L(set0) /* CIE Length */ +L(SCIE): + .long 0 /* CIE Identifier Tag */ + .byte 1 /* CIE Version */ + .ascii "zR\0" /* CIE Augmentation */ + .byte 1 /* CIE Code Alignment Factor */ + .byte 0x78 /* CIE Data Alignment Factor */ + .byte 0x10 /* CIE RA Column */ + .byte 1 /* Augmentation size */ + .byte 0x1b /* FDE Encoding (pcrel sdata4) */ + .byte 0xc, 7, 8 /* DW_CFA_def_cfa, %rsp offset 8 */ + .byte 0x80+16, 1 /* DW_CFA_offset, %rip offset 1*-8 */ + .balign 8 +L(ECIE): + + .set L(set1),L(EFDE1)-L(SFDE1) + .long L(set1) /* FDE Length */ +L(SFDE1): + .long L(SFDE1)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW0)) /* Initial location */ + .long L(UW4)-L(UW0) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW1, UW0) + .byte 0xc, 6, 32 /* DW_CFA_def_cfa, %rbp 32 */ + .byte 0x80+6, 2 /* DW_CFA_offset, %rbp 2*-8 */ + ADV(UW2, UW1) + .byte 0xa /* DW_CFA_remember_state */ + .byte 0xc, 7, 8 /* DW_CFA_def_cfa, %rsp 8 */ + .byte 0xc0+6 /* DW_CFA_restore, %rbp */ + ADV(UW3, UW2) + .byte 0xb /* DW_CFA_restore_state */ + .balign 8 +L(EFDE1): + + .set L(set2),L(EFDE2)-L(SFDE2) + .long L(set2) /* FDE Length */ +L(SFDE2): + .long L(SFDE2)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW5)) /* Initial location */ + .long L(UW7)-L(UW5) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW6, UW5) + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */ + .balign 8 +L(EFDE2): + + .set L(set3),L(EFDE3)-L(SFDE3) + .long L(set3) /* FDE Length */ +L(SFDE3): + .long L(SFDE3)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW8)) /* Initial location */ + .long L(UW11)-L(UW8) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW9, UW8) + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */ + ADV(UW10, UW9) + .byte 0xe, 8 /* DW_CFA_def_cfa_offset 8 */ +L(EFDE3): + + .set L(set4),L(EFDE4)-L(SFDE4) + .long L(set4) /* FDE Length */ +L(SFDE4): + .long L(SFDE4)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW12)) /* Initial location */ + .long L(UW14)-L(UW12) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW13, UW12) + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */ + .balign 8 +L(EFDE4): + + .set L(set5),L(EFDE5)-L(SFDE5) + .long L(set5) /* FDE Length */ +L(SFDE5): + .long L(SFDE5)-L(CIE) /* FDE CIE offset */ + .long PCREL(L(UW15)) /* Initial location */ + .long L(UW17)-L(UW15) /* Address range */ + .byte 0 /* Augmentation size */ + ADV(UW16, UW15) + .byte 0xe /* DW_CFA_def_cfa_offset */ + .byte ffi_closure_FS + 8, 1 /* uleb128, assuming 128 <= FS < 255 */ + .balign 8 +L(EFDE5): +#ifdef __APPLE__ + .subsections_via_symbols + .section __LD,__compact_unwind,regular,debug + + /* compact unwind for ffi_call_unix64 */ + .quad C(ffi_call_unix64) + .set L1,L(UW4)-L(UW0) + .long L1 + .long 0x04000000 /* use dwarf unwind info */ + .quad 0 + .quad 0 + + /* compact unwind for ffi_closure_unix64_sse */ + .quad C(ffi_closure_unix64_sse) + .set L2,L(UW7)-L(UW5) + .long L2 + .long 0x04000000 /* use dwarf unwind info */ + .quad 0 + .quad 0 + + /* compact unwind for ffi_closure_unix64 */ + .quad C(ffi_closure_unix64) + .set L3,L(UW11)-L(UW8) + .long L3 + .long 0x04000000 /* use dwarf unwind info */ + .quad 0 + .quad 0 + + /* compact unwind for ffi_go_closure_unix64_sse */ + .quad C(ffi_go_closure_unix64_sse) + .set L4,L(UW14)-L(UW12) + .long L4 + .long 0x04000000 /* use dwarf unwind info */ + .quad 0 + .quad 0 + + /* compact unwind for ffi_go_closure_unix64 */ + .quad C(ffi_go_closure_unix64) + .set L5,L(UW17)-L(UW15) + .long L5 + .long 0x04000000 /* use dwarf unwind info */ + .quad 0 + .quad 0 +#endif + +#endif /* __x86_64__ */ +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/win64.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/win64.S new file mode 100644 index 0000000..8315e8b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/win64.S @@ -0,0 +1,241 @@ +#ifdef __x86_64__ +#define LIBFFI_ASM +#include +#include +#include +#include "asmnames.h" + +#if defined(HAVE_AS_CFI_PSEUDO_OP) + .cfi_sections .debug_frame +#endif + +#ifdef X86_WIN64 +#define SEH(...) __VA_ARGS__ +#define arg0 %rcx +#define arg1 %rdx +#define arg2 %r8 +#define arg3 %r9 +#else +#define SEH(...) +#define arg0 %rdi +#define arg1 %rsi +#define arg2 %rdx +#define arg3 %rcx +#endif + +/* This macro allows the safe creation of jump tables without an + actual table. The entry points into the table are all 8 bytes. + The use of ORG asserts that we're at the correct location. */ +/* ??? The clang assembler doesn't handle .org with symbolic expressions. */ +#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__)) +# define E(BASE, X) .balign 8 +#else +# define E(BASE, X) .balign 8; .org BASE + (X) * 8 +#endif + + .text + +/* ffi_call_win64 (void *stack, struct win64_call_frame *frame, void *r10) + + Bit o trickiness here -- FRAME is the base of the stack frame + for this function. This has been allocated by ffi_call. We also + deallocate some of the stack that has been alloca'd. */ + + .align 8 + .globl C(ffi_call_win64) + FFI_HIDDEN(C(ffi_call_win64)) + + SEH(.seh_proc ffi_call_win64) +C(ffi_call_win64): + cfi_startproc + _CET_ENDBR + /* Set up the local stack frame and install it in rbp/rsp. */ + movq (%rsp), %rax + movq %rbp, (arg1) + movq %rax, 8(arg1) + movq arg1, %rbp + cfi_def_cfa(%rbp, 16) + cfi_rel_offset(%rbp, 0) + SEH(.seh_pushreg %rbp) + SEH(.seh_setframe %rbp, 0) + SEH(.seh_endprologue) + movq arg0, %rsp + + movq arg2, %r10 + + /* Load all slots into both general and xmm registers. */ + movq (%rsp), %rcx + movsd (%rsp), %xmm0 + movq 8(%rsp), %rdx + movsd 8(%rsp), %xmm1 + movq 16(%rsp), %r8 + movsd 16(%rsp), %xmm2 + movq 24(%rsp), %r9 + movsd 24(%rsp), %xmm3 + + call *16(%rbp) + + movl 24(%rbp), %ecx + movq 32(%rbp), %r8 + leaq 0f(%rip), %r10 + cmpl $FFI_TYPE_SMALL_STRUCT_4B, %ecx + leaq (%r10, %rcx, 8), %r10 + ja 99f + _CET_NOTRACK jmp *%r10 + +/* Below, we're space constrained most of the time. Thus we eschew the + modern "mov, pop, ret" sequence (5 bytes) for "leave, ret" (2 bytes). */ +.macro epilogue + leaveq + cfi_remember_state + cfi_def_cfa(%rsp, 8) + cfi_restore(%rbp) + ret + cfi_restore_state +.endm + + .align 8 +0: +E(0b, FFI_TYPE_VOID) + epilogue +E(0b, FFI_TYPE_INT) + movslq %eax, %rax + movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_FLOAT) + movss %xmm0, (%r8) + epilogue +E(0b, FFI_TYPE_DOUBLE) + movsd %xmm0, (%r8) + epilogue +// FFI_TYPE_LONGDOUBLE may be FFI_TYPE_DOUBLE but we need a different value here. +E(0b, FFI_TYPE_DOUBLE + 1) + call PLT(C(abort)) +E(0b, FFI_TYPE_UINT8) + movzbl %al, %eax + movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_SINT8) + movsbq %al, %rax + jmp 98f +E(0b, FFI_TYPE_UINT16) + movzwl %ax, %eax + movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_SINT16) + movswq %ax, %rax + jmp 98f +E(0b, FFI_TYPE_UINT32) + movl %eax, %eax + movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_SINT32) + movslq %eax, %rax + movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_UINT64) +98: movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_SINT64) + movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_STRUCT) + epilogue +E(0b, FFI_TYPE_POINTER) + movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_COMPLEX) + call PLT(C(abort)) +E(0b, FFI_TYPE_SMALL_STRUCT_1B) + movb %al, (%r8) + epilogue +E(0b, FFI_TYPE_SMALL_STRUCT_2B) + movw %ax, (%r8) + epilogue +E(0b, FFI_TYPE_SMALL_STRUCT_4B) + movl %eax, (%r8) + epilogue + + .align 8 +99: call PLT(C(abort)) + + epilogue + + cfi_endproc + SEH(.seh_endproc) + + +/* 32 bytes of outgoing register stack space, 8 bytes of alignment, + 16 bytes of result, 32 bytes of xmm registers. */ +#define ffi_clo_FS (32+8+16+32) +#define ffi_clo_OFF_R (32+8) +#define ffi_clo_OFF_X (32+8+16) + + .align 8 + .globl C(ffi_go_closure_win64) + FFI_HIDDEN(C(ffi_go_closure_win64)) + + SEH(.seh_proc ffi_go_closure_win64) +C(ffi_go_closure_win64): + cfi_startproc + _CET_ENDBR + /* Save all integer arguments into the incoming reg stack space. */ + movq %rcx, 8(%rsp) + movq %rdx, 16(%rsp) + movq %r8, 24(%rsp) + movq %r9, 32(%rsp) + + movq 8(%r10), %rcx /* load cif */ + movq 16(%r10), %rdx /* load fun */ + movq %r10, %r8 /* closure is user_data */ + jmp 0f + cfi_endproc + SEH(.seh_endproc) + + .align 8 + .globl C(ffi_closure_win64) + FFI_HIDDEN(C(ffi_closure_win64)) + + SEH(.seh_proc ffi_closure_win64) +C(ffi_closure_win64): + cfi_startproc + _CET_ENDBR + /* Save all integer arguments into the incoming reg stack space. */ + movq %rcx, 8(%rsp) + movq %rdx, 16(%rsp) + movq %r8, 24(%rsp) + movq %r9, 32(%rsp) + + movq FFI_TRAMPOLINE_SIZE(%r10), %rcx /* load cif */ + movq FFI_TRAMPOLINE_SIZE+8(%r10), %rdx /* load fun */ + movq FFI_TRAMPOLINE_SIZE+16(%r10), %r8 /* load user_data */ +0: + subq $ffi_clo_FS, %rsp + cfi_adjust_cfa_offset(ffi_clo_FS) + SEH(.seh_stackalloc ffi_clo_FS) + SEH(.seh_endprologue) + + /* Save all sse arguments into the stack frame. */ + movsd %xmm0, ffi_clo_OFF_X(%rsp) + movsd %xmm1, ffi_clo_OFF_X+8(%rsp) + movsd %xmm2, ffi_clo_OFF_X+16(%rsp) + movsd %xmm3, ffi_clo_OFF_X+24(%rsp) + + leaq ffi_clo_OFF_R(%rsp), %r9 + call PLT(C(ffi_closure_win64_inner)) + + /* Load the result into both possible result registers. */ + movq ffi_clo_OFF_R(%rsp), %rax + movsd ffi_clo_OFF_R(%rsp), %xmm0 + + addq $ffi_clo_FS, %rsp + cfi_adjust_cfa_offset(-ffi_clo_FS) + ret + + cfi_endproc + SEH(.seh_endproc) +#endif /* __x86_64__ */ + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/win64_intel.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/win64_intel.S new file mode 100644 index 0000000..970a4f9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/x86/win64_intel.S @@ -0,0 +1,238 @@ +#define LIBFFI_ASM +#include +#include +#include +#include "asmnames.h" + +#if defined(HAVE_AS_CFI_PSEUDO_OP) + .cfi_sections .debug_frame +#endif + +#ifdef X86_WIN64 +#define SEH(...) __VA_ARGS__ +#define arg0 rcx +#define arg1 rdx +#define arg2 r8 +#define arg3 r9 +#else +#define SEH(...) +#define arg0 rdi +#define arg1 rsi +#define arg2 rdx +#define arg3 rcx +#endif + +/* This macro allows the safe creation of jump tables without an + actual table. The entry points into the table are all 8 bytes. + The use of ORG asserts that we're at the correct location. */ +/* ??? The clang assembler doesn't handle .org with symbolic expressions. */ +#if defined(__clang__) || defined(__APPLE__) || (defined (__sun__) && defined(__svr4__)) +# define E(BASE, X) ALIGN 8 +#else +# define E(BASE, X) ALIGN 8; ORG BASE + (X) * 8 +#endif + + .CODE + extern PLT(C(abort)):near + extern C(ffi_closure_win64_inner):near + +/* ffi_call_win64 (void *stack, struct win64_call_frame *frame, void *r10) + + Bit o trickiness here -- FRAME is the base of the stack frame + for this function. This has been allocated by ffi_call. We also + deallocate some of the stack that has been alloca'd. */ + + ALIGN 8 + PUBLIC C(ffi_call_win64) + + ; SEH(.safesh ffi_call_win64) +C(ffi_call_win64) proc SEH(frame) + cfi_startproc + /* Set up the local stack frame and install it in rbp/rsp. */ + mov RAX, [RSP] ; movq (%rsp), %rax + mov [arg1], RBP ; movq %rbp, (arg1) + mov [arg1 + 8], RAX; movq %rax, 8(arg1) + mov RBP, arg1; movq arg1, %rbp + cfi_def_cfa(rbp, 16) + cfi_rel_offset(rbp, 0) + SEH(.pushreg rbp) + SEH(.setframe rbp, 0) + SEH(.endprolog) + mov RSP, arg0 ; movq arg0, %rsp + + mov R10, arg2 ; movq arg2, %r10 + + /* Load all slots into both general and xmm registers. */ + mov RCX, [RSP] ; movq (%rsp), %rcx + movsd XMM0, qword ptr [RSP] ; movsd (%rsp), %xmm0 + mov RDX, [RSP + 8] ;movq 8(%rsp), %rdx + movsd XMM1, qword ptr [RSP + 8]; movsd 8(%rsp), %xmm1 + mov R8, [RSP + 16] ; movq 16(%rsp), %r8 + movsd XMM2, qword ptr [RSP + 16] ; movsd 16(%rsp), %xmm2 + mov R9, [RSP + 24] ; movq 24(%rsp), %r9 + movsd XMM3, qword ptr [RSP + 24] ;movsd 24(%rsp), %xmm3 + + CALL qword ptr [RBP + 16] ; call *16(%rbp) + + mov ECX, [RBP + 24] ; movl 24(%rbp), %ecx + mov R8, [RBP + 32] ; movq 32(%rbp), %r8 + LEA R10, ffi_call_win64_tab ; leaq 0f(%rip), %r10 + CMP ECX, FFI_TYPE_SMALL_STRUCT_4B ; cmpl $FFI_TYPE_SMALL_STRUCT_4B, %ecx + LEA R10, [R10 + RCX*8] ; leaq (%r10, %rcx, 8), %r10 + JA L99 ; ja 99f + JMP R10 ; jmp *%r10 + +/* Below, we're space constrained most of the time. Thus we eschew the + modern "mov, pop, ret" sequence (5 bytes) for "leave, ret" (2 bytes). */ +epilogue macro + LEAVE + cfi_remember_state + cfi_def_cfa(rsp, 8) + cfi_restore(rbp) + RET + cfi_restore_state +endm + + ALIGN 8 +ffi_call_win64_tab LABEL NEAR +E(0b, FFI_TYPE_VOID) + epilogue +E(0b, FFI_TYPE_INT) + movsxd rax, eax ; movslq %eax, %rax + mov qword ptr [r8], rax; movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_FLOAT) + movss dword ptr [r8], xmm0 ; movss %xmm0, (%r8) + epilogue +E(0b, FFI_TYPE_DOUBLE) + movsd qword ptr[r8], xmm0; movsd %xmm0, (%r8) + epilogue +// FFI_TYPE_LONGDOUBLE may be FFI_TYPE_DOUBLE but we need a different value here. +E(0b, FFI_TYPE_DOUBLE + 1) + call PLT(C(abort)) +E(0b, FFI_TYPE_UINT8) + movzx eax, al ;movzbl %al, %eax + mov qword ptr[r8], rax; movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_SINT8) + movsx rax, al ; movsbq %al, %rax + jmp L98 +E(0b, FFI_TYPE_UINT16) + movzx eax, ax ; movzwl %ax, %eax + mov qword ptr[r8], rax; movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_SINT16) + movsx rax, ax; movswq %ax, %rax + jmp L98 +E(0b, FFI_TYPE_UINT32) + mov eax, eax; movl %eax, %eax + mov qword ptr[r8], rax ; movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_SINT32) + movsxd rax, eax; movslq %eax, %rax + mov qword ptr [r8], rax; movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_UINT64) +L98 LABEL near + mov qword ptr [r8], rax ; movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_SINT64) + mov qword ptr [r8], rax;movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_STRUCT) + epilogue +E(0b, FFI_TYPE_POINTER) + mov qword ptr [r8], rax ;movq %rax, (%r8) + epilogue +E(0b, FFI_TYPE_COMPLEX) + call PLT(C(abort)) +E(0b, FFI_TYPE_SMALL_STRUCT_1B) + mov byte ptr [r8], al ; movb %al, (%r8) + epilogue +E(0b, FFI_TYPE_SMALL_STRUCT_2B) + mov word ptr [r8], ax ; movw %ax, (%r8) + epilogue +E(0b, FFI_TYPE_SMALL_STRUCT_4B) + mov dword ptr [r8], eax ; movl %eax, (%r8) + epilogue + + align 8 +L99 LABEL near + call PLT(C(abort)) + + epilogue + + cfi_endproc + C(ffi_call_win64) endp + + +/* 32 bytes of outgoing register stack space, 8 bytes of alignment, + 16 bytes of result, 32 bytes of xmm registers. */ +#define ffi_clo_FS (32+8+16+32) +#define ffi_clo_OFF_R (32+8) +#define ffi_clo_OFF_X (32+8+16) + + align 8 + PUBLIC C(ffi_go_closure_win64) + +C(ffi_go_closure_win64) proc + cfi_startproc + /* Save all integer arguments into the incoming reg stack space. */ + mov qword ptr [rsp + 8], rcx; movq %rcx, 8(%rsp) + mov qword ptr [rsp + 16], rdx; movq %rdx, 16(%rsp) + mov qword ptr [rsp + 24], r8; movq %r8, 24(%rsp) + mov qword ptr [rsp + 32], r9 ;movq %r9, 32(%rsp) + + mov rcx, qword ptr [r10 + 8]; movq 8(%r10), %rcx /* load cif */ + mov rdx, qword ptr [r10 + 16]; movq 16(%r10), %rdx /* load fun */ + mov r8, r10 ; movq %r10, %r8 /* closure is user_data */ + jmp ffi_closure_win64_2 + cfi_endproc + C(ffi_go_closure_win64) endp + + align 8 + +PUBLIC C(ffi_closure_win64) +C(ffi_closure_win64) PROC FRAME + cfi_startproc + /* Save all integer arguments into the incoming reg stack space. */ + mov qword ptr [rsp + 8], rcx; movq %rcx, 8(%rsp) + mov qword ptr [rsp + 16], rdx; movq %rdx, 16(%rsp) + mov qword ptr [rsp + 24], r8; movq %r8, 24(%rsp) + mov qword ptr [rsp + 32], r9; movq %r9, 32(%rsp) + + mov rcx, qword ptr [FFI_TRAMPOLINE_SIZE + r10] ;movq FFI_TRAMPOLINE_SIZE(%r10), %rcx /* load cif */ + mov rdx, qword ptr [FFI_TRAMPOLINE_SIZE + 8 + r10] ; movq FFI_TRAMPOLINE_SIZE+8(%r10), %rdx /* load fun */ + mov r8, qword ptr [FFI_TRAMPOLINE_SIZE+16+r10] ;movq FFI_TRAMPOLINE_SIZE+16(%r10), %r8 /* load user_data */ +ffi_closure_win64_2 LABEL near + sub rsp, ffi_clo_FS ;subq $ffi_clo_FS, %rsp + cfi_adjust_cfa_offset(ffi_clo_FS) + SEH(.allocstack ffi_clo_FS) + SEH(.endprolog) + + /* Save all sse arguments into the stack frame. */ + movsd qword ptr [ffi_clo_OFF_X + rsp], xmm0 ; movsd %xmm0, ffi_clo_OFF_X(%rsp) + movsd qword ptr [ffi_clo_OFF_X+8+rsp], xmm1 ; movsd %xmm1, ffi_clo_OFF_X+8(%rsp) + movsd qword ptr [ffi_clo_OFF_X+16+rsp], xmm2 ; movsd %xmm2, ffi_clo_OFF_X+16(%rsp) + movsd qword ptr [ffi_clo_OFF_X+24+rsp], xmm3 ; movsd %xmm3, ffi_clo_OFF_X+24(%rsp) + + lea r9, [ffi_clo_OFF_R + rsp] ; leaq ffi_clo_OFF_R(%rsp), %r9 + call C(ffi_closure_win64_inner) + + /* Load the result into both possible result registers. */ + + mov rax, qword ptr [ffi_clo_OFF_R + rsp] ;movq ffi_clo_OFF_R(%rsp), %rax + movsd xmm0, qword ptr [rsp + ffi_clo_OFF_R] ;movsd ffi_clo_OFF_R(%rsp), %xmm0 + + add rsp, ffi_clo_FS ;addq $ffi_clo_FS, %rsp + cfi_adjust_cfa_offset(-ffi_clo_FS) + ret + + cfi_endproc + C(ffi_closure_win64) endp + +#if defined __ELF__ && defined __linux__ + .section .note.GNU-stack,"",@progbits +#endif +_text ends +end \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/xtensa/ffi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/xtensa/ffi.c new file mode 100644 index 0000000..9a0575f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/xtensa/ffi.c @@ -0,0 +1,298 @@ +/* ----------------------------------------------------------------------- + ffi.c - Copyright (c) 2013 Tensilica, Inc. + + XTENSA Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +/* + |----------------------------------------| + | | + on entry to ffi_call ----> |----------------------------------------| + | caller stack frame for registers a0-a3 | + |----------------------------------------| + | | + | additional arguments | + entry of the function ---> |----------------------------------------| + | copy of function arguments a2-a7 | + | - - - - - - - - - - - - - | + | | + + The area below the entry line becomes the new stack frame for the function. + +*/ + + +#define FFI_TYPE_STRUCT_REGS FFI_TYPE_LAST + + +extern void ffi_call_SYSV(void *rvalue, unsigned rsize, unsigned flags, + void(*fn)(void), unsigned nbytes, extended_cif*); +extern void ffi_closure_SYSV(void) FFI_HIDDEN; + +ffi_status ffi_prep_cif_machdep(ffi_cif *cif) +{ + switch(cif->rtype->type) { + case FFI_TYPE_SINT8: + case FFI_TYPE_UINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_UINT16: + cif->flags = cif->rtype->type; + break; + case FFI_TYPE_VOID: + case FFI_TYPE_FLOAT: + cif->flags = FFI_TYPE_UINT32; + break; + case FFI_TYPE_DOUBLE: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + cif->flags = FFI_TYPE_UINT64; // cif->rtype->type; + break; + case FFI_TYPE_STRUCT: + cif->flags = FFI_TYPE_STRUCT; //_REGS; + /* Up to 16 bytes are returned in registers */ + if (cif->rtype->size > 4 * 4) { + /* returned structure is referenced by a register; use 8 bytes + (including 4 bytes for potential additional alignment) */ + cif->flags = FFI_TYPE_STRUCT; + cif->bytes += 8; + } + break; + + default: + cif->flags = FFI_TYPE_UINT32; + break; + } + + /* Round the stack up to a full 4 register frame, just in case + (we use this size in movsp). This way, it's also a multiple of + 8 bytes for 64-bit arguments. */ + cif->bytes = FFI_ALIGN(cif->bytes, 16); + + return FFI_OK; +} + +void ffi_prep_args(extended_cif *ecif, unsigned char* stack) +{ + unsigned int i; + unsigned long *addr; + ffi_type **ptr; + + union { + void **v; + char **c; + signed char **sc; + unsigned char **uc; + signed short **ss; + unsigned short **us; + unsigned int **i; + long long **ll; + float **f; + double **d; + } p_argv; + + /* Verify that everything is aligned up properly */ + FFI_ASSERT (((unsigned long) stack & 0x7) == 0); + + p_argv.v = ecif->avalue; + addr = (unsigned long*)stack; + + /* structures with a size greater than 16 bytes are passed in memory */ + if (ecif->cif->rtype->type == FFI_TYPE_STRUCT && ecif->cif->rtype->size > 16) + { + *addr++ = (unsigned long)ecif->rvalue; + } + + for (i = ecif->cif->nargs, ptr = ecif->cif->arg_types; + i > 0; + i--, ptr++, p_argv.v++) + { + switch ((*ptr)->type) + { + case FFI_TYPE_SINT8: + *addr++ = **p_argv.sc; + break; + case FFI_TYPE_UINT8: + *addr++ = **p_argv.uc; + break; + case FFI_TYPE_SINT16: + *addr++ = **p_argv.ss; + break; + case FFI_TYPE_UINT16: + *addr++ = **p_argv.us; + break; + case FFI_TYPE_FLOAT: + case FFI_TYPE_INT: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT32: + case FFI_TYPE_POINTER: + *addr++ = **p_argv.i; + break; + case FFI_TYPE_DOUBLE: + case FFI_TYPE_UINT64: + case FFI_TYPE_SINT64: + if (((unsigned long)addr & 4) != 0) + addr++; + *(unsigned long long*)addr = **p_argv.ll; + addr += sizeof(unsigned long long) / sizeof (addr); + break; + + case FFI_TYPE_STRUCT: + { + unsigned long offs; + unsigned long size; + + if (((unsigned long)addr & 4) != 0 && (*ptr)->alignment > 4) + addr++; + + offs = (unsigned long) addr - (unsigned long) stack; + size = (*ptr)->size; + + /* Entire structure must fit the argument registers or referenced */ + if (offs < FFI_REGISTER_NARGS * 4 + && offs + size > FFI_REGISTER_NARGS * 4) + addr = (unsigned long*) (stack + FFI_REGISTER_NARGS * 4); + + memcpy((char*) addr, *p_argv.c, size); + addr += (size + 3) / 4; + break; + } + + default: + FFI_ASSERT(0); + } + } +} + + +void ffi_call(ffi_cif* cif, void(*fn)(void), void *rvalue, void **avalue) +{ + extended_cif ecif; + unsigned long rsize = cif->rtype->size; + int flags = cif->flags; + void *alloc = NULL; + + ecif.cif = cif; + ecif.avalue = avalue; + + /* Note that for structures that are returned in registers (size <= 16 bytes) + we allocate a temporary buffer and use memcpy to copy it to the final + destination. The reason is that the target address might be misaligned or + the length not a multiple of 4 bytes. Handling all those cases would be + very complex. */ + + if (flags == FFI_TYPE_STRUCT && (rsize <= 16 || rvalue == NULL)) + { + alloc = alloca(FFI_ALIGN(rsize, 4)); + ecif.rvalue = alloc; + } + else + { + ecif.rvalue = rvalue; + } + + if (cif->abi != FFI_SYSV) + FFI_ASSERT(0); + + ffi_call_SYSV (ecif.rvalue, rsize, cif->flags, fn, cif->bytes, &ecif); + + if (alloc != NULL && rvalue != NULL) + memcpy(rvalue, alloc, rsize); +} + +extern void ffi_trampoline(); +extern void ffi_cacheflush(void* start, void* end); + +ffi_status +ffi_prep_closure_loc (ffi_closure* closure, + ffi_cif* cif, + void (*fun)(ffi_cif*, void*, void**, void*), + void *user_data, + void *codeloc) +{ + /* copye trampoline to stack and patch 'ffi_closure_SYSV' pointer */ + memcpy(closure->tramp, ffi_trampoline, FFI_TRAMPOLINE_SIZE); + *(unsigned int*)(&closure->tramp[8]) = (unsigned int)ffi_closure_SYSV; + + // Do we have this function? + // __builtin___clear_cache(closer->tramp, closer->tramp + FFI_TRAMPOLINE_SIZE) + ffi_cacheflush(closure->tramp, closure->tramp + FFI_TRAMPOLINE_SIZE); + + closure->cif = cif; + closure->fun = fun; + closure->user_data = user_data; + return FFI_OK; +} + + +long FFI_HIDDEN +ffi_closure_SYSV_inner(ffi_closure *closure, void **values, void *rvalue) +{ + ffi_cif *cif; + ffi_type **arg_types; + void **avalue; + int i, areg; + + cif = closure->cif; + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; + + areg = 0; + + int rtype = cif->rtype->type; + if (rtype == FFI_TYPE_STRUCT && cif->rtype->size > 4 * 4) + { + rvalue = *values; + areg++; + } + + cif = closure->cif; + arg_types = cif->arg_types; + avalue = alloca(cif->nargs * sizeof(void *)); + + for (i = 0; i < cif->nargs; i++) + { + if (arg_types[i]->alignment == 8 && (areg & 1) != 0) + areg++; + + // skip the entry 16,a1 framework, add 16 bytes (4 registers) + if (areg == FFI_REGISTER_NARGS) + areg += 4; + + if (arg_types[i]->type == FFI_TYPE_STRUCT) + { + int numregs = ((arg_types[i]->size + 3) & ~3) / 4; + if (areg < FFI_REGISTER_NARGS && areg + numregs > FFI_REGISTER_NARGS) + areg = FFI_REGISTER_NARGS + 4; + } + + avalue[i] = &values[areg]; + areg += (arg_types[i]->size + 3) / 4; + } + + (closure->fun)(cif, rvalue, avalue, closure->user_data); + + return rtype; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/xtensa/ffitarget.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/xtensa/ffitarget.h new file mode 100644 index 0000000..0ba728b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/xtensa/ffitarget.h @@ -0,0 +1,53 @@ +/* -----------------------------------------------------------------*-C-*- + ffitarget.h - Copyright (c) 2013 Tensilica, Inc. + Target configuration macros for XTENSA. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#ifndef LIBFFI_TARGET_H +#define LIBFFI_TARGET_H + +#ifndef LIBFFI_H +#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." +#endif + +#ifndef LIBFFI_ASM +typedef unsigned long ffi_arg; +typedef signed long ffi_sarg; + +typedef enum ffi_abi { + FFI_FIRST_ABI = 0, + FFI_SYSV, + FFI_LAST_ABI, + FFI_DEFAULT_ABI = FFI_SYSV +} ffi_abi; +#endif + +#define FFI_REGISTER_NARGS 6 + +/* ---- Definitions for closures ----------------------------------------- */ + +#define FFI_CLOSURES 1 +#define FFI_NATIVE_RAW_API 0 +#define FFI_TRAMPOLINE_SIZE 24 + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/xtensa/sysv.S b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/xtensa/sysv.S new file mode 100644 index 0000000..e942179 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/src/xtensa/sysv.S @@ -0,0 +1,258 @@ +/* ----------------------------------------------------------------------- + sysv.S - Copyright (c) 2013 Tensilica, Inc. + + XTENSA Foreign Function Interface + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#define LIBFFI_ASM +#include +#include + +#define ENTRY(name) .text; .globl name; .type name,@function; .align 4; name: +#define END(name) .size name , . - name + +/* Assert that the table below is in sync with ffi.h. */ + +#if FFI_TYPE_UINT8 != 5 \ + || FFI_TYPE_SINT8 != 6 \ + || FFI_TYPE_UINT16 != 7 \ + || FFI_TYPE_SINT16 != 8 \ + || FFI_TYPE_UINT32 != 9 \ + || FFI_TYPE_SINT32 != 10 \ + || FFI_TYPE_UINT64 != 11 +#error "xtensa/sysv.S out of sync with ffi.h" +#endif + + +/* ffi_call_SYSV (rvalue, rbytes, flags, (*fnaddr)(), bytes, ecif) + void *rvalue; a2 + unsigned long rbytes; a3 + unsigned flags; a4 + void (*fnaddr)(); a5 + unsigned long bytes; a6 + extended_cif* ecif) a7 +*/ + +ENTRY(ffi_call_SYSV) + + entry a1, 32 # 32 byte frame for using call8 below + + mov a10, a7 # a10(->arg0): ecif + sub a11, a1, a6 # a11(->arg1): stack pointer + mov a7, a1 # fp + movsp a1, a11 # set new sp = old_sp - bytes + + movi a8, ffi_prep_args + callx8 a8 # ffi_prep_args(ecif, stack) + + # prepare to move stack pointer back up to 6 arguments + # note that 'bytes' is already aligned + + movi a10, 6*4 + sub a11, a6, a10 + movgez a6, a10, a11 + add a6, a1, a6 + + + # we can pass up to 6 arguments in registers + # for simplicity, just load 6 arguments + # (the stack size is at least 32 bytes, so no risk to cross boundaries) + + l32i a10, a1, 0 + l32i a11, a1, 4 + l32i a12, a1, 8 + l32i a13, a1, 12 + l32i a14, a1, 16 + l32i a15, a1, 20 + + # move stack pointer + + movsp a1, a6 + + callx8 a5 # (*fn)(args...) + + # Handle return value(s) + + beqz a2, .Lexit + + movi a5, FFI_TYPE_STRUCT + bne a4, a5, .Lstore + movi a5, 16 + blt a5, a3, .Lexit + + s32i a10, a2, 0 + blti a3, 5, .Lexit + addi a3, a3, -1 + s32i a11, a2, 4 + blti a3, 8, .Lexit + s32i a12, a2, 8 + blti a3, 12, .Lexit + s32i a13, a2, 12 + +.Lexit: retw + +.Lstore: + addi a4, a4, -FFI_TYPE_UINT8 + bgei a4, 7, .Lexit # should never happen + movi a6, store_calls + add a4, a4, a4 + addx4 a6, a4, a6 # store_table + idx * 8 + jx a6 + + .align 8 +store_calls: + # UINT8 + s8i a10, a2, 0 + retw + + # SINT8 + .align 8 + s8i a10, a2, 0 + retw + + # UINT16 + .align 8 + s16i a10, a2, 0 + retw + + # SINT16 + .align 8 + s16i a10, a2, 0 + retw + + # UINT32 + .align 8 + s32i a10, a2, 0 + retw + + # SINT32 + .align 8 + s32i a10, a2, 0 + retw + + # UINT64 + .align 8 + s32i a10, a2, 0 + s32i a11, a2, 4 + retw + +END(ffi_call_SYSV) + + +/* + * void ffi_cacheflush (unsigned long start, unsigned long end) + */ + +#define EXTRA_ARGS_SIZE 24 + +ENTRY(ffi_cacheflush) + + entry a1, 16 + +1: +#if XCHAL_DCACHE_SIZE + dhwbi a2, 0 +#endif +#if XCHAL_ICACHE_SIZE + ihi a2, 0 +#endif + addi a2, a2, 4 + blt a2, a3, 1b + + retw + +END(ffi_cacheflush) + +/* ffi_trampoline is copied to the stack */ + +ENTRY(ffi_trampoline) + + entry a1, 16 + (FFI_REGISTER_NARGS * 4) + (4 * 4) # [ 0] + j 2f # [ 3] + .align 4 # [ 6] +1: .long 0 # [ 8] +2: l32r a15, 1b # [12] + _mov a14, a0 # [15] + callx0 a15 # [18] + # [21] +END(ffi_trampoline) + +/* + * ffi_closure() + * + * a0: closure + 21 + * a14: return address (a0) + */ + +ENTRY(ffi_closure_SYSV) + + /* intentionally omitting entry here */ + + # restore return address (a0) and move pointer to closure to a10 + addi a10, a0, -21 + mov a0, a14 + + # allow up to 4 arguments as return values + addi a11, a1, 4 * 4 + + # save up to 6 arguments to stack (allocated by entry below) + s32i a2, a11, 0 + s32i a3, a11, 4 + s32i a4, a11, 8 + s32i a5, a11, 12 + s32i a6, a11, 16 + s32i a7, a11, 20 + + movi a8, ffi_closure_SYSV_inner + mov a12, a1 + callx8 a8 # .._inner(*closure, **avalue, *rvalue) + + # load up to four return arguments + l32i a2, a1, 0 + l32i a3, a1, 4 + l32i a4, a1, 8 + l32i a5, a1, 12 + + # (sign-)extend return value + movi a11, FFI_TYPE_UINT8 + bne a10, a11, 1f + extui a2, a2, 0, 8 + retw + +1: movi a11, FFI_TYPE_SINT8 + bne a10, a11, 1f + sext a2, a2, 7 + retw + +1: movi a11, FFI_TYPE_UINT16 + bne a10, a11, 1f + extui a2, a2, 0, 16 + retw + +1: movi a11, FFI_TYPE_SINT16 + bne a10, a11, 1f + sext a2, a2, 15 + +1: retw + +END(ffi_closure_SYSV) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/stamp-h.in b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/stamp-h.in new file mode 100644 index 0000000..9788f70 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/stamp-h.in @@ -0,0 +1 @@ +timestamp diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/Makefile.am b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/Makefile.am new file mode 100644 index 0000000..bcfea57 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/Makefile.am @@ -0,0 +1,122 @@ +## Process this file with automake to produce Makefile.in. + +AUTOMAKE_OPTIONS = foreign dejagnu + +EXTRA_DEJAGNU_SITE_CONFIG=../local.exp + +CLEANFILES = *.exe core* *.log *.sum + +EXTRA_DIST = lib/target-libpath.exp lib/libffi.exp lib/wrapper.exp \ +libffi.call/strlen4.c libffi.call/struct10.c libffi.call/many_mixed.c \ +libffi.call/float.c libffi.call/struct5.c libffi.call/return_fl3.c \ +libffi.call/return_fl1.c libffi.call/call.exp libffi.call/pyobjc-tc.c \ +libffi.call/float_va.c libffi.call/struct8.c libffi.call/pr1172638.c \ +libffi.call/return_sc.c libffi.call/va_struct1.c \ +libffi.call/align_stdcall.c libffi.call/struct9.c libffi.call/va_1.c \ +libffi.call/va_struct2.c libffi.call/return_fl2.c \ +libffi.call/align_mixed.c libffi.call/ffitest.h libffi.call/struct4.c \ +libffi.call/return_ldl.c libffi.call/float3.c libffi.call/return_sl.c \ +libffi.call/return_dbl1.c libffi.call/err_bad_typedef.c \ +libffi.call/return_ll1.c libffi.call/return_dbl2.c \ +libffi.call/negint.c libffi.closures/nested_struct3.c \ +libffi.call/struct2.c libffi.call/struct3.c libffi.call/return_fl.c \ +libffi.call/offsets.c libffi.call/struct7.c libffi.call/va_struct3.c \ +libffi.call/float1.c libffi.call/uninitialized.c libffi.call/many2.c \ +libffi.call/struct6.c libffi.call/strlen2.c libffi.call/float2.c \ +libffi.call/return_ul.c libffi.call/struct1.c libffi.call/strlen3.c \ +libffi.call/return_dbl.c libffi.call/float4.c libffi.call/many.c \ +libffi.call/strlen.c libffi.call/return_uc.c libffi.call/many_double.c \ +libffi.call/return_ll.c libffi.call/promotion.c \ +libffi.complex/complex_defs_longdouble.inc \ +libffi.complex/cls_align_complex_float.c \ +libffi.complex/cls_complex_va_float.c \ +libffi.complex/cls_complex_struct_float.c \ +libffi.complex/return_complex2_longdouble.c \ +libffi.complex/cls_complex_float.c \ +libffi.complex/return_complex_longdouble.c \ +libffi.complex/return_complex2_float.c libffi.complex/cls_complex.inc \ +libffi.complex/cls_complex_va_longdouble.c \ +libffi.complex/return_complex_double.c \ +libffi.complex/return_complex.inc libffi.complex/many_complex.inc \ +libffi.complex/complex_float.c libffi.complex/cls_align_complex.inc \ +libffi.complex/return_complex2_double.c \ +libffi.complex/many_complex_float.c libffi.complex/ffitest.h \ +libffi.complex/return_complex1_double.c \ +libffi.complex/cls_complex_struct_longdouble.c \ +libffi.complex/complex_defs_double.inc \ +libffi.complex/cls_complex_va_double.c \ +libffi.complex/many_complex_double.c \ +libffi.complex/return_complex2.inc \ +libffi.complex/return_complex1_float.c \ +libffi.complex/complex_longdouble.c \ +libffi.complex/complex_defs_float.inc \ +libffi.complex/cls_complex_double.c \ +libffi.complex/cls_align_complex_double.c \ +libffi.complex/cls_align_complex_longdouble.c \ +libffi.complex/complex_double.c libffi.complex/cls_complex_va.inc \ +libffi.complex/many_complex_longdouble.c libffi.complex/complex.inc \ +libffi.complex/return_complex1_longdouble.c \ +libffi.complex/complex_int.c libffi.complex/cls_complex_longdouble.c \ +libffi.complex/cls_complex_struct_double.c \ +libffi.complex/return_complex1.inc libffi.complex/complex.exp \ +libffi.complex/cls_complex_struct.inc \ +libffi.complex/return_complex_float.c libffi.go/closure1.c \ +libffi.go/aa-direct.c libffi.go/ffitest.h libffi.go/go.exp \ +libffi.go/static-chain.h libffi.bhaible/bhaible.exp \ +libffi.bhaible/test-call.c libffi.bhaible/alignof.h \ +libffi.bhaible/testcases.c libffi.bhaible/test-callback.c \ +libffi.bhaible/Makefile libffi.bhaible/README config/default.exp \ +libffi.closures/cls_multi_sshort.c \ +libffi.closures/cls_align_longdouble_split2.c \ +libffi.closures/cls_1_1byte.c libffi.closures/cls_uint_va.c \ +libffi.closures/cls_3_1byte.c libffi.closures/cls_many_mixed_args.c \ +libffi.closures/cls_20byte1.c libffi.closures/cls_pointer_stack.c \ +libffi.closures/cls_align_float.c libffi.closures/cls_5_1_byte.c \ +libffi.closures/cls_9byte1.c libffi.closures/cls_align_uint32.c \ +libffi.closures/stret_medium.c libffi.closures/cls_3byte1.c \ +libffi.closures/cls_align_uint64.c libffi.closures/cls_longdouble_va.c \ +libffi.closures/cls_align_pointer.c libffi.closures/cls_19byte.c \ +libffi.closures/cls_ushort.c libffi.closures/cls_align_sint32.c \ +libffi.closures/cls_ulonglong.c libffi.closures/cls_struct_va1.c \ +libffi.closures/cls_9byte2.c libffi.closures/closure_fn5.c \ +libffi.closures/cls_5byte.c libffi.closures/cls_3float.c \ +libffi.closures/closure.exp libffi.closures/cls_schar.c \ +libffi.closures/closure_fn4.c libffi.closures/cls_uchar_va.c \ +libffi.closures/closure_fn0.c libffi.closures/huge_struct.c \ +libffi.closures/cls_ushort_va.c \ +libffi.closures/cls_64byte.c libffi.closures/cls_longdouble.c \ +libffi.closures/cls_ulong_va.c libffi.closures/cls_6_1_byte.c \ +libffi.closures/cls_align_uint16.c libffi.closures/closure_fn2.c \ +libffi.closures/unwindtest_ffi_call.cc \ +libffi.closures/cls_multi_ushortchar.c libffi.closures/cls_8byte.c \ +libffi.closures/ffitest.h libffi.closures/nested_struct8.c \ +libffi.closures/cls_pointer.c libffi.closures/nested_struct2.c \ +libffi.closures/nested_struct.c libffi.closures/cls_multi_schar.c \ +libffi.closures/cls_align_longdouble_split.c \ +libffi.closures/cls_uchar.c libffi.closures/nested_struct9.c \ +libffi.closures/cls_float.c libffi.closures/stret_medium2.c \ +libffi.closures/closure_loc_fn0.c libffi.closures/cls_6byte.c \ +libffi.closures/closure_simple.c libffi.closures/cls_align_double.c \ +libffi.closures/cls_multi_uchar.c libffi.closures/cls_4_1byte.c \ +libffi.closures/closure_fn3.c libffi.closures/cls_align_sint64.c \ +libffi.closures/nested_struct1.c libffi.closures/unwindtest.cc \ +libffi.closures/nested_struct5.c libffi.closures/cls_multi_ushort.c \ +libffi.closures/nested_struct11.c \ +libffi.closures/cls_multi_sshortchar.c \ +libffi.closures/cls_align_longdouble.c \ +libffi.closures/cls_dbls_struct.c \ +libffi.closures/cls_many_mixed_float_double.c \ +libffi.closures/stret_large.c libffi.closures/stret_large2.c \ +libffi.closures/cls_align_sint16.c libffi.closures/cls_2byte.c \ +libffi.closures/nested_struct4.c libffi.closures/problem1.c \ +libffi.closures/testclosure.c libffi.closures/nested_struct6.c \ +libffi.closures/cls_4byte.c libffi.closures/cls_24byte.c \ +libffi.closures/nested_struct10.c libffi.closures/cls_uint.c \ +libffi.closures/cls_12byte.c libffi.closures/cls_sint.c \ +libffi.closures/cls_7_1_byte.c libffi.closures/cls_sshort.c \ +libffi.closures/cls_16byte.c libffi.closures/nested_struct7.c \ +libffi.closures/cls_double_va.c libffi.closures/cls_3byte2.c \ +libffi.closures/cls_double.c libffi.closures/cls_7byte.c \ +libffi.closures/closure_fn6.c libffi.closures/closure_fn1.c \ +libffi.closures/cls_20byte.c libffi.closures/cls_18byte.c \ +libffi.closures/err_bad_abi.c diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/config/default.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/config/default.exp new file mode 100644 index 0000000..90967cc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/config/default.exp @@ -0,0 +1 @@ +load_lib "standard.exp" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/lib/libffi.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/lib/libffi.exp new file mode 100644 index 0000000..d3c17db --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/lib/libffi.exp @@ -0,0 +1,660 @@ +# Copyright (C) 2003, 2005, 2008, 2009, 2010, 2011, 2014, 2019 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; see the file COPYING3. If not see +# . + +proc load_gcc_lib { filename } { + global srcdir + load_file $srcdir/lib/$filename +} + +load_lib dg.exp +load_lib libgloss.exp +load_gcc_lib target-libpath.exp +load_gcc_lib wrapper.exp + +proc check_effective_target_gccbug { } { + global has_gccbug + return $has_gccbug +} + +# Return 1 if the target matches the effective target 'arg', 0 otherwise. +# This can be used with any check_* proc that takes no argument and +# returns only 1 or 0. It could be used with check_* procs that take +# arguments with keywords that pass particular arguments. + +proc is-effective-target { arg } { + global et_index + set selected 0 + if { ![info exists et_index] } { + # Initialize the effective target index that is used in some + # check_effective_target_* procs. + set et_index 0 + } + if { [info procs check_effective_target_${arg}] != [list] } { + set selected [check_effective_target_${arg}] + } else { + error "unknown effective target keyword `$arg'" + } + verbose "is-effective-target: $arg $selected" 2 + return $selected +} + +proc is-effective-target-keyword { arg } { + if { [info procs check_effective_target_${arg}] != [list] } { + return 1 + } else { + return 0 + } +} + +# Intercept the call to the DejaGnu version of dg-process-target to +# support use of an effective-target keyword in place of a list of +# target triplets to xfail or skip a test. +# +# The argument to dg-process-target is the keyword "target" or "xfail" +# followed by a selector: +# target-triplet-1 ... +# effective-target-keyword +# selector-expression +# +# For a target list the result is "S" if the target is selected, "N" otherwise. +# For an xfail list the result is "F" if the target is affected, "P" otherwise. + +# In contexts that allow either "target" or "xfail" the argument can be +# target selector1 xfail selector2 +# which returns "N" if selector1 is not selected, otherwise the result of +# "xfail selector2". +# +# A selector expression appears within curly braces and uses a single logical +# operator: !, &&, or ||. An operand is another selector expression, an +# effective-target keyword, or a list of target triplets within quotes or +# curly braces. + +if { [info procs saved-dg-process-target] == [list] } { + rename dg-process-target saved-dg-process-target + + # Evaluate an operand within a selector expression. + proc selector_opd { op } { + set selector "target" + lappend selector $op + set answer [ expr { [dg-process-target $selector] == "S" } ] + verbose "selector_opd: `$op' $answer" 2 + return $answer + } + + # Evaluate a target triplet list within a selector expression. + # Unlike other operands, this needs to be expanded from a list to + # the same string as "target". + proc selector_list { op } { + set selector "target [join $op]" + set answer [ expr { [dg-process-target $selector] == "S" } ] + verbose "selector_list: `$op' $answer" 2 + return $answer + } + + # Evaluate a selector expression. + proc selector_expression { exp } { + if { [llength $exp] == 2 } { + if [string match "!" [lindex $exp 0]] { + set op1 [lindex $exp 1] + set answer [expr { ! [selector_opd $op1] }] + } else { + # Assume it's a list of target triplets. + set answer [selector_list $exp] + } + } elseif { [llength $exp] == 3 } { + set op1 [lindex $exp 0] + set opr [lindex $exp 1] + set op2 [lindex $exp 2] + if [string match "&&" $opr] { + set answer [expr { [selector_opd $op1] && [selector_opd $op2] }] + } elseif [string match "||" $opr] { + set answer [expr { [selector_opd $op1] || [selector_opd $op2] }] + } else { + # Assume it's a list of target triplets. + set answer [selector_list $exp] + } + } else { + # Assume it's a list of target triplets. + set answer [selector_list $exp] + } + + verbose "selector_expression: `$exp' $answer" 2 + return $answer + } + + # Evaluate "target selector" or "xfail selector". + + proc dg-process-target-1 { args } { + verbose "dg-process-target-1: `$args'" 2 + + # Extract the 'what' keyword from the argument list. + set selector [string trim [lindex $args 0]] + if [regexp "^xfail " $selector] { + set what "xfail" + } elseif [regexp "^target " $selector] { + set what "target" + } else { + error "syntax error in target selector \"$selector\"" + } + + # Extract the rest of the list, which might be a keyword. + regsub "^${what}" $selector "" rest + set rest [string trim $rest] + + if [is-effective-target-keyword $rest] { + # The selector is an effective target keyword. + if [is-effective-target $rest] { + return [expr { $what == "xfail" ? "F" : "S" }] + } else { + return [expr { $what == "xfail" ? "P" : "N" }] + } + } + + if [string match "{*}" $rest] { + if [selector_expression [lindex $rest 0]] { + return [expr { $what == "xfail" ? "F" : "S" }] + } else { + return [expr { $what == "xfail" ? "P" : "N" }] + } + } + + # The selector is not an effective-target keyword, so process + # the list of target triplets. + return [saved-dg-process-target $selector] + } + + # Intercept calls to the DejaGnu function. In addition to + # processing "target selector" or "xfail selector", handle + # "target selector1 xfail selector2". + + proc dg-process-target { args } { + verbose "replacement dg-process-target: `$args'" 2 + + set selector [string trim [lindex $args 0]] + + # If the argument list contains both 'target' and 'xfail', + # process 'target' and, if that succeeds, process 'xfail'. + if [regexp "^target .* xfail .*" $selector] { + set xfail_index [string first "xfail" $selector] + set xfail_selector [string range $selector $xfail_index end] + set target_selector [string range $selector 0 [expr $xfail_index-1]] + set target_selector [string trim $target_selector] + if { [dg-process-target-1 $target_selector] == "N" } { + return "N" + } + return [dg-process-target-1 $xfail_selector] + + } + return [dg-process-target-1 $selector] + } +} + +# Define libffi callbacks for dg.exp. + +proc libffi-dg-test-1 { target_compile prog do_what extra_tool_flags } { + + # To get all \n in dg-output test strings to match printf output + # in a system that outputs it as \015\012 (i.e. not just \012), we + # need to change all \n into \r?\n. As there is no dejagnu flag + # or hook to do that, we simply change the text being tested. + # Unfortunately, we have to know that the variable is called + # dg-output-text and lives in the caller of libffi-dg-test, which + # is two calls up. Overriding proc dg-output would be longer and + # would necessarily have the same assumption. + upvar 2 dg-output-text output_match + + if { [llength $output_match] > 1 } { + regsub -all "\n" [lindex $output_match 1] "\r?\n" x + set output_match [lreplace $output_match 1 1 $x] + } + + # Set up the compiler flags, based on what we're going to do. + + set options [list] + switch $do_what { + "compile" { + set compile_type "assembly" + set output_file "[file rootname [file tail $prog]].s" + } + "link" { + set compile_type "executable" + set output_file "[file rootname [file tail $prog]].exe" + # The following line is needed for targets like the i960 where + # the default output file is b.out. Sigh. + } + "run" { + set compile_type "executable" + # FIXME: "./" is to cope with "." not being in $PATH. + # Should this be handled elsewhere? + # YES. + set output_file "./[file rootname [file tail $prog]].exe" + # This is the only place where we care if an executable was + # created or not. If it was, dg.exp will try to run it. + remote_file build delete $output_file; + } + default { + perror "$do_what: not a valid dg-do keyword" + return "" + } + } + + if { $extra_tool_flags != "" } { + lappend options "additional_flags=$extra_tool_flags" + } + + set comp_output [libffi_target_compile "$prog" "$output_file" "$compile_type" $options]; + + + return [list $comp_output $output_file] +} + + +proc libffi-dg-test { prog do_what extra_tool_flags } { + return [libffi-dg-test-1 target_compile $prog $do_what $extra_tool_flags] +} + +proc libffi-dg-prune { target_triplet text } { + # We get this with some qemu emulated systems (eg. ppc64le-linux-gnu) + regsub -all "(^|\n)\[^\n\]*unable to perform all requested operations" $text "" text + return $text +} + +proc libffi-init { args } { + global gluefile wrap_flags; + global srcdir + global blddirffi + global objdir + global TOOL_OPTIONS + global tool + global libffi_include + global libffi_link_flags + global tool_root_dir + global ld_library_path + global compiler_vendor + + if ![info exists blddirffi] { + set blddirffi [pwd]/.. + } + + verbose "libffi $blddirffi" + + # Which compiler are we building with? + set tmp [grep "$blddirffi/config.log" "^ax_cv_c_compiler_vendor.*$"] + regexp -- {^[^=]*=(.*)$} $tmp nil compiler_vendor + + if { [string match $compiler_vendor "gnu"] } { + set gccdir [lookfor_file $tool_root_dir gcc/libgcc.a] + if {$gccdir != ""} { + set gccdir [file dirname $gccdir] + } + verbose "gccdir $gccdir" + + set ld_library_path "." + append ld_library_path ":${gccdir}" + + set compiler "${gccdir}/xgcc" + if { [is_remote host] == 0 && [which $compiler] != 0 } { + foreach i "[exec $compiler --print-multi-lib]" { + set mldir "" + regexp -- "\[a-z0-9=_/\.-\]*;" $i mldir + set mldir [string trimright $mldir "\;@"] + if { "$mldir" == "." } { + continue + } + if { [llength [glob -nocomplain ${gccdir}/${mldir}/libgcc_s*.so.*]] >= 1 } { + append ld_library_path ":${gccdir}/${mldir}" + } + } + } + } + + # add the library path for libffi. + append ld_library_path ":${blddirffi}/.libs" + + verbose "ld_library_path: $ld_library_path" + + # Point to the Libffi headers in libffi. + set libffi_include "${blddirffi}/include" + verbose "libffi_include $libffi_include" + + set libffi_dir "${blddirffi}/.libs" + verbose "libffi_dir $libffi_dir" + if { $libffi_dir != "" } { + set libffi_dir [file dirname ${libffi_dir}] + set libffi_link_flags "-L${libffi_dir}/.libs" + } + + set_ld_library_path_env_vars + libffi_maybe_build_wrapper "${objdir}/testglue.o" +} + +proc libffi_exit { } { + global gluefile; + + if [info exists gluefile] { + file_on_build delete $gluefile; + unset gluefile; + } +} + +proc libffi_target_compile { source dest type options } { + global gluefile wrap_flags; + global srcdir + global blddirffi + global TOOL_OPTIONS + global libffi_link_flags + global libffi_include + global target_triplet + global compiler_vendor + + if { [target_info needs_status_wrapper]!="" && [info exists gluefile] } { + lappend options "libs=${gluefile}" + lappend options "ldflags=$wrap_flags" + } + + # TOOL_OPTIONS must come first, so that it doesn't override testcase + # specific options. + if [info exists TOOL_OPTIONS] { + lappend options "additional_flags=$TOOL_OPTIONS" + } + + # search for ffi_mips.h in srcdir, too + lappend options "additional_flags=-I${libffi_include} -I${srcdir}/../include -I${libffi_include}/.." + lappend options "additional_flags=${libffi_link_flags}" + + # Darwin needs a stack execution allowed flag. + + if { [istarget "*-*-darwin9*"] || [istarget "*-*-darwin1*"] + || [istarget "*-*-darwin2*"] } { + lappend options "additional_flags=-Wl,-allow_stack_execute" + } + + # If you're building the compiler with --prefix set to a place + # where it's not yet installed, then the linker won't be able to + # find the libgcc used by libffi.dylib. We could pass the + # -dylib_file option, but that's complicated, and it's much easier + # to just make the linker find libgcc using -L options. + if { [string match "*-*-darwin*" $target_triplet] } { + lappend options "libs= -shared-libgcc" + } + + if { [string match "*-*-openbsd*" $target_triplet] } { + lappend options "libs= -lpthread" + } + + lappend options "libs= -lffi" + + if { [string match "aarch64*-*-linux*" $target_triplet] } { + lappend options "libs= -lpthread" + } + + # this may be required for g++, but just confused clang. + if { [string match "*.cc" $source] } { + lappend options "c++" + } + + if { [string match "arc*-*-linux*" $target_triplet] } { + lappend options "libs= -lpthread" + } + + verbose "options: $options" + return [target_compile $source $dest $type $options] +} + +# TEST should be a preprocessor condition. Returns true if it holds. +proc libffi_feature_test { test } { + set src "ffitest[pid].c" + + set f [open $src "w"] + puts $f "#include " + puts $f $test + puts $f "/* OK */" + puts $f "#else" + puts $f "# error Failed $test" + puts $f "#endif" + close $f + + set lines [libffi_target_compile $src /dev/null assembly ""] + file delete $src + + return [string match "" $lines] +} + +# Utility routines. + +# +# search_for -- looks for a string match in a file +# +proc search_for { file pattern } { + set fd [open $file r] + while { [gets $fd cur_line]>=0 } { + if [string match "*$pattern*" $cur_line] then { + close $fd + return 1 + } + } + close $fd + return 0 +} + +# Modified dg-runtest that can cycle through a list of optimization options +# as c-torture does. +proc libffi-dg-runtest { testcases default-extra-flags } { + global runtests + + foreach test $testcases { + # If we're only testing specific files and this isn't one of + # them, skip it. + if ![runtest_file_p $runtests $test] { + continue + } + + # Look for a loop within the source code - if we don't find one, + # don't pass -funroll[-all]-loops. + global torture_with_loops torture_without_loops + if [expr [search_for $test "for*("]+[search_for $test "while*("]] { + set option_list $torture_with_loops + } else { + set option_list $torture_without_loops + } + + set nshort [file tail [file dirname $test]]/[file tail $test] + + foreach flags $option_list { + verbose "Testing $nshort, $flags" 1 + dg-test $test $flags ${default-extra-flags} + } + } +} + +proc run-many-tests { testcases extra_flags } { + global compiler_vendor + global has_gccbug + global env + switch $compiler_vendor { + "clang" { + set common "-W -Wall" + if [info exists env(LIBFFI_TEST_OPTIMIZATION)] { + set optimizations [ list $env(LIBFFI_TEST_OPTIMIZATION) ] + } else { + set optimizations { "-O0" "-O2" } + } + } + "gnu" { + set common "-W -Wall -Wno-psabi" + if [info exists env(LIBFFI_TEST_OPTIMIZATION)] { + set optimizations [ list $env(LIBFFI_TEST_OPTIMIZATION) ] + } else { + set optimizations { "-O0" "-O2" } + } + } + default { + # Assume we are using the vendor compiler. + set common "" + if [info exists env(LIBFFI_TEST_OPTIMIZATION)] { + set optimizations [ list $env(LIBFFI_TEST_OPTIMIZATION) ] + } else { + set optimizations { "" } + } + } + } + + info exists env(LD_LIBRARY_PATH) + + set targetabis { "" } + if [string match $compiler_vendor "gnu"] { + if [libffi_feature_test "#ifdef __i386__"] { + set targetabis { + "" + "-DABI_NUM=FFI_STDCALL -DABI_ATTR=__STDCALL__" + "-DABI_NUM=FFI_THISCALL -DABI_ATTR=__THISCALL__" + "-DABI_NUM=FFI_FASTCALL -DABI_ATTR=__FASTCALL__" + } + } elseif { [istarget "x86_64-*-*"] \ + && [libffi_feature_test "#if !defined __ILP32__ \ + && !defined __i386__"] } { + set targetabis { + "" + "-DABI_NUM=FFI_GNUW64 -DABI_ATTR=__MSABI__" + } + } + } + + set common [ concat $common $extra_flags ] + foreach test $testcases { + set testname [file tail $test] + if [search_for $test "ABI_NUM"] { + set abis $targetabis + } else { + set abis { "" } + } + foreach opt $optimizations { + foreach abi $abis { + set options [concat $common $opt $abi] + set has_gccbug false; + if { [string match $compiler_vendor "gnu"] \ + && [string match "*MSABI*" $abi] \ + && ( ( [string match "*DGTEST=57 *" $common] \ + && [string match "*call.c*" $testname] ) \ + || ( [string match "*DGTEST=54 *" $common] \ + && [string match "*callback*" $testname] ) \ + || [string match "*DGTEST=55 *" $common] \ + || [string match "*DGTEST=56 *" $common] ) } then { + if [libffi_feature_test "#if (__GNUC__ < 9) || ((__GNUC__ == 9) && (__GNUC_MINOR__ < 3))"] { + set has_gccbug true; + } + } + verbose "Testing $testname, $options" 1 + verbose "has_gccbug = $has_gccbug" 1 + dg-test $test $options "" + } + } + } +} + +# Like check_conditional_xfail, but callable from a dg test. + +proc dg-xfail-if { args } { + set args [lreplace $args 0 0] + set selector "target [join [lindex $args 1]]" + if { [dg-process-target $selector] == "S" } { + global compiler_conditional_xfail_data + set compiler_conditional_xfail_data $args + } +} + +proc check-flags { args } { + + # The args are within another list; pull them out. + set args [lindex $args 0] + + # The next two arguments are optional. If they were not specified, + # use the defaults. + if { [llength $args] == 2 } { + lappend $args [list "*"] + } + if { [llength $args] == 3 } { + lappend $args [list ""] + } + + # If the option strings are the defaults, or the same as the + # defaults, there is no need to call check_conditional_xfail to + # compare them to the actual options. + if { [string compare [lindex $args 2] "*"] == 0 + && [string compare [lindex $args 3] "" ] == 0 } { + set result 1 + } else { + # The target list might be an effective-target keyword, so replace + # the original list with "*-*-*", since we already know it matches. + set result [check_conditional_xfail [lreplace $args 1 1 "*-*-*"]] + } + + return $result +} + +proc dg-skip-if { args } { + # Verify the number of arguments. The last two are optional. + set args [lreplace $args 0 0] + if { [llength $args] < 2 || [llength $args] > 4 } { + error "dg-skip-if 2: need 2, 3, or 4 arguments" + } + + # Don't bother if we're already skipping the test. + upvar dg-do-what dg-do-what + if { [lindex ${dg-do-what} 1] == "N" } { + return + } + + set selector [list target [lindex $args 1]] + if { [dg-process-target $selector] == "S" } { + if [check-flags $args] { + upvar dg-do-what dg-do-what + set dg-do-what [list [lindex ${dg-do-what} 0] "N" "P"] + } + } +} + +# We need to make sure that additional_files and additional_sources +# are both cleared out after every test. It is not enough to clear +# them out *before* the next test run because gcc-target-compile gets +# run directly from some .exp files (outside of any test). (Those +# uses should eventually be eliminated.) + +# Because the DG framework doesn't provide a hook that is run at the +# end of a test, we must replace dg-test with a wrapper. + +if { [info procs saved-dg-test] == [list] } { + rename dg-test saved-dg-test + + proc dg-test { args } { + global additional_files + global additional_sources + global errorInfo + + if { [ catch { eval saved-dg-test $args } errmsg ] } { + set saved_info $errorInfo + set additional_files "" + set additional_sources "" + error $errmsg $saved_info + } + set additional_files "" + set additional_sources "" + } +} + +# Local Variables: +# tcl-indent-level:4 +# End: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/lib/target-libpath.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/lib/target-libpath.exp new file mode 100644 index 0000000..6b7beba --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/lib/target-libpath.exp @@ -0,0 +1,283 @@ +# Copyright (C) 2004, 2005, 2007 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GCC; see the file COPYING3. If not see +# . + +# This file was contributed by John David Anglin (dave.anglin@nrc-cnrc.gc.ca) + +set orig_environment_saved 0 +set orig_ld_library_path_saved 0 +set orig_ld_run_path_saved 0 +set orig_shlib_path_saved 0 +set orig_ld_libraryn32_path_saved 0 +set orig_ld_library64_path_saved 0 +set orig_ld_library_path_32_saved 0 +set orig_ld_library_path_64_saved 0 +set orig_dyld_library_path_saved 0 +set orig_path_saved 0 + +####################################### +# proc set_ld_library_path_env_vars { } +####################################### + +proc set_ld_library_path_env_vars { } { + global ld_library_path + global orig_environment_saved + global orig_ld_library_path_saved + global orig_ld_run_path_saved + global orig_shlib_path_saved + global orig_ld_libraryn32_path_saved + global orig_ld_library64_path_saved + global orig_ld_library_path_32_saved + global orig_ld_library_path_64_saved + global orig_dyld_library_path_saved + global orig_path_saved + global orig_ld_library_path + global orig_ld_run_path + global orig_shlib_path + global orig_ld_libraryn32_path + global orig_ld_library64_path + global orig_ld_library_path_32 + global orig_ld_library_path_64 + global orig_dyld_library_path + global orig_path + global GCC_EXEC_PREFIX + + # Set the relocated compiler prefix, but only if the user hasn't specified one. + if { [info exists GCC_EXEC_PREFIX] && ![info exists env(GCC_EXEC_PREFIX)] } { + setenv GCC_EXEC_PREFIX "$GCC_EXEC_PREFIX" + } + + # Setting the ld library path causes trouble when testing cross-compilers. + if { [is_remote target] } { + return + } + + if { $orig_environment_saved == 0 } { + global env + + set orig_environment_saved 1 + + # Save the original environment. + if [info exists env(LD_LIBRARY_PATH)] { + set orig_ld_library_path "$env(LD_LIBRARY_PATH)" + set orig_ld_library_path_saved 1 + } + if [info exists env(LD_RUN_PATH)] { + set orig_ld_run_path "$env(LD_RUN_PATH)" + set orig_ld_run_path_saved 1 + } + if [info exists env(SHLIB_PATH)] { + set orig_shlib_path "$env(SHLIB_PATH)" + set orig_shlib_path_saved 1 + } + if [info exists env(LD_LIBRARYN32_PATH)] { + set orig_ld_libraryn32_path "$env(LD_LIBRARYN32_PATH)" + set orig_ld_libraryn32_path_saved 1 + } + if [info exists env(LD_LIBRARY64_PATH)] { + set orig_ld_library64_path "$env(LD_LIBRARY64_PATH)" + set orig_ld_library64_path_saved 1 + } + if [info exists env(LD_LIBRARY_PATH_32)] { + set orig_ld_library_path_32 "$env(LD_LIBRARY_PATH_32)" + set orig_ld_library_path_32_saved 1 + } + if [info exists env(LD_LIBRARY_PATH_64)] { + set orig_ld_library_path_64 "$env(LD_LIBRARY_PATH_64)" + set orig_ld_library_path_64_saved 1 + } + if [info exists env(DYLD_LIBRARY_PATH)] { + set orig_dyld_library_path "$env(DYLD_LIBRARY_PATH)" + set orig_dyld_library_path_saved 1 + } + if [info exists env(PATH)] { + set orig_path "$env(PATH)" + set orig_path_saved 1 + } + } + + # We need to set ld library path in the environment. Currently, + # unix.exp doesn't set the environment correctly for all systems. + # It only sets SHLIB_PATH and LD_LIBRARY_PATH when it executes a + # program. We also need the environment set for compilations, etc. + # + # On IRIX 6, we have to set variables akin to LD_LIBRARY_PATH, but + # called LD_LIBRARYN32_PATH (for the N32 ABI) and LD_LIBRARY64_PATH + # (for the 64-bit ABI). The same applies to Darwin (DYLD_LIBRARY_PATH), + # Solaris 32 bit (LD_LIBRARY_PATH_32), Solaris 64 bit (LD_LIBRARY_PATH_64), + # and HP-UX (SHLIB_PATH). In some cases, the variables are independent + # of LD_LIBRARY_PATH, and in other cases LD_LIBRARY_PATH is used if the + # variable is not defined. + # + # Doing this is somewhat of a hack as ld_library_path gets repeated in + # SHLIB_PATH and LD_LIBRARY_PATH when unix_load sets these variables. + if { $orig_ld_library_path_saved } { + setenv LD_LIBRARY_PATH "$ld_library_path:$orig_ld_library_path" + } else { + setenv LD_LIBRARY_PATH "$ld_library_path" + } + if { $orig_ld_run_path_saved } { + setenv LD_RUN_PATH "$ld_library_path:$orig_ld_run_path" + } else { + setenv LD_RUN_PATH "$ld_library_path" + } + # The default shared library dynamic path search for 64-bit + # HP-UX executables searches LD_LIBRARY_PATH before SHLIB_PATH. + # LD_LIBRARY_PATH isn't used for 32-bit executables. Thus, we + # set LD_LIBRARY_PATH and SHLIB_PATH as if they were independent. + if { $orig_shlib_path_saved } { + setenv SHLIB_PATH "$ld_library_path:$orig_shlib_path" + } else { + setenv SHLIB_PATH "$ld_library_path" + } + if { $orig_ld_libraryn32_path_saved } { + setenv LD_LIBRARYN32_PATH "$ld_library_path:$orig_ld_libraryn32_path" + } elseif { $orig_ld_library_path_saved } { + setenv LD_LIBRARYN32_PATH "$ld_library_path:$orig_ld_library_path" + } else { + setenv LD_LIBRARYN32_PATH "$ld_library_path" + } + if { $orig_ld_library64_path_saved } { + setenv LD_LIBRARY64_PATH "$ld_library_path:$orig_ld_library64_path" + } elseif { $orig_ld_library_path_saved } { + setenv LD_LIBRARY64_PATH "$ld_library_path:$orig_ld_library_path" + } else { + setenv LD_LIBRARY64_PATH "$ld_library_path" + } + if { $orig_ld_library_path_32_saved } { + setenv LD_LIBRARY_PATH_32 "$ld_library_path:$orig_ld_library_path_32" + } elseif { $orig_ld_library_path_saved } { + setenv LD_LIBRARY_PATH_32 "$ld_library_path:$orig_ld_library_path" + } else { + setenv LD_LIBRARY_PATH_32 "$ld_library_path" + } + if { $orig_ld_library_path_64_saved } { + setenv LD_LIBRARY_PATH_64 "$ld_library_path:$orig_ld_library_path_64" + } elseif { $orig_ld_library_path_saved } { + setenv LD_LIBRARY_PATH_64 "$ld_library_path:$orig_ld_library_path" + } else { + setenv LD_LIBRARY_PATH_64 "$ld_library_path" + } + if { $orig_dyld_library_path_saved } { + setenv DYLD_LIBRARY_PATH "$ld_library_path:$orig_dyld_library_path" + } else { + setenv DYLD_LIBRARY_PATH "$ld_library_path" + } + if { [istarget *-*-cygwin*] || [istarget *-*-mingw*] } { + if { $orig_path_saved } { + setenv PATH "$ld_library_path:$orig_path" + } else { + setenv PATH "$ld_library_path" + } + } + + verbose -log "set_ld_library_path_env_vars: ld_library_path=$ld_library_path" +} + +####################################### +# proc restore_ld_library_path_env_vars { } +####################################### + +proc restore_ld_library_path_env_vars { } { + global orig_environment_saved + global orig_ld_library_path_saved + global orig_ld_run_path_saved + global orig_shlib_path_saved + global orig_ld_libraryn32_path_saved + global orig_ld_library64_path_saved + global orig_ld_library_path_32_saved + global orig_ld_library_path_64_saved + global orig_dyld_library_path_saved + global orig_path_saved + global orig_ld_library_path + global orig_ld_run_path + global orig_shlib_path + global orig_ld_libraryn32_path + global orig_ld_library64_path + global orig_ld_library_path_32 + global orig_ld_library_path_64 + global orig_dyld_library_path + global orig_path + + if { $orig_environment_saved == 0 } { + return + } + + if { $orig_ld_library_path_saved } { + setenv LD_LIBRARY_PATH "$orig_ld_library_path" + } elseif [info exists env(LD_LIBRARY_PATH)] { + unsetenv LD_LIBRARY_PATH + } + if { $orig_ld_run_path_saved } { + setenv LD_RUN_PATH "$orig_ld_run_path" + } elseif [info exists env(LD_RUN_PATH)] { + unsetenv LD_RUN_PATH + } + if { $orig_shlib_path_saved } { + setenv SHLIB_PATH "$orig_shlib_path" + } elseif [info exists env(SHLIB_PATH)] { + unsetenv SHLIB_PATH + } + if { $orig_ld_libraryn32_path_saved } { + setenv LD_LIBRARYN32_PATH "$orig_ld_libraryn32_path" + } elseif [info exists env(LD_LIBRARYN32_PATH)] { + unsetenv LD_LIBRARYN32_PATH + } + if { $orig_ld_library64_path_saved } { + setenv LD_LIBRARY64_PATH "$orig_ld_library64_path" + } elseif [info exists env(LD_LIBRARY64_PATH)] { + unsetenv LD_LIBRARY64_PATH + } + if { $orig_ld_library_path_32_saved } { + setenv LD_LIBRARY_PATH_32 "$orig_ld_library_path_32" + } elseif [info exists env(LD_LIBRARY_PATH_32)] { + unsetenv LD_LIBRARY_PATH_32 + } + if { $orig_ld_library_path_64_saved } { + setenv LD_LIBRARY_PATH_64 "$orig_ld_library_path_64" + } elseif [info exists env(LD_LIBRARY_PATH_64)] { + unsetenv LD_LIBRARY_PATH_64 + } + if { $orig_dyld_library_path_saved } { + setenv DYLD_LIBRARY_PATH "$orig_dyld_library_path" + } elseif [info exists env(DYLD_LIBRARY_PATH)] { + unsetenv DYLD_LIBRARY_PATH + } + if { $orig_path_saved } { + setenv PATH "$orig_path" + } elseif [info exists env(PATH)] { + unsetenv PATH + } +} + +####################################### +# proc get_shlib_extension { } +####################################### + +proc get_shlib_extension { } { + global shlib_ext + + if { [ istarget *-*-darwin* ] } { + set shlib_ext "dylib" + } elseif { [ istarget *-*-cygwin* ] || [ istarget *-*-mingw* ] } { + set shlib_ext "dll" + } elseif { [ istarget hppa*-*-hpux* ] } { + set shlib_ext "sl" + } else { + set shlib_ext "so" + } + return $shlib_ext +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/lib/wrapper.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/lib/wrapper.exp new file mode 100644 index 0000000..4e5ae43 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/lib/wrapper.exp @@ -0,0 +1,45 @@ +# Copyright (C) 2004, 2007 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GCC; see the file COPYING3. If not see +# . + +# This file contains GCC-specifics for status wrappers for test programs. + +# ${tool}_maybe_build_wrapper -- Build wrapper object if the target +# needs it. FILENAME is the path to the wrapper file. If there are +# additional arguments, they are command-line options to provide to +# the compiler when compiling FILENAME. + +proc ${tool}_maybe_build_wrapper { filename args } { + global gluefile wrap_flags + + if { [target_info needs_status_wrapper] != "" \ + && [target_info needs_status_wrapper] != "0" \ + && ![info exists gluefile] } { + set saved_wrap_compile_flags [target_info wrap_compile_flags] + set flags [join $args " "] + # The wrapper code may contain code that gcc objects on. This + # became true for dejagnu-1.4.4. The set of warnings and code + # that gcc objects on may change, so just make sure -w is always + # passed to turn off all warnings. + set_currtarget_info wrap_compile_flags \ + "$saved_wrap_compile_flags -w $flags" + set result [build_wrapper $filename] + set_currtarget_info wrap_compile_flags "$saved_wrap_compile_flags" + if { $result != "" } { + set gluefile [lindex $result 0] + set wrap_flags [lindex $result 1] + } + } +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/Makefile b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/Makefile new file mode 100644 index 0000000..3322de9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/Makefile @@ -0,0 +1,28 @@ +CC = gcc +CFLAGS = -O2 -Wall +prefix = +includedir = $(prefix)/include +libdir = $(prefix)/lib +CPPFLAGS = -I$(includedir) +LDFLAGS = -L$(libdir) -Wl,-rpath,$(libdir) + +all: check-call check-callback + +test-call: test-call.c testcases.c + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o test-call test-call.c -lffi + +test-callback: test-callback.c testcases.c + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o test-callback test-callback.c -lffi + +check-call: test-call + ./test-call > test-call.out + LC_ALL=C uniq -u < test-call.out > failed-call + test '!' -s failed-call + +check-callback: test-callback + ./test-callback > test-callback.out + LC_ALL=C uniq -u < test-callback.out > failed-callback + test '!' -s failed-callback + +clean: + rm -f test-call test-callback test-call.out test-callback.out failed-call failed-callback diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/README b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/README new file mode 100644 index 0000000..be8540b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/README @@ -0,0 +1,78 @@ +This package contains a test suite for libffi. + +This test suite can be compiled with a C compiler. No need for 'expect' +or some other package that is often not installed. + +The test suite consists of 81 C functions, each with a different signature. +* test-call verifies that calling each function directly produces the same + results as calling the function indirectly through 'ffi_call'. +* test-callback verifies that calling each function directly produces the same + results as calling a function that is a callback (object build by + 'ffi_prep_closure_loc') and simulates the original function. + +Each direct or indirect invocation should produce one line of output to +stdout. A correct output consists of paired lines, such as + +void f(void): +void f(void): +int f(void):->99 +int f(void):->99 +int f(int):(1)->2 +int f(int):(1)->2 +int f(2*int):(1,2)->3 +int f(2*int):(1,2)->3 +... + +The Makefile then creates two files: +* failed-call, which consists of the non-paired lines of output of + 'test-call', +* failed-callback, which consists of the non-paired lines of output of + 'test-callback'. + +The test suite passes if both failed-call and failed-callback come out +as empty. + + +How to use the test suite +------------------------- + +1. Modify the Makefile's variables + prefix = the directory in which libffi was installed + CC = the C compiler, often with options such as "-m32" or "-m64" + that enforce a certain ABI, + CFLAGS = optimization options (need to change them only for non-GCC + compilers) +2. Run "make". If it fails already in "test-call", run also + "make check-callback". +3. If this failed, inspect the output files. + + +How to interpret the results +---------------------------- + +The failed-call and failed-callback files consist of paired lines: +The first line is the result of the direct invocation. +The second line is the result of invocation through libffi. + +For example, this output + +uchar f(uchar,ushort,uint,ulong):(97,2,3,4)->255 +uchar f(uchar,ushort,uint,ulong):(97,2,3,4)->0 + +indicates that the arguments were passed correctly, but the return +value came out wrong. + +And this output + +float f(17*float,3*int,L):(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,6,7,8,561,1105,1729,2465,2821,6601)->15319.1 +float f(17*float,3*int,L):(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,-140443648,10,268042216,-72537980,-140443648,-140443648,-140443648,-140443648,-140443648)->-6.47158e+08 + +indicates that integer arguments that come after 17 floating-point arguments +were not passed correctly. + + +Credits +------- + +The test suite is based on the one of GNU libffcall-2.0. +Authors: Bill Triggs, Bruno Haible diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/alignof.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/alignof.h new file mode 100644 index 0000000..00604a5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/alignof.h @@ -0,0 +1,50 @@ +/* Determine alignment of types. + Copyright (C) 2003-2004, 2006, 2009-2017 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see . */ + +#ifndef _ALIGNOF_H +#define _ALIGNOF_H + +#include + +/* alignof_slot (TYPE) + Determine the alignment of a structure slot (field) of a given type, + at compile time. Note that the result depends on the ABI. + This is the same as alignof (TYPE) and _Alignof (TYPE), defined in + if __alignof_is_defined is 1. + Note: The result cannot be used as a value for an 'enum' constant, + due to bugs in HP-UX 10.20 cc and AIX 3.2.5 xlc. */ +#if defined __cplusplus + template struct alignof_helper { char __slot1; type __slot2; }; +# define alignof_slot(type) offsetof (alignof_helper, __slot2) +#else +# define alignof_slot(type) offsetof (struct { char __slot1; type __slot2; }, __slot2) +#endif + +/* alignof_type (TYPE) + Determine the good alignment of an object of the given type at compile time. + Note that this is not necessarily the same as alignof_slot(type). + For example, with GNU C on x86 platforms: alignof_type(double) = 8, but + - when -malign-double is not specified: alignof_slot(double) = 4, + - when -malign-double is specified: alignof_slot(double) = 8. + Note: The result cannot be used as a value for an 'enum' constant, + due to bugs in HP-UX 10.20 cc and AIX 3.2.5 xlc. */ +#if defined __GNUC__ || defined __IBM__ALIGNOF__ +# define alignof_type __alignof__ +#else +# define alignof_type alignof_slot +#endif + +#endif /* _ALIGNOF_H */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/bhaible.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/bhaible.exp new file mode 100644 index 0000000..44aebc5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/bhaible.exp @@ -0,0 +1,63 @@ +# Copyright (C) 2003, 2006, 2009, 2010, 2014, 2018 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; see the file COPYING3. If not see +# . + +dg-init +libffi-init + +global srcdir subdir +global compiler_vendor + +# The conversion of this testsuite into a dejagnu compatible testsuite +# was done in a pretty lazy fashion, and requires the use of compiler +# flags to disable warnings for now. +if { [string match $compiler_vendor "gnu"] } { + set warning_options "-Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-uninitialized"; +} +if { [string match $compiler_vendor "microsoft"] } { + # -wd4996 suggest use of vsprintf_s instead of vsprintf + # -wd4116 unnamed type definition + # -wd4101 unreferenced local variable + # -wd4244 warning about implicit double to float conversion + set warning_options "-wd4996 -wd4116 -wd4101 -wd4244"; +} +if { ![string match $compiler_vendor "microsoft"] && ![string match $compiler_vendor "gnu"] } { + set warning_options "-Wno-unused-variable -Wno-unused-parameter -Wno-uninitialized"; +} + + +set tlist [lsort [glob -nocomplain -- $srcdir/$subdir/test-call.c]] + +for {set i 1} {$i < 82} {incr i} { + run-many-tests $tlist [format "-DDGTEST=%d %s" $i $warning_options] +} + +set tlist [lsort [glob -nocomplain -- $srcdir/$subdir/test-callback.c]] + +for {set i 1} {$i < 81} {incr i} { + if { [libffi_feature_test "#if FFI_CLOSURES"] } { + run-many-tests $tlist [format "-DDGTEST=%d %s" $i $warning_options] + } else { + foreach test $tlist { + unsupported [format "%s -DDGTEST=%d %s" $test $i $warning_options] + } + } +} + +dg-finish + +# Local Variables: +# tcl-indent-level:4 +# End: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/test-call.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/test-call.c new file mode 100644 index 0000000..cf9219e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/test-call.c @@ -0,0 +1,1745 @@ +/** + Copyright 1993 Bill Triggs + Copyright 1995-2017 Bruno Haible + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +**/ + +/* { dg-do run { xfail gccbug } } */ + +#include +#include +#include +#include +#include "alignof.h" +#include + +/* libffi testsuite local changes -------------------------------- */ +#ifdef DGTEST +/* Redefine exit(1) as a test failure */ +#define exit(V) (void)((V) ? (abort(), 1) : exit(0)) +int count = 0; +char rbuf1[2048]; +char rbuf2[2048]; +int _fprintf(FILE *stream, const char *format, ...) +{ + va_list args; + va_start(args, format); + + switch (count++) + { + case 0: + case 1: + vsprintf(&rbuf1[strlen(rbuf1)], format, args); + break; + case 2: + printf("%s", rbuf1); + vsprintf(rbuf2, format, args); + break; + case 3: + vsprintf(&rbuf2[strlen(rbuf2)], format, args); + printf("%s", rbuf2); + if (strcmp (rbuf1, rbuf2)) abort(); + break; + } + + va_end(args); + + return 0; +} +#define fprintf _fprintf +#endif +/* --------------------------------------------------------------- */ + +#include "testcases.c" + +#ifndef ABI_NUM +#define ABI_NUM FFI_DEFAULT_ABI +#endif + +/* Definitions that ought to be part of libffi. */ +static ffi_type ffi_type_char; +#define ffi_type_slonglong ffi_type_sint64 +#define ffi_type_ulonglong ffi_type_uint64 + +/* libffi does not support arrays inside structs. */ +#define SKIP_EXTRA_STRUCTS + +#define FFI_PREP_CIF(cif,argtypes,rettype) \ + if (ffi_prep_cif(&(cif),ABI_NUM,sizeof(argtypes)/sizeof(argtypes[0]),&rettype,argtypes) != FFI_OK) abort() +#define FFI_PREP_CIF_NOARGS(cif,rettype) \ + if (ffi_prep_cif(&(cif),ABI_NUM,0,&rettype,NULL) != FFI_OK) abort() +#define FFI_CALL(cif,fn,args,retaddr) \ + ffi_call(&(cif),(void(*)(void))(fn),retaddr,args) + +long clear_traces_i (long a, long b, long c, long d, long e, long f, long g, long h, + long i, long j, long k, long l, long m, long n, long o, long p) +{ return 0; } +float clear_traces_f (float a, float b, float c, float d, float e, float f, float g, + float h, float i, float j, float k, float l, float m, float n, + float o, float p) +{ return 0.0; } +double clear_traces_d (double a, double b, double c, double d, double e, double f, double g, + double h, double i, double j, double k, double l, double m, double n, + double o, double p) +{ return 0.0; } +J clear_traces_J (void) +{ J j; j.l1 = j.l2 = 0; return j; } +void clear_traces (void) +{ clear_traces_i(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0); + clear_traces_f(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0); + clear_traces_d(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0); + clear_traces_J(); +} + +void + void_tests (void) +{ +#if (!defined(DGTEST)) || DGTEST == 1 + v_v(); + clear_traces(); + { + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_void); + { + FFI_CALL(cif,v_v,NULL,NULL); + } + } +#endif + return; +} +void + int_tests (void) +{ + int ir; + ffi_arg retvalue; +#if (!defined(DGTEST)) || DGTEST == 2 + ir = i_v(); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + { + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_sint); + { + FFI_CALL(cif,i_v,NULL,&retvalue); + ir = retvalue; + } + } + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 3 + ir = i_i(i1); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_sint); + { + /*const*/ void* args[] = { &i1 }; + FFI_CALL(cif,i_i,args,&retvalue); + ir = retvalue; + } + } + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 4 + ir = i_i2(i1,i2); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_sint); + { + /*const*/ void* args[] = { &i1, &i2 }; + FFI_CALL(cif,i_i2,args,&retvalue); + ir = retvalue; + } + } + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 5 + ir = i_i4(i1,i2,i3,i4); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_sint); + { + /*const*/ void* args[] = { &i1, &i2, &i3, &i4 }; + FFI_CALL(cif,i_i4,args,&retvalue); + ir = retvalue; + } + } + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 6 + ir = i_i8(i1,i2,i3,i4,i5,i6,i7,i8); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_sint); + { + /*const*/ void* args[] = { &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8 }; + FFI_CALL(cif,i_i8,args,&retvalue); + ir = retvalue; + } + } + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 7 + ir = i_i16(i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_sint); + { + /*const*/ void* args[] = { &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8, &i9, &i10, &i11, &i12, &i13, &i14, &i15, &i16 }; + FFI_CALL(cif,i_i16,args,&retvalue); + ir = retvalue; + } + } + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + + return; +} +void + float_tests (void) +{ + float fr; + +#if (!defined(DGTEST)) || DGTEST == 8 + fr = f_f(f1); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1 }; + FFI_CALL(cif,f_f,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 9 + fr = f_f2(f1,f2); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2 }; + FFI_CALL(cif,f_f2,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 10 + fr = f_f4(f1,f2,f3,f4); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &f3, &f4 }; + FFI_CALL(cif,f_f4,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 11 + fr = f_f8(f1,f2,f3,f4,f5,f6,f7,f8); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8 }; + FFI_CALL(cif,f_f8,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 12 + fr = f_f16(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &f14, &f15, &f16 }; + FFI_CALL(cif,f_f16,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 13 + fr = f_f24(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &f14, &f15, &f16, &f17, &f18, &f19, &f20, &f21, &f22, &f23, &f24 }; + FFI_CALL(cif,f_f24,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif +} +void + double_tests (void) +{ + double dr; + +#if (!defined(DGTEST)) || DGTEST == 14 + + dr = d_d(d1); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1 }; + FFI_CALL(cif,d_d,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 15 + dr = d_d2(d1,d2); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2 }; + FFI_CALL(cif,d_d2,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 16 + dr = d_d4(d1,d2,d3,d4); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2, &d3, &d4 }; + FFI_CALL(cif,d_d4,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 17 + dr = d_d8(d1,d2,d3,d4,d5,d6,d7,d8); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8 }; + FFI_CALL(cif,d_d8,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 18 + dr = d_d16(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &d13, &d14, &d15, &d16 }; + FFI_CALL(cif,d_d16,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + return; +} +void + pointer_tests (void) +{ + void* vpr; + +#if (!defined(DGTEST)) || DGTEST == 19 + vpr = vp_vpdpcpsp(&uc1,&d2,str3,&I4); + fprintf(out,"->0x%p\n",vpr); + fflush(out); + vpr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_pointer); + { + void* puc1 = &uc1; + void* pd2 = &d2; + void* pstr3 = str3; + void* pI4 = &I4; + /*const*/ void* args[] = { &puc1, &pd2, &pstr3, &pI4 }; + FFI_CALL(cif,vp_vpdpcpsp,args,&vpr); + } + } + fprintf(out,"->0x%p\n",vpr); + fflush(out); +#endif + return; +} +void + mixed_number_tests (void) +{ + uchar ucr; + ushort usr; + float fr; + double dr; + long long llr; + + /* Unsigned types. + */ +#if (!defined(DGTEST)) || DGTEST == 20 + ucr = uc_ucsil(uc1, us2, ui3, ul4); + fprintf(out,"->%u\n",ucr); + fflush(out); + ucr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_uchar, &ffi_type_ushort, &ffi_type_uint, &ffi_type_ulong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_uchar); + { + ffi_arg r; + /*const*/ void* args[] = { &uc1, &us2, &ui3, &ul4 }; + FFI_CALL(cif,uc_ucsil,args,&r); + ucr = (uchar) r; + } + } + fprintf(out,"->%u\n",ucr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 21 + /* Mixed int & float types. + */ + dr = d_iidd(i1,i2,d3,d4); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &i1, &i2, &d3, &d4 }; + FFI_CALL(cif,d_iidd,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 22 + dr = d_iiidi(i1,i2,i3,d4,i5); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &i1, &i2, &i3, &d4, &i5 }; + FFI_CALL(cif,d_iiidi,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 23 + dr = d_idid(i1,d2,i3,d4); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_double, &ffi_type_sint, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &i1, &d2, &i3, &d4 }; + FFI_CALL(cif,d_idid,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 24 + dr = d_fdi(f1,d2,i3); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &f1, &d2, &i3 }; + FFI_CALL(cif,d_fdi,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 25 + usr = us_cdcd(c1,d2,c3,d4); + fprintf(out,"->%u\n",usr); + fflush(out); + usr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_char, &ffi_type_double, &ffi_type_char, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_ushort); + { + ffi_arg rint; + /*const*/ void* args[] = { &c1, &d2, &c3, &d4 }; + FFI_CALL(cif,us_cdcd,args,&rint); + usr = (ushort) rint; + } + } + fprintf(out,"->%u\n",usr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 26 + /* Long long types. + */ + llr = ll_iiilli(i1,i2,i3,ll1,i13); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_slonglong, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + { + /*const*/ void* args[] = { &i1, &i2, &i3, &ll1, &i13 }; + FFI_CALL(cif,ll_iiilli,args,&llr); + } + } + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 27 + llr = ll_flli(f13,ll1,i13); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_slonglong, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + { + /*const*/ void* args[] = { &f13, &ll1, &i13 }; + FFI_CALL(cif,ll_flli,args,&llr); + } + } + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 28 + fr = f_fi(f1,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &i9 }; + FFI_CALL(cif,f_fi,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 29 + fr = f_f2i(f1,f2,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &i9 }; + FFI_CALL(cif,f_f2i,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 30 + fr = f_f3i(f1,f2,f3,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &f3, &i9 }; + FFI_CALL(cif,f_f3i,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 31 + fr = f_f4i(f1,f2,f3,f4,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &i9 }; + FFI_CALL(cif,f_f4i,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 32 + fr = f_f7i(f1,f2,f3,f4,f5,f6,f7,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &i9 }; + FFI_CALL(cif,f_f7i,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 33 + fr = f_f8i(f1,f2,f3,f4,f5,f6,f7,f8,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &i9 }; + FFI_CALL(cif,f_f8i,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 34 + fr = f_f12i(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &i9 }; + FFI_CALL(cif,f_f12i,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 35 + fr = f_f13i(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &i9 }; + FFI_CALL(cif,f_f13i,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 36 + dr = d_di(d1,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &i9 }; + FFI_CALL(cif,d_di,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 37 + dr = d_d2i(d1,d2,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2, &i9 }; + FFI_CALL(cif,d_d2i,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 38 + dr = d_d3i(d1,d2,d3,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2, &d3, &i9 }; + FFI_CALL(cif,d_d3i,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 39 + dr = d_d4i(d1,d2,d3,d4,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &i9 }; + FFI_CALL(cif,d_d4i,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 40 + dr = d_d7i(d1,d2,d3,d4,d5,d6,d7,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &i9 }; + FFI_CALL(cif,d_d7i,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 41 + dr = d_d8i(d1,d2,d3,d4,d5,d6,d7,d8,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &i9 }; + FFI_CALL(cif,d_d8i,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 42 + dr = d_d12i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &i9 }; + FFI_CALL(cif,d_d12i,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 43 + dr = d_d13i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &d13, &i9 }; + FFI_CALL(cif,d_d13i,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + return; +} +void + small_structure_return_tests (void) +{ +#if (!defined(DGTEST)) || DGTEST == 44 + { + Size1 r = S1_v(); + fprintf(out,"->{%c}\n",r.x1); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + { + ffi_type* ffi_type_Size1_elements[] = { &ffi_type_char, NULL }; + ffi_type ffi_type_Size1; + ffi_type_Size1.type = FFI_TYPE_STRUCT; + ffi_type_Size1.size = sizeof(Size1); + ffi_type_Size1.alignment = alignof_slot(Size1); + ffi_type_Size1.elements = ffi_type_Size1_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size1); + { + FFI_CALL(cif,S1_v,NULL,&r); + } + } + fprintf(out,"->{%c}\n",r.x1); + fflush(out); + } +#endif +#if (!defined(DGTEST)) || DGTEST == 45 + { + Size2 r = S2_v(); + fprintf(out,"->{%c%c}\n",r.x1,r.x2); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + { + ffi_type* ffi_type_Size2_elements[] = { &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size2; + ffi_type_Size2.type = FFI_TYPE_STRUCT; + ffi_type_Size2.size = sizeof(Size2); + ffi_type_Size2.alignment = alignof_slot(Size2); + ffi_type_Size2.elements = ffi_type_Size2_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size2); + { + FFI_CALL(cif,S2_v,NULL,&r); + } + } + fprintf(out,"->{%c%c}\n",r.x1,r.x2); + fflush(out); + } +#endif +#if (!defined(DGTEST)) || DGTEST == 46 + { + Size3 r = S3_v(); + fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + { + ffi_type* ffi_type_Size3_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size3; + ffi_type_Size3.type = FFI_TYPE_STRUCT; + ffi_type_Size3.size = sizeof(Size3); + ffi_type_Size3.alignment = alignof_slot(Size3); + ffi_type_Size3.elements = ffi_type_Size3_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size3); + { + FFI_CALL(cif,S3_v,NULL,&r); + } + } + fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3); + fflush(out); + } +#endif +#if (!defined(DGTEST)) || DGTEST == 47 + { + Size4 r = S4_v(); + fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + { + ffi_type* ffi_type_Size4_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size4; + ffi_type_Size4.type = FFI_TYPE_STRUCT; + ffi_type_Size4.size = sizeof(Size4); + ffi_type_Size4.alignment = alignof_slot(Size4); + ffi_type_Size4.elements = ffi_type_Size4_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size4); + { + FFI_CALL(cif,S4_v,NULL,&r); + } + } + fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4); + fflush(out); + } +#endif +#if (!defined(DGTEST)) || DGTEST == 48 + { + Size7 r = S7_v(); + fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + { + ffi_type* ffi_type_Size7_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size7; + ffi_type_Size7.type = FFI_TYPE_STRUCT; + ffi_type_Size7.size = sizeof(Size7); + ffi_type_Size7.alignment = alignof_slot(Size7); + ffi_type_Size7.elements = ffi_type_Size7_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size7); + { + FFI_CALL(cif,S7_v,NULL,&r); + } + } + fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7); + fflush(out); + } +#endif +#if (!defined(DGTEST)) || DGTEST == 49 + { + Size8 r = S8_v(); + fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + { + ffi_type* ffi_type_Size8_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size8; + ffi_type_Size8.type = FFI_TYPE_STRUCT; + ffi_type_Size8.size = sizeof(Size8); + ffi_type_Size8.alignment = alignof_slot(Size8); + ffi_type_Size8.elements = ffi_type_Size8_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size8); + { + FFI_CALL(cif,S8_v,NULL,&r); + } + } + fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8); + fflush(out); + } +#endif +#if (!defined(DGTEST)) || DGTEST == 50 + { + Size12 r = S12_v(); + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + { + ffi_type* ffi_type_Size12_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size12; + ffi_type_Size12.type = FFI_TYPE_STRUCT; + ffi_type_Size12.size = sizeof(Size12); + ffi_type_Size12.alignment = alignof_slot(Size12); + ffi_type_Size12.elements = ffi_type_Size12_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size12); + { + FFI_CALL(cif,S12_v,NULL,&r); + } + } + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12); + fflush(out); + } +#endif +#if (!defined(DGTEST)) || DGTEST == 51 + { + Size15 r = S15_v(); + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + { + ffi_type* ffi_type_Size15_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size15; + ffi_type_Size15.type = FFI_TYPE_STRUCT; + ffi_type_Size15.size = sizeof(Size15); + ffi_type_Size15.alignment = alignof_slot(Size15); + ffi_type_Size15.elements = ffi_type_Size15_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size15); + { + FFI_CALL(cif,S15_v,NULL,&r); + } + } + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15); + fflush(out); + } +#endif +#if (!defined(DGTEST)) || DGTEST == 52 + { + Size16 r = S16_v(); + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + { + ffi_type* ffi_type_Size16_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size16; + ffi_type_Size16.type = FFI_TYPE_STRUCT; + ffi_type_Size16.size = sizeof(Size16); + ffi_type_Size16.alignment = alignof_slot(Size16); + ffi_type_Size16.elements = ffi_type_Size16_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size16); + { + FFI_CALL(cif,S16_v,NULL,&r); + } + } + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16); + fflush(out); + } +#endif +} +void + structure_tests (void) +{ + Int Ir; + Char Cr; + Float Fr; + Double Dr; + J Jr; +#ifndef SKIP_EXTRA_STRUCTS + T Tr; + X Xr; +#endif + +#if (!defined(DGTEST)) || DGTEST == 53 + Ir = I_III(I1,I2,I3); + fprintf(out,"->{%d}\n",Ir.x); + fflush(out); + Ir.x = 0; clear_traces(); + { + ffi_type* ffi_type_Int_elements[] = { &ffi_type_sint, NULL }; + ffi_type ffi_type_Int; + ffi_type_Int.type = FFI_TYPE_STRUCT; + ffi_type_Int.size = sizeof(Int); + ffi_type_Int.alignment = alignof_slot(Int); + ffi_type_Int.elements = ffi_type_Int_elements; + ffi_type* argtypes[] = { &ffi_type_Int, &ffi_type_Int, &ffi_type_Int }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_Int); + { + /*const*/ void* args[] = { &I1, &I2, &I3 }; + FFI_CALL(cif,I_III,args,&Ir); + } + } + fprintf(out,"->{%d}\n",Ir.x); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 54 + Cr = C_CdC(C1,d2,C3); + fprintf(out,"->{'%c'}\n",Cr.x); + fflush(out); + Cr.x = '\0'; clear_traces(); + { + ffi_type* ffi_type_Char_elements[] = { &ffi_type_char, NULL }; + ffi_type ffi_type_Char; + ffi_type_Char.type = FFI_TYPE_STRUCT; + ffi_type_Char.size = sizeof(Char); + ffi_type_Char.alignment = alignof_slot(Char); + ffi_type_Char.elements = ffi_type_Char_elements; + ffi_type* argtypes[] = { &ffi_type_Char, &ffi_type_double, &ffi_type_Char }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_Char); + { + /*const*/ void* args[] = { &C1, &d2, &C3 }; + FFI_CALL(cif,C_CdC,args,&Cr); + } + } + fprintf(out,"->{'%c'}\n",Cr.x); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 55 + Fr = F_Ffd(F1,f2,d3); + fprintf(out,"->{%g}\n",Fr.x); + fflush(out); + Fr.x = 0.0; clear_traces(); + { + ffi_type* ffi_type_Float_elements[] = { &ffi_type_float, NULL }; + ffi_type ffi_type_Float; + ffi_type_Float.type = FFI_TYPE_STRUCT; + ffi_type_Float.size = sizeof(Float); + ffi_type_Float.alignment = alignof_slot(Float); + ffi_type_Float.elements = ffi_type_Float_elements; + ffi_type* argtypes[] = { &ffi_type_Float, &ffi_type_float, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_Float); + { + /*const*/ void* args[] = { &F1, &f2, &d3 }; + FFI_CALL(cif,F_Ffd,args,&Fr); + } + } + fprintf(out,"->{%g}\n",Fr.x); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 56 + Dr = D_fDd(f1,D2,d3); + fprintf(out,"->{%g}\n",Dr.x); + fflush(out); + Dr.x = 0.0; clear_traces(); + { + ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL }; + ffi_type ffi_type_Double; + ffi_type_Double.type = FFI_TYPE_STRUCT; + ffi_type_Double.size = sizeof(Double); + ffi_type_Double.alignment = alignof_slot(Double); + ffi_type_Double.elements = ffi_type_Double_elements; + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_Double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_Double); + { + /*const*/ void* args[] = { &f1, &D2, &d3 }; + FFI_CALL(cif,D_fDd,args,&Dr); + } + } + fprintf(out,"->{%g}\n",Dr.x); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 57 + Dr = D_Dfd(D1,f2,d3); + fprintf(out,"->{%g}\n",Dr.x); + fflush(out); + Dr.x = 0.0; clear_traces(); + { + ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL }; + ffi_type ffi_type_Double; + ffi_type_Double.type = FFI_TYPE_STRUCT; + ffi_type_Double.size = sizeof(Double); + ffi_type_Double.alignment = alignof_slot(Double); + ffi_type_Double.elements = ffi_type_Double_elements; + ffi_type* argtypes[] = { &ffi_type_Double, &ffi_type_float, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_Double); + { + /*const*/ void* args[] = { &D1, &f2, &d3 }; + FFI_CALL(cif,D_Dfd,args,&Dr); + } + } + fprintf(out,"->{%g}\n",Dr.x); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 58 + Jr = J_JiJ(J1,i2,J2); + fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2); + fflush(out); + Jr.l1 = Jr.l2 = 0; clear_traces(); + { + ffi_type* ffi_type_J_elements[] = { &ffi_type_slong, &ffi_type_slong, NULL }; + ffi_type ffi_type_J; + ffi_type_J.type = FFI_TYPE_STRUCT; + ffi_type_J.size = sizeof(J); + ffi_type_J.alignment = alignof_slot(J); + ffi_type_J.elements = ffi_type_J_elements; + ffi_type* argtypes[] = { &ffi_type_J, &ffi_type_sint, &ffi_type_J }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_J); + { + /*const*/ void* args[] = { &J1, &i2, &J2 }; + FFI_CALL(cif,J_JiJ,args,&Jr); + } + } + fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2); + fflush(out); +#endif +#ifndef SKIP_EXTRA_STRUCTS +#if (!defined(DGTEST)) || DGTEST == 59 + Tr = T_TcT(T1,' ',T2); + fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]); + fflush(out); + Tr.c[0] = Tr.c[1] = Tr.c[2] = 0; clear_traces(); + { + ffi_type* ffi_type_T_elements[] = { ??, NULL }; + ffi_type ffi_type_T; + ffi_type_T.type = FFI_TYPE_STRUCT; + ffi_type_T.size = sizeof(T); + ffi_type_T.alignment = alignof_slot(T); + ffi_type_T.elements = ffi_type_T_elements; + ffi_type* argtypes[] = { &ffi_type_T, &ffi_type_char, &ffi_type_T }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_T); + { + char space = ' '; + /*const*/ void* args[] = { &T1, &space, &T2 }; + FFI_CALL(cif,T_TcT,args,&Tr); + } + } + fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 60 + Xr = X_BcdB(B1,c2,d3,B2); + fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1); + fflush(out); + Xr.c[0]=Xr.c1='\0'; clear_traces(); + { + ffi_type* ffi_type_X_elements[] = { ??, NULL }; + ffi_type ffi_type_X; + ffi_type_X.type = FFI_TYPE_STRUCT; + ffi_type_X.size = sizeof(X); + ffi_type_X.alignment = alignof_slot(X); + ffi_type_X.elements = ffi_type_X_elements; + ffi_type* argtypes[] = { &ffi_type_X, &ffi_type_char, &ffi_type_double, &ffi_type_X }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_X); + { + /*const*/ void* args[] = { &B1, &c2, &d3, &B2 }; + FFI_CALL(cif,X_BcdB,args,&Xr); + } + } + fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1); + fflush(out); +#endif +#endif + + return; +} + +void + gpargs_boundary_tests (void) +{ + ffi_type* ffi_type_K_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL }; + ffi_type ffi_type_K; + ffi_type* ffi_type_L_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL }; + ffi_type ffi_type_L; + long lr; + long long llr; + float fr; + double dr; + + ffi_type_K.type = FFI_TYPE_STRUCT; + ffi_type_K.size = sizeof(K); + ffi_type_K.alignment = alignof_slot(K); + ffi_type_K.elements = ffi_type_K_elements; + + ffi_type_L.type = FFI_TYPE_STRUCT; + ffi_type_L.size = sizeof(L); + ffi_type_L.alignment = alignof_slot(L); + ffi_type_L.elements = ffi_type_L_elements; + +#if (!defined(DGTEST)) || DGTEST == 61 + lr = l_l0K(K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + { + /*const*/ void* args[] = { &K1, &l9 }; + FFI_CALL(cif,l_l0K,args,&lr); + } + } + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 62 + lr = l_l1K(l1,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + { + /*const*/ void* args[] = { &l1, &K1, &l9 }; + FFI_CALL(cif,l_l1K,args,&lr); + } + } + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 63 + lr = l_l2K(l1,l2,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + { + /*const*/ void* args[] = { &l1, &l2, &K1, &l9 }; + FFI_CALL(cif,l_l2K,args,&lr); + } + } + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 64 + lr = l_l3K(l1,l2,l3,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &K1, &l9 }; + FFI_CALL(cif,l_l3K,args,&lr); + } + } + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 65 + lr = l_l4K(l1,l2,l3,l4,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &K1, &l9 }; + FFI_CALL(cif,l_l4K,args,&lr); + } + } + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 66 + lr = l_l5K(l1,l2,l3,l4,l5,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &K1, &l9 }; + FFI_CALL(cif,l_l5K,args,&lr); + } + } + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 67 + lr = l_l6K(l1,l2,l3,l4,l5,l6,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &K1, &l9 }; + FFI_CALL(cif,l_l6K,args,&lr); + } + } + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 68 + fr = f_f17l3L(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,l6,l7,l8,L1); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + { + /*const*/ void* args[] = { &f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8, &f9, &f10, &f11, &f12, &f13, &f14, &f15, &f16, &f17, &l6, &l7, &l8, &L1 }; + FFI_CALL(cif,f_f17l3L,args,&fr); + } + } + fprintf(out,"->%g\n",fr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 69 + dr = d_d17l3L(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17,l6,l7,l8,L1); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8, &d9, &d10, &d11, &d12, &d13, &d14, &d15, &d16, &d17, &l6, &l7, &l8, &L1 }; + FFI_CALL(cif,d_d17l3L,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 70 + llr = ll_l2ll(l1,l2,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + { + /*const*/ void* args[] = { &l1, &l2, &ll1, &l9 }; + FFI_CALL(cif,ll_l2ll,args,&llr); + } + } + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 71 + llr = ll_l3ll(l1,l2,l3,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &ll1, &l9 }; + FFI_CALL(cif,ll_l3ll,args,&llr); + } + } + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 72 + llr = ll_l4ll(l1,l2,l3,l4,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &ll1, &l9 }; + FFI_CALL(cif,ll_l4ll,args,&llr); + } + } + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 73 + llr = ll_l5ll(l1,l2,l3,l4,l5,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &ll1, &l9 }; + FFI_CALL(cif,ll_l5ll,args,&llr); + } + } + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 74 + llr = ll_l6ll(l1,l2,l3,l4,l5,l6,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &ll1, &l9 }; + FFI_CALL(cif,ll_l6ll,args,&llr); + } + } + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 75 + llr = ll_l7ll(l1,l2,l3,l4,l5,l6,l7,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &l7, &ll1, &l9 }; + FFI_CALL(cif,ll_l7ll,args,&llr); + } + } + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 76 + dr = d_l2d(l1,l2,d2,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &l1, &l2, &d2, &l9 }; + FFI_CALL(cif,d_l2d,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 77 + dr = d_l3d(l1,l2,l3,d2,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &d2, &l9 }; + FFI_CALL(cif,d_l3d,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 78 + dr = d_l4d(l1,l2,l3,l4,d2,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &d2, &l9 }; + FFI_CALL(cif,d_l4d,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 79 + dr = d_l5d(l1,l2,l3,l4,l5,d2,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &d2, &l9 }; + FFI_CALL(cif,d_l5d,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 80 + dr = d_l6d(l1,l2,l3,l4,l5,l6,d2,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &d2, &l9 }; + FFI_CALL(cif,d_l6d,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif +#if (!defined(DGTEST)) || DGTEST == 81 + dr = d_l7d(l1,l2,l3,l4,l5,l6,l7,d2,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + { + /*const*/ void* args[] = { &l1, &l2, &l3, &l4, &l5, &l6, &l7, &d2, &l9 }; + FFI_CALL(cif,d_l7d,args,&dr); + } + } + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + return; +} + +int + main (void) +{ + ffi_type_char = (char)(-1) < 0 ? ffi_type_schar : ffi_type_uchar; + out = stdout; + + void_tests(); + int_tests(); + float_tests(); + double_tests(); + pointer_tests(); + mixed_number_tests(); + small_structure_return_tests(); + structure_tests(); + gpargs_boundary_tests(); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/test-callback.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/test-callback.c new file mode 100644 index 0000000..0b16799 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/test-callback.c @@ -0,0 +1,2885 @@ +/* + * Copyright 1993 Bill Triggs + * Copyright 1995-2017 Bruno Haible + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/* { dg-do run { xfail gccbug } } */ + +#include +#include +#include +#include +#include "alignof.h" +#include + +/* libffi testsuite local changes -------------------------------- */ +#ifdef DGTEST +/* Redefine exit(1) as a test failure */ +#define exit(V) (void)((V) ? (abort(), 1) : exit(0)) +int count = 0; +char rbuf1[2048]; +char rbuf2[2048]; +int _fprintf(FILE *stream, const char *format, ...) +{ + va_list args; + va_start(args, format); + + switch (count++) + { + case 0: + case 1: + vsprintf(&rbuf1[strlen(rbuf1)], format, args); + break; + case 2: + printf("%s", rbuf1); + vsprintf(rbuf2, format, args); + break; + case 3: + vsprintf(&rbuf2[strlen(rbuf2)], format, args); + printf("%s", rbuf2); + if (strcmp (rbuf1, rbuf2)) abort(); + break; + } + + va_end(args); + + return 0; +} +#define fprintf _fprintf +#endif +/* --------------------------------------------------------------- */ + +#include "testcases.c" + +#ifndef ABI_NUM +#define ABI_NUM FFI_DEFAULT_ABI +#endif + +/* Definitions that ought to be part of libffi. */ +static ffi_type ffi_type_char; +#define ffi_type_slonglong ffi_type_sint64 +#define ffi_type_ulonglong ffi_type_uint64 + +/* libffi does not support arrays inside structs. */ +#define SKIP_EXTRA_STRUCTS + +#define FFI_PREP_CIF(cif,argtypes,rettype) \ + if (ffi_prep_cif(&(cif),ABI_NUM,sizeof(argtypes)/sizeof(argtypes[0]),&rettype,argtypes) != FFI_OK) abort() +#define FFI_PREP_CIF_NOARGS(cif,rettype) \ + if (ffi_prep_cif(&(cif),ABI_NUM,0,&rettype,NULL) != FFI_OK) abort() + +#if defined(__sparc__) && defined(__sun) && defined(__SUNPRO_C) /* SUNWspro cc */ +/* SunPRO cc miscompiles the simulator function for X_BcdB: d.i[1] is + * temporarily stored in %l2 and put onto the stack from %l2, but in between + * the copy of X has used %l2 as a counter without saving and restoring its + * value. + */ +#define SKIP_X +#endif +#if defined(__mipsn32__) && !defined(__GNUC__) +/* The X test crashes for an unknown reason. */ +#define SKIP_X +#endif + + +/* These functions simulate the behaviour of the functions defined in testcases.c. */ + +/* void tests */ +void v_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&v_v) { fprintf(out,"wrong data for v_v\n"); exit(1); } + fprintf(out,"void f(void):\n"); + fflush(out); +} + +/* int tests */ +void i_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&i_v) { fprintf(out,"wrong data for i_v\n"); exit(1); } + {int r=99; + fprintf(out,"int f(void):"); + fflush(out); + *(ffi_arg*)retp = r; +}} +void i_i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&i_i) { fprintf(out,"wrong data for i_i\n"); exit(1); } + int a = *(int*)(*args++); + int r=a+1; + fprintf(out,"int f(int):(%d)",a); + fflush(out); + *(ffi_arg*)retp = r; +} +void i_i2_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&i_i2) { fprintf(out,"wrong data for i_i2\n"); exit(1); } + {int a = *(int*)(*args++); + int b = *(int*)(*args++); + int r=a+b; + fprintf(out,"int f(2*int):(%d,%d)",a,b); + fflush(out); + *(ffi_arg*)retp = r; +}} +void i_i4_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&i_i4) { fprintf(out,"wrong data for i_i4\n"); exit(1); } + {int a = *(int*)(*args++); + int b = *(int*)(*args++); + int c = *(int*)(*args++); + int d = *(int*)(*args++); + int r=a+b+c+d; + fprintf(out,"int f(4*int):(%d,%d,%d,%d)",a,b,c,d); + fflush(out); + *(ffi_arg*)retp = r; +}} +void i_i8_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&i_i8) { fprintf(out,"wrong data for i_i8\n"); exit(1); } + {int a = *(int*)(*args++); + int b = *(int*)(*args++); + int c = *(int*)(*args++); + int d = *(int*)(*args++); + int e = *(int*)(*args++); + int f = *(int*)(*args++); + int g = *(int*)(*args++); + int h = *(int*)(*args++); + int r=a+b+c+d+e+f+g+h; + fprintf(out,"int f(8*int):(%d,%d,%d,%d,%d,%d,%d,%d)",a,b,c,d,e,f,g,h); + fflush(out); + *(ffi_arg*)retp = r; +}} +void i_i16_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&i_i16) { fprintf(out,"wrong data for i_i16\n"); exit(1); } + {int a = *(int*)(*args++); + int b = *(int*)(*args++); + int c = *(int*)(*args++); + int d = *(int*)(*args++); + int e = *(int*)(*args++); + int f = *(int*)(*args++); + int g = *(int*)(*args++); + int h = *(int*)(*args++); + int i = *(int*)(*args++); + int j = *(int*)(*args++); + int k = *(int*)(*args++); + int l = *(int*)(*args++); + int m = *(int*)(*args++); + int n = *(int*)(*args++); + int o = *(int*)(*args++); + int p = *(int*)(*args++); + int r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p; + fprintf(out,"int f(16*int):(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)", + a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p); + fflush(out); + *(ffi_arg*)retp = r; +}} + +/* float tests */ +void f_f_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f) { fprintf(out,"wrong data for f_f\n"); exit(1); } + {float a = *(float*)(*args++); + float r=a+1.0; + fprintf(out,"float f(float):(%g)",a); + fflush(out); + *(float*)retp = r; +}} +void f_f2_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f2) { fprintf(out,"wrong data for f_f2\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float r=a+b; + fprintf(out,"float f(2*float):(%g,%g)",a,b); + fflush(out); + *(float*)retp = r; +}} +void f_f4_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f4) { fprintf(out,"wrong data for f_f4\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float c = *(float*)(*args++); + float d = *(float*)(*args++); + float r=a+b+c+d; + fprintf(out,"float f(4*float):(%g,%g,%g,%g)",a,b,c,d); + fflush(out); + *(float*)retp = r; +}} +void f_f8_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f8) { fprintf(out,"wrong data for f_f8\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float c = *(float*)(*args++); + float d = *(float*)(*args++); + float e = *(float*)(*args++); + float f = *(float*)(*args++); + float g = *(float*)(*args++); + float h = *(float*)(*args++); + float r=a+b+c+d+e+f+g+h; + fprintf(out,"float f(8*float):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h); + fflush(out); + *(float*)retp = r; +}} +void f_f16_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f16) { fprintf(out,"wrong data for f_f16\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float c = *(float*)(*args++); + float d = *(float*)(*args++); + float e = *(float*)(*args++); + float f = *(float*)(*args++); + float g = *(float*)(*args++); + float h = *(float*)(*args++); + float i = *(float*)(*args++); + float j = *(float*)(*args++); + float k = *(float*)(*args++); + float l = *(float*)(*args++); + float m = *(float*)(*args++); + float n = *(float*)(*args++); + float o = *(float*)(*args++); + float p = *(float*)(*args++); + float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p; + fprintf(out,"float f(16*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p); + fflush(out); + *(float*)retp = r; +}} +void f_f24_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f24) { fprintf(out,"wrong data for f_f24\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float c = *(float*)(*args++); + float d = *(float*)(*args++); + float e = *(float*)(*args++); + float f = *(float*)(*args++); + float g = *(float*)(*args++); + float h = *(float*)(*args++); + float i = *(float*)(*args++); + float j = *(float*)(*args++); + float k = *(float*)(*args++); + float l = *(float*)(*args++); + float m = *(float*)(*args++); + float n = *(float*)(*args++); + float o = *(float*)(*args++); + float p = *(float*)(*args++); + float q = *(float*)(*args++); + float s = *(float*)(*args++); + float t = *(float*)(*args++); + float u = *(float*)(*args++); + float v = *(float*)(*args++); + float w = *(float*)(*args++); + float x = *(float*)(*args++); + float y = *(float*)(*args++); + float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+v+w+x+y; + fprintf(out,"float f(24*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,v,w,x,y); + fflush(out); + *(float*)retp = r; +}} + +/* double tests */ +void d_d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d) { fprintf(out,"wrong data for d_d\n"); exit(1); } + {double a = *(double*)(*args++); + double r=a+1.0; + fprintf(out,"double f(double):(%g)",a); + fflush(out); + *(double*)retp = r; +}} +void d_d2_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d2) { fprintf(out,"wrong data for d_d2\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + double r=a+b; + fprintf(out,"double f(2*double):(%g,%g)",a,b); + fflush(out); + *(double*)retp = r; +}} +void d_d4_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d4) { fprintf(out,"wrong data for d_d4\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + double c = *(double*)(*args++); + double d = *(double*)(*args++); + double r=a+b+c+d; + fprintf(out,"double f(4*double):(%g,%g,%g,%g)",a,b,c,d); + fflush(out); + *(double*)retp = r; +}} +void d_d8_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d8) { fprintf(out,"wrong data for d_d8\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + double c = *(double*)(*args++); + double d = *(double*)(*args++); + double e = *(double*)(*args++); + double f = *(double*)(*args++); + double g = *(double*)(*args++); + double h = *(double*)(*args++); + double r=a+b+c+d+e+f+g+h; + fprintf(out,"double f(8*double):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h); + fflush(out); + *(double*)retp = r; +}} +void d_d16_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d16) { fprintf(out,"wrong data for d_d16\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + double c = *(double*)(*args++); + double d = *(double*)(*args++); + double e = *(double*)(*args++); + double f = *(double*)(*args++); + double g = *(double*)(*args++); + double h = *(double*)(*args++); + double i = *(double*)(*args++); + double j = *(double*)(*args++); + double k = *(double*)(*args++); + double l = *(double*)(*args++); + double m = *(double*)(*args++); + double n = *(double*)(*args++); + double o = *(double*)(*args++); + double p = *(double*)(*args++); + double r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p; + fprintf(out,"double f(16*double):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p); + fflush(out); + *(double*)retp = r; +}} + +/* pointer tests */ +void vp_vpdpcpsp_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&vp_vpdpcpsp) { fprintf(out,"wrong data for vp_vpdpcpsp\n"); exit(1); } + {void* a = *(void* *)(*args++); + double* b = *(double* *)(*args++); + char* c = *(char* *)(*args++); + Int* d = *(Int* *)(*args++); + void* ret = (char*)b + 1; + fprintf(out,"void* f(void*,double*,char*,Int*):(0x%p,0x%p,0x%p,0x%p)",a,b,c,d); + fflush(out); + *(void* *)retp = ret; +}} + +/* mixed number tests */ +void uc_ucsil_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&uc_ucsil) { fprintf(out,"wrong data for uc_ucsil\n"); exit(1); } + {uchar a = *(unsigned char *)(*args++); + ushort b = *(unsigned short *)(*args++); + uint c = *(unsigned int *)(*args++); + ulong d = *(unsigned long *)(*args++); + uchar r = (uchar)-1; + fprintf(out,"uchar f(uchar,ushort,uint,ulong):(%u,%u,%u,%lu)",a,b,c,d); + fflush(out); + *(ffi_arg *)retp = r; +}} +void d_iidd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_iidd) { fprintf(out,"wrong data for d_iidd\n"); exit(1); } + {int a = *(int*)(*args++); + int b = *(int*)(*args++); + double c = *(double*)(*args++); + double d = *(double*)(*args++); + double r=a+b+c+d; + fprintf(out,"double f(int,int,double,double):(%d,%d,%g,%g)",a,b,c,d); + fflush(out); + *(double*)retp = r; +}} +void d_iiidi_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_iiidi) { fprintf(out,"wrong data for d_iiidi\n"); exit(1); } + {int a = *(int*)(*args++); + int b = *(int*)(*args++); + int c = *(int*)(*args++); + double d = *(double*)(*args++); + int e = *(int*)(*args++); + double r=a+b+c+d+e; + fprintf(out,"double f(int,int,int,double,int):(%d,%d,%d,%g,%d)",a,b,c,d,e); + fflush(out); + *(double*)retp = r; +}} +void d_idid_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_idid) { fprintf(out,"wrong data for d_idid\n"); exit(1); } + {int a = *(int*)(*args++); + double b = *(double*)(*args++); + int c = *(int*)(*args++); + double d = *(double*)(*args++); + double r=a+b+c+d; + fprintf(out,"double f(int,double,int,double):(%d,%g,%d,%g)",a,b,c,d); + fflush(out); + *(double*)retp = r; +}} +void d_fdi_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_fdi) { fprintf(out,"wrong data for d_fdi\n"); exit(1); } + {float a = *(float*)(*args++); + double b = *(double*)(*args++); + int c = *(int*)(*args++); + double r=a+b+c; + fprintf(out,"double f(float,double,int):(%g,%g,%d)",a,b,c); + fflush(out); + *(double*)retp = r; +}} +void us_cdcd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&us_cdcd) { fprintf(out,"wrong data for us_cdcd\n"); exit(1); } + {char a = *(char*)(*args++); + double b = *(double*)(*args++); + char c = *(char*)(*args++); + double d = *(double*)(*args++); + ushort r = (ushort)(a + b + c + d); + fprintf(out,"ushort f(char,double,char,double):('%c',%g,'%c',%g)",a,b,c,d); + fflush(out); + *(ffi_arg *)retp = r; +}} +void ll_iiilli_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&ll_iiilli) { fprintf(out,"wrong data for ll_iiilli\n"); exit(1); } + {int a = *(int*)(*args++); + int b = *(int*)(*args++); + int c = *(int*)(*args++); + long long d = *(long long *)(*args++); + int e = *(int*)(*args++); + long long r = (long long)(int)a + (long long)(int)b + (long long)(int)c + d + (long long)e; + fprintf(out,"long long f(int,int,int,long long,int):(%d,%d,%d,0x%lx%08lx,%d)",a,b,c,(long)(d>>32),(long)(d&0xffffffff),e); + fflush(out); + *(long long *)retp = r; +}} +void ll_flli_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&ll_flli) { fprintf(out,"wrong data for ll_flli\n"); exit(1); } + {float a = *(float*)(*args++); + long long b = *(long long *)(*args++); + int c = *(int*)(*args++); + long long r = (long long)(int)a + b + (long long)c; + fprintf(out,"long long f(float,long long,int):(%g,0x%lx%08lx,0x%lx)",a,(long)(b>>32),(long)(b&0xffffffff),(long)c); + fflush(out); + *(long long *)retp = r; +}} +void f_fi_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_fi) { fprintf(out,"wrong data for f_fi\n"); exit(1); } + {float a = *(float*)(*args++); + int z = *(int*)(*args++); + float r=a+z; + fprintf(out,"float f(float,int):(%g,%d)",a,z); + fflush(out); + *(float*)retp = r; +}} +void f_f2i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f2i) { fprintf(out,"wrong data for f_f2i\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + int z = *(int*)(*args++); + float r=a+b+z; + fprintf(out,"float f(2*float,int):(%g,%g,%d)",a,b,z); + fflush(out); + *(float*)retp = r; +}} +void f_f3i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f3i) { fprintf(out,"wrong data for f_f3i\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float c = *(float*)(*args++); + int z = *(int*)(*args++); + float r=a+b+c+z; + fprintf(out,"float f(3*float,int):(%g,%g,%g,%d)",a,b,c,z); + fflush(out); + *(float*)retp = r; +}} +void f_f4i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f4i) { fprintf(out,"wrong data for f_f4i\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float c = *(float*)(*args++); + float d = *(float*)(*args++); + int z = *(int*)(*args++); + float r=a+b+c+d+z; + fprintf(out,"float f(4*float,int):(%g,%g,%g,%g,%d)",a,b,c,d,z); + fflush(out); + *(float*)retp = r; +}} +void f_f7i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f7i) { fprintf(out,"wrong data for f_f7i\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float c = *(float*)(*args++); + float d = *(float*)(*args++); + float e = *(float*)(*args++); + float f = *(float*)(*args++); + float g = *(float*)(*args++); + int z = *(int*)(*args++); + float r=a+b+c+d+e+f+g+z; + fprintf(out,"float f(7*float,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z); + fflush(out); + *(float*)retp = r; +}} +void f_f8i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f8i) { fprintf(out,"wrong data for f_f8i\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float c = *(float*)(*args++); + float d = *(float*)(*args++); + float e = *(float*)(*args++); + float f = *(float*)(*args++); + float g = *(float*)(*args++); + float h = *(float*)(*args++); + int z = *(int*)(*args++); + float r=a+b+c+d+e+f+g+h+z; + fprintf(out,"float f(8*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z); + fflush(out); + *(float*)retp = r; +}} +void f_f12i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f12i) { fprintf(out,"wrong data for f_f12i\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float c = *(float*)(*args++); + float d = *(float*)(*args++); + float e = *(float*)(*args++); + float f = *(float*)(*args++); + float g = *(float*)(*args++); + float h = *(float*)(*args++); + float i = *(float*)(*args++); + float j = *(float*)(*args++); + float k = *(float*)(*args++); + float l = *(float*)(*args++); + int z = *(int*)(*args++); + float r=a+b+c+d+e+f+g+h+i+j+k+l+z; + fprintf(out,"float f(12*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z); + fflush(out); + *(float*)retp = r; +}} +void f_f13i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f13i) { fprintf(out,"wrong data for f_f13i\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float c = *(float*)(*args++); + float d = *(float*)(*args++); + float e = *(float*)(*args++); + float f = *(float*)(*args++); + float g = *(float*)(*args++); + float h = *(float*)(*args++); + float i = *(float*)(*args++); + float j = *(float*)(*args++); + float k = *(float*)(*args++); + float l = *(float*)(*args++); + float m = *(float*)(*args++); + int z = *(int*)(*args++); + float r=a+b+c+d+e+f+g+h+i+j+k+l+m+z; + fprintf(out,"float f(13*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z); + fflush(out); + *(float*)retp = r; +}} +void d_di_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_di) { fprintf(out,"wrong data for d_di\n"); exit(1); } + {double a = *(double*)(*args++); + int z = *(int*)(*args++); + double r=a+z; + fprintf(out,"double f(double,int):(%g,%d)",a,z); + fflush(out); + *(double*)retp = r; +}} +void d_d2i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d2i) { fprintf(out,"wrong data for d_d2i\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + int z = *(int*)(*args++); + double r=a+b+z; + fprintf(out,"double f(2*double,int):(%g,%g,%d)",a,b,z); + fflush(out); + *(double*)retp = r; +}} +void d_d3i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d3i) { fprintf(out,"wrong data for d_d3i\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + double c = *(double*)(*args++); + int z = *(int*)(*args++); + double r=a+b+c+z; + fprintf(out,"double f(3*double,int):(%g,%g,%g,%d)",a,b,c,z); + fflush(out); + *(double*)retp = r; +}} +void d_d4i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d4i) { fprintf(out,"wrong data for d_d4i\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + double c = *(double*)(*args++); + double d = *(double*)(*args++); + int z = *(int*)(*args++); + double r=a+b+c+d+z; + fprintf(out,"double f(4*double,int):(%g,%g,%g,%g,%d)",a,b,c,d,z); + fflush(out); + *(double*)retp = r; +}} +void d_d7i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d7i) { fprintf(out,"wrong data for d_d7i\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + double c = *(double*)(*args++); + double d = *(double*)(*args++); + double e = *(double*)(*args++); + double f = *(double*)(*args++); + double g = *(double*)(*args++); + int z = *(int*)(*args++); + double r=a+b+c+d+e+f+g+z; + fprintf(out,"double f(7*double,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z); + fflush(out); + *(double*)retp = r; +}} +void d_d8i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d8i) { fprintf(out,"wrong data for d_d8i\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + double c = *(double*)(*args++); + double d = *(double*)(*args++); + double e = *(double*)(*args++); + double f = *(double*)(*args++); + double g = *(double*)(*args++); + double h = *(double*)(*args++); + int z = *(int*)(*args++); + double r=a+b+c+d+e+f+g+h+z; + fprintf(out,"double f(8*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z); + fflush(out); + *(double*)retp = r; +}} +void d_d12i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d12i) { fprintf(out,"wrong data for d_d12i\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + double c = *(double*)(*args++); + double d = *(double*)(*args++); + double e = *(double*)(*args++); + double f = *(double*)(*args++); + double g = *(double*)(*args++); + double h = *(double*)(*args++); + double i = *(double*)(*args++); + double j = *(double*)(*args++); + double k = *(double*)(*args++); + double l = *(double*)(*args++); + int z = *(int*)(*args++); + double r=a+b+c+d+e+f+g+h+i+j+k+l+z; + fprintf(out,"double f(12*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z); + fflush(out); + *(double*)retp = r; +}} +void d_d13i_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d13i) { fprintf(out,"wrong data for d_d13i\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + double c = *(double*)(*args++); + double d = *(double*)(*args++); + double e = *(double*)(*args++); + double f = *(double*)(*args++); + double g = *(double*)(*args++); + double h = *(double*)(*args++); + double i = *(double*)(*args++); + double j = *(double*)(*args++); + double k = *(double*)(*args++); + double l = *(double*)(*args++); + double m = *(double*)(*args++); + int z = *(int*)(*args++); + double r=a+b+c+d+e+f+g+h+i+j+k+l+m+z; + fprintf(out,"double f(13*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z); + fflush(out); + *(double*)retp = r; +}} + +/* small structure return tests */ +void S1_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&S1_v) { fprintf(out,"wrong data for S1_v\n"); exit(1); } + {Size1 r = Size1_1; + fprintf(out,"Size1 f(void):"); + fflush(out); + *(Size1*)retp = r; +}} +void S2_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&S2_v) { fprintf(out,"wrong data for S2_v\n"); exit(1); } + {Size2 r = Size2_1; + fprintf(out,"Size2 f(void):"); + fflush(out); + *(Size2*)retp = r; +}} +void S3_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&S3_v) { fprintf(out,"wrong data for S3_v\n"); exit(1); } + {Size3 r = Size3_1; + fprintf(out,"Size3 f(void):"); + fflush(out); + *(Size3*)retp = r; +}} +void S4_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&S4_v) { fprintf(out,"wrong data for S4_v\n"); exit(1); } + {Size4 r = Size4_1; + fprintf(out,"Size4 f(void):"); + fflush(out); + *(Size4*)retp = r; +}} +void S7_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&S7_v) { fprintf(out,"wrong data for S7_v\n"); exit(1); } + {Size7 r = Size7_1; + fprintf(out,"Size7 f(void):"); + fflush(out); + *(Size7*)retp = r; +}} +void S8_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&S8_v) { fprintf(out,"wrong data for S8_v\n"); exit(1); } + {Size8 r = Size8_1; + fprintf(out,"Size8 f(void):"); + fflush(out); + *(Size8*)retp = r; +}} +void S12_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&S12_v) { fprintf(out,"wrong data for S12_v\n"); exit(1); } + {Size12 r = Size12_1; + fprintf(out,"Size12 f(void):"); + fflush(out); + *(Size12*)retp = r; +}} +void S15_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&S15_v) { fprintf(out,"wrong data for S15_v\n"); exit(1); } + {Size15 r = Size15_1; + fprintf(out,"Size15 f(void):"); + fflush(out); + *(Size15*)retp = r; +}} +void S16_v_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&S16_v) { fprintf(out,"wrong data for S16_v\n"); exit(1); } + {Size16 r = Size16_1; + fprintf(out,"Size16 f(void):"); + fflush(out); + *(Size16*)retp = r; +}} + +/* structure tests */ +void I_III_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&I_III) { fprintf(out,"wrong data for I_III\n"); exit(1); } + {Int a = *(Int*)(*args++); + Int b = *(Int*)(*args++); + Int c = *(Int*)(*args++); + Int r; + r.x = a.x + b.x + c.x; + fprintf(out,"Int f(Int,Int,Int):({%d},{%d},{%d})",a.x,b.x,c.x); + fflush(out); + *(Int*)retp = r; +}} +void C_CdC_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&C_CdC) { fprintf(out,"wrong data for C_CdC\n"); exit(1); } + {Char a = *(Char*)(*args++); + double b = *(double*)(*args++); + Char c = *(Char*)(*args++); + Char r; + r.x = (a.x + c.x)/2; + fprintf(out,"Char f(Char,double,Char):({'%c'},%g,{'%c'})",a.x,b,c.x); + fflush(out); + *(Char*)retp = r; +}} +void F_Ffd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&F_Ffd) { fprintf(out,"wrong data for F_Ffd\n"); exit(1); } + {Float a = *(Float*)(*args++); + float b = *(float*)(*args++); + double c = *(double*)(*args++); + Float r; + r.x = a.x + b + c; + fprintf(out,"Float f(Float,float,double):({%g},%g,%g)",a.x,b,c); + fflush(out); + *(Float*)retp = r; +}} +void D_fDd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&D_fDd) { fprintf(out,"wrong data for D_fDd\n"); exit(1); } + {float a = *(float*)(*args++); + Double b = *(Double*)(*args++); + double c = *(double*)(*args++); + Double r; + r.x = a + b.x + c; + fprintf(out,"Double f(float,Double,double):(%g,{%g},%g)",a,b.x,c); + fflush(out); + *(Double*)retp = r; +}} +void D_Dfd_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&D_Dfd) { fprintf(out,"wrong data for D_Dfd\n"); exit(1); } + {Double a = *(Double*)(*args++); + float b = *(float*)(*args++); + double c = *(double*)(*args++); + Double r; + r.x = a.x + b + c; + fprintf(out,"Double f(Double,float,double):({%g},%g,%g)",a.x,b,c); + fflush(out); + *(Double*)retp = r; +}} +void J_JiJ_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&J_JiJ) { fprintf(out,"wrong data for J_JiJ\n"); exit(1); } + {J a = *(J*)(*args++); + int b= *(int*)(*args++); + J c = *(J*)(*args++); + J r; + r.l1 = a.l1+c.l1; r.l2 = a.l2+b+c.l2; + fprintf(out,"J f(J,int,J):({%ld,%ld},%d,{%ld,%ld})",a.l1,a.l2,b,c.l1,c.l2); + fflush(out); + *(J*)retp = r; +}} +#ifndef SKIP_EXTRA_STRUCTS +void T_TcT_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&T_TcT) { fprintf(out,"wrong data for T_TcT\n"); exit(1); } + {T a = *(T*)(*args++); + char b = *(char*)(*args++); + T c = *(T*)(*args++); + T r; + r.c[0]='b'; r.c[1]=c.c[1]; r.c[2]=c.c[2]; + fprintf(out,"T f(T,char,T):({\"%c%c%c\"},'%c',{\"%c%c%c\"})",a.c[0],a.c[1],a.c[2],b,c.c[0],c.c[1],c.c[2]); + fflush(out); + *(T*)retp = r; +}} +void X_BcdB_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&X_BcdB) { fprintf(out,"wrong data for X_BcdB\n"); exit(1); } + {B a = *(B*)(*args++); + char b = *(char*)(*args++); + double c = *(double*)(*args++); + B d = *(B*)(*args++); + static X xr={"return val",'R'}; + X r; + r = xr; + r.c1 = b; + fprintf(out,"X f(B,char,double,B):({%g,{%d,%d,%d}},'%c',%g,{%g,{%d,%d,%d}})", + a.d,a.i[0],a.i[1],a.i[2],b,c,d.d,d.i[0],d.i[1],d.i[2]); + fflush(out); + *(X*)retp = r; +}} +#endif + +/* gpargs boundary tests */ +void l_l0K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&l_l0K) { fprintf(out,"wrong data for l_l0K\n"); exit(1); } + {K b = *(K*)(*args++); + long c = *(long*)(*args++); + long r = b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(K,long):(%ld,%ld,%ld,%ld,%ld)",b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + *(ffi_arg*)retp = r; +}} +void l_l1K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&l_l1K) { fprintf(out,"wrong data for l_l1K\n"); exit(1); } + {long a1 = *(long*)(*args++); + K b = *(K*)(*args++); + long c = *(long*)(*args++); + long r = a1 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld)",a1,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + *(ffi_arg*)retp = r; +}} +void l_l2K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&l_l2K) { fprintf(out,"wrong data for l_l2K\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + K b = *(K*)(*args++); + long c = *(long*)(*args++); + long r = a1 + a2 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(2*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + *(ffi_arg*)retp = r; +}} +void l_l3K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&l_l3K) { fprintf(out,"wrong data for l_l3K\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + K b = *(K*)(*args++); + long c = *(long*)(*args++); + long r = a1 + a2 + a3 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(3*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + *(ffi_arg*)retp = r; +}} +void l_l4K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&l_l4K) { fprintf(out,"wrong data for l_l4K\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long a4 = *(long*)(*args++); + K b = *(K*)(*args++); + long c = *(long*)(*args++); + long r = a1 + a2 + a3 + a4 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(4*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + *(ffi_arg*)retp = r; +}} +void l_l5K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&l_l5K) { fprintf(out,"wrong data for l_l5K\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long a4 = *(long*)(*args++); + long a5 = *(long*)(*args++); + K b = *(K*)(*args++); + long c = *(long*)(*args++); + long r = a1 + a2 + a3 + a4 + a5 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(5*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + *(ffi_arg*)retp = r; +}} +void l_l6K_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&l_l6K) { fprintf(out,"wrong data for l_l6K\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long a4 = *(long*)(*args++); + long a5 = *(long*)(*args++); + long a6 = *(long*)(*args++); + K b = *(K*)(*args++); + long c = *(long*)(*args++); + long r = a1 + a2 + a3 + a4 + a5 + a6 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(6*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,a6,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + *(ffi_arg*)retp = r; +}} +void f_f17l3L_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&f_f17l3L) { fprintf(out,"wrong data for f_f17l3L\n"); exit(1); } + {float a = *(float*)(*args++); + float b = *(float*)(*args++); + float c = *(float*)(*args++); + float d = *(float*)(*args++); + float e = *(float*)(*args++); + float f = *(float*)(*args++); + float g = *(float*)(*args++); + float h = *(float*)(*args++); + float i = *(float*)(*args++); + float j = *(float*)(*args++); + float k = *(float*)(*args++); + float l = *(float*)(*args++); + float m = *(float*)(*args++); + float n = *(float*)(*args++); + float o = *(float*)(*args++); + float p = *(float*)(*args++); + float q = *(float*)(*args++); + long s = *(long*)(*args++); + long t = *(long*)(*args++); + long u = *(long*)(*args++); + L z = *(L*)(*args++); + float r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6; + fprintf(out,"float f(17*float,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6); + fflush(out); + *(float*)retp = r; +}} +void d_d17l3L_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_d17l3L) { fprintf(out,"wrong data for d_d17l3L\n"); exit(1); } + {double a = *(double*)(*args++); + double b = *(double*)(*args++); + double c = *(double*)(*args++); + double d = *(double*)(*args++); + double e = *(double*)(*args++); + double f = *(double*)(*args++); + double g = *(double*)(*args++); + double h = *(double*)(*args++); + double i = *(double*)(*args++); + double j = *(double*)(*args++); + double k = *(double*)(*args++); + double l = *(double*)(*args++); + double m = *(double*)(*args++); + double n = *(double*)(*args++); + double o = *(double*)(*args++); + double p = *(double*)(*args++); + double q = *(double*)(*args++); + long s = *(long*)(*args++); + long t = *(long*)(*args++); + long u = *(long*)(*args++); + L z = *(L*)(*args++); + double r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6; + fprintf(out,"double f(17*double,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6); + fflush(out); + *(double*)retp = r; +}} +void ll_l2ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&ll_l2ll) { fprintf(out,"wrong data for ll_l2ll\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long long b = *(long long *)(*args++); + long c = *(long*)(*args++); + long long r = (long long) (a1 + a2) + b + c; + fprintf(out,"long long f(2*long,long long,long):(%ld,%ld,0x%lx%08lx,%ld)",a1,a2,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + *(long long *)retp = r; +}} +void ll_l3ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&ll_l3ll) { fprintf(out,"wrong data for ll_l3ll\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long long b = *(long long *)(*args++); + long c = *(long*)(*args++); + long long r = (long long) (a1 + a2 + a3) + b + c; + fprintf(out,"long long f(3*long,long long,long):(%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + *(long long *)retp = r; +}} +void ll_l4ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&ll_l4ll) { fprintf(out,"wrong data for ll_l4ll\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long a4 = *(long*)(*args++); + long long b = *(long long *)(*args++); + long c = *(long*)(*args++); + long long r = (long long) (a1 + a2 + a3 + a4) + b + c; + fprintf(out,"long long f(4*long,long long,long):(%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + *(long long *)retp = r; +}} +void ll_l5ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&ll_l5ll) { fprintf(out,"wrong data for ll_l5ll\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long a4 = *(long*)(*args++); + long a5 = *(long*)(*args++); + long long b = *(long long *)(*args++); + long c = *(long*)(*args++); + long long r = (long long) (a1 + a2 + a3 + a4 + a5) + b + c; + fprintf(out,"long long f(5*long,long long,long):(%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + *(long long *)retp = r; +}} +void ll_l6ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&ll_l6ll) { fprintf(out,"wrong data for ll_l6ll\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long a4 = *(long*)(*args++); + long a5 = *(long*)(*args++); + long a6 = *(long*)(*args++); + long long b = *(long long *)(*args++); + long c = *(long*)(*args++); + long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6) + b + c; + fprintf(out,"long long f(6*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + *(long long *)retp = r; +}} +void ll_l7ll_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&ll_l7ll) { fprintf(out,"wrong data for ll_l7ll\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long a4 = *(long*)(*args++); + long a5 = *(long*)(*args++); + long a6 = *(long*)(*args++); + long a7 = *(long*)(*args++); + long long b = *(long long *)(*args++); + long c = *(long*)(*args++); + long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c; + fprintf(out,"long long f(7*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,a7,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + *(long long *)retp = r; +}} +void d_l2d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_l2d) { fprintf(out,"wrong data for d_l2d\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + double b = *(double*)(*args++); + long c = *(long*)(*args++); + double r = (double) (a1 + a2) + b + c; + fprintf(out,"double f(2*long,double,long):(%ld,%ld,%g,%ld)",a1,a2,b,c); + fflush(out); + *(double*)retp = r; +}} +void d_l3d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_l3d) { fprintf(out,"wrong data for d_l3d\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + double b = *(double*)(*args++); + long c = *(long*)(*args++); + double r = (double) (a1 + a2 + a3) + b + c; + fprintf(out,"double f(3*long,double,long):(%ld,%ld,%ld,%g,%ld)",a1,a2,a3,b,c); + fflush(out); + *(double*)retp = r; +}} +void d_l4d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_l4d) { fprintf(out,"wrong data for d_l4d\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long a4 = *(long*)(*args++); + double b = *(double*)(*args++); + long c = *(long*)(*args++); + double r = (double) (a1 + a2 + a3 + a4) + b + c; + fprintf(out,"double f(4*long,double,long):(%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,b,c); + fflush(out); + *(double*)retp = r; +}} +void d_l5d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_l5d) { fprintf(out,"wrong data for d_l5d\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long a4 = *(long*)(*args++); + long a5 = *(long*)(*args++); + double b = *(double*)(*args++); + long c = *(long*)(*args++); + double r = (double) (a1 + a2 + a3 + a4 + a5) + b + c; + fprintf(out,"double f(5*long,double,long):(%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,b,c); + fflush(out); + *(double*)retp = r; +}} +void d_l6d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_l6d) { fprintf(out,"wrong data for d_l6d\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long a4 = *(long*)(*args++); + long a5 = *(long*)(*args++); + long a6 = *(long*)(*args++); + double b = *(double*)(*args++); + long c = *(long*)(*args++); + double r = (double) (a1 + a2 + a3 + a4 + a5 + a6) + b + c; + fprintf(out,"double f(6*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,b,c); + fflush(out); + *(double*)retp = r; +}} +void d_l7d_simulator (ffi_cif* cif, void* retp, /*const*/ void* /*const*/ *args, void* data) +{ + if (data != (void*)&d_l7d) { fprintf(out,"wrong data for d_l7d\n"); exit(1); } + {long a1 = *(long*)(*args++); + long a2 = *(long*)(*args++); + long a3 = *(long*)(*args++); + long a4 = *(long*)(*args++); + long a5 = *(long*)(*args++); + long a6 = *(long*)(*args++); + long a7 = *(long*)(*args++); + double b = *(double*)(*args++); + long c = *(long*)(*args++); + double r = (double) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c; + fprintf(out,"double f(7*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,a7,b,c); + fflush(out); + *(double*)retp = r; +}} + + +/* + * The way we run these tests - first call the function directly, then + * through vacall() - there is the danger that arguments or results seem + * to be passed correctly, but what we are seeing are in fact the vestiges + * (traces) or the previous call. This may seriously fake the test. + * Avoid this by clearing the registers between the first and the second call. + */ +long clear_traces_i (long a, long b, long c, long d, long e, long f, long g, long h, + long i, long j, long k, long l, long m, long n, long o, long p) +{ return 0; } +float clear_traces_f (float a, float b, float c, float d, float e, float f, float g, + float h, float i, float j, float k, float l, float m, float n, + float o, float p) +{ return 0.0; } +double clear_traces_d (double a, double b, double c, double d, double e, double f, double g, + double h, double i, double j, double k, double l, double m, double n, + double o, double p) +{ return 0.0; } +J clear_traces_J (void) +{ J j; j.l1 = j.l2 = 0; return j; } +void clear_traces (void) +{ clear_traces_i(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0); + clear_traces_f(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0); + clear_traces_d(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0); + clear_traces_J(); +} + +int main (void) +{ + void* callback_code; + void* callback_writable; +#define ALLOC_CALLBACK() \ + callback_writable = ffi_closure_alloc(sizeof(ffi_closure),&callback_code); \ + if (!callback_writable) abort() +#define PREP_CALLBACK(cif,simulator,data) \ + if (ffi_prep_closure_loc(callback_writable,&(cif),simulator,data,callback_code) != FFI_OK) abort() +#define FREE_CALLBACK() \ + ffi_closure_free(callback_writable) + + ffi_type_char = (char)(-1) < 0 ? ffi_type_schar : ffi_type_uchar; + out = stdout; + +#if (!defined(DGTEST)) || DGTEST == 1 + /* void tests */ + v_v(); + clear_traces(); + ALLOC_CALLBACK(); + { + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_void); + PREP_CALLBACK(cif,v_v_simulator,(void*)&v_v); + ((void (ABI_ATTR *) (void)) callback_code) (); + } + FREE_CALLBACK(); +#endif + + /* int tests */ + { int ir; + +#if (!defined(DGTEST)) || DGTEST == 2 + ir = i_v(); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_sint); + PREP_CALLBACK(cif,i_v_simulator,(void*)&i_v); + ir = ((int (ABI_ATTR *) (void)) callback_code) (); + } + FREE_CALLBACK(); + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 3 + ir = i_i(i1); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_sint); + PREP_CALLBACK(cif,i_i_simulator,(void*)&i_i); + ir = ((int (ABI_ATTR *) (int)) callback_code) (i1); + } + FREE_CALLBACK(); + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 4 + ir = i_i2(i1,i2); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_sint); + PREP_CALLBACK(cif,i_i2_simulator,(void*)&i_i2); + ir = ((int (ABI_ATTR *) (int,int)) callback_code) (i1,i2); + } + FREE_CALLBACK(); + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 5 + ir = i_i4(i1,i2,i3,i4); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_sint); + PREP_CALLBACK(cif,i_i4_simulator,(void*)&i_i4); + ir = ((int (ABI_ATTR *) (int,int,int,int)) callback_code) (i1,i2,i3,i4); + } + FREE_CALLBACK(); + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 6 + ir = i_i8(i1,i2,i3,i4,i5,i6,i7,i8); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_sint); + PREP_CALLBACK(cif,i_i8_simulator,(void*)&i_i8); + ir = ((int (ABI_ATTR *) (int,int,int,int,int,int,int,int)) callback_code) (i1,i2,i3,i4,i5,i6,i7,i8); + } + FREE_CALLBACK(); + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 7 + ir = i_i16(i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16); + fprintf(out,"->%d\n",ir); + fflush(out); + ir = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_sint); + PREP_CALLBACK(cif,i_i16_simulator,(void*)&i_i16); + ir = ((int (ABI_ATTR *) (int,int,int,int,int,int,int,int,int,int,int,int,int,int,int,int)) callback_code) (i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16); + } + FREE_CALLBACK(); + fprintf(out,"->%d\n",ir); + fflush(out); +#endif + } + + /* float tests */ + { float fr; + +#if (!defined(DGTEST)) || DGTEST == 8 + fr = f_f(f1); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f_simulator,(void*)&f_f); + fr = ((float (ABI_ATTR *) (float)) callback_code) (f1); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 9 + fr = f_f2(f1,f2); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f2_simulator,(void*)&f_f2); + fr = ((float (ABI_ATTR *) (float,float)) callback_code) (f1,f2); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 10 + fr = f_f4(f1,f2,f3,f4); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f4_simulator,(void*)&f_f4); + fr = ((float (ABI_ATTR *) (float,float,float,float)) callback_code) (f1,f2,f3,f4); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 11 + fr = f_f8(f1,f2,f3,f4,f5,f6,f7,f8); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f8_simulator,(void*)&f_f8); + fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 12 + fr = f_f16(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f16_simulator,(void*)&f_f16); + fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 13 + fr = f_f24(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f24_simulator,(void*)&f_f24); + fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + + } + + /* double tests */ + { double dr; + +#if (!defined(DGTEST)) || DGTEST == 14 + dr = d_d(d1); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d_simulator,(void*)&d_d); + dr = ((double (ABI_ATTR *) (double)) callback_code) (d1); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 15 + dr = d_d2(d1,d2); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d2_simulator,(void*)&d_d2); + dr = ((double (ABI_ATTR *) (double,double)) callback_code) (d1,d2); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 16 + dr = d_d4(d1,d2,d3,d4); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d4_simulator,(void*)&d_d4); + dr = ((double (ABI_ATTR *) (double,double,double,double)) callback_code) (d1,d2,d3,d4); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 17 + dr = d_d8(d1,d2,d3,d4,d5,d6,d7,d8); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d8_simulator,(void*)&d_d8); + dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 18 + dr = d_d16(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d16_simulator,(void*)&d_d16); + dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,double)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + } + + /* pointer tests */ + { void* vpr; + +#if (!defined(DGTEST)) || DGTEST == 19 + vpr = vp_vpdpcpsp(&uc1,&d2,str3,&I4); + fprintf(out,"->0x%p\n",vpr); + fflush(out); + vpr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer, &ffi_type_pointer }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_pointer); + PREP_CALLBACK(cif,vp_vpdpcpsp_simulator,(void*)&vp_vpdpcpsp); + vpr = ((void* (ABI_ATTR *) (void*,double*,char*,Int*)) callback_code) (&uc1,&d2,str3,&I4); + } + FREE_CALLBACK(); + fprintf(out,"->0x%p\n",vpr); + fflush(out); +#endif + } + + /* mixed number tests */ + { uchar ucr; + ushort usr; + float fr; + double dr; + long long llr; + +#if (!defined(DGTEST)) || DGTEST == 20 + ucr = uc_ucsil(uc1,us2,ui3,ul4); + fprintf(out,"->%u\n",ucr); + fflush(out); + ucr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_uchar, &ffi_type_ushort, &ffi_type_uint, &ffi_type_ulong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_uchar); + PREP_CALLBACK(cif,uc_ucsil_simulator,(void*)&uc_ucsil); + ucr = ((uchar (ABI_ATTR *) (uchar,ushort,uint,ulong)) callback_code) (uc1,us2,ui3,ul4); + } + FREE_CALLBACK(); + fprintf(out,"->%u\n",ucr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 21 + dr = d_iidd(i1,i2,d3,d4); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_iidd_simulator,(void*)&d_iidd); + dr = ((double (ABI_ATTR *) (int,int,double,double)) callback_code) (i1,i2,d3,d4); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 22 + dr = d_iiidi(i1,i2,i3,d4,i5); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_iiidi_simulator,(void*)&d_iiidi); + dr = ((double (ABI_ATTR *) (int,int,int,double,int)) callback_code) (i1,i2,i3,d4,i5); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 23 + dr = d_idid(i1,d2,i3,d4); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_double, &ffi_type_sint, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_idid_simulator,(void*)&d_idid); + dr = ((double (ABI_ATTR *) (int,double,int,double)) callback_code) (i1,d2,i3,d4); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 24 + dr = d_fdi(f1,d2,i3); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_fdi_simulator,(void*)&d_fdi); + dr = ((double (ABI_ATTR *) (float,double,int)) callback_code) (f1,d2,i3); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 25 + usr = us_cdcd(c1,d2,c3,d4); + fprintf(out,"->%u\n",usr); + fflush(out); + usr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_char, &ffi_type_double, &ffi_type_char, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_ushort); + PREP_CALLBACK(cif,us_cdcd_simulator,(void*)&us_cdcd); + usr = ((ushort (ABI_ATTR *) (char,double,char,double)) callback_code) (c1,d2,c3,d4); + } + FREE_CALLBACK(); + fprintf(out,"->%u\n",usr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 26 + llr = ll_iiilli(i1,i2,i3,ll1,i13); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_sint, &ffi_type_sint, &ffi_type_sint, &ffi_type_slonglong, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + PREP_CALLBACK(cif,ll_iiilli_simulator,(void*)&ll_iiilli); + llr = ((long long (ABI_ATTR *) (int,int,int,long long,int)) callback_code) (i1,i2,i3,ll1,i13); + } + FREE_CALLBACK(); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 27 + llr = ll_flli(f13,ll1,i13); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_slonglong, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + PREP_CALLBACK(cif,ll_flli_simulator,(void*)&ll_flli); + llr = ((long long (ABI_ATTR *) (float,long long,int)) callback_code) (f13,ll1,i13); + } + FREE_CALLBACK(); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 28 + fr = f_fi(f1,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_fi_simulator,(void*)&f_fi); + fr = ((float (ABI_ATTR *) (float,int)) callback_code) (f1,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 29 + fr = f_f2i(f1,f2,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f2i_simulator,(void*)&f_f2i); + fr = ((float (ABI_ATTR *) (float,float,int)) callback_code) (f1,f2,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 30 + fr = f_f3i(f1,f2,f3,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f3i_simulator,(void*)&f_f3i); + fr = ((float (ABI_ATTR *) (float,float,float,int)) callback_code) (f1,f2,f3,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 31 + fr = f_f4i(f1,f2,f3,f4,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f4i_simulator,(void*)&f_f4i); + fr = ((float (ABI_ATTR *) (float,float,float,float,int)) callback_code) (f1,f2,f3,f4,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 32 + fr = f_f7i(f1,f2,f3,f4,f5,f6,f7,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f7i_simulator,(void*)&f_f7i); + fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,int)) callback_code) (f1,f2,f3,f4,f5,f6,f7,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 33 + fr = f_f8i(f1,f2,f3,f4,f5,f6,f7,f8,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f8i_simulator,(void*)&f_f8i); + fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,int)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 34 + fr = f_f13i(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,i9); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f13i_simulator,(void*)&f_f13i); + fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,int)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 35 + dr = d_di(d1,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_di_simulator,(void*)&d_di); + dr = ((double (ABI_ATTR *) (double,int)) callback_code) (d1,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 36 + dr = d_d2i(d1,d2,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d2i_simulator,(void*)&d_d2i); + dr = ((double (ABI_ATTR *) (double,double,int)) callback_code) (d1,d2,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 37 + dr = d_d3i(d1,d2,d3,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d3i_simulator,(void*)&d_d3i); + dr = ((double (ABI_ATTR *) (double,double,double,int)) callback_code) (d1,d2,d3,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 38 + dr = d_d4i(d1,d2,d3,d4,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d4i_simulator,(void*)&d_d4i); + dr = ((double (ABI_ATTR *) (double,double,double,double,int)) callback_code) (d1,d2,d3,d4,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 39 + dr = d_d7i(d1,d2,d3,d4,d5,d6,d7,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d7i_simulator,(void*)&d_d7i); + dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 40 + dr = d_d8i(d1,d2,d3,d4,d5,d6,d7,d8,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d8i_simulator,(void*)&d_d8i); + dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 41 + dr = d_d12i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d12i_simulator,(void*)&d_d12i); + dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 42 + dr = d_d13i(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,i9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_sint }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d13i_simulator,(void*)&d_d13i); + dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,double,int)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,i9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + } + + /* small structure return tests */ +#if (!defined(DGTEST)) || DGTEST == 43 + { + Size1 r = S1_v(); + fprintf(out,"->{%c}\n",r.x1); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Size1_elements[] = { &ffi_type_char, NULL }; + ffi_type ffi_type_Size1; + ffi_type_Size1.type = FFI_TYPE_STRUCT; + ffi_type_Size1.size = sizeof(Size1); + ffi_type_Size1.alignment = alignof_slot(Size1); + ffi_type_Size1.elements = ffi_type_Size1_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size1); + PREP_CALLBACK(cif,S1_v_simulator,(void*)&S1_v); + r = ((Size1 (ABI_ATTR *) (void)) callback_code) (); + } + FREE_CALLBACK(); + fprintf(out,"->{%c}\n",r.x1); + fflush(out); + } +#endif + +#if (!defined(DGTEST)) || DGTEST == 44 + { + Size2 r = S2_v(); + fprintf(out,"->{%c%c}\n",r.x1,r.x2); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Size2_elements[] = { &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size2; + ffi_type_Size2.type = FFI_TYPE_STRUCT; + ffi_type_Size2.size = sizeof(Size2); + ffi_type_Size2.alignment = alignof_slot(Size2); + ffi_type_Size2.elements = ffi_type_Size2_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size2); + PREP_CALLBACK(cif,S2_v_simulator,(void*)&S2_v); + r = ((Size2 (ABI_ATTR *) (void)) callback_code) (); + } + FREE_CALLBACK(); + fprintf(out,"->{%c%c}\n",r.x1,r.x2); + fflush(out); + } +#endif + +#if (!defined(DGTEST)) || DGTEST == 45 + { + Size3 r = S3_v(); + fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Size3_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size3; + ffi_type_Size3.type = FFI_TYPE_STRUCT; + ffi_type_Size3.size = sizeof(Size3); + ffi_type_Size3.alignment = alignof_slot(Size3); + ffi_type_Size3.elements = ffi_type_Size3_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size3); + PREP_CALLBACK(cif,S3_v_simulator,(void*)&S3_v); + r = ((Size3 (ABI_ATTR *) (void)) callback_code) (); + } + FREE_CALLBACK(); + fprintf(out,"->{%c%c%c}\n",r.x1,r.x2,r.x3); + fflush(out); + } +#endif + +#if (!defined(DGTEST)) || DGTEST == 46 + { + Size4 r = S4_v(); + fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Size4_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size4; + ffi_type_Size4.type = FFI_TYPE_STRUCT; + ffi_type_Size4.size = sizeof(Size4); + ffi_type_Size4.alignment = alignof_slot(Size4); + ffi_type_Size4.elements = ffi_type_Size4_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size4); + PREP_CALLBACK(cif,S4_v_simulator,(void*)&S4_v); + r = ((Size4 (ABI_ATTR *) (void)) callback_code) (); + } + FREE_CALLBACK(); + fprintf(out,"->{%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4); + fflush(out); + } +#endif + +#if (!defined(DGTEST)) || DGTEST == 47 + { + Size7 r = S7_v(); + fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Size7_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size7; + ffi_type_Size7.type = FFI_TYPE_STRUCT; + ffi_type_Size7.size = sizeof(Size7); + ffi_type_Size7.alignment = alignof_slot(Size7); + ffi_type_Size7.elements = ffi_type_Size7_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size7); + PREP_CALLBACK(cif,S7_v_simulator,(void*)&S7_v); + r = ((Size7 (ABI_ATTR *) (void)) callback_code) (); + } + FREE_CALLBACK(); + fprintf(out,"->{%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7); + fflush(out); + } +#endif + +#if (!defined(DGTEST)) || DGTEST == 48 + { + Size8 r = S8_v(); + fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Size8_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size8; + ffi_type_Size8.type = FFI_TYPE_STRUCT; + ffi_type_Size8.size = sizeof(Size8); + ffi_type_Size8.alignment = alignof_slot(Size8); + ffi_type_Size8.elements = ffi_type_Size8_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size8); + PREP_CALLBACK(cif,S8_v_simulator,(void*)&S8_v); + r = ((Size8 (ABI_ATTR *) (void)) callback_code) (); + } + FREE_CALLBACK(); + fprintf(out,"->{%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8); + fflush(out); + } +#endif + +#if (!defined(DGTEST)) || DGTEST == 49 + { + Size12 r = S12_v(); + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Size12_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size12; + ffi_type_Size12.type = FFI_TYPE_STRUCT; + ffi_type_Size12.size = sizeof(Size12); + ffi_type_Size12.alignment = alignof_slot(Size12); + ffi_type_Size12.elements = ffi_type_Size12_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size12); + PREP_CALLBACK(cif,S12_v_simulator,(void*)&S12_v); + r = ((Size12 (ABI_ATTR *) (void)) callback_code) (); + } + FREE_CALLBACK(); + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12); + fflush(out); + } +#endif + +#if (!defined(DGTEST)) || DGTEST == 50 + { + Size15 r = S15_v(); + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Size15_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size15; + ffi_type_Size15.type = FFI_TYPE_STRUCT; + ffi_type_Size15.size = sizeof(Size15); + ffi_type_Size15.alignment = alignof_slot(Size15); + ffi_type_Size15.elements = ffi_type_Size15_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size15); + PREP_CALLBACK(cif,S15_v_simulator,(void*)&S15_v); + r = ((Size15 (ABI_ATTR *) (void)) callback_code) (); + } + FREE_CALLBACK(); + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15); + fflush(out); + } +#endif + +#if (!defined(DGTEST)) || DGTEST == 51 + { + Size16 r = S16_v(); + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16); + fflush(out); + memset(&r,0,sizeof(r)); clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Size16_elements[] = { &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, &ffi_type_char, NULL }; + ffi_type ffi_type_Size16; + ffi_type_Size16.type = FFI_TYPE_STRUCT; + ffi_type_Size16.size = sizeof(Size16); + ffi_type_Size16.alignment = alignof_slot(Size16); + ffi_type_Size16.elements = ffi_type_Size16_elements; + ffi_cif cif; + FFI_PREP_CIF_NOARGS(cif,ffi_type_Size16); + PREP_CALLBACK(cif,S16_v_simulator,(void*)&S16_v); + r = ((Size16 (ABI_ATTR *) (void)) callback_code) (); + } + FREE_CALLBACK(); + fprintf(out,"->{%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c}\n",r.x1,r.x2,r.x3,r.x4,r.x5,r.x6,r.x7,r.x8,r.x9,r.x10,r.x11,r.x12,r.x13,r.x14,r.x15,r.x16); + fflush(out); + } +#endif + + + /* structure tests */ + { Int Ir; + Char Cr; + Float Fr; + Double Dr; + J Jr; +#ifndef SKIP_EXTRA_STRUCTS + T Tr; + X Xr; +#endif + +#if (!defined(DGTEST)) || DGTEST == 52 + Ir = I_III(I1,I2,I3); + fprintf(out,"->{%d}\n",Ir.x); + fflush(out); + Ir.x = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Int_elements[] = { &ffi_type_sint, NULL }; + ffi_type ffi_type_Int; + ffi_type_Int.type = FFI_TYPE_STRUCT; + ffi_type_Int.size = sizeof(Int); + ffi_type_Int.alignment = alignof_slot(Int); + ffi_type_Int.elements = ffi_type_Int_elements; + ffi_type* argtypes[] = { &ffi_type_Int, &ffi_type_Int, &ffi_type_Int }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_Int); + PREP_CALLBACK(cif,I_III_simulator,(void*)&I_III); + Ir = ((Int (ABI_ATTR *) (Int,Int,Int)) callback_code) (I1,I2,I3); + } + FREE_CALLBACK(); + fprintf(out,"->{%d}\n",Ir.x); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 53 + Cr = C_CdC(C1,d2,C3); + fprintf(out,"->{'%c'}\n",Cr.x); + fflush(out); + Cr.x = '\0'; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Char_elements[] = { &ffi_type_char, NULL }; + ffi_type ffi_type_Char; + ffi_type_Char.type = FFI_TYPE_STRUCT; + ffi_type_Char.size = sizeof(Char); + ffi_type_Char.alignment = alignof_slot(Char); + ffi_type_Char.elements = ffi_type_Char_elements; + ffi_type* argtypes[] = { &ffi_type_Char, &ffi_type_double, &ffi_type_Char }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_Char); + PREP_CALLBACK(cif,C_CdC_simulator,(void*)&C_CdC); + Cr = ((Char (ABI_ATTR *) (Char,double,Char)) callback_code) (C1,d2,C3); + } + FREE_CALLBACK(); + fprintf(out,"->{'%c'}\n",Cr.x); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 54 + Fr = F_Ffd(F1,f2,d3); + fprintf(out,"->{%g}\n",Fr.x); + fflush(out); + Fr.x = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Float_elements[] = { &ffi_type_float, NULL }; + ffi_type ffi_type_Float; + ffi_type_Float.type = FFI_TYPE_STRUCT; + ffi_type_Float.size = sizeof(Float); + ffi_type_Float.alignment = alignof_slot(Float); + ffi_type_Float.elements = ffi_type_Float_elements; + ffi_type* argtypes[] = { &ffi_type_Float, &ffi_type_float, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_Float); + PREP_CALLBACK(cif,F_Ffd_simulator,(void*)&F_Ffd); + Fr = ((Float (ABI_ATTR *) (Float,float,double)) callback_code) (F1,f2,d3); + } + FREE_CALLBACK(); + fprintf(out,"->{%g}\n",Fr.x); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 55 + Dr = D_fDd(f1,D2,d3); + fprintf(out,"->{%g}\n",Dr.x); + fflush(out); + Dr.x = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL }; + ffi_type ffi_type_Double; + ffi_type_Double.type = FFI_TYPE_STRUCT; + ffi_type_Double.size = sizeof(Double); + ffi_type_Double.alignment = alignof_slot(Double); + ffi_type_Double.elements = ffi_type_Double_elements; + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_Double, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_Double); + PREP_CALLBACK(cif,D_fDd_simulator,(void*)&D_fDd); + Dr = ((Double (ABI_ATTR *) (float,Double,double)) callback_code) (f1,D2,d3); + } + FREE_CALLBACK(); + fprintf(out,"->{%g}\n",Dr.x); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 56 + Dr = D_Dfd(D1,f2,d3); + fprintf(out,"->{%g}\n",Dr.x); + fflush(out); + Dr.x = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_Double_elements[] = { &ffi_type_double, NULL }; + ffi_type ffi_type_Double; + ffi_type_Double.type = FFI_TYPE_STRUCT; + ffi_type_Double.size = sizeof(Double); + ffi_type_Double.alignment = alignof_slot(Double); + ffi_type_Double.elements = ffi_type_Double_elements; + ffi_type* argtypes[] = { &ffi_type_Double, &ffi_type_float, &ffi_type_double }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_Double); + PREP_CALLBACK(cif,D_Dfd_simulator,(void*)&D_Dfd); + Dr = ((Double (ABI_ATTR *) (Double,float,double)) callback_code) (D1,f2,d3); + } + FREE_CALLBACK(); + fprintf(out,"->{%g}\n",Dr.x); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 57 + Jr = J_JiJ(J1,i2,J2); + fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2); + fflush(out); + Jr.l1 = Jr.l2 = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_J_elements[] = { &ffi_type_slong, &ffi_type_slong, NULL }; + ffi_type ffi_type_J; + ffi_type_J.type = FFI_TYPE_STRUCT; + ffi_type_J.size = sizeof(J); + ffi_type_J.alignment = alignof_slot(J); + ffi_type_J.elements = ffi_type_J_elements; + ffi_type* argtypes[] = { &ffi_type_J, &ffi_type_sint, &ffi_type_J }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_J); + PREP_CALLBACK(cif,J_JiJ_simulator,(void*)&J_JiJ); + Jr = ((J (ABI_ATTR *) (J,int,J)) callback_code) (J1,i2,J2); + } + FREE_CALLBACK(); + fprintf(out,"->{%ld,%ld}\n",Jr.l1,Jr.l2); + fflush(out); +#endif + +#ifndef SKIP_EXTRA_STRUCTS +#if (!defined(DGTEST)) || DGTEST == 58 + Tr = T_TcT(T1,' ',T2); + fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]); + fflush(out); + Tr.c[0] = Tr.c[1] = Tr.c[2] = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_T_elements[] = { ??, NULL }; + ffi_type ffi_type_T; + ffi_type_T.type = FFI_TYPE_STRUCT; + ffi_type_T.size = sizeof(T); + ffi_type_T.alignment = alignof_slot(T); + ffi_type_T.elements = ffi_type_T_elements; + ffi_type* argtypes[] = { &ffi_type_T, &ffi_type_char, &ffi_type_T }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_T); + PREP_CALLBACK(cif,T_TcT_simulator,(void*)&T_TcT); + Tr = ((T (ABI_ATTR *) (T,char,T)) callback_code) (T1,' ',T2); + } + FREE_CALLBACK(); + fprintf(out,"->{\"%c%c%c\"}\n",Tr.c[0],Tr.c[1],Tr.c[2]); + fflush(out); +#endif + +#ifndef SKIP_X +#if (!defined(DGTEST)) || DGTEST == 59 + Xr = X_BcdB(B1,c2,d3,B2); + fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1); + fflush(out); + Xr.c[0]=Xr.c1='\0'; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* ffi_type_X_elements[] = { ??, NULL }; + ffi_type ffi_type_X; + ffi_type_X.type = FFI_TYPE_STRUCT; + ffi_type_X.size = sizeof(X); + ffi_type_X.alignment = alignof_slot(X); + ffi_type_X.elements = ffi_type_X_elements; + ffi_type* argtypes[] = { &ffi_type_X, &ffi_type_char, &ffi_type_double, &ffi_type_X }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_X); + PREP_CALLBACK(cif,X_BcdB_simulator,(void*)&X_BcdB); + Xr = ((X (ABI_ATTR *) (B,char,double,B)) callback_code) (B1,c2,d3,B2); + } + FREE_CALLBACK(); + fprintf(out,"->{\"%s\",'%c'}\n",Xr.c,Xr.c1); + fflush(out); +#endif +#endif +#endif + } + + + /* gpargs boundary tests */ + { + ffi_type* ffi_type_K_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL }; + ffi_type ffi_type_K; + ffi_type* ffi_type_L_elements[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, NULL }; + ffi_type ffi_type_L; + long lr; + long long llr; + float fr; + double dr; + + ffi_type_K.type = FFI_TYPE_STRUCT; + ffi_type_K.size = sizeof(K); + ffi_type_K.alignment = alignof_slot(K); + ffi_type_K.elements = ffi_type_K_elements; + + ffi_type_L.type = FFI_TYPE_STRUCT; + ffi_type_L.size = sizeof(L); + ffi_type_L.alignment = alignof_slot(L); + ffi_type_L.elements = ffi_type_L_elements; + +#if (!defined(DGTEST)) || DGTEST == 60 + lr = l_l0K(K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + PREP_CALLBACK(cif,l_l0K_simulator,(void*)l_l0K); + lr = ((long (ABI_ATTR *) (K,long)) callback_code) (K1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 61 + lr = l_l1K(l1,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + PREP_CALLBACK(cif,l_l1K_simulator,(void*)l_l1K); + lr = ((long (ABI_ATTR *) (long,K,long)) callback_code) (l1,K1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 62 + lr = l_l2K(l1,l2,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + PREP_CALLBACK(cif,l_l2K_simulator,(void*)l_l2K); + lr = ((long (ABI_ATTR *) (long,long,K,long)) callback_code) (l1,l2,K1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 63 + lr = l_l3K(l1,l2,l3,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + PREP_CALLBACK(cif,l_l3K_simulator,(void*)l_l3K); + lr = ((long (ABI_ATTR *) (long,long,long,K,long)) callback_code) (l1,l2,l3,K1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 64 + lr = l_l4K(l1,l2,l3,l4,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + PREP_CALLBACK(cif,l_l4K_simulator,(void*)l_l4K); + lr = ((long (ABI_ATTR *) (long,long,long,long,K,long)) callback_code) (l1,l2,l3,l4,K1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 65 + lr = l_l5K(l1,l2,l3,l4,l5,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + PREP_CALLBACK(cif,l_l5K_simulator,(void*)l_l5K); + lr = ((long (ABI_ATTR *) (long,long,long,long,long,K,long)) callback_code) (l1,l2,l3,l4,l5,K1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 66 + lr = l_l6K(l1,l2,l3,l4,l5,l6,K1,l9); + fprintf(out,"->%ld\n",lr); + fflush(out); + lr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_K, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slong); + PREP_CALLBACK(cif,l_l6K_simulator,(void*)l_l6K); + lr = ((long (ABI_ATTR *) (long,long,long,long,long,long,K,long)) callback_code) (l1,l2,l3,l4,l5,l6,K1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%ld\n",lr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 67 + fr = f_f17l3L(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,l6,l7,l8,L1); + fprintf(out,"->%g\n",fr); + fflush(out); + fr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_float, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_float); + PREP_CALLBACK(cif,f_f17l3L_simulator,(void*)&f_f17l3L); + fr = ((float (ABI_ATTR *) (float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,long,long,long,L)) callback_code) (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,l6,l7,l8,L1); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",fr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 68 + dr = d_d17l3L(d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17,l6,l7,l8,L1); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_double, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_L }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_d17l3L_simulator,(void*)&d_d17l3L); + dr = ((double (ABI_ATTR *) (double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,long,long,long,L)) callback_code) (d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12,d13,d14,d15,d16,d17,l6,l7,l8,L1); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 69 + llr = ll_l2ll(l1,l2,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + PREP_CALLBACK(cif,ll_l2ll_simulator,(void*)ll_l2ll); + llr = ((long long (ABI_ATTR *) (long,long,long long,long)) callback_code) (l1,l2,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 70 + llr = ll_l3ll(l1,l2,l3,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + PREP_CALLBACK(cif,ll_l3ll_simulator,(void*)ll_l3ll); + llr = ((long long (ABI_ATTR *) (long,long,long,long long,long)) callback_code) (l1,l2,l3,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 71 + llr = ll_l4ll(l1,l2,l3,l4,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + PREP_CALLBACK(cif,ll_l4ll_simulator,(void*)ll_l4ll); + llr = ((long long (ABI_ATTR *) (long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 72 + llr = ll_l5ll(l1,l2,l3,l4,l5,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + PREP_CALLBACK(cif,ll_l5ll_simulator,(void*)ll_l5ll); + llr = ((long long (ABI_ATTR *) (long,long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,l5,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 73 + llr = ll_l6ll(l1,l2,l3,l4,l5,l6,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + PREP_CALLBACK(cif,ll_l6ll_simulator,(void*)ll_l6ll); + llr = ((long long (ABI_ATTR *) (long,long,long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,l5,l6,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 74 + llr = ll_l7ll(l1,l2,l3,l4,l5,l6,l7,ll1,l9); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); + llr = 0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slonglong, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_slonglong); + PREP_CALLBACK(cif,ll_l7ll_simulator,(void*)ll_l7ll); + llr = ((long long (ABI_ATTR *) (long,long,long,long,long,long,long,long long,long)) callback_code) (l1,l2,l3,l4,l5,l6,l7,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->0x%lx%08lx\n",(long)(llr>>32),(long)(llr&0xffffffff)); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 75 + dr = d_l2d(l1,l2,ll1,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_l2d_simulator,(void*)d_l2d); + dr = ((double (ABI_ATTR *) (long,long,double,long)) callback_code) (l1,l2,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 76 + dr = d_l3d(l1,l2,l3,ll1,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_l3d_simulator,(void*)d_l3d); + dr = ((double (ABI_ATTR *) (long,long,long,double,long)) callback_code) (l1,l2,l3,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 77 + dr = d_l4d(l1,l2,l3,l4,ll1,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_l4d_simulator,(void*)d_l4d); + dr = ((double (ABI_ATTR *) (long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 78 + dr = d_l5d(l1,l2,l3,l4,l5,ll1,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_l5d_simulator,(void*)d_l5d); + dr = ((double (ABI_ATTR *) (long,long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,l5,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 79 + dr = d_l6d(l1,l2,l3,l4,l5,l6,ll1,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_l6d_simulator,(void*)d_l6d); + dr = ((double (ABI_ATTR *) (long,long,long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,l5,l6,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + +#if (!defined(DGTEST)) || DGTEST == 80 + dr = d_l7d(l1,l2,l3,l4,l5,l6,l7,ll1,l9); + fprintf(out,"->%g\n",dr); + fflush(out); + dr = 0.0; clear_traces(); + ALLOC_CALLBACK(); + { + ffi_type* argtypes[] = { &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_slong, &ffi_type_double, &ffi_type_slong }; + ffi_cif cif; + FFI_PREP_CIF(cif,argtypes,ffi_type_double); + PREP_CALLBACK(cif,d_l7d_simulator,(void*)d_l7d); + dr = ((double (ABI_ATTR *) (long,long,long,long,long,long,long,double,long)) callback_code) (l1,l2,l3,l4,l5,l6,l7,ll1,l9); + } + FREE_CALLBACK(); + fprintf(out,"->%g\n",dr); + fflush(out); +#endif + + } + + exit(0); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/testcases.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/testcases.c new file mode 100644 index 0000000..d25ebf4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.bhaible/testcases.c @@ -0,0 +1,743 @@ +/* + * Copyright 1993 Bill Triggs + * Copyright 1995-2017 Bruno Haible + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/* This file defines test functions of selected signatures, that exercise + dark corners of the various ABIs. */ + +#include + +FILE* out; + +#define uchar unsigned char +#define ushort unsigned short +#define uint unsigned int +#define ulong unsigned long + +typedef struct { char x; } Char; +typedef struct { short x; } Short; +typedef struct { int x; } Int; +typedef struct { long x; } Long; +typedef struct { float x; } Float; +typedef struct { double x; } Double; +typedef struct { char c; float f; } A; +typedef struct { double d; int i[3]; } B; +typedef struct { long l1; long l2; } J; +typedef struct { long l1; long l2; long l3; long l4; } K; +typedef struct { long l1; long l2; long l3; long l4; long l5; long l6; } L; +typedef struct { char x1; } Size1; +typedef struct { char x1; char x2; } Size2; +typedef struct { char x1; char x2; char x3; } Size3; +typedef struct { char x1; char x2; char x3; char x4; } Size4; +typedef struct { + char x1; char x2; char x3; char x4; char x5; char x6; char x7; +} Size7; +typedef struct { + char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8; +} Size8; +typedef struct { + char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8; + char x9; char x10; char x11; char x12; +} Size12; +typedef struct { + char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8; + char x9; char x10; char x11; char x12; char x13; char x14; char x15; +} Size15; +typedef struct { + char x1; char x2; char x3; char x4; char x5; char x6; char x7; char x8; + char x9; char x10; char x11; char x12; char x13; char x14; char x15; char x16; +} Size16; +typedef struct { char c[3]; } T; +typedef struct { char c[33],c1; } X; + +char c1='a', c2=127, c3=(char)128, c4=(char)255, c5=-1; +short s1=32767, s2=(short)32768, s3=3, s4=4, s5=5, s6=6, s7=7, s8=8, s9=9; +int i1=1, i2=2, i3=3, i4=4, i5=5, i6=6, i7=7, i8=8, i9=9, + i10=11, i11=12, i12=13, i13=14, i14=15, i15=16, i16=17; +long l1=1, l2=2, l3=3, l4=4, l5=5, l6=6, l7=7, l8=8, l9=9; +long long ll1 = 3875056143130689530LL; +float f1=0.1f, f2=0.2f, f3=0.3f, f4=0.4f, f5=0.5f, f6=0.6f, f7=0.7f, f8=0.8f, f9=0.9f, + f10=1.1f, f11=1.2f, f12=1.3f, f13=1.4f, f14=1.5f, f15=1.6f, f16=1.7f, f17=1.8f, + f18=1.9f, f19=2.1f, f20=2.2f, f21=2.3f, f22=2.4f, f23=2.5f, f24=2.6f; +double d1=0.1, d2=0.2, d3=0.3, d4=0.4, d5=0.5, d6=0.6, d7=0.7, d8=0.8, d9=0.9, + d10=1.1, d11=1.2, d12=1.3, d13=1.4, d14=1.5, d15=1.6, d16=1.7, d17=1.8; + +uchar uc1='a', uc2=127, uc3=128, uc4=255, uc5=(uchar)-1; +ushort us1=1, us2=2, us3=3, us4=4, us5=5, us6=6, us7=7, us8=8, us9=9; +uint ui1=1, ui2=2, ui3=3, ui4=4, ui5=5, ui6=6, ui7=7, ui8=8, ui9=9; +ulong ul1=1, ul2=2, ul3=3, ul4=4, ul5=5, ul6=6, ul7=7, ul8=8, ul9=9; + +char *str1="hello",str2[]="goodbye",*str3="still here?"; +Char C1={'A'}, C2={'B'}, C3={'C'}, C4={'\377'}, C5={(char)(-1)}; +Short S1={1}, S2={2}, S3={3}, S4={4}, S5={5}, S6={6}, S7={7}, S8={8}, S9={9}; +Int I1={1}, I2={2}, I3={3}, I4={4}, I5={5}, I6={6}, I7={7}, I8={8}, I9={9}; +Float F1={0.1f}, F2={0.2f}, F3={0.3f}, F4={0.4f}, F5={0.5f}, F6={0.6f}, F7={0.7f}, F8={0.8f}, F9={0.9f}; +Double D1={0.1}, D2={0.2}, D3={0.3}, D4={0.4}, D5={0.5}, D6={0.6}, D7={0.7}, D8={0.8}, D9={0.9}; + +A A1={'a',0.1f},A2={'b',0.2f},A3={'\377',0.3f}; +B B1={0.1,{1,2,3}},B2={0.2,{5,4,3}}; +J J1={47,11},J2={73,55}; +K K1={19,69,12,28}; +L L1={561,1105,1729,2465,2821,6601}; /* A002997 */ +Size1 Size1_1={'a'}; +Size2 Size2_1={'a','b'}; +Size3 Size3_1={'a','b','c'}; +Size4 Size4_1={'a','b','c','d'}; +Size7 Size7_1={'a','b','c','d','e','f','g'}; +Size8 Size8_1={'a','b','c','d','e','f','g','h'}; +Size12 Size12_1={'a','b','c','d','e','f','g','h','i','j','k','l'}; +Size15 Size15_1={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o'}; +Size16 Size16_1={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'}; +T T1={{'t','h','e'}},T2={{'f','o','x'}}; +X X1={"abcdefghijklmnopqrstuvwxyzABCDEF",'G'}, X2={"123",'9'}, X3={"return-return-return",'R'}; + +#if defined(__GNUC__) +#define __STDCALL__ __attribute__((stdcall)) +#define __THISCALL__ __attribute__((thiscall)) +#define __FASTCALL__ __attribute__((fastcall)) +#define __MSABI__ __attribute__((ms_abi)) +#else +#define __STDCALL__ __stdcall +#define __THISCALL__ __thiscall +#define __FASTCALL__ __fastcall +#endif + +#ifndef ABI_ATTR +#define ABI_ATTR +#endif + +/* void tests */ +void ABI_ATTR v_v (void) +{ + fprintf(out,"void f(void):\n"); + fflush(out); +} + +/* int tests */ +int ABI_ATTR i_v (void) +{ + int r=99; + fprintf(out,"int f(void):"); + fflush(out); + return r; +} +int ABI_ATTR i_i (int a) +{ + int r=a+1; + fprintf(out,"int f(int):(%d)",a); + fflush(out); + return r; +} +int ABI_ATTR i_i2 (int a, int b) +{ + int r=a+b; + fprintf(out,"int f(2*int):(%d,%d)",a,b); + fflush(out); + return r; +} +int ABI_ATTR i_i4 (int a, int b, int c, int d) +{ + int r=a+b+c+d; + fprintf(out,"int f(4*int):(%d,%d,%d,%d)",a,b,c,d); + fflush(out); + return r; +} +int ABI_ATTR i_i8 (int a, int b, int c, int d, int e, int f, int g, int h) +{ + int r=a+b+c+d+e+f+g+h; + fprintf(out,"int f(8*int):(%d,%d,%d,%d,%d,%d,%d,%d)",a,b,c,d,e,f,g,h); + fflush(out); + return r; +} +int ABI_ATTR i_i16 (int a, int b, int c, int d, int e, int f, int g, int h, + int i, int j, int k, int l, int m, int n, int o, int p) +{ + int r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p; + fprintf(out,"int f(16*int):(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)", + a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p); + fflush(out); + return r; +} + +/* float tests */ +float ABI_ATTR f_f (float a) +{ + float r=a+1.0f; + fprintf(out,"float f(float):(%g)",a); + fflush(out); + return r; +} +float ABI_ATTR f_f2 (float a, float b) +{ + float r=a+b; + fprintf(out,"float f(2*float):(%g,%g)",a,b); + fflush(out); + return r; +} +float ABI_ATTR f_f4 (float a, float b, float c, float d) +{ + float r=a+b+c+d; + fprintf(out,"float f(4*float):(%g,%g,%g,%g)",a,b,c,d); + fflush(out); + return r; +} +float ABI_ATTR f_f8 (float a, float b, float c, float d, float e, float f, + float g, float h) +{ + float r=a+b+c+d+e+f+g+h; + fprintf(out,"float f(8*float):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h); + fflush(out); + return r; +} +float ABI_ATTR f_f16 (float a, float b, float c, float d, float e, float f, float g, float h, + float i, float j, float k, float l, float m, float n, float o, float p) +{ + float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p; + fprintf(out,"float f(16*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p); + fflush(out); + return r; +} +float ABI_ATTR f_f24 (float a, float b, float c, float d, float e, float f, float g, float h, + float i, float j, float k, float l, float m, float n, float o, float p, + float q, float s, float t, float u, float v, float w, float x, float y) +{ + float r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+v+w+x+y; + fprintf(out,"float f(24*float):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,v,w,x,y); + fflush(out); + return r; +} + +/* double tests */ +double ABI_ATTR d_d (double a) +{ + double r=a+1.0; + fprintf(out,"double f(double):(%g)",a); + fflush(out); + return r; +} +double ABI_ATTR d_d2 (double a, double b) +{ + double r=a+b; + fprintf(out,"double f(2*double):(%g,%g)",a,b); + fflush(out); + return r; +} +double ABI_ATTR d_d4 (double a, double b, double c, double d) +{ + double r=a+b+c+d; + fprintf(out,"double f(4*double):(%g,%g,%g,%g)",a,b,c,d); + fflush(out); + return r; +} +double ABI_ATTR d_d8 (double a, double b, double c, double d, double e, double f, + double g, double h) +{ + double r=a+b+c+d+e+f+g+h; + fprintf(out,"double f(8*double):(%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h); + fflush(out); + return r; +} +double ABI_ATTR d_d16 (double a, double b, double c, double d, double e, double f, + double g, double h, double i, double j, double k, double l, + double m, double n, double o, double p) +{ + double r=a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p; + fprintf(out,"double f(16*double):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p); + fflush(out); + return r; +} + +/* pointer tests */ +void* ABI_ATTR vp_vpdpcpsp (void* a, double* b, char* c, Int* d) +{ + void* ret = (char*)b + 1; + fprintf(out,"void* f(void*,double*,char*,Int*):(0x%p,0x%p,0x%p,0x%p)",a,b,c,d); + fflush(out); + return ret; +} + +/* mixed number tests */ +uchar ABI_ATTR uc_ucsil (uchar a, ushort b, uint c, ulong d) +{ + uchar r = (uchar)-1; + fprintf(out,"uchar f(uchar,ushort,uint,ulong):(%u,%u,%u,%lu)",a,b,c,d); + fflush(out); + return r; +} +double ABI_ATTR d_iidd (int a, int b, double c, double d) +{ + double r = a+b+c+d; + fprintf(out,"double f(int,int,double,double):(%d,%d,%g,%g)",a,b,c,d); + fflush(out); + return r; +} +double ABI_ATTR d_iiidi (int a, int b, int c, double d, int e) +{ + double r = a+b+c+d+e; + fprintf(out,"double f(int,int,int,double,int):(%d,%d,%d,%g,%d)",a,b,c,d,e); + fflush(out); + return r; +} +double ABI_ATTR d_idid (int a, double b, int c, double d) +{ + double r = a+b+c+d; + fprintf(out,"double f(int,double,int,double):(%d,%g,%d,%g)",a,b,c,d); + fflush(out); + return r; +} +double ABI_ATTR d_fdi (float a, double b, int c) +{ + double r = a+b+c; + fprintf(out,"double f(float,double,int):(%g,%g,%d)",a,b,c); + fflush(out); + return r; +} +ushort ABI_ATTR us_cdcd (char a, double b, char c, double d) +{ + ushort r = (ushort)(a + b + c + d); + fprintf(out,"ushort f(char,double,char,double):('%c',%g,'%c',%g)",a,b,c,d); + fflush(out); + return r; +} + +long long ABI_ATTR ll_iiilli (int a, int b, int c, long long d, int e) +{ + long long r = (long long)(int)a+(long long)(int)b+(long long)(int)c+d+(long long)(int)e; + fprintf(out,"long long f(int,int,int,long long,int):(%d,%d,%d,0x%lx%08lx,%d)",a,b,c,(long)(d>>32),(long)(d&0xffffffff),e); + fflush(out); + return r; +} +long long ABI_ATTR ll_flli (float a, long long b, int c) +{ + long long r = (long long)(int)a + b + (long long)c; + fprintf(out,"long long f(float,long long,int):(%g,0x%lx%08lx,0x%lx)",a,(long)(b>>32),(long)(b&0xffffffff),(long)c); + fflush(out); + return r; +} + +float ABI_ATTR f_fi (float a, int z) +{ + float r = a+z; + fprintf(out,"float f(float,int):(%g,%d)",a,z); + fflush(out); + return r; +} +float ABI_ATTR f_f2i (float a, float b, int z) +{ + float r = a+b+z; + fprintf(out,"float f(2*float,int):(%g,%g,%d)",a,b,z); + fflush(out); + return r; +} +float ABI_ATTR f_f3i (float a, float b, float c, int z) +{ + float r = a+b+c+z; + fprintf(out,"float f(3*float,int):(%g,%g,%g,%d)",a,b,c,z); + fflush(out); + return r; +} +float ABI_ATTR f_f4i (float a, float b, float c, float d, int z) +{ + float r = a+b+c+d+z; + fprintf(out,"float f(4*float,int):(%g,%g,%g,%g,%d)",a,b,c,d,z); + fflush(out); + return r; +} +float ABI_ATTR f_f7i (float a, float b, float c, float d, float e, float f, float g, + int z) +{ + float r = a+b+c+d+e+f+g+z; + fprintf(out,"float f(7*float,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z); + fflush(out); + return r; +} +float ABI_ATTR f_f8i (float a, float b, float c, float d, float e, float f, float g, + float h, int z) +{ + float r = a+b+c+d+e+f+g+h+z; + fprintf(out,"float f(8*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z); + fflush(out); + return r; +} +float ABI_ATTR f_f12i (float a, float b, float c, float d, float e, float f, float g, + float h, float i, float j, float k, float l, int z) +{ + float r = a+b+c+d+e+f+g+h+i+j+k+l+z; + fprintf(out,"float f(12*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z); + fflush(out); + return r; +} +float ABI_ATTR f_f13i (float a, float b, float c, float d, float e, float f, float g, + float h, float i, float j, float k, float l, float m, int z) +{ + float r = a+b+c+d+e+f+g+h+i+j+k+l+m+z; + fprintf(out,"float f(13*float,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z); + fflush(out); + return r; +} + +double ABI_ATTR d_di (double a, int z) +{ + double r = a+z; + fprintf(out,"double f(double,int):(%g,%d)",a,z); + fflush(out); + return r; +} +double ABI_ATTR d_d2i (double a, double b, int z) +{ + double r = a+b+z; + fprintf(out,"double f(2*double,int):(%g,%g,%d)",a,b,z); + fflush(out); + return r; +} +double ABI_ATTR d_d3i (double a, double b, double c, int z) +{ + double r = a+b+c+z; + fprintf(out,"double f(3*double,int):(%g,%g,%g,%d)",a,b,c,z); + fflush(out); + return r; +} +double ABI_ATTR d_d4i (double a, double b, double c, double d, int z) +{ + double r = a+b+c+d+z; + fprintf(out,"double f(4*double,int):(%g,%g,%g,%g,%d)",a,b,c,d,z); + fflush(out); + return r; +} +double ABI_ATTR d_d7i (double a, double b, double c, double d, double e, double f, + double g, int z) +{ + double r = a+b+c+d+e+f+g+z; + fprintf(out,"double f(7*double,int):(%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,z); + fflush(out); + return r; +} +double ABI_ATTR d_d8i (double a, double b, double c, double d, double e, double f, + double g, double h, int z) +{ + double r = a+b+c+d+e+f+g+h+z; + fprintf(out,"double f(8*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,z); + fflush(out); + return r; +} +double ABI_ATTR d_d12i (double a, double b, double c, double d, double e, double f, + double g, double h, double i, double j, double k, double l, + int z) +{ + double r = a+b+c+d+e+f+g+h+i+j+k+l+z; + fprintf(out,"double f(12*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,z); + fflush(out); + return r; +} +double ABI_ATTR d_d13i (double a, double b, double c, double d, double e, double f, + double g, double h, double i, double j, double k, double l, + double m, int z) +{ + double r = a+b+c+d+e+f+g+h+i+j+k+l+m+z; + fprintf(out,"double f(13*double,int):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%d)",a,b,c,d,e,f,g,h,i,j,k,l,m,z); + fflush(out); + return r; +} + +/* small structure return tests */ +Size1 ABI_ATTR S1_v (void) +{ + fprintf(out,"Size1 f(void):"); + fflush(out); + return Size1_1; +} +Size2 ABI_ATTR S2_v (void) +{ + fprintf(out,"Size2 f(void):"); + fflush(out); + return Size2_1; +} +Size3 ABI_ATTR S3_v (void) +{ + fprintf(out,"Size3 f(void):"); + fflush(out); + return Size3_1; +} +Size4 ABI_ATTR S4_v (void) +{ + fprintf(out,"Size4 f(void):"); + fflush(out); + return Size4_1; +} +Size7 ABI_ATTR S7_v (void) +{ + fprintf(out,"Size7 f(void):"); + fflush(out); + return Size7_1; +} +Size8 ABI_ATTR S8_v (void) +{ + fprintf(out,"Size8 f(void):"); + fflush(out); + return Size8_1; +} +Size12 ABI_ATTR S12_v (void) +{ + fprintf(out,"Size12 f(void):"); + fflush(out); + return Size12_1; +} +Size15 ABI_ATTR S15_v (void) +{ + fprintf(out,"Size15 f(void):"); + fflush(out); + return Size15_1; +} +Size16 ABI_ATTR S16_v (void) +{ + fprintf(out,"Size16 f(void):"); + fflush(out); + return Size16_1; +} + +/* structure tests */ +Int ABI_ATTR I_III (Int a, Int b, Int c) +{ + Int r; + r.x = a.x + b.x + c.x; + fprintf(out,"Int f(Int,Int,Int):({%d},{%d},{%d})",a.x,b.x,c.x); + fflush(out); + return r; +} +Char ABI_ATTR C_CdC (Char a, double b, Char c) +{ + Char r; + r.x = (a.x + c.x)/2; + fprintf(out,"Char f(Char,double,Char):({'%c'},%g,{'%c'})",a.x,b,c.x); + fflush(out); + return r; +} +Float ABI_ATTR F_Ffd (Float a, float b, double c) +{ + Float r; + r.x = (float) (a.x + b + c); + fprintf(out,"Float f(Float,float,double):({%g},%g,%g)",a.x,b,c); + fflush(out); + return r; +} +Double ABI_ATTR D_fDd (float a, Double b, double c) +{ + Double r; + r.x = a + b.x + c; + fprintf(out,"Double f(float,Double,double):(%g,{%g},%g)",a,b.x,c); + fflush(out); + return r; +} +Double ABI_ATTR D_Dfd (Double a, float b, double c) +{ + Double r; + r.x = a.x + b + c; + fprintf(out,"Double f(Double,float,double):({%g},%g,%g)",a.x,b,c); + fflush(out); + return r; +} +J ABI_ATTR J_JiJ (J a, int b, J c) +{ + J r; + r.l1 = a.l1+c.l1; r.l2 = a.l2+b+c.l2; + fprintf(out,"J f(J,int,J):({%ld,%ld},%d,{%ld,%ld})",a.l1,a.l2,b,c.l1,c.l2); + fflush(out); + return r; +} +T ABI_ATTR T_TcT (T a, char b, T c) +{ + T r; + r.c[0]='b'; r.c[1]=c.c[1]; r.c[2]=c.c[2]; + fprintf(out,"T f(T,char,T):({\"%c%c%c\"},'%c',{\"%c%c%c\"})",a.c[0],a.c[1],a.c[2],b,c.c[0],c.c[1],c.c[2]); + fflush(out); + return r; +} +X ABI_ATTR X_BcdB (B a, char b, double c, B d) +{ + static X xr={"return val",'R'}; + X r; + r = xr; + r.c1 = b; + fprintf(out,"X f(B,char,double,B):({%g,{%d,%d,%d}},'%c',%g,{%g,{%d,%d,%d}})", + a.d,a.i[0],a.i[1],a.i[2],b,c,d.d,d.i[0],d.i[1],d.i[2]); + fflush(out); + return r; +} + +/* Test for cases where some argument (especially structure, 'long long', or + 'double') may be passed partially in general-purpose argument registers + and partially on the stack. Different ABIs pass between 4 and 8 arguments + (or none) in general-purpose argument registers. */ + +long ABI_ATTR l_l0K (K b, long c) +{ + long r = b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(K,long):(%ld,%ld,%ld,%ld,%ld)",b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + return r; +} +long ABI_ATTR l_l1K (long a1, K b, long c) +{ + long r = a1 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld)",a1,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + return r; +} +long ABI_ATTR l_l2K (long a1, long a2, K b, long c) +{ + long r = a1 + a2 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(2*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + return r; +} +long ABI_ATTR l_l3K (long a1, long a2, long a3, K b, long c) +{ + long r = a1 + a2 + a3 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(3*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + return r; +} +long ABI_ATTR l_l4K (long a1, long a2, long a3, long a4, K b, long c) +{ + long r = a1 + a2 + a3 + a4 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(4*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + return r; +} +long ABI_ATTR l_l5K (long a1, long a2, long a3, long a4, long a5, K b, long c) +{ + long r = a1 + a2 + a3 + a4 + a5 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(5*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + return r; +} +long ABI_ATTR l_l6K (long a1, long a2, long a3, long a4, long a5, long a6, K b, long c) +{ + long r = a1 + a2 + a3 + a4 + a5 + a6 + b.l1 + b.l2 + b.l3 + b.l4 + c; + fprintf(out,"long f(6*long,K,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a1,a2,a3,a4,a5,a6,b.l1,b.l2,b.l3,b.l4,c); + fflush(out); + return r; +} +/* These tests is crafted on the knowledge that for all known ABIs: + * 17 > number of floating-point argument registers, + * 3 < number of general-purpose argument registers < 3 + 6. */ +float ABI_ATTR f_f17l3L (float a, float b, float c, float d, float e, float f, float g, + float h, float i, float j, float k, float l, float m, float n, + float o, float p, float q, + long s, long t, long u, L z) +{ + float r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6; + fprintf(out,"float f(17*float,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6); + fflush(out); + return r; +} +double ABI_ATTR d_d17l3L (double a, double b, double c, double d, double e, double f, + double g, double h, double i, double j, double k, double l, + double m, double n, double o, double p, double q, + long s, long t, long u, L z) +{ + double r = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+s+t+u+z.l1+z.l2+z.l3+z.l4+z.l5+z.l6; + fprintf(out,"double f(17*double,3*int,L):(%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld)",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,s,t,u,z.l1,z.l2,z.l3,z.l4,z.l5,z.l6); + fflush(out); + return r; +} + +long long ABI_ATTR ll_l2ll (long a1, long a2, long long b, long c) +{ + long long r = (long long) (a1 + a2) + b + c; + fprintf(out,"long long f(2*long,long long,long):(%ld,%ld,0x%lx%08lx,%ld)",a1,a2,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + return r; +} +long long ABI_ATTR ll_l3ll (long a1, long a2, long a3, long long b, long c) +{ + long long r = (long long) (a1 + a2 + a3) + b + c; + fprintf(out,"long long f(3*long,long long,long):(%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + return r; +} +long long ABI_ATTR ll_l4ll (long a1, long a2, long a3, long a4, long long b, long c) +{ + long long r = (long long) (a1 + a2 + a3 + a4) + b + c; + fprintf(out,"long long f(4*long,long long,long):(%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + return r; +} +long long ABI_ATTR ll_l5ll (long a1, long a2, long a3, long a4, long a5, long long b, long c) +{ + long long r = (long long) (a1 + a2 + a3 + a4 + a5) + b + c; + fprintf(out,"long long f(5*long,long long,long):(%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + return r; +} +long long ABI_ATTR ll_l6ll (long a1, long a2, long a3, long a4, long a5, long a6, long long b, long c) +{ + long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6) + b + c; + fprintf(out,"long long f(6*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + return r; +} +long long ABI_ATTR ll_l7ll (long a1, long a2, long a3, long a4, long a5, long a6, long a7, long long b, long c) +{ + long long r = (long long) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c; + fprintf(out,"long long f(7*long,long long,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,0x%lx%08lx,%ld)",a1,a2,a3,a4,a5,a6,a7,(long)(b>>32),(long)(b&0xffffffff),c); + fflush(out); + return r; +} + +double ABI_ATTR d_l2d (long a1, long a2, double b, long c) +{ + double r = (double) (a1 + a2) + b + c; + fprintf(out,"double f(2*long,double,long):(%ld,%ld,%g,%ld)",a1,a2,b,c); + fflush(out); + return r; +} +double ABI_ATTR d_l3d (long a1, long a2, long a3, double b, long c) +{ + double r = (double) (a1 + a2 + a3) + b + c; + fprintf(out,"double f(3*long,double,long):(%ld,%ld,%ld,%g,%ld)",a1,a2,a3,b,c); + fflush(out); + return r; +} +double ABI_ATTR d_l4d (long a1, long a2, long a3, long a4, double b, long c) +{ + double r = (double) (a1 + a2 + a3 + a4) + b + c; + fprintf(out,"double f(4*long,double,long):(%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,b,c); + fflush(out); + return r; +} +double ABI_ATTR d_l5d (long a1, long a2, long a3, long a4, long a5, double b, long c) +{ + double r = (double) (a1 + a2 + a3 + a4 + a5) + b + c; + fprintf(out,"double f(5*long,double,long):(%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,b,c); + fflush(out); + return r; +} +double ABI_ATTR d_l6d (long a1, long a2, long a3, long a4, long a5, long a6, double b, long c) +{ + double r = (double) (a1 + a2 + a3 + a4 + a5 + a6) + b + c; + fprintf(out,"double f(6*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,b,c); + fflush(out); + return r; +} +double ABI_ATTR d_l7d (long a1, long a2, long a3, long a4, long a5, long a6, long a7, double b, long c) +{ + double r = (double) (a1 + a2 + a3 + a4 + a5 + a6 + a7) + b + c; + fprintf(out,"double f(7*long,double,long):(%ld,%ld,%ld,%ld,%ld,%ld,%ld,%g,%ld)",a1,a2,a3,a4,a5,a6,a7,b,c); + fflush(out); + return r; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/align_mixed.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/align_mixed.c new file mode 100644 index 0000000..5d4959c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/align_mixed.c @@ -0,0 +1,46 @@ +/* Area: ffi_call + Purpose: Check for proper argument alignment. + Limitations: none. + PR: none. + Originator: (from many_win32.c) */ + +/* { dg-do run } */ + +#include "ffitest.h" + +static float ABI_ATTR align_arguments(int i1, + double f2, + int i3, + double f4) +{ + return i1+f2+i3+f4; +} + +int main(void) +{ + ffi_cif cif; + ffi_type *args[4] = { + &ffi_type_sint, + &ffi_type_double, + &ffi_type_sint, + &ffi_type_double + }; + double fa[2] = {1,2}; + int ia[2] = {1,2}; + void *values[4] = {&ia[0], &fa[0], &ia[1], &fa[1]}; + float f, ff; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 4, + &ffi_type_float, args) == FFI_OK); + + ff = align_arguments(ia[0], fa[0], ia[1], fa[1]); + + ffi_call(&cif, FFI_FN(align_arguments), &f, values); + + if (f == ff) + printf("align arguments tests ok!\n"); + else + CHECK(0); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/align_stdcall.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/align_stdcall.c new file mode 100644 index 0000000..5e5cb86 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/align_stdcall.c @@ -0,0 +1,46 @@ +/* Area: ffi_call + Purpose: Check for proper argument alignment. + Limitations: none. + PR: none. + Originator: (from many_win32.c) */ + +/* { dg-do run } */ + +#include "ffitest.h" + +static float ABI_ATTR align_arguments(int i1, + double f2, + int i3, + double f4) +{ + return i1+f2+i3+f4; +} + +int main(void) +{ + ffi_cif cif; + ffi_type *args[4] = { + &ffi_type_sint, + &ffi_type_double, + &ffi_type_sint, + &ffi_type_double + }; + double fa[2] = {1,2}; + int ia[2] = {1,2}; + void *values[4] = {&ia[0], &fa[0], &ia[1], &fa[1]}; + float f, ff; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 4, + &ffi_type_float, args) == FFI_OK); + + ff = align_arguments(ia[0], fa[0], ia[1], fa[1]);; + + ffi_call(&cif, FFI_FN(align_arguments), &f, values); + + if (f == ff) + printf("align arguments tests ok!\n"); + else + CHECK(0); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/call.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/call.exp new file mode 100644 index 0000000..13ba2bd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/call.exp @@ -0,0 +1,54 @@ +# Copyright (C) 2003, 2006, 2009, 2010, 2014 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; see the file COPYING3. If not see +# . + +dg-init +libffi-init + +global srcdir subdir + +if { [string match $compiler_vendor "microsoft"] } { + # -wd4005 macro redefinition + # -wd4244 implicit conversion to type of smaller size + # -wd4305 truncation to smaller type + # -wd4477 printf %lu of uintptr_t + # -wd4312 implicit conversion to type of greater size + # -wd4311 pointer truncation to unsigned long + # -EHsc C++ Exception Handling (no SEH exceptions) + set additional_options "-wd4005 -wd4244 -wd4305 -wd4477 -wd4312 -wd4311 -EHsc"; +} else { + set additional_options ""; +} + +set tlist [lsort [glob -nocomplain -- $srcdir/$subdir/*.c]] + +run-many-tests $tlist $additional_options + +set tlist [lsort [glob -nocomplain -- $srcdir/$subdir/*.cc]] + +# No C++ for or1k +if { [istarget "or1k-*-*"] } { + foreach test $tlist { + unsupported "$test" + } +} else { + run-many-tests $tlist $additional_options +} + +dg-finish + +# Local Variables: +# tcl-indent-level:4 +# End: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/err_bad_typedef.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/err_bad_typedef.c new file mode 100644 index 0000000..bf60161 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/err_bad_typedef.c @@ -0,0 +1,26 @@ +/* Area: ffi_prep_cif + Purpose: Test error return for bad typedefs. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/6/2007 */ + +/* { dg-do run } */ + +#include "ffitest.h" + +int main (void) +{ + ffi_cif cif; + ffi_type* arg_types[1]; + + ffi_type badType = ffi_type_void; + + arg_types[0] = NULL; + + badType.size = 0; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, &badType, + arg_types) == FFI_BAD_TYPEDEF); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/ffitest.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/ffitest.h new file mode 100644 index 0000000..cfce1ad --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/ffitest.h @@ -0,0 +1,138 @@ +#include +#include +#include +#include +#include +#include "fficonfig.h" + +#if defined HAVE_STDINT_H +#include +#endif + +#if defined HAVE_INTTYPES_H +#include +#endif + +#define MAX_ARGS 256 + +#define CHECK(x) (void)(!(x) ? (abort(), 1) : 0) + +/* Define macros so that compilers other than gcc can run the tests. */ +#undef __UNUSED__ +#if defined(__GNUC__) +#define __UNUSED__ __attribute__((__unused__)) +#define __STDCALL__ __attribute__((stdcall)) +#define __THISCALL__ __attribute__((thiscall)) +#define __FASTCALL__ __attribute__((fastcall)) +#define __MSABI__ __attribute__((ms_abi)) +#else +#define __UNUSED__ +#define __STDCALL__ __stdcall +#define __THISCALL__ __thiscall +#define __FASTCALL__ __fastcall +#endif + +#ifndef ABI_NUM +#define ABI_NUM FFI_DEFAULT_ABI +#define ABI_ATTR +#endif + +/* Prefer MAP_ANON(YMOUS) to /dev/zero, since we don't need to keep a + file open. */ +#ifdef HAVE_MMAP_ANON +# undef HAVE_MMAP_DEV_ZERO + +# include +# ifndef MAP_FAILED +# define MAP_FAILED -1 +# endif +# if !defined (MAP_ANONYMOUS) && defined (MAP_ANON) +# define MAP_ANONYMOUS MAP_ANON +# endif +# define USING_MMAP + +#endif + +#ifdef HAVE_MMAP_DEV_ZERO + +# include +# ifndef MAP_FAILED +# define MAP_FAILED -1 +# endif +# define USING_MMAP + +#endif + +/* MinGW kludge. */ +#if defined(_WIN64) | defined(_WIN32) +#define PRIdLL "I64d" +#define PRIuLL "I64u" +#else +#define PRIdLL "lld" +#define PRIuLL "llu" +#endif + +/* Tru64 UNIX kludge. */ +#if defined(__alpha__) && defined(__osf__) +/* Tru64 UNIX V4.0 doesn't support %lld/%lld, but long is 64-bit. */ +#undef PRIdLL +#define PRIdLL "ld" +#undef PRIuLL +#define PRIuLL "lu" +#define PRId8 "hd" +#define PRIu8 "hu" +#define PRId64 "ld" +#define PRIu64 "lu" +#define PRIuPTR "lu" +#endif + +/* PA HP-UX kludge. */ +#if defined(__hppa__) && defined(__hpux__) && !defined(PRIuPTR) +#define PRIuPTR "lu" +#endif + +/* IRIX kludge. */ +#if defined(__sgi) +/* IRIX 6.5 provides all definitions, but only for C99 + compilations. */ +#define PRId8 "hhd" +#define PRIu8 "hhu" +#if (_MIPS_SZLONG == 32) +#define PRId64 "lld" +#define PRIu64 "llu" +#endif +/* This doesn't match , which always has "lld" here, but the + arguments are uint64_t, int64_t, which are unsigned long, long for + 64-bit in . */ +#if (_MIPS_SZLONG == 64) +#define PRId64 "ld" +#define PRIu64 "lu" +#endif +/* This doesn't match , which has "u" here, but the arguments + are uintptr_t, which is always unsigned long. */ +#define PRIuPTR "lu" +#endif + +/* Solaris < 10 kludge. */ +#if defined(__sun__) && defined(__svr4__) && !defined(PRIuPTR) +#if defined(__arch64__) || defined (__x86_64__) +#define PRIuPTR "lu" +#else +#define PRIuPTR "u" +#endif +#endif + +/* MSVC kludge. */ +#if defined _MSC_VER +#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) +#define PRIuPTR "lu" +#define PRIu8 "u" +#define PRId8 "d" +#define PRIu64 "I64u" +#define PRId64 "I64d" +#endif +#endif + +#ifndef PRIuPTR +#define PRIuPTR "u" +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float.c new file mode 100644 index 0000000..fbc272d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float.c @@ -0,0 +1,59 @@ +/* Area: ffi_call + Purpose: Check return value float. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ + +#include "ffitest.h" + +static int floating(int a, float b, double c, long double d) +{ + int i; + + i = (int) ((float)a/b + ((float)c/(float)d)); + + return i; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg rint; + + float f; + signed int si1; + double d; + long double ld; + + args[0] = &ffi_type_sint; + values[0] = &si1; + args[1] = &ffi_type_float; + values[1] = &f; + args[2] = &ffi_type_double; + values[2] = &d; + args[3] = &ffi_type_longdouble; + values[3] = &ld; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, + &ffi_type_sint, args) == FFI_OK); + + si1 = 6; + f = 3.14159; + d = (double)1.0/(double)3.0; + ld = 2.71828182846L; + + floating (si1, f, d, ld); + + ffi_call(&cif, FFI_FN(floating), &rint, values); + + printf ("%d vs %d\n", (int)rint, floating (si1, f, d, ld)); + + CHECK((int)rint == floating(si1, f, d, ld)); + + exit (0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float1.c new file mode 100644 index 0000000..c48493c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float1.c @@ -0,0 +1,60 @@ +/* Area: ffi_call + Purpose: Check return value double. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" +#include "float.h" + +#include + +typedef union +{ + double d; + unsigned char c[sizeof (double)]; +} value_type; + +#define CANARY 0xba + +static double dblit(float f) +{ + return f/3.0; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + float f; + value_type result[2]; + unsigned int i; + + args[0] = &ffi_type_float; + values[0] = &f; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_double, args) == FFI_OK); + + f = 3.14159; + + /* Put a canary in the return array. This is a regression test for + a buffer overrun. */ + memset(result[1].c, CANARY, sizeof (double)); + + ffi_call(&cif, FFI_FN(dblit), &result[0].d, values); + + /* These are not always the same!! Check for a reasonable delta */ + + CHECK(fabs(result[0].d - dblit(f)) < DBL_EPSILON); + + /* Check the canary. */ + for (i = 0; i < sizeof (double); ++i) + CHECK(result[1].c[i] == CANARY); + + exit(0); + +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float2.c new file mode 100644 index 0000000..57cd9e3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float2.c @@ -0,0 +1,61 @@ +/* Area: ffi_call + Purpose: Check return value long double. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ +/* { dg-do run } */ + +#include "ffitest.h" +#include "float.h" + +#include + +static long double ldblit(float f) +{ + return (long double) (((long double) f)/ (long double) 3.0); +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + float f; + long double ld; + long double original; + + args[0] = &ffi_type_float; + values[0] = &f; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_longdouble, args) == FFI_OK); + + f = 3.14159; + +#if defined(__sun) && defined(__GNUC__) + /* long double support under SunOS/gcc is pretty much non-existent. + You'll get the odd bus error in library routines like printf() */ +#else + printf ("%Lf\n", ldblit(f)); +#endif + + ld = 666; + ffi_call(&cif, FFI_FN(ldblit), &ld, values); + +#if defined(__sun) && defined(__GNUC__) + /* long double support under SunOS/gcc is pretty much non-existent. + You'll get the odd bus error in library routines like printf() */ +#else + printf ("%Lf, %Lf, %Lf, %Lf\n", ld, ldblit(f), ld - ldblit(f), LDBL_EPSILON); +#endif + + /* These are not always the same!! Check for a reasonable delta */ + original = ldblit(f); + if (((ld > original) ? (ld - original) : (original - ld)) < LDBL_EPSILON) + puts("long double return value tests ok!"); + else + CHECK(0); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float3.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float3.c new file mode 100644 index 0000000..bab3206 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float3.c @@ -0,0 +1,74 @@ +/* Area: ffi_call + Purpose: Check float arguments with different orders. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ + +#include "ffitest.h" +#include "float.h" + +#include + +static double floating_1(float a, double b, long double c) +{ + return (double) a + b + (double) c; +} + +static double floating_2(long double a, double b, float c) +{ + return (double) a + b + (double) c; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + double rd; + + float f; + double d; + long double ld; + + args[0] = &ffi_type_float; + values[0] = &f; + args[1] = &ffi_type_double; + values[1] = &d; + args[2] = &ffi_type_longdouble; + values[2] = &ld; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, + &ffi_type_double, args) == FFI_OK); + + f = 3.14159; + d = (double)1.0/(double)3.0; + ld = 2.71828182846L; + + floating_1 (f, d, ld); + + ffi_call(&cif, FFI_FN(floating_1), &rd, values); + + CHECK(fabs(rd - floating_1(f, d, ld)) < DBL_EPSILON); + + args[0] = &ffi_type_longdouble; + values[0] = &ld; + args[1] = &ffi_type_double; + values[1] = &d; + args[2] = &ffi_type_float; + values[2] = &f; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, + &ffi_type_double, args) == FFI_OK); + + floating_2 (ld, d, f); + + ffi_call(&cif, FFI_FN(floating_2), &rd, values); + + CHECK(fabs(rd - floating_2(ld, d, f)) < DBL_EPSILON); + + exit (0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float4.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float4.c new file mode 100644 index 0000000..0dd6d85 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float4.c @@ -0,0 +1,62 @@ +/* Area: ffi_call + Purpose: Check denorm double value. + Limitations: none. + PR: PR26483. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +/* { dg-options "-mieee" { target alpha*-*-* } } */ + +#include "ffitest.h" +#include "float.h" + +typedef union +{ + double d; + unsigned char c[sizeof (double)]; +} value_type; + +#define CANARY 0xba + +static double dblit(double d) +{ + return d; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + double d; + value_type result[2]; + unsigned int i; + + args[0] = &ffi_type_double; + values[0] = &d; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_double, args) == FFI_OK); + + d = DBL_MIN / 2; + + /* Put a canary in the return array. This is a regression test for + a buffer overrun. */ + memset(result[1].c, CANARY, sizeof (double)); + + ffi_call(&cif, FFI_FN(dblit), &result[0].d, values); + + /* The standard delta check doesn't work for denorms. Since we didn't do + any arithmetic, we should get the original result back, and hence an + exact check should be OK here. */ + + CHECK(result[0].d == dblit(d)); + + /* Check the canary. */ + for (i = 0; i < sizeof (double); ++i) + CHECK(result[1].c[i] == CANARY); + + exit(0); + +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float_va.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float_va.c new file mode 100644 index 0000000..5acff91 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/float_va.c @@ -0,0 +1,107 @@ +/* Area: fp and variadics + Purpose: check fp inputs and returns work on variadics, even the fixed params + Limitations: None + PR: none + Originator: 2011-01-25 + + Intended to stress the difference in ABI on ARM vfp +*/ + +/* { dg-do run } */ + +#include + +#include "ffitest.h" + +/* prints out all the parameters, and returns the sum of them all. + * 'x' is the number of variadic parameters all of which are double in this test + */ +double float_va_fn(unsigned int x, double y,...) +{ + double total=0.0; + va_list ap; + unsigned int i; + + total+=(double)x; + total+=y; + + printf("%u: %.1f :", x, y); + + va_start(ap, y); + for(i=0;i +#include +#include + +static float ABI_ATTR many(float f1, float f2, float f3, float f4, float f5, float f6, float f7, float f8, float f9, float f10, float f11, float f12, float f13) +{ +#if 0 + printf("%f %f %f %f %f %f %f %f %f %f %f %f %f\n", + (double) f1, (double) f2, (double) f3, (double) f4, (double) f5, + (double) f6, (double) f7, (double) f8, (double) f9, (double) f10, + (double) f11, (double) f12, (double) f13); +#endif + + return f1+f2+f3+f4+f5+f6+f7+f8+f9+f10+f11+f12+f13; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[13]; + void *values[13]; + float fa[13]; + float f, ff; + int i; + + for (i = 0; i < 13; i++) + { + args[i] = &ffi_type_float; + values[i] = &fa[i]; + fa[i] = (float) i; + } + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 13, + &ffi_type_float, args) == FFI_OK); + + ffi_call(&cif, FFI_FN(many), &f, values); + + ff = many(fa[0], fa[1], + fa[2], fa[3], + fa[4], fa[5], + fa[6], fa[7], + fa[8], fa[9], + fa[10],fa[11],fa[12]); + + if (fabs(f - ff) < FLT_EPSILON) + exit(0); + else + abort(); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/many2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/many2.c new file mode 100644 index 0000000..1c85746 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/many2.c @@ -0,0 +1,57 @@ +/* Area: ffi_call + Purpose: Check uint8_t arguments. + Limitations: none. + PR: PR45677. + Originator: Dan Witte 20100916 */ + +/* { dg-do run } */ + +#include "ffitest.h" + +#define NARGS 7 + +typedef unsigned char u8; + +#ifdef __GNUC__ +__attribute__((noinline)) +#endif +uint8_t +foo (uint8_t a, uint8_t b, uint8_t c, uint8_t d, + uint8_t e, uint8_t f, uint8_t g) +{ + return a + b + c + d + e + f + g; +} + +uint8_t ABI_ATTR +bar (uint8_t a, uint8_t b, uint8_t c, uint8_t d, + uint8_t e, uint8_t f, uint8_t g) +{ + return foo (a, b, c, d, e, f, g); +} + +int +main (void) +{ + ffi_type *ffitypes[NARGS]; + int i; + ffi_cif cif; + ffi_arg result = 0; + uint8_t args[NARGS]; + void *argptrs[NARGS]; + + for (i = 0; i < NARGS; ++i) + ffitypes[i] = &ffi_type_uint8; + + CHECK (ffi_prep_cif (&cif, ABI_NUM, NARGS, + &ffi_type_uint8, ffitypes) == FFI_OK); + + for (i = 0; i < NARGS; ++i) + { + args[i] = i; + argptrs[i] = &args[i]; + } + ffi_call (&cif, FFI_FN (bar), &result, argptrs); + + CHECK (result == 21); + return 0; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/many_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/many_double.c new file mode 100644 index 0000000..4ef8c8a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/many_double.c @@ -0,0 +1,70 @@ +/* Area: ffi_call + Purpose: Check return value double, with many arguments + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" + +#include +#include +#include + +static double many(double f1, + double f2, + double f3, + double f4, + double f5, + double f6, + double f7, + double f8, + double f9, + double f10, + double f11, + double f12, + double f13) +{ +#if 0 + printf("%f %f %f %f %f %f %f %f %f %f %f %f %f\n", + (double) f1, (double) f2, (double) f3, (double) f4, (double) f5, + (double) f6, (double) f7, (double) f8, (double) f9, (double) f10, + (double) f11, (double) f12, (double) f13); +#endif + + return ((f1/f2+f3/f4+f5/f6+f7/f8+f9/f10+f11/f12) * f13); +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[13]; + void *values[13]; + double fa[13]; + double f, ff; + int i; + + for (i = 0; i < 13; i++) + { + args[i] = &ffi_type_double; + values[i] = &fa[i]; + fa[i] = (double) i; + } + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 13, + &ffi_type_double, args) == FFI_OK); + + ffi_call(&cif, FFI_FN(many), &f, values); + + ff = many(fa[0], fa[1], + fa[2], fa[3], + fa[4], fa[5], + fa[6], fa[7], + fa[8], fa[9], + fa[10],fa[11],fa[12]); + if (fabs(f - ff) < FLT_EPSILON) + exit(0); + else + abort(); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/many_mixed.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/many_mixed.c new file mode 100644 index 0000000..85ec36e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/many_mixed.c @@ -0,0 +1,78 @@ +/* Area: ffi_call + Purpose: Check return value double, with many arguments + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" + +#include +#include +#include + +static double many(double f1, + double f2, + long int i1, + double f3, + double f4, + long int i2, + double f5, + double f6, + long int i3, + double f7, + double f8, + long int i4, + double f9, + double f10, + long int i5, + double f11, + double f12, + long int i6, + double f13) +{ + return ((double) (i1 + i2 + i3 + i4 + i5 + i6) + (f1/f2+f3/f4+f5/f6+f7/f8+f9/f10+f11/f12) * f13); +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[19]; + void *values[19]; + double fa[19]; + long int la[19]; + double f, ff; + int i; + + for (i = 0; i < 19; i++) + { + if( (i - 2) % 3 == 0) { + args[i] = &ffi_type_slong; + la[i] = (long int) i; + values[i] = &la[i]; + } + else { + args[i] = &ffi_type_double; + fa[i] = (double) i; + values[i] = &fa[i]; + } + } + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 19, + &ffi_type_double, args) == FFI_OK); + + ffi_call(&cif, FFI_FN(many), &f, values); + + ff = many(fa[0], fa[1], la[2], + fa[3], fa[4], la[5], + fa[6], fa[7], la[8], + fa[9], fa[10], la[11], + fa[12], fa[13], la[14], + fa[15], fa[16], la[17], + fa[18]); + if (fabs(f - ff) < FLT_EPSILON) + exit(0); + else + abort(); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/negint.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/negint.c new file mode 100644 index 0000000..6e2f26f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/negint.c @@ -0,0 +1,52 @@ +/* Area: ffi_call + Purpose: Check that negative integers are passed correctly. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ + +#include "ffitest.h" + +static int checking(int a, short b, signed char c) +{ + + return (a < 0 && b < 0 && c < 0); +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg rint; + + signed int si; + signed short ss; + signed char sc; + + args[0] = &ffi_type_sint; + values[0] = &si; + args[1] = &ffi_type_sshort; + values[1] = &ss; + args[2] = &ffi_type_schar; + values[2] = ≻ + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, + &ffi_type_sint, args) == FFI_OK); + + si = -6; + ss = -12; + sc = -1; + + checking (si, ss, sc); + + ffi_call(&cif, FFI_FN(checking), &rint, values); + + printf ("%d vs %d\n", (int)rint, checking (si, ss, sc)); + + CHECK(rint != 0); + + exit (0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/offsets.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/offsets.c new file mode 100644 index 0000000..23d88b3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/offsets.c @@ -0,0 +1,46 @@ +/* Area: Struct layout + Purpose: Test ffi_get_struct_offsets + Limitations: none. + PR: none. + Originator: Tom Tromey. */ + +/* { dg-do run } */ +#include "ffitest.h" +#include + +struct test_1 +{ + char c; + float f; + char c2; + int i; +}; + +int +main (void) +{ + ffi_type test_1_type; + ffi_type *test_1_elements[5]; + size_t test_1_offsets[4]; + + test_1_elements[0] = &ffi_type_schar; + test_1_elements[1] = &ffi_type_float; + test_1_elements[2] = &ffi_type_schar; + test_1_elements[3] = &ffi_type_sint; + test_1_elements[4] = NULL; + + test_1_type.size = 0; + test_1_type.alignment = 0; + test_1_type.type = FFI_TYPE_STRUCT; + test_1_type.elements = test_1_elements; + + CHECK (ffi_get_struct_offsets (FFI_DEFAULT_ABI, &test_1_type, test_1_offsets) + == FFI_OK); + CHECK (test_1_type.size == sizeof (struct test_1)); + CHECK (offsetof (struct test_1, c) == test_1_offsets[0]); + CHECK (offsetof (struct test_1, f) == test_1_offsets[1]); + CHECK (offsetof (struct test_1, c2) == test_1_offsets[2]); + CHECK (offsetof (struct test_1, i) == test_1_offsets[3]); + + return 0; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/pr1172638.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/pr1172638.c new file mode 100644 index 0000000..7da1621 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/pr1172638.c @@ -0,0 +1,127 @@ +/* Area: ffi_call + Purpose: Reproduce bug found in python ctypes + Limitations: none. + PR: Fedora 1174037 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct { + long x; + long y; +} POINT; + +typedef struct { + long left; + long top; + long right; + long bottom; +} RECT; + +static RECT ABI_ATTR pr_test(int i __UNUSED__, RECT ar __UNUSED__, + RECT* br __UNUSED__, POINT cp __UNUSED__, + RECT dr __UNUSED__, RECT *er __UNUSED__, + POINT fp, RECT gr __UNUSED__) +{ + RECT result; + + result.left = fp.x; + result.right = fp.y; + result.top = fp.x; + result.bottom = fp.y; + + return result; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_type point_type, rect_type; + ffi_type *point_type_elements[3]; + ffi_type *rect_type_elements[5]; + + int i; + POINT cp, fp; + RECT ar, br, dr, er, gr; + RECT *p1, *p2; + + /* This is a hack to get a properly aligned result buffer */ + RECT *rect_result = + (RECT *) malloc (sizeof(RECT)); + + point_type.size = 0; + point_type.alignment = 0; + point_type.type = FFI_TYPE_STRUCT; + point_type.elements = point_type_elements; + point_type_elements[0] = &ffi_type_slong; + point_type_elements[1] = &ffi_type_slong; + point_type_elements[2] = NULL; + + rect_type.size = 0; + rect_type.alignment = 0; + rect_type.type = FFI_TYPE_STRUCT; + rect_type.elements = rect_type_elements; + rect_type_elements[0] = &ffi_type_slong; + rect_type_elements[1] = &ffi_type_slong; + rect_type_elements[2] = &ffi_type_slong; + rect_type_elements[3] = &ffi_type_slong; + rect_type_elements[4] = NULL; + + args[0] = &ffi_type_sint; + args[1] = &rect_type; + args[2] = &ffi_type_pointer; + args[3] = &point_type; + args[4] = &rect_type; + args[5] = &ffi_type_pointer; + args[6] = &point_type; + args[7] = &rect_type; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 8, &rect_type, args) == FFI_OK); + + i = 1; + ar.left = 2; + ar.right = 3; + ar.top = 4; + ar.bottom = 5; + br.left = 6; + br.right = 7; + br.top = 8; + br.bottom = 9; + cp.x = 10; + cp.y = 11; + dr.left = 12; + dr.right = 13; + dr.top = 14; + dr.bottom = 15; + er.left = 16; + er.right = 17; + er.top = 18; + er.bottom = 19; + fp.x = 20; + fp.y = 21; + gr.left = 22; + gr.right = 23; + gr.top = 24; + gr.bottom = 25; + + values[0] = &i; + values[1] = &ar; + p1 = &br; + values[2] = &p1; + values[3] = &cp; + values[4] = &dr; + p2 = &er; + values[5] = &p2; + values[6] = &fp; + values[7] = &gr; + + ffi_call (&cif, FFI_FN(pr_test), rect_result, values); + + CHECK(rect_result->top == 20); + + free (rect_result); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/promotion.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/promotion.c new file mode 100644 index 0000000..4456161 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/promotion.c @@ -0,0 +1,59 @@ +/* Area: ffi_call + Purpose: Promotion test. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" +static int promotion(signed char sc, signed short ss, + unsigned char uc, unsigned short us) +{ + int r = (int) sc + (int) ss + (int) uc + (int) us; + + return r; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg rint; + signed char sc; + unsigned char uc; + signed short ss; + unsigned short us; + unsigned long ul; + + args[0] = &ffi_type_schar; + args[1] = &ffi_type_sshort; + args[2] = &ffi_type_uchar; + args[3] = &ffi_type_ushort; + values[0] = ≻ + values[1] = &ss; + values[2] = &uc; + values[3] = &us; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, + &ffi_type_sint, args) == FFI_OK); + + us = 0; + ul = 0; + + for (sc = (signed char) -127; + sc <= (signed char) 120; sc += 1) + for (ss = -30000; ss <= 30000; ss += 10000) + for (uc = (unsigned char) 0; + uc <= (unsigned char) 200; uc += 20) + for (us = 0; us <= 60000; us += 10000) + { + ul++; + ffi_call(&cif, FFI_FN(promotion), &rint, values); + CHECK((int)rint == (signed char) sc + (signed short) ss + + (unsigned char) uc + (unsigned short) us); + } + printf("%lu promotion tests run\n", ul); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/pyobjc-tc.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/pyobjc-tc.c new file mode 100644 index 0000000..e29bd6c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/pyobjc-tc.c @@ -0,0 +1,114 @@ +/* Area: ffi_call + Purpose: Check different structures. + Limitations: none. + PR: none. + Originator: Ronald Oussoren 20030824 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct Point { + float x; + float y; +} Point; + +typedef struct Size { + float h; + float w; +} Size; + +typedef struct Rect { + Point o; + Size s; +} Rect; + +int doit(int o, char* s, Point p, Rect r, int last) +{ + printf("CALLED WITH %d %s {%f %f} {{%f %f} {%f %f}} %d\n", + o, s, p.x, p.y, r.o.x, r.o.y, r.s.h, r.s.w, last); + return 42; +} + + +int main(void) +{ + ffi_type point_type; + ffi_type size_type; + ffi_type rect_type; + ffi_cif cif; + ffi_type* arglist[6]; + void* values[6]; + int r; + + /* + * First set up FFI types for the 3 struct types + */ + + point_type.size = 0; /*sizeof(Point);*/ + point_type.alignment = 0; /*__alignof__(Point);*/ + point_type.type = FFI_TYPE_STRUCT; + point_type.elements = malloc(3 * sizeof(ffi_type*)); + point_type.elements[0] = &ffi_type_float; + point_type.elements[1] = &ffi_type_float; + point_type.elements[2] = NULL; + + size_type.size = 0;/* sizeof(Size);*/ + size_type.alignment = 0;/* __alignof__(Size);*/ + size_type.type = FFI_TYPE_STRUCT; + size_type.elements = malloc(3 * sizeof(ffi_type*)); + size_type.elements[0] = &ffi_type_float; + size_type.elements[1] = &ffi_type_float; + size_type.elements[2] = NULL; + + rect_type.size = 0;/*sizeof(Rect);*/ + rect_type.alignment =0;/* __alignof__(Rect);*/ + rect_type.type = FFI_TYPE_STRUCT; + rect_type.elements = malloc(3 * sizeof(ffi_type*)); + rect_type.elements[0] = &point_type; + rect_type.elements[1] = &size_type; + rect_type.elements[2] = NULL; + + /* + * Create a CIF + */ + arglist[0] = &ffi_type_sint; + arglist[1] = &ffi_type_pointer; + arglist[2] = &point_type; + arglist[3] = &rect_type; + arglist[4] = &ffi_type_sint; + arglist[5] = NULL; + + r = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, + 5, &ffi_type_sint, arglist); + if (r != FFI_OK) { + abort(); + } + + + /* And call the function through the CIF */ + + { + Point p = { 1.0, 2.0 }; + Rect r = { { 9.0, 10.0}, { -1.0, -2.0 } }; + int o = 0; + int l = 42; + char* m = "myMethod"; + ffi_arg result; + + values[0] = &o; + values[1] = &m; + values[2] = &p; + values[3] = &r; + values[4] = &l; + values[5] = NULL; + + printf("CALLING WITH %d %s {%f %f} {{%f %f} {%f %f}} %d\n", + o, m, p.x, p.y, r.o.x, r.o.y, r.s.h, r.s.w, l); + + ffi_call(&cif, FFI_FN(doit), &result, values); + + printf ("The result is %d\n", (int)result); + + } + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_dbl.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_dbl.c new file mode 100644 index 0000000..fd07e50 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_dbl.c @@ -0,0 +1,36 @@ +/* Area: ffi_call + Purpose: Check return value double. + Limitations: none. + PR: none. + Originator: 20050212 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static double return_dbl(double dbl) +{ + printf ("%f\n", dbl); + return 2 * dbl; +} +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + double dbl, rdbl; + + args[0] = &ffi_type_double; + values[0] = &dbl; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_double, args) == FFI_OK); + + for (dbl = -127.3; dbl < 127; dbl++) + { + ffi_call(&cif, FFI_FN(return_dbl), &rdbl, values); + printf ("%f vs %f\n", rdbl, return_dbl(dbl)); + CHECK(rdbl == 2 * dbl); + } + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_dbl1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_dbl1.c new file mode 100644 index 0000000..0ea5d50 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_dbl1.c @@ -0,0 +1,43 @@ +/* Area: ffi_call + Purpose: Check return value double. + Limitations: none. + PR: none. + Originator: 20050212 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static double return_dbl(double dbl1, float fl2, unsigned int in3, double dbl4) +{ + return dbl1 + fl2 + in3 + dbl4; +} +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + double dbl1, dbl4, rdbl; + float fl2; + unsigned int in3; + args[0] = &ffi_type_double; + args[1] = &ffi_type_float; + args[2] = &ffi_type_uint; + args[3] = &ffi_type_double; + values[0] = &dbl1; + values[1] = &fl2; + values[2] = &in3; + values[3] = &dbl4; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, + &ffi_type_double, args) == FFI_OK); + dbl1 = 127.0; + fl2 = 128.0; + in3 = 255; + dbl4 = 512.7; + + ffi_call(&cif, FFI_FN(return_dbl), &rdbl, values); + printf ("%f vs %f\n", rdbl, return_dbl(dbl1, fl2, in3, dbl4)); + CHECK(rdbl == dbl1 + fl2 + in3 + dbl4); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_dbl2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_dbl2.c new file mode 100644 index 0000000..b3818f8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_dbl2.c @@ -0,0 +1,42 @@ +/* Area: ffi_call + Purpose: Check return value double. + Limitations: none. + PR: none. + Originator: 20050212 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static double return_dbl(double dbl1, double dbl2, unsigned int in3, double dbl4) +{ + return dbl1 + dbl2 + in3 + dbl4; +} +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + double dbl1, dbl2, dbl4, rdbl; + unsigned int in3; + args[0] = &ffi_type_double; + args[1] = &ffi_type_double; + args[2] = &ffi_type_uint; + args[3] = &ffi_type_double; + values[0] = &dbl1; + values[1] = &dbl2; + values[2] = &in3; + values[3] = &dbl4; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, + &ffi_type_double, args) == FFI_OK); + dbl1 = 127.0; + dbl2 = 128.0; + in3 = 255; + dbl4 = 512.7; + + ffi_call(&cif, FFI_FN(return_dbl), &rdbl, values); + printf ("%f vs %f\n", rdbl, return_dbl(dbl1, dbl2, in3, dbl4)); + CHECK(rdbl == dbl1 + dbl2 + in3 + dbl4); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl.c new file mode 100644 index 0000000..fb8a09e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl.c @@ -0,0 +1,35 @@ +/* Area: ffi_call + Purpose: Check return value float. + Limitations: none. + PR: none. + Originator: 20050212 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static float return_fl(float fl) +{ + return 2 * fl; +} +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + float fl, rfl; + + args[0] = &ffi_type_float; + values[0] = &fl; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_float, args) == FFI_OK); + + for (fl = -127.0; fl < 127; fl++) + { + ffi_call(&cif, FFI_FN(return_fl), &rfl, values); + printf ("%f vs %f\n", rfl, return_fl(fl)); + CHECK(rfl == 2 * fl); + } + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl1.c new file mode 100644 index 0000000..c3d92c2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl1.c @@ -0,0 +1,36 @@ +/* Area: ffi_call + Purpose: Check return value float. + Limitations: none. + PR: none. + Originator: 20050212 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static float return_fl(float fl1, float fl2) +{ + return fl1 + fl2; +} +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + float fl1, fl2, rfl; + + args[0] = &ffi_type_float; + args[1] = &ffi_type_float; + values[0] = &fl1; + values[1] = &fl2; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, + &ffi_type_float, args) == FFI_OK); + fl1 = 127.0; + fl2 = 128.0; + + ffi_call(&cif, FFI_FN(return_fl), &rfl, values); + printf ("%f vs %f\n", rfl, return_fl(fl1, fl2)); + CHECK(rfl == fl1 + fl2); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl2.c new file mode 100644 index 0000000..ddb976c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl2.c @@ -0,0 +1,49 @@ +/* Area: ffi_call + Purpose: Check return value float. + Limitations: none. + PR: none. + Originator: 20050212 */ + +/* { dg-do run } */ +#include "ffitest.h" + +/* Use volatile float to avoid false negative on ix86. See PR target/323. */ +static float return_fl(float fl1, float fl2, float fl3, float fl4) +{ + volatile float sum; + + sum = fl1 + fl2 + fl3 + fl4; + return sum; +} +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + float fl1, fl2, fl3, fl4, rfl; + volatile float sum; + + args[0] = &ffi_type_float; + args[1] = &ffi_type_float; + args[2] = &ffi_type_float; + args[3] = &ffi_type_float; + values[0] = &fl1; + values[1] = &fl2; + values[2] = &fl3; + values[3] = &fl4; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, + &ffi_type_float, args) == FFI_OK); + fl1 = 127.0; + fl2 = 128.0; + fl3 = 255.1; + fl4 = 512.7; + + ffi_call(&cif, FFI_FN(return_fl), &rfl, values); + printf ("%f vs %f\n", rfl, return_fl(fl1, fl2, fl3, fl4)); + + sum = fl1 + fl2 + fl3 + fl4; + CHECK(rfl == sum); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl3.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl3.c new file mode 100644 index 0000000..c37877b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_fl3.c @@ -0,0 +1,42 @@ +/* Area: ffi_call + Purpose: Check return value float. + Limitations: none. + PR: none. + Originator: 20050212 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static float return_fl(float fl1, float fl2, unsigned int in3, float fl4) +{ + return fl1 + fl2 + in3 + fl4; +} +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + float fl1, fl2, fl4, rfl; + unsigned int in3; + args[0] = &ffi_type_float; + args[1] = &ffi_type_float; + args[2] = &ffi_type_uint; + args[3] = &ffi_type_float; + values[0] = &fl1; + values[1] = &fl2; + values[2] = &in3; + values[3] = &fl4; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, + &ffi_type_float, args) == FFI_OK); + fl1 = 127.0; + fl2 = 128.0; + in3 = 255; + fl4 = 512.7; + + ffi_call(&cif, FFI_FN(return_fl), &rfl, values); + printf ("%f vs %f\n", rfl, return_fl(fl1, fl2, in3, fl4)); + CHECK(rfl == fl1 + fl2 + in3 + fl4); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ldl.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ldl.c new file mode 100644 index 0000000..52a92fe --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ldl.c @@ -0,0 +1,34 @@ +/* Area: ffi_call + Purpose: Check return value long double. + Limitations: none. + PR: none. + Originator: 20071113 */ +/* { dg-do run } */ + +#include "ffitest.h" + +static long double return_ldl(long double ldl) +{ + return 2*ldl; +} +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + long double ldl, rldl; + + args[0] = &ffi_type_longdouble; + values[0] = &ldl; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_longdouble, args) == FFI_OK); + + for (ldl = -127.0; ldl < 127.0; ldl++) + { + ffi_call(&cif, FFI_FN(return_ldl), &rldl, values); + CHECK(rldl == 2 * ldl); + } + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ll.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ll.c new file mode 100644 index 0000000..ea4a1e4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ll.c @@ -0,0 +1,41 @@ +/* Area: ffi_call + Purpose: Check return value long long. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" +static long long return_ll(long long ll) +{ + return ll; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + long long rlonglong; + long long ll; + + args[0] = &ffi_type_sint64; + values[0] = ≪ + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_sint64, args) == FFI_OK); + + for (ll = 0LL; ll < 100LL; ll++) + { + ffi_call(&cif, FFI_FN(return_ll), &rlonglong, values); + CHECK(rlonglong == ll); + } + + for (ll = 55555555555000LL; ll < 55555555555100LL; ll++) + { + ffi_call(&cif, FFI_FN(return_ll), &rlonglong, values); + CHECK(rlonglong == ll); + } + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ll1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ll1.c new file mode 100644 index 0000000..593e8a3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ll1.c @@ -0,0 +1,43 @@ +/* Area: ffi_call + Purpose: Check if long long are passed in the corresponding regs on ppc. + Limitations: none. + PR: 20104. + Originator: 20050222 */ + +/* { dg-do run } */ +/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */ +#include "ffitest.h" +static long long return_ll(int ll0, long long ll1, int ll2) +{ + return ll0 + ll1 + ll2; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + long long rlonglong; + long long ll1; + unsigned ll0, ll2; + + args[0] = &ffi_type_sint; + args[1] = &ffi_type_sint64; + args[2] = &ffi_type_sint; + values[0] = &ll0; + values[1] = &ll1; + values[2] = &ll2; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, + &ffi_type_sint64, args) == FFI_OK); + + ll0 = 11111111; + ll1 = 11111111111000LL; + ll2 = 11111111; + + ffi_call(&cif, FFI_FN(return_ll), &rlonglong, values); + printf("res: %" PRIdLL ", %" PRIdLL "\n", rlonglong, ll0 + ll1 + ll2); + /* { dg-output "res: 11111133333222, 11111133333222" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_sc.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_sc.c new file mode 100644 index 0000000..a36cf3e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_sc.c @@ -0,0 +1,36 @@ +/* Area: ffi_call + Purpose: Check return value signed char. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" + +static signed char return_sc(signed char sc) +{ + return sc; +} +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg rint; + signed char sc; + + args[0] = &ffi_type_schar; + values[0] = ≻ + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_schar, args) == FFI_OK); + + for (sc = (signed char) -127; + sc < (signed char) 127; sc++) + { + ffi_call(&cif, FFI_FN(return_sc), &rint, values); + CHECK((signed char)rint == sc); + } + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_sl.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_sl.c new file mode 100644 index 0000000..f0fd345 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_sl.c @@ -0,0 +1,38 @@ +/* Area: ffi_call + Purpose: Check if long as return type is handled correctly. + Limitations: none. + PR: none. + */ + +/* { dg-do run } */ +#include "ffitest.h" +static long return_sl(long l1, long l2) +{ + return l1 - l2; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg res; + unsigned long l1, l2; + + args[0] = &ffi_type_slong; + args[1] = &ffi_type_slong; + values[0] = &l1; + values[1] = &l2; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, + &ffi_type_slong, args) == FFI_OK); + + l1 = 1073741823L; + l2 = 1073741824L; + + ffi_call(&cif, FFI_FN(return_sl), &res, values); + printf("res: %ld, %ld\n", (long)res, l1 - l2); + /* { dg-output "res: -1, -1" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_uc.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_uc.c new file mode 100644 index 0000000..6fe5546 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_uc.c @@ -0,0 +1,38 @@ +/* Area: ffi_call + Purpose: Check return value unsigned char. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" + +static unsigned char return_uc(unsigned char uc) +{ + return uc; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg rint; + + unsigned char uc; + + args[0] = &ffi_type_uchar; + values[0] = &uc; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_uchar, args) == FFI_OK); + + for (uc = (unsigned char) '\x00'; + uc < (unsigned char) '\xff'; uc++) + { + ffi_call(&cif, FFI_FN(return_uc), &rint, values); + CHECK((unsigned char)rint == uc); + } + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ul.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ul.c new file mode 100644 index 0000000..12b266f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/return_ul.c @@ -0,0 +1,38 @@ +/* Area: ffi_call + Purpose: Check if unsigned long as return type is handled correctly. + Limitations: none. + PR: none. + Originator: 20060724 */ + +/* { dg-do run } */ +#include "ffitest.h" +static unsigned long return_ul(unsigned long ul1, unsigned long ul2) +{ + return ul1 + ul2; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg res; + unsigned long ul1, ul2; + + args[0] = &ffi_type_ulong; + args[1] = &ffi_type_ulong; + values[0] = &ul1; + values[1] = &ul2; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, + &ffi_type_ulong, args) == FFI_OK); + + ul1 = 1073741823L; + ul2 = 1073741824L; + + ffi_call(&cif, FFI_FN(return_ul), &res, values); + printf("res: %lu, %lu\n", (unsigned long)res, ul1 + ul2); + /* { dg-output "res: 2147483647, 2147483647" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen.c new file mode 100644 index 0000000..35b70ea --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen.c @@ -0,0 +1,44 @@ +/* Area: ffi_call + Purpose: Check strlen function call. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" + +static size_t ABI_ATTR my_strlen(char *s) +{ + return (strlen(s)); +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg rint; + char *s; + + args[0] = &ffi_type_pointer; + values[0] = (void*) &s; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, + &ffi_type_sint, args) == FFI_OK); + + s = "a"; + ffi_call(&cif, FFI_FN(my_strlen), &rint, values); + CHECK(rint == 1); + + s = "1234567"; + ffi_call(&cif, FFI_FN(my_strlen), &rint, values); + CHECK(rint == 7); + + s = "1234567890123456789012345"; + ffi_call(&cif, FFI_FN(my_strlen), &rint, values); + CHECK(rint == 25); + + exit (0); +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen2.c new file mode 100644 index 0000000..96282bc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen2.c @@ -0,0 +1,49 @@ +/* Area: ffi_call + Purpose: Check strlen function call with additional arguments. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ + +#include "ffitest.h" + +static size_t ABI_ATTR my_f(char *s, float a) +{ + return (size_t) ((int) strlen(s) + (int) a); +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg rint; + char *s; + float v2; + args[0] = &ffi_type_pointer; + args[1] = &ffi_type_float; + values[0] = (void*) &s; + values[1] = (void*) &v2; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 2, + &ffi_type_sint, args) == FFI_OK); + + s = "a"; + v2 = 0.0; + ffi_call(&cif, FFI_FN(my_f), &rint, values); + CHECK(rint == 1); + + s = "1234567"; + v2 = -1.0; + ffi_call(&cif, FFI_FN(my_f), &rint, values); + CHECK(rint == 6); + + s = "1234567890123456789012345"; + v2 = 1.0; + ffi_call(&cif, FFI_FN(my_f), &rint, values); + CHECK(rint == 26); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen3.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen3.c new file mode 100644 index 0000000..beba86e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen3.c @@ -0,0 +1,49 @@ +/* Area: ffi_call + Purpose: Check strlen function call with additional arguments. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ + +#include "ffitest.h" + +static size_t ABI_ATTR my_f(float a, char *s) +{ + return (size_t) ((int) strlen(s) + (int) a); +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg rint; + char *s; + float v2; + args[1] = &ffi_type_pointer; + args[0] = &ffi_type_float; + values[1] = (void*) &s; + values[0] = (void*) &v2; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 2, + &ffi_type_sint, args) == FFI_OK); + + s = "a"; + v2 = 0.0; + ffi_call(&cif, FFI_FN(my_f), &rint, values); + CHECK(rint == 1); + + s = "1234567"; + v2 = -1.0; + ffi_call(&cif, FFI_FN(my_f), &rint, values); + CHECK(rint == 6); + + s = "1234567890123456789012345"; + v2 = 1.0; + ffi_call(&cif, FFI_FN(my_f), &rint, values); + CHECK(rint == 26); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen4.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen4.c new file mode 100644 index 0000000..d5d42b4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/strlen4.c @@ -0,0 +1,55 @@ +/* Area: ffi_call + Purpose: Check strlen function call with additional arguments. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ + +#include "ffitest.h" + +static size_t ABI_ATTR my_f(float a, char *s, int i) +{ + return (size_t) ((int) strlen(s) + (int) a + i); +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg rint; + char *s; + int v1; + float v2; + args[2] = &ffi_type_sint; + args[1] = &ffi_type_pointer; + args[0] = &ffi_type_float; + values[2] = (void*) &v1; + values[1] = (void*) &s; + values[0] = (void*) &v2; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 3, + &ffi_type_sint, args) == FFI_OK); + + s = "a"; + v1 = 1; + v2 = 0.0; + ffi_call(&cif, FFI_FN(my_f), &rint, values); + CHECK(rint == 2); + + s = "1234567"; + v2 = -1.0; + v1 = -2; + ffi_call(&cif, FFI_FN(my_f), &rint, values); + CHECK(rint == 4); + + s = "1234567890123456789012345"; + v2 = 1.0; + v1 = 2; + ffi_call(&cif, FFI_FN(my_f), &rint, values); + CHECK(rint == 28); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct1.c new file mode 100644 index 0000000..c13e23f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct1.c @@ -0,0 +1,67 @@ +/* Area: ffi_call + Purpose: Check structures. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct +{ + unsigned char uc; + double d; + unsigned int ui; +} test_structure_1; + +static test_structure_1 ABI_ATTR struct1(test_structure_1 ts) +{ + ts.uc++; + ts.d--; + ts.ui++; + + return ts; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_type ts1_type; + ffi_type *ts1_type_elements[4]; + + test_structure_1 ts1_arg; + + /* This is a hack to get a properly aligned result buffer */ + test_structure_1 *ts1_result = + (test_structure_1 *) malloc (sizeof(test_structure_1)); + + ts1_type.size = 0; + ts1_type.alignment = 0; + ts1_type.type = FFI_TYPE_STRUCT; + ts1_type.elements = ts1_type_elements; + ts1_type_elements[0] = &ffi_type_uchar; + ts1_type_elements[1] = &ffi_type_double; + ts1_type_elements[2] = &ffi_type_uint; + ts1_type_elements[3] = NULL; + + args[0] = &ts1_type; + values[0] = &ts1_arg; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, + &ts1_type, args) == FFI_OK); + + ts1_arg.uc = '\x01'; + ts1_arg.d = 3.14159; + ts1_arg.ui = 555; + + ffi_call(&cif, FFI_FN(struct1), ts1_result, values); + + CHECK(ts1_result->ui == 556); + CHECK(ts1_result->d == 3.14159 - 1); + + free (ts1_result); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct10.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct10.c new file mode 100644 index 0000000..17b1377 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct10.c @@ -0,0 +1,57 @@ +/* Area: ffi_call + Purpose: Check structures. + Limitations: none. + PR: none. + Originator: Sergei Trofimovich + + The test originally discovered in ruby's bindings + for ffi in https://bugs.gentoo.org/634190 */ + +/* { dg-do run } */ +#include "ffitest.h" + +struct s { + int s32; + float f32; + signed char s8; +}; + +struct s make_s(void) { + struct s r; + r.s32 = 0x1234; + r.f32 = 7.0; + r.s8 = 0x78; + return r; +} + +int main() { + ffi_cif cif; + struct s r; + ffi_type rtype; + ffi_type* s_fields[] = { + &ffi_type_sint, + &ffi_type_float, + &ffi_type_schar, + NULL, + }; + + rtype.size = 0; + rtype.alignment = 0, + rtype.type = FFI_TYPE_STRUCT, + rtype.elements = s_fields, + + r.s32 = 0xbad; + r.f32 = 999.999; + r.s8 = 0x51; + + // Here we emulate the following call: + //r = make_s(); + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, &rtype, NULL) == FFI_OK); + ffi_call(&cif, FFI_FN(make_s), &r, NULL); + + CHECK(r.s32 == 0x1234); + CHECK(r.f32 == 7.0); + CHECK(r.s8 == 0x78); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct2.c new file mode 100644 index 0000000..5077a5e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct2.c @@ -0,0 +1,67 @@ +/* Area: ffi_call + Purpose: Check structures. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct +{ + double d1; + double d2; +} test_structure_2; + +static test_structure_2 ABI_ATTR struct2(test_structure_2 ts) +{ + ts.d1--; + ts.d2--; + + return ts; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + test_structure_2 ts2_arg; + ffi_type ts2_type; + ffi_type *ts2_type_elements[3]; + + /* This is a hack to get a properly aligned result buffer */ + test_structure_2 *ts2_result = + (test_structure_2 *) malloc (sizeof(test_structure_2)); + + ts2_type.size = 0; + ts2_type.alignment = 0; + ts2_type.type = FFI_TYPE_STRUCT; + ts2_type.elements = ts2_type_elements; + ts2_type_elements[0] = &ffi_type_double; + ts2_type_elements[1] = &ffi_type_double; + ts2_type_elements[2] = NULL; + + args[0] = &ts2_type; + values[0] = &ts2_arg; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts2_type, args) == FFI_OK); + + ts2_arg.d1 = 5.55; + ts2_arg.d2 = 6.66; + + printf ("%g\n", ts2_arg.d1); + printf ("%g\n", ts2_arg.d2); + + ffi_call(&cif, FFI_FN(struct2), ts2_result, values); + + printf ("%g\n", ts2_result->d1); + printf ("%g\n", ts2_result->d2); + + CHECK(ts2_result->d1 == 5.55 - 1); + CHECK(ts2_result->d2 == 6.66 - 1); + + free (ts2_result); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct3.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct3.c new file mode 100644 index 0000000..7eba0ea --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct3.c @@ -0,0 +1,60 @@ +/* Area: ffi_call + Purpose: Check structures. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct +{ + int si; +} test_structure_3; + +static test_structure_3 ABI_ATTR struct3(test_structure_3 ts) +{ + ts.si = -(ts.si*2); + + return ts; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + int compare_value; + ffi_type ts3_type; + ffi_type *ts3_type_elements[2]; + + test_structure_3 ts3_arg; + test_structure_3 *ts3_result = + (test_structure_3 *) malloc (sizeof(test_structure_3)); + + ts3_type.size = 0; + ts3_type.alignment = 0; + ts3_type.type = FFI_TYPE_STRUCT; + ts3_type.elements = ts3_type_elements; + ts3_type_elements[0] = &ffi_type_sint; + ts3_type_elements[1] = NULL; + + args[0] = &ts3_type; + values[0] = &ts3_arg; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, + &ts3_type, args) == FFI_OK); + + ts3_arg.si = -123; + compare_value = ts3_arg.si; + + ffi_call(&cif, FFI_FN(struct3), ts3_result, values); + + printf ("%d %d\n", ts3_result->si, -(compare_value*2)); + + CHECK(ts3_result->si == -(compare_value*2)); + + free (ts3_result); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct4.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct4.c new file mode 100644 index 0000000..66a9551 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct4.c @@ -0,0 +1,64 @@ +/* Area: ffi_call + Purpose: Check structures. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct +{ + unsigned ui1; + unsigned ui2; + unsigned ui3; +} test_structure_4; + +static test_structure_4 ABI_ATTR struct4(test_structure_4 ts) +{ + ts.ui3 = ts.ui1 * ts.ui2 * ts.ui3; + + return ts; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_type ts4_type; + ffi_type *ts4_type_elements[4]; + + test_structure_4 ts4_arg; + + /* This is a hack to get a properly aligned result buffer */ + test_structure_4 *ts4_result = + (test_structure_4 *) malloc (sizeof(test_structure_4)); + + ts4_type.size = 0; + ts4_type.alignment = 0; + ts4_type.type = FFI_TYPE_STRUCT; + ts4_type.elements = ts4_type_elements; + ts4_type_elements[0] = &ffi_type_uint; + ts4_type_elements[1] = &ffi_type_uint; + ts4_type_elements[2] = &ffi_type_uint; + ts4_type_elements[3] = NULL; + + args[0] = &ts4_type; + values[0] = &ts4_arg; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts4_type, args) == FFI_OK); + + ts4_arg.ui1 = 2; + ts4_arg.ui2 = 3; + ts4_arg.ui3 = 4; + + ffi_call (&cif, FFI_FN(struct4), ts4_result, values); + + CHECK(ts4_result->ui3 == 2U * 3U * 4U); + + + free (ts4_result); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct5.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct5.c new file mode 100644 index 0000000..23e2a3f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct5.c @@ -0,0 +1,66 @@ +/* Area: ffi_call + Purpose: Check structures. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" +typedef struct +{ + char c1; + char c2; +} test_structure_5; + +static test_structure_5 ABI_ATTR struct5(test_structure_5 ts1, test_structure_5 ts2) +{ + ts1.c1 += ts2.c1; + ts1.c2 -= ts2.c2; + + return ts1; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_type ts5_type; + ffi_type *ts5_type_elements[3]; + + test_structure_5 ts5_arg1, ts5_arg2; + + /* This is a hack to get a properly aligned result buffer */ + test_structure_5 *ts5_result = + (test_structure_5 *) malloc (sizeof(test_structure_5)); + + ts5_type.size = 0; + ts5_type.alignment = 0; + ts5_type.type = FFI_TYPE_STRUCT; + ts5_type.elements = ts5_type_elements; + ts5_type_elements[0] = &ffi_type_schar; + ts5_type_elements[1] = &ffi_type_schar; + ts5_type_elements[2] = NULL; + + args[0] = &ts5_type; + args[1] = &ts5_type; + values[0] = &ts5_arg1; + values[1] = &ts5_arg2; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 2, &ts5_type, args) == FFI_OK); + + ts5_arg1.c1 = 2; + ts5_arg1.c2 = 6; + ts5_arg2.c1 = 5; + ts5_arg2.c2 = 3; + + ffi_call (&cif, FFI_FN(struct5), ts5_result, values); + + CHECK(ts5_result->c1 == 7); + CHECK(ts5_result->c2 == 3); + + + free (ts5_result); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct6.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct6.c new file mode 100644 index 0000000..173c66e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct6.c @@ -0,0 +1,64 @@ +/* Area: ffi_call + Purpose: Check structures. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" +typedef struct +{ + float f; + double d; +} test_structure_6; + +static test_structure_6 ABI_ATTR struct6 (test_structure_6 ts) +{ + ts.f += 1; + ts.d += 1; + + return ts; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_type ts6_type; + ffi_type *ts6_type_elements[3]; + + test_structure_6 ts6_arg; + + /* This is a hack to get a properly aligned result buffer */ + test_structure_6 *ts6_result = + (test_structure_6 *) malloc (sizeof(test_structure_6)); + + ts6_type.size = 0; + ts6_type.alignment = 0; + ts6_type.type = FFI_TYPE_STRUCT; + ts6_type.elements = ts6_type_elements; + ts6_type_elements[0] = &ffi_type_float; + ts6_type_elements[1] = &ffi_type_double; + ts6_type_elements[2] = NULL; + + args[0] = &ts6_type; + values[0] = &ts6_arg; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts6_type, args) == FFI_OK); + + ts6_arg.f = 5.55f; + ts6_arg.d = 6.66; + + printf ("%g\n", ts6_arg.f); + printf ("%g\n", ts6_arg.d); + + ffi_call(&cif, FFI_FN(struct6), ts6_result, values); + + CHECK(ts6_result->f == 5.55f + 1); + CHECK(ts6_result->d == 6.66 + 1); + + free (ts6_result); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct7.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct7.c new file mode 100644 index 0000000..badc7e0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct7.c @@ -0,0 +1,74 @@ +/* Area: ffi_call + Purpose: Check structures. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" +typedef struct +{ + float f1; + float f2; + double d; +} test_structure_7; + +static test_structure_7 ABI_ATTR struct7 (test_structure_7 ts) +{ + ts.f1 += 1; + ts.f2 += 1; + ts.d += 1; + + return ts; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_type ts7_type; + ffi_type *ts7_type_elements[4]; + + test_structure_7 ts7_arg; + + /* This is a hack to get a properly aligned result buffer */ + test_structure_7 *ts7_result = + (test_structure_7 *) malloc (sizeof(test_structure_7)); + + ts7_type.size = 0; + ts7_type.alignment = 0; + ts7_type.type = FFI_TYPE_STRUCT; + ts7_type.elements = ts7_type_elements; + ts7_type_elements[0] = &ffi_type_float; + ts7_type_elements[1] = &ffi_type_float; + ts7_type_elements[2] = &ffi_type_double; + ts7_type_elements[3] = NULL; + + args[0] = &ts7_type; + values[0] = &ts7_arg; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts7_type, args) == FFI_OK); + + ts7_arg.f1 = 5.55f; + ts7_arg.f2 = 55.5f; + ts7_arg.d = 6.66; + + printf ("%g\n", ts7_arg.f1); + printf ("%g\n", ts7_arg.f2); + printf ("%g\n", ts7_arg.d); + + ffi_call(&cif, FFI_FN(struct7), ts7_result, values); + + printf ("%g\n", ts7_result->f1); + printf ("%g\n", ts7_result->f2); + printf ("%g\n", ts7_result->d); + + CHECK(ts7_result->f1 == 5.55f + 1); + CHECK(ts7_result->f2 == 55.5f + 1); + CHECK(ts7_result->d == 6.66 + 1); + + free (ts7_result); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct8.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct8.c new file mode 100644 index 0000000..ef204ec --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct8.c @@ -0,0 +1,81 @@ +/* Area: ffi_call + Purpose: Check structures. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" +typedef struct +{ + float f1; + float f2; + float f3; + float f4; +} test_structure_8; + +static test_structure_8 ABI_ATTR struct8 (test_structure_8 ts) +{ + ts.f1 += 1; + ts.f2 += 1; + ts.f3 += 1; + ts.f4 += 1; + + return ts; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_type ts8_type; + ffi_type *ts8_type_elements[5]; + + test_structure_8 ts8_arg; + + /* This is a hack to get a properly aligned result buffer */ + test_structure_8 *ts8_result = + (test_structure_8 *) malloc (sizeof(test_structure_8)); + + ts8_type.size = 0; + ts8_type.alignment = 0; + ts8_type.type = FFI_TYPE_STRUCT; + ts8_type.elements = ts8_type_elements; + ts8_type_elements[0] = &ffi_type_float; + ts8_type_elements[1] = &ffi_type_float; + ts8_type_elements[2] = &ffi_type_float; + ts8_type_elements[3] = &ffi_type_float; + ts8_type_elements[4] = NULL; + + args[0] = &ts8_type; + values[0] = &ts8_arg; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts8_type, args) == FFI_OK); + + ts8_arg.f1 = 5.55f; + ts8_arg.f2 = 55.5f; + ts8_arg.f3 = -5.55f; + ts8_arg.f4 = -55.5f; + + printf ("%g\n", ts8_arg.f1); + printf ("%g\n", ts8_arg.f2); + printf ("%g\n", ts8_arg.f3); + printf ("%g\n", ts8_arg.f4); + + ffi_call(&cif, FFI_FN(struct8), ts8_result, values); + + printf ("%g\n", ts8_result->f1); + printf ("%g\n", ts8_result->f2); + printf ("%g\n", ts8_result->f3); + printf ("%g\n", ts8_result->f4); + + CHECK(ts8_result->f1 == 5.55f + 1); + CHECK(ts8_result->f2 == 55.5f + 1); + CHECK(ts8_result->f3 == -5.55f + 1); + CHECK(ts8_result->f4 == -55.5f + 1); + + free (ts8_result); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct9.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct9.c new file mode 100644 index 0000000..4a13b81 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/struct9.c @@ -0,0 +1,68 @@ +/* Area: ffi_call + Purpose: Check structures. + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct +{ + float f; + int i; +} test_structure_9; + +static test_structure_9 ABI_ATTR struct9 (test_structure_9 ts) +{ + ts.f += 1; + ts.i += 1; + + return ts; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_type ts9_type; + ffi_type *ts9_type_elements[3]; + + test_structure_9 ts9_arg; + + /* This is a hack to get a properly aligned result buffer */ + test_structure_9 *ts9_result = + (test_structure_9 *) malloc (sizeof(test_structure_9)); + + ts9_type.size = 0; + ts9_type.alignment = 0; + ts9_type.type = FFI_TYPE_STRUCT; + ts9_type.elements = ts9_type_elements; + ts9_type_elements[0] = &ffi_type_float; + ts9_type_elements[1] = &ffi_type_sint; + ts9_type_elements[2] = NULL; + + args[0] = &ts9_type; + values[0] = &ts9_arg; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 1, &ts9_type, args) == FFI_OK); + + ts9_arg.f = 5.55f; + ts9_arg.i = 5; + + printf ("%g\n", ts9_arg.f); + printf ("%d\n", ts9_arg.i); + + ffi_call(&cif, FFI_FN(struct9), ts9_result, values); + + printf ("%g\n", ts9_result->f); + printf ("%d\n", ts9_result->i); + + CHECK(ts9_result->f == 5.55f + 1); + CHECK(ts9_result->i == 5 + 1); + + free (ts9_result); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/uninitialized.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/uninitialized.c new file mode 100644 index 0000000..f00d830 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/uninitialized.c @@ -0,0 +1,61 @@ +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct +{ + unsigned char uc; + double d; + unsigned int ui; +} test_structure_1; + +static test_structure_1 struct1(test_structure_1 ts) +{ + ts.uc++; + ts.d--; + ts.ui++; + + return ts; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_type ts1_type; + ffi_type *ts1_type_elements[4]; + + memset(&cif, 1, sizeof(cif)); + ts1_type.size = 0; + ts1_type.alignment = 0; + ts1_type.type = FFI_TYPE_STRUCT; + ts1_type.elements = ts1_type_elements; + ts1_type_elements[0] = &ffi_type_uchar; + ts1_type_elements[1] = &ffi_type_double; + ts1_type_elements[2] = &ffi_type_uint; + ts1_type_elements[3] = NULL; + + test_structure_1 ts1_arg; + /* This is a hack to get a properly aligned result buffer */ + test_structure_1 *ts1_result = + (test_structure_1 *) malloc (sizeof(test_structure_1)); + + args[0] = &ts1_type; + values[0] = &ts1_arg; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ts1_type, args) == FFI_OK); + + ts1_arg.uc = '\x01'; + ts1_arg.d = 3.14159; + ts1_arg.ui = 555; + + ffi_call(&cif, FFI_FN(struct1), ts1_result, values); + + CHECK(ts1_result->ui == 556); + CHECK(ts1_result->d == 3.14159 - 1); + + free (ts1_result); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_1.c new file mode 100644 index 0000000..59d085c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_1.c @@ -0,0 +1,196 @@ +/* Area: ffi_call + Purpose: Test passing struct in variable argument lists. + Limitations: none. + PR: none. + Originator: ARM Ltd. */ + +/* { dg-do run } */ +/* { dg-output "" { xfail avr32*-*-* m68k-*-* alpha-*-* } } */ + +#include "ffitest.h" +#include + +struct small_tag +{ + unsigned char a; + unsigned char b; +}; + +struct large_tag +{ + unsigned a; + unsigned b; + unsigned c; + unsigned d; + unsigned e; +}; + +static int +test_fn (int n, ...) +{ + va_list ap; + struct small_tag s1; + struct small_tag s2; + struct large_tag l; + unsigned char uc; + signed char sc; + unsigned short us; + signed short ss; + unsigned int ui; + signed int si; + unsigned long ul; + signed long sl; + float f; + double d; + + va_start (ap, n); + s1 = va_arg (ap, struct small_tag); + l = va_arg (ap, struct large_tag); + s2 = va_arg (ap, struct small_tag); + + uc = va_arg (ap, unsigned); + sc = va_arg (ap, signed); + + us = va_arg (ap, unsigned); + ss = va_arg (ap, signed); + + ui = va_arg (ap, unsigned int); + si = va_arg (ap, signed int); + + ul = va_arg (ap, unsigned long); + sl = va_arg (ap, signed long); + + f = va_arg (ap, double); /* C standard promotes float->double + when anonymous */ + d = va_arg (ap, double); + + printf ("%u %u %u %u %u %u %u %u %u uc=%u sc=%d %u %d %u %d %lu %ld %f %f\n", + s1.a, s1.b, l.a, l.b, l.c, l.d, l.e, + s2.a, s2.b, + uc, sc, + us, ss, + ui, si, + ul, sl, + f, d); + va_end (ap); + return n + 1; +} + +int +main (void) +{ + ffi_cif cif; + void* args[15]; + ffi_type* arg_types[15]; + + ffi_type s_type; + ffi_type *s_type_elements[3]; + + ffi_type l_type; + ffi_type *l_type_elements[6]; + + struct small_tag s1; + struct small_tag s2; + struct large_tag l1; + + int n; + ffi_arg res; + + unsigned char uc; + signed char sc; + unsigned short us; + signed short ss; + unsigned int ui; + signed int si; + unsigned long ul; + signed long sl; + double d1; + double f1; + + s_type.size = 0; + s_type.alignment = 0; + s_type.type = FFI_TYPE_STRUCT; + s_type.elements = s_type_elements; + + s_type_elements[0] = &ffi_type_uchar; + s_type_elements[1] = &ffi_type_uchar; + s_type_elements[2] = NULL; + + l_type.size = 0; + l_type.alignment = 0; + l_type.type = FFI_TYPE_STRUCT; + l_type.elements = l_type_elements; + + l_type_elements[0] = &ffi_type_uint; + l_type_elements[1] = &ffi_type_uint; + l_type_elements[2] = &ffi_type_uint; + l_type_elements[3] = &ffi_type_uint; + l_type_elements[4] = &ffi_type_uint; + l_type_elements[5] = NULL; + + arg_types[0] = &ffi_type_sint; + arg_types[1] = &s_type; + arg_types[2] = &l_type; + arg_types[3] = &s_type; + arg_types[4] = &ffi_type_uchar; + arg_types[5] = &ffi_type_schar; + arg_types[6] = &ffi_type_ushort; + arg_types[7] = &ffi_type_sshort; + arg_types[8] = &ffi_type_uint; + arg_types[9] = &ffi_type_sint; + arg_types[10] = &ffi_type_ulong; + arg_types[11] = &ffi_type_slong; + arg_types[12] = &ffi_type_double; + arg_types[13] = &ffi_type_double; + arg_types[14] = NULL; + + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 14, &ffi_type_sint, arg_types) == FFI_OK); + + s1.a = 5; + s1.b = 6; + + l1.a = 10; + l1.b = 11; + l1.c = 12; + l1.d = 13; + l1.e = 14; + + s2.a = 7; + s2.b = 8; + + n = 41; + + uc = 9; + sc = 10; + us = 11; + ss = 12; + ui = 13; + si = 14; + ul = 15; + sl = 16; + f1 = 2.12; + d1 = 3.13; + + args[0] = &n; + args[1] = &s1; + args[2] = &l1; + args[3] = &s2; + args[4] = &uc; + args[5] = ≻ + args[6] = &us; + args[7] = &ss; + args[8] = &ui; + args[9] = &si; + args[10] = &ul; + args[11] = &sl; + args[12] = &f1; + args[13] = &d1; + args[14] = NULL; + + ffi_call(&cif, FFI_FN(test_fn), &res, args); + /* { dg-output "5 6 10 11 12 13 14 7 8 uc=9 sc=10 11 12 13 14 15 16 2.120000 3.130000" } */ + printf("res: %d\n", (int) res); + /* { dg-output "\nres: 42" } */ + + return 0; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_struct1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_struct1.c new file mode 100644 index 0000000..e645206 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_struct1.c @@ -0,0 +1,121 @@ +/* Area: ffi_call + Purpose: Test passing struct in variable argument lists. + Limitations: none. + PR: none. + Originator: ARM Ltd. */ + +/* { dg-do run } */ +/* { dg-output "" { xfail avr32*-*-* } } */ + +#include "ffitest.h" +#include + +struct small_tag +{ + unsigned char a; + unsigned char b; +}; + +struct large_tag +{ + unsigned a; + unsigned b; + unsigned c; + unsigned d; + unsigned e; +}; + +static int +test_fn (int n, ...) +{ + va_list ap; + struct small_tag s1; + struct small_tag s2; + struct large_tag l; + + va_start (ap, n); + s1 = va_arg (ap, struct small_tag); + l = va_arg (ap, struct large_tag); + s2 = va_arg (ap, struct small_tag); + printf ("%u %u %u %u %u %u %u %u %u\n", s1.a, s1.b, l.a, l.b, l.c, l.d, l.e, + s2.a, s2.b); + va_end (ap); + return n + 1; +} + +int +main (void) +{ + ffi_cif cif; + void* args[5]; + ffi_type* arg_types[5]; + + ffi_type s_type; + ffi_type *s_type_elements[3]; + + ffi_type l_type; + ffi_type *l_type_elements[6]; + + struct small_tag s1; + struct small_tag s2; + struct large_tag l1; + + int n; + ffi_arg res; + + s_type.size = 0; + s_type.alignment = 0; + s_type.type = FFI_TYPE_STRUCT; + s_type.elements = s_type_elements; + + s_type_elements[0] = &ffi_type_uchar; + s_type_elements[1] = &ffi_type_uchar; + s_type_elements[2] = NULL; + + l_type.size = 0; + l_type.alignment = 0; + l_type.type = FFI_TYPE_STRUCT; + l_type.elements = l_type_elements; + + l_type_elements[0] = &ffi_type_uint; + l_type_elements[1] = &ffi_type_uint; + l_type_elements[2] = &ffi_type_uint; + l_type_elements[3] = &ffi_type_uint; + l_type_elements[4] = &ffi_type_uint; + l_type_elements[5] = NULL; + + arg_types[0] = &ffi_type_sint; + arg_types[1] = &s_type; + arg_types[2] = &l_type; + arg_types[3] = &s_type; + arg_types[4] = NULL; + + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &ffi_type_sint, arg_types) == FFI_OK); + + s1.a = 5; + s1.b = 6; + + l1.a = 10; + l1.b = 11; + l1.c = 12; + l1.d = 13; + l1.e = 14; + + s2.a = 7; + s2.b = 8; + + n = 41; + + args[0] = &n; + args[1] = &s1; + args[2] = &l1; + args[3] = &s2; + args[4] = NULL; + + ffi_call(&cif, FFI_FN(test_fn), &res, args); + /* { dg-output "5 6 10 11 12 13 14 7 8" } */ + printf("res: %d\n", (int) res); + /* { dg-output "\nres: 42" } */ + + return 0; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_struct2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_struct2.c new file mode 100644 index 0000000..56f5b9c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_struct2.c @@ -0,0 +1,123 @@ +/* Area: ffi_call + Purpose: Test passing struct in variable argument lists. + Limitations: none. + PR: none. + Originator: ARM Ltd. */ + +/* { dg-do run } */ +/* { dg-output "" { xfail avr32*-*-* } } */ + +#include "ffitest.h" +#include + +struct small_tag +{ + unsigned char a; + unsigned char b; +}; + +struct large_tag +{ + unsigned a; + unsigned b; + unsigned c; + unsigned d; + unsigned e; +}; + +static struct small_tag +test_fn (int n, ...) +{ + va_list ap; + struct small_tag s1; + struct small_tag s2; + struct large_tag l; + + va_start (ap, n); + s1 = va_arg (ap, struct small_tag); + l = va_arg (ap, struct large_tag); + s2 = va_arg (ap, struct small_tag); + printf ("%u %u %u %u %u %u %u %u %u\n", s1.a, s1.b, l.a, l.b, l.c, l.d, l.e, + s2.a, s2.b); + va_end (ap); + s1.a += s2.a; + s1.b += s2.b; + return s1; +} + +int +main (void) +{ + ffi_cif cif; + void* args[5]; + ffi_type* arg_types[5]; + + ffi_type s_type; + ffi_type *s_type_elements[3]; + + ffi_type l_type; + ffi_type *l_type_elements[6]; + + struct small_tag s1; + struct small_tag s2; + struct large_tag l1; + + int n; + struct small_tag res; + + s_type.size = 0; + s_type.alignment = 0; + s_type.type = FFI_TYPE_STRUCT; + s_type.elements = s_type_elements; + + s_type_elements[0] = &ffi_type_uchar; + s_type_elements[1] = &ffi_type_uchar; + s_type_elements[2] = NULL; + + l_type.size = 0; + l_type.alignment = 0; + l_type.type = FFI_TYPE_STRUCT; + l_type.elements = l_type_elements; + + l_type_elements[0] = &ffi_type_uint; + l_type_elements[1] = &ffi_type_uint; + l_type_elements[2] = &ffi_type_uint; + l_type_elements[3] = &ffi_type_uint; + l_type_elements[4] = &ffi_type_uint; + l_type_elements[5] = NULL; + + arg_types[0] = &ffi_type_sint; + arg_types[1] = &s_type; + arg_types[2] = &l_type; + arg_types[3] = &s_type; + arg_types[4] = NULL; + + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &s_type, arg_types) == FFI_OK); + + s1.a = 5; + s1.b = 6; + + l1.a = 10; + l1.b = 11; + l1.c = 12; + l1.d = 13; + l1.e = 14; + + s2.a = 7; + s2.b = 8; + + n = 41; + + args[0] = &n; + args[1] = &s1; + args[2] = &l1; + args[3] = &s2; + args[4] = NULL; + + ffi_call(&cif, FFI_FN(test_fn), &res, args); + /* { dg-output "5 6 10 11 12 13 14 7 8" } */ + printf("res: %d %d\n", res.a, res.b); + /* { dg-output "\nres: 12 14" } */ + + return 0; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_struct3.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_struct3.c new file mode 100644 index 0000000..9a27e7f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.call/va_struct3.c @@ -0,0 +1,125 @@ +/* Area: ffi_call + Purpose: Test passing struct in variable argument lists. + Limitations: none. + PR: none. + Originator: ARM Ltd. */ + +/* { dg-do run } */ +/* { dg-output "" { xfail avr32*-*-* } } */ + +#include "ffitest.h" +#include + +struct small_tag +{ + unsigned char a; + unsigned char b; +}; + +struct large_tag +{ + unsigned a; + unsigned b; + unsigned c; + unsigned d; + unsigned e; +}; + +static struct large_tag +test_fn (int n, ...) +{ + va_list ap; + struct small_tag s1; + struct small_tag s2; + struct large_tag l; + + va_start (ap, n); + s1 = va_arg (ap, struct small_tag); + l = va_arg (ap, struct large_tag); + s2 = va_arg (ap, struct small_tag); + printf ("%u %u %u %u %u %u %u %u %u\n", s1.a, s1.b, l.a, l.b, l.c, l.d, l.e, + s2.a, s2.b); + va_end (ap); + l.a += s1.a; + l.b += s1.b; + l.c += s2.a; + l.d += s2.b; + return l; +} + +int +main (void) +{ + ffi_cif cif; + void* args[5]; + ffi_type* arg_types[5]; + + ffi_type s_type; + ffi_type *s_type_elements[3]; + + ffi_type l_type; + ffi_type *l_type_elements[6]; + + struct small_tag s1; + struct small_tag s2; + struct large_tag l1; + + int n; + struct large_tag res; + + s_type.size = 0; + s_type.alignment = 0; + s_type.type = FFI_TYPE_STRUCT; + s_type.elements = s_type_elements; + + s_type_elements[0] = &ffi_type_uchar; + s_type_elements[1] = &ffi_type_uchar; + s_type_elements[2] = NULL; + + l_type.size = 0; + l_type.alignment = 0; + l_type.type = FFI_TYPE_STRUCT; + l_type.elements = l_type_elements; + + l_type_elements[0] = &ffi_type_uint; + l_type_elements[1] = &ffi_type_uint; + l_type_elements[2] = &ffi_type_uint; + l_type_elements[3] = &ffi_type_uint; + l_type_elements[4] = &ffi_type_uint; + l_type_elements[5] = NULL; + + arg_types[0] = &ffi_type_sint; + arg_types[1] = &s_type; + arg_types[2] = &l_type; + arg_types[3] = &s_type; + arg_types[4] = NULL; + + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &l_type, arg_types) == FFI_OK); + + s1.a = 5; + s1.b = 6; + + l1.a = 10; + l1.b = 11; + l1.c = 12; + l1.d = 13; + l1.e = 14; + + s2.a = 7; + s2.b = 8; + + n = 41; + + args[0] = &n; + args[1] = &s1; + args[2] = &l1; + args[3] = &s2; + args[4] = NULL; + + ffi_call(&cif, FFI_FN(test_fn), &res, args); + /* { dg-output "5 6 10 11 12 13 14 7 8" } */ + printf("res: %d %d %d %d %d\n", res.a, res.b, res.c, res.d, res.e); + /* { dg-output "\nres: 15 17 19 21 14" } */ + + return 0; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure.exp new file mode 100644 index 0000000..ed4145c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure.exp @@ -0,0 +1,67 @@ +# Copyright (C) 2003, 2006, 2009, 2010, 2014, 2019 Free Software Foundation, Inc. +# Copyright (C) 2019 Anthony Green + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; see the file COPYING3. If not see +# . + +dg-init +libffi-init + +global srcdir subdir + +if { [string match $compiler_vendor "microsoft"] } { + # -wd4005 macro redefinition + # -wd4244 implicit conversion to type of smaller size + # -wd4305 truncation to smaller type + # -wd4477 printf %lu of uintptr_t + # -wd4312 implicit conversion to type of greater size + # -wd4311 pointer truncation to unsigned long + # -EHsc C++ Exception Handling (no SEH exceptions) + set additional_options "-wd4005 -wd4244 -wd4305 -wd4477 -wd4312 -wd4311 -EHsc"; +} else { + set additional_options ""; +} + +set tlist [lsort [glob -nocomplain -- $srcdir/$subdir/*.c]] + +if { [libffi_feature_test "#if FFI_CLOSURES"] } { + run-many-tests $tlist "" +} else { + foreach test $tlist { + unsupported "$test" + } +} + +set tlist [lsort [glob -nocomplain -- $srcdir/$subdir/*.cc]] + +# No C++ for or1k +if { [istarget "or1k-*-*"] } { + foreach test $tlist { + unsupported "$test" + } +} else { + if { [libffi_feature_test "#if FFI_CLOSURES"] } { + run-many-tests $tlist $additional_options + } else { + foreach test $tlist { + unsupported "$test" + } + } +} + +dg-finish + +# Local Variables: +# tcl-indent-level:4 +# End: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn0.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn0.c new file mode 100644 index 0000000..a579ff6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn0.c @@ -0,0 +1,89 @@ +/* Area: closure_call + Purpose: Check multiple values passing from different type. + Also, exceed the limit of gpr and fpr registers on PowerPC + Darwin. + Limitations: none. + PR: none. + Originator: 20030828 */ + + + + +/* { dg-do run } */ +#include "ffitest.h" + +static void +closure_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata) +{ + *(ffi_arg*)resp = + (int)*(unsigned long long *)args[0] + (int)(*(int *)args[1]) + + (int)(*(unsigned long long *)args[2]) + (int)*(int *)args[3] + + (int)(*(signed short *)args[4]) + + (int)(*(unsigned long long *)args[5]) + + (int)*(int *)args[6] + (int)(*(int *)args[7]) + + (int)(*(double *)args[8]) + (int)*(int *)args[9] + + (int)(*(int *)args[10]) + (int)(*(float *)args[11]) + + (int)*(int *)args[12] + (int)(*(int *)args[13]) + + (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata; + + printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n", + (int)*(unsigned long long *)args[0], (int)(*(int *)args[1]), + (int)(*(unsigned long long *)args[2]), + (int)*(int *)args[3], (int)(*(signed short *)args[4]), + (int)(*(unsigned long long *)args[5]), + (int)*(int *)args[6], (int)(*(int *)args[7]), + (int)(*(double *)args[8]), (int)*(int *)args[9], + (int)(*(int *)args[10]), (int)(*(float *)args[11]), + (int)*(int *)args[12], (int)(*(int *)args[13]), + (int)(*(int *)args[14]),*(int *)args[15], + (int)(intptr_t)userdata, (int)*(ffi_arg *)resp); + +} + +typedef int (*closure_test_type0)(unsigned long long, int, unsigned long long, + int, signed short, unsigned long long, int, + int, double, int, int, float, int, int, + int, int); + +int main (void) +{ + ffi_cif cif; + void * code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[17]; + int res; + + cl_arg_types[0] = &ffi_type_uint64; + cl_arg_types[1] = &ffi_type_sint; + cl_arg_types[2] = &ffi_type_uint64; + cl_arg_types[3] = &ffi_type_sint; + cl_arg_types[4] = &ffi_type_sshort; + cl_arg_types[5] = &ffi_type_uint64; + cl_arg_types[6] = &ffi_type_sint; + cl_arg_types[7] = &ffi_type_sint; + cl_arg_types[8] = &ffi_type_double; + cl_arg_types[9] = &ffi_type_sint; + cl_arg_types[10] = &ffi_type_sint; + cl_arg_types[11] = &ffi_type_float; + cl_arg_types[12] = &ffi_type_sint; + cl_arg_types[13] = &ffi_type_sint; + cl_arg_types[14] = &ffi_type_sint; + cl_arg_types[15] = &ffi_type_sint; + cl_arg_types[16] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16, + &ffi_type_sint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn0, + (void *) 3 /* userdata */, code) == FFI_OK); + + res = (*((closure_test_type0)code)) + (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13, + 19, 21, 1); + /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 680" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn1.c new file mode 100644 index 0000000..9123173 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn1.c @@ -0,0 +1,81 @@ +/* Area: closure_call. + Purpose: Check multiple values passing from different type. + Also, exceed the limit of gpr and fpr registers on PowerPC + Darwin. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + + +static void closure_test_fn1(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata) +{ + *(ffi_arg*)resp = + (int)*(float *)args[0] +(int)(*(float *)args[1]) + + (int)(*(float *)args[2]) + (int)*(float *)args[3] + + (int)(*(signed short *)args[4]) + (int)(*(float *)args[5]) + + (int)*(float *)args[6] + (int)(*(int *)args[7]) + + (int)(*(double*)args[8]) + (int)*(int *)args[9] + + (int)(*(int *)args[10]) + (int)(*(float *)args[11]) + + (int)*(int *)args[12] + (int)(*(int *)args[13]) + + (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata; + + printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n", + (int)*(float *)args[0], (int)(*(float *)args[1]), + (int)(*(float *)args[2]), (int)*(float *)args[3], + (int)(*(signed short *)args[4]), (int)(*(float *)args[5]), + (int)*(float *)args[6], (int)(*(int *)args[7]), + (int)(*(double *)args[8]), (int)*(int *)args[9], + (int)(*(int *)args[10]), (int)(*(float *)args[11]), + (int)*(int *)args[12], (int)(*(int *)args[13]), + (int)(*(int *)args[14]), *(int *)args[15], + (int)(intptr_t)userdata, (int)*(ffi_arg *)resp); +} + +typedef int (*closure_test_type1)(float, float, float, float, signed short, + float, float, int, double, int, int, float, + int, int, int, int); +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[17]; + int res; + + cl_arg_types[0] = &ffi_type_float; + cl_arg_types[1] = &ffi_type_float; + cl_arg_types[2] = &ffi_type_float; + cl_arg_types[3] = &ffi_type_float; + cl_arg_types[4] = &ffi_type_sshort; + cl_arg_types[5] = &ffi_type_float; + cl_arg_types[6] = &ffi_type_float; + cl_arg_types[7] = &ffi_type_sint; + cl_arg_types[8] = &ffi_type_double; + cl_arg_types[9] = &ffi_type_sint; + cl_arg_types[10] = &ffi_type_sint; + cl_arg_types[11] = &ffi_type_float; + cl_arg_types[12] = &ffi_type_sint; + cl_arg_types[13] = &ffi_type_sint; + cl_arg_types[14] = &ffi_type_sint; + cl_arg_types[15] = &ffi_type_sint; + cl_arg_types[16] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16, + &ffi_type_sint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn1, + (void *) 3 /* userdata */, code) == FFI_OK); + + res = (*((closure_test_type1)code)) + (1.1, 2.2, 3.3, 4.4, 127, 5.5, 6.6, 8, 9, 10, 11, 12.0, 13, + 19, 21, 1); + /* { dg-output "1 2 3 4 127 5 6 8 9 10 11 12 13 19 21 1 3: 255" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 255" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn2.c new file mode 100644 index 0000000..08ff9d9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn2.c @@ -0,0 +1,81 @@ +/* Area: closure_call + Purpose: Check multiple values passing from different type. + Also, exceed the limit of gpr and fpr registers on PowerPC + Darwin. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void closure_test_fn2(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata) +{ + *(ffi_arg*)resp = + (int)*(double *)args[0] +(int)(*(double *)args[1]) + + (int)(*(double *)args[2]) + (int)*(double *)args[3] + + (int)(*(signed short *)args[4]) + (int)(*(double *)args[5]) + + (int)*(double *)args[6] + (int)(*(int *)args[7]) + + (int)(*(double *)args[8]) + (int)*(int *)args[9] + + (int)(*(int *)args[10]) + (int)(*(float *)args[11]) + + (int)*(int *)args[12] + (int)(*(float *)args[13]) + + (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata; + + printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n", + (int)*(double *)args[0], (int)(*(double *)args[1]), + (int)(*(double *)args[2]), (int)*(double *)args[3], + (int)(*(signed short *)args[4]), (int)(*(double *)args[5]), + (int)*(double *)args[6], (int)(*(int *)args[7]), + (int)(*(double*)args[8]), (int)*(int *)args[9], + (int)(*(int *)args[10]), (int)(*(float *)args[11]), + (int)*(int *)args[12], (int)(*(float *)args[13]), + (int)(*(int *)args[14]), *(int *)args[15], (int)(intptr_t)userdata, + (int)*(ffi_arg *)resp); +} + +typedef int (*closure_test_type2)(double, double, double, double, signed short, + double, double, int, double, int, int, float, + int, float, int, int); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[17]; + int res; + + cl_arg_types[0] = &ffi_type_double; + cl_arg_types[1] = &ffi_type_double; + cl_arg_types[2] = &ffi_type_double; + cl_arg_types[3] = &ffi_type_double; + cl_arg_types[4] = &ffi_type_sshort; + cl_arg_types[5] = &ffi_type_double; + cl_arg_types[6] = &ffi_type_double; + cl_arg_types[7] = &ffi_type_sint; + cl_arg_types[8] = &ffi_type_double; + cl_arg_types[9] = &ffi_type_sint; + cl_arg_types[10] = &ffi_type_sint; + cl_arg_types[11] = &ffi_type_float; + cl_arg_types[12] = &ffi_type_sint; + cl_arg_types[13] = &ffi_type_float; + cl_arg_types[14] = &ffi_type_sint; + cl_arg_types[15] = &ffi_type_sint; + cl_arg_types[16] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16, + &ffi_type_sint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn2, + (void *) 3 /* userdata */, code) == FFI_OK); + + res = (*((closure_test_type2)code)) + (1, 2, 3, 4, 127, 5, 6, 8, 9, 10, 11, 12.0, 13, + 19.0, 21, 1); + /* { dg-output "1 2 3 4 127 5 6 8 9 10 11 12 13 19 21 1 3: 255" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 255" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn3.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn3.c new file mode 100644 index 0000000..9b54d80 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn3.c @@ -0,0 +1,82 @@ +/* Area: closure_call + Purpose: Check multiple values passing from different type. + Also, exceed the limit of gpr and fpr registers on PowerPC + Darwin. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void closure_test_fn3(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata) + { + *(ffi_arg*)resp = + (int)*(float *)args[0] +(int)(*(float *)args[1]) + + (int)(*(float *)args[2]) + (int)*(float *)args[3] + + (int)(*(float *)args[4]) + (int)(*(float *)args[5]) + + (int)*(float *)args[6] + (int)(*(float *)args[7]) + + (int)(*(double *)args[8]) + (int)*(int *)args[9] + + (int)(*(float *)args[10]) + (int)(*(float *)args[11]) + + (int)*(int *)args[12] + (int)(*(float *)args[13]) + + (int)(*(float *)args[14]) + *(int *)args[15] + (intptr_t)userdata; + + printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n", + (int)*(float *)args[0], (int)(*(float *)args[1]), + (int)(*(float *)args[2]), (int)*(float *)args[3], + (int)(*(float *)args[4]), (int)(*(float *)args[5]), + (int)*(float *)args[6], (int)(*(float *)args[7]), + (int)(*(double *)args[8]), (int)*(int *)args[9], + (int)(*(float *)args[10]), (int)(*(float *)args[11]), + (int)*(int *)args[12], (int)(*(float *)args[13]), + (int)(*(float *)args[14]), *(int *)args[15], (int)(intptr_t)userdata, + (int)*(ffi_arg *)resp); + + } + +typedef int (*closure_test_type3)(float, float, float, float, float, float, + float, float, double, int, float, float, int, + float, float, int); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[17]; + int res; + + cl_arg_types[0] = &ffi_type_float; + cl_arg_types[1] = &ffi_type_float; + cl_arg_types[2] = &ffi_type_float; + cl_arg_types[3] = &ffi_type_float; + cl_arg_types[4] = &ffi_type_float; + cl_arg_types[5] = &ffi_type_float; + cl_arg_types[6] = &ffi_type_float; + cl_arg_types[7] = &ffi_type_float; + cl_arg_types[8] = &ffi_type_double; + cl_arg_types[9] = &ffi_type_sint; + cl_arg_types[10] = &ffi_type_float; + cl_arg_types[11] = &ffi_type_float; + cl_arg_types[12] = &ffi_type_sint; + cl_arg_types[13] = &ffi_type_float; + cl_arg_types[14] = &ffi_type_float; + cl_arg_types[15] = &ffi_type_sint; + cl_arg_types[16] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16, + &ffi_type_sint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn3, + (void *) 3 /* userdata */, code) == FFI_OK); + + res = (*((closure_test_type3)code)) + (1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9, 10, 11.11, 12.0, 13, + 19.19, 21.21, 1); + /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 12 13 19 21 1 3: 135" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 135" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn4.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn4.c new file mode 100644 index 0000000..d4a1530 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn4.c @@ -0,0 +1,89 @@ +/* Area: closure_call + Purpose: Check multiple long long values passing. + Also, exceed the limit of gpr and fpr registers on PowerPC + Darwin. + Limitations: none. + PR: none. + Originator: 20031026 */ + +/* { dg-do run } */ + +#include "ffitest.h" + +static void +closure_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata) +{ + *(ffi_arg*)resp = + (int)*(unsigned long long *)args[0] + (int)*(unsigned long long *)args[1] + + (int)*(unsigned long long *)args[2] + (int)*(unsigned long long *)args[3] + + (int)*(unsigned long long *)args[4] + (int)*(unsigned long long *)args[5] + + (int)*(unsigned long long *)args[6] + (int)*(unsigned long long *)args[7] + + (int)*(unsigned long long *)args[8] + (int)*(unsigned long long *)args[9] + + (int)*(unsigned long long *)args[10] + + (int)*(unsigned long long *)args[11] + + (int)*(unsigned long long *)args[12] + + (int)*(unsigned long long *)args[13] + + (int)*(unsigned long long *)args[14] + + *(int *)args[15] + (intptr_t)userdata; + + printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n", + (int)*(unsigned long long *)args[0], + (int)*(unsigned long long *)args[1], + (int)*(unsigned long long *)args[2], + (int)*(unsigned long long *)args[3], + (int)*(unsigned long long *)args[4], + (int)*(unsigned long long *)args[5], + (int)*(unsigned long long *)args[6], + (int)*(unsigned long long *)args[7], + (int)*(unsigned long long *)args[8], + (int)*(unsigned long long *)args[9], + (int)*(unsigned long long *)args[10], + (int)*(unsigned long long *)args[11], + (int)*(unsigned long long *)args[12], + (int)*(unsigned long long *)args[13], + (int)*(unsigned long long *)args[14], + *(int *)args[15], + (int)(intptr_t)userdata, (int)*(ffi_arg *)resp); + +} + +typedef int (*closure_test_type0)(unsigned long long, unsigned long long, + unsigned long long, unsigned long long, + unsigned long long, unsigned long long, + unsigned long long, unsigned long long, + unsigned long long, unsigned long long, + unsigned long long, unsigned long long, + unsigned long long, unsigned long long, + unsigned long long, int); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[17]; + int i, res; + + for (i = 0; i < 15; i++) { + cl_arg_types[i] = &ffi_type_uint64; + } + cl_arg_types[15] = &ffi_type_sint; + cl_arg_types[16] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16, + &ffi_type_sint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn0, + (void *) 3 /* userdata */, code) == FFI_OK); + + res = (*((closure_test_type0)code)) + (1LL, 2LL, 3LL, 4LL, 127LL, 429LL, 7LL, 8LL, 9LL, 10LL, 11LL, 12LL, + 13LL, 19LL, 21LL, 1); + /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 680" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn5.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn5.c new file mode 100644 index 0000000..9907442 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn5.c @@ -0,0 +1,92 @@ +/* Area: closure_call + Purpose: Check multiple long long values passing. + Exceed the limit of gpr registers on PowerPC + Darwin. + Limitations: none. + PR: none. + Originator: 20031026 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void +closure_test_fn5(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata) +{ + *(ffi_arg*)resp = + (int)*(unsigned long long *)args[0] + (int)*(unsigned long long *)args[1] + + (int)*(unsigned long long *)args[2] + (int)*(unsigned long long *)args[3] + + (int)*(unsigned long long *)args[4] + (int)*(unsigned long long *)args[5] + + (int)*(unsigned long long *)args[6] + (int)*(unsigned long long *)args[7] + + (int)*(unsigned long long *)args[8] + (int)*(unsigned long long *)args[9] + + (int)*(int *)args[10] + + (int)*(unsigned long long *)args[11] + + (int)*(unsigned long long *)args[12] + + (int)*(unsigned long long *)args[13] + + (int)*(unsigned long long *)args[14] + + *(int *)args[15] + (intptr_t)userdata; + + printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n", + (int)*(unsigned long long *)args[0], + (int)*(unsigned long long *)args[1], + (int)*(unsigned long long *)args[2], + (int)*(unsigned long long *)args[3], + (int)*(unsigned long long *)args[4], + (int)*(unsigned long long *)args[5], + (int)*(unsigned long long *)args[6], + (int)*(unsigned long long *)args[7], + (int)*(unsigned long long *)args[8], + (int)*(unsigned long long *)args[9], + (int)*(int *)args[10], + (int)*(unsigned long long *)args[11], + (int)*(unsigned long long *)args[12], + (int)*(unsigned long long *)args[13], + (int)*(unsigned long long *)args[14], + *(int *)args[15], + (int)(intptr_t)userdata, (int)*(ffi_arg *)resp); + +} + +typedef int (*closure_test_type0)(unsigned long long, unsigned long long, + unsigned long long, unsigned long long, + unsigned long long, unsigned long long, + unsigned long long, unsigned long long, + unsigned long long, unsigned long long, + int, unsigned long long, + unsigned long long, unsigned long long, + unsigned long long, int); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[17]; + int i, res; + + for (i = 0; i < 10; i++) { + cl_arg_types[i] = &ffi_type_uint64; + } + cl_arg_types[10] = &ffi_type_sint; + for (i = 11; i < 15; i++) { + cl_arg_types[i] = &ffi_type_uint64; + } + cl_arg_types[15] = &ffi_type_sint; + cl_arg_types[16] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16, + &ffi_type_sint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn5, + (void *) 3 /* userdata */, code) == FFI_OK); + + res = (*((closure_test_type0)code)) + (1LL, 2LL, 3LL, 4LL, 127LL, 429LL, 7LL, 8LL, 9LL, 10LL, 11, 12LL, + 13LL, 19LL, 21LL, 1); + /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 680" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn6.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn6.c new file mode 100644 index 0000000..73c54fd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_fn6.c @@ -0,0 +1,90 @@ +/* Area: closure_call + Purpose: Check multiple values passing from different type. + Also, exceed the limit of gpr and fpr registers on PowerPC. + Limitations: none. + PR: PR23404 + Originator: 20050830 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void +closure_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata) +{ + *(ffi_arg*)resp = + (int)*(unsigned long long *)args[0] + + (int)(*(unsigned long long *)args[1]) + + (int)(*(unsigned long long *)args[2]) + + (int)*(unsigned long long *)args[3] + + (int)(*(int *)args[4]) + (int)(*(double *)args[5]) + + (int)*(double *)args[6] + (int)(*(float *)args[7]) + + (int)(*(double *)args[8]) + (int)*(double *)args[9] + + (int)(*(int *)args[10]) + (int)(*(float *)args[11]) + + (int)*(int *)args[12] + (int)(*(int *)args[13]) + + (int)(*(double *)args[14]) + (int)*(double *)args[15] + + (intptr_t)userdata; + + printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n", + (int)*(unsigned long long *)args[0], + (int)(*(unsigned long long *)args[1]), + (int)(*(unsigned long long *)args[2]), + (int)*(unsigned long long *)args[3], + (int)(*(int *)args[4]), (int)(*(double *)args[5]), + (int)*(double *)args[6], (int)(*(float *)args[7]), + (int)(*(double *)args[8]), (int)*(double *)args[9], + (int)(*(int *)args[10]), (int)(*(float *)args[11]), + (int)*(int *)args[12], (int)(*(int *)args[13]), + (int)(*(double *)args[14]), (int)(*(double *)args[15]), + (int)(intptr_t)userdata, (int)*(ffi_arg *)resp); + +} + +typedef int (*closure_test_type0)(unsigned long long, + unsigned long long, + unsigned long long, + unsigned long long, + int, double, double, float, double, double, + int, float, int, int, double, double); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[17]; + int res; + + cl_arg_types[0] = &ffi_type_uint64; + cl_arg_types[1] = &ffi_type_uint64; + cl_arg_types[2] = &ffi_type_uint64; + cl_arg_types[3] = &ffi_type_uint64; + cl_arg_types[4] = &ffi_type_sint; + cl_arg_types[5] = &ffi_type_double; + cl_arg_types[6] = &ffi_type_double; + cl_arg_types[7] = &ffi_type_float; + cl_arg_types[8] = &ffi_type_double; + cl_arg_types[9] = &ffi_type_double; + cl_arg_types[10] = &ffi_type_sint; + cl_arg_types[11] = &ffi_type_float; + cl_arg_types[12] = &ffi_type_sint; + cl_arg_types[13] = &ffi_type_sint; + cl_arg_types[14] = &ffi_type_double; + cl_arg_types[15] = &ffi_type_double; + cl_arg_types[16] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16, + &ffi_type_sint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn0, + (void *) 3 /* userdata */, code) == FFI_OK); + + res = (*((closure_test_type0)code)) + (1, 2, 3, 4, 127, 429., 7., 8., 9.5, 10., 11, 12., 13, + 19, 21., 1.); + /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 680" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_loc_fn0.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_loc_fn0.c new file mode 100644 index 0000000..b3afa0b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_loc_fn0.c @@ -0,0 +1,95 @@ +/* Area: closure_call + Purpose: Check multiple values passing from different type. + Also, exceed the limit of gpr and fpr registers on PowerPC + Darwin. + Limitations: none. + PR: none. + Originator: 20030828 */ + + + + +/* { dg-do run } */ +#include "ffitest.h" + +static void +closure_loc_test_fn0(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata) +{ + *(ffi_arg*)resp = + (int)*(unsigned long long *)args[0] + (int)(*(int *)args[1]) + + (int)(*(unsigned long long *)args[2]) + (int)*(int *)args[3] + + (int)(*(signed short *)args[4]) + + (int)(*(unsigned long long *)args[5]) + + (int)*(int *)args[6] + (int)(*(int *)args[7]) + + (int)(*(double *)args[8]) + (int)*(int *)args[9] + + (int)(*(int *)args[10]) + (int)(*(float *)args[11]) + + (int)*(int *)args[12] + (int)(*(int *)args[13]) + + (int)(*(int *)args[14]) + *(int *)args[15] + (intptr_t)userdata; + + printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n", + (int)*(unsigned long long *)args[0], (int)(*(int *)args[1]), + (int)(*(unsigned long long *)args[2]), + (int)*(int *)args[3], (int)(*(signed short *)args[4]), + (int)(*(unsigned long long *)args[5]), + (int)*(int *)args[6], (int)(*(int *)args[7]), + (int)(*(double *)args[8]), (int)*(int *)args[9], + (int)(*(int *)args[10]), (int)(*(float *)args[11]), + (int)*(int *)args[12], (int)(*(int *)args[13]), + (int)(*(int *)args[14]),*(int *)args[15], + (int)(intptr_t)userdata, (int)*(ffi_arg *)resp); + +} + +typedef int (*closure_loc_test_type0)(unsigned long long, int, unsigned long long, + int, signed short, unsigned long long, int, + int, double, int, int, float, int, int, + int, int); + +int main (void) +{ + ffi_cif cif; + ffi_closure *pcl; + ffi_type * cl_arg_types[17]; + int res; + void *codeloc; + + cl_arg_types[0] = &ffi_type_uint64; + cl_arg_types[1] = &ffi_type_sint; + cl_arg_types[2] = &ffi_type_uint64; + cl_arg_types[3] = &ffi_type_sint; + cl_arg_types[4] = &ffi_type_sshort; + cl_arg_types[5] = &ffi_type_uint64; + cl_arg_types[6] = &ffi_type_sint; + cl_arg_types[7] = &ffi_type_sint; + cl_arg_types[8] = &ffi_type_double; + cl_arg_types[9] = &ffi_type_sint; + cl_arg_types[10] = &ffi_type_sint; + cl_arg_types[11] = &ffi_type_float; + cl_arg_types[12] = &ffi_type_sint; + cl_arg_types[13] = &ffi_type_sint; + cl_arg_types[14] = &ffi_type_sint; + cl_arg_types[15] = &ffi_type_sint; + cl_arg_types[16] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16, + &ffi_type_sint, cl_arg_types) == FFI_OK); + + pcl = ffi_closure_alloc(sizeof(ffi_closure), &codeloc); + CHECK(pcl != NULL); + CHECK(codeloc != NULL); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0, + (void *) 3 /* userdata */, codeloc) == FFI_OK); + + CHECK(memcmp(pcl, codeloc, sizeof(*pcl)) == 0); + + res = (*((closure_loc_test_type0)codeloc)) + (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13, + 19, 21, 1); + /* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 680" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_simple.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_simple.c new file mode 100644 index 0000000..5a4e728 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/closure_simple.c @@ -0,0 +1,55 @@ +/* Area: closure_call + Purpose: Check simple closure handling with all ABIs + Limitations: none. + PR: none. + Originator: */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void +closure_test(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata) +{ + *(ffi_arg*)resp = + (int)*(int *)args[0] + (int)(*(int *)args[1]) + + (int)(*(int *)args[2]) + (int)(*(int *)args[3]) + + (int)(intptr_t)userdata; + + printf("%d %d %d %d: %d\n", + (int)*(int *)args[0], (int)(*(int *)args[1]), + (int)(*(int *)args[2]), (int)(*(int *)args[3]), + (int)*(ffi_arg *)resp); + +} + +typedef int (ABI_ATTR *closure_test_type0)(int, int, int, int); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[17]; + int res; + + cl_arg_types[0] = &ffi_type_uint; + cl_arg_types[1] = &ffi_type_uint; + cl_arg_types[2] = &ffi_type_uint; + cl_arg_types[3] = &ffi_type_uint; + cl_arg_types[4] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 4, + &ffi_type_sint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test, + (void *) 3 /* userdata */, code) == FFI_OK); + + res = (*(closure_test_type0)code)(0, 1, 2, 3); + /* { dg-output "0 1 2 3: 9" } */ + + printf("res: %d\n",res); + /* { dg-output "\nres: 9" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_12byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_12byte.c new file mode 100644 index 0000000..ea0825d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_12byte.c @@ -0,0 +1,94 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_12byte { + int a; + int b; + int c; +} cls_struct_12byte; + +cls_struct_12byte cls_struct_12byte_fn(struct cls_struct_12byte b1, + struct cls_struct_12byte b2) +{ + struct cls_struct_12byte result; + + result.a = b1.a + b2.a; + result.b = b1.b + b2.b; + result.c = b1.c + b2.c; + + printf("%d %d %d %d %d %d: %d %d %d\n", b1.a, b1.b, b1.c, b2.a, b2.b, b2.c, + result.a, result.b, result.c); + + return result; +} + +static void cls_struct_12byte_gn(ffi_cif* cif __UNUSED__, void* resp, + void** args , void* userdata __UNUSED__) +{ + struct cls_struct_12byte b1, b2; + + b1 = *(struct cls_struct_12byte*)(args[0]); + b2 = *(struct cls_struct_12byte*)(args[1]); + + *(cls_struct_12byte*)resp = cls_struct_12byte_fn(b1, b2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_12byte h_dbl = { 7, 4, 9 }; + struct cls_struct_12byte j_dbl = { 1, 5, 3 }; + struct cls_struct_12byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_sint; + cls_struct_fields[1] = &ffi_type_sint; + cls_struct_fields[2] = &ffi_type_sint; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &h_dbl; + args_dbl[1] = &j_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_12byte_fn), &res_dbl, args_dbl); + /* { dg-output "7 4 9 1 5 3: 8 9 12" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 8 9 12" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_12byte_gn, NULL, code) == FFI_OK); + + res_dbl.a = 0; + res_dbl.b = 0; + res_dbl.c = 0; + + res_dbl = ((cls_struct_12byte(*)(cls_struct_12byte, cls_struct_12byte))(code))(h_dbl, j_dbl); + /* { dg-output "\n7 4 9 1 5 3: 8 9 12" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 8 9 12" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_16byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_16byte.c new file mode 100644 index 0000000..89a08a2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_16byte.c @@ -0,0 +1,95 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_16byte { + int a; + double b; + int c; +} cls_struct_16byte; + +cls_struct_16byte cls_struct_16byte_fn(struct cls_struct_16byte b1, + struct cls_struct_16byte b2) +{ + struct cls_struct_16byte result; + + result.a = b1.a + b2.a; + result.b = b1.b + b2.b; + result.c = b1.c + b2.c; + + printf("%d %g %d %d %g %d: %d %g %d\n", b1.a, b1.b, b1.c, b2.a, b2.b, b2.c, + result.a, result.b, result.c); + + return result; +} + +static void cls_struct_16byte_gn(ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) +{ + struct cls_struct_16byte b1, b2; + + b1 = *(struct cls_struct_16byte*)(args[0]); + b2 = *(struct cls_struct_16byte*)(args[1]); + + *(cls_struct_16byte*)resp = cls_struct_16byte_fn(b1, b2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_16byte h_dbl = { 7, 8.0, 9 }; + struct cls_struct_16byte j_dbl = { 1, 9.0, 3 }; + struct cls_struct_16byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_sint; + cls_struct_fields[1] = &ffi_type_double; + cls_struct_fields[2] = &ffi_type_sint; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &h_dbl; + args_dbl[1] = &j_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_16byte_fn), &res_dbl, args_dbl); + /* { dg-output "7 8 9 1 9 3: 8 17 12" } */ + printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 8 17 12" } */ + + res_dbl.a = 0; + res_dbl.b = 0.0; + res_dbl.c = 0; + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_16byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_16byte(*)(cls_struct_16byte, cls_struct_16byte))(code))(h_dbl, j_dbl); + /* { dg-output "\n7 8 9 1 9 3: 8 17 12" } */ + printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 8 17 12" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_18byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_18byte.c new file mode 100644 index 0000000..9f75da8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_18byte.c @@ -0,0 +1,96 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Double alignment check on darwin. + Limitations: none. + PR: none. + Originator: 20030915 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_18byte { + double a; + unsigned char b; + unsigned char c; + double d; +} cls_struct_18byte; + +cls_struct_18byte cls_struct_18byte_fn(struct cls_struct_18byte a1, + struct cls_struct_18byte a2) +{ + struct cls_struct_18byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + result.d = a1.d + a2.d; + + + printf("%g %d %d %g %g %d %d %g: %g %d %d %g\n", a1.a, a1.b, a1.c, a1.d, + a2.a, a2.b, a2.c, a2.d, + result.a, result.b, result.c, result.d); + return result; +} + +static void +cls_struct_18byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct cls_struct_18byte a1, a2; + + a1 = *(struct cls_struct_18byte*)(args[0]); + a2 = *(struct cls_struct_18byte*)(args[1]); + + *(cls_struct_18byte*)resp = cls_struct_18byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[5]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[3]; + + struct cls_struct_18byte g_dbl = { 1.0, 127, 126, 3.0 }; + struct cls_struct_18byte f_dbl = { 4.0, 125, 124, 5.0 }; + struct cls_struct_18byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = &ffi_type_double; + cls_struct_fields[4] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_18byte_fn), &res_dbl, args_dbl); + /* { dg-output "1 127 126 3 4 125 124 5: 5 252 250 8" } */ + printf("res: %g %d %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 5 252 250 8" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_18byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_18byte(*)(cls_struct_18byte, cls_struct_18byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n1 127 126 3 4 125 124 5: 5 252 250 8" } */ + printf("res: %g %d %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 5 252 250 8" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_19byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_19byte.c new file mode 100644 index 0000000..278794b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_19byte.c @@ -0,0 +1,102 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Double alignment check on darwin. + Limitations: none. + PR: none. + Originator: 20030915 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_19byte { + double a; + unsigned char b; + unsigned char c; + double d; + unsigned char e; +} cls_struct_19byte; + +cls_struct_19byte cls_struct_19byte_fn(struct cls_struct_19byte a1, + struct cls_struct_19byte a2) +{ + struct cls_struct_19byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + result.d = a1.d + a2.d; + result.e = a1.e + a2.e; + + + printf("%g %d %d %g %d %g %d %d %g %d: %g %d %d %g %d\n", + a1.a, a1.b, a1.c, a1.d, a1.e, + a2.a, a2.b, a2.c, a2.d, a2.e, + result.a, result.b, result.c, result.d, result.e); + return result; +} + +static void +cls_struct_19byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct cls_struct_19byte a1, a2; + + a1 = *(struct cls_struct_19byte*)(args[0]); + a2 = *(struct cls_struct_19byte*)(args[1]); + + *(cls_struct_19byte*)resp = cls_struct_19byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[6]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[3]; + + struct cls_struct_19byte g_dbl = { 1.0, 127, 126, 3.0, 120 }; + struct cls_struct_19byte f_dbl = { 4.0, 125, 124, 5.0, 119 }; + struct cls_struct_19byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = &ffi_type_double; + cls_struct_fields[4] = &ffi_type_uchar; + cls_struct_fields[5] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_19byte_fn), &res_dbl, args_dbl); + /* { dg-output "1 127 126 3 120 4 125 124 5 119: 5 252 250 8 239" } */ + printf("res: %g %d %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e); + /* { dg-output "\nres: 5 252 250 8 239" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_19byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_19byte(*)(cls_struct_19byte, cls_struct_19byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n1 127 126 3 120 4 125 124 5 119: 5 252 250 8 239" } */ + printf("res: %g %d %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e); + /* { dg-output "\nres: 5 252 250 8 239" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_1_1byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_1_1byte.c new file mode 100644 index 0000000..82492c0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_1_1byte.c @@ -0,0 +1,89 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Especially with small structures which may fit in one + register. Depending on the ABI. + Limitations: none. + PR: none. + Originator: 20030902 */ + + + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_1_1byte { + unsigned char a; +} cls_struct_1_1byte; + +cls_struct_1_1byte cls_struct_1_1byte_fn(struct cls_struct_1_1byte a1, + struct cls_struct_1_1byte a2) +{ + struct cls_struct_1_1byte result; + + result.a = a1.a + a2.a; + + printf("%d %d: %d\n", a1.a, a2.a, result.a); + + return result; +} + +static void +cls_struct_1_1byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_1_1byte a1, a2; + + a1 = *(struct cls_struct_1_1byte*)(args[0]); + a2 = *(struct cls_struct_1_1byte*)(args[1]); + + *(cls_struct_1_1byte*)resp = cls_struct_1_1byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[2]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_1_1byte g_dbl = { 12 }; + struct cls_struct_1_1byte f_dbl = { 178 }; + struct cls_struct_1_1byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_1_1byte_fn), &res_dbl, args_dbl); + /* { dg-output "12 178: 190" } */ + printf("res: %d\n", res_dbl.a); + /* { dg-output "\nres: 190" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_1_1byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_1_1byte(*)(cls_struct_1_1byte, cls_struct_1_1byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 178: 190" } */ + printf("res: %d\n", res_dbl.a); + /* { dg-output "\nres: 190" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_20byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_20byte.c new file mode 100644 index 0000000..3f8bb28 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_20byte.c @@ -0,0 +1,91 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_20byte { + double a; + double b; + int c; +} cls_struct_20byte; + +cls_struct_20byte cls_struct_20byte_fn(struct cls_struct_20byte a1, + struct cls_struct_20byte a2) +{ + struct cls_struct_20byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%g %g %d %g %g %d: %g %g %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, + result.a, result.b, result.c); + return result; +} + +static void +cls_struct_20byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct cls_struct_20byte a1, a2; + + a1 = *(struct cls_struct_20byte*)(args[0]); + a2 = *(struct cls_struct_20byte*)(args[1]); + + *(cls_struct_20byte*)resp = cls_struct_20byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_20byte g_dbl = { 1.0, 2.0, 3 }; + struct cls_struct_20byte f_dbl = { 4.0, 5.0, 7 }; + struct cls_struct_20byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_double; + cls_struct_fields[2] = &ffi_type_sint; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_20byte_fn), &res_dbl, args_dbl); + /* { dg-output "1 2 3 4 5 7: 5 7 10" } */ + printf("res: %g %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 5 7 10" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_20byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_20byte(*)(cls_struct_20byte, cls_struct_20byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n1 2 3 4 5 7: 5 7 10" } */ + printf("res: %g %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 5 7 10" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_20byte1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_20byte1.c new file mode 100644 index 0000000..6562727 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_20byte1.c @@ -0,0 +1,93 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + + + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_20byte { + int a; + double b; + double c; +} cls_struct_20byte; + +cls_struct_20byte cls_struct_20byte_fn(struct cls_struct_20byte a1, + struct cls_struct_20byte a2) +{ + struct cls_struct_20byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %g %g %d %g %g: %d %g %g\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, + result.a, result.b, result.c); + return result; +} + +static void +cls_struct_20byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct cls_struct_20byte a1, a2; + + a1 = *(struct cls_struct_20byte*)(args[0]); + a2 = *(struct cls_struct_20byte*)(args[1]); + + *(cls_struct_20byte*)resp = cls_struct_20byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[3]; + + struct cls_struct_20byte g_dbl = { 1, 2.0, 3.0 }; + struct cls_struct_20byte f_dbl = { 4, 5.0, 7.0 }; + struct cls_struct_20byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_sint; + cls_struct_fields[1] = &ffi_type_double; + cls_struct_fields[2] = &ffi_type_double; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_20byte_fn), &res_dbl, args_dbl); + /* { dg-output "1 2 3 4 5 7: 5 7 10" } */ + printf("res: %d %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 5 7 10" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_20byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_20byte(*)(cls_struct_20byte, cls_struct_20byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n1 2 3 4 5 7: 5 7 10" } */ + printf("res: %d %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 5 7 10" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_24byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_24byte.c new file mode 100644 index 0000000..1d82f6e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_24byte.c @@ -0,0 +1,113 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_24byte { + double a; + double b; + int c; + float d; +} cls_struct_24byte; + +cls_struct_24byte cls_struct_24byte_fn(struct cls_struct_24byte b0, + struct cls_struct_24byte b1, + struct cls_struct_24byte b2, + struct cls_struct_24byte b3) +{ + struct cls_struct_24byte result; + + result.a = b0.a + b1.a + b2.a + b3.a; + result.b = b0.b + b1.b + b2.b + b3.b; + result.c = b0.c + b1.c + b2.c + b3.c; + result.d = b0.d + b1.d + b2.d + b3.d; + + printf("%g %g %d %g %g %g %d %g %g %g %d %g %g %g %d %g: %g %g %d %g\n", + b0.a, b0.b, b0.c, b0.d, + b1.a, b1.b, b1.c, b1.d, + b2.a, b2.b, b2.c, b2.d, + b3.a, b3.b, b3.c, b2.d, + result.a, result.b, result.c, result.d); + + return result; +} + +static void +cls_struct_24byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct cls_struct_24byte b0, b1, b2, b3; + + b0 = *(struct cls_struct_24byte*)(args[0]); + b1 = *(struct cls_struct_24byte*)(args[1]); + b2 = *(struct cls_struct_24byte*)(args[2]); + b3 = *(struct cls_struct_24byte*)(args[3]); + + *(cls_struct_24byte*)resp = cls_struct_24byte_fn(b0, b1, b2, b3); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[5]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_24byte e_dbl = { 9.0, 2.0, 6, 5.0 }; + struct cls_struct_24byte f_dbl = { 1.0, 2.0, 3, 7.0 }; + struct cls_struct_24byte g_dbl = { 4.0, 5.0, 7, 9.0 }; + struct cls_struct_24byte h_dbl = { 8.0, 6.0, 1, 4.0 }; + struct cls_struct_24byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_double; + cls_struct_fields[2] = &ffi_type_sint; + cls_struct_fields[3] = &ffi_type_float; + cls_struct_fields[4] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = &cls_struct_type; + dbl_arg_types[3] = &cls_struct_type; + dbl_arg_types[4] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = &h_dbl; + args_dbl[4] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_24byte_fn), &res_dbl, args_dbl); + /* { dg-output "9 2 6 5 1 2 3 7 4 5 7 9 8 6 1 9: 22 15 17 25" } */ + printf("res: %g %g %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 22 15 17 25" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_24byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_24byte(*)(cls_struct_24byte, + cls_struct_24byte, + cls_struct_24byte, + cls_struct_24byte)) + (code))(e_dbl, f_dbl, g_dbl, h_dbl); + /* { dg-output "\n9 2 6 5 1 2 3 7 4 5 7 9 8 6 1 9: 22 15 17 25" } */ + printf("res: %g %g %d %g\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 22 15 17 25" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_2byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_2byte.c new file mode 100644 index 0000000..81bb0a6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_2byte.c @@ -0,0 +1,90 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Especially with small structures which may fit in one + register. Depending on the ABI. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_2byte { + unsigned char a; + unsigned char b; +} cls_struct_2byte; + +cls_struct_2byte cls_struct_2byte_fn(struct cls_struct_2byte a1, + struct cls_struct_2byte a2) +{ + struct cls_struct_2byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + + printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b); + + return result; +} + +static void +cls_struct_2byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_2byte a1, a2; + + a1 = *(struct cls_struct_2byte*)(args[0]); + a2 = *(struct cls_struct_2byte*)(args[1]); + + *(cls_struct_2byte*)resp = cls_struct_2byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_2byte g_dbl = { 12, 127 }; + struct cls_struct_2byte f_dbl = { 1, 13 }; + struct cls_struct_2byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_2byte_fn), &res_dbl, args_dbl); + /* { dg-output "12 127 1 13: 13 140" } */ + printf("res: %d %d\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 13 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_2byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_2byte(*)(cls_struct_2byte, cls_struct_2byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 127 1 13: 13 140" } */ + printf("res: %d %d\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 13 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3_1byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3_1byte.c new file mode 100644 index 0000000..b782746 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3_1byte.c @@ -0,0 +1,95 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Especially with small structures which may fit in one + register. Depending on the ABI. + Limitations: none. + PR: none. + Originator: 20030902 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_3_1byte { + unsigned char a; + unsigned char b; + unsigned char c; +} cls_struct_3_1byte; + +cls_struct_3_1byte cls_struct_3_1byte_fn(struct cls_struct_3_1byte a1, + struct cls_struct_3_1byte a2) +{ + struct cls_struct_3_1byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, + a2.a, a2.b, a2.c, + result.a, result.b, result.c); + + return result; +} + +static void +cls_struct_3_1byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_3_1byte a1, a2; + + a1 = *(struct cls_struct_3_1byte*)(args[0]); + a2 = *(struct cls_struct_3_1byte*)(args[1]); + + *(cls_struct_3_1byte*)resp = cls_struct_3_1byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_3_1byte g_dbl = { 12, 13, 14 }; + struct cls_struct_3_1byte f_dbl = { 178, 179, 180 }; + struct cls_struct_3_1byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_3_1byte_fn), &res_dbl, args_dbl); + /* { dg-output "12 13 14 178 179 180: 190 192 194" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 190 192 194" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3_1byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_3_1byte(*)(cls_struct_3_1byte, cls_struct_3_1byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 13 14 178 179 180: 190 192 194" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 190 192 194" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3byte1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3byte1.c new file mode 100644 index 0000000..a02c463 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3byte1.c @@ -0,0 +1,90 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Especially with small structures which may fit in one + register. Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_3byte { + unsigned short a; + unsigned char b; +} cls_struct_3byte; + +cls_struct_3byte cls_struct_3byte_fn(struct cls_struct_3byte a1, + struct cls_struct_3byte a2) +{ + struct cls_struct_3byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + + printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b); + + return result; +} + +static void +cls_struct_3byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_3byte a1, a2; + + a1 = *(struct cls_struct_3byte*)(args[0]); + a2 = *(struct cls_struct_3byte*)(args[1]); + + *(cls_struct_3byte*)resp = cls_struct_3byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_3byte g_dbl = { 12, 119 }; + struct cls_struct_3byte f_dbl = { 1, 15 }; + struct cls_struct_3byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_ushort; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_3byte_fn), &res_dbl, args_dbl); + /* { dg-output "12 119 1 15: 13 134" } */ + printf("res: %d %d\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 13 134" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_3byte(*)(cls_struct_3byte, cls_struct_3byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 119 1 15: 13 134" } */ + printf("res: %d %d\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 13 134" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3byte2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3byte2.c new file mode 100644 index 0000000..c7251ce --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3byte2.c @@ -0,0 +1,90 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Especially with small structures which may fit in one + register. Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_3byte_1 { + unsigned char a; + unsigned short b; +} cls_struct_3byte_1; + +cls_struct_3byte_1 cls_struct_3byte_fn1(struct cls_struct_3byte_1 a1, + struct cls_struct_3byte_1 a2) +{ + struct cls_struct_3byte_1 result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + + printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b); + + return result; +} + +static void +cls_struct_3byte_gn1(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_3byte_1 a1, a2; + + a1 = *(struct cls_struct_3byte_1*)(args[0]); + a2 = *(struct cls_struct_3byte_1*)(args[1]); + + *(cls_struct_3byte_1*)resp = cls_struct_3byte_fn1(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_3byte_1 g_dbl = { 15, 125 }; + struct cls_struct_3byte_1 f_dbl = { 9, 19 }; + struct cls_struct_3byte_1 res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_ushort; + cls_struct_fields[2] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_3byte_fn1), &res_dbl, args_dbl); + /* { dg-output "15 125 9 19: 24 144" } */ + printf("res: %d %d\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 24 144" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3byte_gn1, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_3byte_1(*)(cls_struct_3byte_1, cls_struct_3byte_1))(code))(g_dbl, f_dbl); + /* { dg-output "\n15 125 9 19: 24 144" } */ + printf("res: %d %d\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 24 144" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3float.c new file mode 100644 index 0000000..48888f8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_3float.c @@ -0,0 +1,95 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations:>none. + PR: none. + Originator: 20171026 */ + +/* { dg-do run } */ + +#include "ffitest.h" + +typedef struct cls_struct_3float { + float f; + float g; + float h; +} cls_struct_3float; + +cls_struct_3float cls_struct_3float_fn(struct cls_struct_3float a1, + struct cls_struct_3float a2) +{ + struct cls_struct_3float result; + + result.f = a1.f + a2.f; + result.g = a1.g + a2.g; + result.h = a1.h + a2.h; + + printf("%g %g %g %g %g %g: %g %g %g\n", a1.f, a1.g, a1.h, + a2.f, a2.g, a2.h, result.f, result.g, result.h); + + return result; +} + +static void +cls_struct_3float_gn(ffi_cif *cif __UNUSED__, void* resp, void **args, + void* userdata __UNUSED__) +{ + struct cls_struct_3float a1, a2; + + a1 = *(struct cls_struct_3float*)(args[0]); + a2 = *(struct cls_struct_3float*)(args[1]); + + *(cls_struct_3float*)resp = cls_struct_3float_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void *args_dbl[3]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[3]; + + struct cls_struct_3float g_dbl = { 1.0f, 2.0f, 3.0f }; + struct cls_struct_3float f_dbl = { 1.0f, 2.0f, 3.0f }; + struct cls_struct_3float res_dbl; + + cls_struct_fields[0] = &ffi_type_float; + cls_struct_fields[1] = &ffi_type_float; + cls_struct_fields[2] = &ffi_type_float; + cls_struct_fields[3] = NULL; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_3float_fn), &res_dbl, args_dbl); + /* { dg-output "1 2 3 1 2 3: 2 4 6" } */ + printf("res: %g %g %g\n", res_dbl.f, res_dbl.g, res_dbl.h); + /* { dg-output "\nres: 2 4 6" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_3float_gn, NULL, code) == + FFI_OK); + + res_dbl = ((cls_struct_3float(*)(cls_struct_3float, + cls_struct_3float))(code))(g_dbl, f_dbl); + /* { dg-output "\n1 2 3 1 2 3: 2 4 6" } */ + printf("res: %g %g %g\n", res_dbl.f, res_dbl.g, res_dbl.h); + /* { dg-output "\nres: 2 4 6" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_4_1byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_4_1byte.c new file mode 100644 index 0000000..2d6d8b6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_4_1byte.c @@ -0,0 +1,98 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Especially with small structures which may fit in one + register. Depending on the ABI. + Limitations: none. + PR: none. + Originator: 20030902 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_4_1byte { + unsigned char a; + unsigned char b; + unsigned char c; + unsigned char d; +} cls_struct_4_1byte; + +cls_struct_4_1byte cls_struct_4_1byte_fn(struct cls_struct_4_1byte a1, + struct cls_struct_4_1byte a2) +{ + struct cls_struct_4_1byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + result.d = a1.d + a2.d; + + printf("%d %d %d %d %d %d %d %d: %d %d %d %d\n", a1.a, a1.b, a1.c, a1.d, + a2.a, a2.b, a2.c, a2.d, + result.a, result.b, result.c, result.d); + + return result; +} + +static void +cls_struct_4_1byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_4_1byte a1, a2; + + a1 = *(struct cls_struct_4_1byte*)(args[0]); + a2 = *(struct cls_struct_4_1byte*)(args[1]); + + *(cls_struct_4_1byte*)resp = cls_struct_4_1byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[5]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_4_1byte g_dbl = { 12, 13, 14, 15 }; + struct cls_struct_4_1byte f_dbl = { 178, 179, 180, 181 }; + struct cls_struct_4_1byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = &ffi_type_uchar; + cls_struct_fields[4] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_4_1byte_fn), &res_dbl, args_dbl); + /* { dg-output "12 13 14 15 178 179 180 181: 190 192 194 196" } */ + printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 190 192 194 196" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_4_1byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_4_1byte(*)(cls_struct_4_1byte, cls_struct_4_1byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 13 14 15 178 179 180 181: 190 192 194 196" } */ + printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 190 192 194 196" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_4byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_4byte.c new file mode 100644 index 0000000..4ac3787 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_4byte.c @@ -0,0 +1,90 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ + +#include "ffitest.h" + +typedef struct cls_struct_4byte { + unsigned short a; + unsigned short b; +} cls_struct_4byte; + +cls_struct_4byte cls_struct_4byte_fn(struct cls_struct_4byte a1, + struct cls_struct_4byte a2) +{ + struct cls_struct_4byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + + printf("%d %d %d %d: %d %d\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b); + + return result; +} + +static void +cls_struct_4byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_4byte a1, a2; + + a1 = *(struct cls_struct_4byte*)(args[0]); + a2 = *(struct cls_struct_4byte*)(args[1]); + + *(cls_struct_4byte*)resp = cls_struct_4byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_4byte g_dbl = { 127, 120 }; + struct cls_struct_4byte f_dbl = { 12, 128 }; + struct cls_struct_4byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_ushort; + cls_struct_fields[1] = &ffi_type_ushort; + cls_struct_fields[2] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_4byte_fn), &res_dbl, args_dbl); + /* { dg-output "127 120 12 128: 139 248" } */ + printf("res: %d %d\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 139 248" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_4byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_4byte(*)(cls_struct_4byte, cls_struct_4byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n127 120 12 128: 139 248" } */ + printf("res: %d %d\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 139 248" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_5_1_byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_5_1_byte.c new file mode 100644 index 0000000..ad9d51c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_5_1_byte.c @@ -0,0 +1,109 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20050708 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_5byte { + unsigned char a; + unsigned char b; + unsigned char c; + unsigned char d; + unsigned char e; +} cls_struct_5byte; + +cls_struct_5byte cls_struct_5byte_fn(struct cls_struct_5byte a1, + struct cls_struct_5byte a2) +{ + struct cls_struct_5byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + result.d = a1.d + a2.d; + result.e = a1.e + a2.e; + + printf("%d %d %d %d %d %d %d %d %d %d: %d %d %d %d %d\n", + a1.a, a1.b, a1.c, a1.d, a1.e, + a2.a, a2.b, a2.c, a2.d, a2.e, + result.a, result.b, result.c, result.d, result.e); + + return result; +} + +static void +cls_struct_5byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_5byte a1, a2; + + a1 = *(struct cls_struct_5byte*)(args[0]); + a2 = *(struct cls_struct_5byte*)(args[1]); + + *(cls_struct_5byte*)resp = cls_struct_5byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[6]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_5byte g_dbl = { 127, 120, 1, 3, 4 }; + struct cls_struct_5byte f_dbl = { 12, 128, 9, 3, 4 }; + struct cls_struct_5byte res_dbl = { 0, 0, 0, 0, 0 }; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = &ffi_type_uchar; + cls_struct_fields[4] = &ffi_type_uchar; + cls_struct_fields[5] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_5byte_fn), &res_dbl, args_dbl); + /* { dg-output "127 120 1 3 4 12 128 9 3 4: 139 248 10 6 8" } */ + printf("res: %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e); + /* { dg-output "\nres: 139 248 10 6 8" } */ + + res_dbl.a = 0; + res_dbl.b = 0; + res_dbl.c = 0; + res_dbl.d = 0; + res_dbl.e = 0; + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_5byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_5byte(*)(cls_struct_5byte, cls_struct_5byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n127 120 1 3 4 12 128 9 3 4: 139 248 10 6 8" } */ + printf("res: %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e); + /* { dg-output "\nres: 139 248 10 6 8" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_5byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_5byte.c new file mode 100644 index 0000000..4e0c000 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_5byte.c @@ -0,0 +1,98 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_5byte { + unsigned short a; + unsigned short b; + unsigned char c; +} cls_struct_5byte; + +cls_struct_5byte cls_struct_5byte_fn(struct cls_struct_5byte a1, + struct cls_struct_5byte a2) +{ + struct cls_struct_5byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, + a2.a, a2.b, a2.c, + result.a, result.b, result.c); + + return result; +} + +static void +cls_struct_5byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_5byte a1, a2; + + a1 = *(struct cls_struct_5byte*)(args[0]); + a2 = *(struct cls_struct_5byte*)(args[1]); + + *(cls_struct_5byte*)resp = cls_struct_5byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_5byte g_dbl = { 127, 120, 1 }; + struct cls_struct_5byte f_dbl = { 12, 128, 9 }; + struct cls_struct_5byte res_dbl = { 0, 0, 0 }; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_ushort; + cls_struct_fields[1] = &ffi_type_ushort; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_5byte_fn), &res_dbl, args_dbl); + /* { dg-output "127 120 1 12 128 9: 139 248 10" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 139 248 10" } */ + + res_dbl.a = 0; + res_dbl.b = 0; + res_dbl.c = 0; + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_5byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_5byte(*)(cls_struct_5byte, cls_struct_5byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n127 120 1 12 128 9: 139 248 10" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 139 248 10" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_64byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_64byte.c new file mode 100644 index 0000000..a55edc2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_64byte.c @@ -0,0 +1,124 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check bigger struct which overlaps + the gp and fp register count on Darwin/AIX/ppc64. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_64byte { + double a; + double b; + double c; + double d; + double e; + double f; + double g; + double h; +} cls_struct_64byte; + +cls_struct_64byte cls_struct_64byte_fn(struct cls_struct_64byte b0, + struct cls_struct_64byte b1, + struct cls_struct_64byte b2, + struct cls_struct_64byte b3) +{ + struct cls_struct_64byte result; + + result.a = b0.a + b1.a + b2.a + b3.a; + result.b = b0.b + b1.b + b2.b + b3.b; + result.c = b0.c + b1.c + b2.c + b3.c; + result.d = b0.d + b1.d + b2.d + b3.d; + result.e = b0.e + b1.e + b2.e + b3.e; + result.f = b0.f + b1.f + b2.f + b3.f; + result.g = b0.g + b1.g + b2.g + b3.g; + result.h = b0.h + b1.h + b2.h + b3.h; + + printf("%g %g %g %g %g %g %g %g\n", result.a, result.b, result.c, + result.d, result.e, result.f, result.g, result.h); + + return result; +} + +static void +cls_struct_64byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct cls_struct_64byte b0, b1, b2, b3; + + b0 = *(struct cls_struct_64byte*)(args[0]); + b1 = *(struct cls_struct_64byte*)(args[1]); + b2 = *(struct cls_struct_64byte*)(args[2]); + b3 = *(struct cls_struct_64byte*)(args[3]); + + *(cls_struct_64byte*)resp = cls_struct_64byte_fn(b0, b1, b2, b3); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[9]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_64byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0 }; + struct cls_struct_64byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0 }; + struct cls_struct_64byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0 }; + struct cls_struct_64byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0 }; + struct cls_struct_64byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_double; + cls_struct_fields[2] = &ffi_type_double; + cls_struct_fields[3] = &ffi_type_double; + cls_struct_fields[4] = &ffi_type_double; + cls_struct_fields[5] = &ffi_type_double; + cls_struct_fields[6] = &ffi_type_double; + cls_struct_fields[7] = &ffi_type_double; + cls_struct_fields[8] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = &cls_struct_type; + dbl_arg_types[3] = &cls_struct_type; + dbl_arg_types[4] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = &h_dbl; + args_dbl[4] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_64byte_fn), &res_dbl, args_dbl); + /* { dg-output "22 15 17 25 6 13 19 18" } */ + printf("res: %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h); + /* { dg-output "\nres: 22 15 17 25 6 13 19 18" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_64byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_64byte(*)(cls_struct_64byte, + cls_struct_64byte, + cls_struct_64byte, + cls_struct_64byte)) + (code))(e_dbl, f_dbl, g_dbl, h_dbl); + /* { dg-output "\n22 15 17 25 6 13 19 18" } */ + printf("res: %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h); + /* { dg-output "\nres: 22 15 17 25 6 13 19 18" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_6_1_byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_6_1_byte.c new file mode 100644 index 0000000..b4dcdba --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_6_1_byte.c @@ -0,0 +1,113 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20050708 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_6byte { + unsigned char a; + unsigned char b; + unsigned char c; + unsigned char d; + unsigned char e; + unsigned char f; +} cls_struct_6byte; + +cls_struct_6byte cls_struct_6byte_fn(struct cls_struct_6byte a1, + struct cls_struct_6byte a2) +{ + struct cls_struct_6byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + result.d = a1.d + a2.d; + result.e = a1.e + a2.e; + result.f = a1.f + a2.f; + + printf("%d %d %d %d %d %d %d %d %d %d %d %d: %d %d %d %d %d %d\n", + a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, + a2.a, a2.b, a2.c, a2.d, a2.e, a2.f, + result.a, result.b, result.c, result.d, result.e, result.f); + + return result; +} + +static void +cls_struct_6byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_6byte a1, a2; + + a1 = *(struct cls_struct_6byte*)(args[0]); + a2 = *(struct cls_struct_6byte*)(args[1]); + + *(cls_struct_6byte*)resp = cls_struct_6byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[7]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_6byte g_dbl = { 127, 120, 1, 3, 4, 5 }; + struct cls_struct_6byte f_dbl = { 12, 128, 9, 3, 4, 5 }; + struct cls_struct_6byte res_dbl = { 0, 0, 0, 0, 0, 0 }; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = &ffi_type_uchar; + cls_struct_fields[4] = &ffi_type_uchar; + cls_struct_fields[5] = &ffi_type_uchar; + cls_struct_fields[6] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_6byte_fn), &res_dbl, args_dbl); + /* { dg-output "127 120 1 3 4 5 12 128 9 3 4 5: 139 248 10 6 8 10" } */ + printf("res: %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e, res_dbl.f); + /* { dg-output "\nres: 139 248 10 6 8 10" } */ + + res_dbl.a = 0; + res_dbl.b = 0; + res_dbl.c = 0; + res_dbl.d = 0; + res_dbl.e = 0; + res_dbl.f = 0; + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_6byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_6byte(*)(cls_struct_6byte, cls_struct_6byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n127 120 1 3 4 5 12 128 9 3 4 5: 139 248 10 6 8 10" } */ + printf("res: %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e, res_dbl.f); + /* { dg-output "\nres: 139 248 10 6 8 10" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_6byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_6byte.c new file mode 100644 index 0000000..7406780 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_6byte.c @@ -0,0 +1,99 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_6byte { + unsigned short a; + unsigned short b; + unsigned char c; + unsigned char d; +} cls_struct_6byte; + +cls_struct_6byte cls_struct_6byte_fn(struct cls_struct_6byte a1, + struct cls_struct_6byte a2) +{ + struct cls_struct_6byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + result.d = a1.d + a2.d; + + printf("%d %d %d %d %d %d %d %d: %d %d %d %d\n", a1.a, a1.b, a1.c, a1.d, + a2.a, a2.b, a2.c, a2.d, + result.a, result.b, result.c, result.d); + + return result; +} + +static void +cls_struct_6byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_6byte a1, a2; + + a1 = *(struct cls_struct_6byte*)(args[0]); + a2 = *(struct cls_struct_6byte*)(args[1]); + + *(cls_struct_6byte*)resp = cls_struct_6byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[5]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_6byte g_dbl = { 127, 120, 1, 128 }; + struct cls_struct_6byte f_dbl = { 12, 128, 9, 127 }; + struct cls_struct_6byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_ushort; + cls_struct_fields[1] = &ffi_type_ushort; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = &ffi_type_uchar; + cls_struct_fields[4] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_6byte_fn), &res_dbl, args_dbl); + /* { dg-output "127 120 1 128 12 128 9 127: 139 248 10 255" } */ + printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 139 248 10 255" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_6byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_6byte(*)(cls_struct_6byte, cls_struct_6byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n127 120 1 128 12 128 9 127: 139 248 10 255" } */ + printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 139 248 10 255" } */ + + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_7_1_byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_7_1_byte.c new file mode 100644 index 0000000..14a7e96 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_7_1_byte.c @@ -0,0 +1,117 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20050708 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_7byte { + unsigned char a; + unsigned char b; + unsigned char c; + unsigned char d; + unsigned char e; + unsigned char f; + unsigned char g; +} cls_struct_7byte; + +cls_struct_7byte cls_struct_7byte_fn(struct cls_struct_7byte a1, + struct cls_struct_7byte a2) +{ + struct cls_struct_7byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + result.d = a1.d + a2.d; + result.e = a1.e + a2.e; + result.f = a1.f + a2.f; + result.g = a1.g + a2.g; + + printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d %d %d %d %d %d %d\n", + a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g, + a2.a, a2.b, a2.c, a2.d, a2.e, a2.f, a2.g, + result.a, result.b, result.c, result.d, result.e, result.f, result.g); + + return result; +} + +static void +cls_struct_7byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_7byte a1, a2; + + a1 = *(struct cls_struct_7byte*)(args[0]); + a2 = *(struct cls_struct_7byte*)(args[1]); + + *(cls_struct_7byte*)resp = cls_struct_7byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[8]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_7byte g_dbl = { 127, 120, 1, 3, 4, 5, 6 }; + struct cls_struct_7byte f_dbl = { 12, 128, 9, 3, 4, 5, 6 }; + struct cls_struct_7byte res_dbl = { 0, 0, 0, 0, 0, 0, 0 }; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = &ffi_type_uchar; + cls_struct_fields[4] = &ffi_type_uchar; + cls_struct_fields[5] = &ffi_type_uchar; + cls_struct_fields[6] = &ffi_type_uchar; + cls_struct_fields[7] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_7byte_fn), &res_dbl, args_dbl); + /* { dg-output "127 120 1 3 4 5 6 12 128 9 3 4 5 6: 139 248 10 6 8 10 12" } */ + printf("res: %d %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g); + /* { dg-output "\nres: 139 248 10 6 8 10 12" } */ + + res_dbl.a = 0; + res_dbl.b = 0; + res_dbl.c = 0; + res_dbl.d = 0; + res_dbl.e = 0; + res_dbl.f = 0; + res_dbl.g = 0; + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_7byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_7byte(*)(cls_struct_7byte, cls_struct_7byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n127 120 1 3 4 5 6 12 128 9 3 4 5 6: 139 248 10 6 8 10 12" } */ + printf("res: %d %d %d %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g); + /* { dg-output "\nres: 139 248 10 6 8 10 12" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_7byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_7byte.c new file mode 100644 index 0000000..1645cc6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_7byte.c @@ -0,0 +1,97 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_7byte { + unsigned short a; + unsigned short b; + unsigned char c; + unsigned short d; +} cls_struct_7byte; + +cls_struct_7byte cls_struct_7byte_fn(struct cls_struct_7byte a1, + struct cls_struct_7byte a2) +{ + struct cls_struct_7byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + result.d = a1.d + a2.d; + + printf("%d %d %d %d %d %d %d %d: %d %d %d %d\n", a1.a, a1.b, a1.c, a1.d, + a2.a, a2.b, a2.c, a2.d, + result.a, result.b, result.c, result.d); + + return result; +} + +static void +cls_struct_7byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_7byte a1, a2; + + a1 = *(struct cls_struct_7byte*)(args[0]); + a2 = *(struct cls_struct_7byte*)(args[1]); + + *(cls_struct_7byte*)resp = cls_struct_7byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[5]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_7byte g_dbl = { 127, 120, 1, 254 }; + struct cls_struct_7byte f_dbl = { 12, 128, 9, 255 }; + struct cls_struct_7byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_ushort; + cls_struct_fields[1] = &ffi_type_ushort; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = &ffi_type_ushort; + cls_struct_fields[4] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_7byte_fn), &res_dbl, args_dbl); + /* { dg-output "127 120 1 254 12 128 9 255: 139 248 10 509" } */ + printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 139 248 10 509" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_7byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_7byte(*)(cls_struct_7byte, cls_struct_7byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n127 120 1 254 12 128 9 255: 139 248 10 509" } */ + printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 139 248 10 509" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_8byte.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_8byte.c new file mode 100644 index 0000000..f6c1ea5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_8byte.c @@ -0,0 +1,88 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_8byte { + int a; + float b; +} cls_struct_8byte; + +cls_struct_8byte cls_struct_8byte_fn(struct cls_struct_8byte a1, + struct cls_struct_8byte a2) +{ + struct cls_struct_8byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + + printf("%d %g %d %g: %d %g\n", a1.a, a1.b, a2.a, a2.b, result.a, result.b); + + return result; +} + +static void +cls_struct_8byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_8byte a1, a2; + + a1 = *(struct cls_struct_8byte*)(args[0]); + a2 = *(struct cls_struct_8byte*)(args[1]); + + *(cls_struct_8byte*)resp = cls_struct_8byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_8byte g_dbl = { 1, 2.0 }; + struct cls_struct_8byte f_dbl = { 4, 5.0 }; + struct cls_struct_8byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_sint; + cls_struct_fields[1] = &ffi_type_float; + cls_struct_fields[2] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_8byte_fn), &res_dbl, args_dbl); + /* { dg-output "1 2 4 5: 5 7" } */ + printf("res: %d %g\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 5 7" } */ + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_8byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_8byte(*)(cls_struct_8byte, cls_struct_8byte))(code))(g_dbl, f_dbl); + /* { dg-output "\n1 2 4 5: 5 7" } */ + printf("res: %d %g\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 5 7" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_9byte1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_9byte1.c new file mode 100644 index 0000000..0b85722 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_9byte1.c @@ -0,0 +1,90 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Darwin/AIX do double-word + alignment of the struct if the first element is a double. + Check that it does not here. + Limitations: none. + PR: none. + Originator: 20030914 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_9byte { + int a; + double b; +} cls_struct_9byte; + +cls_struct_9byte cls_struct_9byte_fn(struct cls_struct_9byte b1, + struct cls_struct_9byte b2) +{ + struct cls_struct_9byte result; + + result.a = b1.a + b2.a; + result.b = b1.b + b2.b; + + printf("%d %g %d %g: %d %g\n", b1.a, b1.b, b2.a, b2.b, + result.a, result.b); + + return result; +} + +static void cls_struct_9byte_gn(ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) +{ + struct cls_struct_9byte b1, b2; + + b1 = *(struct cls_struct_9byte*)(args[0]); + b2 = *(struct cls_struct_9byte*)(args[1]); + + *(cls_struct_9byte*)resp = cls_struct_9byte_fn(b1, b2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[3]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[3]; + + struct cls_struct_9byte h_dbl = { 7, 8.0}; + struct cls_struct_9byte j_dbl = { 1, 9.0}; + struct cls_struct_9byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_sint; + cls_struct_fields[1] = &ffi_type_double; + cls_struct_fields[2] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &h_dbl; + args_dbl[1] = &j_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_9byte_fn), &res_dbl, args_dbl); + /* { dg-output "7 8 1 9: 8 17" } */ + printf("res: %d %g\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 8 17" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_9byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_9byte(*)(cls_struct_9byte, cls_struct_9byte))(code))(h_dbl, j_dbl); + /* { dg-output "\n7 8 1 9: 8 17" } */ + printf("res: %d %g\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 8 17" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_9byte2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_9byte2.c new file mode 100644 index 0000000..edf991d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_9byte2.c @@ -0,0 +1,91 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Darwin/AIX do double-word + alignment of the struct if the first element is a double. + Check that it does here. + Limitations: none. + PR: none. + Originator: 20030914 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_9byte { + double a; + int b; +} cls_struct_9byte; + +cls_struct_9byte cls_struct_9byte_fn(struct cls_struct_9byte b1, + struct cls_struct_9byte b2) +{ + struct cls_struct_9byte result; + + result.a = b1.a + b2.a; + result.b = b1.b + b2.b; + + printf("%g %d %g %d: %g %d\n", b1.a, b1.b, b2.a, b2.b, + result.a, result.b); + + return result; +} + +static void cls_struct_9byte_gn(ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) +{ + struct cls_struct_9byte b1, b2; + + b1 = *(struct cls_struct_9byte*)(args[0]); + b2 = *(struct cls_struct_9byte*)(args[1]); + + *(cls_struct_9byte*)resp = cls_struct_9byte_fn(b1, b2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[3]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[3]; + + struct cls_struct_9byte h_dbl = { 7.0, 8}; + struct cls_struct_9byte j_dbl = { 1.0, 9}; + struct cls_struct_9byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_sint; + cls_struct_fields[2] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &h_dbl; + args_dbl[1] = &j_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_9byte_fn), &res_dbl, args_dbl); + /* { dg-output "7 8 1 9: 8 17" } */ + printf("res: %g %d\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 8 17" } */ + + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_9byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_9byte(*)(cls_struct_9byte, cls_struct_9byte))(code))(h_dbl, j_dbl); + /* { dg-output "\n7 8 1 9: 8 17" } */ + printf("res: %g %d\n", res_dbl.a, res_dbl.b); + /* { dg-output "\nres: 8 17" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_double.c new file mode 100644 index 0000000..aad5f3c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_double.c @@ -0,0 +1,93 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of double. + Limitations: none. + PR: none. + Originator: 20031203 */ + + + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_align { + unsigned char a; + double b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, + struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %g %d %d %g %d: %d %g %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_align g_dbl = { 12, 4951, 127 }; + struct cls_struct_align f_dbl = { 1, 9320, 13 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_double; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %g %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_float.c new file mode 100644 index 0000000..37e0855 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_float.c @@ -0,0 +1,91 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of float. + Limitations: none. + PR: none. + Originator: 20031203 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_align { + unsigned char a; + float b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, + struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %g %d %d %g %d: %d %g %d\n", a1.a, (double)a1.b, a1.c, a2.a, (double)a2.b, a2.c, result.a, (double)result.b, result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_align g_dbl = { 12, 4951, 127 }; + struct cls_struct_align f_dbl = { 1, 9320, 13 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_float; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_longdouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_longdouble.c new file mode 100644 index 0000000..b3322d8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_longdouble.c @@ -0,0 +1,92 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of long double. + Limitations: none. + PR: none. + Originator: 20031203 */ + +/* { dg-do run } */ + +#include "ffitest.h" + +typedef struct cls_struct_align { + unsigned char a; + long double b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, + struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %g %d %d %g %d: %d %g %d\n", a1.a, (double)a1.b, a1.c, a2.a, (double)a2.b, a2.c, result.a, (double)result.b, result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_align g_dbl = { 12, 4951, 127 }; + struct cls_struct_align f_dbl = { 1, 9320, 13 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_longdouble; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c new file mode 100644 index 0000000..cc1c43b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c @@ -0,0 +1,132 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of long double. + Limitations: none. + PR: none. + Originator: 20031203 */ + +/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ +/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */ + +#include "ffitest.h" + +typedef struct cls_struct_align { + long double a; + long double b; + long double c; + long double d; + long double e; + long double f; + long double g; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn( + cls_struct_align a1, + cls_struct_align a2) +{ + struct cls_struct_align r; + + r.a = a1.a + a2.a; + r.b = a1.b + a2.b; + r.c = a1.c + a2.c; + r.d = a1.d + a2.d; + r.e = a1.e + a2.e; + r.f = a1.f + a2.f; + r.g = a1.g + a2.g; + + printf("%Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg: " + "%Lg %Lg %Lg %Lg %Lg %Lg %Lg\n", + a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g, + a2.a, a2.b, a2.c, a2.d, a2.e, a2.f, a2.g, + r.a, r.b, r.c, r.d, r.e, r.f, r.g); + + return r; +} + +cls_struct_align cls_struct_align_fn2( + cls_struct_align a1) +{ + struct cls_struct_align r; + + r.a = a1.a + 1; + r.b = a1.b + 1; + r.c = a1.c + 1; + r.d = a1.d + 1; + r.e = a1.e + 1; + r.f = a1.f + 1; + r.g = a1.g + 1; + + printf("%Lg %Lg %Lg %Lg %Lg %Lg %Lg: " + "%Lg %Lg %Lg %Lg %Lg %Lg %Lg\n", + a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g, + r.a, r.b, r.c, r.d, r.e, r.f, r.g); + + return r; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[8]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[3]; + + struct cls_struct_align g_dbl = { 1, 2, 3, 4, 5, 6, 7 }; + struct cls_struct_align f_dbl = { 8, 9, 10, 11, 12, 13, 14 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_longdouble; + cls_struct_fields[1] = &ffi_type_longdouble; + cls_struct_fields[2] = &ffi_type_longdouble; + cls_struct_fields[3] = &ffi_type_longdouble; + cls_struct_fields[4] = &ffi_type_longdouble; + cls_struct_fields[5] = &ffi_type_longdouble; + cls_struct_fields[6] = &ffi_type_longdouble; + cls_struct_fields[7] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */ + printf("res: %Lg %Lg %Lg %Lg %Lg %Lg %Lg\n", res_dbl.a, res_dbl.b, + res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g); + /* { dg-output "\nres: 9 11 13 15 17 19 21" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */ + printf("res: %Lg %Lg %Lg %Lg %Lg %Lg %Lg\n", res_dbl.a, res_dbl.b, + res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g); + /* { dg-output "\nres: 9 11 13 15 17 19 21" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c new file mode 100644 index 0000000..5d3bec0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c @@ -0,0 +1,115 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of long double. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/18/2007 +*/ + +/* { dg-do run { xfail strongarm*-*-* } } */ +/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */ + +#include "ffitest.h" + +typedef struct cls_struct_align { + long double a; + long double b; + long double c; + long double d; + long double e; + double f; + long double g; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn( + cls_struct_align a1, + cls_struct_align a2) +{ + struct cls_struct_align r; + + r.a = a1.a + a2.a; + r.b = a1.b + a2.b; + r.c = a1.c + a2.c; + r.d = a1.d + a2.d; + r.e = a1.e + a2.e; + r.f = a1.f + a2.f; + r.g = a1.g + a2.g; + + printf("%Lg %Lg %Lg %Lg %Lg %g %Lg %Lg %Lg %Lg %Lg %Lg %g %Lg: " + "%Lg %Lg %Lg %Lg %Lg %g %Lg\n", + a1.a, a1.b, a1.c, a1.d, a1.e, a1.f, a1.g, + a2.a, a2.b, a2.c, a2.d, a2.e, a2.f, a2.g, + r.a, r.b, r.c, r.d, r.e, r.f, r.g); + + return r; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[8]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[3]; + + struct cls_struct_align g_dbl = { 1, 2, 3, 4, 5, 6, 7 }; + struct cls_struct_align f_dbl = { 8, 9, 10, 11, 12, 13, 14 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_longdouble; + cls_struct_fields[1] = &ffi_type_longdouble; + cls_struct_fields[2] = &ffi_type_longdouble; + cls_struct_fields[3] = &ffi_type_longdouble; + cls_struct_fields[4] = &ffi_type_longdouble; + cls_struct_fields[5] = &ffi_type_double; + cls_struct_fields[6] = &ffi_type_longdouble; + cls_struct_fields[7] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */ + printf("res: %Lg %Lg %Lg %Lg %Lg %g %Lg\n", res_dbl.a, res_dbl.b, + res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g); + /* { dg-output "\nres: 9 11 13 15 17 19 21" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n1 2 3 4 5 6 7 8 9 10 11 12 13 14: 9 11 13 15 17 19 21" } */ + printf("res: %Lg %Lg %Lg %Lg %Lg %g %Lg\n", res_dbl.a, res_dbl.b, + res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g); + /* { dg-output "\nres: 9 11 13 15 17 19 21" } */ + + exit(0); +} + + + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_pointer.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_pointer.c new file mode 100644 index 0000000..8fbf36a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_pointer.c @@ -0,0 +1,95 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of pointer. + Limitations: none. + PR: none. + Originator: 20031203 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_align { + unsigned char a; + void *b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, + struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = (void *)((uintptr_t)a1.b + (uintptr_t)a2.b); + result.c = a1.c + a2.c; + + printf("%d %" PRIuPTR " %d %d %" PRIuPTR " %d: %d %" PRIuPTR " %d\n", + a1.a, (uintptr_t)a1.b, a1.c, + a2.a, (uintptr_t)a2.b, a2.c, + result.a, (uintptr_t)result.b, + result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_align g_dbl = { 12, (void *)4951, 127 }; + struct cls_struct_align f_dbl = { 1, (void *)9320, 13 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_pointer; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %" PRIuPTR " %d\n", res_dbl.a, (uintptr_t)res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %" PRIuPTR " %d\n", res_dbl.a, (uintptr_t)res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_sint16.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_sint16.c new file mode 100644 index 0000000..039b874 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_sint16.c @@ -0,0 +1,91 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of sint16. + Limitations: none. + PR: none. + Originator: 20031203 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_align { + unsigned char a; + signed short b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, + struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_align g_dbl = { 12, 4951, 127 }; + struct cls_struct_align f_dbl = { 1, 9320, 13 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_sshort; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_sint32.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_sint32.c new file mode 100644 index 0000000..c96c6d1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_sint32.c @@ -0,0 +1,91 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of sint32. + Limitations: none. + PR: none. + Originator: 20031203 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_align { + unsigned char a; + signed int b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, + struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_align g_dbl = { 12, 4951, 127 }; + struct cls_struct_align f_dbl = { 1, 9320, 13 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_sint; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_sint64.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_sint64.c new file mode 100644 index 0000000..9aa7bdd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_sint64.c @@ -0,0 +1,92 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of sint64. + Limitations: none. + PR: none. + Originator: 20031203 */ + +/* { dg-do run } */ +/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */ +#include "ffitest.h" + +typedef struct cls_struct_align { + unsigned char a; + signed long long b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, + struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %" PRIdLL " %d %d %" PRIdLL " %d: %d %" PRIdLL " %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_align g_dbl = { 12, 4951, 127 }; + struct cls_struct_align f_dbl = { 1, 9320, 13 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_sint64; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_uint16.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_uint16.c new file mode 100644 index 0000000..97620b7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_uint16.c @@ -0,0 +1,91 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of uint16. + Limitations: none. + PR: none. + Originator: 20031203 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_align { + unsigned char a; + unsigned short b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, + struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_align g_dbl = { 12, 4951, 127 }; + struct cls_struct_align f_dbl = { 1, 9320, 13 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_ushort; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_uint32.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_uint32.c new file mode 100644 index 0000000..5766fad --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_uint32.c @@ -0,0 +1,91 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of uint32. + Limitations: none. + PR: none. + Originator: 20031203 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_align { + unsigned char a; + unsigned int b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, + struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_align g_dbl = { 12, 4951, 127 }; + struct cls_struct_align f_dbl = { 1, 9320, 13 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_uint; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_uint64.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_uint64.c new file mode 100644 index 0000000..a52cb89 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_align_uint64.c @@ -0,0 +1,93 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of uint64. + Limitations: none. + PR: none. + Originator: 20031203 */ + + +/* { dg-do run } */ +/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */ +#include "ffitest.h" + +typedef struct cls_struct_align { + unsigned char a; + unsigned long long b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, + struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %" PRIdLL " %d %d %" PRIdLL " %d: %d %" PRIdLL " %d\n", a1.a, a1.b, a1.c, a2.a, a2.b, a2.c, result.a, result.b, result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_align g_dbl = { 12, 4951, 127 }; + struct cls_struct_align f_dbl = { 1, 9320, 13 }; + struct cls_struct_align res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_uint64; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); + /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %" PRIdLL " %d\n", res_dbl.a, res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_dbls_struct.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_dbls_struct.c new file mode 100644 index 0000000..e451dea --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_dbls_struct.c @@ -0,0 +1,66 @@ +/* Area: ffi_call, closure_call + Purpose: Check double arguments in structs. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/23/2007 */ + +/* { dg-do run } */ + +#include "ffitest.h" + +typedef struct Dbls { + double x; + double y; +} Dbls; + +void +closure_test_fn(Dbls p) +{ + printf("%.1f %.1f\n", p.x, p.y); +} + +void +closure_test_gn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__, + void** args, void* userdata __UNUSED__) +{ + closure_test_fn(*(Dbls*)args[0]); +} + +int main(int argc __UNUSED__, char** argv __UNUSED__) +{ + ffi_cif cif; + + void *code; + ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type* cl_arg_types[1]; + + ffi_type ts1_type; + ffi_type* ts1_type_elements[4]; + + Dbls arg = { 1.0, 2.0 }; + + ts1_type.size = 0; + ts1_type.alignment = 0; + ts1_type.type = FFI_TYPE_STRUCT; + ts1_type.elements = ts1_type_elements; + + ts1_type_elements[0] = &ffi_type_double; + ts1_type_elements[1] = &ffi_type_double; + ts1_type_elements[2] = NULL; + + cl_arg_types[0] = &ts1_type; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_void, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_gn, NULL, code) == FFI_OK); + + ((void*(*)(Dbls))(code))(arg); + /* { dg-output "1.0 2.0" } */ + + closure_test_fn(arg); + /* { dg-output "\n1.0 2.0" } */ + + return 0; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_double.c new file mode 100644 index 0000000..84ad4cb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_double.c @@ -0,0 +1,43 @@ +/* Area: closure_call + Purpose: Check return value double. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void cls_ret_double_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) + { + *(double *)resp = *(double *)args[0]; + + printf("%f: %f\n",*(double *)args[0], + *(double *)resp); + } +typedef double (*cls_ret_double)(double); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[2]; + double res; + + cl_arg_types[0] = &ffi_type_double; + cl_arg_types[1] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_double, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_double_fn, NULL, code) == FFI_OK); + + res = (*((cls_ret_double)code))(21474.789); + /* { dg-output "21474.789000: 21474.789000" } */ + printf("res: %.6f\n", res); + /* { dg-output "\nres: 21474.789000" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_double_va.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_double_va.c new file mode 100644 index 0000000..e077f92 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_double_va.c @@ -0,0 +1,61 @@ +/* Area: ffi_call, closure_call + Purpose: Test doubles passed in variable argument lists. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/6/2007 */ + +/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ +/* { dg-output "" { xfail avr32*-*-* } } */ +/* { dg-output "" { xfail mips-sgi-irix6* } } PR libffi/46660 */ + +#include "ffitest.h" + +static void +cls_double_va_fn(ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) +{ + char* format = *(char**)args[0]; + double doubleValue = *(double*)args[1]; + + *(ffi_arg*)resp = printf(format, doubleValue); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args[3]; + ffi_type* arg_types[3]; + + char* format = "%.1f\n"; + double doubleArg = 7; + ffi_arg res = 0; + + arg_types[0] = &ffi_type_pointer; + arg_types[1] = &ffi_type_double; + arg_types[2] = NULL; + + /* This printf call is variadic */ + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2, &ffi_type_sint, + arg_types) == FFI_OK); + + args[0] = &format; + args[1] = &doubleArg; + args[2] = NULL; + + ffi_call(&cif, FFI_FN(printf), &res, args); + /* { dg-output "7.0" } */ + printf("res: %d\n", (int) res); + /* { dg-output "\nres: 4" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_double_va_fn, NULL, + code) == FFI_OK); + + res = ((int(*)(char*, ...))(code))(format, doubleArg); + /* { dg-output "\n7.0" } */ + printf("res: %d\n", (int) res); + /* { dg-output "\nres: 4" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_float.c new file mode 100644 index 0000000..0090fed --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_float.c @@ -0,0 +1,42 @@ +/* Area: closure_call + Purpose: Check return value float. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void cls_ret_float_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) + { + *(float *)resp = *(float *)args[0]; + + printf("%g: %g\n",*(float *)args[0], + *(float *)resp); + } + +typedef float (*cls_ret_float)(float); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[2]; + float res; + + cl_arg_types[0] = &ffi_type_float; + cl_arg_types[1] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_float, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_float_fn, NULL, code) == FFI_OK); + res = ((((cls_ret_float)code)(-2122.12))); + /* { dg-output "\\-2122.12: \\-2122.12" } */ + printf("res: %.6f\n", res); + /* { dg-output "\nres: \-2122.120117" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_longdouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_longdouble.c new file mode 100644 index 0000000..d24e72e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_longdouble.c @@ -0,0 +1,105 @@ +/* Area: ffi_call, closure_call + Purpose: Check long double arguments. + Limitations: none. + PR: none. + Originator: Blake Chaffin */ + +/* This test is known to PASS on armv7l-unknown-linux-gnueabihf, so I have + remove the xfail for arm*-*-* below, until we know more. */ +/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ +/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */ + +#include "ffitest.h" + +long double cls_ldouble_fn( + long double a1, + long double a2, + long double a3, + long double a4, + long double a5, + long double a6, + long double a7, + long double a8) +{ + long double r = a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8; + + printf("%Lg %Lg %Lg %Lg %Lg %Lg %Lg %Lg: %Lg\n", + a1, a2, a3, a4, a5, a6, a7, a8, r); + + return r; +} + +static void +cls_ldouble_gn(ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) +{ + long double a1 = *(long double*)args[0]; + long double a2 = *(long double*)args[1]; + long double a3 = *(long double*)args[2]; + long double a4 = *(long double*)args[3]; + long double a5 = *(long double*)args[4]; + long double a6 = *(long double*)args[5]; + long double a7 = *(long double*)args[6]; + long double a8 = *(long double*)args[7]; + + *(long double*)resp = cls_ldouble_fn( + a1, a2, a3, a4, a5, a6, a7, a8); +} + +int main(void) +{ + ffi_cif cif; + void* code; + ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args[9]; + ffi_type* arg_types[9]; + long double res = 0; + + long double arg1 = 1; + long double arg2 = 2; + long double arg3 = 3; + long double arg4 = 4; + long double arg5 = 5; + long double arg6 = 6; + long double arg7 = 7; + long double arg8 = 8; + + arg_types[0] = &ffi_type_longdouble; + arg_types[1] = &ffi_type_longdouble; + arg_types[2] = &ffi_type_longdouble; + arg_types[3] = &ffi_type_longdouble; + arg_types[4] = &ffi_type_longdouble; + arg_types[5] = &ffi_type_longdouble; + arg_types[6] = &ffi_type_longdouble; + arg_types[7] = &ffi_type_longdouble; + arg_types[8] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 8, &ffi_type_longdouble, + arg_types) == FFI_OK); + + args[0] = &arg1; + args[1] = &arg2; + args[2] = &arg3; + args[3] = &arg4; + args[4] = &arg5; + args[5] = &arg6; + args[6] = &arg7; + args[7] = &arg8; + args[8] = NULL; + + ffi_call(&cif, FFI_FN(cls_ldouble_fn), &res, args); + /* { dg-output "1 2 3 4 5 6 7 8: 36" } */ + printf("res: %Lg\n", res); + /* { dg-output "\nres: 36" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ldouble_gn, NULL, code) == FFI_OK); + + res = ((long double(*)(long double, long double, long double, long double, + long double, long double, long double, long double))(code))(arg1, arg2, + arg3, arg4, arg5, arg6, arg7, arg8); + /* { dg-output "\n1 2 3 4 5 6 7 8: 36" } */ + printf("res: %Lg\n", res); + /* { dg-output "\nres: 36" } */ + + return 0; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_longdouble_va.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_longdouble_va.c new file mode 100644 index 0000000..39b438b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_longdouble_va.c @@ -0,0 +1,61 @@ +/* Area: ffi_call, closure_call + Purpose: Test long doubles passed in variable argument lists. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/6/2007 */ + +/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ +/* { dg-output "" { xfail avr32*-*-* x86_64-*-mingw* } } */ +/* { dg-output "" { xfail mips-sgi-irix6* } } PR libffi/46660 */ + +#include "ffitest.h" + +static void +cls_longdouble_va_fn(ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) +{ + char* format = *(char**)args[0]; + long double ldValue = *(long double*)args[1]; + + *(ffi_arg*)resp = printf(format, ldValue); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args[3]; + ffi_type* arg_types[3]; + + char* format = "%.1Lf\n"; + long double ldArg = 7; + ffi_arg res = 0; + + arg_types[0] = &ffi_type_pointer; + arg_types[1] = &ffi_type_longdouble; + arg_types[2] = NULL; + + /* This printf call is variadic */ + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2, &ffi_type_sint, + arg_types) == FFI_OK); + + args[0] = &format; + args[1] = &ldArg; + args[2] = NULL; + + ffi_call(&cif, FFI_FN(printf), &res, args); + /* { dg-output "7.0" } */ + printf("res: %d\n", (int) res); + /* { dg-output "\nres: 4" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_longdouble_va_fn, NULL, + code) == FFI_OK); + + res = ((int(*)(char*, ...))(code))(format, ldArg); + /* { dg-output "\n7.0" } */ + printf("res: %d\n", (int) res); + /* { dg-output "\nres: 4" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_many_mixed_args.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_many_mixed_args.c new file mode 100644 index 0000000..7fd6c82 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_many_mixed_args.c @@ -0,0 +1,70 @@ +/* Area: closure_call + Purpose: Check closures called with many args of mixed types + Limitations: none. + PR: none. + Originator: */ + +/* { dg-do run } */ +#include "ffitest.h" +#include +#include + +#define NARGS 16 + +static void cls_ret_double_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + int i; + double r = 0; + double t; + for(i = 0; i < NARGS; i++) + { + if(i == 4 || i == 9 || i == 11 || i == 13 || i == 15) + { + t = *(long int *)args[i]; + CHECK(t == i+1); + } + else + { + t = *(double *)args[i]; + CHECK(fabs(t - ((i+1) * 0.1)) < FLT_EPSILON); + } + r += t; + } + *(double *)resp = r; +} +typedef double (*cls_ret_double)(double, double, double, double, long int, +double, double, double, double, long int, double, long int, double, long int, +double, long int); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[NARGS]; + double res; + int i; + double expected = 64.9; + + for(i = 0; i < NARGS; i++) + { + if(i == 4 || i == 9 || i == 11 || i == 13 || i == 15) + cl_arg_types[i] = &ffi_type_slong; + else + cl_arg_types[i] = &ffi_type_double; + } + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NARGS, + &ffi_type_double, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_double_fn, NULL, code) == FFI_OK); + + res = (((cls_ret_double)code))(0.1, 0.2, 0.3, 0.4, 5, 0.6, 0.7, 0.8, 0.9, 10, + 1.1, 12, 1.3, 14, 1.5, 16); + if (fabs(res - expected) < FLT_EPSILON) + exit(0); + else + abort(); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_many_mixed_float_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_many_mixed_float_double.c new file mode 100644 index 0000000..62b0697 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_many_mixed_float_double.c @@ -0,0 +1,55 @@ +/* Area: closure_call + Purpose: Check register allocation for closure calls with many float and double arguments + Limitations: none. + PR: none. + Originator: */ + +/* { dg-do run } */ +#include "ffitest.h" +#include +#include + +#define NARGS 16 + +static void cls_mixed_float_double_fn(ffi_cif* cif , void* ret, void** args, + void* userdata __UNUSED__) +{ + double r = 0; + unsigned int i; + double t; + for(i=0; i < cif->nargs; i++) + { + if(cif->arg_types[i] == &ffi_type_double) { + t = *(((double**)(args))[i]); + } else { + t = *(((float**)(args))[i]); + } + r += t; + } + *((double*)ret) = r; +} +typedef double (*cls_mixed)(double, float, double, double, double, double, double, float, float, double, float, float); + +int main (void) +{ + ffi_cif cif; + ffi_closure *closure; + void* code; + ffi_type *argtypes[12] = {&ffi_type_double, &ffi_type_float, &ffi_type_double, + &ffi_type_double, &ffi_type_double, &ffi_type_double, + &ffi_type_double, &ffi_type_float, &ffi_type_float, + &ffi_type_double, &ffi_type_float, &ffi_type_float}; + + + closure = ffi_closure_alloc(sizeof(ffi_closure), (void**)&code); + if(closure ==NULL) + abort(); + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 12, &ffi_type_double, argtypes) == FFI_OK); + CHECK(ffi_prep_closure_loc(closure, &cif, cls_mixed_float_double_fn, NULL, code) == FFI_OK); + double ret = ((cls_mixed)code)(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2); + ffi_closure_free(closure); + if(fabs(ret - 7.8) < FLT_EPSILON) + exit(0); + else + abort(); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_schar.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_schar.c new file mode 100644 index 0000000..71df7b6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_schar.c @@ -0,0 +1,74 @@ +/* Area: ffi_call, closure_call + Purpose: Check passing of multiple signed char values. + Limitations: none. + PR: PR13221. + Originator: 20031129 */ + +/* { dg-do run } */ +#include "ffitest.h" + +signed char test_func_fn(signed char a1, signed char a2) +{ + signed char result; + + result = a1 + a2; + + printf("%d %d: %d\n", a1, a2, result); + + return result; + +} + +static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals, + void *data __UNUSED__) +{ + signed char a1, a2; + + a1 = *(signed char *)avals[0]; + a2 = *(signed char *)avals[1]; + + *(ffi_arg *)rval = test_func_fn(a1, a2); + +} + +typedef signed char (*test_type)(signed char, signed char); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void * args_dbl[3]; + ffi_type * cl_arg_types[3]; + ffi_arg res_call; + signed char a, b, res_closure; + + a = 2; + b = 125; + + args_dbl[0] = &a; + args_dbl[1] = &b; + args_dbl[2] = NULL; + + cl_arg_types[0] = &ffi_type_schar; + cl_arg_types[1] = &ffi_type_schar; + cl_arg_types[2] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, + &ffi_type_schar, cl_arg_types) == FFI_OK); + + ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl); + /* { dg-output "2 125: 127" } */ + printf("res: %d\n", (signed char)res_call); + /* { dg-output "\nres: 127" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK); + + res_closure = (*((test_type)code))(2, 125); + /* { dg-output "\n2 125: 127" } */ + printf("res: %d\n", res_closure); + /* { dg-output "\nres: 127" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_sshort.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_sshort.c new file mode 100644 index 0000000..4c39153 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_sshort.c @@ -0,0 +1,74 @@ +/* Area: ffi_call, closure_call + Purpose: Check passing of multiple signed short values. + Limitations: none. + PR: PR13221. + Originator: 20031129 */ + +/* { dg-do run } */ +#include "ffitest.h" + +signed short test_func_fn(signed short a1, signed short a2) +{ + signed short result; + + result = a1 + a2; + + printf("%d %d: %d\n", a1, a2, result); + + return result; + +} + +static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals, + void *data __UNUSED__) +{ + signed short a1, a2; + + a1 = *(signed short *)avals[0]; + a2 = *(signed short *)avals[1]; + + *(ffi_arg *)rval = test_func_fn(a1, a2); + +} + +typedef signed short (*test_type)(signed short, signed short); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void * args_dbl[3]; + ffi_type * cl_arg_types[3]; + ffi_arg res_call; + unsigned short a, b, res_closure; + + a = 2; + b = 32765; + + args_dbl[0] = &a; + args_dbl[1] = &b; + args_dbl[2] = NULL; + + cl_arg_types[0] = &ffi_type_sshort; + cl_arg_types[1] = &ffi_type_sshort; + cl_arg_types[2] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, + &ffi_type_sshort, cl_arg_types) == FFI_OK); + + ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl); + /* { dg-output "2 32765: 32767" } */ + printf("res: %d\n", (unsigned short)res_call); + /* { dg-output "\nres: 32767" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK); + + res_closure = (*((test_type)code))(2, 32765); + /* { dg-output "\n2 32765: 32767" } */ + printf("res: %d\n", res_closure); + /* { dg-output "\nres: 32767" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_sshortchar.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_sshortchar.c new file mode 100644 index 0000000..1c3aeb5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_sshortchar.c @@ -0,0 +1,86 @@ +/* Area: ffi_call, closure_call + Purpose: Check passing of multiple signed short/char values. + Limitations: none. + PR: PR13221. + Originator: 20031129 */ + +/* { dg-do run } */ +#include "ffitest.h" + +signed short test_func_fn(signed char a1, signed short a2, + signed char a3, signed short a4) +{ + signed short result; + + result = a1 + a2 + a3 + a4; + + printf("%d %d %d %d: %d\n", a1, a2, a3, a4, result); + + return result; + +} + +static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals, + void *data __UNUSED__) +{ + signed char a1, a3; + signed short a2, a4; + + a1 = *(signed char *)avals[0]; + a2 = *(signed short *)avals[1]; + a3 = *(signed char *)avals[2]; + a4 = *(signed short *)avals[3]; + + *(ffi_arg *)rval = test_func_fn(a1, a2, a3, a4); + +} + +typedef signed short (*test_type)(signed char, signed short, + signed char, signed short); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void * args_dbl[5]; + ffi_type * cl_arg_types[5]; + ffi_arg res_call; + signed char a, c; + signed short b, d, res_closure; + + a = 1; + b = 32765; + c = 127; + d = -128; + + args_dbl[0] = &a; + args_dbl[1] = &b; + args_dbl[2] = &c; + args_dbl[3] = &d; + args_dbl[4] = NULL; + + cl_arg_types[0] = &ffi_type_schar; + cl_arg_types[1] = &ffi_type_sshort; + cl_arg_types[2] = &ffi_type_schar; + cl_arg_types[3] = &ffi_type_sshort; + cl_arg_types[4] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, + &ffi_type_sshort, cl_arg_types) == FFI_OK); + + ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl); + /* { dg-output "1 32765 127 -128: 32765" } */ + printf("res: %d\n", (signed short)res_call); + /* { dg-output "\nres: 32765" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK); + + res_closure = (*((test_type)code))(1, 32765, 127, -128); + /* { dg-output "\n1 32765 127 -128: 32765" } */ + printf("res: %d\n", res_closure); + /* { dg-output "\nres: 32765" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_uchar.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_uchar.c new file mode 100644 index 0000000..009c02c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_uchar.c @@ -0,0 +1,91 @@ +/* Area: ffi_call, closure_call + Purpose: Check passing of multiple unsigned char values. + Limitations: none. + PR: PR13221. + Originator: 20031129 */ + +/* { dg-do run } */ +#include "ffitest.h" + +unsigned char test_func_fn(unsigned char a1, unsigned char a2, + unsigned char a3, unsigned char a4) +{ + unsigned char result; + + result = a1 + a2 + a3 + a4; + + printf("%d %d %d %d: %d\n", a1, a2, a3, a4, result); + + return result; + +} + +static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals, + void *data __UNUSED__) +{ + unsigned char a1, a2, a3, a4; + + a1 = *(unsigned char *)avals[0]; + a2 = *(unsigned char *)avals[1]; + a3 = *(unsigned char *)avals[2]; + a4 = *(unsigned char *)avals[3]; + + *(ffi_arg *)rval = test_func_fn(a1, a2, a3, a4); + +} + +typedef unsigned char (*test_type)(unsigned char, unsigned char, + unsigned char, unsigned char); + +void test_func(ffi_cif *cif __UNUSED__, void *rval __UNUSED__, void **avals, + void *data __UNUSED__) +{ + printf("%d %d %d %d\n", *(unsigned char *)avals[0], + *(unsigned char *)avals[1], *(unsigned char *)avals[2], + *(unsigned char *)avals[3]); +} +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void * args_dbl[5]; + ffi_type * cl_arg_types[5]; + ffi_arg res_call; + unsigned char a, b, c, d, res_closure; + + a = 1; + b = 2; + c = 127; + d = 125; + + args_dbl[0] = &a; + args_dbl[1] = &b; + args_dbl[2] = &c; + args_dbl[3] = &d; + args_dbl[4] = NULL; + + cl_arg_types[0] = &ffi_type_uchar; + cl_arg_types[1] = &ffi_type_uchar; + cl_arg_types[2] = &ffi_type_uchar; + cl_arg_types[3] = &ffi_type_uchar; + cl_arg_types[4] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, + &ffi_type_uchar, cl_arg_types) == FFI_OK); + + ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl); + /* { dg-output "1 2 127 125: 255" } */ + printf("res: %d\n", (unsigned char)res_call); + /* { dg-output "\nres: 255" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK); + + res_closure = (*((test_type)code))(1, 2, 127, 125); + /* { dg-output "\n1 2 127 125: 255" } */ + printf("res: %d\n", res_closure); + /* { dg-output "\nres: 255" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_ushort.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_ushort.c new file mode 100644 index 0000000..dd10ca7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_ushort.c @@ -0,0 +1,74 @@ +/* Area: ffi_call, closure_call + Purpose: Check passing of multiple unsigned short values. + Limitations: none. + PR: PR13221. + Originator: 20031129 */ + +/* { dg-do run } */ +#include "ffitest.h" + +unsigned short test_func_fn(unsigned short a1, unsigned short a2) +{ + unsigned short result; + + result = a1 + a2; + + printf("%d %d: %d\n", a1, a2, result); + + return result; + +} + +static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals, + void *data __UNUSED__) +{ + unsigned short a1, a2; + + a1 = *(unsigned short *)avals[0]; + a2 = *(unsigned short *)avals[1]; + + *(ffi_arg *)rval = test_func_fn(a1, a2); + +} + +typedef unsigned short (*test_type)(unsigned short, unsigned short); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void * args_dbl[3]; + ffi_type * cl_arg_types[3]; + ffi_arg res_call; + unsigned short a, b, res_closure; + + a = 2; + b = 32765; + + args_dbl[0] = &a; + args_dbl[1] = &b; + args_dbl[2] = NULL; + + cl_arg_types[0] = &ffi_type_ushort; + cl_arg_types[1] = &ffi_type_ushort; + cl_arg_types[2] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, + &ffi_type_ushort, cl_arg_types) == FFI_OK); + + ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl); + /* { dg-output "2 32765: 32767" } */ + printf("res: %d\n", (unsigned short)res_call); + /* { dg-output "\nres: 32767" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK); + + res_closure = (*((test_type)code))(2, 32765); + /* { dg-output "\n2 32765: 32767" } */ + printf("res: %d\n", res_closure); + /* { dg-output "\nres: 32767" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_ushortchar.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_ushortchar.c new file mode 100644 index 0000000..2588e97 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_multi_ushortchar.c @@ -0,0 +1,86 @@ +/* Area: ffi_call, closure_call + Purpose: Check passing of multiple unsigned short/char values. + Limitations: none. + PR: PR13221. + Originator: 20031129 */ + +/* { dg-do run } */ +#include "ffitest.h" + +unsigned short test_func_fn(unsigned char a1, unsigned short a2, + unsigned char a3, unsigned short a4) +{ + unsigned short result; + + result = a1 + a2 + a3 + a4; + + printf("%d %d %d %d: %d\n", a1, a2, a3, a4, result); + + return result; + +} + +static void test_func_gn(ffi_cif *cif __UNUSED__, void *rval, void **avals, + void *data __UNUSED__) +{ + unsigned char a1, a3; + unsigned short a2, a4; + + a1 = *(unsigned char *)avals[0]; + a2 = *(unsigned short *)avals[1]; + a3 = *(unsigned char *)avals[2]; + a4 = *(unsigned short *)avals[3]; + + *(ffi_arg *)rval = test_func_fn(a1, a2, a3, a4); + +} + +typedef unsigned short (*test_type)(unsigned char, unsigned short, + unsigned char, unsigned short); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void * args_dbl[5]; + ffi_type * cl_arg_types[5]; + ffi_arg res_call; + unsigned char a, c; + unsigned short b, d, res_closure; + + a = 1; + b = 2; + c = 127; + d = 128; + + args_dbl[0] = &a; + args_dbl[1] = &b; + args_dbl[2] = &c; + args_dbl[3] = &d; + args_dbl[4] = NULL; + + cl_arg_types[0] = &ffi_type_uchar; + cl_arg_types[1] = &ffi_type_ushort; + cl_arg_types[2] = &ffi_type_uchar; + cl_arg_types[3] = &ffi_type_ushort; + cl_arg_types[4] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, + &ffi_type_ushort, cl_arg_types) == FFI_OK); + + ffi_call(&cif, FFI_FN(test_func_fn), &res_call, args_dbl); + /* { dg-output "1 2 127 128: 258" } */ + printf("res: %d\n", (unsigned short)res_call); + /* { dg-output "\nres: 258" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, test_func_gn, NULL, code) == FFI_OK); + + res_closure = (*((test_type)code))(1, 2, 127, 128); + /* { dg-output "\n1 2 127 128: 258" } */ + printf("res: %d\n", res_closure); + /* { dg-output "\nres: 258" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_pointer.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_pointer.c new file mode 100644 index 0000000..d82a87a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_pointer.c @@ -0,0 +1,74 @@ +/* Area: ffi_call, closure_call + Purpose: Check pointer arguments. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/6/2007 */ + +/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ +#include "ffitest.h" + +void* cls_pointer_fn(void* a1, void* a2) +{ + void* result = (void*)((intptr_t)a1 + (intptr_t)a2); + + printf("0x%08x 0x%08x: 0x%08x\n", + (unsigned int)(uintptr_t) a1, + (unsigned int)(uintptr_t) a2, + (unsigned int)(uintptr_t) result); + + return result; +} + +static void +cls_pointer_gn(ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) +{ + void* a1 = *(void**)(args[0]); + void* a2 = *(void**)(args[1]); + + *(void**)resp = cls_pointer_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args[3]; + /* ffi_type cls_pointer_type; */ + ffi_type* arg_types[3]; + +/* cls_pointer_type.size = sizeof(void*); + cls_pointer_type.alignment = 0; + cls_pointer_type.type = FFI_TYPE_POINTER; + cls_pointer_type.elements = NULL;*/ + + void* arg1 = (void*)0x12345678; + void* arg2 = (void*)0x89abcdef; + ffi_arg res = 0; + + arg_types[0] = &ffi_type_pointer; + arg_types[1] = &ffi_type_pointer; + arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_pointer, + arg_types) == FFI_OK); + + args[0] = &arg1; + args[1] = &arg2; + args[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_pointer_fn), &res, args); + /* { dg-output "0x12345678 0x89abcdef: 0x9be02467" } */ + printf("res: 0x%08x\n", (unsigned int) res); + /* { dg-output "\nres: 0x9be02467" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_pointer_gn, NULL, code) == FFI_OK); + + res = (ffi_arg)(uintptr_t)((void*(*)(void*, void*))(code))(arg1, arg2); + /* { dg-output "\n0x12345678 0x89abcdef: 0x9be02467" } */ + printf("res: 0x%08x\n", (unsigned int) res); + /* { dg-output "\nres: 0x9be02467" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_pointer_stack.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_pointer_stack.c new file mode 100644 index 0000000..1f1d915 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_pointer_stack.c @@ -0,0 +1,142 @@ +/* Area: ffi_call, closure_call + Purpose: Check pointer arguments across multiple hideous stack frames. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/7/2007 */ + +/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ +#include "ffitest.h" + +static long dummyVar; + +long dummy_func( + long double a1, char b1, + long double a2, char b2, + long double a3, char b3, + long double a4, char b4) +{ + return a1 + b1 + a2 + b2 + a3 + b3 + a4 + b4; +} + +void* cls_pointer_fn2(void* a1, void* a2) +{ + long double trample1 = (intptr_t)a1 + (intptr_t)a2; + char trample2 = ((char*)&a1)[0] + ((char*)&a2)[0]; + long double trample3 = (intptr_t)trample1 + (intptr_t)a1; + char trample4 = trample2 + ((char*)&a1)[1]; + long double trample5 = (intptr_t)trample3 + (intptr_t)a2; + char trample6 = trample4 + ((char*)&a2)[1]; + long double trample7 = (intptr_t)trample5 + (intptr_t)trample1; + char trample8 = trample6 + trample2; + void* result; + + dummyVar = dummy_func(trample1, trample2, trample3, trample4, + trample5, trample6, trample7, trample8); + + result = (void*)((intptr_t)a1 + (intptr_t)a2); + + printf("0x%08x 0x%08x: 0x%08x\n", + (unsigned int)(uintptr_t) a1, + (unsigned int)(uintptr_t) a2, + (unsigned int)(uintptr_t) result); + + return result; +} + +void* cls_pointer_fn1(void* a1, void* a2) +{ + long double trample1 = (intptr_t)a1 + (intptr_t)a2; + char trample2 = ((char*)&a1)[0] + ((char*)&a2)[0]; + long double trample3 = (intptr_t)trample1 + (intptr_t)a1; + char trample4 = trample2 + ((char*)&a1)[1]; + long double trample5 = (intptr_t)trample3 + (intptr_t)a2; + char trample6 = trample4 + ((char*)&a2)[1]; + long double trample7 = (intptr_t)trample5 + (intptr_t)trample1; + char trample8 = trample6 + trample2; + void* result; + + dummyVar = dummy_func(trample1, trample2, trample3, trample4, + trample5, trample6, trample7, trample8); + + result = (void*)((intptr_t)a1 + (intptr_t)a2); + + printf("0x%08x 0x%08x: 0x%08x\n", + (unsigned int)(intptr_t) a1, + (unsigned int)(intptr_t) a2, + (unsigned int)(intptr_t) result); + + result = cls_pointer_fn2(result, a1); + + return result; +} + +static void +cls_pointer_gn(ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) +{ + void* a1 = *(void**)(args[0]); + void* a2 = *(void**)(args[1]); + + long double trample1 = (intptr_t)a1 + (intptr_t)a2; + char trample2 = ((char*)&a1)[0] + ((char*)&a2)[0]; + long double trample3 = (intptr_t)trample1 + (intptr_t)a1; + char trample4 = trample2 + ((char*)&a1)[1]; + long double trample5 = (intptr_t)trample3 + (intptr_t)a2; + char trample6 = trample4 + ((char*)&a2)[1]; + long double trample7 = (intptr_t)trample5 + (intptr_t)trample1; + char trample8 = trample6 + trample2; + + dummyVar = dummy_func(trample1, trample2, trample3, trample4, + trample5, trample6, trample7, trample8); + + *(void**)resp = cls_pointer_fn1(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure* pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args[3]; + /* ffi_type cls_pointer_type; */ + ffi_type* arg_types[3]; + +/* cls_pointer_type.size = sizeof(void*); + cls_pointer_type.alignment = 0; + cls_pointer_type.type = FFI_TYPE_POINTER; + cls_pointer_type.elements = NULL;*/ + + void* arg1 = (void*)0x01234567; + void* arg2 = (void*)0x89abcdef; + ffi_arg res = 0; + + arg_types[0] = &ffi_type_pointer; + arg_types[1] = &ffi_type_pointer; + arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_pointer, + arg_types) == FFI_OK); + + args[0] = &arg1; + args[1] = &arg2; + args[2] = NULL; + + printf("\n"); + ffi_call(&cif, FFI_FN(cls_pointer_fn1), &res, args); + + printf("res: 0x%08x\n", (unsigned int) res); + /* { dg-output "\n0x01234567 0x89abcdef: 0x8acf1356" } */ + /* { dg-output "\n0x8acf1356 0x01234567: 0x8bf258bd" } */ + /* { dg-output "\nres: 0x8bf258bd" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_pointer_gn, NULL, code) == FFI_OK); + + res = (ffi_arg)(uintptr_t)((void*(*)(void*, void*))(code))(arg1, arg2); + + printf("res: 0x%08x\n", (unsigned int) res); + /* { dg-output "\n0x01234567 0x89abcdef: 0x8acf1356" } */ + /* { dg-output "\n0x8acf1356 0x01234567: 0x8bf258bd" } */ + /* { dg-output "\nres: 0x8bf258bd" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_schar.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_schar.c new file mode 100644 index 0000000..82986b1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_schar.c @@ -0,0 +1,44 @@ +/* Area: closure_call + Purpose: Check return value schar. + Limitations: none. + PR: none. + Originator: 20031108 */ + + + +/* { dg-do run } */ +#include "ffitest.h" + +static void cls_ret_schar_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + *(ffi_arg*)resp = *(signed char *)args[0]; + printf("%d: %d\n",*(signed char *)args[0], + (int)*(ffi_arg *)(resp)); +} +typedef signed char (*cls_ret_schar)(signed char); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[2]; + signed char res; + + cl_arg_types[0] = &ffi_type_schar; + cl_arg_types[1] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_schar, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_schar_fn, NULL, code) == FFI_OK); + + res = (*((cls_ret_schar)code))(127); + /* { dg-output "127: 127" } */ + printf("res: %d\n", res); + /* { dg-output "\nres: 127" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_sint.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_sint.c new file mode 100644 index 0000000..c7e13b7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_sint.c @@ -0,0 +1,42 @@ +/* Area: closure_call + Purpose: Check return value sint32. + Limitations: none. + PR: none. + Originator: 20031108 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void cls_ret_sint_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + *(ffi_arg*)resp = *(signed int *)args[0]; + printf("%d: %d\n",*(signed int *)args[0], + (int)*(ffi_arg *)(resp)); +} +typedef signed int (*cls_ret_sint)(signed int); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[2]; + signed int res; + + cl_arg_types[0] = &ffi_type_sint; + cl_arg_types[1] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_sint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_sint_fn, NULL, code) == FFI_OK); + + res = (*((cls_ret_sint)code))(65534); + /* { dg-output "65534: 65534" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 65534" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_sshort.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_sshort.c new file mode 100644 index 0000000..846d57e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_sshort.c @@ -0,0 +1,42 @@ +/* Area: closure_call + Purpose: Check return value sshort. + Limitations: none. + PR: none. + Originator: 20031108 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void cls_ret_sshort_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + *(ffi_arg*)resp = *(signed short *)args[0]; + printf("%d: %d\n",*(signed short *)args[0], + (int)*(ffi_arg *)(resp)); +} +typedef signed short (*cls_ret_sshort)(signed short); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[2]; + signed short res; + + cl_arg_types[0] = &ffi_type_sshort; + cl_arg_types[1] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_sshort, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_sshort_fn, NULL, code) == FFI_OK); + + res = (*((cls_ret_sshort)code))(255); + /* { dg-output "255: 255" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 255" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_struct_va1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_struct_va1.c new file mode 100644 index 0000000..6d1fdae --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_struct_va1.c @@ -0,0 +1,114 @@ +/* Area: ffi_call, closure_call + Purpose: Test doubles passed in variable argument lists. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/6/2007 */ + +/* { dg-do run } */ +/* { dg-output "" { xfail avr32*-*-* } } */ +#include "ffitest.h" + +struct small_tag +{ + unsigned char a; + unsigned char b; +}; + +struct large_tag +{ + unsigned a; + unsigned b; + unsigned c; + unsigned d; + unsigned e; +}; + +static void +test_fn (ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) +{ + int n = *(int*)args[0]; + struct small_tag s1 = * (struct small_tag *) args[1]; + struct large_tag l1 = * (struct large_tag *) args[2]; + struct small_tag s2 = * (struct small_tag *) args[3]; + + printf ("%d %d %d %d %d %d %d %d %d %d\n", n, s1.a, s1.b, + l1.a, l1.b, l1.c, l1.d, l1.e, + s2.a, s2.b); + * (ffi_arg*) resp = 42; +} + +int +main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc (sizeof (ffi_closure), &code); + ffi_type* arg_types[5]; + + ffi_arg res = 0; + + ffi_type s_type; + ffi_type *s_type_elements[3]; + + ffi_type l_type; + ffi_type *l_type_elements[6]; + + struct small_tag s1; + struct small_tag s2; + struct large_tag l1; + + int si; + + s_type.size = 0; + s_type.alignment = 0; + s_type.type = FFI_TYPE_STRUCT; + s_type.elements = s_type_elements; + + s_type_elements[0] = &ffi_type_uchar; + s_type_elements[1] = &ffi_type_uchar; + s_type_elements[2] = NULL; + + l_type.size = 0; + l_type.alignment = 0; + l_type.type = FFI_TYPE_STRUCT; + l_type.elements = l_type_elements; + + l_type_elements[0] = &ffi_type_uint; + l_type_elements[1] = &ffi_type_uint; + l_type_elements[2] = &ffi_type_uint; + l_type_elements[3] = &ffi_type_uint; + l_type_elements[4] = &ffi_type_uint; + l_type_elements[5] = NULL; + + arg_types[0] = &ffi_type_sint; + arg_types[1] = &s_type; + arg_types[2] = &l_type; + arg_types[3] = &s_type; + arg_types[4] = NULL; + + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 4, &ffi_type_sint, + arg_types) == FFI_OK); + + si = 4; + s1.a = 5; + s1.b = 6; + + s2.a = 20; + s2.b = 21; + + l1.a = 10; + l1.b = 11; + l1.c = 12; + l1.d = 13; + l1.e = 14; + + CHECK(ffi_prep_closure_loc(pcl, &cif, test_fn, NULL, code) == FFI_OK); + + res = ((int (*)(int, ...))(code))(si, s1, l1, s2); + /* { dg-output "4 5 6 10 11 12 13 14 20 21" } */ + printf("res: %d\n", (int) res); + /* { dg-output "\nres: 42" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uchar.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uchar.c new file mode 100644 index 0000000..c1317e7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uchar.c @@ -0,0 +1,42 @@ +/* Area: closure_call + Purpose: Check return value uchar. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void cls_ret_uchar_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + *(ffi_arg*)resp = *(unsigned char *)args[0]; + printf("%d: %d\n",*(unsigned char *)args[0], + (int)*(ffi_arg *)(resp)); +} +typedef unsigned char (*cls_ret_uchar)(unsigned char); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[2]; + unsigned char res; + + cl_arg_types[0] = &ffi_type_uchar; + cl_arg_types[1] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_uchar, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_uchar_fn, NULL, code) == FFI_OK); + + res = (*((cls_ret_uchar)code))(127); + /* { dg-output "127: 127" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 127" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uchar_va.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uchar_va.c new file mode 100644 index 0000000..6491c5b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uchar_va.c @@ -0,0 +1,44 @@ +/* Area: closure_call + Purpose: Test anonymous unsigned char argument. + Limitations: none. + PR: none. + Originator: ARM Ltd. */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef unsigned char T; + +static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) + { + *(ffi_arg *)resp = *(T *)args[0]; + + printf("%d: %d %d\n", (int)(*(ffi_arg *)resp), *(T *)args[0], *(T *)args[1]); + } + +typedef T (*cls_ret_T)(T, ...); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[3]; + T res; + + cl_arg_types[0] = &ffi_type_uchar; + cl_arg_types[1] = &ffi_type_uchar; + cl_arg_types[2] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2, + &ffi_type_uchar, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK); + res = ((((cls_ret_T)code)(67, 4))); + /* { dg-output "67: 67 4" } */ + printf("res: %d\n", res); + /* { dg-output "\nres: 67" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uint.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uint.c new file mode 100644 index 0000000..885cff5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uint.c @@ -0,0 +1,43 @@ +/* Area: closure_call + Purpose: Check return value uint. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void cls_ret_uint_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + *(ffi_arg *)resp = *(unsigned int *)args[0]; + + printf("%d: %d\n",*(unsigned int *)args[0], + (int)*(ffi_arg *)(resp)); +} +typedef unsigned int (*cls_ret_uint)(unsigned int); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[2]; + unsigned int res; + + cl_arg_types[0] = &ffi_type_uint; + cl_arg_types[1] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_uint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_uint_fn, NULL, code) == FFI_OK); + + res = (*((cls_ret_uint)code))(2147483647); + /* { dg-output "2147483647: 2147483647" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 2147483647" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uint_va.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uint_va.c new file mode 100644 index 0000000..b04cfd1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_uint_va.c @@ -0,0 +1,45 @@ +/* Area: closure_call + Purpose: Test anonymous unsigned int argument. + Limitations: none. + PR: none. + Originator: ARM Ltd. */ + +/* { dg-do run } */ + +#include "ffitest.h" + +typedef unsigned int T; + +static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) + { + *(ffi_arg *)resp = *(T *)args[0]; + + printf("%d: %d %d\n", (int)*(ffi_arg *)resp, *(T *)args[0], *(T *)args[1]); + } + +typedef T (*cls_ret_T)(T, ...); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[3]; + T res; + + cl_arg_types[0] = &ffi_type_uint; + cl_arg_types[1] = &ffi_type_uint; + cl_arg_types[2] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2, + &ffi_type_uint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK); + res = ((((cls_ret_T)code)(67, 4))); + /* { dg-output "67: 67 4" } */ + printf("res: %d\n", res); + /* { dg-output "\nres: 67" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ulong_va.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ulong_va.c new file mode 100644 index 0000000..0315082 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ulong_va.c @@ -0,0 +1,45 @@ +/* Area: closure_call + Purpose: Test anonymous unsigned long argument. + Limitations: none. + PR: none. + Originator: ARM Ltd. */ + +/* { dg-do run } */ + +#include "ffitest.h" + +typedef unsigned long T; + +static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) + { + *(T *)resp = *(T *)args[0]; + + printf("%ld: %ld %ld\n", *(T *)resp, *(T *)args[0], *(T *)args[1]); + } + +typedef T (*cls_ret_T)(T, ...); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[3]; + T res; + + cl_arg_types[0] = &ffi_type_ulong; + cl_arg_types[1] = &ffi_type_ulong; + cl_arg_types[2] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2, + &ffi_type_ulong, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK); + res = ((((cls_ret_T)code)(67, 4))); + /* { dg-output "67: 67 4" } */ + printf("res: %ld\n", res); + /* { dg-output "\nres: 67" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ulonglong.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ulonglong.c new file mode 100644 index 0000000..62f2cae --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ulonglong.c @@ -0,0 +1,47 @@ +/* Area: closure_call + Purpose: Check return value long long. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */ +#include "ffitest.h" + +static void cls_ret_ulonglong_fn(ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) +{ + *(unsigned long long *)resp= 0xfffffffffffffffLL ^ *(unsigned long long *)args[0]; + + printf("%" PRIuLL ": %" PRIuLL "\n",*(unsigned long long *)args[0], + *(unsigned long long *)(resp)); +} +typedef unsigned long long (*cls_ret_ulonglong)(unsigned long long); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[2]; + unsigned long long res; + + cl_arg_types[0] = &ffi_type_uint64; + cl_arg_types[1] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_uint64, cl_arg_types) == FFI_OK); + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_ulonglong_fn, NULL, code) == FFI_OK); + res = (*((cls_ret_ulonglong)code))(214LL); + /* { dg-output "214: 1152921504606846761" } */ + printf("res: %" PRIdLL "\n", res); + /* { dg-output "\nres: 1152921504606846761" } */ + + res = (*((cls_ret_ulonglong)code))(9223372035854775808LL); + /* { dg-output "\n9223372035854775808: 8070450533247928831" } */ + printf("res: %" PRIdLL "\n", res); + /* { dg-output "\nres: 8070450533247928831" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ushort.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ushort.c new file mode 100644 index 0000000..a00100e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ushort.c @@ -0,0 +1,43 @@ +/* Area: closure_call + Purpose: Check return value ushort. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +static void cls_ret_ushort_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + *(ffi_arg*)resp = *(unsigned short *)args[0]; + + printf("%d: %d\n",*(unsigned short *)args[0], + (int)*(ffi_arg *)(resp)); +} +typedef unsigned short (*cls_ret_ushort)(unsigned short); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[2]; + unsigned short res; + + cl_arg_types[0] = &ffi_type_ushort; + cl_arg_types[1] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_ushort, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_ushort_fn, NULL, code) == FFI_OK); + + res = (*((cls_ret_ushort)code))(65535); + /* { dg-output "65535: 65535" } */ + printf("res: %d\n",res); + /* { dg-output "\nres: 65535" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ushort_va.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ushort_va.c new file mode 100644 index 0000000..37aa106 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/cls_ushort_va.c @@ -0,0 +1,44 @@ +/* Area: closure_call + Purpose: Test anonymous unsigned short argument. + Limitations: none. + PR: none. + Originator: ARM Ltd. */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef unsigned short T; + +static void cls_ret_T_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) + { + *(ffi_arg *)resp = *(T *)args[0]; + + printf("%d: %d %d\n", (int)(*(ffi_arg *)resp), *(T *)args[0], *(T *)args[1]); + } + +typedef T (*cls_ret_T)(T, ...); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[3]; + T res; + + cl_arg_types[0] = &ffi_type_ushort; + cl_arg_types[1] = &ffi_type_ushort; + cl_arg_types[2] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 2, + &ffi_type_ushort, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_T_fn, NULL, code) == FFI_OK); + res = ((((cls_ret_T)code)(67, 4))); + /* { dg-output "67: 67 4" } */ + printf("res: %d\n", res); + /* { dg-output "\nres: 67" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/err_bad_abi.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/err_bad_abi.c new file mode 100644 index 0000000..f5a7317 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/err_bad_abi.c @@ -0,0 +1,36 @@ +/* Area: ffi_prep_cif, ffi_prep_closure + Purpose: Test error return for bad ABIs. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/6/2007 */ + +/* { dg-do run } */ + +#include "ffitest.h" + +static void +dummy_fn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__, + void** args __UNUSED__, void* userdata __UNUSED__) +{} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type* arg_types[1]; + + arg_types[0] = NULL; + + CHECK(ffi_prep_cif(&cif, 255, 0, &ffi_type_void, + arg_types) == FFI_BAD_ABI); + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, &ffi_type_void, + arg_types) == FFI_OK); + + cif.abi= 255; + + CHECK(ffi_prep_closure_loc(pcl, &cif, dummy_fn, NULL, code) == FFI_BAD_ABI); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/ffitest.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/ffitest.h new file mode 100644 index 0000000..cfce1ad --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/ffitest.h @@ -0,0 +1,138 @@ +#include +#include +#include +#include +#include +#include "fficonfig.h" + +#if defined HAVE_STDINT_H +#include +#endif + +#if defined HAVE_INTTYPES_H +#include +#endif + +#define MAX_ARGS 256 + +#define CHECK(x) (void)(!(x) ? (abort(), 1) : 0) + +/* Define macros so that compilers other than gcc can run the tests. */ +#undef __UNUSED__ +#if defined(__GNUC__) +#define __UNUSED__ __attribute__((__unused__)) +#define __STDCALL__ __attribute__((stdcall)) +#define __THISCALL__ __attribute__((thiscall)) +#define __FASTCALL__ __attribute__((fastcall)) +#define __MSABI__ __attribute__((ms_abi)) +#else +#define __UNUSED__ +#define __STDCALL__ __stdcall +#define __THISCALL__ __thiscall +#define __FASTCALL__ __fastcall +#endif + +#ifndef ABI_NUM +#define ABI_NUM FFI_DEFAULT_ABI +#define ABI_ATTR +#endif + +/* Prefer MAP_ANON(YMOUS) to /dev/zero, since we don't need to keep a + file open. */ +#ifdef HAVE_MMAP_ANON +# undef HAVE_MMAP_DEV_ZERO + +# include +# ifndef MAP_FAILED +# define MAP_FAILED -1 +# endif +# if !defined (MAP_ANONYMOUS) && defined (MAP_ANON) +# define MAP_ANONYMOUS MAP_ANON +# endif +# define USING_MMAP + +#endif + +#ifdef HAVE_MMAP_DEV_ZERO + +# include +# ifndef MAP_FAILED +# define MAP_FAILED -1 +# endif +# define USING_MMAP + +#endif + +/* MinGW kludge. */ +#if defined(_WIN64) | defined(_WIN32) +#define PRIdLL "I64d" +#define PRIuLL "I64u" +#else +#define PRIdLL "lld" +#define PRIuLL "llu" +#endif + +/* Tru64 UNIX kludge. */ +#if defined(__alpha__) && defined(__osf__) +/* Tru64 UNIX V4.0 doesn't support %lld/%lld, but long is 64-bit. */ +#undef PRIdLL +#define PRIdLL "ld" +#undef PRIuLL +#define PRIuLL "lu" +#define PRId8 "hd" +#define PRIu8 "hu" +#define PRId64 "ld" +#define PRIu64 "lu" +#define PRIuPTR "lu" +#endif + +/* PA HP-UX kludge. */ +#if defined(__hppa__) && defined(__hpux__) && !defined(PRIuPTR) +#define PRIuPTR "lu" +#endif + +/* IRIX kludge. */ +#if defined(__sgi) +/* IRIX 6.5 provides all definitions, but only for C99 + compilations. */ +#define PRId8 "hhd" +#define PRIu8 "hhu" +#if (_MIPS_SZLONG == 32) +#define PRId64 "lld" +#define PRIu64 "llu" +#endif +/* This doesn't match , which always has "lld" here, but the + arguments are uint64_t, int64_t, which are unsigned long, long for + 64-bit in . */ +#if (_MIPS_SZLONG == 64) +#define PRId64 "ld" +#define PRIu64 "lu" +#endif +/* This doesn't match , which has "u" here, but the arguments + are uintptr_t, which is always unsigned long. */ +#define PRIuPTR "lu" +#endif + +/* Solaris < 10 kludge. */ +#if defined(__sun__) && defined(__svr4__) && !defined(PRIuPTR) +#if defined(__arch64__) || defined (__x86_64__) +#define PRIuPTR "lu" +#else +#define PRIuPTR "u" +#endif +#endif + +/* MSVC kludge. */ +#if defined _MSC_VER +#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) +#define PRIuPTR "lu" +#define PRIu8 "u" +#define PRId8 "d" +#define PRIu64 "I64u" +#define PRId64 "I64d" +#endif +#endif + +#ifndef PRIuPTR +#define PRIuPTR "u" +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/huge_struct.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/huge_struct.c new file mode 100644 index 0000000..e8e1d86 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/huge_struct.c @@ -0,0 +1,343 @@ +/* Area: ffi_call, closure_call + Purpose: Check large structure returns. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/18/2007 +*/ + +/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ +/* { dg-options -mlong-double-128 { target powerpc64*-*-linux* } } */ +/* { dg-options -Wformat=0 { target moxie*-*-elf or1k-*-* } } */ + +#include + +#include "ffitest.h" + +typedef struct BigStruct{ + uint8_t a; + int8_t b; + uint16_t c; + int16_t d; + uint32_t e; + int32_t f; + uint64_t g; + int64_t h; + float i; + double j; + long double k; + char* l; + uint8_t m; + int8_t n; + uint16_t o; + int16_t p; + uint32_t q; + int32_t r; + uint64_t s; + int64_t t; + float u; + double v; + long double w; + char* x; + uint8_t y; + int8_t z; + uint16_t aa; + int16_t bb; + uint32_t cc; + int32_t dd; + uint64_t ee; + int64_t ff; + float gg; + double hh; + long double ii; + char* jj; + uint8_t kk; + int8_t ll; + uint16_t mm; + int16_t nn; + uint32_t oo; + int32_t pp; + uint64_t qq; + int64_t rr; + float ss; + double tt; + long double uu; + char* vv; + uint8_t ww; + int8_t xx; +} BigStruct; + +BigStruct +test_large_fn( + uint8_t ui8_1, + int8_t si8_1, + uint16_t ui16_1, + int16_t si16_1, + uint32_t ui32_1, + int32_t si32_1, + uint64_t ui64_1, + int64_t si64_1, + float f_1, + double d_1, + long double ld_1, + char* p_1, + uint8_t ui8_2, + int8_t si8_2, + uint16_t ui16_2, + int16_t si16_2, + uint32_t ui32_2, + int32_t si32_2, + uint64_t ui64_2, + int64_t si64_2, + float f_2, + double d_2, + long double ld_2, + char* p_2, + uint8_t ui8_3, + int8_t si8_3, + uint16_t ui16_3, + int16_t si16_3, + uint32_t ui32_3, + int32_t si32_3, + uint64_t ui64_3, + int64_t si64_3, + float f_3, + double d_3, + long double ld_3, + char* p_3, + uint8_t ui8_4, + int8_t si8_4, + uint16_t ui16_4, + int16_t si16_4, + uint32_t ui32_4, + int32_t si32_4, + uint64_t ui64_4, + int64_t si64_4, + float f_4, + double d_4, + long double ld_4, + char* p_4, + uint8_t ui8_5, + int8_t si8_5) +{ + BigStruct retVal = { + ui8_1 + 1, si8_1 + 1, ui16_1 + 1, si16_1 + 1, ui32_1 + 1, si32_1 + 1, + ui64_1 + 1, si64_1 + 1, f_1 + 1, d_1 + 1, ld_1 + 1, (char*)((intptr_t)p_1 + 1), + ui8_2 + 2, si8_2 + 2, ui16_2 + 2, si16_2 + 2, ui32_2 + 2, si32_2 + 2, + ui64_2 + 2, si64_2 + 2, f_2 + 2, d_2 + 2, ld_2 + 2, (char*)((intptr_t)p_2 + 2), + ui8_3 + 3, si8_3 + 3, ui16_3 + 3, si16_3 + 3, ui32_3 + 3, si32_3 + 3, + ui64_3 + 3, si64_3 + 3, f_3 + 3, d_3 + 3, ld_3 + 3, (char*)((intptr_t)p_3 + 3), + ui8_4 + 4, si8_4 + 4, ui16_4 + 4, si16_4 + 4, ui32_4 + 4, si32_4 + 4, + ui64_4 + 4, si64_4 + 4, f_4 + 4, d_4 + 4, ld_4 + 4, (char*)((intptr_t)p_4 + 4), + ui8_5 + 5, si8_5 + 5}; + + printf("%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 ": " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 "\n", + ui8_1, si8_1, ui16_1, si16_1, ui32_1, si32_1, ui64_1, si64_1, f_1, d_1, ld_1, (unsigned long)p_1, + ui8_2, si8_2, ui16_2, si16_2, ui32_2, si32_2, ui64_2, si64_2, f_2, d_2, ld_2, (unsigned long)p_2, + ui8_3, si8_3, ui16_3, si16_3, ui32_3, si32_3, ui64_3, si64_3, f_3, d_3, ld_3, (unsigned long)p_3, + ui8_4, si8_4, ui16_4, si16_4, ui32_4, si32_4, ui64_4, si64_4, f_4, d_4, ld_4, (unsigned long)p_4, ui8_5, si8_5, + retVal.a, retVal.b, retVal.c, retVal.d, retVal.e, retVal.f, + retVal.g, retVal.h, retVal.i, retVal.j, retVal.k, (unsigned long)retVal.l, + retVal.m, retVal.n, retVal.o, retVal.p, retVal.q, retVal.r, + retVal.s, retVal.t, retVal.u, retVal.v, retVal.w, (unsigned long)retVal.x, + retVal.y, retVal.z, retVal.aa, retVal.bb, retVal.cc, retVal.dd, + retVal.ee, retVal.ff, retVal.gg, retVal.hh, retVal.ii, (unsigned long)retVal.jj, + retVal.kk, retVal.ll, retVal.mm, retVal.nn, retVal.oo, retVal.pp, + retVal.qq, retVal.rr, retVal.ss, retVal.tt, retVal.uu, (unsigned long)retVal.vv, retVal.ww, retVal.xx); + + return retVal; +} + +static void +cls_large_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__) +{ + uint8_t ui8_1 = *(uint8_t*)args[0]; + int8_t si8_1 = *(int8_t*)args[1]; + uint16_t ui16_1 = *(uint16_t*)args[2]; + int16_t si16_1 = *(int16_t*)args[3]; + uint32_t ui32_1 = *(uint32_t*)args[4]; + int32_t si32_1 = *(int32_t*)args[5]; + uint64_t ui64_1 = *(uint64_t*)args[6]; + int64_t si64_1 = *(int64_t*)args[7]; + float f_1 = *(float*)args[8]; + double d_1 = *(double*)args[9]; + long double ld_1 = *(long double*)args[10]; + char* p_1 = *(char**)args[11]; + uint8_t ui8_2 = *(uint8_t*)args[12]; + int8_t si8_2 = *(int8_t*)args[13]; + uint16_t ui16_2 = *(uint16_t*)args[14]; + int16_t si16_2 = *(int16_t*)args[15]; + uint32_t ui32_2 = *(uint32_t*)args[16]; + int32_t si32_2 = *(int32_t*)args[17]; + uint64_t ui64_2 = *(uint64_t*)args[18]; + int64_t si64_2 = *(int64_t*)args[19]; + float f_2 = *(float*)args[20]; + double d_2 = *(double*)args[21]; + long double ld_2 = *(long double*)args[22]; + char* p_2 = *(char**)args[23]; + uint8_t ui8_3 = *(uint8_t*)args[24]; + int8_t si8_3 = *(int8_t*)args[25]; + uint16_t ui16_3 = *(uint16_t*)args[26]; + int16_t si16_3 = *(int16_t*)args[27]; + uint32_t ui32_3 = *(uint32_t*)args[28]; + int32_t si32_3 = *(int32_t*)args[29]; + uint64_t ui64_3 = *(uint64_t*)args[30]; + int64_t si64_3 = *(int64_t*)args[31]; + float f_3 = *(float*)args[32]; + double d_3 = *(double*)args[33]; + long double ld_3 = *(long double*)args[34]; + char* p_3 = *(char**)args[35]; + uint8_t ui8_4 = *(uint8_t*)args[36]; + int8_t si8_4 = *(int8_t*)args[37]; + uint16_t ui16_4 = *(uint16_t*)args[38]; + int16_t si16_4 = *(int16_t*)args[39]; + uint32_t ui32_4 = *(uint32_t*)args[40]; + int32_t si32_4 = *(int32_t*)args[41]; + uint64_t ui64_4 = *(uint64_t*)args[42]; + int64_t si64_4 = *(int64_t*)args[43]; + float f_4 = *(float*)args[44]; + double d_4 = *(double*)args[45]; + long double ld_4 = *(long double*)args[46]; + char* p_4 = *(char**)args[47]; + uint8_t ui8_5 = *(uint8_t*)args[48]; + int8_t si8_5 = *(int8_t*)args[49]; + + *(BigStruct*)resp = test_large_fn( + ui8_1, si8_1, ui16_1, si16_1, ui32_1, si32_1, ui64_1, si64_1, f_1, d_1, ld_1, p_1, + ui8_2, si8_2, ui16_2, si16_2, ui32_2, si32_2, ui64_2, si64_2, f_2, d_2, ld_2, p_2, + ui8_3, si8_3, ui16_3, si16_3, ui32_3, si32_3, ui64_3, si64_3, f_3, d_3, ld_3, p_3, + ui8_4, si8_4, ui16_4, si16_4, ui32_4, si32_4, ui64_4, si64_4, f_4, d_4, ld_4, p_4, + ui8_5, si8_5); +} + +int +main(int argc __UNUSED__, const char** argv __UNUSED__) +{ + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + + ffi_cif cif; + ffi_type* argTypes[51]; + void* argValues[51]; + + ffi_type ret_struct_type; + ffi_type* st_fields[51]; + BigStruct retVal; + + uint8_t ui8 = 1; + int8_t si8 = 2; + uint16_t ui16 = 3; + int16_t si16 = 4; + uint32_t ui32 = 5; + int32_t si32 = 6; + uint64_t ui64 = 7; + int64_t si64 = 8; + float f = 9; + double d = 10; + long double ld = 11; + char* p = (char*)0x12345678; + + memset (&retVal, 0, sizeof(retVal)); + + ret_struct_type.size = 0; + ret_struct_type.alignment = 0; + ret_struct_type.type = FFI_TYPE_STRUCT; + ret_struct_type.elements = st_fields; + + st_fields[0] = st_fields[12] = st_fields[24] = st_fields[36] = st_fields[48] = &ffi_type_uint8; + st_fields[1] = st_fields[13] = st_fields[25] = st_fields[37] = st_fields[49] = &ffi_type_sint8; + st_fields[2] = st_fields[14] = st_fields[26] = st_fields[38] = &ffi_type_uint16; + st_fields[3] = st_fields[15] = st_fields[27] = st_fields[39] = &ffi_type_sint16; + st_fields[4] = st_fields[16] = st_fields[28] = st_fields[40] = &ffi_type_uint32; + st_fields[5] = st_fields[17] = st_fields[29] = st_fields[41] = &ffi_type_sint32; + st_fields[6] = st_fields[18] = st_fields[30] = st_fields[42] = &ffi_type_uint64; + st_fields[7] = st_fields[19] = st_fields[31] = st_fields[43] = &ffi_type_sint64; + st_fields[8] = st_fields[20] = st_fields[32] = st_fields[44] = &ffi_type_float; + st_fields[9] = st_fields[21] = st_fields[33] = st_fields[45] = &ffi_type_double; + st_fields[10] = st_fields[22] = st_fields[34] = st_fields[46] = &ffi_type_longdouble; + st_fields[11] = st_fields[23] = st_fields[35] = st_fields[47] = &ffi_type_pointer; + + st_fields[50] = NULL; + + argTypes[0] = argTypes[12] = argTypes[24] = argTypes[36] = argTypes[48] = &ffi_type_uint8; + argValues[0] = argValues[12] = argValues[24] = argValues[36] = argValues[48] = &ui8; + argTypes[1] = argTypes[13] = argTypes[25] = argTypes[37] = argTypes[49] = &ffi_type_sint8; + argValues[1] = argValues[13] = argValues[25] = argValues[37] = argValues[49] = &si8; + argTypes[2] = argTypes[14] = argTypes[26] = argTypes[38] = &ffi_type_uint16; + argValues[2] = argValues[14] = argValues[26] = argValues[38] = &ui16; + argTypes[3] = argTypes[15] = argTypes[27] = argTypes[39] = &ffi_type_sint16; + argValues[3] = argValues[15] = argValues[27] = argValues[39] = &si16; + argTypes[4] = argTypes[16] = argTypes[28] = argTypes[40] = &ffi_type_uint32; + argValues[4] = argValues[16] = argValues[28] = argValues[40] = &ui32; + argTypes[5] = argTypes[17] = argTypes[29] = argTypes[41] = &ffi_type_sint32; + argValues[5] = argValues[17] = argValues[29] = argValues[41] = &si32; + argTypes[6] = argTypes[18] = argTypes[30] = argTypes[42] = &ffi_type_uint64; + argValues[6] = argValues[18] = argValues[30] = argValues[42] = &ui64; + argTypes[7] = argTypes[19] = argTypes[31] = argTypes[43] = &ffi_type_sint64; + argValues[7] = argValues[19] = argValues[31] = argValues[43] = &si64; + argTypes[8] = argTypes[20] = argTypes[32] = argTypes[44] = &ffi_type_float; + argValues[8] = argValues[20] = argValues[32] = argValues[44] = &f; + argTypes[9] = argTypes[21] = argTypes[33] = argTypes[45] = &ffi_type_double; + argValues[9] = argValues[21] = argValues[33] = argValues[45] = &d; + argTypes[10] = argTypes[22] = argTypes[34] = argTypes[46] = &ffi_type_longdouble; + argValues[10] = argValues[22] = argValues[34] = argValues[46] = &ld; + argTypes[11] = argTypes[23] = argTypes[35] = argTypes[47] = &ffi_type_pointer; + argValues[11] = argValues[23] = argValues[35] = argValues[47] = &p; + + argTypes[50] = NULL; + argValues[50] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 50, &ret_struct_type, argTypes) == FFI_OK); + + ffi_call(&cif, FFI_FN(test_large_fn), &retVal, argValues); + /* { dg-output "1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */ + printf("res: %" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 "\n", + retVal.a, retVal.b, retVal.c, retVal.d, retVal.e, retVal.f, + retVal.g, retVal.h, retVal.i, retVal.j, retVal.k, (unsigned long)retVal.l, + retVal.m, retVal.n, retVal.o, retVal.p, retVal.q, retVal.r, + retVal.s, retVal.t, retVal.u, retVal.v, retVal.w, (unsigned long)retVal.x, + retVal.y, retVal.z, retVal.aa, retVal.bb, retVal.cc, retVal.dd, + retVal.ee, retVal.ff, retVal.gg, retVal.hh, retVal.ii, (unsigned long)retVal.jj, + retVal.kk, retVal.ll, retVal.mm, retVal.nn, retVal.oo, retVal.pp, + retVal.qq, retVal.rr, retVal.ss, retVal.tt, retVal.uu, (unsigned long)retVal.vv, retVal.ww, retVal.xx); + /* { dg-output "\nres: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_large_fn, NULL, code) == FFI_OK); + + retVal = ((BigStruct(*)( + uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*, + uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*, + uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*, + uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, long double, char*, + uint8_t, int8_t))(code))( + ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p, + ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p, + ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p, + ui8, si8, ui16, si16, ui32, si32, ui64, si64, f, d, ld, p, + ui8, si8); + /* { dg-output "\n1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2 3 4 5 6 7 8 9 10 11 0x12345678 1 2: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */ + printf("res: %" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx " + "%" PRIu8 " %" PRId8 " %hu %hd %u %d %" PRIu64 " %" PRId64 " %.0f %.0f %.0Lf %#lx %" PRIu8 " %" PRId8 "\n", + retVal.a, retVal.b, retVal.c, retVal.d, retVal.e, retVal.f, + retVal.g, retVal.h, retVal.i, retVal.j, retVal.k, (unsigned long)retVal.l, + retVal.m, retVal.n, retVal.o, retVal.p, retVal.q, retVal.r, + retVal.s, retVal.t, retVal.u, retVal.v, retVal.w, (unsigned long)retVal.x, + retVal.y, retVal.z, retVal.aa, retVal.bb, retVal.cc, retVal.dd, + retVal.ee, retVal.ff, retVal.gg, retVal.hh, retVal.ii, (unsigned long)retVal.jj, + retVal.kk, retVal.ll, retVal.mm, retVal.nn, retVal.oo, retVal.pp, + retVal.qq, retVal.rr, retVal.ss, retVal.tt, retVal.uu, (unsigned long)retVal.vv, retVal.ww, retVal.xx); + /* { dg-output "\nres: 2 3 4 5 6 7 8 9 10 11 12 0x12345679 3 4 5 6 7 8 9 10 11 12 13 0x1234567a 4 5 6 7 8 9 10 11 12 13 14 0x1234567b 5 6 7 8 9 10 11 12 13 14 15 0x1234567c 6 7" } */ + + return 0; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct.c new file mode 100644 index 0000000..c15e3a0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct.c @@ -0,0 +1,152 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_16byte1 { + double a; + float b; + int c; +} cls_struct_16byte1; + +typedef struct cls_struct_16byte2 { + int ii; + double dd; + float ff; +} cls_struct_16byte2; + +typedef struct cls_struct_combined { + cls_struct_16byte1 d; + cls_struct_16byte2 e; +} cls_struct_combined; + +cls_struct_combined cls_struct_combined_fn(struct cls_struct_16byte1 b0, + struct cls_struct_16byte2 b1, + struct cls_struct_combined b2) +{ + struct cls_struct_combined result; + + result.d.a = b0.a + b1.dd + b2.d.a; + result.d.b = b0.b + b1.ff + b2.d.b; + result.d.c = b0.c + b1.ii + b2.d.c; + result.e.ii = b0.c + b1.ii + b2.e.ii; + result.e.dd = b0.a + b1.dd + b2.e.dd; + result.e.ff = b0.b + b1.ff + b2.e.ff; + + printf("%g %g %d %d %g %g %g %g %d %d %g %g: %g %g %d %d %g %g\n", + b0.a, b0.b, b0.c, + b1.ii, b1.dd, b1.ff, + b2.d.a, b2.d.b, b2.d.c, + b2.e.ii, b2.e.dd, b2.e.ff, + result.d.a, result.d.b, result.d.c, + result.e.ii, result.e.dd, result.e.ff); + + return result; +} + +static void +cls_struct_combined_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct cls_struct_16byte1 b0; + struct cls_struct_16byte2 b1; + struct cls_struct_combined b2; + + b0 = *(struct cls_struct_16byte1*)(args[0]); + b1 = *(struct cls_struct_16byte2*)(args[1]); + b2 = *(struct cls_struct_combined*)(args[2]); + + + *(cls_struct_combined*)resp = cls_struct_combined_fn(b0, b1, b2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[5]; + ffi_type* cls_struct_fields1[5]; + ffi_type* cls_struct_fields2[5]; + ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_16byte1 e_dbl = { 9.0, 2.0, 6}; + struct cls_struct_16byte2 f_dbl = { 1, 2.0, 3.0}; + struct cls_struct_combined g_dbl = {{4.0, 5.0, 6}, + {3, 1.0, 8.0}}; + struct cls_struct_combined res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_type2.size = 0; + cls_struct_type2.alignment = 0; + cls_struct_type2.type = FFI_TYPE_STRUCT; + cls_struct_type2.elements = cls_struct_fields2; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_float; + cls_struct_fields[2] = &ffi_type_sint; + cls_struct_fields[3] = NULL; + + cls_struct_fields1[0] = &ffi_type_sint; + cls_struct_fields1[1] = &ffi_type_double; + cls_struct_fields1[2] = &ffi_type_float; + cls_struct_fields1[3] = NULL; + + cls_struct_fields2[0] = &cls_struct_type; + cls_struct_fields2[1] = &cls_struct_type1; + cls_struct_fields2[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = &cls_struct_type2; + dbl_arg_types[3] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type2, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_combined_fn), &res_dbl, args_dbl); + /* { dg-output "9 2 6 1 2 3 4 5 6 3 1 8: 15 10 13 10 12 13" } */ + CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a)); + CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b)); + CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c)); + CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii)); + CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd)); + CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff)); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_combined_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_combined(*)(cls_struct_16byte1, + cls_struct_16byte2, + cls_struct_combined)) + (code))(e_dbl, f_dbl, g_dbl); + /* { dg-output "\n9 2 6 1 2 3 4 5 6 3 1 8: 15 10 13 10 12 13" } */ + CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a)); + CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b)); + CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c)); + CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii)); + CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd)); + CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff)); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct1.c new file mode 100644 index 0000000..477a6b9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct1.c @@ -0,0 +1,161 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_16byte1 { + double a; + float b; + int c; +} cls_struct_16byte1; + +typedef struct cls_struct_16byte2 { + int ii; + double dd; + float ff; +} cls_struct_16byte2; + +typedef struct cls_struct_combined { + cls_struct_16byte1 d; + cls_struct_16byte2 e; +} cls_struct_combined; + +cls_struct_combined cls_struct_combined_fn(struct cls_struct_16byte1 b0, + struct cls_struct_16byte2 b1, + struct cls_struct_combined b2, + struct cls_struct_16byte1 b3) +{ + struct cls_struct_combined result; + + result.d.a = b0.a + b1.dd + b2.d.a; + result.d.b = b0.b + b1.ff + b2.d.b; + result.d.c = b0.c + b1.ii + b2.d.c; + result.e.ii = b0.c + b1.ii + b2.e.ii; + result.e.dd = b0.a + b1.dd + b2.e.dd; + result.e.ff = b0.b + b1.ff + b2.e.ff; + + printf("%g %g %d %d %g %g %g %g %d %d %g %g %g %g %d: %g %g %d %d %g %g\n", + b0.a, b0.b, b0.c, + b1.ii, b1.dd, b1.ff, + b2.d.a, b2.d.b, b2.d.c, + b2.e.ii, b2.e.dd, b2.e.ff, + b3.a, b3.b, b3.c, + result.d.a, result.d.b, result.d.c, + result.e.ii, result.e.dd, result.e.ff); + + return result; +} + +static void +cls_struct_combined_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct cls_struct_16byte1 b0; + struct cls_struct_16byte2 b1; + struct cls_struct_combined b2; + struct cls_struct_16byte1 b3; + + b0 = *(struct cls_struct_16byte1*)(args[0]); + b1 = *(struct cls_struct_16byte2*)(args[1]); + b2 = *(struct cls_struct_combined*)(args[2]); + b3 = *(struct cls_struct_16byte1*)(args[3]); + + + *(cls_struct_combined*)resp = cls_struct_combined_fn(b0, b1, b2, b3); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[5]; + ffi_type* cls_struct_fields1[5]; + ffi_type* cls_struct_fields2[5]; + ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_16byte1 e_dbl = { 9.0, 2.0, 6}; + struct cls_struct_16byte2 f_dbl = { 1, 2.0, 3.0}; + struct cls_struct_combined g_dbl = {{4.0, 5.0, 6}, + {3, 1.0, 8.0}}; + struct cls_struct_16byte1 h_dbl = { 3.0, 2.0, 4}; + struct cls_struct_combined res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_type2.size = 0; + cls_struct_type2.alignment = 0; + cls_struct_type2.type = FFI_TYPE_STRUCT; + cls_struct_type2.elements = cls_struct_fields2; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_float; + cls_struct_fields[2] = &ffi_type_sint; + cls_struct_fields[3] = NULL; + + cls_struct_fields1[0] = &ffi_type_sint; + cls_struct_fields1[1] = &ffi_type_double; + cls_struct_fields1[2] = &ffi_type_float; + cls_struct_fields1[3] = NULL; + + cls_struct_fields2[0] = &cls_struct_type; + cls_struct_fields2[1] = &cls_struct_type1; + cls_struct_fields2[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = &cls_struct_type2; + dbl_arg_types[3] = &cls_struct_type; + dbl_arg_types[4] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type2, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = &h_dbl; + args_dbl[4] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_combined_fn), &res_dbl, args_dbl); + /* { dg-output "9 2 6 1 2 3 4 5 6 3 1 8 3 2 4: 15 10 13 10 12 13" } */ + CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a)); + CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b)); + CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c)); + CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii)); + CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd)); + CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff)); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_combined_gn, NULL, code) == FFI_OK); + + res_dbl = ((cls_struct_combined(*)(cls_struct_16byte1, + cls_struct_16byte2, + cls_struct_combined, + cls_struct_16byte1)) + (code))(e_dbl, f_dbl, g_dbl, h_dbl); + /* { dg-output "\n9 2 6 1 2 3 4 5 6 3 1 8 3 2 4: 15 10 13 10 12 13" } */ + CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a)); + CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b)); + CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c)); + CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii)); + CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd)); + CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff)); + /* CHECK( 1 == 0); */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct10.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct10.c new file mode 100644 index 0000000..3cf2b44 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct10.c @@ -0,0 +1,134 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Sample taken from Alan Modras patch to src/prep_cif.c. + Limitations: none. + PR: none. + Originator: 20051010 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct A { + unsigned long long a; + unsigned char b; +} A; + +typedef struct B { + unsigned char y; + struct A x; + unsigned int z; +} B; + +typedef struct C { + unsigned long long d; + unsigned char e; +} C; + +static B B_fn(struct A b2, struct B b3, struct C b4) +{ + struct B result; + + result.x.a = b2.a + b3.x.a + b3.z + b4.d; + result.x.b = b2.b + b3.x.b + b3.y + b4.e; + result.y = b2.b + b3.x.b + b4.e; + result.z = 0; + + printf("%d %d %d %d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b, + (int)b3.x.a, b3.x.b, b3.y, b3.z, (int)b4.d, b4.e, + (int)result.x.a, result.x.b, result.y); + + return result; +} + +static void +B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct A b0; + struct B b1; + struct C b2; + + b0 = *(struct A*)(args[0]); + b1 = *(struct B*)(args[1]); + b2 = *(struct C*)(args[2]); + + *(B*)resp = B_fn(b0, b1, b2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[4]; + ffi_type* cls_struct_fields[3]; + ffi_type* cls_struct_fields1[4]; + ffi_type* cls_struct_fields2[3]; + ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2; + ffi_type* dbl_arg_types[4]; + + struct A e_dbl = { 1LL, 7}; + struct B f_dbl = { 99, {12LL , 127}, 255}; + struct C g_dbl = { 2LL, 9}; + + struct B res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_type2.size = 0; + cls_struct_type2.alignment = 0; + cls_struct_type2.type = FFI_TYPE_STRUCT; + cls_struct_type2.elements = cls_struct_fields2; + + cls_struct_fields[0] = &ffi_type_uint64; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = NULL; + + cls_struct_fields1[0] = &ffi_type_uchar; + cls_struct_fields1[1] = &cls_struct_type; + cls_struct_fields1[2] = &ffi_type_uint; + cls_struct_fields1[3] = NULL; + + cls_struct_fields2[0] = &ffi_type_uint64; + cls_struct_fields2[1] = &ffi_type_uchar; + cls_struct_fields2[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = &cls_struct_type2; + dbl_arg_types[3] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = NULL; + + ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl); + /* { dg-output "1 7 12 127 99 255 2 9: 270 242 143" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + f_dbl.z + g_dbl.d)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e)); + + CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK); + + res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl); + /* { dg-output "\n1 7 12 127 99 255 2 9: 270 242 143" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + f_dbl.z + g_dbl.d)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e)); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct11.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct11.c new file mode 100644 index 0000000..3510493 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct11.c @@ -0,0 +1,121 @@ +/* Area: ffi_call, closure_call + Purpose: Check parameter passing with nested structs + of a single type. This tests the special cases + for homogeneous floating-point aggregates in the + AArch64 PCS. + Limitations: none. + PR: none. + Originator: ARM Ltd. */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct A { + float a_x; + float a_y; +} A; + +typedef struct B { + float b_x; + float b_y; +} B; + +typedef struct C { + A a; + B b; +} C; + +static C C_fn (int x, int y, int z, C source, int i, int j, int k) +{ + C result; + result.a.a_x = source.a.a_x; + result.a.a_y = source.a.a_y; + result.b.b_x = source.b.b_x; + result.b.b_y = source.b.b_y; + + printf ("%d, %d, %d, %d, %d, %d\n", x, y, z, i, j, k); + + printf ("%.1f, %.1f, %.1f, %.1f, " + "%.1f, %.1f, %.1f, %.1f\n", + source.a.a_x, source.a.a_y, + source.b.b_x, source.b.b_y, + result.a.a_x, result.a.a_y, + result.b.b_x, result.b.b_y); + + return result; +} + +int main (void) +{ + ffi_cif cif; + + ffi_type* struct_fields_source_a[3]; + ffi_type* struct_fields_source_b[3]; + ffi_type* struct_fields_source_c[3]; + ffi_type* arg_types[8]; + + ffi_type struct_type_a, struct_type_b, struct_type_c; + + struct A source_fld_a = {1.0, 2.0}; + struct B source_fld_b = {4.0, 8.0}; + int k = 1; + + struct C result; + struct C source = {source_fld_a, source_fld_b}; + + struct_type_a.size = 0; + struct_type_a.alignment = 0; + struct_type_a.type = FFI_TYPE_STRUCT; + struct_type_a.elements = struct_fields_source_a; + + struct_type_b.size = 0; + struct_type_b.alignment = 0; + struct_type_b.type = FFI_TYPE_STRUCT; + struct_type_b.elements = struct_fields_source_b; + + struct_type_c.size = 0; + struct_type_c.alignment = 0; + struct_type_c.type = FFI_TYPE_STRUCT; + struct_type_c.elements = struct_fields_source_c; + + struct_fields_source_a[0] = &ffi_type_float; + struct_fields_source_a[1] = &ffi_type_float; + struct_fields_source_a[2] = NULL; + + struct_fields_source_b[0] = &ffi_type_float; + struct_fields_source_b[1] = &ffi_type_float; + struct_fields_source_b[2] = NULL; + + struct_fields_source_c[0] = &struct_type_a; + struct_fields_source_c[1] = &struct_type_b; + struct_fields_source_c[2] = NULL; + + arg_types[0] = &ffi_type_sint32; + arg_types[1] = &ffi_type_sint32; + arg_types[2] = &ffi_type_sint32; + arg_types[3] = &struct_type_c; + arg_types[4] = &ffi_type_sint32; + arg_types[5] = &ffi_type_sint32; + arg_types[6] = &ffi_type_sint32; + arg_types[7] = NULL; + + void *args[7]; + args[0] = &k; + args[1] = &k; + args[2] = &k; + args[3] = &source; + args[4] = &k; + args[5] = &k; + args[6] = &k; + CHECK (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, 7, &struct_type_c, + arg_types) == FFI_OK); + + ffi_call (&cif, FFI_FN (C_fn), &result, args); + /* { dg-output "1, 1, 1, 1, 1, 1\n" } */ + /* { dg-output "1.0, 2.0, 4.0, 8.0, 1.0, 2.0, 4.0, 8.0" } */ + CHECK (result.a.a_x == source.a.a_x); + CHECK (result.a.a_y == source.a.a_y); + CHECK (result.b.b_x == source.b.b_x); + CHECK (result.b.b_y == source.b.b_y); + exit (0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct2.c new file mode 100644 index 0000000..69268cd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct2.c @@ -0,0 +1,110 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Sample taken from Alan Modras patch to src/prep_cif.c. + Limitations: none. + PR: none. + Originator: 20030911 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct A { + unsigned long a; + unsigned char b; +} A; + +typedef struct B { + struct A x; + unsigned char y; +} B; + +B B_fn(struct A b0, struct B b1) +{ + struct B result; + + result.x.a = b0.a + b1.x.a; + result.x.b = b0.b + b1.x.b + b1.y; + result.y = b0.b + b1.x.b; + + printf("%lu %d %lu %d %d: %lu %d %d\n", b0.a, b0.b, b1.x.a, b1.x.b, b1.y, + result.x.a, result.x.b, result.y); + + return result; +} + +static void +B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct A b0; + struct B b1; + + b0 = *(struct A*)(args[0]); + b1 = *(struct B*)(args[1]); + + *(B*)resp = B_fn(b0, b1); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[3]; + ffi_type* cls_struct_fields1[3]; + ffi_type cls_struct_type, cls_struct_type1; + ffi_type* dbl_arg_types[3]; + + struct A e_dbl = { 1, 7}; + struct B f_dbl = {{12 , 127}, 99}; + + struct B res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_fields[0] = &ffi_type_ulong; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = NULL; + + cls_struct_fields1[0] = &cls_struct_type; + cls_struct_fields1[1] = &ffi_type_uchar; + cls_struct_fields1[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl); + /* { dg-output "1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + + CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK); + + res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl); + /* { dg-output "\n1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct3.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct3.c new file mode 100644 index 0000000..ab18cad --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct3.c @@ -0,0 +1,111 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Sample taken from Alan Modras patch to src/prep_cif.c. + Limitations: none. + PR: none. + Originator: 20030911 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct A { + unsigned long long a; + unsigned char b; +} A; + +typedef struct B { + struct A x; + unsigned char y; +} B; + +B B_fn(struct A b0, struct B b1) +{ + struct B result; + + result.x.a = b0.a + b1.x.a; + result.x.b = b0.b + b1.x.b + b1.y; + result.y = b0.b + b1.x.b; + + printf("%d %d %d %d %d: %d %d %d\n", (int)b0.a, b0.b, + (int)b1.x.a, b1.x.b, b1.y, + (int)result.x.a, result.x.b, result.y); + + return result; +} + +static void +B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct A b0; + struct B b1; + + b0 = *(struct A*)(args[0]); + b1 = *(struct B*)(args[1]); + + *(B*)resp = B_fn(b0, b1); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[3]; + ffi_type* cls_struct_fields1[3]; + ffi_type cls_struct_type, cls_struct_type1; + ffi_type* dbl_arg_types[3]; + + struct A e_dbl = { 1LL, 7}; + struct B f_dbl = {{12LL , 127}, 99}; + + struct B res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_fields[0] = &ffi_type_uint64; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = NULL; + + cls_struct_fields1[0] = &cls_struct_type; + cls_struct_fields1[1] = &ffi_type_uchar; + cls_struct_fields1[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl); + /* { dg-output "1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + + + CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK); + + res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl); + /* { dg-output "\n1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct4.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct4.c new file mode 100644 index 0000000..2ffb4d6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct4.c @@ -0,0 +1,111 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Sample taken from Alan Modras patch to src/prep_cif.c. + Limitations: none. + PR: PR 25630. + Originator: 20051010 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct A { + double a; + unsigned char b; +} A; + +typedef struct B { + struct A x; + unsigned char y; +} B; + +static B B_fn(struct A b2, struct B b3) +{ + struct B result; + + result.x.a = b2.a + b3.x.a; + result.x.b = b2.b + b3.x.b + b3.y; + result.y = b2.b + b3.x.b; + + printf("%d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b, + (int)b3.x.a, b3.x.b, b3.y, + (int)result.x.a, result.x.b, result.y); + + return result; +} + +static void +B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct A b0; + struct B b1; + + b0 = *(struct A*)(args[0]); + b1 = *(struct B*)(args[1]); + + *(B*)resp = B_fn(b0, b1); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[3]; + ffi_type* cls_struct_fields1[3]; + ffi_type cls_struct_type, cls_struct_type1; + ffi_type* dbl_arg_types[3]; + + struct A e_dbl = { 1.0, 7}; + struct B f_dbl = {{12.0 , 127}, 99}; + + struct B res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = NULL; + + cls_struct_fields1[0] = &cls_struct_type; + cls_struct_fields1[1] = &ffi_type_uchar; + cls_struct_fields1[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl); + /* { dg-output "1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + + CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK); + + res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl); + /* { dg-output "\n1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct5.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct5.c new file mode 100644 index 0000000..6c79845 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct5.c @@ -0,0 +1,112 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Sample taken from Alan Modras patch to src/prep_cif.c. + Limitations: none. + PR: none. + Originator: 20051010 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct A { + long double a; + unsigned char b; +} A; + +typedef struct B { + struct A x; + unsigned char y; +} B; + +static B B_fn(struct A b2, struct B b3) +{ + struct B result; + + result.x.a = b2.a + b3.x.a; + result.x.b = b2.b + b3.x.b + b3.y; + result.y = b2.b + b3.x.b; + + printf("%d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b, + (int)b3.x.a, b3.x.b, b3.y, + (int)result.x.a, result.x.b, result.y); + + return result; +} + +static void +B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct A b0; + struct B b1; + + b0 = *(struct A*)(args[0]); + b1 = *(struct B*)(args[1]); + + *(B*)resp = B_fn(b0, b1); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[3]; + ffi_type* cls_struct_fields1[3]; + ffi_type cls_struct_type, cls_struct_type1; + ffi_type* dbl_arg_types[3]; + + struct A e_dbl = { 1.0, 7}; + struct B f_dbl = {{12.0 , 127}, 99}; + + struct B res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_fields[0] = &ffi_type_longdouble; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = NULL; + + cls_struct_fields1[0] = &cls_struct_type; + cls_struct_fields1[1] = &ffi_type_uchar; + cls_struct_fields1[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl); + /* { dg-output "1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + + + CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK); + + res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl); + /* { dg-output "\n1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct6.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct6.c new file mode 100644 index 0000000..59d3579 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct6.c @@ -0,0 +1,131 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Sample taken from Alan Modras patch to src/prep_cif.c. + Limitations: none. + PR: PR 25630. + Originator: 20051010 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct A { + double a; + unsigned char b; +} A; + +typedef struct B { + struct A x; + unsigned char y; +} B; + +typedef struct C { + long d; + unsigned char e; +} C; + +static B B_fn(struct A b2, struct B b3, struct C b4) +{ + struct B result; + + result.x.a = b2.a + b3.x.a + b4.d; + result.x.b = b2.b + b3.x.b + b3.y + b4.e; + result.y = b2.b + b3.x.b + b4.e; + + printf("%d %d %d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b, + (int)b3.x.a, b3.x.b, b3.y, (int)b4.d, b4.e, + (int)result.x.a, result.x.b, result.y); + + return result; +} + +static void +B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct A b0; + struct B b1; + struct C b2; + + b0 = *(struct A*)(args[0]); + b1 = *(struct B*)(args[1]); + b2 = *(struct C*)(args[2]); + + *(B*)resp = B_fn(b0, b1, b2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[4]; + ffi_type* cls_struct_fields[3]; + ffi_type* cls_struct_fields1[3]; + ffi_type* cls_struct_fields2[3]; + ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2; + ffi_type* dbl_arg_types[4]; + + struct A e_dbl = { 1.0, 7}; + struct B f_dbl = {{12.0 , 127}, 99}; + struct C g_dbl = { 2, 9}; + + struct B res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_type2.size = 0; + cls_struct_type2.alignment = 0; + cls_struct_type2.type = FFI_TYPE_STRUCT; + cls_struct_type2.elements = cls_struct_fields2; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = NULL; + + cls_struct_fields1[0] = &cls_struct_type; + cls_struct_fields1[1] = &ffi_type_uchar; + cls_struct_fields1[2] = NULL; + + cls_struct_fields2[0] = &ffi_type_slong; + cls_struct_fields2[1] = &ffi_type_uchar; + cls_struct_fields2[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = &cls_struct_type2; + dbl_arg_types[3] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = NULL; + + ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl); + /* { dg-output "1 7 12 127 99 2 9: 15 242 143" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e)); + + CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK); + + res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl); + /* { dg-output "\n1 7 12 127 99 2 9: 15 242 143" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e)); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct7.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct7.c new file mode 100644 index 0000000..27595e6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct7.c @@ -0,0 +1,111 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Sample taken from Alan Modras patch to src/prep_cif.c. + Limitations: none. + PR: none. + Originator: 20051010 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct A { + unsigned long long a; + unsigned char b; +} A; + +typedef struct B { + struct A x; + unsigned char y; +} B; + +static B B_fn(struct A b2, struct B b3) +{ + struct B result; + + result.x.a = b2.a + b3.x.a; + result.x.b = b2.b + b3.x.b + b3.y; + result.y = b2.b + b3.x.b; + + printf("%d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b, + (int)b3.x.a, b3.x.b, b3.y, + (int)result.x.a, result.x.b, result.y); + + return result; +} + +static void +B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct A b0; + struct B b1; + + b0 = *(struct A*)(args[0]); + b1 = *(struct B*)(args[1]); + + *(B*)resp = B_fn(b0, b1); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[3]; + ffi_type* cls_struct_fields1[3]; + ffi_type cls_struct_type, cls_struct_type1; + ffi_type* dbl_arg_types[3]; + + struct A e_dbl = { 1LL, 7}; + struct B f_dbl = {{12.0 , 127}, 99}; + + struct B res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_fields[0] = &ffi_type_uint64; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = NULL; + + cls_struct_fields1[0] = &cls_struct_type; + cls_struct_fields1[1] = &ffi_type_uchar; + cls_struct_fields1[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl); + /* { dg-output "1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + + CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK); + + res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl); + /* { dg-output "\n1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct8.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct8.c new file mode 100644 index 0000000..0e6c682 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct8.c @@ -0,0 +1,131 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Sample taken from Alan Modras patch to src/prep_cif.c. + Limitations: none. + PR: none. + Originator: 20051010 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct A { + unsigned long long a; + unsigned char b; +} A; + +typedef struct B { + struct A x; + unsigned char y; +} B; + +typedef struct C { + unsigned long long d; + unsigned char e; +} C; + +static B B_fn(struct A b2, struct B b3, struct C b4) +{ + struct B result; + + result.x.a = b2.a + b3.x.a + b4.d; + result.x.b = b2.b + b3.x.b + b3.y + b4.e; + result.y = b2.b + b3.x.b + b4.e; + + printf("%d %d %d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b, + (int)b3.x.a, b3.x.b, b3.y, (int)b4.d, b4.e, + (int)result.x.a, result.x.b, result.y); + + return result; +} + +static void +B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct A b0; + struct B b1; + struct C b2; + + b0 = *(struct A*)(args[0]); + b1 = *(struct B*)(args[1]); + b2 = *(struct C*)(args[2]); + + *(B*)resp = B_fn(b0, b1, b2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[4]; + ffi_type* cls_struct_fields[3]; + ffi_type* cls_struct_fields1[3]; + ffi_type* cls_struct_fields2[3]; + ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2; + ffi_type* dbl_arg_types[4]; + + struct A e_dbl = { 1LL, 7}; + struct B f_dbl = {{12LL , 127}, 99}; + struct C g_dbl = { 2LL, 9}; + + struct B res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_type2.size = 0; + cls_struct_type2.alignment = 0; + cls_struct_type2.type = FFI_TYPE_STRUCT; + cls_struct_type2.elements = cls_struct_fields2; + + cls_struct_fields[0] = &ffi_type_uint64; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = NULL; + + cls_struct_fields1[0] = &cls_struct_type; + cls_struct_fields1[1] = &ffi_type_uchar; + cls_struct_fields1[2] = NULL; + + cls_struct_fields2[0] = &ffi_type_uint64; + cls_struct_fields2[1] = &ffi_type_uchar; + cls_struct_fields2[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = &cls_struct_type2; + dbl_arg_types[3] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = NULL; + + ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl); + /* { dg-output "1 7 12 127 99 2 9: 15 242 143" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e)); + + CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK); + + res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl); + /* { dg-output "\n1 7 12 127 99 2 9: 15 242 143" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e)); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct9.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct9.c new file mode 100644 index 0000000..5f7ac67 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/nested_struct9.c @@ -0,0 +1,131 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Sample taken from Alan Modras patch to src/prep_cif.c. + Limitations: none. + PR: none. + Originator: 20051010 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct A { + unsigned char a; + unsigned long long b; +} A; + +typedef struct B { + struct A x; + unsigned char y; +} B; + +typedef struct C { + unsigned long d; + unsigned char e; +} C; + +static B B_fn(struct A b2, struct B b3, struct C b4) +{ + struct B result; + + result.x.a = b2.a + b3.x.a + b4.d; + result.x.b = b2.b + b3.x.b + b3.y + b4.e; + result.y = b2.b + b3.x.b + b4.e; + + printf("%d %d %d %d %d %d %d: %d %d %d\n", b2.a, (int)b2.b, + b3.x.a, (int)b3.x.b, b3.y, (int)b4.d, b4.e, + result.x.a, (int)result.x.b, result.y); + + return result; +} + +static void +B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct A b0; + struct B b1; + struct C b2; + + b0 = *(struct A*)(args[0]); + b1 = *(struct B*)(args[1]); + b2 = *(struct C*)(args[2]); + + *(B*)resp = B_fn(b0, b1, b2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[4]; + ffi_type* cls_struct_fields[3]; + ffi_type* cls_struct_fields1[3]; + ffi_type* cls_struct_fields2[3]; + ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2; + ffi_type* dbl_arg_types[4]; + + struct A e_dbl = { 1, 7LL}; + struct B f_dbl = {{12.0 , 127}, 99}; + struct C g_dbl = { 2, 9}; + + struct B res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_type2.size = 0; + cls_struct_type2.alignment = 0; + cls_struct_type2.type = FFI_TYPE_STRUCT; + cls_struct_type2.elements = cls_struct_fields2; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_uint64; + cls_struct_fields[2] = NULL; + + cls_struct_fields1[0] = &cls_struct_type; + cls_struct_fields1[1] = &ffi_type_uchar; + cls_struct_fields1[2] = NULL; + + cls_struct_fields2[0] = &ffi_type_ulong; + cls_struct_fields2[1] = &ffi_type_uchar; + cls_struct_fields2[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = &cls_struct_type2; + dbl_arg_types[3] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type1, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = NULL; + + ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl); + /* { dg-output "1 7 12 127 99 2 9: 15 242 143" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e)); + + CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK); + + res_dbl = ((B(*)(A, B, C))(code))(e_dbl, f_dbl, g_dbl); + /* { dg-output "\n1 7 12 127 99 2 9: 15 242 143" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a + g_dbl.d)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y + g_dbl.e)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b + g_dbl.e)); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/problem1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/problem1.c new file mode 100644 index 0000000..6a91555 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/problem1.c @@ -0,0 +1,90 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Limitations: none. + PR: none. + Originator: 20030828 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct my_ffi_struct { + double a; + double b; + double c; +} my_ffi_struct; + +my_ffi_struct callee(struct my_ffi_struct a1, struct my_ffi_struct a2) +{ + struct my_ffi_struct result; + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + + printf("%g %g %g %g %g %g: %g %g %g\n", a1.a, a1.b, a1.c, + a2.a, a2.b, a2.c, result.a, result.b, result.c); + + return result; +} + +void stub(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct my_ffi_struct a1; + struct my_ffi_struct a2; + + a1 = *(struct my_ffi_struct*)(args[0]); + a2 = *(struct my_ffi_struct*)(args[1]); + + *(my_ffi_struct *)resp = callee(a1, a2); +} + + +int main(void) +{ + ffi_type* my_ffi_struct_fields[4]; + ffi_type my_ffi_struct_type; + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args[4]; + ffi_type* arg_types[3]; + + struct my_ffi_struct g = { 1.0, 2.0, 3.0 }; + struct my_ffi_struct f = { 1.0, 2.0, 3.0 }; + struct my_ffi_struct res; + + my_ffi_struct_type.size = 0; + my_ffi_struct_type.alignment = 0; + my_ffi_struct_type.type = FFI_TYPE_STRUCT; + my_ffi_struct_type.elements = my_ffi_struct_fields; + + my_ffi_struct_fields[0] = &ffi_type_double; + my_ffi_struct_fields[1] = &ffi_type_double; + my_ffi_struct_fields[2] = &ffi_type_double; + my_ffi_struct_fields[3] = NULL; + + arg_types[0] = &my_ffi_struct_type; + arg_types[1] = &my_ffi_struct_type; + arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &my_ffi_struct_type, + arg_types) == FFI_OK); + + args[0] = &g; + args[1] = &f; + args[2] = NULL; + ffi_call(&cif, FFI_FN(callee), &res, args); + /* { dg-output "1 2 3 1 2 3: 2 4 6" } */ + printf("res: %g %g %g\n", res.a, res.b, res.c); + /* { dg-output "\nres: 2 4 6" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, stub, NULL, code) == FFI_OK); + + res = ((my_ffi_struct(*)(struct my_ffi_struct, struct my_ffi_struct))(code))(g, f); + /* { dg-output "\n1 2 3 1 2 3: 2 4 6" } */ + printf("res: %g %g %g\n", res.a, res.b, res.c); + /* { dg-output "\nres: 2 4 6" } */ + + exit(0);; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_large.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_large.c new file mode 100644 index 0000000..71c2469 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_large.c @@ -0,0 +1,145 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure returning with different structure size. + Depending on the ABI. Check bigger struct which overlaps + the gp and fp register count on Darwin/AIX/ppc64. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/21/2007 */ + +/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ +#include "ffitest.h" + +/* 13 FPRs: 104 bytes */ +/* 14 FPRs: 112 bytes */ + +typedef struct struct_108byte { + double a; + double b; + double c; + double d; + double e; + double f; + double g; + double h; + double i; + double j; + double k; + double l; + double m; + int n; +} struct_108byte; + +struct_108byte cls_struct_108byte_fn( + struct_108byte b0, + struct_108byte b1, + struct_108byte b2, + struct_108byte b3) +{ + struct_108byte result; + + result.a = b0.a + b1.a + b2.a + b3.a; + result.b = b0.b + b1.b + b2.b + b3.b; + result.c = b0.c + b1.c + b2.c + b3.c; + result.d = b0.d + b1.d + b2.d + b3.d; + result.e = b0.e + b1.e + b2.e + b3.e; + result.f = b0.f + b1.f + b2.f + b3.f; + result.g = b0.g + b1.g + b2.g + b3.g; + result.h = b0.h + b1.h + b2.h + b3.h; + result.i = b0.i + b1.i + b2.i + b3.i; + result.j = b0.j + b1.j + b2.j + b3.j; + result.k = b0.k + b1.k + b2.k + b3.k; + result.l = b0.l + b1.l + b2.l + b3.l; + result.m = b0.m + b1.m + b2.m + b3.m; + result.n = b0.n + b1.n + b2.n + b3.n; + + printf("%g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", result.a, result.b, result.c, + result.d, result.e, result.f, result.g, result.h, result.i, + result.j, result.k, result.l, result.m, result.n); + + return result; +} + +static void +cls_struct_108byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__) +{ + struct_108byte b0, b1, b2, b3; + + b0 = *(struct_108byte*)(args[0]); + b1 = *(struct_108byte*)(args[1]); + b2 = *(struct_108byte*)(args[2]); + b3 = *(struct_108byte*)(args[3]); + + *(struct_108byte*)resp = cls_struct_108byte_fn(b0, b1, b2, b3); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[15]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct_108byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 1.0, 2.0, 3.0, 7.0, 2.0, 7 }; + struct_108byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4.0, 5.0, 7.0, 9.0, 1.0, 4 }; + struct_108byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 8.0, 6.0, 1.0, 4.0, 0.0, 3 }; + struct_108byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 9.0, 2.0, 6.0, 5.0, 3.0, 2 }; + struct_108byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_double; + cls_struct_fields[2] = &ffi_type_double; + cls_struct_fields[3] = &ffi_type_double; + cls_struct_fields[4] = &ffi_type_double; + cls_struct_fields[5] = &ffi_type_double; + cls_struct_fields[6] = &ffi_type_double; + cls_struct_fields[7] = &ffi_type_double; + cls_struct_fields[8] = &ffi_type_double; + cls_struct_fields[9] = &ffi_type_double; + cls_struct_fields[10] = &ffi_type_double; + cls_struct_fields[11] = &ffi_type_double; + cls_struct_fields[12] = &ffi_type_double; + cls_struct_fields[13] = &ffi_type_sint32; + cls_struct_fields[14] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = &cls_struct_type; + dbl_arg_types[3] = &cls_struct_type; + dbl_arg_types[4] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = &h_dbl; + args_dbl[4] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_108byte_fn), &res_dbl, args_dbl); + /* { dg-output "22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */ + printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b, + res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i, + res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n); + /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_108byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((struct_108byte(*)(struct_108byte, struct_108byte, + struct_108byte, struct_108byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl); + /* { dg-output "\n22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */ + printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b, + res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i, + res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n); + /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 16" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_large2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_large2.c new file mode 100644 index 0000000..d9c750e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_large2.c @@ -0,0 +1,148 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure returning with different structure size. + Depending on the ABI. Check bigger struct which overlaps + the gp and fp register count on Darwin/AIX/ppc64. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/21/2007 */ + +/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ +#include "ffitest.h" + +/* 13 FPRs: 104 bytes */ +/* 14 FPRs: 112 bytes */ + +typedef struct struct_116byte { + double a; + double b; + double c; + double d; + double e; + double f; + double g; + double h; + double i; + double j; + double k; + double l; + double m; + double n; + int o; +} struct_116byte; + +struct_116byte cls_struct_116byte_fn( + struct_116byte b0, + struct_116byte b1, + struct_116byte b2, + struct_116byte b3) +{ + struct_116byte result; + + result.a = b0.a + b1.a + b2.a + b3.a; + result.b = b0.b + b1.b + b2.b + b3.b; + result.c = b0.c + b1.c + b2.c + b3.c; + result.d = b0.d + b1.d + b2.d + b3.d; + result.e = b0.e + b1.e + b2.e + b3.e; + result.f = b0.f + b1.f + b2.f + b3.f; + result.g = b0.g + b1.g + b2.g + b3.g; + result.h = b0.h + b1.h + b2.h + b3.h; + result.i = b0.i + b1.i + b2.i + b3.i; + result.j = b0.j + b1.j + b2.j + b3.j; + result.k = b0.k + b1.k + b2.k + b3.k; + result.l = b0.l + b1.l + b2.l + b3.l; + result.m = b0.m + b1.m + b2.m + b3.m; + result.n = b0.n + b1.n + b2.n + b3.n; + result.o = b0.o + b1.o + b2.o + b3.o; + + printf("%g %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", result.a, result.b, result.c, + result.d, result.e, result.f, result.g, result.h, result.i, + result.j, result.k, result.l, result.m, result.n, result.o); + + return result; +} + +static void +cls_struct_116byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__) +{ + struct_116byte b0, b1, b2, b3; + + b0 = *(struct_116byte*)(args[0]); + b1 = *(struct_116byte*)(args[1]); + b2 = *(struct_116byte*)(args[2]); + b3 = *(struct_116byte*)(args[3]); + + *(struct_116byte*)resp = cls_struct_116byte_fn(b0, b1, b2, b3); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[16]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct_116byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 7 }; + struct_116byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4.0, 5.0, 7.0, 9.0, 1.0, 6.0, 4 }; + struct_116byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 8.0, 6.0, 1.0, 4.0, 0.0, 7.0, 3 }; + struct_116byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 9.0, 2.0, 6.0, 5.0, 3.0, 8.0, 2 }; + struct_116byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_double; + cls_struct_fields[2] = &ffi_type_double; + cls_struct_fields[3] = &ffi_type_double; + cls_struct_fields[4] = &ffi_type_double; + cls_struct_fields[5] = &ffi_type_double; + cls_struct_fields[6] = &ffi_type_double; + cls_struct_fields[7] = &ffi_type_double; + cls_struct_fields[8] = &ffi_type_double; + cls_struct_fields[9] = &ffi_type_double; + cls_struct_fields[10] = &ffi_type_double; + cls_struct_fields[11] = &ffi_type_double; + cls_struct_fields[12] = &ffi_type_double; + cls_struct_fields[13] = &ffi_type_double; + cls_struct_fields[14] = &ffi_type_sint32; + cls_struct_fields[15] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = &cls_struct_type; + dbl_arg_types[3] = &cls_struct_type; + dbl_arg_types[4] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = &h_dbl; + args_dbl[4] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_116byte_fn), &res_dbl, args_dbl); + /* { dg-output "22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */ + printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b, + res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i, + res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n, res_dbl.o); + /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_116byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((struct_116byte(*)(struct_116byte, struct_116byte, + struct_116byte, struct_116byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl); + /* { dg-output "\n22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */ + printf("res: %g %g %g %g %g %g %g %g %g %g %g %g %g %g %d\n", res_dbl.a, res_dbl.b, + res_dbl.c, res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i, + res_dbl.j, res_dbl.k, res_dbl.l, res_dbl.m, res_dbl.n, res_dbl.o); + /* { dg-output "\nres: 22 15 17 25 6 13 19 18 22 15 17 25 6 26 16" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_medium.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_medium.c new file mode 100644 index 0000000..973ee02 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_medium.c @@ -0,0 +1,124 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure returning with different structure size. + Depending on the ABI. Check bigger struct which overlaps + the gp and fp register count on Darwin/AIX/ppc64. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/21/2007 */ + +/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ +#include "ffitest.h" + +typedef struct struct_72byte { + double a; + double b; + double c; + double d; + double e; + double f; + double g; + double h; + double i; +} struct_72byte; + +struct_72byte cls_struct_72byte_fn( + struct_72byte b0, + struct_72byte b1, + struct_72byte b2, + struct_72byte b3) +{ + struct_72byte result; + + result.a = b0.a + b1.a + b2.a + b3.a; + result.b = b0.b + b1.b + b2.b + b3.b; + result.c = b0.c + b1.c + b2.c + b3.c; + result.d = b0.d + b1.d + b2.d + b3.d; + result.e = b0.e + b1.e + b2.e + b3.e; + result.f = b0.f + b1.f + b2.f + b3.f; + result.g = b0.g + b1.g + b2.g + b3.g; + result.h = b0.h + b1.h + b2.h + b3.h; + result.i = b0.i + b1.i + b2.i + b3.i; + + printf("%g %g %g %g %g %g %g %g %g\n", result.a, result.b, result.c, + result.d, result.e, result.f, result.g, result.h, result.i); + + return result; +} + +static void +cls_struct_72byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__) +{ + struct_72byte b0, b1, b2, b3; + + b0 = *(struct_72byte*)(args[0]); + b1 = *(struct_72byte*)(args[1]); + b2 = *(struct_72byte*)(args[2]); + b3 = *(struct_72byte*)(args[3]); + + *(struct_72byte*)resp = cls_struct_72byte_fn(b0, b1, b2, b3); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[10]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct_72byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 7.0 }; + struct_72byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4.0 }; + struct_72byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 3.0 }; + struct_72byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 2.0 }; + struct_72byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_double; + cls_struct_fields[2] = &ffi_type_double; + cls_struct_fields[3] = &ffi_type_double; + cls_struct_fields[4] = &ffi_type_double; + cls_struct_fields[5] = &ffi_type_double; + cls_struct_fields[6] = &ffi_type_double; + cls_struct_fields[7] = &ffi_type_double; + cls_struct_fields[8] = &ffi_type_double; + cls_struct_fields[9] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = &cls_struct_type; + dbl_arg_types[3] = &cls_struct_type; + dbl_arg_types[4] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = &h_dbl; + args_dbl[4] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_72byte_fn), &res_dbl, args_dbl); + /* { dg-output "22 15 17 25 6 13 19 18 16" } */ + printf("res: %g %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i); + /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_72byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((struct_72byte(*)(struct_72byte, struct_72byte, + struct_72byte, struct_72byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl); + /* { dg-output "\n22 15 17 25 6 13 19 18 16" } */ + printf("res: %g %g %g %g %g %g %g %g %g\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i); + /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_medium2.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_medium2.c new file mode 100644 index 0000000..84323d1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/stret_medium2.c @@ -0,0 +1,125 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure returning with different structure size. + Depending on the ABI. Check bigger struct which overlaps + the gp and fp register count on Darwin/AIX/ppc64. + Limitations: none. + PR: none. + Originator: Blake Chaffin 6/21/2007 */ + +/* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ +/* { dg-options "-Wno-format" { target alpha*-dec-osf* } } */ +#include "ffitest.h" + +typedef struct struct_72byte { + double a; + double b; + double c; + double d; + double e; + double f; + double g; + double h; + long long i; +} struct_72byte; + +struct_72byte cls_struct_72byte_fn( + struct_72byte b0, + struct_72byte b1, + struct_72byte b2, + struct_72byte b3) +{ + struct_72byte result; + + result.a = b0.a + b1.a + b2.a + b3.a; + result.b = b0.b + b1.b + b2.b + b3.b; + result.c = b0.c + b1.c + b2.c + b3.c; + result.d = b0.d + b1.d + b2.d + b3.d; + result.e = b0.e + b1.e + b2.e + b3.e; + result.f = b0.f + b1.f + b2.f + b3.f; + result.g = b0.g + b1.g + b2.g + b3.g; + result.h = b0.h + b1.h + b2.h + b3.h; + result.i = b0.i + b1.i + b2.i + b3.i; + + printf("%g %g %g %g %g %g %g %g %" PRIdLL "\n", result.a, result.b, result.c, + result.d, result.e, result.f, result.g, result.h, result.i); + + return result; +} + +static void +cls_struct_72byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__) +{ + struct_72byte b0, b1, b2, b3; + + b0 = *(struct_72byte*)(args[0]); + b1 = *(struct_72byte*)(args[1]); + b2 = *(struct_72byte*)(args[2]); + b3 = *(struct_72byte*)(args[3]); + + *(struct_72byte*)resp = cls_struct_72byte_fn(b0, b1, b2, b3); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[5]; + ffi_type* cls_struct_fields[10]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + + struct_72byte e_dbl = { 9.0, 2.0, 6.0, 5.0, 3.0, 4.0, 8.0, 1.0, 7 }; + struct_72byte f_dbl = { 1.0, 2.0, 3.0, 7.0, 2.0, 5.0, 6.0, 7.0, 4 }; + struct_72byte g_dbl = { 4.0, 5.0, 7.0, 9.0, 1.0, 1.0, 2.0, 9.0, 3 }; + struct_72byte h_dbl = { 8.0, 6.0, 1.0, 4.0, 0.0, 3.0, 3.0, 1.0, 2 }; + struct_72byte res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_double; + cls_struct_fields[1] = &ffi_type_double; + cls_struct_fields[2] = &ffi_type_double; + cls_struct_fields[3] = &ffi_type_double; + cls_struct_fields[4] = &ffi_type_double; + cls_struct_fields[5] = &ffi_type_double; + cls_struct_fields[6] = &ffi_type_double; + cls_struct_fields[7] = &ffi_type_double; + cls_struct_fields[8] = &ffi_type_sint64; + cls_struct_fields[9] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = &cls_struct_type; + dbl_arg_types[3] = &cls_struct_type; + dbl_arg_types[4] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = &g_dbl; + args_dbl[3] = &h_dbl; + args_dbl[4] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_72byte_fn), &res_dbl, args_dbl); + /* { dg-output "22 15 17 25 6 13 19 18 16" } */ + printf("res: %g %g %g %g %g %g %g %g %" PRIdLL "\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i); + /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_72byte_gn, NULL, code) == FFI_OK); + + res_dbl = ((struct_72byte(*)(struct_72byte, struct_72byte, + struct_72byte, struct_72byte))(code))(e_dbl, f_dbl, g_dbl, h_dbl); + /* { dg-output "\n22 15 17 25 6 13 19 18 16" } */ + printf("res: %g %g %g %g %g %g %g %g %" PRIdLL "\n", res_dbl.a, res_dbl.b, res_dbl.c, + res_dbl.d, res_dbl.e, res_dbl.f, res_dbl.g, res_dbl.h, res_dbl.i); + /* { dg-output "\nres: 22 15 17 25 6 13 19 18 16" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/testclosure.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/testclosure.c new file mode 100644 index 0000000..ca31056 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/testclosure.c @@ -0,0 +1,70 @@ +/* Area: closure_call + Purpose: Check return value float. + Limitations: none. + PR: 41908. + Originator: 20091102 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_combined { + float a; + float b; + float c; + float d; +} cls_struct_combined; + +void cls_struct_combined_fn(struct cls_struct_combined arg) +{ + printf("%g %g %g %g\n", + arg.a, arg.b, + arg.c, arg.d); + fflush(stdout); +} + +static void +cls_struct_combined_gn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__, + void** args, void* userdata __UNUSED__) +{ + struct cls_struct_combined a0; + + a0 = *(struct cls_struct_combined*)(args[0]); + + cls_struct_combined_fn(a0); +} + + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type* cls_struct_fields0[5]; + ffi_type cls_struct_type0; + ffi_type* dbl_arg_types[5]; + + struct cls_struct_combined g_dbl = {4.0, 5.0, 1.0, 8.0}; + + cls_struct_type0.size = 0; + cls_struct_type0.alignment = 0; + cls_struct_type0.type = FFI_TYPE_STRUCT; + cls_struct_type0.elements = cls_struct_fields0; + + cls_struct_fields0[0] = &ffi_type_float; + cls_struct_fields0[1] = &ffi_type_float; + cls_struct_fields0[2] = &ffi_type_float; + cls_struct_fields0[3] = &ffi_type_float; + cls_struct_fields0[4] = NULL; + + dbl_arg_types[0] = &cls_struct_type0; + dbl_arg_types[1] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, &ffi_type_void, + dbl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_combined_gn, NULL, code) == FFI_OK); + + ((void(*)(cls_struct_combined)) (code))(g_dbl); + /* { dg-output "4 5 1 8" } */ + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/unwindtest.cc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/unwindtest.cc new file mode 100644 index 0000000..e114565 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/unwindtest.cc @@ -0,0 +1,117 @@ +/* Area: ffi_closure, unwind info + Purpose: Check if the unwind information is passed correctly. + Limitations: none. + PR: none. + Originator: Jeff Sturm */ + +/* { dg-do run { xfail x86_64-apple-darwin* moxie*-*-* } } */ + +#include "ffitest.h" + +void ABI_ATTR +closure_test_fn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__, + void** args __UNUSED__, void* userdata __UNUSED__) +{ + throw 9; +} + +typedef void (*closure_test_type)(); + +void closure_test_fn1(ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) + { + *(ffi_arg*)resp = + (int)*(float *)args[0] +(int)(*(float *)args[1]) + + (int)(*(float *)args[2]) + (int)*(float *)args[3] + + (int)(*(signed short *)args[4]) + (int)(*(float *)args[5]) + + (int)*(float *)args[6] + (int)(*(int *)args[7]) + + (int)(*(double*)args[8]) + (int)*(int *)args[9] + + (int)(*(int *)args[10]) + (int)(*(float *)args[11]) + + (int)*(int *)args[12] + (int)(*(int *)args[13]) + + (int)(*(int *)args[14]) + *(int *)args[15] + (int)(intptr_t)userdata; + + printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n", + (int)*(float *)args[0], (int)(*(float *)args[1]), + (int)(*(float *)args[2]), (int)*(float *)args[3], + (int)(*(signed short *)args[4]), (int)(*(float *)args[5]), + (int)*(float *)args[6], (int)(*(int *)args[7]), + (int)(*(double *)args[8]), (int)*(int *)args[9], + (int)(*(int *)args[10]), (int)(*(float *)args[11]), + (int)*(int *)args[12], (int)(*(int *)args[13]), + (int)(*(int *)args[14]), *(int *)args[15], + (int)(intptr_t)userdata, (int)*(ffi_arg*)resp); + + throw (int)*(ffi_arg*)resp; +} + +typedef int (*closure_test_type1)(float, float, float, float, signed short, + float, float, int, double, int, int, float, + int, int, int, int); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = (ffi_closure *)ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[17]; + + { + cl_arg_types[1] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, + &ffi_type_void, cl_arg_types) == FFI_OK); + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn, NULL, code) == FFI_OK); + + try + { + (*((closure_test_type)(code)))(); + } catch (int exception_code) + { + CHECK(exception_code == 9); + } + + printf("part one OK\n"); + /* { dg-output "part one OK" } */ + } + + { + + cl_arg_types[0] = &ffi_type_float; + cl_arg_types[1] = &ffi_type_float; + cl_arg_types[2] = &ffi_type_float; + cl_arg_types[3] = &ffi_type_float; + cl_arg_types[4] = &ffi_type_sshort; + cl_arg_types[5] = &ffi_type_float; + cl_arg_types[6] = &ffi_type_float; + cl_arg_types[7] = &ffi_type_uint; + cl_arg_types[8] = &ffi_type_double; + cl_arg_types[9] = &ffi_type_uint; + cl_arg_types[10] = &ffi_type_uint; + cl_arg_types[11] = &ffi_type_float; + cl_arg_types[12] = &ffi_type_uint; + cl_arg_types[13] = &ffi_type_uint; + cl_arg_types[14] = &ffi_type_uint; + cl_arg_types[15] = &ffi_type_uint; + cl_arg_types[16] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16, + &ffi_type_sint, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn1, + (void *) 3 /* userdata */, code) == FFI_OK); + try + { + (*((closure_test_type1)code)) + (1.1, 2.2, 3.3, 4.4, 127, 5.5, 6.6, 8, 9, 10, 11, 12.0, 13, + 19, 21, 1); + /* { dg-output "\n1 2 3 4 127 5 6 8 9 10 11 12 13 19 21 1 3: 255" } */ + } catch (int exception_code) + { + CHECK(exception_code == 255); + } + printf("part two OK\n"); + /* { dg-output "\npart two OK" } */ + } + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/unwindtest_ffi_call.cc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/unwindtest_ffi_call.cc new file mode 100644 index 0000000..153d240 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.closures/unwindtest_ffi_call.cc @@ -0,0 +1,54 @@ +/* Area: ffi_call, unwind info + Purpose: Check if the unwind information is passed correctly. + Limitations: none. + PR: none. + Originator: Andreas Tobler 20061213 */ + +/* { dg-do run { xfail moxie*-*-* } } */ + +#include "ffitest.h" + +static int checking(int a __UNUSED__, short b __UNUSED__, + signed char c __UNUSED__) +{ + throw 9; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + ffi_arg rint; + + signed int si; + signed short ss; + signed char sc; + + args[0] = &ffi_type_sint; + values[0] = &si; + args[1] = &ffi_type_sshort; + values[1] = &ss; + args[2] = &ffi_type_schar; + values[2] = ≻ + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, + &ffi_type_sint, args) == FFI_OK); + + si = -6; + ss = -12; + sc = -1; + { + try + { + ffi_call(&cif, FFI_FN(checking), &rint, values); + } catch (int exception_code) + { + CHECK(exception_code == 9); + } + printf("part one OK\n"); + /* { dg-output "part one OK" } */ + } + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex.inc new file mode 100644 index 0000000..4a812ed --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex.inc @@ -0,0 +1,91 @@ +/* -*-c-*- */ +#include "ffitest.h" +#include + +typedef struct cls_struct_align { + unsigned char a; + _Complex T_C_TYPE b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn( + struct cls_struct_align a1, struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + + printf("%d %f,%fi %d %d %f,%fi %d: %d %f,%fi %d\n", + a1.a, T_CONV creal (a1.b), T_CONV cimag (a1.b), a1.c, + a2.a, T_CONV creal (a2.b), T_CONV cimag (a2.b), a2.c, + result.a, T_CONV creal (result.b), T_CONV cimag (result.b), result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_c[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* c_arg_types[5]; + + struct cls_struct_align g_c = { 12, 4951 + 7 * I, 127 }; + struct cls_struct_align f_c = { 1, 9320 + 1 * I, 13 }; + struct cls_struct_align res_c; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &T_FFI_TYPE; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + c_arg_types[0] = &cls_struct_type; + c_arg_types[1] = &cls_struct_type; + c_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + c_arg_types) == FFI_OK); + + args_c[0] = &g_c; + args_c[1] = &f_c; + args_c[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_c, args_c); + /* { dg-output "12 4951,7i 127 1 9320,1i 13: 13 14271,8i 140" } */ + printf("res: %d %f,%fi %d\n", + res_c.a, T_CONV creal (res_c.b), T_CONV cimag (res_c.b), res_c.c); + /* { dg-output "\nres: 13 14271,8i 140" } */ + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); + + res_c = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_c, f_c); + /* { dg-output "\n12 4951,7i 127 1 9320,1i 13: 13 14271,8i 140" } */ + printf("res: %d %f,%fi %d\n", + res_c.a, T_CONV creal (res_c.b), T_CONV cimag (res_c.b), res_c.c); + /* { dg-output "\nres: 13 14271,8i 140" } */ + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex_double.c new file mode 100644 index 0000000..0dff23a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex_double.c @@ -0,0 +1,10 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_double.inc" +#include "cls_align_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex_float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex_float.c new file mode 100644 index 0000000..0affbd0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex_float.c @@ -0,0 +1,10 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_float.inc" +#include "cls_align_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex_longdouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex_longdouble.c new file mode 100644 index 0000000..7889ba8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_align_complex_longdouble.c @@ -0,0 +1,10 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_longdouble.inc" +#include "cls_align_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex.inc new file mode 100644 index 0000000..f937404 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex.inc @@ -0,0 +1,42 @@ +/* -*-c-*- */ +#include "ffitest.h" +#include + +static void cls_ret_complex_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) + { + _Complex T_C_TYPE *pa; + _Complex T_C_TYPE *pr; + pa = (_Complex T_C_TYPE *)args[0]; + pr = (_Complex T_C_TYPE *)resp; + *pr = *pa; + + printf("%.6f,%.6fi: %.6f,%.6fi\n", + T_CONV creal (*pa), T_CONV cimag (*pa), + T_CONV creal (*pr), T_CONV cimag (*pr)); + } +typedef _Complex T_C_TYPE (*cls_ret_complex)(_Complex T_C_TYPE); + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type * cl_arg_types[2]; + _Complex T_C_TYPE res; + + cl_arg_types[0] = &T_FFI_TYPE; + cl_arg_types[1] = NULL; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &T_FFI_TYPE, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_complex_fn, NULL, code) == FFI_OK); + + res = (*((cls_ret_complex)code))(0.125 + 128.0 * I); + printf("res: %.6f,%.6fi\n", T_CONV creal (res), T_CONV cimag (res)); + CHECK (res == (0.125 + 128.0 * I)); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_double.c new file mode 100644 index 0000000..05e3534 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_double.c @@ -0,0 +1,10 @@ +/* Area: closure_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_double.inc" +#include "cls_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_float.c new file mode 100644 index 0000000..5df7849 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_float.c @@ -0,0 +1,10 @@ +/* Area: closure_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_float.inc" +#include "cls_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_longdouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_longdouble.c new file mode 100644 index 0000000..2b1c320 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_longdouble.c @@ -0,0 +1,10 @@ +/* Area: closure_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_longdouble.inc" +#include "cls_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct.inc new file mode 100644 index 0000000..df8708d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct.inc @@ -0,0 +1,71 @@ +/* -*-c-*- */ +#include "ffitest.h" +#include + +typedef struct Cs { + _Complex T_C_TYPE x; + _Complex T_C_TYPE y; +} Cs; + +Cs gc; + +void +closure_test_fn(Cs p) +{ + printf("%.1f,%.1fi %.1f,%.1fi\n", + T_CONV creal (p.x), T_CONV cimag (p.x), + T_CONV creal (p.y), T_CONV cimag (p.y)); + gc = p; +} + +void +closure_test_gn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__, + void** args, void* userdata __UNUSED__) +{ + closure_test_fn(*(Cs*)args[0]); +} + +int main(int argc __UNUSED__, char** argv __UNUSED__) +{ + ffi_cif cif; + + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + ffi_type *cl_arg_types[1]; + + ffi_type ts1_type; + ffi_type* ts1_type_elements[4]; + + Cs arg = { 1.0 + 11.0 * I, 2.0 + 22.0 * I}; + + ts1_type.size = 0; + ts1_type.alignment = 0; + ts1_type.type = FFI_TYPE_STRUCT; + ts1_type.elements = ts1_type_elements; + + ts1_type_elements[0] = &T_FFI_TYPE; + ts1_type_elements[1] = &T_FFI_TYPE; + ts1_type_elements[2] = NULL; + + cl_arg_types[0] = &ts1_type; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_void, cl_arg_types) == FFI_OK); + + CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_gn, NULL, code) == FFI_OK); + + gc.x = 0.0 + 0.0 * I; + gc.y = 0.0 + 0.0 * I; + ((void*(*)(Cs))(code))(arg); + /* { dg-output "1.0,11.0i 2.0,22.0i\n" } */ + CHECK (gc.x == arg.x && gc.y == arg.y); + + gc.x = 0.0 + 0.0 * I; + gc.y = 0.0 + 0.0 * I; + closure_test_fn(arg); + /* { dg-output "1.0,11.0i 2.0,22.0i\n" } */ + CHECK (gc.x == arg.x && gc.y == arg.y); + + return 0; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct_double.c new file mode 100644 index 0000000..ec71346 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct_double.c @@ -0,0 +1,10 @@ +/* Area: ffi_call, closure_call + Purpose: Check complex arguments in structs. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_double.inc" +#include "cls_complex_struct.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct_float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct_float.c new file mode 100644 index 0000000..96fdf75 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct_float.c @@ -0,0 +1,10 @@ +/* Area: ffi_call, closure_call + Purpose: Check complex arguments in structs. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_float.inc" +#include "cls_complex_struct.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble.c new file mode 100644 index 0000000..005b467 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_struct_longdouble.c @@ -0,0 +1,10 @@ +/* Area: ffi_call, closure_call + Purpose: Check complex arguments in structs. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_longdouble.inc" +#include "cls_complex_struct.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va.inc new file mode 100644 index 0000000..8a3e15f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va.inc @@ -0,0 +1,80 @@ +/* -*-c-*- */ +#include "ffitest.h" +#include +#include +#include +#include + +static _Complex T_C_TYPE gComplexValue1 = 1 + 2 * I; +static _Complex T_C_TYPE gComplexValue2 = 3 + 4 * I; + +static int cls_variadic(const char *format, ...) +{ + va_list ap; + _Complex T_C_TYPE p1, p2; + + va_start (ap, format); + p1 = va_arg (ap, _Complex T_C_TYPE); + p2 = va_arg (ap, _Complex T_C_TYPE); + va_end (ap); + + return printf(format, T_CONV creal (p1), T_CONV cimag (p1), + T_CONV creal (p2), T_CONV cimag (p2)); +} + +static void +cls_complex_va_fn(ffi_cif* cif __UNUSED__, void* resp, + void** args, void* userdata __UNUSED__) +{ + char* format = *(char**)args[0]; + gComplexValue1 = *(_Complex T_C_TYPE*)args[1]; + gComplexValue2 = *(_Complex T_C_TYPE*)args[2]; + + *(ffi_arg*)resp = + printf(format, + T_CONV creal (gComplexValue1), T_CONV cimag (gComplexValue1), + T_CONV creal (gComplexValue2), T_CONV cimag (gComplexValue2)); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args[4]; + ffi_type* arg_types[4]; + char *format = "%.1f,%.1fi %.1f,%.1fi\n"; + + _Complex T_C_TYPE complexArg1 = 1.0 + 22.0 *I; + _Complex T_C_TYPE complexArg2 = 333.0 + 4444.0 *I; + ffi_arg res = 0; + + arg_types[0] = &ffi_type_pointer; + arg_types[1] = &T_FFI_TYPE; + arg_types[2] = &T_FFI_TYPE; + arg_types[3] = NULL; + + /* This printf call is variadic */ + CHECK(ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, 1, 3, &ffi_type_sint, + arg_types) == FFI_OK); + + args[0] = &format; + args[1] = &complexArg1; + args[2] = &complexArg2; + args[3] = NULL; + + ffi_call(&cif, FFI_FN(cls_variadic), &res, args); + printf("res: %d\n", (int) res); + CHECK (res == 24); + + CHECK(ffi_prep_closure_loc(pcl, &cif, cls_complex_va_fn, NULL, code) + == FFI_OK); + + res = ((int(*)(char *, ...))(code))(format, complexArg1, complexArg2); + CHECK (gComplexValue1 == complexArg1); + CHECK (gComplexValue2 == complexArg2); + printf("res: %d\n", (int) res); + CHECK (res == 24); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va_double.c new file mode 100644 index 0000000..879ccf3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va_double.c @@ -0,0 +1,10 @@ +/* Area: ffi_call, closure_call + Purpose: Test complex' passed in variable argument lists. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_double.inc" +#include "cls_complex_va.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va_float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va_float.c new file mode 100644 index 0000000..2b17826 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va_float.c @@ -0,0 +1,16 @@ +/* Area: ffi_call, closure_call + Purpose: Test complex' passed in variable argument lists. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +/* Alpha splits _Complex into two arguments. It's illegal to pass + float through varargs, so _Complex float goes badly. In sort of + gets passed as _Complex double, but the compiler doesn't agree + with itself on this issue. */ +/* { dg-do run { xfail alpha*-*-* } } */ + +#include "complex_defs_float.inc" +#include "cls_complex_va.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va_longdouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va_longdouble.c new file mode 100644 index 0000000..6eca965 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/cls_complex_va_longdouble.c @@ -0,0 +1,10 @@ +/* Area: ffi_call, closure_call + Purpose: Test complex' passed in variable argument lists. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_longdouble.inc" +#include "cls_complex_va.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex.exp new file mode 100644 index 0000000..4631db2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex.exp @@ -0,0 +1,36 @@ +# Copyright (C) 2003, 2006, 2009, 2010, 2014 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; see the file COPYING3. If not see +# . + +dg-init +libffi-init + +global srcdir subdir + +set tlist [lsort [glob -nocomplain -- $srcdir/$subdir/*.{c,cc}]] + +if { [libffi_feature_test "#ifdef FFI_TARGET_HAS_COMPLEX_TYPE"] } { + run-many-tests $tlist "" +} else { + foreach test $tlist { + unsupported "$test" + } +} + +dg-finish + +# Local Variables: +# tcl-indent-level:4 +# End: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex.inc new file mode 100644 index 0000000..515ae3e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex.inc @@ -0,0 +1,51 @@ +/* -*-c-*-*/ +#include "ffitest.h" +#include + +static _Complex T_C_TYPE f_complex(_Complex T_C_TYPE c, int x, int *py) +{ + c = -(2 * creal (c)) + (cimag (c) + 1)* I; + *py += x; + + return c; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + + _Complex T_C_TYPE tc_arg; + _Complex T_C_TYPE tc_result; + int tc_int_arg_x; + int tc_y; + int *tc_ptr_arg_y = &tc_y; + + args[0] = &T_FFI_TYPE; + args[1] = &ffi_type_sint; + args[2] = &ffi_type_pointer; + values[0] = &tc_arg; + values[1] = &tc_int_arg_x; + values[2] = &tc_ptr_arg_y; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, + &T_FFI_TYPE, args) == FFI_OK); + + tc_arg = 1 + 7 * I; + tc_int_arg_x = 1234; + tc_y = 9876; + ffi_call(&cif, FFI_FN(f_complex), &tc_result, values); + + printf ("%f,%fi %f,%fi, x %d 1234, y %d 11110\n", + T_CONV creal (tc_result), T_CONV cimag (tc_result), + T_CONV creal (2.0), T_CONV creal (8.0), tc_int_arg_x, tc_y); + + CHECK (creal (tc_result) == -2); + CHECK (cimag (tc_result) == 8); + CHECK (tc_int_arg_x == 1234); + CHECK (*tc_ptr_arg_y == 11110); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_defs_double.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_defs_double.inc new file mode 100644 index 0000000..3583e16 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_defs_double.inc @@ -0,0 +1,7 @@ +/* -*-c-*- */ +/* Complex base type. */ +#define T_FFI_TYPE ffi_type_complex_double +/* C type corresponding to the base type. */ +#define T_C_TYPE double +/* C cast for a value of type T_C_TYPE that is passed to printf. */ +#define T_CONV diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_defs_float.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_defs_float.inc new file mode 100644 index 0000000..bbd9375 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_defs_float.inc @@ -0,0 +1,7 @@ +/* -*-c-*- */ +/* Complex base type. */ +#define T_FFI_TYPE ffi_type_complex_float +/* C type corresponding to the base type. */ +#define T_C_TYPE float +/* C cast for a value of type T_C_TYPE that is passed to printf. */ +#define T_CONV (double) diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_defs_longdouble.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_defs_longdouble.inc new file mode 100644 index 0000000..14b9f24 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_defs_longdouble.inc @@ -0,0 +1,7 @@ +/* -*-c-*- */ +/* Complex base type. */ +#define T_FFI_TYPE ffi_type_complex_longdouble +/* C type corresponding to the base type. */ +#define T_C_TYPE long double +/* C cast for a value of type T_C_TYPE that is passed to printf. */ +#define T_CONV diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_double.c new file mode 100644 index 0000000..8a3297b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_double.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check complex types. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_double.inc" +#include "complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_float.c new file mode 100644 index 0000000..5044ebb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_float.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check complex types. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_float.inc" +#include "complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_int.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_int.c new file mode 100644 index 0000000..bac3190 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_int.c @@ -0,0 +1,86 @@ +/* Area: ffi_call + Purpose: Check non-standard complex types. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "ffitest.h" +#include "ffi.h" +#include + +_Complex int f_complex(_Complex int c, int x, int *py) +{ + __real__ c = -2 * __real__ c; + __imag__ c = __imag__ c + 1; + *py += x; + return c; +} + +/* + * This macro can be used to define new complex type descriptors + * in a platform independent way. + * + * name: Name of the new descriptor is ffi_type_complex_. + * type: The C base type of the complex type. + */ +#define FFI_COMPLEX_TYPEDEF(name, type, ffitype) \ + static ffi_type *ffi_elements_complex_##name [2] = { \ + (ffi_type *)(&ffitype), NULL \ + }; \ + struct struct_align_complex_##name { \ + char c; \ + _Complex type x; \ + }; \ + ffi_type ffi_type_complex_##name = { \ + sizeof(_Complex type), \ + offsetof(struct struct_align_complex_##name, x), \ + FFI_TYPE_COMPLEX, \ + (ffi_type **)ffi_elements_complex_##name \ + } + +/* Define new complex type descriptors using the macro: */ +/* ffi_type_complex_sint */ +FFI_COMPLEX_TYPEDEF(sint, int, ffi_type_sint); +/* ffi_type_complex_uchar */ +FFI_COMPLEX_TYPEDEF(uchar, unsigned char, ffi_type_uint8); + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + + _Complex int tc_arg; + _Complex int tc_result; + int tc_int_arg_x; + int tc_y; + int *tc_ptr_arg_y = &tc_y; + + args[0] = &ffi_type_complex_sint; + args[1] = &ffi_type_sint; + args[2] = &ffi_type_pointer; + values[0] = &tc_arg; + values[1] = &tc_int_arg_x; + values[2] = &tc_ptr_arg_y; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &ffi_type_complex_sint, args) + == FFI_OK); + + tc_arg = 1 + 7 * I; + tc_int_arg_x = 1234; + tc_y = 9876; + ffi_call(&cif, FFI_FN(f_complex), &tc_result, values); + + printf ("%d,%di %d,%di, x %d 1234, y %d 11110\n", + (int)tc_result, (int)(tc_result * -I), 2, 8, tc_int_arg_x, tc_y); + /* dg-output "-2,8i 2,8i, x 1234 1234, y 11110 11110" */ + CHECK (creal (tc_result) == -2); + CHECK (cimag (tc_result) == 8); + CHECK (tc_int_arg_x == 1234); + CHECK (*tc_ptr_arg_y == 11110); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_longdouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_longdouble.c new file mode 100644 index 0000000..7e78366 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/complex_longdouble.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check complex types. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_longdouble.inc" +#include "complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/ffitest.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/ffitest.h new file mode 100644 index 0000000..d27d362 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/ffitest.h @@ -0,0 +1 @@ +#include "../libffi.call/ffitest.h" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex.inc new file mode 100644 index 0000000..e37a774 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex.inc @@ -0,0 +1,78 @@ +/* -*-c-*- */ +#include "ffitest.h" + +#include +#include + +static _Complex T_C_TYPE many(_Complex T_C_TYPE c1, + _Complex T_C_TYPE c2, + _Complex T_C_TYPE c3, + _Complex T_C_TYPE c4, + _Complex T_C_TYPE c5, + _Complex T_C_TYPE c6, + _Complex T_C_TYPE c7, + _Complex T_C_TYPE c8, + _Complex T_C_TYPE c9, + _Complex T_C_TYPE c10, + _Complex T_C_TYPE c11, + _Complex T_C_TYPE c12, + _Complex T_C_TYPE c13) +{ + printf("0 :%f,%fi\n" + "1 :%f,%fi\n" + "2 :%f,%fi\n" + "3 :%f,%fi\n" + "4 :%f,%fi\n" + "5 :%f,%fi\n" + "6 :%f,%fi\n" + "7 :%f,%fi\n" + "8 :%f,%fi\n" + "9 :%f,%fi\n" + "10:%f,%fi\n" + "11:%f,%fi\n" + "12:%f,%fi\n", + T_CONV creal (c1), T_CONV cimag (c1), + T_CONV creal (c2), T_CONV cimag (c2), + T_CONV creal (c3), T_CONV cimag (c3), + T_CONV creal (c4), T_CONV cimag (c4), + T_CONV creal (c5), T_CONV cimag (c5), + T_CONV creal (c6), T_CONV cimag (c6), + T_CONV creal (c7), T_CONV cimag (c7), + T_CONV creal (c8), T_CONV cimag (c8), + T_CONV creal (c9), T_CONV cimag (c9), + T_CONV creal (c10), T_CONV cimag (c10), + T_CONV creal (c11), T_CONV cimag (c11), + T_CONV creal (c12), T_CONV cimag (c12), + T_CONV creal (c13), T_CONV cimag (c13)); + + return (c1+c2-c3-c4+c5+c6+c7-c8-c9-c10-c11+c12+c13); +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[13]; + void *values[13]; + _Complex T_C_TYPE ca[13]; + _Complex T_C_TYPE c, cc; + int i; + + for (i = 0; i < 13; i++) + { + args[i] = &T_FFI_TYPE; + values[i] = &ca[i]; + ca[i] = i + (-20 - i) * I; + } + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 13, &T_FFI_TYPE, args) == FFI_OK); + + ffi_call(&cif, FFI_FN(many), &c, values); + + cc = many(ca[0], ca[1], ca[2], ca[3], ca[4], ca[5], ca[6], ca[7], ca[8], + ca[9], ca[10], ca[11], ca[12]); + CHECK(creal (cc) == creal (c)); + CHECK(cimag (cc) == cimag (c)); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex_double.c new file mode 100644 index 0000000..3fd53c3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex_double.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex, with many arguments + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_double.inc" +#include "many_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex_float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex_float.c new file mode 100644 index 0000000..c43d21c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex_float.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex, with many arguments + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_float.inc" +#include "many_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex_longdouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex_longdouble.c new file mode 100644 index 0000000..dbab723 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/many_complex_longdouble.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex, with many arguments + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_longdouble.inc" +#include "many_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex.inc new file mode 100644 index 0000000..8bf0c1f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex.inc @@ -0,0 +1,37 @@ +/* -*-c-*- */ +#include "ffitest.h" +#include + +static _Complex T_C_TYPE return_c(_Complex T_C_TYPE c) +{ + printf ("%f,%fi\n", T_CONV creal (c), T_CONV cimag (c)); + return 2 * c; +} +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + _Complex T_C_TYPE c, rc, rc2; + T_C_TYPE cr, ci; + + args[0] = &T_FFI_TYPE; + values[0] = &c; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &T_FFI_TYPE, args) == FFI_OK); + + for (cr = -127.0; cr < 127; cr++) + { + ci = 1000.0 - cr; + c = cr + ci * I; + ffi_call(&cif, FFI_FN(return_c), &rc, values); + rc2 = return_c(c); + printf ("%f,%fi vs %f,%fi\n", + T_CONV creal (rc), T_CONV cimag (rc), + T_CONV creal (rc2), T_CONV cimag (rc2)); + CHECK(rc == 2 * c); + } + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1.inc new file mode 100644 index 0000000..7cecc0f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1.inc @@ -0,0 +1,41 @@ +/* -*-c-*- */ +#include "ffitest.h" +#include + +static _Complex T_C_TYPE return_c(_Complex T_C_TYPE c1, float fl2, unsigned int in3, _Complex T_C_TYPE c4) +{ + return c1 + fl2 + in3 + c4; +} +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + _Complex T_C_TYPE c1, c4, rc, rc2; + float fl2; + unsigned int in3; + args[0] = &T_FFI_TYPE; + args[1] = &ffi_type_float; + args[2] = &ffi_type_uint; + args[3] = &T_FFI_TYPE; + values[0] = &c1; + values[1] = &fl2; + values[2] = &in3; + values[3] = &c4; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, + &T_FFI_TYPE, args) == FFI_OK); + c1 = 127.0 + 255.0 * I; + fl2 = 128.0; + in3 = 255; + c4 = 512.7 + 1024.1 * I; + + ffi_call(&cif, FFI_FN(return_c), &rc, values); + rc2 = return_c(c1, fl2, in3, c4); + printf ("%f,%fi vs %f,%fi\n", + T_CONV creal (rc), T_CONV cimag (rc), + T_CONV creal (rc2), T_CONV cimag (rc2)); + CHECK(rc == rc2); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1_double.c new file mode 100644 index 0000000..727410d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1_double.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_double.inc" +#include "return_complex1.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1_float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1_float.c new file mode 100644 index 0000000..a2aeada --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1_float.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_float.inc" +#include "return_complex1.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1_longdouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1_longdouble.c new file mode 100644 index 0000000..103504b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex1_longdouble.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_longdouble.inc" +#include "return_complex1.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2.inc b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2.inc new file mode 100644 index 0000000..265170b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2.inc @@ -0,0 +1,44 @@ +/* -*-c-*- */ +#include "ffitest.h" +#include + +_Complex T_C_TYPE +return_c(_Complex T_C_TYPE c1, _Complex T_C_TYPE c2, + unsigned int in3, _Complex T_C_TYPE c4) +{ + volatile _Complex T_C_TYPE r = c1 + c2 + in3 + c4; + return r; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[MAX_ARGS]; + void *values[MAX_ARGS]; + _Complex T_C_TYPE c1, c2, c4, rc, rc2; + unsigned int in3; + args[0] = &T_FFI_TYPE; + args[1] = &T_FFI_TYPE; + args[2] = &ffi_type_uint; + args[3] = &T_FFI_TYPE; + values[0] = &c1; + values[1] = &c2; + values[2] = &in3; + values[3] = &c4; + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, + &T_FFI_TYPE, args) == FFI_OK); + c1 = 127.0 + 255.0 * I; + c2 = 128.0 + 256.0; + in3 = 255; + c4 = 512.7 + 1024.1 * I; + + ffi_call(&cif, FFI_FN(return_c), &rc, values); + rc2 = return_c(c1, c2, in3, c4); + printf ("%f,%fi vs %f,%fi\n", + T_CONV creal (rc), T_CONV cimag (rc), + T_CONV creal (rc2), T_CONV cimag (rc2)); + CHECK(rc == rc2); + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2_double.c new file mode 100644 index 0000000..ab9efac --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2_double.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_double.inc" +#include "return_complex2.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2_float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2_float.c new file mode 100644 index 0000000..d7f22c2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2_float.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_float.inc" +#include "return_complex2.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2_longdouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2_longdouble.c new file mode 100644 index 0000000..3edea62 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex2_longdouble.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_longdouble.inc" +#include "return_complex2.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex_double.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex_double.c new file mode 100644 index 0000000..e2497cc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex_double.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_double.inc" +#include "return_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex_float.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex_float.c new file mode 100644 index 0000000..a35528f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex_float.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_float.inc" +#include "return_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex_longdouble.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex_longdouble.c new file mode 100644 index 0000000..142d7be --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.complex/return_complex_longdouble.c @@ -0,0 +1,10 @@ +/* Area: ffi_call + Purpose: Check return value complex. + Limitations: none. + PR: none. + Originator: . */ + +/* { dg-do run } */ + +#include "complex_defs_longdouble.inc" +#include "return_complex.inc" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/aa-direct.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/aa-direct.c new file mode 100644 index 0000000..b00c404 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/aa-direct.c @@ -0,0 +1,34 @@ +/* { dg-do run } */ + +#include "static-chain.h" + +#if defined(__GNUC__) && !defined(__clang__) && defined(STATIC_CHAIN_REG) + +#include "ffitest.h" + +/* Blatent assumption here that the prologue doesn't clobber the + static chain for trivial functions. If this is not true, don't + define STATIC_CHAIN_REG, and we'll test what we can via other tests. */ +void *doit(void) +{ + register void *chain __asm__(STATIC_CHAIN_REG); + return chain; +} + +int main() +{ + ffi_cif cif; + void *result; + + CHECK(ffi_prep_cif(&cif, ABI_NUM, 0, &ffi_type_pointer, NULL) == FFI_OK); + + ffi_call_go(&cif, FFI_FN(doit), &result, NULL, &result); + + CHECK(result == &result); + + return 0; +} + +#else /* UNSUPPORTED */ +int main() { return 0; } +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/closure1.c b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/closure1.c new file mode 100644 index 0000000..7b34afc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/closure1.c @@ -0,0 +1,28 @@ +/* { dg-do run } */ + +#include "ffitest.h" + +void doit(ffi_cif *cif, void *rvalue, void **avalue, void *closure) +{ + (void)cif; + (void)avalue; + *(void **)rvalue = closure; +} + +typedef void * (*FN)(void); + +int main() +{ + ffi_cif cif; + ffi_go_closure cl; + void *result; + + CHECK(ffi_prep_cif(&cif, ABI_NUM, 0, &ffi_type_pointer, NULL) == FFI_OK); + CHECK(ffi_prep_go_closure(&cl, &cif, doit) == FFI_OK); + + ffi_call_go(&cif, FFI_FN(*(FN *)&cl), &result, NULL, &cl); + + CHECK(result == &cl); + + exit(0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/ffitest.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/ffitest.h new file mode 100644 index 0000000..d27d362 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/ffitest.h @@ -0,0 +1 @@ +#include "../libffi.call/ffitest.h" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/go.exp b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/go.exp new file mode 100644 index 0000000..100c5e7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/go.exp @@ -0,0 +1,36 @@ +# Copyright (C) 2003, 2006, 2009, 2010, 2014 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; see the file COPYING3. If not see +# . + +dg-init +libffi-init + +global srcdir subdir + +set tlist [lsort [glob -nocomplain -- $srcdir/$subdir/*.{c,cc}]] + +if { [libffi_feature_test "#ifdef FFI_GO_CLOSURES"] } { + run-many-tests $tlist "" +} else { + foreach test $tlist { + unsupported "$test" + } +} + +dg-finish + +# Local Variables: +# tcl-indent-level:4 +# End: diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/static-chain.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/static-chain.h new file mode 100644 index 0000000..3675b40 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/libffi/testsuite/libffi.go/static-chain.h @@ -0,0 +1,19 @@ +#ifdef __aarch64__ +# define STATIC_CHAIN_REG "x18" +#elif defined(__alpha__) +# define STATIC_CHAIN_REG "$1" +#elif defined(__arm__) +# define STATIC_CHAIN_REG "ip" +#elif defined(__sparc__) +# if defined(__arch64__) || defined(__sparcv9) +# define STATIC_CHAIN_REG "g5" +# else +# define STATIC_CHAIN_REG "g2" +# endif +#elif defined(__x86_64__) +# define STATIC_CHAIN_REG "r10" +#elif defined(__i386__) +# ifndef ABI_NUM +# define STATIC_CHAIN_REG "ecx" /* FFI_DEFAULT_ABI only */ +# endif +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/rbffi.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/rbffi.h new file mode 100644 index 0000000..89b3e32 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/rbffi.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2008, 2009, Wayne Meissner + * + * Copyright (c) 2008-2013, Ruby FFI project contributors + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Ruby FFI project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RBFFI_RBFFI_H +#define RBFFI_RBFFI_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define MAX_PARAMETERS (32) + +extern VALUE rbffi_FFIModule; + +extern void rbffi_Type_Init(VALUE ffiModule); +extern void rbffi_Buffer_Init(VALUE ffiModule); +extern void rbffi_Invoker_Init(VALUE ffiModule); +extern void rbffi_Variadic_Init(VALUE ffiModule); +extern VALUE rbffi_AbstractMemoryClass, rbffi_InvokerClass; +extern int rbffi_type_size(VALUE type); +extern void rbffi_Thread_Init(VALUE moduleFFI); + +#ifdef __cplusplus +} +#endif + +#endif /* RBFFI_RBFFI_H */ diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/rbffi_endian.h b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/rbffi_endian.h new file mode 100644 index 0000000..ebb8420 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ext/ffi_c/rbffi_endian.h @@ -0,0 +1,59 @@ +#ifndef JFFI_ENDIAN_H +#define JFFI_ENDIAN_H + +#ifndef _MSC_VER +#include +#endif + +#include + +#if defined(__linux__) || defined(__CYGWIN__) || defined(__GNU__) || defined(__GLIBC__) || defined(__HAIKU__) +# include +# if !defined(LITTLE_ENDIAN) && defined(__LITTLE_ENDIAN) +# define LITTLE_ENDIAN __LITTLE_ENDIAN +# endif +# if !defined(BIG_ENDIAN) && defined(__BIG_ENDIAN) +# define BIG_ENDIAN __BIG_ENDIAN +# endif +# if !defined(BYTE_ORDER) && defined(__BYTE_ORDER) +# define BYTE_ORDER __BYTE_ORDER +# endif +#endif + +#ifdef __sun +# include +# define LITTLE_ENDIAN 1234 +# define BIG_ENDIAN 4321 +# if defined(_BIG_ENDIAN) +# define BYTE_ORDER BIG_ENDIAN +# elif defined(_LITTLE_ENDIAN) +# define BYTE_ORDER LITTLE_ENDIAN +# else +# error "Cannot determine endian-ness" +# endif +#endif + +#if defined(_AIX) && !defined(BYTE_ORDER) +# define LITTLE_ENDIAN 1234 +# define BIG_ENDIAN 4321 +# if defined(__BIG_ENDIAN__) +# define BYTE_ORDER BIG_ENDIAN +# elif defined(__LITTLE_ENDIAN__) +# define BYTE_ORDER LITTLE_ENDIAN +# else +# error "Cannot determine endian-ness" +# endif +#endif + +#if defined(_WIN32) +# define LITTLE_ENDIAN 1234 +# define BIG_ENDIAN 4321 +# define BYTE_ORDER LITTLE_ENDIAN +#endif + +#if !defined(BYTE_ORDER) || !defined(LITTLE_ENDIAN) || !defined(BIG_ENDIAN) +# error "Cannot determine the endian-ness of this platform" +#endif + +#endif /* JFFI_ENDIAN_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ffi.gemspec b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ffi.gemspec new file mode 100644 index 0000000..eaae515 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/ffi.gemspec @@ -0,0 +1,42 @@ +require File.expand_path("../lib/#{File.basename(__FILE__, '.gemspec')}/version", __FILE__) + +Gem::Specification.new do |s| + s.name = 'ffi' + s.version = FFI::VERSION + s.author = 'Wayne Meissner' + s.email = 'wmeissner@gmail.com' + s.homepage = 'https://github.com/ffi/ffi/wiki' + s.summary = 'Ruby FFI' + s.description = 'Ruby FFI library' + if s.respond_to?(:metadata) + s.metadata['bug_tracker_uri'] = 'https://github.com/ffi/ffi/issues' + s.metadata['changelog_uri'] = 'https://github.com/ffi/ffi/blob/master/CHANGELOG.md' + s.metadata['documentation_uri'] = 'https://github.com/ffi/ffi/wiki' + s.metadata['wiki_uri'] = 'https://github.com/ffi/ffi/wiki' + s.metadata['source_code_uri'] = 'https://github.com/ffi/ffi/' + s.metadata['mailing_list_uri'] = 'http://groups.google.com/group/ruby-ffi' + end + s.files = `git ls-files -z`.split("\x0").reject do |f| + f =~ /^(\.|bench|gen|libtest|nbproject|spec)/ + end + + # Add libffi git files + lfs = `git --git-dir ext/ffi_c/libffi/.git ls-files -z`.split("\x0") + # Add autoconf generated files of libffi + lfs += %w[ configure config.guess config.sub install-sh ltmain.sh missing fficonfig.h.in ] + # Add automake generated files of libffi + lfs += `git --git-dir ext/ffi_c/libffi/.git ls-files -z *.am */*.am`.gsub(".am\0", ".in\0").split("\x0") + s.files += lfs.map do |f| + File.join("ext/ffi_c/libffi", f) + end + + s.extensions << 'ext/ffi_c/extconf.rb' + s.rdoc_options = %w[--exclude=ext/ffi_c/.*\.o$ --exclude=ffi_c\.(bundle|so)$] + s.license = 'BSD-3-Clause' + s.require_paths << 'ext/ffi_c' + s.required_ruby_version = '>= 2.3' + s.add_development_dependency 'rake', '~> 13.0' + s.add_development_dependency 'rake-compiler', '~> 1.0' + s.add_development_dependency 'rake-compiler-dock', '~> 1.0' + s.add_development_dependency 'rspec', '~> 2.14.1' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi.rb new file mode 100644 index 0000000..3fb20a8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi.rb @@ -0,0 +1,27 @@ +if RUBY_ENGINE == 'ruby' + begin + require RUBY_VERSION.split('.')[0, 2].join('.') + '/ffi_c' + rescue Exception + require 'ffi_c' + end + + require 'ffi/ffi' + +elsif RUBY_ENGINE == 'jruby' && (RUBY_ENGINE_VERSION.split('.').map(&:to_i) <=> [9, 2, 20]) >= 0 + JRuby::Util.load_ext("org.jruby.ext.ffi.FFIService") + require 'ffi/ffi' + +elsif RUBY_ENGINE == 'truffleruby' && (RUBY_ENGINE_VERSION.split('.').map(&:to_i) <=> [20, 1, 0]) >= 0 + require 'truffleruby/ffi_backend' + require 'ffi/ffi' + +else + # Remove the ffi gem dir from the load path, then reload the internal ffi implementation + $LOAD_PATH.delete(File.dirname(__FILE__)) + $LOAD_PATH.delete(File.join(File.dirname(__FILE__), 'ffi')) + unless $LOADED_FEATURES.nil? + $LOADED_FEATURES.delete(__FILE__) + $LOADED_FEATURES.delete('ffi.rb') + end + require 'ffi.rb' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/abstract_memory.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/abstract_memory.rb new file mode 100644 index 0000000..e0aa221 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/abstract_memory.rb @@ -0,0 +1,44 @@ +# +# Copyright (C) 2020 Lars Kanis +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# + + +module FFI + class AbstractMemory + LONG_MAX = FFI::Pointer.new(1).size + private_constant :LONG_MAX + + # Return +true+ if +self+ has a size limit. + # + # @return [Boolean] + def size_limit? + size != LONG_MAX + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/autopointer.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/autopointer.rb new file mode 100644 index 0000000..679d7e6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/autopointer.rb @@ -0,0 +1,203 @@ +# +# Copyright (C) 2008-2010 Wayne Meissner +# Copyright (C) 2008 Mike Dalessio +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +module FFI + class AutoPointer < Pointer + extend DataConverter + + # @overload initialize(pointer, method) + # @param pointer [Pointer] + # @param method [Method] + # @return [self] + # The passed Method will be invoked at GC time. + # @overload initialize(pointer, proc) + # @param pointer [Pointer] + # @return [self] + # The passed Proc will be invoked at GC time (SEE WARNING BELOW!) + # @note WARNING: passing a proc _may_ cause your pointer to never be + # GC'd, unless you're careful to avoid trapping a reference to the + # pointer in the proc. See the test specs for examples. + # @overload initialize(pointer) { |p| ... } + # @param pointer [Pointer] + # @yieldparam [Pointer] p +pointer+ passed to the block + # @return [self] + # The passed block will be invoked at GC time. + # @note + # WARNING: passing a block will cause your pointer to never be GC'd. + # This is bad. + # @overload initialize(pointer) + # @param pointer [Pointer] + # @return [self] + # The pointer's release() class method will be invoked at GC time. + # + # @note The safest, and therefore preferred, calling + # idiom is to pass a Method as the second parameter. Example usage: + # + # class PointerHelper + # def self.release(pointer) + # ... + # end + # end + # + # p = AutoPointer.new(other_pointer, PointerHelper.method(:release)) + # + # The above code will cause PointerHelper#release to be invoked at GC time. + # + # @note + # The last calling idiom (only one parameter) is generally only + # going to be useful if you subclass {AutoPointer}, and override + # #release, which by default does nothing. + def initialize(ptr, proc=nil, &block) + super(ptr.type_size, ptr) + raise TypeError, "Invalid pointer" if ptr.nil? || !ptr.kind_of?(Pointer) \ + || ptr.kind_of?(MemoryPointer) || ptr.kind_of?(AutoPointer) + + @releaser = if proc + if not proc.respond_to?(:call) + raise RuntimeError.new("proc must be callable") + end + CallableReleaser.new(ptr, proc) + + else + if not self.class.respond_to?(:release) + raise RuntimeError.new("no release method defined") + end + DefaultReleaser.new(ptr, self.class) + end + + ObjectSpace.define_finalizer(self, @releaser) + self + end + + # @return [nil] + # Free the pointer. + def free + @releaser.free + end + + # @param [Boolean] autorelease + # @return [Boolean] +autorelease+ + # Set +autorelease+ property. See {Pointer Autorelease section at Pointer}. + def autorelease=(autorelease) + @releaser.autorelease=(autorelease) + end + + # @return [Boolean] +autorelease+ + # Get +autorelease+ property. See {Pointer Autorelease section at Pointer}. + def autorelease? + @releaser.autorelease + end + + # @abstract Base class for {AutoPointer}'s releasers. + # + # All subclasses of Releaser should define a +#release(ptr)+ method. + # A releaser is an object in charge of release an {AutoPointer}. + class Releaser + attr_accessor :autorelease + + # @param [Pointer] ptr + # @param [#call] proc + # @return [nil] + # A new instance of Releaser. + def initialize(ptr, proc) + @ptr = ptr + @proc = proc + @autorelease = true + end + + # @return [nil] + # Free pointer. + def free + if @ptr + release(@ptr) + @autorelease = false + @ptr = nil + @proc = nil + end + end + + # @param args + # Release pointer if +autorelease+ is set. + def call(*args) + release(@ptr) if @autorelease && @ptr + end + end + + # DefaultReleaser is a {Releaser} used when an {AutoPointer} is defined + # without Proc or Method. In this case, the pointer to release must be of + # a class derived from AutoPointer with a {release} class method. + class DefaultReleaser < Releaser + # @param [Pointer] ptr + # @return [nil] + # Release +ptr+ using the {release} class method of its class. + def release(ptr) + @proc.release(ptr) + end + end + + # CallableReleaser is a {Releaser} used when an {AutoPointer} is defined with a + # Proc or a Method. + class CallableReleaser < Releaser + # Release +ptr+ by using Proc or Method defined at +ptr+ + # {AutoPointer#initialize initialization}. + # + # @param [Pointer] ptr + # @return [nil] + def release(ptr) + @proc.call(ptr) + end + end + + # Return native type of AutoPointer. + # + # Override {DataConverter#native_type}. + # @return [Type::POINTER] + # @raise {RuntimeError} if class does not implement a +#release+ method + def self.native_type + if not self.respond_to?(:release) + raise RuntimeError.new("no release method defined for #{self.inspect}") + end + Type::POINTER + end + + # Create a new AutoPointer. + # + # Override {DataConverter#from_native}. + # @overload self.from_native(ptr, ctx) + # @param [Pointer] ptr + # @param ctx not used. Please set +nil+. + # @return [AutoPointer] + def self.from_native(val, ctx) + self.new(val) + end + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/buffer.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/buffer.rb new file mode 100644 index 0000000..449e45b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/buffer.rb @@ -0,0 +1,4 @@ +# +# All the code from this file is now implemented in C. This file remains +# to satisfy any leftover require 'ffi/buffer' in user code +# diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/callback.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/callback.rb new file mode 100644 index 0000000..32d52f7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/callback.rb @@ -0,0 +1,4 @@ +# +# All the code from this file is now implemented in C. This file remains +# to satisfy any leftover require 'ffi/callback' in user code +# diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/data_converter.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/data_converter.rb new file mode 100644 index 0000000..1527588 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/data_converter.rb @@ -0,0 +1,67 @@ +# +# Copyright (C) 2008-2010 Wayne Meissner +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# + +module FFI + # This module is used to extend somes classes and give then a common API. + # + # Most of methods defined here must be overriden. + module DataConverter + # Get native type. + # + # @overload native_type(type) + # @param [String, Symbol, Type] type + # @return [Type] + # Get native type from +type+. + # + # @overload native_type + # @raise {NotImplementedError} This method must be overriden. + def native_type(type = nil) + if type + @native_type = FFI.find_type(type) + else + native_type = @native_type + unless native_type + raise NotImplementedError, 'native_type method not overridden and no native_type set' + end + native_type + end + end + + # Convert to a native type. + def to_native(value, ctx) + value + end + + # Convert from a native type. + def from_native(value, ctx) + value + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/enum.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/enum.rb new file mode 100644 index 0000000..8fcb498 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/enum.rb @@ -0,0 +1,296 @@ +# +# Copyright (C) 2009, 2010 Wayne Meissner +# Copyright (C) 2009 Luc Heinrich +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +module FFI + + # An instance of this class permits to manage {Enum}s. In fact, Enums is a collection of {Enum}s. + class Enums + + # @return [nil] + def initialize + @all_enums = Array.new + @tagged_enums = Hash.new + @symbol_map = Hash.new + end + + # @param [Enum] enum + # Add an {Enum} to the collection. + def <<(enum) + @all_enums << enum + @tagged_enums[enum.tag] = enum unless enum.tag.nil? + @symbol_map.merge!(enum.symbol_map) + end + + # @param query enum tag or part of an enum name + # @return [Enum] + # Find a {Enum} in collection. + def find(query) + if @tagged_enums.has_key?(query) + @tagged_enums[query] + else + @all_enums.detect { |enum| enum.symbols.include?(query) } + end + end + + # @param symbol a symbol to find in merge symbol maps of all enums. + # @return a symbol + def __map_symbol(symbol) + @symbol_map[symbol] + end + + end + + # Represents a C enum. + # + # For a C enum: + # enum fruits { + # apple, + # banana, + # orange, + # pineapple + # }; + # are defined this vocabulary: + # * a _symbol_ is a word from the enumeration (ie. _apple_, by example); + # * a _value_ is the value of a symbol in the enumeration (by example, apple has value _0_ and banana _1_). + class Enum + include DataConverter + + attr_reader :tag + attr_reader :native_type + + # @overload initialize(info, tag=nil) + # @param [nil, Enumerable] info + # @param [nil, Symbol] tag enum tag + # @overload initialize(native_type, info, tag=nil) + # @param [FFI::Type] native_type Native type for new Enum + # @param [nil, Enumerable] info symbols and values for new Enum + # @param [nil, Symbol] tag name of new Enum + def initialize(*args) + @native_type = args.first.kind_of?(FFI::Type) ? args.shift : Type::INT + info, @tag = *args + @kv_map = Hash.new + unless info.nil? + last_cst = nil + value = 0 + info.each do |i| + case i + when Symbol + raise ArgumentError, "duplicate enum key" if @kv_map.has_key?(i) + @kv_map[i] = value + last_cst = i + value += 1 + when Integer + @kv_map[last_cst] = i + value = i+1 + end + end + end + @vk_map = @kv_map.invert + end + + # @return [Array] enum symbol names + def symbols + @kv_map.keys + end + + # Get a symbol or a value from the enum. + # @overload [](query) + # Get enum value from symbol. + # @param [Symbol] query + # @return [Integer] + # @overload [](query) + # Get enum symbol from value. + # @param [Integer] query + # @return [Symbol] + def [](query) + case query + when Symbol + @kv_map[query] + when Integer + @vk_map[query] + end + end + alias find [] + + # Get the symbol map. + # @return [Hash] + def symbol_map + @kv_map + end + + alias to_h symbol_map + alias to_hash symbol_map + + # @param [Symbol, Integer, #to_int] val + # @param ctx unused + # @return [Integer] value of a enum symbol + def to_native(val, ctx) + @kv_map[val] || if val.is_a?(Integer) + val + elsif val.respond_to?(:to_int) + val.to_int + else + raise ArgumentError, "invalid enum value, #{val.inspect}" + end + end + + # @param val + # @return symbol name if it exists for +val+. + def from_native(val, ctx) + @vk_map[val] || val + end + end + + # Represents a C enum whose values are power of 2 + # + # @example + # enum { + # red = (1<<0), + # green = (1<<1), + # blue = (1<<2) + # } + # + # Contrary to classical enums, bitmask values are usually combined + # when used. + class Bitmask < Enum + + # @overload initialize(info, tag=nil) + # @param [nil, Enumerable] info symbols and bit rank for new Bitmask + # @param [nil, Symbol] tag name of new Bitmask + # @overload initialize(native_type, info, tag=nil) + # @param [FFI::Type] native_type Native type for new Bitmask + # @param [nil, Enumerable] info symbols and bit rank for new Bitmask + # @param [nil, Symbol] tag name of new Bitmask + def initialize(*args) + @native_type = args.first.kind_of?(FFI::Type) ? args.shift : Type::INT + info, @tag = *args + @kv_map = Hash.new + unless info.nil? + last_cst = nil + value = 0 + info.each do |i| + case i + when Symbol + raise ArgumentError, "duplicate bitmask key" if @kv_map.has_key?(i) + @kv_map[i] = 1 << value + last_cst = i + value += 1 + when Integer + raise ArgumentError, "bitmask index should be positive" if i<0 + @kv_map[last_cst] = 1 << i + value = i+1 + end + end + end + @vk_map = @kv_map.invert + end + + # Get a symbol list or a value from the bitmask + # @overload [](*query) + # Get bitmask value from symbol list + # @param [Symbol] query + # @return [Integer] + # @overload [](query) + # Get bitmaks value from symbol array + # @param [Array] query + # @return [Integer] + # @overload [](*query) + # Get a list of bitmask symbols corresponding to + # the or reduction of a list of integer + # @param [Integer] query + # @return [Array] + # @overload [](query) + # Get a list of bitmask symbols corresponding to + # the or reduction of a list of integer + # @param [Array] query + # @return [Array] + def [](*query) + flat_query = query.flatten + raise ArgumentError, "query should be homogeneous, #{query.inspect}" unless flat_query.all? { |o| o.is_a?(Symbol) } || flat_query.all? { |o| o.is_a?(Integer) || o.respond_to?(:to_int) } + case flat_query[0] + when Symbol + flat_query.inject(0) do |val, o| + v = @kv_map[o] + if v then val |= v else val end + end + when Integer, ->(o) { o.respond_to?(:to_int) } + val = flat_query.inject(0) { |mask, o| mask |= o.to_int } + @kv_map.select { |_, v| v & val != 0 }.keys + end + end + + # Get the native value of a bitmask + # @overload to_native(query, ctx) + # @param [Symbol, Integer, #to_int] query + # @param ctx unused + # @return [Integer] value of a bitmask + # @overload to_native(query, ctx) + # @param [Array] query + # @param ctx unused + # @return [Integer] value of a bitmask + def to_native(query, ctx) + return 0 if query.nil? + flat_query = [query].flatten + flat_query.inject(0) do |val, o| + case o + when Symbol + v = @kv_map[o] + raise ArgumentError, "invalid bitmask value, #{o.inspect}" unless v + val |= v + when Integer + val |= o + when ->(obj) { obj.respond_to?(:to_int) } + val |= o.to_int + else + raise ArgumentError, "invalid bitmask value, #{o.inspect}" + end + end + end + + # @param [Integer] val + # @param ctx unused + # @return [Array] list of symbol names corresponding to val, plus an optional remainder if some bits don't match any constant + def from_native(val, ctx) + list = @kv_map.select { |_, v| v & val != 0 }.keys + # If there are unmatch flags, + # return them in an integer, + # else information can be lost. + # Similar to Enum behavior. + remainder = val ^ list.inject(0) do |tmp, o| + v = @kv_map[o] + if v then tmp |= v else tmp end + end + list.push remainder unless remainder == 0 + return list + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/errno.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/errno.rb new file mode 100644 index 0000000..de82d89 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/errno.rb @@ -0,0 +1,43 @@ +# +# Copyright (C) 2008-2010 Wayne Meissner +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# + +module FFI + # @return (see FFI::LastError.error) + # @see FFI::LastError.error + def self.errno + FFI::LastError.error + end + # @param error (see FFI::LastError.error=) + # @return (see FFI::LastError.error=) + # @see FFI::LastError.error= + def self.errno=(error) + FFI::LastError.error = error + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/ffi.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/ffi.rb new file mode 100644 index 0000000..dfffa8c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/ffi.rb @@ -0,0 +1,47 @@ +# +# Copyright (C) 2008-2010 JRuby project +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +require 'ffi/platform' +require 'ffi/data_converter' +require 'ffi/types' +require 'ffi/library' +require 'ffi/errno' +require 'ffi/abstract_memory' +require 'ffi/pointer' +require 'ffi/memorypointer' +require 'ffi/struct' +require 'ffi/union' +require 'ffi/managedstruct' +require 'ffi/callback' +require 'ffi/io' +require 'ffi/autopointer' +require 'ffi/variadic' +require 'ffi/enum' +require 'ffi/version' diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/io.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/io.rb new file mode 100644 index 0000000..e1bb955 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/io.rb @@ -0,0 +1,62 @@ +# +# Copyright (C) 2008, 2009 Wayne Meissner +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# + +module FFI + + # This module implements a couple of class methods to play with IO. + module IO + # @param [Integer] fd file decriptor + # @param [String] mode mode string + # @return [::IO] + # Synonym for IO::for_fd. + def self.for_fd(fd, mode = "r") + ::IO.for_fd(fd, mode) + end + + # @param [#read] io io to read from + # @param [AbstractMemory] buf destination for data read from +io+ + # @param [nil, Numeric] len maximul number of bytes to read from +io+. If +nil+, + # read until end of file. + # @return [Numeric] length really read, in bytes + # + # A version of IO#read that reads data from an IO and put then into a native buffer. + # + # This will be optimized at some future time to eliminate the double copy. + # + def self.native_read(io, buf, len) + tmp = io.read(len) + return -1 unless tmp + buf.put_bytes(0, tmp) + tmp.length + end + + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/library.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/library.rb new file mode 100644 index 0000000..43b2bfe --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/library.rb @@ -0,0 +1,592 @@ +# +# Copyright (C) 2008-2010 Wayne Meissner +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# + +module FFI + CURRENT_PROCESS = USE_THIS_PROCESS_AS_LIBRARY = Object.new + + # @param [#to_s] lib library name + # @return [String] library name formatted for current platform + # Transform a generic library name to a platform library name + # @example + # # Linux + # FFI.map_library_name 'c' # -> "libc.so.6" + # FFI.map_library_name 'jpeg' # -> "libjpeg.so" + # # Windows + # FFI.map_library_name 'c' # -> "msvcrt.dll" + # FFI.map_library_name 'jpeg' # -> "jpeg.dll" + def self.map_library_name(lib) + # Mangle the library name to reflect the native library naming conventions + lib = Library::LIBC if lib == 'c' + + if lib && File.basename(lib) == lib + lib = Platform::LIBPREFIX + lib unless lib =~ /^#{Platform::LIBPREFIX}/ + r = Platform::IS_WINDOWS || Platform::IS_MAC ? "\\.#{Platform::LIBSUFFIX}$" : "\\.so($|\\.[1234567890]+)" + lib += ".#{Platform::LIBSUFFIX}" unless lib =~ /#{r}/ + end + + lib + end + + # Exception raised when a function is not found in libraries + class NotFoundError < LoadError + def initialize(function, *libraries) + super("Function '#{function}' not found in [#{libraries[0].nil? ? 'current process' : libraries.join(", ")}]") + end + end + + # This module is the base to use native functions. + # + # A basic usage may be: + # require 'ffi' + # + # module Hello + # extend FFI::Library + # ffi_lib FFI::Library::LIBC + # attach_function 'puts', [ :string ], :int + # end + # + # Hello.puts("Hello, World") + # + # + module Library + CURRENT_PROCESS = FFI::CURRENT_PROCESS + LIBC = FFI::Platform::LIBC + + # @param mod extended object + # @return [nil] + # @raise {RuntimeError} if +mod+ is not a Module + # Test if extended object is a Module. If not, raise RuntimeError. + def self.extended(mod) + raise RuntimeError.new("must only be extended by module") unless mod.kind_of?(::Module) + end + + + # @param [Array] names names of libraries to load + # @return [Array] + # @raise {LoadError} if a library cannot be opened + # Load native libraries. + def ffi_lib(*names) + raise LoadError.new("library names list must not be empty") if names.empty? + + lib_flags = defined?(@ffi_lib_flags) ? @ffi_lib_flags : FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL + ffi_libs = names.map do |name| + + if name == FFI::CURRENT_PROCESS + FFI::DynamicLibrary.open(nil, FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL) + + else + libnames = (name.is_a?(::Array) ? name : [ name ]).map(&:to_s).map { |n| [ n, FFI.map_library_name(n) ].uniq }.flatten.compact + lib = nil + errors = {} + + libnames.each do |libname| + begin + orig = libname + lib = FFI::DynamicLibrary.open(libname, lib_flags) + break if lib + + rescue Exception => ex + ldscript = false + if ex.message =~ /(([^ \t()])+\.so([^ \t:()])*):([ \t])*(invalid ELF header|file too short|invalid file format)/ + if File.binread($1) =~ /(?:GROUP|INPUT) *\( *([^ \)]+)/ + libname = $1 + ldscript = true + end + end + + if ldscript + retry + else + # TODO better library lookup logic + unless libname.start_with?("/") || FFI::Platform.windows? + path = ['/usr/lib/','/usr/local/lib/','/opt/local/lib/', '/opt/homebrew/lib/'].find do |pth| + File.exist?(pth + libname) + end + if path + libname = path + libname + retry + end + end + + libr = (orig == libname ? orig : "#{orig} #{libname}") + errors[libr] = ex + end + end + end + + if lib.nil? + raise LoadError.new(errors.values.join(".\n")) + end + + # return the found lib + lib + end + end + + @ffi_libs = ffi_libs + end + + # Set the calling convention for {#attach_function} and {#callback} + # + # @see http://en.wikipedia.org/wiki/Stdcall#stdcall + # @note +:stdcall+ is typically used for attaching Windows API functions + # + # @param [Symbol] convention one of +:default+, +:stdcall+ + # @return [Symbol] the new calling convention + def ffi_convention(convention = nil) + @ffi_convention ||= :default + @ffi_convention = convention if convention + @ffi_convention + end + + # @see #ffi_lib + # @return [Array] array of currently loaded FFI libraries + # @raise [LoadError] if no libraries have been loaded (using {#ffi_lib}) + # Get FFI libraries loaded using {#ffi_lib}. + def ffi_libraries + raise LoadError.new("no library specified") if !defined?(@ffi_libs) || @ffi_libs.empty? + @ffi_libs + end + + # Flags used in {#ffi_lib}. + # + # This map allows you to supply symbols to {#ffi_lib_flags} instead of + # the actual constants. + FlagsMap = { + :global => DynamicLibrary::RTLD_GLOBAL, + :local => DynamicLibrary::RTLD_LOCAL, + :lazy => DynamicLibrary::RTLD_LAZY, + :now => DynamicLibrary::RTLD_NOW + } + + # Sets library flags for {#ffi_lib}. + # + # @example + # ffi_lib_flags(:lazy, :local) # => 5 + # + # @param [Symbol, …] flags (see {FlagsMap}) + # @return [Fixnum] the new value + def ffi_lib_flags(*flags) + @ffi_lib_flags = flags.inject(0) { |result, f| result | FlagsMap[f] } + end + + + ## + # @overload attach_function(func, args, returns, options = {}) + # @example attach function without an explicit name + # module Foo + # extend FFI::Library + # ffi_lib FFI::Library::LIBC + # attach_function :malloc, [:size_t], :pointer + # end + # # now callable via Foo.malloc + # @overload attach_function(name, func, args, returns, options = {}) + # @example attach function with an explicit name + # module Bar + # extend FFI::Library + # ffi_lib FFI::Library::LIBC + # attach_function :c_malloc, :malloc, [:size_t], :pointer + # end + # # now callable via Bar.c_malloc + # + # Attach C function +func+ to this module. + # + # + # @param [#to_s] name name of ruby method to attach as + # @param [#to_s] func name of C function to attach + # @param [Array] args an array of types + # @param [Symbol] returns type of return value + # @option options [Boolean] :blocking (@blocking) set to true if the C function is a blocking call + # @option options [Symbol] :convention (:default) calling convention (see {#ffi_convention}) + # @option options [FFI::Enums] :enums + # @option options [Hash] :type_map + # + # @return [FFI::VariadicInvoker] + # + # @raise [FFI::NotFoundError] if +func+ cannot be found in the attached libraries (see {#ffi_lib}) + def attach_function(name, func, args, returns = nil, options = nil) + mname, a2, a3, a4, a5 = name, func, args, returns, options + cname, arg_types, ret_type, opts = (a4 && (a2.is_a?(String) || a2.is_a?(Symbol))) ? [ a2, a3, a4, a5 ] : [ mname.to_s, a2, a3, a4 ] + + # Convert :foo to the native type + arg_types = arg_types.map { |e| find_type(e) } + options = { + :convention => ffi_convention, + :type_map => defined?(@ffi_typedefs) ? @ffi_typedefs : nil, + :blocking => defined?(@blocking) && @blocking, + :enums => defined?(@ffi_enums) ? @ffi_enums : nil, + } + + @blocking = false + options.merge!(opts) if opts && opts.is_a?(Hash) + + # Try to locate the function in any of the libraries + invokers = [] + ffi_libraries.each do |lib| + if invokers.empty? + begin + function = nil + function_names(cname, arg_types).find do |fname| + function = lib.find_function(fname) + end + raise LoadError unless function + + invokers << if arg_types.length > 0 && arg_types[arg_types.length - 1] == FFI::NativeType::VARARGS + VariadicInvoker.new(function, arg_types, find_type(ret_type), options) + + else + Function.new(find_type(ret_type), arg_types, function, options) + end + + rescue LoadError + end + end + end + invoker = invokers.compact.shift + raise FFI::NotFoundError.new(cname.to_s, ffi_libraries.map { |lib| lib.name }) unless invoker + + invoker.attach(self, mname.to_s) + invoker + end + + # @param [#to_s] name function name + # @param [Array] arg_types function's argument types + # @return [Array] + # This function returns a list of possible names to lookup. + # @note Function names on windows may be decorated if they are using stdcall. See + # * http://en.wikipedia.org/wiki/Name_mangling#C_name_decoration_in_Microsoft_Windows + # * http://msdn.microsoft.com/en-us/library/zxk0tw93%28v=VS.100%29.aspx + # * http://en.wikibooks.org/wiki/X86_Disassembly/Calling_Conventions#STDCALL + # Note that decorated names can be overridden via def files. Also note that the + # windows api, although using, doesn't have decorated names. + def function_names(name, arg_types) + result = [name.to_s] + if ffi_convention == :stdcall + # Get the size of each parameter + size = arg_types.inject(0) do |mem, arg| + size = arg.size + # The size must be a multiple of 4 + size += (4 - size) % 4 + mem + size + end + + result << "_#{name.to_s}@#{size}" # win32 + result << "#{name.to_s}@#{size}" # win64 + end + result + end + + # @overload attach_variable(mname, cname, type) + # @param [#to_s] mname name of ruby method to attach as + # @param [#to_s] cname name of C variable to attach + # @param [DataConverter, Struct, Symbol, Type] type C variable's type + # @example + # module Bar + # extend FFI::Library + # ffi_lib 'my_lib' + # attach_variable :c_myvar, :myvar, :long + # end + # # now callable via Bar.c_myvar + # @overload attach_variable(cname, type) + # @param [#to_s] mname name of ruby method to attach as + # @param [DataConverter, Struct, Symbol, Type] type C variable's type + # @example + # module Bar + # extend FFI::Library + # ffi_lib 'my_lib' + # attach_variable :myvar, :long + # end + # # now callable via Bar.myvar + # @return [DynamicLibrary::Symbol] + # @raise {FFI::NotFoundError} if +cname+ cannot be found in libraries + # + # Attach C variable +cname+ to this module. + def attach_variable(mname, a1, a2 = nil) + cname, type = a2 ? [ a1, a2 ] : [ mname.to_s, a1 ] + address = nil + ffi_libraries.each do |lib| + begin + address = lib.find_variable(cname.to_s) + break unless address.nil? + rescue LoadError + end + end + + raise FFI::NotFoundError.new(cname, ffi_libraries) if address.nil? || address.null? + if type.is_a?(Class) && type < FFI::Struct + # If it is a global struct, just attach directly to the pointer + s = s = type.new(address) # Assigning twice to suppress unused variable warning + self.module_eval <<-code, __FILE__, __LINE__ + @@ffi_gvar_#{mname} = s + def self.#{mname} + @@ffi_gvar_#{mname} + end + code + + else + sc = Class.new(FFI::Struct) + sc.layout :gvar, find_type(type) + s = sc.new(address) + # + # Attach to this module as mname/mname= + # + self.module_eval <<-code, __FILE__, __LINE__ + @@ffi_gvar_#{mname} = s + def self.#{mname} + @@ffi_gvar_#{mname}[:gvar] + end + def self.#{mname}=(value) + @@ffi_gvar_#{mname}[:gvar] = value + end + code + + end + + address + end + + + # @overload callback(name, params, ret) + # @param name callback name to add to type map + # @param [Array] params array of parameters' types + # @param [DataConverter, Struct, Symbol, Type] ret callback return type + # @overload callback(params, ret) + # @param [Array] params array of parameters' types + # @param [DataConverter, Struct, Symbol, Type] ret callback return type + # @return [FFI::CallbackInfo] + def callback(*args) + raise ArgumentError, "wrong number of arguments" if args.length < 2 || args.length > 3 + name, params, ret = if args.length == 3 + args + else + [ nil, args[0], args[1] ] + end + + native_params = params.map { |e| find_type(e) } + raise ArgumentError, "callbacks cannot have variadic parameters" if native_params.include?(FFI::Type::VARARGS) + options = Hash.new + options[:convention] = ffi_convention + options[:enums] = @ffi_enums if defined?(@ffi_enums) + ret_type = find_type(ret) + if ret_type == Type::STRING + raise TypeError, ":string is not allowed as return type of callbacks" + end + cb = FFI::CallbackInfo.new(ret_type, native_params, options) + + # Add to the symbol -> type map (unless there was no name) + unless name.nil? + typedef cb, name + end + + cb + end + + # Register or get an already registered type definition. + # + # To register a new type definition, +old+ should be a {FFI::Type}. +add+ + # is in this case the type definition. + # + # If +old+ is a {DataConverter}, a {Type::Mapped} is returned. + # + # If +old+ is +:enum+ + # * and +add+ is an +Array+, a call to {#enum} is made with +add+ as single parameter; + # * in others cases, +info+ is used to create a named enum. + # + # If +old+ is a key for type map, #typedef get +old+ type definition. + # + # @param [DataConverter, Symbol, Type] old + # @param [Symbol] add + # @param [Symbol] info + # @return [FFI::Enum, FFI::Type] + def typedef(old, add, info=nil) + @ffi_typedefs = Hash.new unless defined?(@ffi_typedefs) + + @ffi_typedefs[add] = if old.kind_of?(FFI::Type) + old + + elsif @ffi_typedefs.has_key?(old) + @ffi_typedefs[old] + + elsif old.is_a?(DataConverter) + FFI::Type::Mapped.new(old) + + elsif old == :enum + if add.kind_of?(Array) + self.enum(add) + else + self.enum(info, add) + end + + else + FFI.find_type(old) + end + end + + private + # Generic enum builder + # @param [Class] klass can be one of FFI::Enum or FFI::Bitmask + # @param args (see #enum or #bitmask) + def generic_enum(klass, *args) + native_type = args.first.kind_of?(FFI::Type) ? args.shift : nil + name, values = if args[0].kind_of?(Symbol) && args[1].kind_of?(Array) + [ args[0], args[1] ] + elsif args[0].kind_of?(Array) + [ nil, args[0] ] + else + [ nil, args ] + end + @ffi_enums = FFI::Enums.new unless defined?(@ffi_enums) + @ffi_enums << (e = native_type ? klass.new(native_type, values, name) : klass.new(values, name)) + + # If called with a name, add a typedef alias + typedef(e, name) if name + e + end + + public + # @overload enum(name, values) + # Create a named enum. + # @example + # enum :foo, [:zero, :one, :two] # named enum + # @param [Symbol] name name for new enum + # @param [Array] values values for enum + # @overload enum(*args) + # Create an unnamed enum. + # @example + # enum :zero, :one, :two # unnamed enum + # @param args values for enum + # @overload enum(values) + # Create an unnamed enum. + # @example + # enum [:zero, :one, :two] # unnamed enum, equivalent to above example + # @param [Array] values values for enum + # @overload enum(native_type, name, values) + # Create a named enum and specify the native type. + # @example + # enum FFI::Type::UINT64, :foo, [:zero, :one, :two] # named enum + # @param [FFI::Type] native_type native type for new enum + # @param [Symbol] name name for new enum + # @param [Array] values values for enum + # @overload enum(native_type, *args) + # Create an unnamed enum and specify the native type. + # @example + # enum FFI::Type::UINT64, :zero, :one, :two # unnamed enum + # @param [FFI::Type] native_type native type for new enum + # @param args values for enum + # @overload enum(native_type, values) + # Create an unnamed enum and specify the native type. + # @example + # enum Type::UINT64, [:zero, :one, :two] # unnamed enum, equivalent to above example + # @param [FFI::Type] native_type native type for new enum + # @param [Array] values values for enum + # @return [FFI::Enum] + # Create a new {FFI::Enum}. + def enum(*args) + generic_enum(FFI::Enum, *args) + end + + # @overload bitmask(name, values) + # Create a named bitmask + # @example + # bitmask :foo, [:red, :green, :blue] # bits 0,1,2 are used + # bitmask :foo, [:red, :green, 5, :blue] # bits 0,5,6 are used + # @param [Symbol] name for new bitmask + # @param [Array] values for new bitmask + # @overload bitmask(*args) + # Create an unamed bitmask + # @example + # bm = bitmask :red, :green, :blue # bits 0,1,2 are used + # bm = bitmask :red, :green, 5, blue # bits 0,5,6 are used + # @param [Symbol, Integer] args values for new bitmask + # @overload bitmask(values) + # Create an unamed bitmask + # @example + # bm = bitmask [:red, :green, :blue] # bits 0,1,2 are used + # bm = bitmask [:red, :green, 5, blue] # bits 0,5,6 are used + # @param [Array] values for new bitmask + # @overload bitmask(native_type, name, values) + # Create a named enum and specify the native type. + # @example + # bitmask FFI::Type::UINT64, :foo, [:red, :green, :blue] + # @param [FFI::Type] native_type native type for new bitmask + # @param [Symbol] name for new bitmask + # @param [Array] values for new bitmask + # @overload bitmask(native_type, *args) + # @example + # bitmask FFI::Type::UINT64, :red, :green, :blue + # @param [FFI::Type] native_type native type for new bitmask + # @param [Symbol, Integer] args values for new bitmask + # @overload bitmask(native_type, values) + # Create a named enum and specify the native type. + # @example + # bitmask FFI::Type::UINT64, [:red, :green, :blue] + # @param [FFI::Type] native_type native type for new bitmask + # @param [Array] values for new bitmask + # @return [FFI::Bitmask] + # Create a new FFI::Bitmask + def bitmask(*args) + generic_enum(FFI::Bitmask, *args) + end + + # @param name + # @return [FFI::Enum] + # Find an enum by name. + def enum_type(name) + @ffi_enums.find(name) if defined?(@ffi_enums) + end + + # @param symbol + # @return [FFI::Enum] + # Find an enum by a symbol it contains. + def enum_value(symbol) + @ffi_enums.__map_symbol(symbol) + end + + # @param [DataConverter, Type, Struct, Symbol] t type to find + # @return [Type] + # Find a type definition. + def find_type(t) + if t.kind_of?(Type) + t + + elsif defined?(@ffi_typedefs) && @ffi_typedefs.has_key?(t) + @ffi_typedefs[t] + + elsif t.is_a?(Class) && t < Struct + Type::POINTER + + elsif t.is_a?(DataConverter) + # Add a typedef so next time the converter is used, it hits the cache + typedef Type::Mapped.new(t), t + + end || FFI.find_type(t) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/managedstruct.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/managedstruct.rb new file mode 100644 index 0000000..b5ec8a3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/managedstruct.rb @@ -0,0 +1,84 @@ +# Copyright (C) 2008 Mike Dalessio +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +module FFI + # + # FFI::ManagedStruct allows custom garbage-collection of your FFI::Structs. + # + # The typical use case would be when interacting with a library + # that has a nontrivial memory management design, such as a linked + # list or a binary tree. + # + # When the {Struct} instance is garbage collected, FFI::ManagedStruct will + # invoke the class's release() method during object finalization. + # + # @example Example usage: + # module MyLibrary + # ffi_lib "libmylibrary" + # attach_function :new_dlist, [], :pointer + # attach_function :destroy_dlist, [:pointer], :void + # end + # + # class DoublyLinkedList < FFI::ManagedStruct + # @@@ + # struct do |s| + # s.name 'struct dlist' + # s.include 'dlist.h' + # s.field :head, :pointer + # s.field :tail, :pointer + # end + # @@@ + # + # def self.release ptr + # MyLibrary.destroy_dlist(ptr) + # end + # end + # + # begin + # ptr = DoublyLinkedList.new(MyLibrary.new_dlist) + # # do something with the list + # end + # # struct is out of scope, and will be GC'd using DoublyLinkedList#release + # + # + class ManagedStruct < FFI::Struct + + # @overload initialize(pointer) + # @param [Pointer] pointer + # Create a new ManagedStruct which will invoke the class method #release on + # @overload initialize + # A new instance of FFI::ManagedStruct. + def initialize(pointer=nil) + raise NoMethodError, "release() not implemented for class #{self}" unless self.class.respond_to? :release + raise ArgumentError, "Must supply a pointer to memory for the Struct" unless pointer + super AutoPointer.new(pointer, self.class.method(:release)) + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/memorypointer.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/memorypointer.rb new file mode 100644 index 0000000..9f07bc6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/memorypointer.rb @@ -0,0 +1 @@ +# This class is now implemented in C diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform.rb new file mode 100644 index 0000000..bf01a27 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform.rb @@ -0,0 +1,185 @@ +# +# Copyright (C) 2008, 2009 Wayne Meissner +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# + +require 'rbconfig' +module FFI + class PlatformError < LoadError; end + + # This module defines different constants and class methods to play with + # various platforms. + module Platform + OS = case RbConfig::CONFIG['host_os'].downcase + when /linux/ + "linux" + when /darwin/ + "darwin" + when /freebsd/ + "freebsd" + when /netbsd/ + "netbsd" + when /openbsd/ + "openbsd" + when /dragonfly/ + "dragonflybsd" + when /sunos|solaris/ + "solaris" + when /mingw|mswin/ + "windows" + else + RbConfig::CONFIG['host_os'].downcase + end + + OSVERSION = RbConfig::CONFIG['host_os'].gsub(/[^\d]/, '').to_i + + CPU = RbConfig::CONFIG['host_cpu'] + + ARCH = case CPU.downcase + when /amd64|x86_64|x64/ + "x86_64" + when /i\d86|x86|i86pc/ + "i386" + when /ppc64|powerpc64/ + "powerpc64" + when /ppc|powerpc/ + "powerpc" + when /sparcv9|sparc64/ + "sparcv9" + when /arm64|aarch64/ # MacOS calls it "arm64", other operating systems "aarch64" + "aarch64" + when /^arm/ + if OS == "darwin" # Ruby before 3.0 reports "arm" instead of "arm64" as host_cpu on darwin + "aarch64" + else + "arm" + end + else + RbConfig::CONFIG['host_cpu'] + end + + private + # @param [String) os + # @return [Boolean] + # Test if current OS is +os+. + def self.is_os(os) + OS == os + end + + IS_GNU = defined?(GNU_LIBC) + IS_LINUX = is_os("linux") + IS_MAC = is_os("darwin") + IS_FREEBSD = is_os("freebsd") + IS_NETBSD = is_os("netbsd") + IS_OPENBSD = is_os("openbsd") + IS_DRAGONFLYBSD = is_os("dragonfly") + IS_SOLARIS = is_os("solaris") + IS_WINDOWS = is_os("windows") + IS_BSD = IS_MAC || IS_FREEBSD || IS_NETBSD || IS_OPENBSD || IS_DRAGONFLYBSD + + # Add the version for known ABI breaks + name_version = "12" if IS_FREEBSD && OSVERSION >= 12 # 64-bit inodes + + NAME = "#{ARCH}-#{OS}#{name_version}" + CONF_DIR = File.join(File.dirname(__FILE__), 'platform', NAME) + + public + + LIBPREFIX = case OS + when /windows|msys/ + '' + when /cygwin/ + 'cyg' + else + 'lib' + end + + LIBSUFFIX = case OS + when /darwin/ + 'dylib' + when /linux|bsd|solaris/ + 'so' + when /windows|cygwin|msys/ + 'dll' + else + # Punt and just assume a sane unix (i.e. anything but AIX) + 'so' + end + + LIBC = if IS_WINDOWS + crtname = RbConfig::CONFIG["RUBY_SO_NAME"][/msvc\w+/] || 'ucrtbase' + "#{crtname}.dll" + elsif IS_GNU + GNU_LIBC + elsif OS == 'cygwin' + "cygwin1.dll" + elsif OS == 'msys' + # Not sure how msys 1.0 behaves, tested on MSYS2. + "msys-2.0.dll" + else + "#{LIBPREFIX}c.#{LIBSUFFIX}" + end + + LITTLE_ENDIAN = 1234 unless defined?(LITTLE_ENDIAN) + BIG_ENDIAN = 4321 unless defined?(BIG_ENDIAN) + unless defined?(BYTE_ORDER) + BYTE_ORDER = [0x12345678].pack("I") == [0x12345678].pack("N") ? BIG_ENDIAN : LITTLE_ENDIAN + end + + # Test if current OS is a *BSD (include MAC) + # @return [Boolean] + def self.bsd? + IS_BSD + end + + # Test if current OS is Windows + # @return [Boolean] + def self.windows? + IS_WINDOWS + end + + # Test if current OS is Mac OS + # @return [Boolean] + def self.mac? + IS_MAC + end + + # Test if current OS is Solaris (Sun OS) + # @return [Boolean] + def self.solaris? + IS_SOLARIS + end + + # Test if current OS is a unix OS + # @return [Boolean] + def self.unix? + !IS_WINDOWS + end + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-darwin/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-darwin/types.conf new file mode 100644 index 0000000..68841bb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-darwin/types.conf @@ -0,0 +1,130 @@ +rbx.platform.typedef.__darwin_blkcnt_t = long_long +rbx.platform.typedef.__darwin_blksize_t = int +rbx.platform.typedef.__darwin_clock_t = ulong +rbx.platform.typedef.__darwin_ct_rune_t = int +rbx.platform.typedef.__darwin_dev_t = int +rbx.platform.typedef.__darwin_fsblkcnt_t = uint +rbx.platform.typedef.__darwin_fsfilcnt_t = uint +rbx.platform.typedef.__darwin_gid_t = uint +rbx.platform.typedef.__darwin_id_t = uint +rbx.platform.typedef.__darwin_ino64_t = ulong_long +rbx.platform.typedef.__darwin_ino_t = ulong_long +rbx.platform.typedef.__darwin_intptr_t = long +rbx.platform.typedef.__darwin_mach_port_name_t = uint +rbx.platform.typedef.__darwin_mach_port_t = uint +rbx.platform.typedef.__darwin_mode_t = ushort +rbx.platform.typedef.__darwin_natural_t = uint +rbx.platform.typedef.__darwin_off_t = long_long +rbx.platform.typedef.__darwin_pid_t = int +rbx.platform.typedef.__darwin_pthread_key_t = ulong +rbx.platform.typedef.__darwin_ptrdiff_t = long +rbx.platform.typedef.__darwin_rune_t = int +rbx.platform.typedef.__darwin_sigset_t = uint +rbx.platform.typedef.__darwin_size_t = ulong +rbx.platform.typedef.__darwin_socklen_t = uint +rbx.platform.typedef.__darwin_ssize_t = long +rbx.platform.typedef.__darwin_suseconds_t = int +rbx.platform.typedef.__darwin_time_t = long +rbx.platform.typedef.__darwin_uid_t = uint +rbx.platform.typedef.__darwin_useconds_t = uint +rbx.platform.typedef.__darwin_uuid_string_t[37] = char +rbx.platform.typedef.__darwin_uuid_t[16] = uchar +rbx.platform.typedef.__darwin_wchar_t = int +rbx.platform.typedef.__darwin_wint_t = int +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = ulong +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.errno_t = int +rbx.platform.typedef.fd_mask = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = uint +rbx.platform.typedef.fsfilcnt_t = uint +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino64_t = ulong_long +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = short +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.nlink_t = ushort +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = ulong +rbx.platform.typedef.ptrdiff_t = long +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long_long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.rsize_t = ulong +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.sae_associd_t = uint +rbx.platform.typedef.sae_connid_t = uint +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.syscall_arg_t = ulong_long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = ushort +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.user_addr_t = ulong_long +rbx.platform.typedef.user_long_t = long_long +rbx.platform.typedef.user_off_t = long_long +rbx.platform.typedef.user_size_t = ulong_long +rbx.platform.typedef.user_ssize_t = long_long +rbx.platform.typedef.user_time_t = long_long +rbx.platform.typedef.user_ulong_t = ulong_long +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.wchar_t = int diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-freebsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-freebsd/types.conf new file mode 100644 index 0000000..8d111e0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-freebsd/types.conf @@ -0,0 +1,128 @@ +rbx.platform.typedef.__clock_t = int +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpuid_t = ulong +rbx.platform.typedef.__dev_t = int +rbx.platform.typedef.__fd_mask = int +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__in_addr_t = uint +rbx.platform.typedef.__in_port_t = ushort +rbx.platform.typedef.__ino_t = uint +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__paddr_t = ulong +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__psize_t = ulong +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = long_long +rbx.platform.typedef.__rlim_t = ulong_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = int +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = int +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vaddr_t = ulong +rbx.platform.typedef.__vsize_t = ulong +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wctrans_t = pointer +rbx.platform.typedef.__wctype_t = pointer +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = int +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpuid_t = ulong +rbx.platform.typedef.daddr32_t = int +rbx.platform.typedef.daddr64_t = long_long +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = uint +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.paddr_t = ulong +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.psize_t = ulong +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long_long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.time_t = int +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vaddr_t = ulong +rbx.platform.typedef.vsize_t = ulong diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-freebsd12/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-freebsd12/types.conf new file mode 100644 index 0000000..3ccb8f6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-freebsd12/types.conf @@ -0,0 +1,181 @@ +rbx.platform.typedef.*) = pointer +rbx.platform.typedef.___wchar_t = uint +rbx.platform.typedef.__accmode_t = int +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = int +rbx.platform.typedef.__char16_t = ushort +rbx.platform.typedef.__char32_t = uint +rbx.platform.typedef.__clock_t = int +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpulevel_t = int +rbx.platform.typedef.__cpusetid_t = int +rbx.platform.typedef.__cpuwhich_t = int +rbx.platform.typedef.__critical_t = long +rbx.platform.typedef.__ct_rune_t = int +rbx.platform.typedef.__daddr_t = long +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = ulong +rbx.platform.typedef.__fflags_t = uint +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intfptr_t = long +rbx.platform.typedef.__intmax_t = long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__lwpid_t = int +rbx.platform.typedef.__mode_t = ushort +rbx.platform.typedef.__nl_item = int +rbx.platform.typedef.__nlink_t = ulong +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = long +rbx.platform.typedef.__rlim_t = long +rbx.platform.typedef.__rman_res_t = ulong +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = long +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__u_register_t = ulong +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintfptr_t = ulong +rbx.platform.typedef.__uintmax_t = ulong +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vm_offset_t = ulong +rbx.platform.typedef.__vm_paddr_t = ulong +rbx.platform.typedef.__vm_size_t = ulong +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.accmode_t = int +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.c_caddr_t = pointer +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.cap_ioctl_t = ulong +rbx.platform.typedef.clock_t = int +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpulevel_t = int +rbx.platform.typedef.cpusetid_t = int +rbx.platform.typedef.cpuwhich_t = int +rbx.platform.typedef.critical_t = long +rbx.platform.typedef.daddr_t = long +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = ulong +rbx.platform.typedef.fflags_t = uint +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = long +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = int +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long +rbx.platform.typedef.int_fast8_t = int +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = long +rbx.platform.typedef.kpaddr_t = ulong +rbx.platform.typedef.ksize_t = ulong +rbx.platform.typedef.kssize_t = long +rbx.platform.typedef.kvaddr_t = ulong +rbx.platform.typedef.lwpid_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.off64_t = long +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = int +rbx.platform.typedef.ptrdiff_t = long +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = long +rbx.platform.typedef.rman_res_t = ulong +rbx.platform.typedef.rsize_t = ulong +rbx.platform.typedef.rune_t = int +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.sbintime_t = long +rbx.platform.typedef.segsz_t = long +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_register_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = uint +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong +rbx.platform.typedef.uint_fast8_t = uint +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vm_offset_t = ulong +rbx.platform.typedef.vm_ooffset_t = ulong +rbx.platform.typedef.vm_paddr_t = ulong +rbx.platform.typedef.vm_pindex_t = ulong +rbx.platform.typedef.vm_size_t = ulong +rbx.platform.typedef.wchar_t = uint diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-linux/types.conf new file mode 100644 index 0000000..4cd2438 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-linux/types.conf @@ -0,0 +1,104 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = int +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__fsword_t = long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__syscall_slong_t = long +rbx.platform.typedef.__syscall_ulong_t = ulong +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-openbsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-openbsd/types.conf new file mode 100644 index 0000000..6abc9c0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/aarch64-openbsd/types.conf @@ -0,0 +1,134 @@ +rbx.platform.typedef.__blkcnt_t = long_long +rbx.platform.typedef.__blksize_t = int +rbx.platform.typedef.__clock_t = long_long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpuid_t = ulong +rbx.platform.typedef.__dev_t = int +rbx.platform.typedef.__fd_mask = uint +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__fsblkcnt_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong_long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__in_addr_t = uint +rbx.platform.typedef.__in_port_t = ushort +rbx.platform.typedef.__ino_t = ulong_long +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__paddr_t = ulong +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__psize_t = ulong +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = long +rbx.platform.typedef.__rlim_t = ulong_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = int +rbx.platform.typedef.__time_t = long_long +rbx.platform.typedef.__timer_t = int +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vaddr_t = ulong +rbx.platform.typedef.__vsize_t = ulong +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wctrans_t = pointer +rbx.platform.typedef.__wctype_t = pointer +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = long_long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpuid_t = ulong +rbx.platform.typedef.daddr32_t = int +rbx.platform.typedef.daddr_t = long_long +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.paddr_t = ulong +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.psize_t = ulong +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.sigset_t = uint +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.time_t = long_long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vaddr_t = ulong +rbx.platform.typedef.vsize_t = ulong diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/arm-freebsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/arm-freebsd/types.conf new file mode 100644 index 0000000..cfbb90f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/arm-freebsd/types.conf @@ -0,0 +1,152 @@ + +rbx.platform.typedef.*) = pointer +rbx.platform.typedef.__accmode_t = int +rbx.platform.typedef.__blkcnt_t = long_long +rbx.platform.typedef.__blksize_t = uint +rbx.platform.typedef.__clock_t = ulong +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpulevel_t = int +rbx.platform.typedef.__cpumask_t = uint +rbx.platform.typedef.__cpusetid_t = int +rbx.platform.typedef.__cpuwhich_t = int +rbx.platform.typedef.__critical_t = int +rbx.platform.typedef.__ct_rune_t = int +rbx.platform.typedef.__dev_t = uint +rbx.platform.typedef.__fd_mask = ulong +rbx.platform.typedef.__fflags_t = uint +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__fsblkcnt_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong_long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = long_long +rbx.platform.typedef.__ino_t = uint +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intfptr_t = int +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__lwpid_t = int +rbx.platform.typedef.__mode_t = ushort +rbx.platform.typedef.__nl_item = int +rbx.platform.typedef.__nlink_t = ushort +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__ptrdiff_t = int +rbx.platform.typedef.__register_t = int +rbx.platform.typedef.__rlim_t = long_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = uint +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__time_t = int +rbx.platform.typedef.__u_register_t = uint +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintfptr_t = uint +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = uint +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vm_offset_t = uint +rbx.platform.typedef.__vm_ooffset_t = long_long +rbx.platform.typedef.__vm_paddr_t = uint +rbx.platform.typedef.__vm_pindex_t = ulong_long +rbx.platform.typedef.__vm_size_t = uint +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.accmode_t = int +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = uint +rbx.platform.typedef.c_caddr_t = pointer +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = ulong +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpulevel_t = int +rbx.platform.typedef.cpumask_t = uint +rbx.platform.typedef.cpusetid_t = int +rbx.platform.typedef.cpuwhich_t = int +rbx.platform.typedef.critical_t = int +rbx.platform.typedef.daddr_t = long_long +rbx.platform.typedef.dev_t = uint +rbx.platform.typedef.fd_mask = ulong +rbx.platform.typedef.fflags_t = uint +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = long_long +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = uint +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.intptr_t = int +rbx.platform.typedef.key_t = long +rbx.platform.typedef.lwpid_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.nlink_t = ushort +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = int +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = int +rbx.platform.typedef.rlim_t = long_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_register_t = uint +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uintptr_t = uint +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vm_offset_t = uint +rbx.platform.typedef.vm_ooffset_t = long_long +rbx.platform.typedef.vm_paddr_t = uint +rbx.platform.typedef.vm_pindex_t = ulong_long +rbx.platform.typedef.vm_size_t = uint diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/arm-freebsd12/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/arm-freebsd12/types.conf new file mode 100644 index 0000000..523370d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/arm-freebsd12/types.conf @@ -0,0 +1,152 @@ + +rbx.platform.typedef.*) = pointer +rbx.platform.typedef.__accmode_t = int +rbx.platform.typedef.__blkcnt_t = long_long +rbx.platform.typedef.__blksize_t = uint +rbx.platform.typedef.__clock_t = ulong +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpulevel_t = int +rbx.platform.typedef.__cpumask_t = uint +rbx.platform.typedef.__cpusetid_t = int +rbx.platform.typedef.__cpuwhich_t = int +rbx.platform.typedef.__critical_t = int +rbx.platform.typedef.__ct_rune_t = int +rbx.platform.typedef.__dev_t = ulong_long +rbx.platform.typedef.__fd_mask = ulong +rbx.platform.typedef.__fflags_t = uint +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__fsblkcnt_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong_long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = long_long +rbx.platform.typedef.__ino_t = ulong_long +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intfptr_t = int +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__lwpid_t = int +rbx.platform.typedef.__mode_t = ushort +rbx.platform.typedef.__nl_item = int +rbx.platform.typedef.__nlink_t = ulong_long +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__ptrdiff_t = int +rbx.platform.typedef.__register_t = int +rbx.platform.typedef.__rlim_t = long_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = uint +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__time_t = int +rbx.platform.typedef.__u_register_t = uint +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintfptr_t = uint +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = uint +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vm_offset_t = uint +rbx.platform.typedef.__vm_ooffset_t = long_long +rbx.platform.typedef.__vm_paddr_t = uint +rbx.platform.typedef.__vm_pindex_t = ulong_long +rbx.platform.typedef.__vm_size_t = uint +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.accmode_t = int +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = uint +rbx.platform.typedef.c_caddr_t = pointer +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = ulong +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpulevel_t = int +rbx.platform.typedef.cpumask_t = uint +rbx.platform.typedef.cpusetid_t = int +rbx.platform.typedef.cpuwhich_t = int +rbx.platform.typedef.critical_t = int +rbx.platform.typedef.daddr_t = long_long +rbx.platform.typedef.dev_t = ulong_long +rbx.platform.typedef.fd_mask = ulong +rbx.platform.typedef.fflags_t = uint +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = long_long +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.intptr_t = int +rbx.platform.typedef.key_t = long +rbx.platform.typedef.lwpid_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.nlink_t = ulong_long +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = int +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = int +rbx.platform.typedef.rlim_t = long_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_register_t = uint +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uintptr_t = uint +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vm_offset_t = uint +rbx.platform.typedef.vm_ooffset_t = long_long +rbx.platform.typedef.vm_paddr_t = uint +rbx.platform.typedef.vm_pindex_t = ulong_long +rbx.platform.typedef.vm_size_t = uint diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/arm-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/arm-linux/types.conf new file mode 100644 index 0000000..a070d39 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/arm-linux/types.conf @@ -0,0 +1,132 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.__blkcnt64_t = long_long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong_long +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong_long +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__fsword_t = int +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong_long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long_long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long_long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long_long +rbx.platform.typedef.__rlim64_t = ulong_long +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__syscall_slong_t = long +rbx.platform.typedef.__syscall_ulong_t = ulong +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong_long +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong_long +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = int +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long_long +rbx.platform.typedef.intptr_t = int +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long_long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.ptrdiff_t = int +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = uint +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong_long +rbx.platform.typedef.uintptr_t = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.wchar_t = uint diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-cygwin/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-cygwin/types.conf new file mode 100644 index 0000000..93f6b86 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-cygwin/types.conf @@ -0,0 +1,3 @@ +rbx.platform.typedef.ptrdiff_t = int +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.ssize_t = int diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-darwin/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-darwin/types.conf new file mode 100644 index 0000000..ae100f4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-darwin/types.conf @@ -0,0 +1,100 @@ +rbx.platform.typedef.__darwin_blkcnt_t = long_long +rbx.platform.typedef.__darwin_blksize_t = int +rbx.platform.typedef.__darwin_clock_t = ulong +rbx.platform.typedef.__darwin_ct_rune_t = int +rbx.platform.typedef.__darwin_dev_t = int +rbx.platform.typedef.__darwin_fsblkcnt_t = uint +rbx.platform.typedef.__darwin_fsfilcnt_t = uint +rbx.platform.typedef.__darwin_gid_t = uint +rbx.platform.typedef.__darwin_id_t = uint +rbx.platform.typedef.__darwin_ino64_t = ulong_long +rbx.platform.typedef.__darwin_ino_t = ulong_long +rbx.platform.typedef.__darwin_intptr_t = long +rbx.platform.typedef.__darwin_mach_port_name_t = uint +rbx.platform.typedef.__darwin_mach_port_t = uint +rbx.platform.typedef.__darwin_mode_t = ushort +rbx.platform.typedef.__darwin_natural_t = uint +rbx.platform.typedef.__darwin_off_t = long_long +rbx.platform.typedef.__darwin_pid_t = int +rbx.platform.typedef.__darwin_pthread_key_t = ulong +rbx.platform.typedef.__darwin_ptrdiff_t = int +rbx.platform.typedef.__darwin_rune_t = int +rbx.platform.typedef.__darwin_sigset_t = uint +rbx.platform.typedef.__darwin_size_t = ulong +rbx.platform.typedef.__darwin_socklen_t = uint +rbx.platform.typedef.__darwin_ssize_t = long +rbx.platform.typedef.__darwin_suseconds_t = int +rbx.platform.typedef.__darwin_time_t = long +rbx.platform.typedef.__darwin_uid_t = uint +rbx.platform.typedef.__darwin_useconds_t = uint +rbx.platform.typedef.__darwin_uuid_t[16] = uchar +rbx.platform.typedef.__darwin_wchar_t = int +rbx.platform.typedef.__darwin_wint_t = int +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = ulong +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fd_mask = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = uint +rbx.platform.typedef.fsfilcnt_t = uint +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino64_t = ulong_long +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.nlink_t = ushort +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = ulong +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = int +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.syscall_arg_t = ulong_long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.user_addr_t = ulong_long +rbx.platform.typedef.user_long_t = long_long +rbx.platform.typedef.user_size_t = ulong_long +rbx.platform.typedef.user_ssize_t = long_long +rbx.platform.typedef.user_time_t = long_long +rbx.platform.typedef.user_ulong_t = ulong_long +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-freebsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-freebsd/types.conf new file mode 100644 index 0000000..6c882d4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-freebsd/types.conf @@ -0,0 +1,152 @@ + +rbx.platform.typedef.*) = pointer +rbx.platform.typedef.__accmode_t = int +rbx.platform.typedef.__blkcnt_t = long_long +rbx.platform.typedef.__blksize_t = uint +rbx.platform.typedef.__clock_t = ulong +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpulevel_t = int +rbx.platform.typedef.__cpumask_t = uint +rbx.platform.typedef.__cpusetid_t = int +rbx.platform.typedef.__cpuwhich_t = int +rbx.platform.typedef.__critical_t = int +rbx.platform.typedef.__ct_rune_t = int +rbx.platform.typedef.__dev_t = uint +rbx.platform.typedef.__fd_mask = ulong +rbx.platform.typedef.__fflags_t = uint +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__fsblkcnt_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong_long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = long_long +rbx.platform.typedef.__ino_t = uint +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intfptr_t = int +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__lwpid_t = int +rbx.platform.typedef.__mode_t = ushort +rbx.platform.typedef.__nl_item = int +rbx.platform.typedef.__nlink_t = ushort +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__ptrdiff_t = int +rbx.platform.typedef.__register_t = int +rbx.platform.typedef.__rlim_t = long_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = uint +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__u_register_t = uint +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintfptr_t = uint +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = uint +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vm_offset_t = uint +rbx.platform.typedef.__vm_ooffset_t = long_long +rbx.platform.typedef.__vm_paddr_t = uint +rbx.platform.typedef.__vm_pindex_t = ulong_long +rbx.platform.typedef.__vm_size_t = uint +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.accmode_t = int +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = uint +rbx.platform.typedef.c_caddr_t = pointer +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = ulong +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpulevel_t = int +rbx.platform.typedef.cpumask_t = uint +rbx.platform.typedef.cpusetid_t = int +rbx.platform.typedef.cpuwhich_t = int +rbx.platform.typedef.critical_t = int +rbx.platform.typedef.daddr_t = long_long +rbx.platform.typedef.dev_t = uint +rbx.platform.typedef.fd_mask = ulong +rbx.platform.typedef.fflags_t = uint +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = long_long +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = uint +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.intptr_t = int +rbx.platform.typedef.key_t = long +rbx.platform.typedef.lwpid_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.nlink_t = ushort +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = int +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = int +rbx.platform.typedef.rlim_t = long_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_register_t = uint +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uintptr_t = uint +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vm_offset_t = uint +rbx.platform.typedef.vm_ooffset_t = long_long +rbx.platform.typedef.vm_paddr_t = uint +rbx.platform.typedef.vm_pindex_t = ulong_long +rbx.platform.typedef.vm_size_t = uint diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-freebsd12/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-freebsd12/types.conf new file mode 100644 index 0000000..523370d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-freebsd12/types.conf @@ -0,0 +1,152 @@ + +rbx.platform.typedef.*) = pointer +rbx.platform.typedef.__accmode_t = int +rbx.platform.typedef.__blkcnt_t = long_long +rbx.platform.typedef.__blksize_t = uint +rbx.platform.typedef.__clock_t = ulong +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpulevel_t = int +rbx.platform.typedef.__cpumask_t = uint +rbx.platform.typedef.__cpusetid_t = int +rbx.platform.typedef.__cpuwhich_t = int +rbx.platform.typedef.__critical_t = int +rbx.platform.typedef.__ct_rune_t = int +rbx.platform.typedef.__dev_t = ulong_long +rbx.platform.typedef.__fd_mask = ulong +rbx.platform.typedef.__fflags_t = uint +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__fsblkcnt_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong_long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = long_long +rbx.platform.typedef.__ino_t = ulong_long +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intfptr_t = int +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__lwpid_t = int +rbx.platform.typedef.__mode_t = ushort +rbx.platform.typedef.__nl_item = int +rbx.platform.typedef.__nlink_t = ulong_long +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__ptrdiff_t = int +rbx.platform.typedef.__register_t = int +rbx.platform.typedef.__rlim_t = long_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = uint +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__time_t = int +rbx.platform.typedef.__u_register_t = uint +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintfptr_t = uint +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = uint +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vm_offset_t = uint +rbx.platform.typedef.__vm_ooffset_t = long_long +rbx.platform.typedef.__vm_paddr_t = uint +rbx.platform.typedef.__vm_pindex_t = ulong_long +rbx.platform.typedef.__vm_size_t = uint +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.accmode_t = int +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = uint +rbx.platform.typedef.c_caddr_t = pointer +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = ulong +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpulevel_t = int +rbx.platform.typedef.cpumask_t = uint +rbx.platform.typedef.cpusetid_t = int +rbx.platform.typedef.cpuwhich_t = int +rbx.platform.typedef.critical_t = int +rbx.platform.typedef.daddr_t = long_long +rbx.platform.typedef.dev_t = ulong_long +rbx.platform.typedef.fd_mask = ulong +rbx.platform.typedef.fflags_t = uint +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = long_long +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.intptr_t = int +rbx.platform.typedef.key_t = long +rbx.platform.typedef.lwpid_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.nlink_t = ulong_long +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = int +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = int +rbx.platform.typedef.rlim_t = long_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_register_t = uint +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uintptr_t = uint +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vm_offset_t = uint +rbx.platform.typedef.vm_ooffset_t = long_long +rbx.platform.typedef.vm_paddr_t = uint +rbx.platform.typedef.vm_pindex_t = ulong_long +rbx.platform.typedef.vm_size_t = uint diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-gnu/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-gnu/types.conf new file mode 100644 index 0000000..fa2fa8c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-gnu/types.conf @@ -0,0 +1,107 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long_long +rbx.platform.typedef.__blkcnt64_t = long_long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = uint +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong_long +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__fsid_t = ulong_long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong_long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long_long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long_long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__pthread_key = int +rbx.platform.typedef.__pthread_t = int +rbx.platform.typedef.__quad_t = long_long +rbx.platform.typedef.__rlim64_t = ulong_long +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__sigset_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = int +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong_long +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = uint +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.fsid_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long_long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = int +rbx.platform.typedef.pthread_t = int +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.sigset_t = ulong +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-linux/types.conf new file mode 100644 index 0000000..feb6bc4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-linux/types.conf @@ -0,0 +1,103 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long_long +rbx.platform.typedef.__blkcnt64_t = long_long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong_long +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong_long +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong_long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long_long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long_long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long_long +rbx.platform.typedef.__rlim64_t = ulong_long +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong_long +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong_long +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long_long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-netbsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-netbsd/types.conf new file mode 100644 index 0000000..a5aba89 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-netbsd/types.conf @@ -0,0 +1,126 @@ +rbx.platform.typedef.__clock_t = int +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpuid_t = ulong +rbx.platform.typedef.__dev_t = int +rbx.platform.typedef.__fd_mask = int +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__in_addr_t = uint +rbx.platform.typedef.__in_port_t = ushort +rbx.platform.typedef.__ino_t = uint +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__paddr_t = ulong +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__psize_t = ulong +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = int +rbx.platform.typedef.__rlim_t = ulong_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = int +rbx.platform.typedef.__swblk_t = int +rbx.platform.typedef.__time_t = int +rbx.platform.typedef.__timer_t = int +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vaddr_t = ulong +rbx.platform.typedef.__vsize_t = ulong +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wctrans_t = pointer +rbx.platform.typedef.__wctype_t = pointer +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = int +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpuid_t = ulong +rbx.platform.typedef.daddr32_t = int +rbx.platform.typedef.daddr64_t = long_long +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = uint +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.paddr_t = ulong +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.psize_t = ulong +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = int +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.time_t = int +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vaddr_t = ulong +rbx.platform.typedef.vsize_t = ulong diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-openbsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-openbsd/types.conf new file mode 100644 index 0000000..15a0d61 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-openbsd/types.conf @@ -0,0 +1,128 @@ +rbx.platform.typedef.__clock_t = int +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpuid_t = ulong +rbx.platform.typedef.__dev_t = int +rbx.platform.typedef.__fd_mask = int +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__in_addr_t = uint +rbx.platform.typedef.__in_port_t = ushort +rbx.platform.typedef.__ino_t = uint +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__paddr_t = ulong +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__psize_t = ulong +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = int +rbx.platform.typedef.__rlim_t = ulong_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = int +rbx.platform.typedef.__swblk_t = int +rbx.platform.typedef.__time_t = int +rbx.platform.typedef.__timer_t = int +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vaddr_t = ulong +rbx.platform.typedef.__vsize_t = ulong +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wctrans_t = pointer +rbx.platform.typedef.__wctype_t = pointer +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = int +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpuid_t = ulong +rbx.platform.typedef.daddr32_t = int +rbx.platform.typedef.daddr64_t = long_long +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = uint +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.paddr_t = ulong +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.psize_t = ulong +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = int +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.time_t = int +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vaddr_t = ulong +rbx.platform.typedef.vsize_t = ulong diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-solaris/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-solaris/types.conf new file mode 100644 index 0000000..22a2414 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-solaris/types.conf @@ -0,0 +1,122 @@ +rbx.platform.typedef.*caddr_t = char +rbx.platform.typedef.blkcnt64_t = long_long +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cnt_t = short +rbx.platform.typedef.cpu_flag_t = ushort +rbx.platform.typedef.ctid_t = long +rbx.platform.typedef.daddr_t = long +rbx.platform.typedef.datalink_id_t = uint +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.diskaddr_t = ulong_long +rbx.platform.typedef.disp_lock_t = uchar +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fds_mask = long +rbx.platform.typedef.fsblkcnt64_t = ulong_long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt64_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.hrtime_t = long_long +rbx.platform.typedef.id_t = long +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.index_t = short +rbx.platform.typedef.ino64_t = ulong_long +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = int +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long_long +rbx.platform.typedef.intptr_t = int +rbx.platform.typedef.ipaddr_t = uint +rbx.platform.typedef.k_fltset_t = uint +rbx.platform.typedef.key_t = int +rbx.platform.typedef.len_t = ulong_long +rbx.platform.typedef.lgrp_id_t = long +rbx.platform.typedef.lock_t = uchar +rbx.platform.typedef.longlong_t = long_long +rbx.platform.typedef.major_t = ulong +rbx.platform.typedef.minor_t = ulong +rbx.platform.typedef.mode_t = ulong +rbx.platform.typedef.model_t = uint +rbx.platform.typedef.nfds_t = ulong +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.o_dev_t = short +rbx.platform.typedef.o_gid_t = ushort +rbx.platform.typedef.o_ino_t = ushort +rbx.platform.typedef.o_mode_t = ushort +rbx.platform.typedef.o_nlink_t = short +rbx.platform.typedef.o_pid_t = short +rbx.platform.typedef.o_uid_t = ushort +rbx.platform.typedef.off64_t = long_long +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.offset_t = long_long +rbx.platform.typedef.pad64_t = long_long +rbx.platform.typedef.pfn_t = ulong +rbx.platform.typedef.pgcnt_t = ulong +rbx.platform.typedef.pid_t = long +rbx.platform.typedef.poolid_t = long +rbx.platform.typedef.pri_t = short +rbx.platform.typedef.projid_t = long +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_t = uint +rbx.platform.typedef.ptrdiff_t = int +rbx.platform.typedef.rlim64_t = ulong_long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.spgcnt_t = long +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.sysid_t = short +rbx.platform.typedef.t_scalar_t = long +rbx.platform.typedef.t_uscalar_t = ulong +rbx.platform.typedef.taskid_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_longlong_t = ulong_long +rbx.platform.typedef.u_offset_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uchar_t = uchar +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = uint +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uint_t = uint +rbx.platform.typedef.uintmax_t = ulong_long +rbx.platform.typedef.uintptr_t = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ulong_t = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.upad64_t = ulong_long +rbx.platform.typedef.use_t = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.ushort_t = ushort +rbx.platform.typedef.zoneid_t = long diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-windows/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-windows/types.conf new file mode 100644 index 0000000..a5d0b05 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/i386-windows/types.conf @@ -0,0 +1,52 @@ +rbx.platform.typedef.__time32_t = long +rbx.platform.typedef.__time64_t = long_long +rbx.platform.typedef._dev_t = uint +rbx.platform.typedef._ino_t = ushort +rbx.platform.typedef._mode_t = ushort +rbx.platform.typedef._off64_t = long_long +rbx.platform.typedef._off_t = long +rbx.platform.typedef._pid_t = int +rbx.platform.typedef._sigset_t = ulong +rbx.platform.typedef.dev_t = uint +rbx.platform.typedef.errno_t = int +rbx.platform.typedef.ino_t = ushort +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = short +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long_long +rbx.platform.typedef.intptr_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.off32_t = long +rbx.platform.typedef.off64_t = long_long +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.ptrdiff_t = int +rbx.platform.typedef.rsize_t = uint +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.time_t = long +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = ushort +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong_long +rbx.platform.typedef.uintptr_t = uint +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.wchar_t = ushort +rbx.platform.typedef.wctype_t = ushort +rbx.platform.typedef.wint_t = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/ia64-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/ia64-linux/types.conf new file mode 100644 index 0000000..e0eeecc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/ia64-linux/types.conf @@ -0,0 +1,104 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__in_addr_t = uint +rbx.platform.typedef.__in_port_t = ushort +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = ulong +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mips-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mips-linux/types.conf new file mode 100644 index 0000000..24e8202 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mips-linux/types.conf @@ -0,0 +1,102 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long_long +rbx.platform.typedef.__blkcnt64_t = long_long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong_long +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong_long +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong_long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long_long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long_long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long_long +rbx.platform.typedef.__rlim64_t = ulong_long +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong_long +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong_long +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long_long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mips64-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mips64-linux/types.conf new file mode 100644 index 0000000..b61f4f7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mips64-linux/types.conf @@ -0,0 +1,104 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__fsword_t = long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = ulong +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__syscall_slong_t = long +rbx.platform.typedef.__syscall_ulong_t = ulong +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mips64el-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mips64el-linux/types.conf new file mode 100644 index 0000000..b61f4f7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mips64el-linux/types.conf @@ -0,0 +1,104 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__fsword_t = long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = ulong +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__syscall_slong_t = long +rbx.platform.typedef.__syscall_ulong_t = ulong +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsel-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsel-linux/types.conf new file mode 100644 index 0000000..24e8202 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsel-linux/types.conf @@ -0,0 +1,102 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long_long +rbx.platform.typedef.__blkcnt64_t = long_long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong_long +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong_long +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong_long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long_long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long_long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long_long +rbx.platform.typedef.__rlim64_t = ulong_long +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong_long +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong_long +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long_long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa32r6-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa32r6-linux/types.conf new file mode 100644 index 0000000..24e8202 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa32r6-linux/types.conf @@ -0,0 +1,102 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long_long +rbx.platform.typedef.__blkcnt64_t = long_long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong_long +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong_long +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong_long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long_long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long_long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long_long +rbx.platform.typedef.__rlim64_t = ulong_long +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong_long +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong_long +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long_long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa32r6el-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa32r6el-linux/types.conf new file mode 100644 index 0000000..24e8202 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa32r6el-linux/types.conf @@ -0,0 +1,102 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long_long +rbx.platform.typedef.__blkcnt64_t = long_long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong_long +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong_long +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong_long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long_long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long_long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long_long +rbx.platform.typedef.__rlim64_t = ulong_long +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong_long +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong_long +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long_long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa64r6-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa64r6-linux/types.conf new file mode 100644 index 0000000..b61f4f7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa64r6-linux/types.conf @@ -0,0 +1,104 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__fsword_t = long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = ulong +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__syscall_slong_t = long +rbx.platform.typedef.__syscall_ulong_t = ulong +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa64r6el-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa64r6el-linux/types.conf new file mode 100644 index 0000000..b61f4f7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/mipsisa64r6el-linux/types.conf @@ -0,0 +1,104 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__fsword_t = long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = ulong +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__syscall_slong_t = long +rbx.platform.typedef.__syscall_ulong_t = ulong +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-aix/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-aix/types.conf new file mode 100644 index 0000000..cbd20e7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-aix/types.conf @@ -0,0 +1,180 @@ +rbx.platform.typedef.UTF32Char = uint +rbx.platform.typedef.UniChar = ushort +rbx.platform.typedef.__cptr32 = string +rbx.platform.typedef.__cptr64 = ulong_long +rbx.platform.typedef.__long32_t = long +rbx.platform.typedef.__long64_t = int +rbx.platform.typedef.__ptr32 = pointer +rbx.platform.typedef.__ptr64 = ulong_long +rbx.platform.typedef.__ulong32_t = ulong +rbx.platform.typedef.__ulong64_t = uint +rbx.platform.typedef.aptx_t = ushort +rbx.platform.typedef.blkcnt32_t = int +rbx.platform.typedef.blkcnt64_t = ulong_long +rbx.platform.typedef.blkcnt_t = int +rbx.platform.typedef.blksize32_t = int +rbx.platform.typedef.blksize64_t = ulong_long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.boolean_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.chan_t = int +rbx.platform.typedef.class_id_t = uint +rbx.platform.typedef.clock_t = int +rbx.platform.typedef.clockid_t = long_long +rbx.platform.typedef.cnt64_t = long_long +rbx.platform.typedef.cnt_t = short +rbx.platform.typedef.crid_t = int +rbx.platform.typedef.daddr32_t = int +rbx.platform.typedef.daddr64_t = long_long +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev32_t = uint +rbx.platform.typedef.dev64_t = ulong_long +rbx.platform.typedef.dev_t = uint +rbx.platform.typedef.esid_t = uint +rbx.platform.typedef.ext_t = int +rbx.platform.typedef.fpos64_t = long_long +rbx.platform.typedef.fpos_t = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino32_t = uint +rbx.platform.typedef.ino64_t = ulong_long +rbx.platform.typedef.ino_t = uint +rbx.platform.typedef.int16 = short +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32 = int +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int32long64_t = int +rbx.platform.typedef.int64 = long_long +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8 = char +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = short +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intfast_t = int +rbx.platform.typedef.intmax_t = long_long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = int +rbx.platform.typedef.krpn_t = int +rbx.platform.typedef.kvmhandle_t = ulong +rbx.platform.typedef.kvmid_t = long +rbx.platform.typedef.kvpn_t = int +rbx.platform.typedef.level_t = int +rbx.platform.typedef.liobn_t = uint +rbx.platform.typedef.long32int64_t = long +rbx.platform.typedef.longlong_t = long_long +rbx.platform.typedef.mid_t = pointer +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.mtyp_t = long +rbx.platform.typedef.nlink_t = short +rbx.platform.typedef.off64_t = long_long +rbx.platform.typedef.off_t = long +rbx.platform.typedef.offset_t = long_long +rbx.platform.typedef.paddr_t = long +rbx.platform.typedef.pdtx_t = int +rbx.platform.typedef.pid32_t = int +rbx.platform.typedef.pid64_t = ulong_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pshift_t = ushort +rbx.platform.typedef.psize_t = long_long +rbx.platform.typedef.psx_t = short +rbx.platform.typedef.ptex_t = ulong +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_t = uint +rbx.platform.typedef.ptrdiff_t = long +rbx.platform.typedef.rlim64_t = ulong_long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.rpn64_t = long_long +rbx.platform.typedef.rpn_t = int +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.signal_t = int +rbx.platform.typedef.size64_t = ulong_long +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.slab_t[12] = char +rbx.platform.typedef.snidx_t = int +rbx.platform.typedef.socklen_t = ulong +rbx.platform.typedef.soff_t = int +rbx.platform.typedef.sshift_t = ushort +rbx.platform.typedef.ssize64_t = long_long +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.swhatx_t = ulong +rbx.platform.typedef.tid32_t = int +rbx.platform.typedef.tid64_t = ulong_long +rbx.platform.typedef.tid_t = int +rbx.platform.typedef.time32_t = int +rbx.platform.typedef.time64_t = long_long +rbx.platform.typedef.time_t = int +rbx.platform.typedef.timer32_t = int +rbx.platform.typedef.timer64_t = long_long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16 = ushort +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32 = uint +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64 = ulong_long +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8 = uchar +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_longlong_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uchar = uchar +rbx.platform.typedef.uchar_t = uchar +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint32long64_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = ushort +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uint_t = uint +rbx.platform.typedef.uintfast_t = uint +rbx.platform.typedef.uintmax_t = ulong_long +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ulong32int64_t = ulong +rbx.platform.typedef.ulong_t = ulong +rbx.platform.typedef.unidx_t = int +rbx.platform.typedef.unit_addr_t = ulong_long +rbx.platform.typedef.ureg_t = ulong +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.ushort_t = ushort +rbx.platform.typedef.va_list = string +rbx.platform.typedef.vmfkey_t = uint +rbx.platform.typedef.vmhandle32_t = uint +rbx.platform.typedef.vmhandle_t = ulong +rbx.platform.typedef.vmhwkey_t = int +rbx.platform.typedef.vmid32_t = int +rbx.platform.typedef.vmid64_t = long_long +rbx.platform.typedef.vmid_t = long +rbx.platform.typedef.vmidx_t = int +rbx.platform.typedef.vmkey_t = int +rbx.platform.typedef.vmlpghandle_t = ulong +rbx.platform.typedef.vmm_lock_t = int +rbx.platform.typedef.vmnodeidx_t = int +rbx.platform.typedef.vmprkey_t = uint +rbx.platform.typedef.vmsize_t = int +rbx.platform.typedef.vpn_t = int +rbx.platform.typedef.wchar_t = ushort +rbx.platform.typedef.wctype_t = uint +rbx.platform.typedef.wint_t = int diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-darwin/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-darwin/types.conf new file mode 100644 index 0000000..ae100f4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-darwin/types.conf @@ -0,0 +1,100 @@ +rbx.platform.typedef.__darwin_blkcnt_t = long_long +rbx.platform.typedef.__darwin_blksize_t = int +rbx.platform.typedef.__darwin_clock_t = ulong +rbx.platform.typedef.__darwin_ct_rune_t = int +rbx.platform.typedef.__darwin_dev_t = int +rbx.platform.typedef.__darwin_fsblkcnt_t = uint +rbx.platform.typedef.__darwin_fsfilcnt_t = uint +rbx.platform.typedef.__darwin_gid_t = uint +rbx.platform.typedef.__darwin_id_t = uint +rbx.platform.typedef.__darwin_ino64_t = ulong_long +rbx.platform.typedef.__darwin_ino_t = ulong_long +rbx.platform.typedef.__darwin_intptr_t = long +rbx.platform.typedef.__darwin_mach_port_name_t = uint +rbx.platform.typedef.__darwin_mach_port_t = uint +rbx.platform.typedef.__darwin_mode_t = ushort +rbx.platform.typedef.__darwin_natural_t = uint +rbx.platform.typedef.__darwin_off_t = long_long +rbx.platform.typedef.__darwin_pid_t = int +rbx.platform.typedef.__darwin_pthread_key_t = ulong +rbx.platform.typedef.__darwin_ptrdiff_t = int +rbx.platform.typedef.__darwin_rune_t = int +rbx.platform.typedef.__darwin_sigset_t = uint +rbx.platform.typedef.__darwin_size_t = ulong +rbx.platform.typedef.__darwin_socklen_t = uint +rbx.platform.typedef.__darwin_ssize_t = long +rbx.platform.typedef.__darwin_suseconds_t = int +rbx.platform.typedef.__darwin_time_t = long +rbx.platform.typedef.__darwin_uid_t = uint +rbx.platform.typedef.__darwin_useconds_t = uint +rbx.platform.typedef.__darwin_uuid_t[16] = uchar +rbx.platform.typedef.__darwin_wchar_t = int +rbx.platform.typedef.__darwin_wint_t = int +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = ulong +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fd_mask = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = uint +rbx.platform.typedef.fsfilcnt_t = uint +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino64_t = ulong_long +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.nlink_t = ushort +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = ulong +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = int +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.syscall_arg_t = ulong_long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.user_addr_t = ulong_long +rbx.platform.typedef.user_long_t = long_long +rbx.platform.typedef.user_size_t = ulong_long +rbx.platform.typedef.user_ssize_t = long_long +rbx.platform.typedef.user_time_t = long_long +rbx.platform.typedef.user_ulong_t = ulong_long +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-linux/types.conf new file mode 100644 index 0000000..42eec13 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-linux/types.conf @@ -0,0 +1,130 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long_long +rbx.platform.typedef.__blkcnt64_t = long_long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong_long +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong_long +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__fsword_t = int +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong_long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long_long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long_long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long_long +rbx.platform.typedef.__rlim64_t = ulong_long +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__syscall_slong_t = long +rbx.platform.typedef.__syscall_ulong_t = ulong +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong_long +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong_long +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = int +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long_long +rbx.platform.typedef.intptr_t = int +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long_long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.ptrdiff_t = int +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = uint +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong_long +rbx.platform.typedef.uintptr_t = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.wchar_t = long diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-openbsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-openbsd/types.conf new file mode 100644 index 0000000..aea7955 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc-openbsd/types.conf @@ -0,0 +1,156 @@ +rbx.platform.typedef.__blkcnt_t = long_long +rbx.platform.typedef.__blksize_t = int +rbx.platform.typedef.__clock_t = long_long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpuid_t = ulong +rbx.platform.typedef.__dev_t = int +rbx.platform.typedef.__fd_mask = uint +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__fsblkcnt_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong_long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__in_addr_t = uint +rbx.platform.typedef.__in_port_t = ushort +rbx.platform.typedef.__ino_t = ulong_long +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__paddr_t = ulong +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__psize_t = ulong +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = long +rbx.platform.typedef.__rlim_t = ulong_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = int +rbx.platform.typedef.__time_t = long_long +rbx.platform.typedef.__timer_t = int +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vaddr_t = ulong +rbx.platform.typedef.__vsize_t = ulong +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wctrans_t = pointer +rbx.platform.typedef.__wctype_t = pointer +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = long_long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpuid_t = ulong +rbx.platform.typedef.daddr32_t = int +rbx.platform.typedef.daddr_t = long_long +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = int +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = int +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long_long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.paddr_t = ulong +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.psize_t = ulong +rbx.platform.typedef.ptrdiff_t = long +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.sigset_t = uint +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.time_t = long_long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = uint +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uint +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong_long +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vaddr_t = ulong +rbx.platform.typedef.vsize_t = ulong +rbx.platform.typedef.wchar_t = int +rbx.platform.typedef.wint_t = int diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc64-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc64-linux/types.conf new file mode 100644 index 0000000..b61f4f7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc64-linux/types.conf @@ -0,0 +1,104 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__fsword_t = long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = ulong +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__syscall_slong_t = long +rbx.platform.typedef.__syscall_ulong_t = ulong +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc64le-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc64le-linux/types.conf new file mode 100644 index 0000000..9ac9c2e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/powerpc64le-linux/types.conf @@ -0,0 +1,100 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = ulong +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/riscv64-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/riscv64-linux/types.conf new file mode 100644 index 0000000..ede0f98 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/riscv64-linux/types.conf @@ -0,0 +1,104 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = int +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__fsword_t = long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__syscall_slong_t = long +rbx.platform.typedef.__syscall_ulong_t = ulong +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/s390-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/s390-linux/types.conf new file mode 100644 index 0000000..291b032 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/s390-linux/types.conf @@ -0,0 +1,102 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long_long +rbx.platform.typedef.__blkcnt64_t = long_long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong_long +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong_long +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong_long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long_long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long_long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long_long +rbx.platform.typedef.__rlim64_t = ulong_long +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong_long +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong_long +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long_long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/s390x-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/s390x-linux/types.conf new file mode 100644 index 0000000..32a7feb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/s390x-linux/types.conf @@ -0,0 +1,102 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = ulong +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparc-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparc-linux/types.conf new file mode 100644 index 0000000..aea09d3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparc-linux/types.conf @@ -0,0 +1,102 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long_long +rbx.platform.typedef.__blkcnt64_t = long_long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong_long +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong_long +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong_long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = int +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long_long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long_long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long_long +rbx.platform.typedef.__rlim64_t = ulong_long +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = int +rbx.platform.typedef.__suseconds_t = int +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong_long +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong_long +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long_long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparc-solaris/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparc-solaris/types.conf new file mode 100644 index 0000000..a1548e5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparc-solaris/types.conf @@ -0,0 +1,128 @@ +rbx.platform.typedef.() = pointer +rbx.platform.typedef.*caddr_t = char +rbx.platform.typedef.Psocklen_t = pointer +rbx.platform.typedef.avl_index_t = uint +rbx.platform.typedef.blkcnt64_t = long_long +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cnt_t = short +rbx.platform.typedef.cpu_flag_t = ushort +rbx.platform.typedef.ctid_t = long +rbx.platform.typedef.daddr_t = long +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.diskaddr_t = ulong_long +rbx.platform.typedef.disp_lock_t = uchar +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fds_mask = long +rbx.platform.typedef.fsblkcnt64_t = ulong_long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt64_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = long +rbx.platform.typedef.hrtime_t = long_long +rbx.platform.typedef.id_t = long +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.index_t = short +rbx.platform.typedef.ino64_t = ulong_long +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int) = pointer +rbx.platform.typedef.int) = pointer +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = int +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long_long +rbx.platform.typedef.intptr_t = int +rbx.platform.typedef.ipaddr_t = uint +rbx.platform.typedef.k_fltset_t = uint +rbx.platform.typedef.key_t = int +rbx.platform.typedef.kid_t = int +rbx.platform.typedef.len_t = ulong_long +rbx.platform.typedef.lock_t = uchar +rbx.platform.typedef.longlong_t = long_long +rbx.platform.typedef.major_t = ulong +rbx.platform.typedef.minor_t = ulong +rbx.platform.typedef.mode_t = ulong +rbx.platform.typedef.model_t = uint +rbx.platform.typedef.nfds_t = ulong +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.o_dev_t = short +rbx.platform.typedef.o_gid_t = ushort +rbx.platform.typedef.o_ino_t = ushort +rbx.platform.typedef.o_mode_t = ushort +rbx.platform.typedef.o_nlink_t = short +rbx.platform.typedef.o_pid_t = short +rbx.platform.typedef.o_uid_t = ushort +rbx.platform.typedef.off64_t = long_long +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.offset_t = long_long +rbx.platform.typedef.pad64_t = long_long +rbx.platform.typedef.pfn_t = ulong +rbx.platform.typedef.pgcnt_t = ulong +rbx.platform.typedef.pid_t = long +rbx.platform.typedef.poolid_t = long +rbx.platform.typedef.pri_t = short +rbx.platform.typedef.projid_t = long +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_t = uint +rbx.platform.typedef.ptrdiff_t = int +rbx.platform.typedef.rlim64_t = ulong_long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.size_t) = pointer +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.spgcnt_t = long +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.sysid_t = short +rbx.platform.typedef.t_scalar_t = long +rbx.platform.typedef.t_uscalar_t = ulong +rbx.platform.typedef.taskid_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.ts_t = long_long +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_longlong_t = ulong_long +rbx.platform.typedef.u_offset_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uchar_t = uchar +rbx.platform.typedef.uid_t = long +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = uint +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uint_t = uint +rbx.platform.typedef.uintmax_t = ulong_long +rbx.platform.typedef.uintptr_t = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ulong_t = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.upad64_t = ulong_long +rbx.platform.typedef.use_t = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.ushort_t = ushort +rbx.platform.typedef.zoneid_t = long diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparc64-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparc64-linux/types.conf new file mode 100644 index 0000000..7626bfc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparc64-linux/types.conf @@ -0,0 +1,102 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.*__qaddr_t = long +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = int +rbx.platform.typedef.__swblk_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparcv9-openbsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparcv9-openbsd/types.conf new file mode 100644 index 0000000..aea7955 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparcv9-openbsd/types.conf @@ -0,0 +1,156 @@ +rbx.platform.typedef.__blkcnt_t = long_long +rbx.platform.typedef.__blksize_t = int +rbx.platform.typedef.__clock_t = long_long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpuid_t = ulong +rbx.platform.typedef.__dev_t = int +rbx.platform.typedef.__fd_mask = uint +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__fsblkcnt_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong_long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__in_addr_t = uint +rbx.platform.typedef.__in_port_t = ushort +rbx.platform.typedef.__ino_t = ulong_long +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__paddr_t = ulong +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__psize_t = ulong +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = long +rbx.platform.typedef.__rlim_t = ulong_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = int +rbx.platform.typedef.__time_t = long_long +rbx.platform.typedef.__timer_t = int +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vaddr_t = ulong +rbx.platform.typedef.__vsize_t = ulong +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wctrans_t = pointer +rbx.platform.typedef.__wctype_t = pointer +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = long_long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpuid_t = ulong +rbx.platform.typedef.daddr32_t = int +rbx.platform.typedef.daddr_t = long_long +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = int +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = int +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long_long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.paddr_t = ulong +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.psize_t = ulong +rbx.platform.typedef.ptrdiff_t = long +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.sigset_t = uint +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.time_t = long_long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = uint +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uint +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong_long +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vaddr_t = ulong +rbx.platform.typedef.vsize_t = ulong +rbx.platform.typedef.wchar_t = int +rbx.platform.typedef.wint_t = int diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparcv9-solaris/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparcv9-solaris/types.conf new file mode 100644 index 0000000..a1548e5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/sparcv9-solaris/types.conf @@ -0,0 +1,128 @@ +rbx.platform.typedef.() = pointer +rbx.platform.typedef.*caddr_t = char +rbx.platform.typedef.Psocklen_t = pointer +rbx.platform.typedef.avl_index_t = uint +rbx.platform.typedef.blkcnt64_t = long_long +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cnt_t = short +rbx.platform.typedef.cpu_flag_t = ushort +rbx.platform.typedef.ctid_t = long +rbx.platform.typedef.daddr_t = long +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.diskaddr_t = ulong_long +rbx.platform.typedef.disp_lock_t = uchar +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fds_mask = long +rbx.platform.typedef.fsblkcnt64_t = ulong_long +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt64_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = long +rbx.platform.typedef.hrtime_t = long_long +rbx.platform.typedef.id_t = long +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.index_t = short +rbx.platform.typedef.ino64_t = ulong_long +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int) = pointer +rbx.platform.typedef.int) = pointer +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = int +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long_long +rbx.platform.typedef.intptr_t = int +rbx.platform.typedef.ipaddr_t = uint +rbx.platform.typedef.k_fltset_t = uint +rbx.platform.typedef.key_t = int +rbx.platform.typedef.kid_t = int +rbx.platform.typedef.len_t = ulong_long +rbx.platform.typedef.lock_t = uchar +rbx.platform.typedef.longlong_t = long_long +rbx.platform.typedef.major_t = ulong +rbx.platform.typedef.minor_t = ulong +rbx.platform.typedef.mode_t = ulong +rbx.platform.typedef.model_t = uint +rbx.platform.typedef.nfds_t = ulong +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.o_dev_t = short +rbx.platform.typedef.o_gid_t = ushort +rbx.platform.typedef.o_ino_t = ushort +rbx.platform.typedef.o_mode_t = ushort +rbx.platform.typedef.o_nlink_t = short +rbx.platform.typedef.o_pid_t = short +rbx.platform.typedef.o_uid_t = ushort +rbx.platform.typedef.off64_t = long_long +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.offset_t = long_long +rbx.platform.typedef.pad64_t = long_long +rbx.platform.typedef.pfn_t = ulong +rbx.platform.typedef.pgcnt_t = ulong +rbx.platform.typedef.pid_t = long +rbx.platform.typedef.poolid_t = long +rbx.platform.typedef.pri_t = short +rbx.platform.typedef.projid_t = long +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_t = uint +rbx.platform.typedef.ptrdiff_t = int +rbx.platform.typedef.rlim64_t = ulong_long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = uint +rbx.platform.typedef.size_t) = pointer +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.spgcnt_t = long +rbx.platform.typedef.ssize_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.sysid_t = short +rbx.platform.typedef.t_scalar_t = long +rbx.platform.typedef.t_uscalar_t = ulong +rbx.platform.typedef.taskid_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.ts_t = long_long +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_longlong_t = ulong_long +rbx.platform.typedef.u_offset_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uchar_t = uchar +rbx.platform.typedef.uid_t = long +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = uint +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uint_t = uint +rbx.platform.typedef.uintmax_t = ulong_long +rbx.platform.typedef.uintptr_t = uint +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ulong_t = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.upad64_t = ulong_long +rbx.platform.typedef.use_t = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.ushort_t = ushort +rbx.platform.typedef.zoneid_t = long diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-cygwin/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-cygwin/types.conf new file mode 100644 index 0000000..5bef6d7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-cygwin/types.conf @@ -0,0 +1,3 @@ +rbx.platform.typedef.ptrdiff_t = int64 +rbx.platform.typedef.size_t = uint64 +rbx.platform.typedef.ssize_t = int64 diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-darwin/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-darwin/types.conf new file mode 100644 index 0000000..68841bb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-darwin/types.conf @@ -0,0 +1,130 @@ +rbx.platform.typedef.__darwin_blkcnt_t = long_long +rbx.platform.typedef.__darwin_blksize_t = int +rbx.platform.typedef.__darwin_clock_t = ulong +rbx.platform.typedef.__darwin_ct_rune_t = int +rbx.platform.typedef.__darwin_dev_t = int +rbx.platform.typedef.__darwin_fsblkcnt_t = uint +rbx.platform.typedef.__darwin_fsfilcnt_t = uint +rbx.platform.typedef.__darwin_gid_t = uint +rbx.platform.typedef.__darwin_id_t = uint +rbx.platform.typedef.__darwin_ino64_t = ulong_long +rbx.platform.typedef.__darwin_ino_t = ulong_long +rbx.platform.typedef.__darwin_intptr_t = long +rbx.platform.typedef.__darwin_mach_port_name_t = uint +rbx.platform.typedef.__darwin_mach_port_t = uint +rbx.platform.typedef.__darwin_mode_t = ushort +rbx.platform.typedef.__darwin_natural_t = uint +rbx.platform.typedef.__darwin_off_t = long_long +rbx.platform.typedef.__darwin_pid_t = int +rbx.platform.typedef.__darwin_pthread_key_t = ulong +rbx.platform.typedef.__darwin_ptrdiff_t = long +rbx.platform.typedef.__darwin_rune_t = int +rbx.platform.typedef.__darwin_sigset_t = uint +rbx.platform.typedef.__darwin_size_t = ulong +rbx.platform.typedef.__darwin_socklen_t = uint +rbx.platform.typedef.__darwin_ssize_t = long +rbx.platform.typedef.__darwin_suseconds_t = int +rbx.platform.typedef.__darwin_time_t = long +rbx.platform.typedef.__darwin_uid_t = uint +rbx.platform.typedef.__darwin_useconds_t = uint +rbx.platform.typedef.__darwin_uuid_string_t[37] = char +rbx.platform.typedef.__darwin_uuid_t[16] = uchar +rbx.platform.typedef.__darwin_wchar_t = int +rbx.platform.typedef.__darwin_wint_t = int +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = ulong +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.errno_t = int +rbx.platform.typedef.fd_mask = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = uint +rbx.platform.typedef.fsfilcnt_t = uint +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino64_t = ulong_long +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = short +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.nlink_t = ushort +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = ulong +rbx.platform.typedef.ptrdiff_t = long +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long_long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.rsize_t = ulong +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.sae_associd_t = uint +rbx.platform.typedef.sae_connid_t = uint +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.syscall_arg_t = ulong_long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = ushort +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.user_addr_t = ulong_long +rbx.platform.typedef.user_long_t = long_long +rbx.platform.typedef.user_off_t = long_long +rbx.platform.typedef.user_size_t = ulong_long +rbx.platform.typedef.user_ssize_t = long_long +rbx.platform.typedef.user_time_t = long_long +rbx.platform.typedef.user_ulong_t = ulong_long +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.wchar_t = int diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-dragonflybsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-dragonflybsd/types.conf new file mode 100644 index 0000000..889f6a3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-dragonflybsd/types.conf @@ -0,0 +1,130 @@ +rbx.platform.typedef.*) = pointer +rbx.platform.typedef.___wchar_t = int +rbx.platform.typedef.__clock_t = ulong +rbx.platform.typedef.__clockid_t = ulong +rbx.platform.typedef.__fd_mask = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intlp_t = long +rbx.platform.typedef.__intmax_t = long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = long +rbx.platform.typedef.__rlim_t = long +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = int +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintlp_t = ulong +rbx.platform.typedef.__uintmax_t = ulong +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.c_caddr_t = pointer +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = ulong +rbx.platform.typedef.clockid_t = ulong +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = uint +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = long +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = int +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long +rbx.platform.typedef.int_fast8_t = int +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = long +rbx.platform.typedef.lwpid_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = int +rbx.platform.typedef.ptrdiff_t = long +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = long +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_daddr_t = uint +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = uint +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong +rbx.platform.typedef.uint_fast8_t = uint +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.v_caddr_t = pointer +rbx.platform.typedef.wchar_t = int diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-freebsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-freebsd/types.conf new file mode 100644 index 0000000..8dbe370 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-freebsd/types.conf @@ -0,0 +1,128 @@ +rbx.platform.typedef.__clock_t = int +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpuid_t = ulong +rbx.platform.typedef.__dev_t = int +rbx.platform.typedef.__fd_mask = int +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__in_addr_t = uint +rbx.platform.typedef.__in_port_t = ushort +rbx.platform.typedef.__ino_t = uint +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__paddr_t = ulong +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__psize_t = ulong +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = long_long +rbx.platform.typedef.__rlim_t = ulong_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = int +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = int +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vaddr_t = ulong +rbx.platform.typedef.__vsize_t = ulong +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wctrans_t = pointer +rbx.platform.typedef.__wctype_t = pointer +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = int +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpuid_t = ulong +rbx.platform.typedef.daddr32_t = int +rbx.platform.typedef.daddr64_t = long_long +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = uint +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.paddr_t = ulong +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.psize_t = ulong +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long_long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vaddr_t = ulong +rbx.platform.typedef.vsize_t = ulong diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-freebsd12/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-freebsd12/types.conf new file mode 100644 index 0000000..31b1073 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-freebsd12/types.conf @@ -0,0 +1,158 @@ +rbx.platform.typedef.*) = pointer +rbx.platform.typedef.___wchar_t = int +rbx.platform.typedef.__accmode_t = int +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = int +rbx.platform.typedef.__char16_t = ushort +rbx.platform.typedef.__char32_t = uint +rbx.platform.typedef.__clock_t = int +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpulevel_t = int +rbx.platform.typedef.__cpusetid_t = int +rbx.platform.typedef.__cpuwhich_t = int +rbx.platform.typedef.__critical_t = long +rbx.platform.typedef.__ct_rune_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = ulong +rbx.platform.typedef.__fflags_t = uint +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = long +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intfptr_t = long +rbx.platform.typedef.__intmax_t = long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__lwpid_t = int +rbx.platform.typedef.__mode_t = ushort +rbx.platform.typedef.__nl_item = int +rbx.platform.typedef.__nlink_t = ulong +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = long +rbx.platform.typedef.__rlim_t = long +rbx.platform.typedef.__rman_res_t = ulong +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = long +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__u_register_t = ulong +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintfptr_t = ulong +rbx.platform.typedef.__uintmax_t = ulong +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vm_offset_t = ulong +rbx.platform.typedef.__vm_paddr_t = ulong +rbx.platform.typedef.__vm_size_t = ulong +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.accmode_t = int +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.c_caddr_t = pointer +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.cap_ioctl_t = ulong +rbx.platform.typedef.clock_t = int +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpulevel_t = int +rbx.platform.typedef.cpusetid_t = int +rbx.platform.typedef.cpuwhich_t = int +rbx.platform.typedef.critical_t = long +rbx.platform.typedef.daddr_t = long +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = ulong +rbx.platform.typedef.fflags_t = uint +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = long +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.intmax_t = long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = long +rbx.platform.typedef.ksize_t = ulong +rbx.platform.typedef.kvaddr_t = ulong +rbx.platform.typedef.lwpid_t = int +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.off64_t = long +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = int +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = long +rbx.platform.typedef.rman_res_t = ulong +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.sbintime_t = long +rbx.platform.typedef.segsz_t = long +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_register_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uintmax_t = ulong +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vm_offset_t = ulong +rbx.platform.typedef.vm_ooffset_t = long +rbx.platform.typedef.vm_paddr_t = ulong +rbx.platform.typedef.vm_pindex_t = ulong +rbx.platform.typedef.vm_size_t = ulong diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-haiku/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-haiku/types.conf new file mode 100644 index 0000000..d5ddfa7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-haiku/types.conf @@ -0,0 +1,117 @@ +rbx.platform.typedef.__haiku_addr_t = ulong +rbx.platform.typedef.__haiku_generic_addr_t = ulong +rbx.platform.typedef.__haiku_int16 = short +rbx.platform.typedef.__haiku_int32 = int +rbx.platform.typedef.__haiku_int64 = long +rbx.platform.typedef.__haiku_int8 = char +rbx.platform.typedef.__haiku_phys_addr_t = ulong +rbx.platform.typedef.__haiku_phys_saddr_t = long +rbx.platform.typedef.__haiku_saddr_t = long +rbx.platform.typedef.__haiku_std_int16 = short +rbx.platform.typedef.__haiku_std_int32 = int +rbx.platform.typedef.__haiku_std_int64 = long +rbx.platform.typedef.__haiku_std_int8 = char +rbx.platform.typedef.__haiku_std_uint16 = ushort +rbx.platform.typedef.__haiku_std_uint32 = uint +rbx.platform.typedef.__haiku_std_uint64 = ulong +rbx.platform.typedef.__haiku_std_uint8 = uchar +rbx.platform.typedef.__haiku_uint16 = ushort +rbx.platform.typedef.__haiku_uint32 = uint +rbx.platform.typedef.__haiku_uint64 = ulong +rbx.platform.typedef.__haiku_uint8 = uchar +rbx.platform.typedef.addr_t = ulong +rbx.platform.typedef.bigtime_t = long +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.caddr_t = pointer +rbx.platform.typedef.clock_t = int +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cnt_t = int +rbx.platform.typedef.daddr_t = long +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fd_mask = uint +rbx.platform.typedef.fsblkcnt_t = long +rbx.platform.typedef.fsfilcnt_t = long +rbx.platform.typedef.generic_addr_t = ulong +rbx.platform.typedef.generic_size_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = int +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = long +rbx.platform.typedef.int16 = short +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32 = int +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64 = long +rbx.platform.typedef.int64_t = long +rbx.platform.typedef.int8 = char +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = int +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long +rbx.platform.typedef.int_fast8_t = int +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = int +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nanotime_t = long +rbx.platform.typedef.nlink_t = int +rbx.platform.typedef.off_t = long +rbx.platform.typedef.perform_code = uint +rbx.platform.typedef.phys_addr_t = ulong +rbx.platform.typedef.phys_size_t = ulong +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = int +rbx.platform.typedef.ptrdiff_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.sig_atomic_t = int +rbx.platform.typedef.sigset_t = ulong +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.status_t = int +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.time_t = long +rbx.platform.typedef.type_code = uint +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uchar = uchar +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16 = ushort +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32 = uint +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64 = ulong +rbx.platform.typedef.uint64_t = ulong +rbx.platform.typedef.uint8 = uchar +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = uint +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong +rbx.platform.typedef.uint_fast8_t = uint +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.umode_t = uint +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.unichar = ushort +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.void*) = pointer +rbx.platform.typedef.wchar_t = int diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-linux/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-linux/types.conf new file mode 100644 index 0000000..060f161 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-linux/types.conf @@ -0,0 +1,132 @@ +rbx.platform.typedef.*__caddr_t = char +rbx.platform.typedef.__blkcnt64_t = long +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = long +rbx.platform.typedef.__clock_t = long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__daddr_t = int +rbx.platform.typedef.__dev_t = ulong +rbx.platform.typedef.__fd_mask = long +rbx.platform.typedef.__fsblkcnt64_t = ulong +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt64_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__fsword_t = long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino64_t = ulong +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__intmax_t = long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = int +rbx.platform.typedef.__loff_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = ulong +rbx.platform.typedef.__off64_t = long +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__priority_which_t = int +rbx.platform.typedef.__quad_t = long +rbx.platform.typedef.__rlim64_t = ulong +rbx.platform.typedef.__rlim_t = ulong +rbx.platform.typedef.__rlimit_resource_t = int +rbx.platform.typedef.__rusage_who_t = int +rbx.platform.typedef.__sig_atomic_t = int +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__syscall_slong_t = long +rbx.platform.typedef.__syscall_ulong_t = ulong +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = pointer +rbx.platform.typedef.__u_char = uchar +rbx.platform.typedef.__u_int = uint +rbx.platform.typedef.__u_long = ulong +rbx.platform.typedef.__u_quad_t = ulong +rbx.platform.typedef.__u_short = ushort +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = long +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = long +rbx.platform.typedef.int_fast32_t = long +rbx.platform.typedef.int_fast64_t = long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = int +rbx.platform.typedef.loff_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = ulong +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_once_t = int +rbx.platform.typedef.pthread_t = ulong +rbx.platform.typedef.ptrdiff_t = long +rbx.platform.typedef.quad_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = pointer +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = ulong +rbx.platform.typedef.uint_fast32_t = ulong +rbx.platform.typedef.uint_fast64_t = ulong +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.wchar_t = int diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-msys/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-msys/types.conf new file mode 100644 index 0000000..aa827c0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-msys/types.conf @@ -0,0 +1,119 @@ +rbx.platform.typedef.*addr_t = char +rbx.platform.typedef.__ULong = uint +rbx.platform.typedef.__blkcnt_t = long +rbx.platform.typedef.__blksize_t = int +rbx.platform.typedef.__clock_t = ulong +rbx.platform.typedef.__clockid_t = ulong +rbx.platform.typedef.__cpu_mask = ulong +rbx.platform.typedef.__dev_t = uint +rbx.platform.typedef.__fsblkcnt_t = ulong +rbx.platform.typedef.__fsfilcnt_t = ulong +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__ino_t = ulong +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intmax_t = long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long_long +rbx.platform.typedef.__loff_t = long_long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nl_item = int +rbx.platform.typedef.__nlink_t = ushort +rbx.platform.typedef.__off_t = long +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__sigset_t = ulong +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = int +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__time_t = long +rbx.platform.typedef.__timer_t = ulong +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = ulong +rbx.platform.typedef._fpos64_t = long_long +rbx.platform.typedef._fpos_t = long +rbx.platform.typedef._off64_t = long_long +rbx.platform.typedef._off_t = long +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = ulong +rbx.platform.typedef.clockid_t = ulong +rbx.platform.typedef.daddr_t = long +rbx.platform.typedef.dev_t = uint +rbx.platform.typedef.fd_mask = ulong +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = long +rbx.platform.typedef.int_fast32_t = long +rbx.platform.typedef.int_fast64_t = long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = long_long +rbx.platform.typedef.loff_t = long_long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = ushort +rbx.platform.typedef.off_t = long +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.ptrdiff_t = long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sbintime_t = long +rbx.platform.typedef.sig_atomic_t = int +rbx.platform.typedef.sigset_t = ulong +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = int +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = ulong +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_register_t = ulong +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = ulong +rbx.platform.typedef.uint_fast32_t = ulong +rbx.platform.typedef.uint_fast64_t = ulong +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.useconds_t = ulong +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vm_offset_t = ulong +rbx.platform.typedef.vm_size_t = ulong +rbx.platform.typedef.wint_t = uint diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-netbsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-netbsd/types.conf new file mode 100644 index 0000000..15a0d61 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-netbsd/types.conf @@ -0,0 +1,128 @@ +rbx.platform.typedef.__clock_t = int +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpuid_t = ulong +rbx.platform.typedef.__dev_t = int +rbx.platform.typedef.__fd_mask = int +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__in_addr_t = uint +rbx.platform.typedef.__in_port_t = ushort +rbx.platform.typedef.__ino_t = uint +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__paddr_t = ulong +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__psize_t = ulong +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = int +rbx.platform.typedef.__rlim_t = ulong_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = int +rbx.platform.typedef.__swblk_t = int +rbx.platform.typedef.__time_t = int +rbx.platform.typedef.__timer_t = int +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vaddr_t = ulong +rbx.platform.typedef.__vsize_t = ulong +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wctrans_t = pointer +rbx.platform.typedef.__wctype_t = pointer +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = int +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpuid_t = ulong +rbx.platform.typedef.daddr32_t = int +rbx.platform.typedef.daddr64_t = long_long +rbx.platform.typedef.daddr_t = int +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = uint +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.key_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.paddr_t = ulong +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.psize_t = ulong +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = int +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = int +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.time_t = int +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vaddr_t = ulong +rbx.platform.typedef.vsize_t = ulong diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-openbsd/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-openbsd/types.conf new file mode 100644 index 0000000..6abc9c0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-openbsd/types.conf @@ -0,0 +1,134 @@ +rbx.platform.typedef.__blkcnt_t = long_long +rbx.platform.typedef.__blksize_t = int +rbx.platform.typedef.__clock_t = long_long +rbx.platform.typedef.__clockid_t = int +rbx.platform.typedef.__cpuid_t = ulong +rbx.platform.typedef.__dev_t = int +rbx.platform.typedef.__fd_mask = uint +rbx.platform.typedef.__fixpt_t = uint +rbx.platform.typedef.__fsblkcnt_t = ulong_long +rbx.platform.typedef.__fsfilcnt_t = ulong_long +rbx.platform.typedef.__gid_t = uint +rbx.platform.typedef.__id_t = uint +rbx.platform.typedef.__in_addr_t = uint +rbx.platform.typedef.__in_port_t = ushort +rbx.platform.typedef.__ino_t = ulong_long +rbx.platform.typedef.__int16_t = short +rbx.platform.typedef.__int32_t = int +rbx.platform.typedef.__int64_t = long_long +rbx.platform.typedef.__int8_t = char +rbx.platform.typedef.__int_fast16_t = int +rbx.platform.typedef.__int_fast32_t = int +rbx.platform.typedef.__int_fast64_t = long_long +rbx.platform.typedef.__int_fast8_t = int +rbx.platform.typedef.__int_least16_t = short +rbx.platform.typedef.__int_least32_t = int +rbx.platform.typedef.__int_least64_t = long_long +rbx.platform.typedef.__int_least8_t = char +rbx.platform.typedef.__intmax_t = long_long +rbx.platform.typedef.__intptr_t = long +rbx.platform.typedef.__key_t = long +rbx.platform.typedef.__mode_t = uint +rbx.platform.typedef.__nlink_t = uint +rbx.platform.typedef.__off_t = long_long +rbx.platform.typedef.__paddr_t = ulong +rbx.platform.typedef.__pid_t = int +rbx.platform.typedef.__psize_t = ulong +rbx.platform.typedef.__ptrdiff_t = long +rbx.platform.typedef.__register_t = long +rbx.platform.typedef.__rlim_t = ulong_long +rbx.platform.typedef.__rune_t = int +rbx.platform.typedef.__sa_family_t = uchar +rbx.platform.typedef.__segsz_t = int +rbx.platform.typedef.__size_t = ulong +rbx.platform.typedef.__socklen_t = uint +rbx.platform.typedef.__ssize_t = long +rbx.platform.typedef.__suseconds_t = long +rbx.platform.typedef.__swblk_t = int +rbx.platform.typedef.__time_t = long_long +rbx.platform.typedef.__timer_t = int +rbx.platform.typedef.__uid_t = uint +rbx.platform.typedef.__uint16_t = ushort +rbx.platform.typedef.__uint32_t = uint +rbx.platform.typedef.__uint64_t = ulong_long +rbx.platform.typedef.__uint8_t = uchar +rbx.platform.typedef.__uint_fast16_t = uint +rbx.platform.typedef.__uint_fast32_t = uint +rbx.platform.typedef.__uint_fast64_t = ulong_long +rbx.platform.typedef.__uint_fast8_t = uint +rbx.platform.typedef.__uint_least16_t = ushort +rbx.platform.typedef.__uint_least32_t = uint +rbx.platform.typedef.__uint_least64_t = ulong_long +rbx.platform.typedef.__uint_least8_t = uchar +rbx.platform.typedef.__uintmax_t = ulong_long +rbx.platform.typedef.__uintptr_t = ulong +rbx.platform.typedef.__useconds_t = uint +rbx.platform.typedef.__vaddr_t = ulong +rbx.platform.typedef.__vsize_t = ulong +rbx.platform.typedef.__wchar_t = int +rbx.platform.typedef.__wctrans_t = pointer +rbx.platform.typedef.__wctype_t = pointer +rbx.platform.typedef.__wint_t = int +rbx.platform.typedef.blkcnt_t = long_long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.caddr_t = string +rbx.platform.typedef.clock_t = long_long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cpuid_t = ulong +rbx.platform.typedef.daddr32_t = int +rbx.platform.typedef.daddr_t = long_long +rbx.platform.typedef.dev_t = int +rbx.platform.typedef.fixpt_t = uint +rbx.platform.typedef.fsblkcnt_t = ulong_long +rbx.platform.typedef.fsfilcnt_t = ulong_long +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.id_t = uint +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.ino_t = ulong_long +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.key_t = long +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.paddr_t = ulong +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.psize_t = ulong +rbx.platform.typedef.qaddr_t = pointer +rbx.platform.typedef.quad_t = long_long +rbx.platform.typedef.register_t = long +rbx.platform.typedef.rlim_t = ulong_long +rbx.platform.typedef.sa_family_t = uchar +rbx.platform.typedef.segsz_t = int +rbx.platform.typedef.sigset_t = uint +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.swblk_t = int +rbx.platform.typedef.time_t = long_long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_int16_t = ushort +rbx.platform.typedef.u_int32_t = uint +rbx.platform.typedef.u_int64_t = ulong_long +rbx.platform.typedef.u_int8_t = uchar +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_quad_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.vaddr_t = ulong +rbx.platform.typedef.vsize_t = ulong diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-solaris/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-solaris/types.conf new file mode 100644 index 0000000..a7890d1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-solaris/types.conf @@ -0,0 +1,122 @@ +rbx.platform.typedef.*caddr_t = char +rbx.platform.typedef.blkcnt64_t = long +rbx.platform.typedef.blkcnt_t = long +rbx.platform.typedef.blksize_t = int +rbx.platform.typedef.clock_t = long +rbx.platform.typedef.clockid_t = int +rbx.platform.typedef.cnt_t = short +rbx.platform.typedef.cpu_flag_t = ushort +rbx.platform.typedef.ctid_t = int +rbx.platform.typedef.daddr_t = long +rbx.platform.typedef.datalink_id_t = uint +rbx.platform.typedef.dev_t = ulong +rbx.platform.typedef.diskaddr_t = ulong_long +rbx.platform.typedef.disp_lock_t = uchar +rbx.platform.typedef.fd_mask = long +rbx.platform.typedef.fds_mask = long +rbx.platform.typedef.fsblkcnt64_t = ulong +rbx.platform.typedef.fsblkcnt_t = ulong +rbx.platform.typedef.fsfilcnt64_t = ulong +rbx.platform.typedef.fsfilcnt_t = ulong +rbx.platform.typedef.gid_t = uint +rbx.platform.typedef.hrtime_t = long_long +rbx.platform.typedef.id_t = int +rbx.platform.typedef.in_addr_t = uint +rbx.platform.typedef.in_port_t = ushort +rbx.platform.typedef.index_t = short +rbx.platform.typedef.ino64_t = ulong +rbx.platform.typedef.ino_t = ulong +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = int +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long +rbx.platform.typedef.intptr_t = long +rbx.platform.typedef.ipaddr_t = uint +rbx.platform.typedef.k_fltset_t = uint +rbx.platform.typedef.key_t = int +rbx.platform.typedef.len_t = ulong_long +rbx.platform.typedef.lgrp_id_t = int +rbx.platform.typedef.lock_t = uchar +rbx.platform.typedef.longlong_t = long_long +rbx.platform.typedef.major_t = uint +rbx.platform.typedef.minor_t = uint +rbx.platform.typedef.mode_t = uint +rbx.platform.typedef.model_t = uint +rbx.platform.typedef.nfds_t = ulong +rbx.platform.typedef.nlink_t = uint +rbx.platform.typedef.o_dev_t = short +rbx.platform.typedef.o_gid_t = ushort +rbx.platform.typedef.o_ino_t = ushort +rbx.platform.typedef.o_mode_t = ushort +rbx.platform.typedef.o_nlink_t = short +rbx.platform.typedef.o_pid_t = short +rbx.platform.typedef.o_uid_t = ushort +rbx.platform.typedef.off64_t = long +rbx.platform.typedef.off_t = long +rbx.platform.typedef.offset_t = long_long +rbx.platform.typedef.pad64_t = long +rbx.platform.typedef.pfn_t = ulong +rbx.platform.typedef.pgcnt_t = ulong +rbx.platform.typedef.pid_t = int +rbx.platform.typedef.poolid_t = int +rbx.platform.typedef.pri_t = short +rbx.platform.typedef.projid_t = int +rbx.platform.typedef.pthread_key_t = uint +rbx.platform.typedef.pthread_t = uint +rbx.platform.typedef.ptrdiff_t = long +rbx.platform.typedef.rlim64_t = ulong_long +rbx.platform.typedef.rlim_t = ulong +rbx.platform.typedef.sa_family_t = ushort +rbx.platform.typedef.size_t = ulong +rbx.platform.typedef.socklen_t = uint +rbx.platform.typedef.spgcnt_t = long +rbx.platform.typedef.ssize_t = long +rbx.platform.typedef.suseconds_t = long +rbx.platform.typedef.sysid_t = short +rbx.platform.typedef.t_scalar_t = int +rbx.platform.typedef.t_uscalar_t = uint +rbx.platform.typedef.taskid_t = int +rbx.platform.typedef.time_t = long +rbx.platform.typedef.timer_t = int +rbx.platform.typedef.u_char = uchar +rbx.platform.typedef.u_int = uint +rbx.platform.typedef.u_long = ulong +rbx.platform.typedef.u_longlong_t = ulong_long +rbx.platform.typedef.u_offset_t = ulong_long +rbx.platform.typedef.u_short = ushort +rbx.platform.typedef.uchar_t = uchar +rbx.platform.typedef.uid_t = uint +rbx.platform.typedef.uint = uint +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint32_t = uint +rbx.platform.typedef.uint64_t = ulong +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = uint +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least32_t = uint +rbx.platform.typedef.uint_least64_t = ulong +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uint_t = uint +rbx.platform.typedef.uintmax_t = ulong +rbx.platform.typedef.uintptr_t = ulong +rbx.platform.typedef.ulong = ulong +rbx.platform.typedef.ulong_t = ulong +rbx.platform.typedef.unchar = uchar +rbx.platform.typedef.upad64_t = ulong +rbx.platform.typedef.use_t = uchar +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.ushort = ushort +rbx.platform.typedef.ushort_t = ushort +rbx.platform.typedef.zoneid_t = int diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-windows/types.conf b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-windows/types.conf new file mode 100644 index 0000000..5bdbbde --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/platform/x86_64-windows/types.conf @@ -0,0 +1,52 @@ +rbx.platform.typedef.__time32_t = long +rbx.platform.typedef.__time64_t = long_long +rbx.platform.typedef._dev_t = uint +rbx.platform.typedef._ino_t = ushort +rbx.platform.typedef._mode_t = ushort +rbx.platform.typedef._off64_t = long_long +rbx.platform.typedef._off_t = long +rbx.platform.typedef._pid_t = long_long +rbx.platform.typedef._sigset_t = ulong_long +rbx.platform.typedef.dev_t = uint +rbx.platform.typedef.errno_t = int +rbx.platform.typedef.ino_t = ushort +rbx.platform.typedef.int16_t = short +rbx.platform.typedef.int32_t = int +rbx.platform.typedef.int64_t = long_long +rbx.platform.typedef.int8_t = char +rbx.platform.typedef.int_fast16_t = short +rbx.platform.typedef.int_fast32_t = int +rbx.platform.typedef.int_fast64_t = long_long +rbx.platform.typedef.int_fast8_t = char +rbx.platform.typedef.int_least16_t = short +rbx.platform.typedef.int_least32_t = int +rbx.platform.typedef.int_least64_t = long_long +rbx.platform.typedef.int_least8_t = char +rbx.platform.typedef.intmax_t = long_long +rbx.platform.typedef.intptr_t = long_long +rbx.platform.typedef.mode_t = ushort +rbx.platform.typedef.off32_t = long +rbx.platform.typedef.off64_t = long_long +rbx.platform.typedef.off_t = long_long +rbx.platform.typedef.pid_t = long_long +rbx.platform.typedef.ptrdiff_t = long_long +rbx.platform.typedef.rsize_t = ulong_long +rbx.platform.typedef.size_t = ulong_long +rbx.platform.typedef.ssize_t = long_long +rbx.platform.typedef.time_t = long_long +rbx.platform.typedef.uint16_t = ushort +rbx.platform.typedef.uint64_t = ulong_long +rbx.platform.typedef.uint8_t = uchar +rbx.platform.typedef.uint_fast16_t = ushort +rbx.platform.typedef.uint_fast32_t = uint +rbx.platform.typedef.uint_fast64_t = ulong_long +rbx.platform.typedef.uint_fast8_t = uchar +rbx.platform.typedef.uint_least16_t = ushort +rbx.platform.typedef.uint_least64_t = ulong_long +rbx.platform.typedef.uint_least8_t = uchar +rbx.platform.typedef.uintmax_t = ulong_long +rbx.platform.typedef.uintptr_t = ulong_long +rbx.platform.typedef.useconds_t = uint +rbx.platform.typedef.wchar_t = ushort +rbx.platform.typedef.wctype_t = ushort +rbx.platform.typedef.wint_t = ushort diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/pointer.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/pointer.rb new file mode 100644 index 0000000..37a054b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/pointer.rb @@ -0,0 +1,167 @@ +# +# Copyright (C) 2008, 2009 Wayne Meissner +# Copyright (c) 2007, 2008 Evan Phoenix +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +require 'ffi/platform' + +# NOTE: all method definitions in this file are conditional on +# whether they are not already defined. This is needed because +# some Ruby implementations (e.g., TruffleRuby) might already +# provide these methods due to using FFI internally, and we +# should not override them to avoid warnings. + +module FFI + class Pointer + + # Pointer size + SIZE = Platform::ADDRESS_SIZE / 8 unless const_defined?(:SIZE) + + # Return the size of a pointer on the current platform, in bytes + # @return [Numeric] + def self.size + SIZE + end unless respond_to?(:size) + + # @param [nil,Numeric] len length of string to return + # @return [String] + # Read pointer's contents as a string, or the first +len+ bytes of the + # equivalent string if +len+ is not +nil+. + def read_string(len=nil) + if len + return ''.b if len == 0 + get_bytes(0, len) + else + get_string(0) + end + end unless method_defined?(:read_string) + + # @param [Numeric] len length of string to return + # @return [String] + # Read the first +len+ bytes of pointer's contents as a string. + # + # Same as: + # ptr.read_string(len) # with len not nil + def read_string_length(len) + get_bytes(0, len) + end unless method_defined?(:read_string_length) + + # @return [String] + # Read pointer's contents as a string. + # + # Same as: + # ptr.read_string # with no len + def read_string_to_null + get_string(0) + end unless method_defined?(:read_string_to_null) + + # @param [String] str string to write + # @param [Numeric] len length of string to return + # @return [self] + # Write +len+ first bytes of +str+ in pointer's contents. + # + # Same as: + # ptr.write_string(str, len) # with len not nil + def write_string_length(str, len) + put_bytes(0, str, 0, len) + end unless method_defined?(:write_string_length) + + # @param [String] str string to write + # @param [Numeric] len length of string to return + # @return [self] + # Write +str+ in pointer's contents, or first +len+ bytes if + # +len+ is not +nil+. + def write_string(str, len=nil) + len = str.bytesize unless len + # Write the string data without NUL termination + put_bytes(0, str, 0, len) + end unless method_defined?(:write_string) + + # @param [Type] type type of data to read from pointer's contents + # @param [Symbol] reader method to send to +self+ to read +type+ + # @param [Numeric] length + # @return [Array] + # Read an array of +type+ of length +length+. + # @example + # ptr.read_array_of_type(TYPE_UINT8, :read_uint8, 4) # -> [1, 2, 3, 4] + def read_array_of_type(type, reader, length) + ary = [] + size = FFI.type_size(type) + tmp = self + length.times { |j| + ary << tmp.send(reader) + tmp += size unless j == length-1 # avoid OOB + } + ary + end unless method_defined?(:read_array_of_type) + + # @param [Type] type type of data to write to pointer's contents + # @param [Symbol] writer method to send to +self+ to write +type+ + # @param [Array] ary + # @return [self] + # Write +ary+ in pointer's contents as +type+. + # @example + # ptr.write_array_of_type(TYPE_UINT8, :put_uint8, [1, 2, 3 ,4]) + def write_array_of_type(type, writer, ary) + size = FFI.type_size(type) + ary.each_with_index { |val, i| + break unless i < self.size + self.send(writer, i * size, val) + } + self + end unless method_defined?(:write_array_of_type) + + # @return [self] + def to_ptr + self + end unless method_defined?(:to_ptr) + + # @param [Symbol,Type] type of data to read + # @return [Object] + # Read pointer's contents as +type+ + # + # Same as: + # ptr.get(type, 0) + def read(type) + get(type, 0) + end unless method_defined?(:read) + + # @param [Symbol,Type] type of data to read + # @param [Object] value to write + # @return [nil] + # Write +value+ of type +type+ to pointer's content + # + # Same as: + # ptr.put(type, 0) + def write(type, value) + put(type, 0, value) + end unless method_defined?(:write) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct.rb new file mode 100644 index 0000000..7028258 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct.rb @@ -0,0 +1,316 @@ +# +# Copyright (C) 2008-2010 Wayne Meissner +# Copyright (C) 2008, 2009 Andrea Fazzi +# Copyright (C) 2008, 2009 Luc Heinrich +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +require 'ffi/platform' +require 'ffi/struct_layout' +require 'ffi/struct_layout_builder' +require 'ffi/struct_by_reference' + +module FFI + + class Struct + + # Get struct size + # @return [Numeric] + def size + self.class.size + end + + # @return [Fixnum] Struct alignment + def alignment + self.class.alignment + end + alias_method :align, :alignment + + # (see FFI::StructLayout#offset_of) + def offset_of(name) + self.class.offset_of(name) + end + + # (see FFI::StructLayout#members) + def members + self.class.members + end + + # @return [Array] + # Get array of values from Struct fields. + def values + members.map { |m| self[m] } + end + + # (see FFI::StructLayout#offsets) + def offsets + self.class.offsets + end + + # Clear the struct content. + # @return [self] + def clear + pointer.clear + self + end + + # Get {Pointer} to struct content. + # @return [AbstractMemory] + def to_ptr + pointer + end + + # Get struct size + # @return [Numeric] + def self.size + defined?(@layout) ? @layout.size : defined?(@size) ? @size : 0 + end + + # set struct size + # @param [Numeric] size + # @return [size] + def self.size=(size) + raise ArgumentError, "Size already set" if defined?(@size) || defined?(@layout) + @size = size + end + + # @return (see Struct#alignment) + def self.alignment + @layout.alignment + end + + # (see FFI::Type#members) + def self.members + @layout.members + end + + # (see FFI::StructLayout#offsets) + def self.offsets + @layout.offsets + end + + # (see FFI::StructLayout#offset_of) + def self.offset_of(name) + @layout.offset_of(name) + end + + def self.in + ptr(:in) + end + + def self.out + ptr(:out) + end + + def self.ptr(flags = :inout) + @ref_data_type ||= Type::Mapped.new(StructByReference.new(self)) + end + + def self.val + @val_data_type ||= StructByValue.new(self) + end + + def self.by_value + self.val + end + + def self.by_ref(flags = :inout) + self.ptr(flags) + end + + class ManagedStructConverter < StructByReference + + # @param [Struct] struct_class + def initialize(struct_class) + super(struct_class) + + raise NoMethodError, "release() not implemented for class #{struct_class}" unless struct_class.respond_to? :release + @method = struct_class.method(:release) + end + + # @param [Pointer] ptr + # @param [nil] ctx + # @return [Struct] + def from_native(ptr, ctx) + struct_class.new(AutoPointer.new(ptr, @method)) + end + end + + def self.auto_ptr + @managed_type ||= Type::Mapped.new(ManagedStructConverter.new(self)) + end + + + class << self + public + + # @return [StructLayout] + # @overload layout + # @return [StructLayout] + # Get struct layout. + # @overload layout(*spec) + # @param [Array,Array(Hash)] spec + # @return [StructLayout] + # Create struct layout from +spec+. + # @example Creating a layout from an array +spec+ + # class MyStruct < Struct + # layout :field1, :int, + # :field2, :pointer, + # :field3, :string + # end + # @example Creating a layout from an array +spec+ with offset + # class MyStructWithOffset < Struct + # layout :field1, :int, + # :field2, :pointer, 6, # set offset to 6 for this field + # :field3, :string + # end + # @example Creating a layout from a hash +spec+ + # class MyStructFromHash < Struct + # layout :field1 => :int, + # :field2 => :pointer, + # :field3 => :string + # end + # @example Creating a layout with pointers to functions + # class MyFunctionTable < Struct + # layout :function1, callback([:int, :int], :int), + # :function2, callback([:pointer], :void), + # :field3, :string + # end + def layout(*spec) + warn "[DEPRECATION] Struct layout is already defined for class #{self.inspect}. Redefinition as in #{caller[0]} will be disallowed in ffi-2.0." if defined?(@layout) + return @layout if spec.size == 0 + + builder = StructLayoutBuilder.new + builder.union = self < Union + builder.packed = @packed if defined?(@packed) + builder.alignment = @min_alignment if defined?(@min_alignment) + + if spec[0].kind_of?(Hash) + hash_layout(builder, spec) + else + array_layout(builder, spec) + end + builder.size = @size if defined?(@size) && @size > builder.size + cspec = builder.build + @layout = cspec unless self == Struct + @size = cspec.size + return cspec + end + + + protected + + def callback(params, ret) + mod = enclosing_module + ret_type = find_type(ret, mod) + if ret_type == Type::STRING + raise TypeError, ":string is not allowed as return type of callbacks" + end + FFI::CallbackInfo.new(ret_type, params.map { |e| find_type(e, mod) }) + end + + def packed(packed = 1) + @packed = packed + end + alias :pack :packed + + def aligned(alignment = 1) + @min_alignment = alignment + end + alias :align :aligned + + def enclosing_module + begin + mod = self.name.split("::")[0..-2].inject(Object) { |obj, c| obj.const_get(c) } + if mod.respond_to?(:find_type) && (mod.is_a?(FFI::Library) || mod < FFI::Struct) + mod + end + rescue Exception + nil + end + end + + + def find_field_type(type, mod = enclosing_module) + if type.kind_of?(Class) && type < Struct + FFI::Type::Struct.new(type) + + elsif type.kind_of?(Class) && type < FFI::StructLayout::Field + type + + elsif type.kind_of?(::Array) + FFI::Type::Array.new(find_field_type(type[0]), type[1]) + + else + find_type(type, mod) + end + end + + def find_type(type, mod = enclosing_module) + if mod + mod.find_type(type) + end || FFI.find_type(type) + end + + private + + # @param [StructLayoutBuilder] builder + # @param [Hash] spec + # @return [builder] + # Add hash +spec+ to +builder+. + def hash_layout(builder, spec) + spec[0].each do |name, type| + builder.add name, find_field_type(type), nil + end + end + + # @param [StructLayoutBuilder] builder + # @param [Array] spec + # @return [builder] + # Add array +spec+ to +builder+. + def array_layout(builder, spec) + i = 0 + while i < spec.size + name, type = spec[i, 2] + i += 2 + + # If the next param is a Integer, it specifies the offset + if spec[i].kind_of?(Integer) + offset = spec[i] + i += 1 + else + offset = nil + end + + builder.add name, find_field_type(type), offset + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct_by_reference.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct_by_reference.rb new file mode 100644 index 0000000..27f25ec --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct_by_reference.rb @@ -0,0 +1,72 @@ +# +# Copyright (C) 2010 Wayne Meissner +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# + +module FFI + # This class includes the {FFI::DataConverter} module. + class StructByReference + include DataConverter + + attr_reader :struct_class + + # @param [Struct] struct_class + def initialize(struct_class) + unless Class === struct_class and struct_class < FFI::Struct + raise TypeError, 'wrong type (expected subclass of FFI::Struct)' + end + @struct_class = struct_class + end + + # Always get {FFI::Type}::POINTER. + def native_type + FFI::Type::POINTER + end + + # @param [nil, Struct] value + # @param [nil] ctx + # @return [AbstractMemory] Pointer on +value+. + def to_native(value, ctx) + return Pointer::NULL if value.nil? + + unless @struct_class === value + raise TypeError, "wrong argument type #{value.class} (expected #{@struct_class})" + end + + value.pointer + end + + # @param [AbstractMemory] value + # @param [nil] ctx + # @return [Struct] + # Create a struct from content of memory +value+. + def from_native(value, ctx) + @struct_class.new(value) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct_layout.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct_layout.rb new file mode 100644 index 0000000..d5a78a7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct_layout.rb @@ -0,0 +1,96 @@ +# +# Copyright (C) 2008-2010 Wayne Meissner +# Copyright (C) 2008, 2009 Andrea Fazzi +# Copyright (C) 2008, 2009 Luc Heinrich +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +module FFI + + class StructLayout + + # @return [Array + # Get an array of tuples (field name, offset of the field). + def offsets + members.map { |m| [ m, self[m].offset ] } + end + + # @return [Numeric] + # Get the offset of a field. + def offset_of(field_name) + self[field_name].offset + end + + # An enum {Field} in a {StructLayout}. + class Enum < Field + + # @param [AbstractMemory] ptr pointer on a {Struct} + # @return [Object] + # Get an object of type {#type} from memory pointed by +ptr+. + def get(ptr) + type.find(ptr.get_int(offset)) + end + + # @param [AbstractMemory] ptr pointer on a {Struct} + # @param value + # @return [nil] + # Set +value+ into memory pointed by +ptr+. + def put(ptr, value) + ptr.put_int(offset, type.find(value)) + end + + end + + class InnerStruct < Field + def get(ptr) + type.struct_class.new(ptr.slice(self.offset, self.size)) + end + + def put(ptr, value) + raise TypeError, "wrong value type (expected #{type.struct_class})" unless value.is_a?(type.struct_class) + ptr.slice(self.offset, self.size).__copy_from__(value.pointer, self.size) + end + end + + class Mapped < Field + def initialize(name, offset, type, orig_field) + super(name, offset, type) + @orig_field = orig_field + end + + def get(ptr) + type.from_native(@orig_field.get(ptr), nil) + end + + def put(ptr, value) + @orig_field.put(ptr, type.to_native(value, nil)) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct_layout_builder.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct_layout_builder.rb new file mode 100644 index 0000000..4d6a464 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/struct_layout_builder.rb @@ -0,0 +1,227 @@ +# +# Copyright (C) 2008-2010 Wayne Meissner +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +module FFI + + # Build a {StructLayout struct layout}. + class StructLayoutBuilder + attr_reader :size + attr_reader :alignment + + def initialize + @size = 0 + @alignment = 1 + @min_alignment = 1 + @packed = false + @union = false + @fields = Array.new + end + + # Set size attribute with +size+ only if +size+ is greater than attribute value. + # @param [Numeric] size + def size=(size) + @size = size if size > @size + end + + # Set alignment attribute with +align+ only if it is greater than attribute value. + # @param [Numeric] align + def alignment=(align) + @alignment = align if align > @alignment + @min_alignment = align + end + + # Set union attribute. + # Set to +true+ to build a {Union} instead of a {Struct}. + # @param [Boolean] is_union + # @return [is_union] + def union=(is_union) + @union = is_union + end + + # Building a {Union} or a {Struct} ? + # + # @return [Boolean] + # + def union? + @union + end + + # Set packed attribute + # @overload packed=(packed) Set alignment and packed attributes to + # +packed+. + # + # @param [Fixnum] packed + # + # @return [packed] + # @overload packed=(packed) Set packed attribute. + # @param packed + # + # @return [0,1] + # + def packed=(packed) + if packed.is_a?(0.class) + @alignment = packed + @packed = packed + else + @packed = packed ? 1 : 0 + end + end + + + # List of number types + NUMBER_TYPES = [ + Type::INT8, + Type::UINT8, + Type::INT16, + Type::UINT16, + Type::INT32, + Type::UINT32, + Type::LONG, + Type::ULONG, + Type::INT64, + Type::UINT64, + Type::FLOAT32, + Type::FLOAT64, + Type::LONGDOUBLE, + Type::BOOL, + ] + + # @param [String, Symbol] name name of the field + # @param [Array, DataConverter, Struct, StructLayout::Field, Symbol, Type] type type of the field + # @param [Numeric, nil] offset + # @return [self] + # Add a field to the builder. + # @note Setting +offset+ to +nil+ or +-1+ is equivalent to +0+. + def add(name, type, offset = nil) + + if offset.nil? || offset == -1 + offset = @union ? 0 : align(@size, @packed ? [ @packed, type.alignment ].min : [ @min_alignment, type.alignment ].max) + end + + # + # If a FFI::Type type was passed in as the field arg, try and convert to a StructLayout::Field instance + # + field = type.is_a?(StructLayout::Field) ? type : field_for_type(name, offset, type) + @fields << field + @alignment = [ @alignment, field.alignment ].max unless @packed + @size = [ @size, field.size + (@union ? 0 : field.offset) ].max + + return self + end + + # @param (see #add) + # @return (see #add) + # Same as {#add}. + # @see #add + def add_field(name, type, offset = nil) + add(name, type, offset) + end + + # @param (see #add) + # @return (see #add) + # Add a struct as a field to the builder. + def add_struct(name, type, offset = nil) + add(name, Type::Struct.new(type), offset) + end + + # @param name (see #add) + # @param type (see #add) + # @param [Numeric] count array length + # @param offset (see #add) + # @return (see #add) + # Add an array as a field to the builder. + def add_array(name, type, count, offset = nil) + add(name, Type::Array.new(type, count), offset) + end + + # @return [StructLayout] + # Build and return the struct layout. + def build + # Add tail padding if the struct is not packed + size = @packed ? @size : align(@size, @alignment) + + layout = StructLayout.new(@fields, size, @alignment) + layout.__union! if @union + layout + end + + private + + # @param [Numeric] offset + # @param [Numeric] align + # @return [Numeric] + def align(offset, align) + align + ((offset - 1) & ~(align - 1)); + end + + # @param (see #add) + # @return [StructLayout::Field] + def field_for_type(name, offset, type) + field_class = case + when type.is_a?(Type::Function) + StructLayout::Function + + when type.is_a?(Type::Struct) + StructLayout::InnerStruct + + when type.is_a?(Type::Array) + StructLayout::Array + + when type.is_a?(FFI::Enum) + StructLayout::Enum + + when NUMBER_TYPES.include?(type) + StructLayout::Number + + when type == Type::POINTER + StructLayout::Pointer + + when type == Type::STRING + StructLayout::String + + when type.is_a?(Class) && type < StructLayout::Field + type + + when type.is_a?(DataConverter) + return StructLayout::Mapped.new(name, offset, Type::Mapped.new(type), field_for_type(name, offset, type.native_type)) + + when type.is_a?(Type::Mapped) + return StructLayout::Mapped.new(name, offset, type, field_for_type(name, offset, type.native_type)) + + else + raise TypeError, "invalid struct field type #{type.inspect}" + end + + field_class.new(name, offset, type) + end + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/const_generator.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/const_generator.rb new file mode 100644 index 0000000..70ba9c2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/const_generator.rb @@ -0,0 +1,232 @@ +require 'tempfile' +require 'open3' + +module FFI + + # ConstGenerator turns C constants into ruby values. + # + # @example a simple example for stdio + # require 'ffi/tools/const_generator' + # cg = FFI::ConstGenerator.new('stdio') do |gen| + # gen.const(:SEEK_SET) + # gen.const('SEEK_CUR') + # gen.const('seek_end') # this constant does not exist + # end # #calculate called automatically at the end of the block + # + # cg['SEEK_SET'] # => 0 + # cg['SEEK_CUR'] # => 1 + # cg['seek_end'] # => nil + # cg.to_ruby # => "SEEK_SET = 0\nSEEK_CUR = 1\n# seek_end not available" + class ConstGenerator + @options = {} + attr_reader :constants + + # Creates a new constant generator that uses +prefix+ as a name, and an + # options hash. + # + # The only option is +:required+, which if set to +true+ raises an error if a + # constant you have requested was not found. + # + # @param [#to_s] prefix + # @param [Hash] options + # @return + # @option options [Boolean] :required + # @overload initialize(prefix, options) + # @overload initialize(prefix, options) { |gen| ... } + # @yieldparam [ConstGenerator] gen new generator is passed to the block + # When passed a block, {#calculate} is automatically called at the end of + # the block, otherwise you must call it yourself. + def initialize(prefix = nil, options = {}) + @includes = ['stdio.h', 'stddef.h'] + @constants = {} + @prefix = prefix + + @required = options[:required] + @options = options + + if block_given? then + yield self + calculate self.class.options.merge(options) + end + end + # Set class options + # These options are merged with {#initialize} options when it is called with a block. + # @param [Hash] options + # @return [Hash] class options + def self.options=(options) + @options = options + end + # Get class options. + # @return [Hash] class options + def self.options + @options + end + # @param [String] name + # @return constant value (converted if a +converter+ was defined). + # Access a constant by name. + def [](name) + @constants[name].converted_value + end + + # Request the value for C constant +name+. + # + # @param [#to_s] name C constant name + # @param [String] format a printf format string to print the value out + # @param [String] cast a C cast for the value + # @param ruby_name alternate ruby name for {#to_ruby} + # + # @overload const(name, format=nil, cast='', ruby_name=nil, converter=nil) + # +converter+ is a Method or a Proc. + # @param [#call] converter convert the value from a string to the appropriate + # type for {#to_ruby}. + # @overload const(name, format=nil, cast='', ruby_name=nil) { |value| ... } + # Use a converter block. This block convert the value from a string to the + # appropriate type for {#to_ruby}. + # @yieldparam value constant value + def const(name, format = nil, cast = '', ruby_name = nil, converter = nil, + &converter_proc) + format ||= '%d' + cast ||= '' + + if converter_proc and converter then + raise ArgumentError, "Supply only converter or converter block" + end + + converter = converter_proc if converter.nil? + + const = Constant.new name, format, cast, ruby_name, converter + @constants[name.to_s] = const + return const + end + + # Calculate constants values. + # @param [Hash] options + # @option options [String] :cppflags flags for C compiler + # @return [nil] + # @raise if a constant is missing and +:required+ was set to +true+ (see {#initialize}) + def calculate(options = {}) + binary_path = nil + + Tempfile.open("#{@prefix}.const_generator") do |f| + binary_path = f.path + ".bin" + @includes.each do |inc| + f.puts "#include <#{inc}>" + end + f.puts "\nint main(int argc, char **argv)\n{" + + @constants.each_value do |const| + f.puts <<-EOF + #ifdef #{const.name} + printf("#{const.name} #{const.format}\\n", #{const.cast}#{const.name}); + #endif + EOF + end + + f.puts "\n\treturn 0;\n}" + f.flush + + cc = ENV['CC'] || 'gcc' + output = `#{cc} #{options[:cppflags]} -D_DARWIN_USE_64_BIT_INODE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -x c -Wall -Werror #{f.path} -o #{binary_path} 2>&1` + + unless $?.success? then + output = output.split("\n").map { |l| "\t#{l}" }.join "\n" + raise "Compilation error generating constants #{@prefix}:\n#{output}" + end + end + + output = `#{binary_path}` + File.unlink(binary_path + (FFI::Platform.windows? ? ".exe" : "")) + output.each_line do |line| + line =~ /^(\S+)\s(.*)$/ + const = @constants[$1] + const.value = $2 + end + + missing_constants = @constants.select do |name, constant| + constant.value.nil? + end.map { |name,| name } + + if @required and not missing_constants.empty? then + raise "Missing required constants for #{@prefix}: #{missing_constants.join ', '}" + end + end + + # Dump constants to +io+. + # @param [#puts] io + # @return [nil] + def dump_constants(io) + @constants.each do |name, constant| + name = [@prefix, name].join '.' if @prefix + io.puts "#{name} = #{constant.converted_value}" + end + end + + # Outputs values for discovered constants. If the constant's value was + # not discovered it is not omitted. + # @return [String] + def to_ruby + @constants.sort_by { |name,| name }.map do |name, constant| + if constant.value.nil? then + "# #{name} not available" + else + constant.to_ruby + end + end.join "\n" + end + + # Add additional C include file(s) to calculate constants from. + # @note +stdio.h+ and +stddef.h+ automatically included + # @param [List, Array] i include file(s) + # @return [Array] array of include files + def include(*i) + @includes |= i.flatten + end + + end + + # This class hold constants for {ConstGenerator} + class ConstGenerator::Constant + + attr_reader :name, :format, :cast + attr_accessor :value + + # @param [#to_s] name + # @param [String] format a printf format string to print the value out + # @param [String] cast a C cast for the value + # @param ruby_name alternate ruby name for {#to_ruby} + # @param [#call] converter convert the value from a string to the appropriate + # type for {#to_ruby}. + def initialize(name, format, cast, ruby_name = nil, converter=nil) + @name = name + @format = format + @cast = cast + @ruby_name = ruby_name + @converter = converter + @value = nil + end + + # Return constant value (converted if a +converter+ was defined). + # @return constant value. + def converted_value + if @converter + @converter.call(@value) + else + @value + end + end + + # get constant ruby name + # @return [String] + def ruby_name + @ruby_name || @name + end + + # Get an evaluable string from constant. + # @return [String] + def to_ruby + "#{ruby_name} = #{converted_value}" + end + + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/generator.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/generator.rb new file mode 100644 index 0000000..5552ea5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/generator.rb @@ -0,0 +1,105 @@ +require 'ffi/tools/struct_generator' +require 'ffi/tools/const_generator' + +module FFI + + ## + # Generate files with C structs for FFI::Struct and C constants. + # + # == A simple example + # + # In file +zlib.rb.ffi+: + # module Zlib + # @@@ + # constants do |c| + # c.include "zlib.h" + # c.const :ZLIB_VERNUM + # end + # @@@ + # + # class ZStream < FFI::Struct + # + # struct do |s| + # s.name "struct z_stream_s" + # s.include "zlib.h" + # + # s.field :next_in, :pointer + # s.field :avail_in, :uint + # s.field :total_in, :ulong + # end + # @@@ + # end + # end + # + # Translate the file: + # require "ffi/tools/generator" + # FFI::Generator.new "zlib.rb.ffi", "zlib.rb" + # + # Generates the file +zlib.rb+ with constant values and offsets: + # module Zlib + # ZLIB_VERNUM = 4784 + # + # class ZStream < FFI::Struct + # layout :next_in, :pointer, 0, + # :avail_in, :uint, 8, + # :total_in, :ulong, 16 + # end + # + # @see FFI::Generator::Task for easy integration in a Rakefile + class Generator + + def initialize(ffi_name, rb_name, options = {}) + @ffi_name = ffi_name + @rb_name = rb_name + @options = options + @name = File.basename rb_name, '.rb' + + file = File.read @ffi_name + + new_file = file.gsub(/^( *)@@@(.*?)@@@/m) do + @constants = [] + @structs = [] + + indent = $1 + original_lines = $2.count "\n" + + instance_eval $2, @ffi_name, $`.count("\n") + + new_lines = [] + @constants.each { |c| new_lines << c.to_ruby } + @structs.each { |s| new_lines << s.generate_layout } + + new_lines = new_lines.join("\n").split "\n" # expand multiline blocks + new_lines = new_lines.map { |line| indent + line } + + padding = original_lines - new_lines.length + new_lines += [nil] * padding if padding >= 0 + + new_lines.join "\n" + end + + open @rb_name, 'w' do |f| + f.puts "# This file is generated from `#{@ffi_name}'. Do not edit." + f.puts + f.puts new_file + end + end + + def constants(options = {}, &block) + @constants << FFI::ConstGenerator.new(@name, @options.merge(options), &block) + end + + def struct(options = {}, &block) + @structs << FFI::StructGenerator.new(@name, @options.merge(options), &block) + end + + ## + # Utility converter for constants + + def to_s + proc { |obj| obj.to_s.inspect } + end + + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/generator_task.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/generator_task.rb new file mode 100644 index 0000000..da72968 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/generator_task.rb @@ -0,0 +1,32 @@ +require 'ffi/tools/generator' +require 'rake' +require 'rake/tasklib' + +## +# Add Rake tasks that generate files with C structs for FFI::Struct and C constants. +# +# @example a simple example for your Rakefile +# require "ffi/tools/generator_task" +# # Add a task to generate my_object.rb out of my_object.rb.ffi +# FFI::Generator::Task.new ["my_object.rb"], cflags: "-I/usr/local/mylibrary" +# +# The generated files are also added to the 'clear' task. +# +# @see FFI::Generator for a description of the file content +class FFI::Generator::Task < Rake::TaskLib + + def initialize(rb_names, options={}) + task :clean do rm_f rb_names end + + rb_names.each do |rb_name| + ffi_name = "#{rb_name}.ffi" + + file rb_name => ffi_name do |t| + puts "Generating #{rb_name}..." if Rake.application.options.trace + + FFI::Generator.new ffi_name, rb_name, options + end + end + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/struct_generator.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/struct_generator.rb new file mode 100644 index 0000000..3a951c3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/struct_generator.rb @@ -0,0 +1,195 @@ +require 'tempfile' + +module FFI + + ## + # Generates an FFI Struct layout. + # + # Given the @@@ portion in: + # + # class Zlib::ZStream < FFI::Struct + # @@@ + # name "struct z_stream_s" + # include "zlib.h" + # + # field :next_in, :pointer + # field :avail_in, :uint + # field :total_in, :ulong + # + # # ... + # @@@ + # end + # + # StructGenerator will create the layout: + # + # layout :next_in, :pointer, 0, + # :avail_in, :uint, 4, + # :total_in, :ulong, 8, + # # ... + # + # StructGenerator does its best to pad the layout it produces to preserve + # line numbers. Place the struct definition as close to the top of the file + # for best results. + + class StructGenerator + @options = {} + attr_accessor :size + attr_reader :fields + + def initialize(name, options = {}) + @name = name + @struct_name = nil + @includes = [] + @fields = [] + @found = false + @size = nil + + if block_given? then + yield self + calculate self.class.options.merge(options) + end + end + def self.options=(options) + @options = options + end + def self.options + @options + end + def calculate(options = {}) + binary = File.join Dir.tmpdir, "rb_struct_gen_bin_#{Process.pid}" + + raise "struct name not set" if @struct_name.nil? + + Tempfile.open("#{@name}.struct_generator") do |f| + f.puts "#include " + + @includes.each do |inc| + f.puts "#include <#{inc}>" + end + + f.puts "#include \n\n" + f.puts "int main(int argc, char **argv)\n{" + f.puts " #{@struct_name} s;" + f.puts %[ printf("sizeof(#{@struct_name}) %u\\n", (unsigned int) sizeof(#{@struct_name}));] + + @fields.each do |field| + f.puts <<-EOF + printf("#{field.name} %u %u\\n", (unsigned int) offsetof(#{@struct_name}, #{field.name}), + (unsigned int) sizeof(s.#{field.name})); + EOF + end + + f.puts "\n return 0;\n}" + f.flush + + cc = ENV['CC'] || 'gcc' + output = `#{cc} #{options[:cppflags]} #{options[:cflags]} -D_DARWIN_USE_64_BIT_INODE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -x c -Wall -Werror #{f.path} -o #{binary} 2>&1` + + unless $?.success? then + @found = false + output = output.split("\n").map { |l| "\t#{l}" }.join "\n" + raise "Compilation error generating struct #{@name} (#{@struct_name}):\n#{output}" + end + end + + output = `#{binary}`.split "\n" + File.unlink(binary + (FFI::Platform.windows? ? ".exe" : "")) + sizeof = output.shift + unless @size + m = /\s*sizeof\([^)]+\) (\d+)/.match sizeof + @size = m[1] + end + + line_no = 0 + output.each do |line| + md = line.match(/.+ (\d+) (\d+)/) + @fields[line_no].offset = md[1].to_i + @fields[line_no].size = md[2].to_i + + line_no += 1 + end + + @found = true + end + + def field(name, type=nil) + field = Field.new(name, type) + @fields << field + return field + end + + def found? + @found + end + + def dump_config(io) + io.puts "rbx.platform.#{@name}.sizeof = #{@size}" + + @fields.each { |field| io.puts field.to_config(@name) } + end + + def generate_layout + buf = "" + + @fields.each_with_index do |field, i| + if buf.empty? + buf << "layout :#{field.name}, :#{field.type}, #{field.offset}" + else + buf << " :#{field.name}, :#{field.type}, #{field.offset}" + end + + if i < @fields.length - 1 + buf << ",\n" + end + end + + buf + end + + def get_field(name) + @fields.find { |f| name == f.name } + end + + def include(i) + @includes << i + end + + def name(n) + @struct_name = n + end + + end + + ## + # A field in a Struct. + + class StructGenerator::Field + + attr_reader :name + attr_reader :type + attr_reader :offset + attr_accessor :size + + def initialize(name, type) + @name = name + @type = type + @offset = nil + @size = nil + end + + def offset=(o) + @offset = o + end + + def to_config(name) + buf = [] + buf << "rbx.platform.#{name}.#{@name}.offset = #{@offset}" + buf << "rbx.platform.#{name}.#{@name}.size = #{@size}" + buf << "rbx.platform.#{name}.#{@name}.type = #{@type}" if @type + buf + end + + end + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/types_generator.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/types_generator.rb new file mode 100644 index 0000000..ba2d8c5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/tools/types_generator.rb @@ -0,0 +1,137 @@ +require 'tempfile' + +module FFI + + # @private + class TypesGenerator + + ## + # Maps different C types to the C type representations we use + + TYPE_MAP = { + "char" => :char, + "signed char" => :char, + "__signed char" => :char, + "unsigned char" => :uchar, + + "short" => :short, + "signed short" => :short, + "signed short int" => :short, + "unsigned short" => :ushort, + "unsigned short int" => :ushort, + + "int" => :int, + "signed int" => :int, + "unsigned int" => :uint, + + "long" => :long, + "long int" => :long, + "signed long" => :long, + "signed long int" => :long, + "unsigned long" => :ulong, + "unsigned long int" => :ulong, + "long unsigned int" => :ulong, + + "long long" => :long_long, + "long long int" => :long_long, + "signed long long" => :long_long, + "signed long long int" => :long_long, + "unsigned long long" => :ulong_long, + "unsigned long long int" => :ulong_long, + + "char *" => :string, + "void *" => :pointer, + } + + def self.generate(options = {}) + typedefs = nil + Tempfile.open 'ffi_types_generator' do |io| + io.puts <<-C +#include +#include +#include +#if !(defined(WIN32)) +#include +#include +#include +#endif + C + + io.close + cc = ENV['CC'] || 'gcc' + cmd = "#{cc} -E -x c #{options[:cppflags]} -D_DARWIN_USE_64_BIT_INODE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -c" + if options[:input] + typedefs = File.read(options[:input]) + elsif options[:remote] + typedefs = `ssh #{options[:remote]} #{cmd} - < #{io.path}` + else + typedefs = `#{cmd} #{io.path}` + end + end + + code = [] + + typedefs.each_line do |type| + # We only care about single line typedef + next unless type =~ /typedef/ + # Ignore unions or structs + next if type =~ /union|struct/ + + # strip off the starting typedef and ending ; + type.gsub!(/^(.*typedef\s*)/, "") + type.gsub!(/\s*;\s*$/, "") + + parts = type.split(/\s+/) + def_type = parts.join(" ") + + # GCC does mapping with __attribute__ stuf, also see + # http://hal.cs.berkeley.edu/cil/cil016.html section 16.2.7. Problem + # with this is that the __attribute__ stuff can either occur before or + # after the new type that is defined... + if type =~ /__attribute__/ + if parts.last =~ /__QI__|__HI__|__SI__|__DI__|__word__/ + + # In this case, the new type is BEFORE __attribute__ we need to + # find the final_type as the type before the part that starts with + # __attribute__ + final_type = "" + parts.each do |p| + break if p =~ /__attribute__/ + final_type = p + end + else + final_type = parts.pop + end + + def_type = case type + when /__QI__/ then "char" + when /__HI__/ then "short" + when /__SI__/ then "int" + when /__DI__/ then "long long" + when /__word__/ then "long" + else "int" + end + + def_type = "unsigned #{def_type}" if type =~ /unsigned/ + else + final_type = parts.pop + def_type = parts.join(" ") + end + + if type = TYPE_MAP[def_type] + code << "rbx.platform.typedef.#{final_type} = #{type}" + TYPE_MAP[final_type] = TYPE_MAP[def_type] + else + # Fallback to an ordinary pointer if we don't know the type + if def_type =~ /\*/ + code << "rbx.platform.typedef.#{final_type} = pointer" + TYPE_MAP[final_type] = :pointer + end + end + end + + code.sort.join("\n") + end + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/types.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/types.rb new file mode 100644 index 0000000..90f50c1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/types.rb @@ -0,0 +1,194 @@ +# +# Copyright (C) 2008-2010 Wayne Meissner +# Copyright (c) 2007, 2008 Evan Phoenix +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +# see {file:README} +module FFI + + # @param [Type, DataConverter, Symbol] old type definition used by {FFI.find_type} + # @param [Symbol] add new type definition's name to add + # @return [Type] + # Add a definition type to type definitions. + def self.typedef(old, add) + TypeDefs[add] = self.find_type(old) + end + + # (see FFI.typedef) + def self.add_typedef(old, add) + typedef old, add + end + + + # @param [Type, DataConverter, Symbol] name + # @param [Hash] type_map if nil, {FFI::TypeDefs} is used + # @return [Type] + # Find a type in +type_map+ ({FFI::TypeDefs}, by default) from + # a type objet, a type name (symbol). If +name+ is a {DataConverter}, + # a new {Type::Mapped} is created. + def self.find_type(name, type_map = nil) + if name.is_a?(Type) + name + + elsif type_map && type_map.has_key?(name) + type_map[name] + + elsif TypeDefs.has_key?(name) + TypeDefs[name] + + elsif name.is_a?(DataConverter) + (type_map || TypeDefs)[name] = Type::Mapped.new(name) + else + raise TypeError, "unable to resolve type '#{name}'" + end + end + + # List of type definitions + TypeDefs.merge!({ + # The C void type; only useful for function return types + :void => Type::VOID, + + # C boolean type + :bool => Type::BOOL, + + # C nul-terminated string + :string => Type::STRING, + + # C signed char + :char => Type::CHAR, + # C unsigned char + :uchar => Type::UCHAR, + + # C signed short + :short => Type::SHORT, + # C unsigned short + :ushort => Type::USHORT, + + # C signed int + :int => Type::INT, + # C unsigned int + :uint => Type::UINT, + + # C signed long + :long => Type::LONG, + + # C unsigned long + :ulong => Type::ULONG, + + # C signed long long integer + :long_long => Type::LONG_LONG, + + # C unsigned long long integer + :ulong_long => Type::ULONG_LONG, + + # C single precision float + :float => Type::FLOAT, + + # C double precision float + :double => Type::DOUBLE, + + # C long double + :long_double => Type::LONGDOUBLE, + + # Native memory address + :pointer => Type::POINTER, + + # 8 bit signed integer + :int8 => Type::INT8, + # 8 bit unsigned integer + :uint8 => Type::UINT8, + + # 16 bit signed integer + :int16 => Type::INT16, + # 16 bit unsigned integer + :uint16 => Type::UINT16, + + # 32 bit signed integer + :int32 => Type::INT32, + # 32 bit unsigned integer + :uint32 => Type::UINT32, + + # 64 bit signed integer + :int64 => Type::INT64, + # 64 bit unsigned integer + :uint64 => Type::UINT64, + + :buffer_in => Type::BUFFER_IN, + :buffer_out => Type::BUFFER_OUT, + :buffer_inout => Type::BUFFER_INOUT, + + # Used in function prototypes to indicate the arguments are variadic + :varargs => Type::VARARGS, + }) + + # This will convert a pointer to a Ruby string (just like `:string`), but + # also allow to work with the pointer itself. This is useful when you want + # a Ruby string already containing a copy of the data, but also the pointer + # to the data for you to do something with it, like freeing it, in case the + # library handed the memory off to the caller (Ruby-FFI). + # + # It's {typedef}'d as +:strptr+. + class StrPtrConverter + extend DataConverter + native_type Type::POINTER + + # @param [Pointer] val + # @param ctx not used + # @return [Array(String, Pointer)] + # Returns a [ String, Pointer ] tuple so the C memory for the string can be freed + def self.from_native(val, ctx) + [ val.null? ? nil : val.get_string(0), val ] + end + end + + typedef(StrPtrConverter, :strptr) + + # @param type +type+ is an instance of class accepted by {FFI.find_type} + # @return [Numeric] + # Get +type+ size, in bytes. + def self.type_size(type) + find_type(type).size + end + + # Load all the platform dependent types + begin + File.open(File.join(Platform::CONF_DIR, 'types.conf'), "r") do |f| + prefix = "rbx.platform.typedef." + f.each_line { |line| + if line.index(prefix) == 0 + new_type, orig_type = line.chomp.slice(prefix.length..-1).split(/\s*=\s*/) + typedef(orig_type.to_sym, new_type.to_sym) + end + } + end + typedef :pointer, :caddr_t + rescue Errno::ENOENT + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/union.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/union.rb new file mode 100644 index 0000000..38414ab --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/union.rb @@ -0,0 +1,43 @@ +# +# Copyright (C) 2009 Andrea Fazzi +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +require 'ffi/struct' + +module FFI + + class Union < FFI::Struct + def self.builder + b = StructLayoutBuilder.new + b.union = true + b + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/variadic.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/variadic.rb new file mode 100644 index 0000000..743ce7f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/variadic.rb @@ -0,0 +1,69 @@ +# +# Copyright (C) 2008, 2009 Wayne Meissner +# Copyright (C) 2009 Luc Heinrich +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +module FFI + class VariadicInvoker + def call(*args, &block) + param_types = Array.new(@fixed) + param_values = Array.new + @fixed.each_with_index do |t, i| + param_values << args[i] + end + i = @fixed.length + while i < args.length + param_types << FFI.find_type(args[i], @type_map) + param_values << args[i + 1] + i += 2 + end + invoke(param_types, param_values, &block) + end + + # + # Attach the invoker to module +mod+ as +mname+ + # + def attach(mod, mname) + invoker = self + params = "*args" + call = "call" + mod.module_eval <<-code + @@#{mname} = invoker + def self.#{mname}(#{params}) + @@#{mname}.#{call}(#{params}) + end + def #{mname}(#{params}) + @@#{mname}.#{call}(#{params}) + end + code + invoker + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/version.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/version.rb new file mode 100644 index 0000000..3027569 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/lib/ffi/version.rb @@ -0,0 +1,3 @@ +module FFI + VERSION = '1.15.5' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/rakelib/ffi_gem_helper.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/rakelib/ffi_gem_helper.rb new file mode 100644 index 0000000..74be131 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/rakelib/ffi_gem_helper.rb @@ -0,0 +1,65 @@ +require 'bundler' +require 'bundler/gem_helper' + +class FfiGemHelper < Bundler::GemHelper + attr_accessor :cross_platforms + + def install + super + + task "release:guard_clean" => ["release:update_history"] + + task "release:update_history" do + update_history + end + + task "release:rubygem_push" => ["gem:native", "gem:java"] + end + + def hfile + "CHANGELOG.md" + end + + def headline + '([^\w]*)(\d+\.\d+\.\d+(?:\.\w+)?)([^\w]+)([2Y][0Y][0-9Y][0-9Y]-[0-1M][0-9M]-[0-3D][0-9D])([^\w]*|$)' + end + + def reldate + Time.now.strftime("%Y-%m-%d") + end + + def update_history + hin = File.read(hfile) + hout = hin.sub(/#{headline}/) do + raise "#{hfile} isn't up-to-date for version #{version}" unless $2==version.to_s + $1 + $2 + $3 + reldate + $5 + end + if hout != hin + Bundler.ui.confirm "Updating #{hfile} for release." + File.write(hfile, hout) + Rake::FileUtilsExt.sh "git", "commit", hfile, "-m", "Update release date in #{hfile}" + end + end + + def tag_version + Bundler.ui.confirm "Tag release with annotation:" + m = File.read(hfile).match(/(?#{headline}.*?)#{headline}/m) || raise("Unable to find release notes in #{hfile}") + Bundler.ui.info(m[:annotation].gsub(/^/, " ")) + IO.popen(["git", "tag", "--file=-", version_tag], "w") do |fd| + fd.write m[:annotation] + end + yield if block_given? + rescue + Bundler.ui.error "Untagging #{version_tag} due to error." + sh_with_code "git tag -d #{version_tag}" + raise + end + + def rubygem_push(path) + cross_platforms.each do |ruby_platform| + super(path.gsub(/\.gem\z/, "-#{ruby_platform}.gem")) + end + super(path.gsub(/\.gem\z/, "-java.gem")) + super(path) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/getlogin.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/getlogin.rb new file mode 100644 index 0000000..6713021 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/getlogin.rb @@ -0,0 +1,8 @@ +require 'ffi' + +module Foo + extend FFI::Library + ffi_lib FFI::Library::LIBC + attach_function :getlogin, [ ], :string +end +puts "getlogin=#{Foo.getlogin}" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/getpid.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/getpid.rb new file mode 100644 index 0000000..1720635 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/getpid.rb @@ -0,0 +1,8 @@ +require 'ffi' + +module Foo + extend FFI::Library + ffi_lib FFI::Library::LIBC + attach_function :getpid, [ ], :int +end +puts "My pid=#{Foo.getpid}" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/gettimeofday.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/gettimeofday.rb new file mode 100644 index 0000000..864bbb6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/gettimeofday.rb @@ -0,0 +1,18 @@ +require 'ffi' +require 'rbconfig' + +class Timeval < FFI::Struct + layout tv_sec: :ulong, tv_usec: :ulong +end +module LibC + extend FFI::Library + if FFI::Platform.windows? + ffi_lib RbConfig::CONFIG["LIBRUBY_SO"] + else + ffi_lib FFI::Library::LIBC + end + attach_function :gettimeofday, [ :pointer, :pointer ], :int +end +t = Timeval.new +LibC.gettimeofday(t.pointer, nil) +puts "t.tv_sec=#{t[:tv_sec]} t.tv_usec=#{t[:tv_usec]}" diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/hello.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/hello.rb new file mode 100644 index 0000000..f2ccf37 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/hello.rb @@ -0,0 +1,8 @@ +require 'ffi' + +module Foo + extend FFI::Library + ffi_lib FFI::Library::LIBC + attach_function("cputs", "puts", [ :string ], :int) +end +Foo.cputs("Hello, World via libc puts using FFI on MRI ruby") diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/inotify.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/inotify.rb new file mode 100644 index 0000000..018d78c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/inotify.rb @@ -0,0 +1,60 @@ +require 'ffi' + +module Inotify + extend FFI::Library + ffi_lib FFI::Library::LIBC + class Event < FFI::Struct + layout \ + :wd, :int, + :mask, :uint, + :cookie, :uint, + :len, :uint + end + attach_function :init, :inotify_init, [ ], :int + attach_function :add_watch, :inotify_add_watch, [ :int, :string, :uint ], :int + attach_function :rm_watch, :inotify_rm_watch, [ :int, :uint ], :int + attach_function :read, [ :int, :buffer_out, :uint ], :int + IN_ACCESS=0x00000001 + IN_MODIFY=0x00000002 + IN_ATTRIB=0x00000004 + IN_CLOSE_WRITE=0x00000008 + IN_CLOSE_NOWRITE=0x00000010 + IN_CLOSE=(IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) + IN_OPEN=0x00000020 + IN_MOVED_FROM=0x00000040 + IN_MOVED_TO=0x00000080 + IN_MOVE= (IN_MOVED_FROM | IN_MOVED_TO) + IN_CREATE=0x00000100 + IN_DELETE=0x00000200 + IN_DELETE_SELF=0x00000400 + IN_MOVE_SELF=0x00000800 + # Events sent by the kernel. + IN_UNMOUNT=0x00002000 + IN_Q_OVERFLOW=0x00004000 + IN_IGNORED=0x00008000 + IN_ONLYDIR=0x01000000 + IN_DONT_FOLLOW=0x02000000 + IN_MASK_ADD=0x20000000 + IN_ISDIR=0x40000000 + IN_ONESHOT=0x80000000 + IN_ALL_EVENTS=(IN_ACCESS | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE \ + | IN_CLOSE_NOWRITE | IN_OPEN | IN_MOVED_FROM \ + | IN_MOVED_TO | IN_CREATE | IN_DELETE \ + | IN_DELETE_SELF | IN_MOVE_SELF) + +end +if $0 == __FILE__ + fd = Inotify.init + puts "fd=#{fd}" + wd = Inotify.add_watch(fd, "/tmp/", Inotify::IN_ALL_EVENTS) + fp = FFI::IO.for_fd(fd) + puts "wfp=#{fp}" + while true + buf = FFI::Buffer.alloc_out(Inotify::Event.size + 4096, 1, false) + ev = Inotify::Event.new buf + ready = IO.select([ fp ], nil, nil, nil) + n = Inotify.read(fd, buf, buf.total) + puts "Read #{n} bytes from inotify fd" + puts "event.wd=#{ev[:wd]} mask=#{ev[:mask]} len=#{ev[:len]} name=#{ev[:len] > 0 ? buf.get_string(16) : 'unknown'}" + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/pty.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/pty.rb new file mode 100644 index 0000000..8b6b885 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/pty.rb @@ -0,0 +1,75 @@ +require 'ffi' + +module PTY + private + module LibC + extend FFI::Library + ffi_lib FFI::Library::LIBC + attach_function :forkpty, [ :buffer_out, :buffer_out, :buffer_in, :buffer_in ], :int + attach_function :openpty, [ :buffer_out, :buffer_out, :buffer_out, :buffer_in, :buffer_in ], :int + attach_function :login_tty, [ :int ], :int + attach_function :close, [ :int ], :int + attach_function :strerror, [ :int ], :string + attach_function :fork, [], :int + attach_function :execv, [ :string, :buffer_in ], :int + attach_function :execvp, [ :string, :buffer_in ], :int + attach_function :dup2, [ :int, :int ], :int + attach_function :dup, [ :int ], :int + end + Buffer = FFI::Buffer + def self.build_args(args) + cmd = args.shift + cmd_args = args.map do |arg| + MemoryPointer.from_string(arg) + end + exec_args = MemoryPointer.new(:pointer, 1 + cmd_args.length + 1) + exec_cmd = MemoryPointer.from_string(cmd) + exec_args[0].put_pointer(0, exec_cmd) + cmd_args.each_with_index do |arg, i| + exec_args[i + 1].put_pointer(0, arg) + end + [ cmd, exec_args ] + end + public + def self.getpty(*args) + mfdp = Buffer.new :int + name = Buffer.new 1024 + # + # All the execv setup is done in the parent, since doing anything other than + # execv in the child after fork is really flakey + # + exec_cmd, exec_args = build_args(args) + pid = LibC.forkpty(mfdp, name, nil, nil) + raise "forkpty failed: #{LibC.strerror(FFI.errno)}" if pid < 0 + if pid == 0 + LibC.execvp(exec_cmd, exec_args) + exit 1 + end + masterfd = mfdp.get_int(0) + rfp = FFI::IO.for_fd(masterfd, "r") + wfp = FFI::IO.for_fd(LibC.dup(masterfd), "w") + if block_given? + yield rfp, wfp, pid + rfp.close unless rfp.closed? + wfp.close unless wfp.closed? + else + [ rfp, wfp, pid ] + end + end + def self.spawn(*args, &block) + self.getpty("/bin/sh", "-c", args[0], &block) + end +end +module LibC + extend FFI::Library + attach_function :close, [ :int ], :int + attach_function :write, [ :int, :buffer_in, :ulong ], :long + attach_function :read, [ :int, :buffer_out, :ulong ], :long +end +PTY.getpty("/bin/ls", "-alR", "/") { |rfd, wfd, pid| +#PTY.spawn("ls -laR /") { |rfd, wfd, pid| + puts "child pid=#{pid}" + while !rfd.eof? && (buf = rfd.gets) + puts "child: '#{buf.strip}'" + end +} diff --git a/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/qsort.rb b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/qsort.rb new file mode 100644 index 0000000..58622c1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/ffi-1.15.5/samples/qsort.rb @@ -0,0 +1,20 @@ +require 'ffi' + +module LibC + extend FFI::Library + ffi_lib FFI::Library::LIBC + callback :qsort_cmp, [ :pointer, :pointer ], :int + attach_function :qsort, [ :pointer, :ulong, :ulong, :qsort_cmp ], :int +end + +p = FFI::MemoryPointer.new(:int, 2) +p.put_array_of_int32(0, [ 2, 1 ]) +puts "ptr=#{p.inspect}" +puts "Before qsort #{p.get_array_of_int32(0, 2).join(', ')}" +LibC.qsort(p, 2, 4) do |p1, p2| + i1 = p1.get_int32(0) + i2 = p2.get_int32(0) + puts "In block: comparing #{i1} and #{i2}" + i1 < i2 ? -1 : i1 > i2 ? 1 : 0 +end +puts "After qsort #{p.get_array_of_int32(0, 2).join(', ')}" diff --git a/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/LICENSE.txt b/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/LICENSE.txt new file mode 100644 index 0000000..a009cae --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright (C) 1993-2013 Yukihiro Matsumoto. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. diff --git a/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/README.md b/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/README.md new file mode 100644 index 0000000..1a857d2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/README.md @@ -0,0 +1,42 @@ +# FileUtils + +Namespace for several file utility methods for copying, moving, removing, etc. + +## Installation + +Add this line to your application's Gemfile: + +```ruby +gem 'fileutils' +``` + +And then execute: + + $ bundle + +Or install it yourself as: + + $ gem install fileutils + +## Usage + +Just call `FileUtils` methods. For example: + +```ruby +FileUtils.mkdir("somedir") +# => ["somedir"] + +FileUtils.cd("/usr/bin") +FileUtils.pwd +# => "/usr/bin" +``` + +You can find a full method list in the [documentation](https://ruby-doc.org/stdlib/libdoc/fileutils/rdoc/FileUtils.html). + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/ruby/fileutils. + +## License + +The gem is available as open source under the terms of the [2-Clause BSD License](https://opensource.org/licenses/BSD-2-Clause). diff --git a/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/Rakefile b/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/Rakefile new file mode 100644 index 0000000..5a7afab --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/Rakefile @@ -0,0 +1,17 @@ +require "bundler/gem_tasks" +require "rake/testtask" + +Rake::TestTask.new(:test) do |t| + t.libs << "test/lib" + t.ruby_opts << "-rhelper" + t.test_files = FileList["test/**/test_*.rb"] +end + +task :sync_tool do + require 'fileutils' + FileUtils.cp "../ruby/tool/lib/core_assertions.rb", "./test/lib" + FileUtils.cp "../ruby/tool/lib/envutil.rb", "./test/lib" + FileUtils.cp "../ruby/tool/lib/find_executable.rb", "./test/lib" +end + +task :default => :test diff --git a/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/fileutils.gemspec b/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/fileutils.gemspec new file mode 100644 index 0000000..76baea3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/fileutils.gemspec @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +source_version = ["", "lib/"].find do |dir| + begin + break File.open(File.join(__dir__, "#{dir}fileutils.rb")) {|f| + f.gets("\n VERSION = ") + f.gets[/\s*"(.+)"/, 1] + } + rescue Errno::ENOENT + end +end + +Gem::Specification.new do |s| + s.name = "fileutils" + s.version = source_version + s.summary = "Several file utility methods for copying, moving, removing, etc." + s.description = "Several file utility methods for copying, moving, removing, etc." + + s.require_path = %w{lib} + s.files = ["LICENSE.txt", "README.md", "Rakefile", "fileutils.gemspec", "lib/fileutils.rb"] + s.required_ruby_version = ">= 2.5.0" + + s.authors = ["Minero Aoki"] + s.email = [nil] + s.homepage = "https://github.com/ruby/fileutils" + s.licenses = ["Ruby", "BSD-2-Clause"] + + s.metadata = { + "source_code_uri" => "https://github.com/ruby/fileutils" + } +end diff --git a/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/lib/fileutils.rb b/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/lib/fileutils.rb new file mode 100644 index 0000000..c115005 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/fileutils-1.6.0/lib/fileutils.rb @@ -0,0 +1,1753 @@ +# frozen_string_literal: true + +begin + require 'rbconfig' +rescue LoadError + # for make mjit-headers +end + +# +# = fileutils.rb +# +# Copyright (c) 2000-2007 Minero Aoki +# +# This program is free software. +# You can distribute/modify this program under the same terms of ruby. +# +# == module FileUtils +# +# Namespace for several file utility methods for copying, moving, removing, etc. +# +# === Module Functions +# +# require 'fileutils' +# +# FileUtils.cd(dir, **options) +# FileUtils.cd(dir, **options) {|dir| block } +# FileUtils.pwd() +# FileUtils.mkdir(dir, **options) +# FileUtils.mkdir(list, **options) +# FileUtils.mkdir_p(dir, **options) +# FileUtils.mkdir_p(list, **options) +# FileUtils.rmdir(dir, **options) +# FileUtils.rmdir(list, **options) +# FileUtils.ln(target, link, **options) +# FileUtils.ln(targets, dir, **options) +# FileUtils.ln_s(target, link, **options) +# FileUtils.ln_s(targets, dir, **options) +# FileUtils.ln_sf(target, link, **options) +# FileUtils.cp(src, dest, **options) +# FileUtils.cp(list, dir, **options) +# FileUtils.cp_r(src, dest, **options) +# FileUtils.cp_r(list, dir, **options) +# FileUtils.mv(src, dest, **options) +# FileUtils.mv(list, dir, **options) +# FileUtils.rm(list, **options) +# FileUtils.rm_r(list, **options) +# FileUtils.rm_rf(list, **options) +# FileUtils.install(src, dest, **options) +# FileUtils.chmod(mode, list, **options) +# FileUtils.chmod_R(mode, list, **options) +# FileUtils.chown(user, group, list, **options) +# FileUtils.chown_R(user, group, list, **options) +# FileUtils.touch(list, **options) +# +# Possible options are: +# +# :force :: forced operation (rewrite files if exist, remove +# directories if not empty, etc.); +# :verbose :: print command to be run, in bash syntax, before +# performing it; +# :preserve :: preserve object's group, user and modification +# time on copying; +# :noop :: no changes are made (usable in combination with +# :verbose which will print the command to run) +# +# Each method documents the options that it honours. See also ::commands, +# ::options and ::options_of methods to introspect which command have which +# options. +# +# All methods that have the concept of a "source" file or directory can take +# either one file or a list of files in that argument. See the method +# documentation for examples. +# +# There are some `low level' methods, which do not accept keyword arguments: +# +# FileUtils.copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false) +# FileUtils.copy_file(src, dest, preserve = false, dereference = true) +# FileUtils.copy_stream(srcstream, deststream) +# FileUtils.remove_entry(path, force = false) +# FileUtils.remove_entry_secure(path, force = false) +# FileUtils.remove_file(path, force = false) +# FileUtils.compare_file(path_a, path_b) +# FileUtils.compare_stream(stream_a, stream_b) +# FileUtils.uptodate?(file, cmp_list) +# +# == module FileUtils::Verbose +# +# This module has all methods of FileUtils module, but it outputs messages +# before acting. This equates to passing the :verbose flag to methods +# in FileUtils. +# +# == module FileUtils::NoWrite +# +# This module has all methods of FileUtils module, but never changes +# files/directories. This equates to passing the :noop flag to methods +# in FileUtils. +# +# == module FileUtils::DryRun +# +# This module has all methods of FileUtils module, but never changes +# files/directories. This equates to passing the :noop and +# :verbose flags to methods in FileUtils. +# +module FileUtils + VERSION = "1.6.0" + + def self.private_module_function(name) #:nodoc: + module_function name + private_class_method name + end + + # + # Returns the name of the current directory. + # + def pwd + Dir.pwd + end + module_function :pwd + + alias getwd pwd + module_function :getwd + + # + # Changes the current directory to the directory +dir+. + # + # If this method is called with block, resumes to the previous + # working directory after the block execution has finished. + # + # FileUtils.cd('/') # change directory + # + # FileUtils.cd('/', verbose: true) # change directory and report it + # + # FileUtils.cd('/') do # change directory + # # ... # do something + # end # return to original directory + # + def cd(dir, verbose: nil, &block) # :yield: dir + fu_output_message "cd #{dir}" if verbose + result = Dir.chdir(dir, &block) + fu_output_message 'cd -' if verbose and block + result + end + module_function :cd + + alias chdir cd + module_function :chdir + + # + # Returns true if +new+ is newer than all +old_list+. + # Non-existent files are older than any file. + # + # FileUtils.uptodate?('hello.o', %w(hello.c hello.h)) or \ + # system 'make hello.o' + # + def uptodate?(new, old_list) + return false unless File.exist?(new) + new_time = File.mtime(new) + old_list.each do |old| + if File.exist?(old) + return false unless new_time > File.mtime(old) + end + end + true + end + module_function :uptodate? + + def remove_trailing_slash(dir) #:nodoc: + dir == '/' ? dir : dir.chomp(?/) + end + private_module_function :remove_trailing_slash + + # + # Creates one or more directories. + # + # FileUtils.mkdir 'test' + # FileUtils.mkdir %w(tmp data) + # FileUtils.mkdir 'notexist', noop: true # Does not really create. + # FileUtils.mkdir 'tmp', mode: 0700 + # + def mkdir(list, mode: nil, noop: nil, verbose: nil) + list = fu_list(list) + fu_output_message "mkdir #{mode ? ('-m %03o ' % mode) : ''}#{list.join ' '}" if verbose + return if noop + + list.each do |dir| + fu_mkdir dir, mode + end + end + module_function :mkdir + + # + # Creates a directory and all its parent directories. + # For example, + # + # FileUtils.mkdir_p '/usr/local/lib/ruby' + # + # causes to make following directories, if they do not exist. + # + # * /usr + # * /usr/local + # * /usr/local/lib + # * /usr/local/lib/ruby + # + # You can pass several directories at a time in a list. + # + def mkdir_p(list, mode: nil, noop: nil, verbose: nil) + list = fu_list(list) + fu_output_message "mkdir -p #{mode ? ('-m %03o ' % mode) : ''}#{list.join ' '}" if verbose + return *list if noop + + list.each do |item| + path = remove_trailing_slash(item) + + stack = [] + until File.directory?(path) + stack.push path + path = File.dirname(path) + end + stack.reverse_each do |dir| + begin + fu_mkdir dir, mode + rescue SystemCallError + raise unless File.directory?(dir) + end + end + end + + return *list + end + module_function :mkdir_p + + alias mkpath mkdir_p + alias makedirs mkdir_p + module_function :mkpath + module_function :makedirs + + def fu_mkdir(path, mode) #:nodoc: + path = remove_trailing_slash(path) + if mode + Dir.mkdir path, mode + File.chmod mode, path + else + Dir.mkdir path + end + end + private_module_function :fu_mkdir + + # + # Removes one or more directories. + # + # FileUtils.rmdir 'somedir' + # FileUtils.rmdir %w(somedir anydir otherdir) + # # Does not really remove directory; outputs message. + # FileUtils.rmdir 'somedir', verbose: true, noop: true + # + def rmdir(list, parents: nil, noop: nil, verbose: nil) + list = fu_list(list) + fu_output_message "rmdir #{parents ? '-p ' : ''}#{list.join ' '}" if verbose + return if noop + list.each do |dir| + Dir.rmdir(dir = remove_trailing_slash(dir)) + if parents + begin + until (parent = File.dirname(dir)) == '.' or parent == dir + dir = parent + Dir.rmdir(dir) + end + rescue Errno::ENOTEMPTY, Errno::EEXIST, Errno::ENOENT + end + end + end + end + module_function :rmdir + + # + # :call-seq: + # FileUtils.ln(target, link, force: nil, noop: nil, verbose: nil) + # FileUtils.ln(target, dir, force: nil, noop: nil, verbose: nil) + # FileUtils.ln(targets, dir, force: nil, noop: nil, verbose: nil) + # + # In the first form, creates a hard link +link+ which points to +target+. + # If +link+ already exists, raises Errno::EEXIST. + # But if the +force+ option is set, overwrites +link+. + # + # FileUtils.ln 'gcc', 'cc', verbose: true + # FileUtils.ln '/usr/bin/emacs21', '/usr/bin/emacs' + # + # In the second form, creates a link +dir/target+ pointing to +target+. + # In the third form, creates several hard links in the directory +dir+, + # pointing to each item in +targets+. + # If +dir+ is not a directory, raises Errno::ENOTDIR. + # + # FileUtils.cd '/sbin' + # FileUtils.ln %w(cp mv mkdir), '/bin' # Now /sbin/cp and /bin/cp are linked. + # + def ln(src, dest, force: nil, noop: nil, verbose: nil) + fu_output_message "ln#{force ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if verbose + return if noop + fu_each_src_dest0(src, dest) do |s,d| + remove_file d, true if force + File.link s, d + end + end + module_function :ln + + alias link ln + module_function :link + + # + # Hard link +src+ to +dest+. If +src+ is a directory, this method links + # all its contents recursively. If +dest+ is a directory, links + # +src+ to +dest/src+. + # + # +src+ can be a list of files. + # + # If +dereference_root+ is true, this method dereference tree root. + # + # If +remove_destination+ is true, this method removes each destination file before copy. + # + # FileUtils.rm_r site_ruby + '/mylib', force: true + # FileUtils.cp_lr 'lib/', site_ruby + '/mylib' + # + # # Examples of linking several files to target directory. + # FileUtils.cp_lr %w(mail.rb field.rb debug/), site_ruby + '/tmail' + # FileUtils.cp_lr Dir.glob('*.rb'), '/home/aamine/lib/ruby', noop: true, verbose: true + # + # # If you want to link all contents of a directory instead of the + # # directory itself, c.f. src/x -> dest/x, src/y -> dest/y, + # # use the following code. + # FileUtils.cp_lr 'src/.', 'dest' # cp_lr('src', 'dest') makes dest/src, but this doesn't. + # + def cp_lr(src, dest, noop: nil, verbose: nil, + dereference_root: true, remove_destination: false) + fu_output_message "cp -lr#{remove_destination ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if verbose + return if noop + fu_each_src_dest(src, dest) do |s, d| + link_entry s, d, dereference_root, remove_destination + end + end + module_function :cp_lr + + # + # :call-seq: + # FileUtils.ln_s(target, link, force: nil, noop: nil, verbose: nil) + # FileUtils.ln_s(target, dir, force: nil, noop: nil, verbose: nil) + # FileUtils.ln_s(targets, dir, force: nil, noop: nil, verbose: nil) + # + # In the first form, creates a symbolic link +link+ which points to +target+. + # If +link+ already exists, raises Errno::EEXIST. + # But if the force option is set, overwrites +link+. + # + # FileUtils.ln_s '/usr/bin/ruby', '/usr/local/bin/ruby' + # FileUtils.ln_s 'verylongsourcefilename.c', 'c', force: true + # + # In the second form, creates a link +dir/target+ pointing to +target+. + # In the third form, creates several symbolic links in the directory +dir+, + # pointing to each item in +targets+. + # If +dir+ is not a directory, raises Errno::ENOTDIR. + # + # FileUtils.ln_s Dir.glob('/bin/*.rb'), '/home/foo/bin' + # + def ln_s(src, dest, force: nil, noop: nil, verbose: nil) + fu_output_message "ln -s#{force ? 'f' : ''} #{[src,dest].flatten.join ' '}" if verbose + return if noop + fu_each_src_dest0(src, dest) do |s,d| + remove_file d, true if force + File.symlink s, d + end + end + module_function :ln_s + + alias symlink ln_s + module_function :symlink + + # + # :call-seq: + # FileUtils.ln_sf(*args) + # + # Same as + # + # FileUtils.ln_s(*args, force: true) + # + def ln_sf(src, dest, noop: nil, verbose: nil) + ln_s src, dest, force: true, noop: noop, verbose: verbose + end + module_function :ln_sf + + # + # Hard links a file system entry +src+ to +dest+. + # If +src+ is a directory, this method links its contents recursively. + # + # Both of +src+ and +dest+ must be a path name. + # +src+ must exist, +dest+ must not exist. + # + # If +dereference_root+ is true, this method dereferences the tree root. + # + # If +remove_destination+ is true, this method removes each destination file before copy. + # + def link_entry(src, dest, dereference_root = false, remove_destination = false) + Entry_.new(src, nil, dereference_root).traverse do |ent| + destent = Entry_.new(dest, ent.rel, false) + File.unlink destent.path if remove_destination && File.file?(destent.path) + ent.link destent.path + end + end + module_function :link_entry + + # + # Copies a file content +src+ to +dest+. If +dest+ is a directory, + # copies +src+ to +dest/src+. + # + # If +src+ is a list of files, then +dest+ must be a directory. + # + # FileUtils.cp 'eval.c', 'eval.c.org' + # FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6' + # FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', verbose: true + # FileUtils.cp 'symlink', 'dest' # copy content, "dest" is not a symlink + # + def cp(src, dest, preserve: nil, noop: nil, verbose: nil) + fu_output_message "cp#{preserve ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if verbose + return if noop + fu_each_src_dest(src, dest) do |s, d| + copy_file s, d, preserve + end + end + module_function :cp + + alias copy cp + module_function :copy + + # + # Copies +src+ to +dest+. If +src+ is a directory, this method copies + # all its contents recursively. If +dest+ is a directory, copies + # +src+ to +dest/src+. + # + # +src+ can be a list of files. + # + # If +dereference_root+ is true, this method dereference tree root. + # + # If +remove_destination+ is true, this method removes each destination file before copy. + # + # # Installing Ruby library "mylib" under the site_ruby + # FileUtils.rm_r site_ruby + '/mylib', force: true + # FileUtils.cp_r 'lib/', site_ruby + '/mylib' + # + # # Examples of copying several files to target directory. + # FileUtils.cp_r %w(mail.rb field.rb debug/), site_ruby + '/tmail' + # FileUtils.cp_r Dir.glob('*.rb'), '/home/foo/lib/ruby', noop: true, verbose: true + # + # # If you want to copy all contents of a directory instead of the + # # directory itself, c.f. src/x -> dest/x, src/y -> dest/y, + # # use following code. + # FileUtils.cp_r 'src/.', 'dest' # cp_r('src', 'dest') makes dest/src, + # # but this doesn't. + # + def cp_r(src, dest, preserve: nil, noop: nil, verbose: nil, + dereference_root: true, remove_destination: nil) + fu_output_message "cp -r#{preserve ? 'p' : ''}#{remove_destination ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if verbose + return if noop + fu_each_src_dest(src, dest) do |s, d| + copy_entry s, d, preserve, dereference_root, remove_destination + end + end + module_function :cp_r + + # + # Copies a file system entry +src+ to +dest+. + # If +src+ is a directory, this method copies its contents recursively. + # This method preserves file types, c.f. symlink, directory... + # (FIFO, device files and etc. are not supported yet) + # + # Both of +src+ and +dest+ must be a path name. + # +src+ must exist, +dest+ must not exist. + # + # If +preserve+ is true, this method preserves owner, group, and + # modified time. Permissions are copied regardless +preserve+. + # + # If +dereference_root+ is true, this method dereference tree root. + # + # If +remove_destination+ is true, this method removes each destination file before copy. + # + def copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false) + if dereference_root + src = File.realpath(src) + end + + Entry_.new(src, nil, false).wrap_traverse(proc do |ent| + destent = Entry_.new(dest, ent.rel, false) + File.unlink destent.path if remove_destination && (File.file?(destent.path) || File.symlink?(destent.path)) + ent.copy destent.path + end, proc do |ent| + destent = Entry_.new(dest, ent.rel, false) + ent.copy_metadata destent.path if preserve + end) + end + module_function :copy_entry + + # + # Copies file contents of +src+ to +dest+. + # Both of +src+ and +dest+ must be a path name. + # + def copy_file(src, dest, preserve = false, dereference = true) + ent = Entry_.new(src, nil, dereference) + ent.copy_file dest + ent.copy_metadata dest if preserve + end + module_function :copy_file + + # + # Copies stream +src+ to +dest+. + # +src+ must respond to #read(n) and + # +dest+ must respond to #write(str). + # + def copy_stream(src, dest) + IO.copy_stream(src, dest) + end + module_function :copy_stream + + # + # Moves file(s) +src+ to +dest+. If +file+ and +dest+ exist on the different + # disk partition, the file is copied then the original file is removed. + # + # FileUtils.mv 'badname.rb', 'goodname.rb' + # FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', force: true # no error + # + # FileUtils.mv %w(junk.txt dust.txt), '/home/foo/.trash/' + # FileUtils.mv Dir.glob('test*.rb'), 'test', noop: true, verbose: true + # + def mv(src, dest, force: nil, noop: nil, verbose: nil, secure: nil) + fu_output_message "mv#{force ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if verbose + return if noop + fu_each_src_dest(src, dest) do |s, d| + destent = Entry_.new(d, nil, true) + begin + if destent.exist? + if destent.directory? + raise Errno::EEXIST, d + end + end + begin + File.rename s, d + rescue Errno::EXDEV, + Errno::EPERM # move from unencrypted to encrypted dir (ext4) + copy_entry s, d, true + if secure + remove_entry_secure s, force + else + remove_entry s, force + end + end + rescue SystemCallError + raise unless force + end + end + end + module_function :mv + + alias move mv + module_function :move + + # + # Remove file(s) specified in +list+. This method cannot remove directories. + # All StandardErrors are ignored when the :force option is set. + # + # FileUtils.rm %w( junk.txt dust.txt ) + # FileUtils.rm Dir.glob('*.so') + # FileUtils.rm 'NotExistFile', force: true # never raises exception + # + def rm(list, force: nil, noop: nil, verbose: nil) + list = fu_list(list) + fu_output_message "rm#{force ? ' -f' : ''} #{list.join ' '}" if verbose + return if noop + + list.each do |path| + remove_file path, force + end + end + module_function :rm + + alias remove rm + module_function :remove + + # + # Equivalent to + # + # FileUtils.rm(list, force: true) + # + def rm_f(list, noop: nil, verbose: nil) + rm list, force: true, noop: noop, verbose: verbose + end + module_function :rm_f + + alias safe_unlink rm_f + module_function :safe_unlink + + # + # remove files +list+[0] +list+[1]... If +list+[n] is a directory, + # removes its all contents recursively. This method ignores + # StandardError when :force option is set. + # + # FileUtils.rm_r Dir.glob('/tmp/*') + # FileUtils.rm_r 'some_dir', force: true + # + # WARNING: This method causes local vulnerability + # if one of parent directories or removing directory tree are world + # writable (including /tmp, whose permission is 1777), and the current + # process has strong privilege such as Unix super user (root), and the + # system has symbolic link. For secure removing, read the documentation + # of remove_entry_secure carefully, and set :secure option to true. + # Default is secure: false. + # + # NOTE: This method calls remove_entry_secure if :secure option is set. + # See also remove_entry_secure. + # + def rm_r(list, force: nil, noop: nil, verbose: nil, secure: nil) + list = fu_list(list) + fu_output_message "rm -r#{force ? 'f' : ''} #{list.join ' '}" if verbose + return if noop + list.each do |path| + if secure + remove_entry_secure path, force + else + remove_entry path, force + end + end + end + module_function :rm_r + + # + # Equivalent to + # + # FileUtils.rm_r(list, force: true) + # + # WARNING: This method causes local vulnerability. + # Read the documentation of rm_r first. + # + def rm_rf(list, noop: nil, verbose: nil, secure: nil) + rm_r list, force: true, noop: noop, verbose: verbose, secure: secure + end + module_function :rm_rf + + alias rmtree rm_rf + module_function :rmtree + + # + # This method removes a file system entry +path+. +path+ shall be a + # regular file, a directory, or something. If +path+ is a directory, + # remove it recursively. This method is required to avoid TOCTTOU + # (time-of-check-to-time-of-use) local security vulnerability of rm_r. + # #rm_r causes security hole when: + # + # * Parent directory is world writable (including /tmp). + # * Removing directory tree includes world writable directory. + # * The system has symbolic link. + # + # To avoid this security hole, this method applies special preprocess. + # If +path+ is a directory, this method chown(2) and chmod(2) all + # removing directories. This requires the current process is the + # owner of the removing whole directory tree, or is the super user (root). + # + # WARNING: You must ensure that *ALL* parent directories cannot be + # moved by other untrusted users. For example, parent directories + # should not be owned by untrusted users, and should not be world + # writable except when the sticky bit set. + # + # WARNING: Only the owner of the removing directory tree, or Unix super + # user (root) should invoke this method. Otherwise this method does not + # work. + # + # For details of this security vulnerability, see Perl's case: + # + # * https://cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2005-0448 + # * https://cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2004-0452 + # + # For fileutils.rb, this vulnerability is reported in [ruby-dev:26100]. + # + def remove_entry_secure(path, force = false) + unless fu_have_symlink? + remove_entry path, force + return + end + fullpath = File.expand_path(path) + st = File.lstat(fullpath) + unless st.directory? + File.unlink fullpath + return + end + # is a directory. + parent_st = File.stat(File.dirname(fullpath)) + unless parent_st.world_writable? + remove_entry path, force + return + end + unless parent_st.sticky? + raise ArgumentError, "parent directory is world writable, FileUtils#remove_entry_secure does not work; abort: #{path.inspect} (parent directory mode #{'%o' % parent_st.mode})" + end + + # freeze tree root + euid = Process.euid + dot_file = fullpath + "/." + begin + File.open(dot_file) {|f| + unless fu_stat_identical_entry?(st, f.stat) + # symlink (TOC-to-TOU attack?) + File.unlink fullpath + return + end + f.chown euid, -1 + f.chmod 0700 + } + rescue Errno::EISDIR # JRuby in non-native mode can't open files as dirs + File.lstat(dot_file).tap {|fstat| + unless fu_stat_identical_entry?(st, fstat) + # symlink (TOC-to-TOU attack?) + File.unlink fullpath + return + end + File.chown euid, -1, dot_file + File.chmod 0700, dot_file + } + end + + unless fu_stat_identical_entry?(st, File.lstat(fullpath)) + # TOC-to-TOU attack? + File.unlink fullpath + return + end + + # ---- tree root is frozen ---- + root = Entry_.new(path) + root.preorder_traverse do |ent| + if ent.directory? + ent.chown euid, -1 + ent.chmod 0700 + end + end + root.postorder_traverse do |ent| + begin + ent.remove + rescue + raise unless force + end + end + rescue + raise unless force + end + module_function :remove_entry_secure + + def fu_have_symlink? #:nodoc: + File.symlink nil, nil + rescue NotImplementedError + return false + rescue TypeError + return true + end + private_module_function :fu_have_symlink? + + def fu_stat_identical_entry?(a, b) #:nodoc: + a.dev == b.dev and a.ino == b.ino + end + private_module_function :fu_stat_identical_entry? + + # + # This method removes a file system entry +path+. + # +path+ might be a regular file, a directory, or something. + # If +path+ is a directory, remove it recursively. + # + # See also remove_entry_secure. + # + def remove_entry(path, force = false) + Entry_.new(path).postorder_traverse do |ent| + begin + ent.remove + rescue + raise unless force + end + end + rescue + raise unless force + end + module_function :remove_entry + + # + # Removes a file +path+. + # This method ignores StandardError if +force+ is true. + # + def remove_file(path, force = false) + Entry_.new(path).remove_file + rescue + raise unless force + end + module_function :remove_file + + # + # Removes a directory +dir+ and its contents recursively. + # This method ignores StandardError if +force+ is true. + # + def remove_dir(path, force = false) + remove_entry path, force # FIXME?? check if it is a directory + end + module_function :remove_dir + + # + # Returns true if the contents of a file +a+ and a file +b+ are identical. + # + # FileUtils.compare_file('somefile', 'somefile') #=> true + # FileUtils.compare_file('/dev/null', '/dev/urandom') #=> false + # + def compare_file(a, b) + return false unless File.size(a) == File.size(b) + File.open(a, 'rb') {|fa| + File.open(b, 'rb') {|fb| + return compare_stream(fa, fb) + } + } + end + module_function :compare_file + + alias identical? compare_file + alias cmp compare_file + module_function :identical? + module_function :cmp + + # + # Returns true if the contents of a stream +a+ and +b+ are identical. + # + def compare_stream(a, b) + bsize = fu_stream_blksize(a, b) + + sa = String.new(capacity: bsize) + sb = String.new(capacity: bsize) + + begin + a.read(bsize, sa) + b.read(bsize, sb) + return true if sa.empty? && sb.empty? + end while sa == sb + false + end + module_function :compare_stream + + # + # If +src+ is not same as +dest+, copies it and changes the permission + # mode to +mode+. If +dest+ is a directory, destination is +dest+/+src+. + # This method removes destination before copy. + # + # FileUtils.install 'ruby', '/usr/local/bin/ruby', mode: 0755, verbose: true + # FileUtils.install 'lib.rb', '/usr/local/lib/ruby/site_ruby', verbose: true + # + def install(src, dest, mode: nil, owner: nil, group: nil, preserve: nil, + noop: nil, verbose: nil) + if verbose + msg = +"install -c" + msg << ' -p' if preserve + msg << ' -m ' << mode_to_s(mode) if mode + msg << " -o #{owner}" if owner + msg << " -g #{group}" if group + msg << ' ' << [src,dest].flatten.join(' ') + fu_output_message msg + end + return if noop + uid = fu_get_uid(owner) + gid = fu_get_gid(group) + fu_each_src_dest(src, dest) do |s, d| + st = File.stat(s) + unless File.exist?(d) and compare_file(s, d) + remove_file d, true + copy_file s, d + File.utime st.atime, st.mtime, d if preserve + File.chmod fu_mode(mode, st), d if mode + File.chown uid, gid, d if uid or gid + end + end + end + module_function :install + + def user_mask(target) #:nodoc: + target.each_char.inject(0) do |mask, chr| + case chr + when "u" + mask | 04700 + when "g" + mask | 02070 + when "o" + mask | 01007 + when "a" + mask | 07777 + else + raise ArgumentError, "invalid `who' symbol in file mode: #{chr}" + end + end + end + private_module_function :user_mask + + def apply_mask(mode, user_mask, op, mode_mask) #:nodoc: + case op + when '=' + (mode & ~user_mask) | (user_mask & mode_mask) + when '+' + mode | (user_mask & mode_mask) + when '-' + mode & ~(user_mask & mode_mask) + end + end + private_module_function :apply_mask + + def symbolic_modes_to_i(mode_sym, path) #:nodoc: + path = File.stat(path) unless File::Stat === path + mode = path.mode + mode_sym.split(/,/).inject(mode & 07777) do |current_mode, clause| + target, *actions = clause.split(/([=+-])/) + raise ArgumentError, "invalid file mode: #{mode_sym}" if actions.empty? + target = 'a' if target.empty? + user_mask = user_mask(target) + actions.each_slice(2) do |op, perm| + need_apply = op == '=' + mode_mask = (perm || '').each_char.inject(0) do |mask, chr| + case chr + when "r" + mask | 0444 + when "w" + mask | 0222 + when "x" + mask | 0111 + when "X" + if path.directory? + mask | 0111 + else + mask + end + when "s" + mask | 06000 + when "t" + mask | 01000 + when "u", "g", "o" + if mask.nonzero? + current_mode = apply_mask(current_mode, user_mask, op, mask) + end + need_apply = false + copy_mask = user_mask(chr) + (current_mode & copy_mask) / (copy_mask & 0111) * (user_mask & 0111) + else + raise ArgumentError, "invalid `perm' symbol in file mode: #{chr}" + end + end + + if mode_mask.nonzero? || need_apply + current_mode = apply_mask(current_mode, user_mask, op, mode_mask) + end + end + current_mode + end + end + private_module_function :symbolic_modes_to_i + + def fu_mode(mode, path) #:nodoc: + mode.is_a?(String) ? symbolic_modes_to_i(mode, path) : mode + end + private_module_function :fu_mode + + def mode_to_s(mode) #:nodoc: + mode.is_a?(String) ? mode : "%o" % mode + end + private_module_function :mode_to_s + + # + # Changes permission bits on the named files (in +list+) to the bit pattern + # represented by +mode+. + # + # +mode+ is the symbolic and absolute mode can be used. + # + # Absolute mode is + # FileUtils.chmod 0755, 'somecommand' + # FileUtils.chmod 0644, %w(my.rb your.rb his.rb her.rb) + # FileUtils.chmod 0755, '/usr/bin/ruby', verbose: true + # + # Symbolic mode is + # FileUtils.chmod "u=wrx,go=rx", 'somecommand' + # FileUtils.chmod "u=wr,go=rr", %w(my.rb your.rb his.rb her.rb) + # FileUtils.chmod "u=wrx,go=rx", '/usr/bin/ruby', verbose: true + # + # "a" :: is user, group, other mask. + # "u" :: is user's mask. + # "g" :: is group's mask. + # "o" :: is other's mask. + # "w" :: is write permission. + # "r" :: is read permission. + # "x" :: is execute permission. + # "X" :: + # is execute permission for directories only, must be used in conjunction with "+" + # "s" :: is uid, gid. + # "t" :: is sticky bit. + # "+" :: is added to a class given the specified mode. + # "-" :: Is removed from a given class given mode. + # "=" :: Is the exact nature of the class will be given a specified mode. + + def chmod(mode, list, noop: nil, verbose: nil) + list = fu_list(list) + fu_output_message sprintf('chmod %s %s', mode_to_s(mode), list.join(' ')) if verbose + return if noop + list.each do |path| + Entry_.new(path).chmod(fu_mode(mode, path)) + end + end + module_function :chmod + + # + # Changes permission bits on the named files (in +list+) + # to the bit pattern represented by +mode+. + # + # FileUtils.chmod_R 0700, "/tmp/app.#{$$}" + # FileUtils.chmod_R "u=wrx", "/tmp/app.#{$$}" + # + def chmod_R(mode, list, noop: nil, verbose: nil, force: nil) + list = fu_list(list) + fu_output_message sprintf('chmod -R%s %s %s', + (force ? 'f' : ''), + mode_to_s(mode), list.join(' ')) if verbose + return if noop + list.each do |root| + Entry_.new(root).traverse do |ent| + begin + ent.chmod(fu_mode(mode, ent.path)) + rescue + raise unless force + end + end + end + end + module_function :chmod_R + + # + # Changes owner and group on the named files (in +list+) + # to the user +user+ and the group +group+. +user+ and +group+ + # may be an ID (Integer/String) or a name (String). + # If +user+ or +group+ is nil, this method does not change + # the attribute. + # + # FileUtils.chown 'root', 'staff', '/usr/local/bin/ruby' + # FileUtils.chown nil, 'bin', Dir.glob('/usr/bin/*'), verbose: true + # + def chown(user, group, list, noop: nil, verbose: nil) + list = fu_list(list) + fu_output_message sprintf('chown %s %s', + (group ? "#{user}:#{group}" : user || ':'), + list.join(' ')) if verbose + return if noop + uid = fu_get_uid(user) + gid = fu_get_gid(group) + list.each do |path| + Entry_.new(path).chown uid, gid + end + end + module_function :chown + + # + # Changes owner and group on the named files (in +list+) + # to the user +user+ and the group +group+ recursively. + # +user+ and +group+ may be an ID (Integer/String) or + # a name (String). If +user+ or +group+ is nil, this + # method does not change the attribute. + # + # FileUtils.chown_R 'www', 'www', '/var/www/htdocs' + # FileUtils.chown_R 'cvs', 'cvs', '/var/cvs', verbose: true + # + def chown_R(user, group, list, noop: nil, verbose: nil, force: nil) + list = fu_list(list) + fu_output_message sprintf('chown -R%s %s %s', + (force ? 'f' : ''), + (group ? "#{user}:#{group}" : user || ':'), + list.join(' ')) if verbose + return if noop + uid = fu_get_uid(user) + gid = fu_get_gid(group) + list.each do |root| + Entry_.new(root).traverse do |ent| + begin + ent.chown uid, gid + rescue + raise unless force + end + end + end + end + module_function :chown_R + + def fu_get_uid(user) #:nodoc: + return nil unless user + case user + when Integer + user + when /\A\d+\z/ + user.to_i + else + require 'etc' + Etc.getpwnam(user) ? Etc.getpwnam(user).uid : nil + end + end + private_module_function :fu_get_uid + + def fu_get_gid(group) #:nodoc: + return nil unless group + case group + when Integer + group + when /\A\d+\z/ + group.to_i + else + require 'etc' + Etc.getgrnam(group) ? Etc.getgrnam(group).gid : nil + end + end + private_module_function :fu_get_gid + + # + # Updates modification time (mtime) and access time (atime) of file(s) in + # +list+. Files are created if they don't exist. + # + # FileUtils.touch 'timestamp' + # FileUtils.touch Dir.glob('*.c'); system 'make' + # + def touch(list, noop: nil, verbose: nil, mtime: nil, nocreate: nil) + list = fu_list(list) + t = mtime + if verbose + fu_output_message "touch #{nocreate ? '-c ' : ''}#{t ? t.strftime('-t %Y%m%d%H%M.%S ') : ''}#{list.join ' '}" + end + return if noop + list.each do |path| + created = nocreate + begin + File.utime(t, t, path) + rescue Errno::ENOENT + raise if created + File.open(path, 'a') { + ; + } + created = true + retry if t + end + end + end + module_function :touch + + private + + module StreamUtils_ + private + + case (defined?(::RbConfig) ? ::RbConfig::CONFIG['host_os'] : ::RUBY_PLATFORM) + when /mswin|mingw/ + def fu_windows?; true end + else + def fu_windows?; false end + end + + def fu_copy_stream0(src, dest, blksize = nil) #:nodoc: + IO.copy_stream(src, dest) + end + + def fu_stream_blksize(*streams) + streams.each do |s| + next unless s.respond_to?(:stat) + size = fu_blksize(s.stat) + return size if size + end + fu_default_blksize() + end + + def fu_blksize(st) + s = st.blksize + return nil unless s + return nil if s == 0 + s + end + + def fu_default_blksize + 1024 + end + end + + include StreamUtils_ + extend StreamUtils_ + + class Entry_ #:nodoc: internal use only + include StreamUtils_ + + def initialize(a, b = nil, deref = false) + @prefix = @rel = @path = nil + if b + @prefix = a + @rel = b + else + @path = a + end + @deref = deref + @stat = nil + @lstat = nil + end + + def inspect + "\#<#{self.class} #{path()}>" + end + + def path + if @path + File.path(@path) + else + join(@prefix, @rel) + end + end + + def prefix + @prefix || @path + end + + def rel + @rel + end + + def dereference? + @deref + end + + def exist? + begin + lstat + true + rescue Errno::ENOENT + false + end + end + + def file? + s = lstat! + s and s.file? + end + + def directory? + s = lstat! + s and s.directory? + end + + def symlink? + s = lstat! + s and s.symlink? + end + + def chardev? + s = lstat! + s and s.chardev? + end + + def blockdev? + s = lstat! + s and s.blockdev? + end + + def socket? + s = lstat! + s and s.socket? + end + + def pipe? + s = lstat! + s and s.pipe? + end + + S_IF_DOOR = 0xD000 + + def door? + s = lstat! + s and (s.mode & 0xF000 == S_IF_DOOR) + end + + def entries + opts = {} + opts[:encoding] = fu_windows? ? ::Encoding::UTF_8 : path.encoding + + files = Dir.children(path, **opts) + + untaint = RUBY_VERSION < '2.7' + files.map {|n| Entry_.new(prefix(), join(rel(), untaint ? n.untaint : n)) } + end + + def stat + return @stat if @stat + if lstat() and lstat().symlink? + @stat = File.stat(path()) + else + @stat = lstat() + end + @stat + end + + def stat! + return @stat if @stat + if lstat! and lstat!.symlink? + @stat = File.stat(path()) + else + @stat = lstat! + end + @stat + rescue SystemCallError + nil + end + + def lstat + if dereference? + @lstat ||= File.stat(path()) + else + @lstat ||= File.lstat(path()) + end + end + + def lstat! + lstat() + rescue SystemCallError + nil + end + + def chmod(mode) + if symlink? + File.lchmod mode, path() if have_lchmod? + else + File.chmod mode, path() + end + rescue Errno::EOPNOTSUPP + end + + def chown(uid, gid) + if symlink? + File.lchown uid, gid, path() if have_lchown? + else + File.chown uid, gid, path() + end + end + + def link(dest) + case + when directory? + if !File.exist?(dest) and descendant_directory?(dest, path) + raise ArgumentError, "cannot link directory %s to itself %s" % [path, dest] + end + begin + Dir.mkdir dest + rescue + raise unless File.directory?(dest) + end + else + File.link path(), dest + end + end + + def copy(dest) + lstat + case + when file? + copy_file dest + when directory? + if !File.exist?(dest) and descendant_directory?(dest, path) + raise ArgumentError, "cannot copy directory %s to itself %s" % [path, dest] + end + begin + Dir.mkdir dest + rescue + raise unless File.directory?(dest) + end + when symlink? + File.symlink File.readlink(path()), dest + when chardev?, blockdev? + raise "cannot handle device file" + when socket? + begin + require 'socket' + rescue LoadError + raise "cannot handle socket" + else + raise "cannot handle socket" unless defined?(UNIXServer) + end + UNIXServer.new(dest).close + File.chmod lstat().mode, dest + when pipe? + raise "cannot handle FIFO" unless File.respond_to?(:mkfifo) + File.mkfifo dest, lstat().mode + when door? + raise "cannot handle door: #{path()}" + else + raise "unknown file type: #{path()}" + end + end + + def copy_file(dest) + File.open(path()) do |s| + File.open(dest, 'wb', s.stat.mode) do |f| + IO.copy_stream(s, f) + end + end + end + + def copy_metadata(path) + st = lstat() + if !st.symlink? + File.utime st.atime, st.mtime, path + end + mode = st.mode + begin + if st.symlink? + begin + File.lchown st.uid, st.gid, path + rescue NotImplementedError + end + else + File.chown st.uid, st.gid, path + end + rescue Errno::EPERM, Errno::EACCES + # clear setuid/setgid + mode &= 01777 + end + if st.symlink? + begin + File.lchmod mode, path + rescue NotImplementedError, Errno::EOPNOTSUPP + end + else + File.chmod mode, path + end + end + + def remove + if directory? + remove_dir1 + else + remove_file + end + end + + def remove_dir1 + platform_support { + Dir.rmdir path().chomp(?/) + } + end + + def remove_file + platform_support { + File.unlink path + } + end + + def platform_support + return yield unless fu_windows? + first_time_p = true + begin + yield + rescue Errno::ENOENT + raise + rescue => err + if first_time_p + first_time_p = false + begin + File.chmod 0700, path() # Windows does not have symlink + retry + rescue SystemCallError + end + end + raise err + end + end + + def preorder_traverse + stack = [self] + while ent = stack.pop + yield ent + stack.concat ent.entries.reverse if ent.directory? + end + end + + alias traverse preorder_traverse + + def postorder_traverse + if directory? + entries().each do |ent| + ent.postorder_traverse do |e| + yield e + end + end + end + ensure + yield self + end + + def wrap_traverse(pre, post) + pre.call self + if directory? + entries.each do |ent| + ent.wrap_traverse pre, post + end + end + post.call self + end + + private + + @@fileutils_rb_have_lchmod = nil + + def have_lchmod? + # This is not MT-safe, but it does not matter. + if @@fileutils_rb_have_lchmod == nil + @@fileutils_rb_have_lchmod = check_have_lchmod? + end + @@fileutils_rb_have_lchmod + end + + def check_have_lchmod? + return false unless File.respond_to?(:lchmod) + File.lchmod 0 + return true + rescue NotImplementedError + return false + end + + @@fileutils_rb_have_lchown = nil + + def have_lchown? + # This is not MT-safe, but it does not matter. + if @@fileutils_rb_have_lchown == nil + @@fileutils_rb_have_lchown = check_have_lchown? + end + @@fileutils_rb_have_lchown + end + + def check_have_lchown? + return false unless File.respond_to?(:lchown) + File.lchown nil, nil + return true + rescue NotImplementedError + return false + end + + def join(dir, base) + return File.path(dir) if not base or base == '.' + return File.path(base) if not dir or dir == '.' + begin + File.join(dir, base) + rescue EncodingError + if fu_windows? + File.join(dir.encode(::Encoding::UTF_8), base.encode(::Encoding::UTF_8)) + else + raise + end + end + end + + if File::ALT_SEPARATOR + DIRECTORY_TERM = "(?=[/#{Regexp.quote(File::ALT_SEPARATOR)}]|\\z)" + else + DIRECTORY_TERM = "(?=/|\\z)" + end + + def descendant_directory?(descendant, ascendant) + if File::FNM_SYSCASE.nonzero? + File.expand_path(File.dirname(descendant)).casecmp(File.expand_path(ascendant)) == 0 + else + File.expand_path(File.dirname(descendant)) == File.expand_path(ascendant) + end + end + end # class Entry_ + + def fu_list(arg) #:nodoc: + [arg].flatten.map {|path| File.path(path) } + end + private_module_function :fu_list + + def fu_each_src_dest(src, dest) #:nodoc: + fu_each_src_dest0(src, dest) do |s, d| + raise ArgumentError, "same file: #{s} and #{d}" if fu_same?(s, d) + yield s, d + end + end + private_module_function :fu_each_src_dest + + def fu_each_src_dest0(src, dest) #:nodoc: + if tmp = Array.try_convert(src) + tmp.each do |s| + s = File.path(s) + yield s, File.join(dest, File.basename(s)) + end + else + src = File.path(src) + if File.directory?(dest) + yield src, File.join(dest, File.basename(src)) + else + yield src, File.path(dest) + end + end + end + private_module_function :fu_each_src_dest0 + + def fu_same?(a, b) #:nodoc: + File.identical?(a, b) + end + private_module_function :fu_same? + + def fu_output_message(msg) #:nodoc: + output = @fileutils_output if defined?(@fileutils_output) + output ||= $stdout + if defined?(@fileutils_label) + msg = @fileutils_label + msg + end + output.puts msg + end + private_module_function :fu_output_message + + # This hash table holds command options. + OPT_TABLE = {} #:nodoc: internal use only + (private_instance_methods & methods(false)).inject(OPT_TABLE) {|tbl, name| + (tbl[name.to_s] = instance_method(name).parameters).map! {|t, n| n if t == :key}.compact! + tbl + } + + public + + # + # Returns an Array of names of high-level methods that accept any keyword + # arguments. + # + # p FileUtils.commands #=> ["chmod", "cp", "cp_r", "install", ...] + # + def self.commands + OPT_TABLE.keys + end + + # + # Returns an Array of option names. + # + # p FileUtils.options #=> ["noop", "force", "verbose", "preserve", "mode"] + # + def self.options + OPT_TABLE.values.flatten.uniq.map {|sym| sym.to_s } + end + + # + # Returns true if the method +mid+ have an option +opt+. + # + # p FileUtils.have_option?(:cp, :noop) #=> true + # p FileUtils.have_option?(:rm, :force) #=> true + # p FileUtils.have_option?(:rm, :preserve) #=> false + # + def self.have_option?(mid, opt) + li = OPT_TABLE[mid.to_s] or raise ArgumentError, "no such method: #{mid}" + li.include?(opt) + end + + # + # Returns an Array of option names of the method +mid+. + # + # p FileUtils.options_of(:rm) #=> ["noop", "verbose", "force"] + # + def self.options_of(mid) + OPT_TABLE[mid.to_s].map {|sym| sym.to_s } + end + + # + # Returns an Array of methods names which have the option +opt+. + # + # p FileUtils.collect_method(:preserve) #=> ["cp", "cp_r", "copy", "install"] + # + def self.collect_method(opt) + OPT_TABLE.keys.select {|m| OPT_TABLE[m].include?(opt) } + end + + private + + LOW_METHODS = singleton_methods(false) - collect_method(:noop).map(&:intern) # :nodoc: + module LowMethods # :nodoc: internal use only + private + def _do_nothing(*)end + ::FileUtils::LOW_METHODS.map {|name| alias_method name, :_do_nothing} + end + + METHODS = singleton_methods() - [:private_module_function, # :nodoc: + :commands, :options, :have_option?, :options_of, :collect_method] + + # + # This module has all methods of FileUtils module, but it outputs messages + # before acting. This equates to passing the :verbose flag to + # methods in FileUtils. + # + module Verbose + include FileUtils + names = ::FileUtils.collect_method(:verbose) + names.each do |name| + module_eval(<<-EOS, __FILE__, __LINE__ + 1) + def #{name}(*args, **options) + super(*args, **options, verbose: true) + end + EOS + end + private(*names) + extend self + class << self + public(*::FileUtils::METHODS) + end + end + + # + # This module has all methods of FileUtils module, but never changes + # files/directories. This equates to passing the :noop flag + # to methods in FileUtils. + # + module NoWrite + include FileUtils + include LowMethods + names = ::FileUtils.collect_method(:noop) + names.each do |name| + module_eval(<<-EOS, __FILE__, __LINE__ + 1) + def #{name}(*args, **options) + super(*args, **options, noop: true) + end + EOS + end + private(*names) + extend self + class << self + public(*::FileUtils::METHODS) + end + end + + # + # This module has all methods of FileUtils module, but never changes + # files/directories, with printing message before acting. + # This equates to passing the :noop and :verbose flag + # to methods in FileUtils. + # + module DryRun + include FileUtils + include LowMethods + names = ::FileUtils.collect_method(:noop) + names.each do |name| + module_eval(<<-EOS, __FILE__, __LINE__ + 1) + def #{name}(*args, **options) + super(*args, **options, noop: true, verbose: true) + end + EOS + end + private(*names) + extend self + class << self + public(*::FileUtils::METHODS) + end + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/MIT-LICENSE b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/MIT-LICENSE new file mode 100644 index 0000000..ed8e9ee --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2008 The Ruby I18n team + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/README.md b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/README.md new file mode 100644 index 0000000..318e05d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/README.md @@ -0,0 +1,123 @@ +# Ruby I18n + +[![Gem Version](https://badge.fury.io/rb/i18n.svg)](https://badge.fury.io/rb/i18n) +[![Build Status](https://github.com/ruby-i18n/i18n/workflows/Ruby/badge.svg)](https://github.com/ruby-i18n/i18n/actions?query=workflow%3ARuby) + +Ruby internationalization and localization (i18n) solution. + +Currently maintained by @radar. + +## Usage + +### Rails + +You will most commonly use this library within a Rails app. + +[See the Rails Guide](https://guides.rubyonrails.org/i18n.html) for an example of its usage. + +### Ruby (without Rails) + +If you want to use this library without Rails, you can simply add `i18n` to your `Gemfile`: + +```ruby +gem 'i18n' +``` + +Then configure I18n with some translations, and a default locale: + +```ruby +I18n.load_path << Dir[File.expand_path("config/locales") + "/*.yml"] +I18n.default_locale = :en # (note that `en` is already the default!) +``` + +A simple translation file in your project might live at `config/locales/en.yml` and look like: + +```yml +en: + test: "This is a test" +``` + +You can then access this translation by doing: + +```ruby +I18n.t(:test) +``` + +You can switch locales in your project by setting `I18n.locale` to a different value: + +```ruby +I18n.locale = :de +I18n.t(:test) # => "Dies ist ein Test" +``` + +## Features + +* Translation and localization +* Interpolation of values to translations +* Pluralization (CLDR compatible) +* Customizable transliteration to ASCII +* Flexible defaults +* Bulk lookup +* Lambdas as translation data +* Custom key/scope separator +* Custom exception handlers +* Extensible architecture with a swappable backend + +## Pluggable Features + +* Cache +* Pluralization: lambda pluralizers stored as translation data +* Locale fallbacks, RFC4647 compliant (optionally: RFC4646 locale validation) +* [Gettext support](https://github.com/ruby-i18n/i18n/wiki/Gettext) +* Translation metadata + +## Alternative Backend + +* Chain +* ActiveRecord (optionally: ActiveRecord::Missing and ActiveRecord::StoreProcs) +* KeyValue (uses active_support/json and cannot store procs) + +For more information and lots of resources see [the 'Resources' page on the wiki](https://github.com/ruby-i18n/i18n/wiki/Resources). + +## Tests + +You can run tests both with + +* `rake test` or just `rake` +* run any test file directly, e.g. `ruby -Ilib:test test/api/simple_test.rb` + +You can run all tests against all Gemfiles with + +* `ruby test/run_all.rb` + +The structure of the test suite is a bit unusual as it uses modules to reuse +particular tests in different test cases. + +The reason for this is that we need to enforce the I18n API across various +combinations of extensions. E.g. the Simple backend alone needs to support +the same API as any combination of feature and/or optimization modules included +to the Simple backend. We test this by reusing the same API definition (implemented +as test methods) in test cases with different setups. + +You can find the test cases that enforce the API in test/api. And you can find +the API definition test methods in test/api/tests. + +All other test cases (e.g. as defined in test/backend, test/core_ext) etc. +follow the usual test setup and should be easy to grok. + +## More Documentation + +Additional documentation can be found here: https://github.com/ruby-i18n/i18n/wiki + +## Contributors + +* @radar +* @carlosantoniodasilva +* @josevalim +* @knapo +* @tigrish +* [and many more](https://github.com/ruby-i18n/i18n/graphs/contributors) + +## License + +MIT License. See the included MIT-LICENSE file. diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n.rb new file mode 100644 index 0000000..e197e2b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n.rb @@ -0,0 +1,429 @@ +# frozen_string_literal: true + +require 'concurrent/map' +require 'concurrent/hash' + +require 'i18n/version' +require 'i18n/utils' +require 'i18n/exceptions' +require 'i18n/interpolate/ruby' + +module I18n + autoload :Backend, 'i18n/backend' + autoload :Config, 'i18n/config' + autoload :Gettext, 'i18n/gettext' + autoload :Locale, 'i18n/locale' + autoload :Tests, 'i18n/tests' + autoload :Middleware, 'i18n/middleware' + + RESERVED_KEYS = %i[ + cascade + deep_interpolation + default + exception_handler + fallback + fallback_in_progress + fallback_original_locale + format + object + raise + resolve + scope + separator + throw + ] + EMPTY_HASH = {}.freeze + + def self.new_double_nested_cache # :nodoc: + Concurrent::Map.new { |h, k| h[k] = Concurrent::Map.new } + end + + # Marks a key as reserved. Reserved keys are used internally, + # and can't also be used for interpolation. If you are using any + # extra keys as I18n options, you should call I18n.reserve_key + # before any I18n.translate (etc) calls are made. + def self.reserve_key(key) + RESERVED_KEYS << key.to_sym + @reserved_keys_pattern = nil + end + + def self.reserved_keys_pattern # :nodoc: + @reserved_keys_pattern ||= /%\{(#{RESERVED_KEYS.join("|")})\}/ + end + + module Base + # Gets I18n configuration object. + def config + Thread.current[:i18n_config] ||= I18n::Config.new + end + + # Sets I18n configuration object. + def config=(value) + Thread.current[:i18n_config] = value + end + + # Write methods which delegates to the configuration object + %w(locale backend default_locale available_locales default_separator + exception_handler load_path enforce_available_locales).each do |method| + module_eval <<-DELEGATORS, __FILE__, __LINE__ + 1 + def #{method} + config.#{method} + end + + def #{method}=(value) + config.#{method} = (value) + end + DELEGATORS + end + + # Tells the backend to reload translations. Used in situations like the + # Rails development environment. Backends can implement whatever strategy + # is useful. + def reload! + config.clear_available_locales_set + config.backend.reload! + end + + # Tells the backend to load translations now. Used in situations like the + # Rails production environment. Backends can implement whatever strategy + # is useful. + def eager_load! + config.backend.eager_load! + end + + # Translates, pluralizes and interpolates a given key using a given locale, + # scope, and default, as well as interpolation values. + # + # *LOOKUP* + # + # Translation data is organized as a nested hash using the upper-level keys + # as namespaces. E.g., ActionView ships with the translation: + # :date => {:formats => {:short => "%b %d"}}. + # + # Translations can be looked up at any level of this hash using the key argument + # and the scope option. E.g., in this example I18n.t :date + # returns the whole translations hash {:formats => {:short => "%b %d"}}. + # + # Key can be either a single key or a dot-separated key (both Strings and Symbols + # work). E.g., the short format can be looked up using both: + # I18n.t 'date.formats.short' + # I18n.t :'date.formats.short' + # + # Scope can be either a single key, a dot-separated key or an array of keys + # or dot-separated keys. Keys and scopes can be combined freely. So these + # examples will all look up the same short date format: + # I18n.t 'date.formats.short' + # I18n.t 'formats.short', :scope => 'date' + # I18n.t 'short', :scope => 'date.formats' + # I18n.t 'short', :scope => %w(date formats) + # + # *INTERPOLATION* + # + # Translations can contain interpolation variables which will be replaced by + # values passed to #translate as part of the options hash, with the keys matching + # the interpolation variable names. + # + # E.g., with a translation :foo => "foo %{bar}" the option + # value for the key +bar+ will be interpolated into the translation: + # I18n.t :foo, :bar => 'baz' # => 'foo baz' + # + # *PLURALIZATION* + # + # Translation data can contain pluralized translations. Pluralized translations + # are arrays of singular/plural versions of translations like ['Foo', 'Foos']. + # + # Note that I18n::Backend::Simple only supports an algorithm for English + # pluralization rules. Other algorithms can be supported by custom backends. + # + # This returns the singular version of a pluralized translation: + # I18n.t :foo, :count => 1 # => 'Foo' + # + # These both return the plural version of a pluralized translation: + # I18n.t :foo, :count => 0 # => 'Foos' + # I18n.t :foo, :count => 2 # => 'Foos' + # + # The :count option can be used both for pluralization and interpolation. + # E.g., with the translation + # :foo => ['%{count} foo', '%{count} foos'], count will + # be interpolated to the pluralized translation: + # I18n.t :foo, :count => 1 # => '1 foo' + # + # *DEFAULTS* + # + # This returns the translation for :foo or default if no translation was found: + # I18n.t :foo, :default => 'default' + # + # This returns the translation for :foo or the translation for :bar if no + # translation for :foo was found: + # I18n.t :foo, :default => :bar + # + # Returns the translation for :foo or the translation for :bar + # or default if no translations for :foo and :bar were found. + # I18n.t :foo, :default => [:bar, 'default'] + # + # *BULK LOOKUP* + # + # This returns an array with the translations for :foo and :bar. + # I18n.t [:foo, :bar] + # + # Can be used with dot-separated nested keys: + # I18n.t [:'baz.foo', :'baz.bar'] + # + # Which is the same as using a scope option: + # I18n.t [:foo, :bar], :scope => :baz + # + # *LAMBDAS* + # + # Both translations and defaults can be given as Ruby lambdas. Lambdas will be + # called and passed the key and options. + # + # E.g. assuming the key :salutation resolves to: + # lambda { |key, options| options[:gender] == 'm' ? "Mr. #{options[:name]}" : "Mrs. #{options[:name]}" } + # + # Then I18n.t(:salutation, :gender => 'w', :name => 'Smith') will result in "Mrs. Smith". + # + # Note that the string returned by lambda will go through string interpolation too, + # so the following lambda would give the same result: + # lambda { |key, options| options[:gender] == 'm' ? "Mr. %{name}" : "Mrs. %{name}" } + # + # It is recommended to use/implement lambdas in an "idempotent" way. E.g. when + # a cache layer is put in front of I18n.translate it will generate a cache key + # from the argument values passed to #translate. Therefore your lambdas should + # always return the same translations/values per unique combination of argument + # values. + # + # *Ruby 2.7+ keyword arguments warning* + # + # This method uses keyword arguments. + # There is a breaking change in ruby that produces warning with ruby 2.7 and won't work as expected with ruby 3.0 + # The "hash" parameter must be passed as keyword argument. + # + # Good: + # I18n.t(:salutation, :gender => 'w', :name => 'Smith') + # I18n.t(:salutation, **{ :gender => 'w', :name => 'Smith' }) + # I18n.t(:salutation, **any_hash) + # + # Bad: + # I18n.t(:salutation, { :gender => 'w', :name => 'Smith' }) + # I18n.t(:salutation, any_hash) + # + def translate(key = nil, throw: false, raise: false, locale: nil, **options) # TODO deprecate :raise + locale ||= config.locale + raise Disabled.new('t') if locale == false + enforce_available_locales!(locale) + + backend = config.backend + + result = catch(:exception) do + if key.is_a?(Array) + key.map { |k| backend.translate(locale, k, options) } + else + backend.translate(locale, key, options) + end + end + + if result.is_a?(MissingTranslation) + handle_exception((throw && :throw || raise && :raise), result, locale, key, options) + else + result + end + end + alias :t :translate + + # Wrapper for translate that adds :raise => true. With + # this option, if no translation is found, it will raise I18n::MissingTranslationData + def translate!(key, **options) + translate(key, **options, raise: true) + end + alias :t! :translate! + + # Returns true if a translation exists for a given key, otherwise returns false. + def exists?(key, _locale = nil, locale: _locale, **options) + locale ||= config.locale + raise Disabled.new('exists?') if locale == false + raise I18n::ArgumentError if key.is_a?(String) && key.empty? + config.backend.exists?(locale, key, options) + end + + # Transliterates UTF-8 characters to ASCII. By default this method will + # transliterate only Latin strings to an ASCII approximation: + # + # I18n.transliterate("Ærøskøbing") + # # => "AEroskobing" + # + # I18n.transliterate("日本語") + # # => "???" + # + # It's also possible to add support for per-locale transliterations. I18n + # expects transliteration rules to be stored at + # i18n.transliterate.rule. + # + # Transliteration rules can either be a Hash or a Proc. Procs must accept a + # single string argument. Hash rules inherit the default transliteration + # rules, while Procs do not. + # + # *Examples* + # + # Setting a Hash in .yml: + # + # i18n: + # transliterate: + # rule: + # ü: "ue" + # ö: "oe" + # + # Setting a Hash using Ruby: + # + # store_translations(:de, i18n: { + # transliterate: { + # rule: { + # 'ü' => 'ue', + # 'ö' => 'oe' + # } + # } + # }) + # + # Setting a Proc: + # + # translit = lambda {|string| MyTransliterator.transliterate(string) } + # store_translations(:xx, :i18n => {:transliterate => {:rule => translit}) + # + # Transliterating strings: + # + # I18n.locale = :en + # I18n.transliterate("Jürgen") # => "Jurgen" + # I18n.locale = :de + # I18n.transliterate("Jürgen") # => "Juergen" + # I18n.transliterate("Jürgen", :locale => :en) # => "Jurgen" + # I18n.transliterate("Jürgen", :locale => :de) # => "Juergen" + def transliterate(key, throw: false, raise: false, locale: nil, replacement: nil, **options) + locale ||= config.locale + raise Disabled.new('transliterate') if locale == false + enforce_available_locales!(locale) + + config.backend.transliterate(locale, key, replacement) + rescue I18n::ArgumentError => exception + handle_exception((throw && :throw || raise && :raise), exception, locale, key, options) + end + + # Localizes certain objects, such as dates and numbers to local formatting. + def localize(object, locale: nil, format: nil, **options) + locale ||= config.locale + raise Disabled.new('l') if locale == false + enforce_available_locales!(locale) + + format ||= :default + config.backend.localize(locale, object, format, options) + end + alias :l :localize + + # Executes block with given I18n.locale set. + def with_locale(tmp_locale = nil) + if tmp_locale == nil + yield + else + current_locale = self.locale + self.locale = tmp_locale + begin + yield + ensure + self.locale = current_locale + end + end + end + + # Merges the given locale, key and scope into a single array of keys. + # Splits keys that contain dots into multiple keys. Makes sure all + # keys are Symbols. + def normalize_keys(locale, key, scope, separator = nil) + separator ||= I18n.default_separator + + [ + *normalize_key(locale, separator), + *normalize_key(scope, separator), + *normalize_key(key, separator) + ] + end + + # Returns true when the passed locale, which can be either a String or a + # Symbol, is in the list of available locales. Returns false otherwise. + def locale_available?(locale) + I18n.config.available_locales_set.include?(locale) + end + + # Raises an InvalidLocale exception when the passed locale is not available. + def enforce_available_locales!(locale) + if locale != false && config.enforce_available_locales + raise I18n::InvalidLocale.new(locale) if !locale_available?(locale) + end + end + + def available_locales_initialized? + config.available_locales_initialized? + end + + private + + # Any exceptions thrown in translate will be sent to the @@exception_handler + # which can be a Symbol, a Proc or any other Object unless they're forced to + # be raised or thrown (MissingTranslation). + # + # If exception_handler is a Symbol then it will simply be sent to I18n as + # a method call. A Proc will simply be called. In any other case the + # method #call will be called on the exception_handler object. + # + # Examples: + # + # I18n.exception_handler = :custom_exception_handler # this is the default + # I18n.custom_exception_handler(exception, locale, key, options) # will be called like this + # + # I18n.exception_handler = lambda { |*args| ... } # a lambda + # I18n.exception_handler.call(exception, locale, key, options) # will be called like this + # + # I18n.exception_handler = I18nExceptionHandler.new # an object + # I18n.exception_handler.call(exception, locale, key, options) # will be called like this + def handle_exception(handling, exception, locale, key, options) + case handling + when :raise + raise exception.respond_to?(:to_exception) ? exception.to_exception : exception + when :throw + throw :exception, exception + else + case handler = options[:exception_handler] || config.exception_handler + when Symbol + send(handler, exception, locale, key, options) + else + handler.call(exception, locale, key, options) + end + end + end + + @@normalized_key_cache = I18n.new_double_nested_cache + + def normalize_key(key, separator) + @@normalized_key_cache[separator][key] ||= + case key + when Array + key.flat_map { |k| normalize_key(k, separator) } + else + keys = key.to_s.split(separator) + keys.delete('') + keys.map! do |k| + case k + when /\A[-+]?([1-9]\d*|0)\z/ # integer + k.to_i + when 'true' + true + when 'false' + false + else + k.to_sym + end + end + keys + end + end + end + + extend Base +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend.rb new file mode 100644 index 0000000..863d618 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +module I18n + module Backend + autoload :Base, 'i18n/backend/base' + autoload :Cache, 'i18n/backend/cache' + autoload :CacheFile, 'i18n/backend/cache_file' + autoload :Cascade, 'i18n/backend/cascade' + autoload :Chain, 'i18n/backend/chain' + autoload :Fallbacks, 'i18n/backend/fallbacks' + autoload :Flatten, 'i18n/backend/flatten' + autoload :Gettext, 'i18n/backend/gettext' + autoload :InterpolationCompiler, 'i18n/backend/interpolation_compiler' + autoload :KeyValue, 'i18n/backend/key_value' + autoload :LazyLoadable, 'i18n/backend/lazy_loadable' + autoload :Memoize, 'i18n/backend/memoize' + autoload :Metadata, 'i18n/backend/metadata' + autoload :Pluralization, 'i18n/backend/pluralization' + autoload :Simple, 'i18n/backend/simple' + autoload :Transliterator, 'i18n/backend/transliterator' + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/base.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/base.rb new file mode 100644 index 0000000..4cbcc3c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/base.rb @@ -0,0 +1,299 @@ +# frozen_string_literal: true + +require 'yaml' +require 'json' + +module I18n + module Backend + module Base + include I18n::Backend::Transliterator + + # Accepts a list of paths to translation files. Loads translations from + # plain Ruby (*.rb), YAML files (*.yml), or JSON files (*.json). See #load_rb, #load_yml, and #load_json + # for details. + def load_translations(*filenames) + filenames = I18n.load_path if filenames.empty? + filenames.flatten.each do |filename| + loaded_translations = load_file(filename) + yield filename, loaded_translations if block_given? + end + end + + # This method receives a locale, a data hash and options for storing translations. + # Should be implemented + def store_translations(locale, data, options = EMPTY_HASH) + raise NotImplementedError + end + + def translate(locale, key, options = EMPTY_HASH) + raise I18n::ArgumentError if (key.is_a?(String) || key.is_a?(Symbol)) && key.empty? + raise InvalidLocale.new(locale) unless locale + return nil if key.nil? && !options.key?(:default) + + entry = lookup(locale, key, options[:scope], options) unless key.nil? + + if entry.nil? && options.key?(:default) + entry = default(locale, key, options[:default], options) + else + entry = resolve_entry(locale, key, entry, options) + end + + count = options[:count] + + if entry.nil? && (subtrees? || !count) + if (options.key?(:default) && !options[:default].nil?) || !options.key?(:default) + throw(:exception, I18n::MissingTranslation.new(locale, key, options)) + end + end + + entry = entry.dup if entry.is_a?(String) + entry = pluralize(locale, entry, count) if count + + if entry.nil? && !subtrees? + throw(:exception, I18n::MissingTranslation.new(locale, key, options)) + end + + deep_interpolation = options[:deep_interpolation] + values = Utils.except(options, *RESERVED_KEYS) + if values + entry = if deep_interpolation + deep_interpolate(locale, entry, values) + else + interpolate(locale, entry, values) + end + end + entry + end + + def exists?(locale, key, options = EMPTY_HASH) + lookup(locale, key) != nil + end + + # Acts the same as +strftime+, but uses a localized version of the + # format string. Takes a key from the date/time formats translations as + # a format argument (e.g., :short in :'date.formats'). + def localize(locale, object, format = :default, options = EMPTY_HASH) + if object.nil? && options.include?(:default) + return options[:default] + end + raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime) + + if Symbol === format + key = format + type = object.respond_to?(:sec) ? 'time' : 'date' + options = options.merge(:raise => true, :object => object, :locale => locale) + format = I18n.t(:"#{type}.formats.#{key}", **options) + end + + format = translate_localization_format(locale, object, format, options) + object.strftime(format) + end + + # Returns an array of locales for which translations are available + # ignoring the reserved translation meta data key :i18n. + def available_locales + raise NotImplementedError + end + + def reload! + eager_load! if eager_loaded? + end + + def eager_load! + @eager_loaded = true + end + + protected + + def eager_loaded? + @eager_loaded ||= false + end + + # The method which actually looks up for the translation in the store. + def lookup(locale, key, scope = [], options = EMPTY_HASH) + raise NotImplementedError + end + + def subtrees? + true + end + + # Evaluates defaults. + # If given subject is an Array, it walks the array and returns the + # first translation that can be resolved. Otherwise it tries to resolve + # the translation directly. + def default(locale, object, subject, options = EMPTY_HASH) + options = options.reject { |key, value| key == :default } + case subject + when Array + subject.each do |item| + result = resolve(locale, object, item, options) + return result unless result.nil? + end and nil + else + resolve(locale, object, subject, options) + end + end + + # Resolves a translation. + # If the given subject is a Symbol, it will be translated with the + # given options. If it is a Proc then it will be evaluated. All other + # subjects will be returned directly. + def resolve(locale, object, subject, options = EMPTY_HASH) + return subject if options[:resolve] == false + result = catch(:exception) do + case subject + when Symbol + I18n.translate(subject, **options.merge(:locale => locale, :throw => true)) + when Proc + date_or_time = options.delete(:object) || object + resolve(locale, object, subject.call(date_or_time, **options)) + else + subject + end + end + result unless result.is_a?(MissingTranslation) + end + alias_method :resolve_entry, :resolve + + # Picks a translation from a pluralized mnemonic subkey according to English + # pluralization rules : + # - It will pick the :one subkey if count is equal to 1. + # - It will pick the :other subkey otherwise. + # - It will pick the :zero subkey in the special case where count is + # equal to 0 and there is a :zero subkey present. This behaviour is + # not standard with regards to the CLDR pluralization rules. + # Other backends can implement more flexible or complex pluralization rules. + def pluralize(locale, entry, count) + entry = entry.reject { |k, _v| k == :attributes } if entry.is_a?(Hash) + return entry unless entry.is_a?(Hash) && count && entry.values.none? { |v| v.is_a?(Hash) } + + key = pluralization_key(entry, count) + raise InvalidPluralizationData.new(entry, count, key) unless entry.has_key?(key) + entry[key] + end + + # Interpolates values into a given subject. + # + # if the given subject is a string then: + # method interpolates "file %{file} opened by %%{user}", :file => 'test.txt', :user => 'Mr. X' + # # => "file test.txt opened by %{user}" + # + # if the given subject is an array then: + # each element of the array is recursively interpolated (until it finds a string) + # method interpolates ["yes, %{user}", ["maybe no, %{user}, "no, %{user}"]], :user => "bartuz" + # # => "["yes, bartuz",["maybe no, bartuz", "no, bartuz"]]" + def interpolate(locale, subject, values = EMPTY_HASH) + return subject if values.empty? + + case subject + when ::String then I18n.interpolate(subject, values) + when ::Array then subject.map { |element| interpolate(locale, element, values) } + else + subject + end + end + + # Deep interpolation + # + # deep_interpolate { people: { ann: "Ann is %{ann}", john: "John is %{john}" } }, + # ann: 'good', john: 'big' + # #=> { people: { ann: "Ann is good", john: "John is big" } } + def deep_interpolate(locale, data, values = EMPTY_HASH) + return data if values.empty? + + case data + when ::String + I18n.interpolate(data, values) + when ::Hash + data.each_with_object({}) do |(k, v), result| + result[k] = deep_interpolate(locale, v, values) + end + when ::Array + data.map do |v| + deep_interpolate(locale, v, values) + end + else + data + end + end + + # Loads a single translations file by delegating to #load_rb or + # #load_yml depending on the file extension and directly merges the + # data to the existing translations. Raises I18n::UnknownFileType + # for all other file extensions. + def load_file(filename) + type = File.extname(filename).tr('.', '').downcase + raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}", true) + data, keys_symbolized = send(:"load_#{type}", filename) + unless data.is_a?(Hash) + raise InvalidLocaleData.new(filename, 'expects it to return a hash, but does not') + end + data.each { |locale, d| store_translations(locale, d || {}, skip_symbolize_keys: keys_symbolized) } + + data + end + + # Loads a plain Ruby translations file. eval'ing the file must yield + # a Hash containing translation data with locales as toplevel keys. + def load_rb(filename) + translations = eval(IO.read(filename), binding, filename) + [translations, false] + end + + # Loads a YAML translations file. The data must have locales as + # toplevel keys. + def load_yml(filename) + begin + if YAML.respond_to?(:unsafe_load_file) # Psych 4.0 way + [YAML.unsafe_load_file(filename, symbolize_names: true, freeze: true), true] + else + [YAML.load_file(filename), false] + end + rescue TypeError, ScriptError, StandardError => e + raise InvalidLocaleData.new(filename, e.inspect) + end + end + alias_method :load_yaml, :load_yml + + # Loads a JSON translations file. The data must have locales as + # toplevel keys. + def load_json(filename) + begin + # Use #load_file as a proxy for a version of JSON where symbolize_names and freeze are supported. + if ::JSON.respond_to?(:load_file) + [::JSON.load_file(filename, symbolize_names: true, freeze: true), true] + else + [::JSON.parse(File.read(filename)), false] + end + rescue TypeError, StandardError => e + raise InvalidLocaleData.new(filename, e.inspect) + end + end + + def translate_localization_format(locale, object, format, options) + format.to_s.gsub(/%(|\^)[aAbBpP]/) do |match| + case match + when '%a' then I18n.t!(:"date.abbr_day_names", :locale => locale, :format => format)[object.wday] + when '%^a' then I18n.t!(:"date.abbr_day_names", :locale => locale, :format => format)[object.wday].upcase + when '%A' then I18n.t!(:"date.day_names", :locale => locale, :format => format)[object.wday] + when '%^A' then I18n.t!(:"date.day_names", :locale => locale, :format => format)[object.wday].upcase + when '%b' then I18n.t!(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon] + when '%^b' then I18n.t!(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon].upcase + when '%B' then I18n.t!(:"date.month_names", :locale => locale, :format => format)[object.mon] + when '%^B' then I18n.t!(:"date.month_names", :locale => locale, :format => format)[object.mon].upcase + when '%p' then I18n.t!(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).upcase if object.respond_to? :hour + when '%P' then I18n.t!(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).downcase if object.respond_to? :hour + end + end + rescue MissingTranslationData => e + e.message + end + + def pluralization_key(entry, count) + key = :zero if count == 0 && entry.has_key?(:zero) + key ||= count == 1 ? :one : :other + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/cache.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/cache.rb new file mode 100644 index 0000000..40c18d6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/cache.rb @@ -0,0 +1,113 @@ +# frozen_string_literal: true + +# This module allows you to easily cache all responses from the backend - thus +# speeding up the I18n aspects of your application quite a bit. +# +# To enable caching you can simply include the Cache module to the Simple +# backend - or whatever other backend you are using: +# +# I18n::Backend::Simple.send(:include, I18n::Backend::Cache) +# +# You will also need to set a cache store implementation that you want to use: +# +# I18n.cache_store = ActiveSupport::Cache.lookup_store(:memory_store) +# +# You can use any cache implementation you want that provides the same API as +# ActiveSupport::Cache (only the methods #fetch and #write are being used). +# +# The cache_key implementation by default assumes you pass values that return +# a valid key from #hash (see +# https://www.ruby-doc.org/core/classes/Object.html#M000337). However, you can +# configure your own digest method via which responds to #hexdigest (see +# https://ruby-doc.org/stdlib/libdoc/openssl/rdoc/OpenSSL/Digest.html): +# +# I18n.cache_key_digest = OpenSSL::Digest::SHA256.new +# +# If you use a lambda as a default value in your translation like this: +# +# I18n.t(:"date.order", :default => lambda {[:month, :day, :year]}) +# +# Then you will always have a cache miss, because each time this method +# is called the lambda will have a different hash value. If you know +# the result of the lambda is a constant as in the example above, then +# to cache this you can make the lambda a constant, like this: +# +# DEFAULT_DATE_ORDER = lambda {[:month, :day, :year]} +# ... +# I18n.t(:"date.order", :default => DEFAULT_DATE_ORDER) +# +# If the lambda may result in different values for each call then consider +# also using the Memoize backend. +# +module I18n + class << self + @@cache_store = nil + @@cache_namespace = nil + @@cache_key_digest = nil + + def cache_store + @@cache_store + end + + def cache_store=(store) + @@cache_store = store + end + + def cache_namespace + @@cache_namespace + end + + def cache_namespace=(namespace) + @@cache_namespace = namespace + end + + def cache_key_digest + @@cache_key_digest + end + + def cache_key_digest=(key_digest) + @@cache_key_digest = key_digest + end + + def perform_caching? + !cache_store.nil? + end + end + + module Backend + # TODO Should the cache be cleared if new translations are stored? + module Cache + def translate(locale, key, options = EMPTY_HASH) + I18n.perform_caching? ? fetch(cache_key(locale, key, options)) { super } : super + end + + protected + + def fetch(cache_key, &block) + result = _fetch(cache_key, &block) + throw(:exception, result) if result.is_a?(MissingTranslation) + result = result.dup if result.frozen? rescue result + result + end + + def _fetch(cache_key, &block) + result = I18n.cache_store.read(cache_key) + return result unless result.nil? + result = catch(:exception, &block) + I18n.cache_store.write(cache_key, result) unless result.is_a?(Proc) + result + end + + def cache_key(locale, key, options) + # This assumes that only simple, native Ruby values are passed to I18n.translate. + "i18n/#{I18n.cache_namespace}/#{locale}/#{digest_item(key)}/#{digest_item(options)}" + end + + private + + def digest_item(key) + I18n.cache_key_digest ? I18n.cache_key_digest.hexdigest(key.to_s) : key.to_s.hash + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/cache_file.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/cache_file.rb new file mode 100644 index 0000000..0c5e192 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/cache_file.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +require 'openssl' + +module I18n + module Backend + # Overwrites the Base load_file method to cache loaded file contents. + module CacheFile + # Optionally provide path_roots array to normalize filename paths, + # to make the cached i18n data portable across environments. + attr_accessor :path_roots + + protected + + # Track loaded translation files in the `i18n.load_file` scope, + # and skip loading the file if its contents are still up-to-date. + def load_file(filename) + initialized = !respond_to?(:initialized?) || initialized? + key = I18n::Backend::Flatten.escape_default_separator(normalized_path(filename)) + old_mtime, old_digest = initialized && lookup(:i18n, key, :load_file) + return if (mtime = File.mtime(filename).to_i) == old_mtime || + (digest = OpenSSL::Digest::SHA256.file(filename).hexdigest) == old_digest + super + store_translations(:i18n, load_file: { key => [mtime, digest] }) + end + + # Translate absolute filename to relative path for i18n key. + def normalized_path(file) + return file unless path_roots + path = path_roots.find(&file.method(:start_with?)) || + raise(InvalidLocaleData.new(file, 'outside expected path roots')) + file.sub(path, path_roots.index(path).to_s) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/cascade.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/cascade.rb new file mode 100644 index 0000000..782b07b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/cascade.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +# The Cascade module adds the ability to do cascading lookups to backends that +# are compatible to the Simple backend. +# +# By cascading lookups we mean that for any key that can not be found the +# Cascade module strips one segment off the scope part of the key and then +# tries to look up the key in that scope. +# +# E.g. when a lookup for the key :"foo.bar.baz" does not yield a result then +# the segment :bar will be stripped off the scope part :"foo.bar" and the new +# scope :foo will be used to look up the key :baz. If that does not succeed +# then the remaining scope segment :foo will be omitted, too, and again the +# key :baz will be looked up (now with no scope). +# +# To enable a cascading lookup one passes the :cascade option: +# +# I18n.t(:'foo.bar.baz', :cascade => true) +# +# This will return the first translation found for :"foo.bar.baz", :"foo.baz" +# or :baz in this order. +# +# The cascading lookup takes precedence over resolving any given defaults. +# I.e. defaults will kick in after the cascading lookups haven't succeeded. +# +# This behavior is useful for libraries like ActiveRecord validations where +# the library wants to give users a bunch of more or less fine-grained options +# of scopes for a particular key. +# +# Thanks to Clemens Kofler for the initial idea and implementation! See +# http://github.com/clemens/i18n-cascading-backend + +module I18n + module Backend + module Cascade + def lookup(locale, key, scope = [], options = EMPTY_HASH) + return super unless cascade = options[:cascade] + + cascade = { :step => 1 } unless cascade.is_a?(Hash) + step = cascade[:step] || 1 + offset = cascade[:offset] || 1 + separator = options[:separator] || I18n.default_separator + skip_root = cascade.has_key?(:skip_root) ? cascade[:skip_root] : true + + scope = I18n.normalize_keys(nil, key, scope, separator) + key = (scope.slice!(-offset, offset) || []).join(separator) + + begin + result = super + return result unless result.nil? + scope = scope.dup + end while (!scope.empty? || !skip_root) && scope.slice!(-step, step) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/chain.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/chain.rb new file mode 100644 index 0000000..525dd2d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/chain.rb @@ -0,0 +1,128 @@ +# frozen_string_literal: true + +module I18n + module Backend + # Backend that chains multiple other backends and checks each of them when + # a translation needs to be looked up. This is useful when you want to use + # standard translations with a Simple backend but store custom application + # translations in a database or other backends. + # + # To use the Chain backend instantiate it and set it to the I18n module. + # You can add chained backends through the initializer or backends + # accessor: + # + # # preserves the existing Simple backend set to I18n.backend + # I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend) + # + # The implementation assumes that all backends added to the Chain implement + # a lookup method with the same API as Simple backend does. + class Chain + module Implementation + include Base + + attr_accessor :backends + + def initialize(*backends) + self.backends = backends + end + + def initialized? + backends.all? do |backend| + backend.instance_eval do + return false unless initialized? + end + end + true + end + + def reload! + backends.each { |backend| backend.reload! } + end + + def eager_load! + backends.each { |backend| backend.eager_load! } + end + + def store_translations(locale, data, options = EMPTY_HASH) + backends.first.store_translations(locale, data, options) + end + + def available_locales + backends.map { |backend| backend.available_locales }.flatten.uniq + end + + def translate(locale, key, default_options = EMPTY_HASH) + namespace = nil + options = Utils.except(default_options, :default) + + backends.each do |backend| + catch(:exception) do + options = default_options if backend == backends.last + translation = backend.translate(locale, key, options) + if namespace_lookup?(translation, options) + namespace = _deep_merge(translation, namespace || {}) + elsif !translation.nil? || (options.key?(:default) && options[:default].nil?) + return translation + end + end + end + + return namespace if namespace + throw(:exception, I18n::MissingTranslation.new(locale, key, options)) + end + + def exists?(locale, key, options = EMPTY_HASH) + backends.any? do |backend| + backend.exists?(locale, key, options) + end + end + + def localize(locale, object, format = :default, options = EMPTY_HASH) + backends.each do |backend| + catch(:exception) do + result = backend.localize(locale, object, format, options) and return result + end + end + throw(:exception, I18n::MissingTranslation.new(locale, format, options)) + end + + protected + def init_translations + backends.each do |backend| + backend.send(:init_translations) + end + end + + def translations + backends.reverse.each_with_object({}) do |backend, memo| + partial_translations = backend.instance_eval do + init_translations unless initialized? + translations + end + Utils.deep_merge!(memo, partial_translations) { |_, a, b| b || a } + end + end + + def namespace_lookup?(result, options) + result.is_a?(Hash) && !options.has_key?(:count) + end + + private + # This is approximately what gets used in ActiveSupport. + # However since we are not guaranteed to run in an ActiveSupport context + # it is wise to have our own copy. We underscore it + # to not pollute the namespace of the including class. + def _deep_merge(hash, other_hash) + copy = hash.dup + other_hash.each_pair do |k,v| + value_from_other = hash[k] + copy[k] = value_from_other.is_a?(Hash) && v.is_a?(Hash) ? _deep_merge(value_from_other, v) : v + end + copy + end + end + + include Implementation + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/fallbacks.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/fallbacks.rb new file mode 100644 index 0000000..7afbfe3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/fallbacks.rb @@ -0,0 +1,115 @@ +# frozen_string_literal: true + +# I18n locale fallbacks are useful when you want your application to use +# translations from other locales when translations for the current locale are +# missing. E.g. you might want to use :en translations when translations in +# your applications main locale :de are missing. +# +# To enable locale fallbacks you can simply include the Fallbacks module to +# the Simple backend - or whatever other backend you are using: +# +# I18n::Backend::Simple.include(I18n::Backend::Fallbacks) +module I18n + @@fallbacks = nil + + class << self + # Returns the current fallbacks implementation. Defaults to +I18n::Locale::Fallbacks+. + def fallbacks + @@fallbacks ||= I18n::Locale::Fallbacks.new + Thread.current[:i18n_fallbacks] || @@fallbacks + end + + # Sets the current fallbacks implementation. Use this to set a different fallbacks implementation. + def fallbacks=(fallbacks) + @@fallbacks = fallbacks.is_a?(Array) ? I18n::Locale::Fallbacks.new(fallbacks) : fallbacks + Thread.current[:i18n_fallbacks] = @@fallbacks + end + end + + module Backend + module Fallbacks + # Overwrites the Base backend translate method so that it will try each + # locale given by I18n.fallbacks for the given locale. E.g. for the + # locale :"de-DE" it might try the locales :"de-DE", :de and :en + # (depends on the fallbacks implementation) until it finds a result with + # the given options. If it does not find any result for any of the + # locales it will then throw MissingTranslation as usual. + # + # The default option takes precedence over fallback locales only when + # it's a Symbol. When the default contains a String, Proc or Hash + # it is evaluated last after all the fallback locales have been tried. + def translate(locale, key, options = EMPTY_HASH) + return super unless options.fetch(:fallback, true) + return super if options[:fallback_in_progress] + default = extract_non_symbol_default!(options) if options[:default] + + fallback_options = options.merge(:fallback_in_progress => true, fallback_original_locale: locale) + I18n.fallbacks[locale].each do |fallback| + begin + catch(:exception) do + result = super(fallback, key, fallback_options) + unless result.nil? + on_fallback(locale, fallback, key, options) if locale.to_s != fallback.to_s + return result + end + end + rescue I18n::InvalidLocale + # we do nothing when the locale is invalid, as this is a fallback anyways. + end + end + + return if options.key?(:default) && options[:default].nil? + + return super(locale, nil, options.merge(:default => default)) if default + throw(:exception, I18n::MissingTranslation.new(locale, key, options)) + end + + def resolve_entry(locale, object, subject, options = EMPTY_HASH) + return subject if options[:resolve] == false + result = catch(:exception) do + options.delete(:fallback_in_progress) if options.key?(:fallback_in_progress) + + case subject + when Symbol + I18n.translate(subject, **options.merge(:locale => options[:fallback_original_locale], :throw => true)) + when Proc + date_or_time = options.delete(:object) || object + resolve_entry(options[:fallback_original_locale], object, subject.call(date_or_time, **options)) + else + subject + end + end + result unless result.is_a?(MissingTranslation) + end + + def extract_non_symbol_default!(options) + defaults = [options[:default]].flatten + first_non_symbol_default = defaults.detect{|default| !default.is_a?(Symbol)} + if first_non_symbol_default + options[:default] = defaults[0, defaults.index(first_non_symbol_default)] + end + return first_non_symbol_default + end + + def exists?(locale, key, options = EMPTY_HASH) + return super unless options.fetch(:fallback, true) + I18n.fallbacks[locale].each do |fallback| + begin + return true if super(fallback, key) + rescue I18n::InvalidLocale + # we do nothing when the locale is invalid, as this is a fallback anyways. + end + end + + false + end + + private + + # Overwrite on_fallback to add specified logic when the fallback succeeds. + def on_fallback(_original_locale, _fallback_locale, _key, _optoins) + nil + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/flatten.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/flatten.rb new file mode 100644 index 0000000..e9bd9d5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/flatten.rb @@ -0,0 +1,118 @@ +# frozen_string_literal: true + +module I18n + module Backend + # This module contains several helpers to assist flattening translations. + # You may want to flatten translations for: + # + # 1) speed up lookups, as in the Memoize backend; + # 2) In case you want to store translations in a data store, as in ActiveRecord backend; + # + # You can check both backends above for some examples. + # This module also keeps all links in a hash so they can be properly resolved when flattened. + module Flatten + SEPARATOR_ESCAPE_CHAR = "\001" + FLATTEN_SEPARATOR = "." + + # normalize_keys the flatten way. This method is significantly faster + # and creates way less objects than the one at I18n.normalize_keys. + # It also handles escaping the translation keys. + def self.normalize_flat_keys(locale, key, scope, separator) + keys = [scope, key] + keys.flatten! + keys.compact! + + separator ||= I18n.default_separator + + if separator != FLATTEN_SEPARATOR + from_str = "#{FLATTEN_SEPARATOR}#{separator}" + to_str = "#{SEPARATOR_ESCAPE_CHAR}#{FLATTEN_SEPARATOR}" + + keys.map! { |k| k.to_s.tr from_str, to_str } + end + + keys.join(".") + end + + # Receives a string and escape the default separator. + def self.escape_default_separator(key) #:nodoc: + key.to_s.tr(FLATTEN_SEPARATOR, SEPARATOR_ESCAPE_CHAR) + end + + # Shortcut to I18n::Backend::Flatten.normalize_flat_keys + # and then resolve_links. + def normalize_flat_keys(locale, key, scope, separator) + key = I18n::Backend::Flatten.normalize_flat_keys(locale, key, scope, separator) + resolve_link(locale, key) + end + + # Store flattened links. + def links + @links ||= I18n.new_double_nested_cache + end + + # Flatten keys for nested Hashes by chaining up keys: + # + # >> { "a" => { "b" => { "c" => "d", "e" => "f" }, "g" => "h" }, "i" => "j"}.wind + # => { "a.b.c" => "d", "a.b.e" => "f", "a.g" => "h", "i" => "j" } + # + def flatten_keys(hash, escape, prev_key=nil, &block) + hash.each_pair do |key, value| + key = escape_default_separator(key) if escape + curr_key = [prev_key, key].compact.join(FLATTEN_SEPARATOR).to_sym + yield curr_key, value + flatten_keys(value, escape, curr_key, &block) if value.is_a?(Hash) + end + end + + # Receives a hash of translations (where the key is a locale and + # the value is another hash) and return a hash with all + # translations flattened. + # + # Nested hashes are included in the flattened hash just if subtree + # is true and Symbols are automatically stored as links. + def flatten_translations(locale, data, escape, subtree) + hash = {} + flatten_keys(data, escape) do |key, value| + if value.is_a?(Hash) + hash[key] = value if subtree + else + store_link(locale, key, value) if value.is_a?(Symbol) + hash[key] = value + end + end + hash + end + + protected + + def store_link(locale, key, link) + links[locale.to_sym][key.to_s] = link.to_s + end + + def resolve_link(locale, key) + key, locale = key.to_s, locale.to_sym + links = self.links[locale] + + if links.key?(key) + links[key] + elsif link = find_link(locale, key) + store_link(locale, key, key.gsub(*link)) + else + key + end + end + + def find_link(locale, key) #:nodoc: + links[locale].each_pair do |from, to| + return [from, to] if key[0, from.length] == from + end && nil + end + + def escape_default_separator(key) #:nodoc: + I18n::Backend::Flatten.escape_default_separator(key) + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/gettext.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/gettext.rb new file mode 100644 index 0000000..0769646 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/gettext.rb @@ -0,0 +1,83 @@ +# frozen_string_literal: true + +require 'i18n/gettext' +require 'i18n/gettext/po_parser' + +module I18n + module Backend + # Experimental support for using Gettext po files to store translations. + # + # To use this you can simply include the module to the Simple backend - or + # whatever other backend you are using. + # + # I18n::Backend::Simple.include(I18n::Backend::Gettext) + # + # Now you should be able to include your Gettext translation (*.po) files to + # the +I18n.load_path+ so they're loaded to the backend and you can use them as + # usual: + # + # I18n.load_path += Dir["path/to/locales/*.po"] + # + # Following the Gettext convention this implementation expects that your + # translation files are named by their locales. E.g. the file en.po would + # contain the translations for the English locale. + # + # To translate text you must use one of the translate methods provided by + # I18n::Gettext::Helpers. + # + # include I18n::Gettext::Helpers + # puts _("some string") + # + # Without it strings containing periods (".") will not be translated. + + module Gettext + class PoData < Hash + def set_comment(msgid_or_sym, comment) + # ignore + end + end + + protected + def load_po(filename) + locale = ::File.basename(filename, '.po').to_sym + data = normalize(locale, parse(filename)) + [{ locale => data }, false] + end + + def parse(filename) + GetText::PoParser.new.parse(::File.read(filename), PoData.new) + end + + def normalize(locale, data) + data.inject({}) do |result, (key, value)| + unless key.nil? || key.empty? + key = key.gsub(I18n::Gettext::CONTEXT_SEPARATOR, '|') + key, value = normalize_pluralization(locale, key, value) if key.index("\000") + + parts = key.split('|').reverse + normalized = parts.inject({}) do |_normalized, part| + { part => _normalized.empty? ? value : _normalized } + end + + Utils.deep_merge!(result, normalized) + end + result + end + end + + def normalize_pluralization(locale, key, value) + # FIXME po_parser includes \000 chars that can not be turned into Symbols + key = key.gsub("\000", I18n::Gettext::PLURAL_SEPARATOR).split(I18n::Gettext::PLURAL_SEPARATOR).first + + keys = I18n::Gettext.plural_keys(locale) + values = value.split("\000") + raise "invalid number of plurals: #{values.size}, keys: #{keys.inspect} on #{locale} locale for msgid #{key.inspect} with values #{values.inspect}" if values.size != keys.size + + result = {} + values.each_with_index { |_value, ix| result[keys[ix]] = _value } + [key, result] + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/interpolation_compiler.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/interpolation_compiler.rb new file mode 100644 index 0000000..8b52e7b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/interpolation_compiler.rb @@ -0,0 +1,123 @@ +# frozen_string_literal: true + +# The InterpolationCompiler module contains optimizations that can tremendously +# speed up the interpolation process on the Simple backend. +# +# It works by defining a pre-compiled method on stored translation Strings that +# already bring all the knowledge about contained interpolation variables etc. +# so that the actual recurring interpolation will be very fast. +# +# To enable pre-compiled interpolations you can simply include the +# InterpolationCompiler module to the Simple backend: +# +# I18n::Backend::Simple.include(I18n::Backend::InterpolationCompiler) +# +# Note that InterpolationCompiler does not yield meaningful results and consequently +# should not be used with Ruby 1.9 (YARV) but improves performance everywhere else +# (jRuby, Rubinius). +module I18n + module Backend + module InterpolationCompiler + module Compiler + extend self + + TOKENIZER = /(%%\{[^\}]+\}|%\{[^\}]+\})/ + INTERPOLATION_SYNTAX_PATTERN = /(%)?(%\{([^\}]+)\})/ + + def compile_if_an_interpolation(string) + if interpolated_str?(string) + string.instance_eval <<-RUBY_EVAL, __FILE__, __LINE__ + def i18n_interpolate(v = {}) + "#{compiled_interpolation_body(string)}" + end + RUBY_EVAL + end + + string + end + + def interpolated_str?(str) + str.kind_of?(::String) && str =~ INTERPOLATION_SYNTAX_PATTERN + end + + protected + # tokenize("foo %{bar} baz %%{buz}") # => ["foo ", "%{bar}", " baz ", "%%{buz}"] + def tokenize(str) + str.split(TOKENIZER) + end + + def compiled_interpolation_body(str) + tokenize(str).map do |token| + (matchdata = token.match(INTERPOLATION_SYNTAX_PATTERN)) ? handle_interpolation_token(token, matchdata) : escape_plain_str(token) + end.join + end + + def handle_interpolation_token(interpolation, matchdata) + escaped, pattern, key = matchdata.values_at(1, 2, 3) + escaped ? pattern : compile_interpolation_token(key.to_sym) + end + + def compile_interpolation_token(key) + "\#{#{interpolate_or_raise_missing(key)}}" + end + + def interpolate_or_raise_missing(key) + escaped_key = escape_key_sym(key) + RESERVED_KEYS.include?(key) ? reserved_key(escaped_key) : interpolate_key(escaped_key) + end + + def interpolate_key(key) + [direct_key(key), nil_key(key), missing_key(key)].join('||') + end + + def direct_key(key) + "((t = v[#{key}]) && t.respond_to?(:call) ? t.call : t)" + end + + def nil_key(key) + "(v.has_key?(#{key}) && '')" + end + + def missing_key(key) + "I18n.config.missing_interpolation_argument_handler.call(#{key}, v, self)" + end + + def reserved_key(key) + "raise(ReservedInterpolationKey.new(#{key}, self))" + end + + def escape_plain_str(str) + str.gsub(/"|\\|#/) {|x| "\\#{x}"} + end + + def escape_key_sym(key) + # rely on Ruby to do all the hard work :) + key.to_sym.inspect + end + end + + def interpolate(locale, string, values) + if string.respond_to?(:i18n_interpolate) + string.i18n_interpolate(values) + elsif values + super + else + string + end + end + + def store_translations(locale, data, options = EMPTY_HASH) + compile_all_strings_in(data) + super + end + + protected + def compile_all_strings_in(data) + data.each_value do |value| + Compiler.compile_if_an_interpolation(value) + compile_all_strings_in(value) if value.kind_of?(Hash) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/key_value.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/key_value.rb new file mode 100644 index 0000000..b937e25 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/key_value.rb @@ -0,0 +1,204 @@ +# frozen_string_literal: true + +require 'i18n/backend/base' + +module I18n + + begin + require 'oj' + class JSON + class << self + def encode(value) + Oj::Rails.encode(value) + end + def decode(value) + Oj.load(value) + end + end + end + rescue LoadError + require 'active_support/json' + JSON = ActiveSupport::JSON + end + + module Backend + # This is a basic backend for key value stores. It receives on + # initialization the store, which should respond to three methods: + # + # * store#[](key) - Used to get a value + # * store#[]=(key, value) - Used to set a value + # * store#keys - Used to get all keys + # + # Since these stores only supports string, all values are converted + # to JSON before being stored, allowing it to also store booleans, + # hashes and arrays. However, this store does not support Procs. + # + # As the ActiveRecord backend, Symbols are just supported when loading + # translations from the filesystem or through explicit store translations. + # + # Also, avoid calling I18n.available_locales since it's a somehow + # expensive operation in most stores. + # + # == Example + # + # To setup I18n to use TokyoCabinet in memory is quite straightforward: + # + # require 'rufus/tokyo/cabinet' # gem install rufus-tokyo + # I18n.backend = I18n::Backend::KeyValue.new(Rufus::Tokyo::Cabinet.new('*')) + # + # == Performance + # + # You may make this backend even faster by including the Memoize module. + # However, notice that you should properly clear the cache if you change + # values directly in the key-store. + # + # == Subtrees + # + # In most backends, you are allowed to retrieve part of a translation tree: + # + # I18n.backend.store_translations :en, :foo => { :bar => :baz } + # I18n.t "foo" #=> { :bar => :baz } + # + # This backend supports this feature by default, but it slows down the storage + # of new data considerably and makes hard to delete entries. That said, you are + # allowed to disable the storage of subtrees on initialization: + # + # I18n::Backend::KeyValue.new(@store, false) + # + # This is useful if you are using a KeyValue backend chained to a Simple backend. + class KeyValue + module Implementation + attr_accessor :store + + include Base, Flatten + + def initialize(store, subtrees=true) + @store, @subtrees = store, subtrees + end + + def initialized? + !@store.nil? + end + + def store_translations(locale, data, options = EMPTY_HASH) + escape = options.fetch(:escape, true) + flatten_translations(locale, data, escape, @subtrees).each do |key, value| + key = "#{locale}.#{key}" + + case value + when Hash + if @subtrees && (old_value = @store[key]) + old_value = JSON.decode(old_value) + value = Utils.deep_merge!(Utils.deep_symbolize_keys(old_value), value) if old_value.is_a?(Hash) + end + when Proc + raise "Key-value stores cannot handle procs" + end + + @store[key] = JSON.encode(value) unless value.is_a?(Symbol) + end + end + + def available_locales + locales = @store.keys.map { |k| k =~ /\./; $` } + locales.uniq! + locales.compact! + locales.map! { |k| k.to_sym } + locales + end + + protected + + # Queries the translations from the key-value store and converts + # them into a hash such as the one returned from loading the + # haml files + def translations + @translations = Utils.deep_symbolize_keys(@store.keys.clone.map do |main_key| + main_value = JSON.decode(@store[main_key]) + main_key.to_s.split(".").reverse.inject(main_value) do |value, key| + {key.to_sym => value} + end + end.inject{|hash, elem| Utils.deep_merge!(hash, elem)}) + end + + def init_translations + # NO OP + # This call made also inside Simple Backend and accessed by + # other plugins like I18n-js and babilu and + # to use it along with the Chain backend we need to + # provide a uniform API even for protected methods :S + end + + def subtrees? + @subtrees + end + + def lookup(locale, key, scope = [], options = EMPTY_HASH) + key = normalize_flat_keys(locale, key, scope, options[:separator]) + value = @store["#{locale}.#{key}"] + value = JSON.decode(value) if value + + if value.is_a?(Hash) + Utils.deep_symbolize_keys(value) + elsif !value.nil? + value + elsif !@subtrees + SubtreeProxy.new("#{locale}.#{key}", @store) + end + end + + def pluralize(locale, entry, count) + if subtrees? + super + else + return entry unless entry.is_a?(Hash) + key = pluralization_key(entry, count) + entry[key] + end + end + end + + class SubtreeProxy + def initialize(master_key, store) + @master_key = master_key + @store = store + @subtree = nil + end + + def has_key?(key) + @subtree && @subtree.has_key?(key) || self[key] + end + + def [](key) + unless @subtree && value = @subtree[key] + value = @store["#{@master_key}.#{key}"] + if value + value = JSON.decode(value) + (@subtree ||= {})[key] = value + end + end + value + end + + def is_a?(klass) + Hash == klass || super + end + alias :kind_of? :is_a? + + def instance_of?(klass) + Hash == klass || super + end + + def nil? + @subtree.nil? + end + + def inspect + @subtree.inspect + end + end + + include Implementation + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/lazy_loadable.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/lazy_loadable.rb new file mode 100644 index 0000000..60f21fa --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/lazy_loadable.rb @@ -0,0 +1,184 @@ +# frozen_string_literal: true + +module I18n + module Backend + # Backend that lazy loads translations based on the current locale. This + # implementation avoids loading all translations up front. Instead, it only + # loads the translations that belong to the current locale. This offers a + # performance incentive in local development and test environments for + # applications with many translations for many different locales. It's + # particularly useful when the application only refers to a single locales' + # translations at a time (ex. A Rails workload). The implementation + # identifies which translation files from the load path belong to the + # current locale by pattern matching against their path name. + # + # Specifically, a translation file is considered to belong to a locale if: + # a) the filename is in the I18n load path + # b) the filename ends in a supported extension (ie. .yml, .json, .po, .rb) + # c) the filename starts with the locale identifier + # d) the locale identifier and optional proceeding text is separated by an underscore, ie. "_". + # + # Examples: + # Valid files that will be selected by this backend: + # + # "files/locales/en_translation.yml" (Selected for locale "en") + # "files/locales/fr.po" (Selected for locale "fr") + # + # Invalid files that won't be selected by this backend: + # + # "files/locales/translation-file" + # "files/locales/en-translation.unsupported" + # "files/locales/french/translation.yml" + # "files/locales/fr/translation.yml" + # + # The implementation uses this assumption to defer the loading of + # translation files until the current locale actually requires them. + # + # The backend has two working modes: lazy_load and eager_load. + # + # Note: This backend should only be enabled in test environments! + # When the mode is set to false, the backend behaves exactly like the + # Simple backend, with an additional check that the paths being loaded + # abide by the format. If paths can't be matched to the format, an error is raised. + # + # You can configure lazy loaded backends through the initializer or backends + # accessor: + # + # # In test environments + # + # I18n.backend = I18n::Backend::LazyLoadable.new(lazy_load: true) + # + # # In other environments, such as production and CI + # + # I18n.backend = I18n::Backend::LazyLoadable.new(lazy_load: false) # default + # + class LocaleExtractor + class << self + def locale_from_path(path) + name = File.basename(path, ".*") + locale = name.split("_").first + locale.to_sym unless locale.nil? + end + end + end + + class LazyLoadable < Simple + def initialize(lazy_load: false) + @lazy_load = lazy_load + end + + # Returns whether the current locale is initialized. + def initialized? + if lazy_load? + initialized_locales[I18n.locale] + else + super + end + end + + # Clean up translations and uninitialize all locales. + def reload! + if lazy_load? + @initialized_locales = nil + @translations = nil + else + super + end + end + + # Eager loading is not supported in the lazy context. + def eager_load! + if lazy_load? + raise UnsupportedMethod.new(__method__, self.class, "Cannot eager load translations because backend was configured with lazy_load: true.") + else + super + end + end + + # Parse the load path and extract all locales. + def available_locales + if lazy_load? + I18n.load_path.map { |path| LocaleExtractor.locale_from_path(path) } + else + super + end + end + + def lookup(locale, key, scope = [], options = EMPTY_HASH) + if lazy_load? + I18n.with_locale(locale) do + super + end + else + super + end + end + + protected + + + # Load translations from files that belong to the current locale. + def init_translations + file_errors = if lazy_load? + initialized_locales[I18n.locale] = true + load_translations_and_collect_file_errors(filenames_for_current_locale) + else + @initialized = true + load_translations_and_collect_file_errors(I18n.load_path) + end + + raise InvalidFilenames.new(file_errors) unless file_errors.empty? + end + + def initialized_locales + @initialized_locales ||= Hash.new(false) + end + + private + + def lazy_load? + @lazy_load + end + + class FilenameIncorrect < StandardError + def initialize(file, expected_locale, unexpected_locales) + super "#{file} can only load translations for \"#{expected_locale}\". Found translations for: #{unexpected_locales}." + end + end + + # Loads each file supplied and asserts that the file only loads + # translations as expected by the name. The method returns a list of + # errors corresponding to offending files. + def load_translations_and_collect_file_errors(files) + errors = [] + + load_translations(files) do |file, loaded_translations| + assert_file_named_correctly!(file, loaded_translations) + rescue FilenameIncorrect => e + errors << e + end + + errors + end + + # Select all files from I18n load path that belong to current locale. + # These files must start with the locale identifier (ie. "en", "pt-BR"), + # followed by an "_" demarcation to separate proceeding text. + def filenames_for_current_locale + I18n.load_path.flatten.select do |path| + LocaleExtractor.locale_from_path(path) == I18n.locale + end + end + + # Checks if a filename is named in correspondence to the translations it loaded. + # The locale extracted from the path must be the single locale loaded in the translations. + def assert_file_named_correctly!(file, translations) + loaded_locales = translations.keys.map(&:to_sym) + expected_locale = LocaleExtractor.locale_from_path(file) + unexpected_locales = loaded_locales.reject { |locale| locale == expected_locale } + + raise FilenameIncorrect.new(file, expected_locale, unexpected_locales) unless unexpected_locales.empty? + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/memoize.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/memoize.rb new file mode 100644 index 0000000..3293d2b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/memoize.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +# Memoize module simply memoizes the values returned by lookup using +# a flat hash and can tremendously speed up the lookup process in a backend. +# +# To enable it you can simply include the Memoize module to your backend: +# +# I18n::Backend::Simple.include(I18n::Backend::Memoize) +# +# Notice that it's the responsibility of the backend to define whenever the +# cache should be cleaned. +module I18n + module Backend + module Memoize + def available_locales + @memoized_locales ||= super + end + + def store_translations(locale, data, options = EMPTY_HASH) + reset_memoizations!(locale) + super + end + + def reload! + reset_memoizations! + super + end + + def eager_load! + memoized_lookup + available_locales + super + end + + protected + + def lookup(locale, key, scope = nil, options = EMPTY_HASH) + flat_key = I18n::Backend::Flatten.normalize_flat_keys(locale, + key, scope, options[:separator]).to_sym + flat_hash = memoized_lookup[locale.to_sym] + flat_hash.key?(flat_key) ? flat_hash[flat_key] : (flat_hash[flat_key] = super) + end + + def memoized_lookup + @memoized_lookup ||= I18n.new_double_nested_cache + end + + def reset_memoizations!(locale=nil) + @memoized_locales = nil + (locale ? memoized_lookup[locale.to_sym] : memoized_lookup).clear + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/metadata.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/metadata.rb new file mode 100644 index 0000000..51ea7a2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/metadata.rb @@ -0,0 +1,71 @@ +# frozen_string_literal: true + +# I18n translation metadata is useful when you want to access information +# about how a translation was looked up, pluralized or interpolated in +# your application. +# +# msg = I18n.t(:message, :default => 'Hi!', :scope => :foo) +# msg.translation_metadata +# # => { :key => :message, :scope => :foo, :default => 'Hi!' } +# +# If a :count option was passed to #translate it will be set to the metadata. +# Likewise, if any interpolation variables were passed they will also be set. +# +# To enable translation metadata you can simply include the Metadata module +# into the Simple backend class - or whatever other backend you are using: +# +# I18n::Backend::Simple.include(I18n::Backend::Metadata) +# +module I18n + module Backend + module Metadata + class << self + def included(base) + Object.class_eval do + def translation_metadata + unless self.frozen? + @translation_metadata ||= {} + else + {} + end + end + + def translation_metadata=(translation_metadata) + @translation_metadata = translation_metadata unless self.frozen? + end + end unless Object.method_defined?(:translation_metadata) + end + end + + def translate(locale, key, options = EMPTY_HASH) + metadata = { + :locale => locale, + :key => key, + :scope => options[:scope], + :default => options[:default], + :separator => options[:separator], + :values => options.reject { |name, _value| RESERVED_KEYS.include?(name) } + } + with_metadata(metadata) { super } + end + + def interpolate(locale, entry, values = EMPTY_HASH) + metadata = entry.translation_metadata.merge(:original => entry) + with_metadata(metadata) { super } + end + + def pluralize(locale, entry, count) + with_metadata(:count => count) { super } + end + + protected + + def with_metadata(metadata, &block) + result = yield + result.translation_metadata = result.translation_metadata.merge(metadata) if result + result + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/pluralization.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/pluralization.rb new file mode 100644 index 0000000..b602657 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/pluralization.rb @@ -0,0 +1,55 @@ +# frozen_string_literal: true + +# I18n Pluralization are useful when you want your application to +# customize pluralization rules. +# +# To enable locale specific pluralizations you can simply include the +# Pluralization module to the Simple backend - or whatever other backend you +# are using. +# +# I18n::Backend::Simple.include(I18n::Backend::Pluralization) +# +# You also need to make sure to provide pluralization algorithms to the +# backend, i.e. include them to your I18n.load_path accordingly. +module I18n + module Backend + module Pluralization + # Overwrites the Base backend translate method so that it will check the + # translation meta data space (:i18n) for a locale specific pluralization + # rule and use it to pluralize the given entry. I.e. the library expects + # pluralization rules to be stored at I18n.t(:'i18n.plural.rule') + # + # Pluralization rules are expected to respond to #call(count) and + # return a pluralization key. Valid keys depend on the translation data + # hash (entry) but it is generally recommended to follow CLDR's style, + # i.e., return one of the keys :zero, :one, :few, :many, :other. + # + # The :zero key is always picked directly when count equals 0 AND the + # translation data has the key :zero. This way translators are free to + # either pick a special :zero translation even for languages where the + # pluralizer does not return a :zero key. + def pluralize(locale, entry, count) + return entry unless entry.is_a?(Hash) && count + + pluralizer = pluralizer(locale) + if pluralizer.respond_to?(:call) + key = count == 0 && entry.has_key?(:zero) ? :zero : pluralizer.call(count) + raise InvalidPluralizationData.new(entry, count, key) unless entry.has_key?(key) + entry[key] + else + super + end + end + + protected + + def pluralizers + @pluralizers ||= {} + end + + def pluralizer(locale) + pluralizers[locale] ||= I18n.t(:'i18n.plural.rule', :locale => locale, :resolve => false) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/simple.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/simple.rb new file mode 100644 index 0000000..0c49de8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/simple.rb @@ -0,0 +1,106 @@ +# frozen_string_literal: true + +require 'i18n/backend/base' + +module I18n + module Backend + # A simple backend that reads translations from YAML files and stores them in + # an in-memory hash. Relies on the Base backend. + # + # The implementation is provided by a Implementation module allowing to easily + # extend Simple backend's behavior by including modules. E.g.: + # + # module I18n::Backend::Pluralization + # def pluralize(*args) + # # extended pluralization logic + # super + # end + # end + # + # I18n::Backend::Simple.include(I18n::Backend::Pluralization) + class Simple + module Implementation + include Base + + def initialized? + @initialized ||= false + end + + # Stores translations for the given locale in memory. + # This uses a deep merge for the translations hash, so existing + # translations will be overwritten by new ones only at the deepest + # level of the hash. + def store_translations(locale, data, options = EMPTY_HASH) + if I18n.enforce_available_locales && + I18n.available_locales_initialized? && + !I18n.locale_available?(locale) + return data + end + locale = locale.to_sym + translations[locale] ||= Concurrent::Hash.new + data = Utils.deep_symbolize_keys(data) unless options.fetch(:skip_symbolize_keys, false) + Utils.deep_merge!(translations[locale], data) + end + + # Get available locales from the translations hash + def available_locales + init_translations unless initialized? + translations.inject([]) do |locales, (locale, data)| + locales << locale unless data.size <= 1 && (data.empty? || data.has_key?(:i18n)) + locales + end + end + + # Clean up translations hash and set initialized to false on reload! + def reload! + @initialized = false + @translations = nil + super + end + + def eager_load! + init_translations unless initialized? + super + end + + def translations(do_init: false) + # To avoid returning empty translations, + # call `init_translations` + init_translations if do_init && !initialized? + + @translations ||= Concurrent::Hash.new { |h, k| h[k] = Concurrent::Hash.new } + end + + protected + + def init_translations + load_translations + @initialized = true + end + + # Looks up a translation from the translations hash. Returns nil if + # either key is nil, or locale, scope or key do not exist as a key in the + # nested translations hash. Splits keys or scopes containing dots + # into multiple keys, i.e. currency.format is regarded the same as + # %w(currency format). + def lookup(locale, key, scope = [], options = EMPTY_HASH) + init_translations unless initialized? + keys = I18n.normalize_keys(locale, key, scope, options[:separator]) + + keys.inject(translations) do |result, _key| + return nil unless result.is_a?(Hash) + unless result.has_key?(_key) + _key = _key.to_s.to_sym + return nil unless result.has_key?(_key) + end + result = result[_key] + result = resolve_entry(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol) + result + end + end + end + + include Implementation + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/transliterator.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/transliterator.rb new file mode 100644 index 0000000..bb704ab --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/backend/transliterator.rb @@ -0,0 +1,108 @@ +# encoding: utf-8 +# frozen_string_literal: true + +module I18n + module Backend + module Transliterator + DEFAULT_REPLACEMENT_CHAR = "?" + + # Given a locale and a UTF-8 string, return the locale's ASCII + # approximation for the string. + def transliterate(locale, string, replacement = nil) + @transliterators ||= {} + @transliterators[locale] ||= Transliterator.get I18n.t(:'i18n.transliterate.rule', + :locale => locale, :resolve => false, :default => {}) + @transliterators[locale].transliterate(string, replacement) + end + + # Get a transliterator instance. + def self.get(rule = nil) + if !rule || rule.kind_of?(Hash) + HashTransliterator.new(rule) + elsif rule.kind_of? Proc + ProcTransliterator.new(rule) + else + raise I18n::ArgumentError, "Transliteration rule must be a proc or a hash." + end + end + + # A transliterator which accepts a Proc as its transliteration rule. + class ProcTransliterator + def initialize(rule) + @rule = rule + end + + def transliterate(string, replacement = nil) + @rule.call(string) + end + end + + # A transliterator which accepts a Hash of characters as its translation + # rule. + class HashTransliterator + DEFAULT_APPROXIMATIONS = { + "À"=>"A", "Á"=>"A", "Â"=>"A", "Ã"=>"A", "Ä"=>"A", "Å"=>"A", "Æ"=>"AE", + "Ç"=>"C", "È"=>"E", "É"=>"E", "Ê"=>"E", "Ë"=>"E", "Ì"=>"I", "Í"=>"I", + "Î"=>"I", "Ï"=>"I", "Ð"=>"D", "Ñ"=>"N", "Ò"=>"O", "Ó"=>"O", "Ô"=>"O", + "Õ"=>"O", "Ö"=>"O", "×"=>"x", "Ø"=>"O", "Ù"=>"U", "Ú"=>"U", "Û"=>"U", + "Ü"=>"U", "Ý"=>"Y", "Þ"=>"Th", "ß"=>"ss", "à"=>"a", "á"=>"a", "â"=>"a", + "ã"=>"a", "ä"=>"a", "å"=>"a", "æ"=>"ae", "ç"=>"c", "è"=>"e", "é"=>"e", + "ê"=>"e", "ë"=>"e", "ì"=>"i", "í"=>"i", "î"=>"i", "ï"=>"i", "ð"=>"d", + "ñ"=>"n", "ò"=>"o", "ó"=>"o", "ô"=>"o", "õ"=>"o", "ö"=>"o", "ø"=>"o", + "ù"=>"u", "ú"=>"u", "û"=>"u", "ü"=>"u", "ý"=>"y", "þ"=>"th", "ÿ"=>"y", + "Ā"=>"A", "ā"=>"a", "Ă"=>"A", "ă"=>"a", "Ą"=>"A", "ą"=>"a", "Ć"=>"C", + "ć"=>"c", "Ĉ"=>"C", "ĉ"=>"c", "Ċ"=>"C", "ċ"=>"c", "Č"=>"C", "č"=>"c", + "Ď"=>"D", "ď"=>"d", "Đ"=>"D", "đ"=>"d", "Ē"=>"E", "ē"=>"e", "Ĕ"=>"E", + "ĕ"=>"e", "Ė"=>"E", "ė"=>"e", "Ę"=>"E", "ę"=>"e", "Ě"=>"E", "ě"=>"e", + "Ĝ"=>"G", "ĝ"=>"g", "Ğ"=>"G", "ğ"=>"g", "Ġ"=>"G", "ġ"=>"g", "Ģ"=>"G", + "ģ"=>"g", "Ĥ"=>"H", "ĥ"=>"h", "Ħ"=>"H", "ħ"=>"h", "Ĩ"=>"I", "ĩ"=>"i", + "Ī"=>"I", "ī"=>"i", "Ĭ"=>"I", "ĭ"=>"i", "Į"=>"I", "į"=>"i", "İ"=>"I", + "ı"=>"i", "IJ"=>"IJ", "ij"=>"ij", "Ĵ"=>"J", "ĵ"=>"j", "Ķ"=>"K", "ķ"=>"k", + "ĸ"=>"k", "Ĺ"=>"L", "ĺ"=>"l", "Ļ"=>"L", "ļ"=>"l", "Ľ"=>"L", "ľ"=>"l", + "Ŀ"=>"L", "ŀ"=>"l", "Ł"=>"L", "ł"=>"l", "Ń"=>"N", "ń"=>"n", "Ņ"=>"N", + "ņ"=>"n", "Ň"=>"N", "ň"=>"n", "ʼn"=>"'n", "Ŋ"=>"NG", "ŋ"=>"ng", + "Ō"=>"O", "ō"=>"o", "Ŏ"=>"O", "ŏ"=>"o", "Ő"=>"O", "ő"=>"o", "Œ"=>"OE", + "œ"=>"oe", "Ŕ"=>"R", "ŕ"=>"r", "Ŗ"=>"R", "ŗ"=>"r", "Ř"=>"R", "ř"=>"r", + "Ś"=>"S", "ś"=>"s", "Ŝ"=>"S", "ŝ"=>"s", "Ş"=>"S", "ş"=>"s", "Š"=>"S", + "š"=>"s", "Ţ"=>"T", "ţ"=>"t", "Ť"=>"T", "ť"=>"t", "Ŧ"=>"T", "ŧ"=>"t", + "Ũ"=>"U", "ũ"=>"u", "Ū"=>"U", "ū"=>"u", "Ŭ"=>"U", "ŭ"=>"u", "Ů"=>"U", + "ů"=>"u", "Ű"=>"U", "ű"=>"u", "Ų"=>"U", "ų"=>"u", "Ŵ"=>"W", "ŵ"=>"w", + "Ŷ"=>"Y", "ŷ"=>"y", "Ÿ"=>"Y", "Ź"=>"Z", "ź"=>"z", "Ż"=>"Z", "ż"=>"z", + "Ž"=>"Z", "ž"=>"z" + }.freeze + + def initialize(rule = nil) + @rule = rule + add_default_approximations + add rule if rule + end + + def transliterate(string, replacement = nil) + replacement ||= DEFAULT_REPLACEMENT_CHAR + string.gsub(/[^\x00-\x7f]/u) do |char| + approximations[char] || replacement + end + end + + private + + def approximations + @approximations ||= {} + end + + def add_default_approximations + DEFAULT_APPROXIMATIONS.each do |key, value| + approximations[key] = value + end + end + + # Add transliteration rules to the approximations hash. + def add(hash) + hash.each do |key, value| + approximations[key.to_s] = value.to_s + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/config.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/config.rb new file mode 100644 index 0000000..ea3dd1e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/config.rb @@ -0,0 +1,165 @@ +# frozen_string_literal: true + +require 'set' + +module I18n + class Config + # The only configuration value that is not global and scoped to thread is :locale. + # It defaults to the default_locale. + def locale + defined?(@locale) && @locale != nil ? @locale : default_locale + end + + # Sets the current locale pseudo-globally, i.e. in the Thread.current hash. + def locale=(locale) + I18n.enforce_available_locales!(locale) + @locale = locale && locale.to_sym + end + + # Returns the current backend. Defaults to +Backend::Simple+. + def backend + @@backend ||= Backend::Simple.new + end + + # Sets the current backend. Used to set a custom backend. + def backend=(backend) + @@backend = backend + end + + # Returns the current default locale. Defaults to :'en' + def default_locale + @@default_locale ||= :en + end + + # Sets the current default locale. Used to set a custom default locale. + def default_locale=(locale) + I18n.enforce_available_locales!(locale) + @@default_locale = locale && locale.to_sym + end + + # Returns an array of locales for which translations are available. + # Unless you explicitely set these through I18n.available_locales= + # the call will be delegated to the backend. + def available_locales + @@available_locales ||= nil + @@available_locales || backend.available_locales + end + + # Caches the available locales list as both strings and symbols in a Set, so + # that we can have faster lookups to do the available locales enforce check. + def available_locales_set #:nodoc: + @@available_locales_set ||= available_locales.inject(Set.new) do |set, locale| + set << locale.to_s << locale.to_sym + end + end + + # Sets the available locales. + def available_locales=(locales) + @@available_locales = Array(locales).map { |locale| locale.to_sym } + @@available_locales = nil if @@available_locales.empty? + @@available_locales_set = nil + end + + # Returns true if the available_locales have been initialized + def available_locales_initialized? + ( !!defined?(@@available_locales) && !!@@available_locales ) + end + + # Clears the available locales set so it can be recomputed again after I18n + # gets reloaded. + def clear_available_locales_set #:nodoc: + @@available_locales_set = nil + end + + # Returns the current default scope separator. Defaults to '.' + def default_separator + @@default_separator ||= '.' + end + + # Sets the current default scope separator. + def default_separator=(separator) + @@default_separator = separator + end + + # Returns the current exception handler. Defaults to an instance of + # I18n::ExceptionHandler. + def exception_handler + @@exception_handler ||= ExceptionHandler.new + end + + # Sets the exception handler. + def exception_handler=(exception_handler) + @@exception_handler = exception_handler + end + + # Returns the current handler for situations when interpolation argument + # is missing. MissingInterpolationArgument will be raised by default. + def missing_interpolation_argument_handler + @@missing_interpolation_argument_handler ||= lambda do |missing_key, provided_hash, string| + raise MissingInterpolationArgument.new(missing_key, provided_hash, string) + end + end + + # Sets the missing interpolation argument handler. It can be any + # object that responds to #call. The arguments that will be passed to #call + # are the same as for MissingInterpolationArgument initializer. Use +Proc.new+ + # if you don't care about arity. + # + # == Example: + # You can supress raising an exception and return string instead: + # + # I18n.config.missing_interpolation_argument_handler = Proc.new do |key| + # "#{key} is missing" + # end + def missing_interpolation_argument_handler=(exception_handler) + @@missing_interpolation_argument_handler = exception_handler + end + + # Allow clients to register paths providing translation data sources. The + # backend defines acceptable sources. + # + # E.g. the provided SimpleBackend accepts a list of paths to translation + # files which are either named *.rb and contain plain Ruby Hashes or are + # named *.yml and contain YAML data. So for the SimpleBackend clients may + # register translation files like this: + # I18n.load_path << 'path/to/locale/en.yml' + def load_path + @@load_path ||= [] + end + + # Sets the load path instance. Custom implementations are expected to + # behave like a Ruby Array. + def load_path=(load_path) + @@load_path = load_path + @@available_locales_set = nil + backend.reload! + end + + # Whether or not to verify if locales are in the list of available locales. + # Defaults to true. + @@enforce_available_locales = true + def enforce_available_locales + @@enforce_available_locales + end + + def enforce_available_locales=(enforce_available_locales) + @@enforce_available_locales = enforce_available_locales + end + + # Returns the current interpolation patterns. Defaults to + # I18n::DEFAULT_INTERPOLATION_PATTERNS. + def interpolation_patterns + @@interpolation_patterns ||= I18n::DEFAULT_INTERPOLATION_PATTERNS.dup + end + + # Sets the current interpolation patterns. Used to set a interpolation + # patterns. + # + # E.g. using {{}} as a placeholder like "{{hello}}, world!": + # + # I18n.config.interpolation_patterns << /\{\{(\w+)\}\}/ + def interpolation_patterns=(interpolation_patterns) + @@interpolation_patterns = interpolation_patterns + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/exceptions.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/exceptions.rb new file mode 100644 index 0000000..f66e207 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/exceptions.rb @@ -0,0 +1,147 @@ +# frozen_string_literal: true + +require 'cgi' + +module I18n + class ExceptionHandler + def call(exception, _locale, _key, _options) + if exception.is_a?(MissingTranslation) + exception.message + else + raise exception + end + end + end + + class ArgumentError < ::ArgumentError; end + + class Disabled < ArgumentError + def initialize(method) + super(<<~MESSAGE) + I18n.#{method} is currently disabled, likely because your application is still in its loading phase. + + This method is meant to display text in the user locale, so calling it before the user locale has + been set is likely to display text from the wrong locale to some users. + + If you have a legitimate reason to access i18n data outside of the user flow, you can do so by passing + the desired locale explictly with the `locale` argument, e.g. `I18n.#{method}(..., locale: :en)` + MESSAGE + end + end + + class InvalidLocale < ArgumentError + attr_reader :locale + def initialize(locale) + @locale = locale + super "#{locale.inspect} is not a valid locale" + end + end + + class InvalidLocaleData < ArgumentError + attr_reader :filename + def initialize(filename, exception_message) + @filename, @exception_message = filename, exception_message + super "can not load translations from #{filename}: #{exception_message}" + end + end + + class MissingTranslation < ArgumentError + module Base + PERMITTED_KEYS = [:scope].freeze + + attr_reader :locale, :key, :options + + def initialize(locale, key, options = EMPTY_HASH) + @key, @locale, @options = key, locale, options.slice(*PERMITTED_KEYS) + options.each { |k, v| self.options[k] = v.inspect if v.is_a?(Proc) } + end + + def keys + @keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys| + keys << 'no key' if keys.size < 2 + end + end + + def message + "translation missing: #{keys.join('.')}" + end + alias :to_s :message + + def to_exception + MissingTranslationData.new(locale, key, options) + end + end + + include Base + end + + class MissingTranslationData < ArgumentError + include MissingTranslation::Base + end + + class InvalidPluralizationData < ArgumentError + attr_reader :entry, :count, :key + def initialize(entry, count, key) + @entry, @count, @key = entry, count, key + super "translation data #{entry.inspect} can not be used with :count => #{count}. key '#{key}' is missing." + end + end + + class MissingInterpolationArgument < ArgumentError + attr_reader :key, :values, :string + def initialize(key, values, string) + @key, @values, @string = key, values, string + super "missing interpolation argument #{key.inspect} in #{string.inspect} (#{values.inspect} given)" + end + end + + class ReservedInterpolationKey < ArgumentError + attr_reader :key, :string + def initialize(key, string) + @key, @string = key, string + super "reserved key #{key.inspect} used in #{string.inspect}" + end + end + + class UnknownFileType < ArgumentError + attr_reader :type, :filename + def initialize(type, filename) + @type, @filename = type, filename + super "can not load translations from #{filename}, the file type #{type} is not known" + end + end + + class UnsupportedMethod < ArgumentError + attr_reader :method, :backend_klass, :msg + def initialize(method, backend_klass, msg) + @method = method + @backend_klass = backend_klass + @msg = msg + super "#{backend_klass} does not support the ##{method} method. #{msg}" + end + end + + class InvalidFilenames < ArgumentError + NUMBER_OF_ERRORS_SHOWN = 20 + def initialize(file_errors) + super <<~MSG + Found #{file_errors.count} error(s). + The first #{[file_errors.count, NUMBER_OF_ERRORS_SHOWN].min} error(s): + #{file_errors.map(&:message).first(NUMBER_OF_ERRORS_SHOWN).join("\n")} + + To use the LazyLoadable backend: + 1. Filenames must start with the locale. + 2. An underscore must separate the locale with any optional text that follows. + 3. The file must only contain translation data for the single locale. + + Example: + "/config/locales/fr.yml" which contains: + ```yml + fr: + dog: + chien + ``` + MSG + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/gettext.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/gettext.rb new file mode 100644 index 0000000..858daff --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/gettext.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +module I18n + module Gettext + PLURAL_SEPARATOR = "\001" + CONTEXT_SEPARATOR = "\004" + + autoload :Helpers, 'i18n/gettext/helpers' + + @@plural_keys = { :en => [:one, :other] } + + class << self + # returns an array of plural keys for the given locale or the whole hash + # of locale mappings to plural keys so that we can convert from gettext's + # integer-index based style + # TODO move this information to the pluralization module + def plural_keys(*args) + args.empty? ? @@plural_keys : @@plural_keys[args.first] || @@plural_keys[:en] + end + + def extract_scope(msgid, separator) + scope = msgid.to_s.split(separator) + msgid = scope.pop + [scope, msgid] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/gettext/helpers.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/gettext/helpers.rb new file mode 100644 index 0000000..d077619 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/gettext/helpers.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true + +require 'i18n/gettext' + +module I18n + module Gettext + # Implements classical Gettext style accessors. To use this include the + # module to the global namespace or wherever you want to use it. + # + # include I18n::Gettext::Helpers + module Helpers + # Makes dynamic translation messages readable for the gettext parser. + # _(fruit) cannot be understood by the gettext parser. To help the parser find all your translations, + # you can add fruit = N_("Apple") which does not translate, but tells the parser: "Apple" needs translation. + # * msgid: the message id. + # * Returns: msgid. + def N_(msgsid) + msgsid + end + + def gettext(msgid, options = EMPTY_HASH) + I18n.t(msgid, **{:default => msgid, :separator => '|'}.merge(options)) + end + alias _ gettext + + def sgettext(msgid, separator = '|') + scope, msgid = I18n::Gettext.extract_scope(msgid, separator) + I18n.t(msgid, :scope => scope, :default => msgid, :separator => separator) + end + alias s_ sgettext + + def pgettext(msgctxt, msgid) + separator = I18n::Gettext::CONTEXT_SEPARATOR + sgettext([msgctxt, msgid].join(separator), separator) + end + alias p_ pgettext + + def ngettext(msgid, msgid_plural, n = 1) + nsgettext(msgid, msgid_plural, n) + end + alias n_ ngettext + + # Method signatures: + # nsgettext('Fruits|apple', 'apples', 2) + # nsgettext(['Fruits|apple', 'apples'], 2) + def nsgettext(msgid, msgid_plural, n = 1, separator = '|') + if msgid.is_a?(Array) + msgid, msgid_plural, n, separator = msgid[0], msgid[1], msgid_plural, n + separator = '|' unless separator.is_a?(::String) + end + + scope, msgid = I18n::Gettext.extract_scope(msgid, separator) + default = { :one => msgid, :other => msgid_plural } + I18n.t(msgid, :default => default, :count => n, :scope => scope, :separator => separator) + end + alias ns_ nsgettext + + # Method signatures: + # npgettext('Fruits', 'apple', 'apples', 2) + # npgettext('Fruits', ['apple', 'apples'], 2) + def npgettext(msgctxt, msgid, msgid_plural, n = 1) + separator = I18n::Gettext::CONTEXT_SEPARATOR + + if msgid.is_a?(Array) + msgid_plural, msgid, n = msgid[1], [msgctxt, msgid[0]].join(separator), msgid_plural + else + msgid = [msgctxt, msgid].join(separator) + end + + nsgettext(msgid, msgid_plural, n, separator) + end + alias np_ npgettext + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/gettext/po_parser.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/gettext/po_parser.rb new file mode 100644 index 0000000..a07fdc5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/gettext/po_parser.rb @@ -0,0 +1,329 @@ +=begin + poparser.rb - Generate a .mo + + Copyright (C) 2003-2009 Masao Mutoh + + You may redistribute it and/or modify it under the same + license terms as Ruby. +=end + +#MODIFIED +# removed include GetText etc +# added stub translation method _(x) +require 'racc/parser' + +module GetText + + class PoParser < Racc::Parser + + def _(x) + x + end + +module_eval <<'..end src/poparser.ry modeval..id7a99570e05', 'src/poparser.ry', 108 + def unescape(orig) + ret = orig.gsub(/\\n/, "\n") + ret.gsub!(/\\t/, "\t") + ret.gsub!(/\\r/, "\r") + ret.gsub!(/\\"/, "\"") + ret + end + + def parse(str, data, ignore_fuzzy = true) + @comments = [] + @data = data + @fuzzy = false + @msgctxt = "" + $ignore_fuzzy = ignore_fuzzy + + str.strip! + @q = [] + until str.empty? do + case str + when /\A\s+/ + str = $' + when /\Amsgctxt/ + @q.push [:MSGCTXT, $&] + str = $' + when /\Amsgid_plural/ + @q.push [:MSGID_PLURAL, $&] + str = $' + when /\Amsgid/ + @q.push [:MSGID, $&] + str = $' + when /\Amsgstr/ + @q.push [:MSGSTR, $&] + str = $' + when /\A\[(\d+)\]/ + @q.push [:PLURAL_NUM, $1] + str = $' + when /\A\#~(.*)/ + $stderr.print _("Warning: obsolete msgid exists.\n") + $stderr.print " #{$&}\n" + @q.push [:COMMENT, $&] + str = $' + when /\A\#(.*)/ + @q.push [:COMMENT, $&] + str = $' + when /\A\"(.*)\"/ + @q.push [:STRING, $1] + str = $' + else + #c = str[0,1] + #@q.push [:STRING, c] + str = str[1..-1] + end + end + @q.push [false, '$end'] + if $DEBUG + @q.each do |a,b| + puts "[#{a}, #{b}]" + end + end + @yydebug = true if $DEBUG + do_parse + + if @comments.size > 0 + @data.set_comment(:last, @comments.join("\n")) + end + @data + end + + def next_token + @q.shift + end + + def on_message(msgid, msgstr) + if msgstr.size > 0 + @data[msgid] = msgstr + @data.set_comment(msgid, @comments.join("\n")) + end + @comments.clear + @msgctxt = "" + end + + def on_comment(comment) + @fuzzy = true if (/fuzzy/ =~ comment) + @comments << comment + end + + +..end src/poparser.ry modeval..id7a99570e05 + +##### racc 1.4.5 generates ### + +racc_reduce_table = [ + 0, 0, :racc_error, + 0, 10, :_reduce_none, + 2, 10, :_reduce_none, + 2, 10, :_reduce_none, + 2, 10, :_reduce_none, + 2, 12, :_reduce_5, + 1, 13, :_reduce_none, + 1, 13, :_reduce_none, + 4, 15, :_reduce_8, + 5, 16, :_reduce_9, + 2, 17, :_reduce_10, + 1, 17, :_reduce_none, + 3, 18, :_reduce_12, + 1, 11, :_reduce_13, + 2, 14, :_reduce_14, + 1, 14, :_reduce_15 ] + +racc_reduce_n = 16 + +racc_shift_n = 26 + +racc_action_table = [ + 3, 13, 5, 7, 9, 15, 16, 17, 20, 17, + 13, 17, 13, 13, 11, 17, 23, 20, 13, 17 ] + +racc_action_check = [ + 1, 16, 1, 1, 1, 12, 12, 12, 18, 18, + 7, 14, 15, 9, 3, 19, 20, 21, 23, 25 ] + +racc_action_pointer = [ + nil, 0, nil, 14, nil, nil, nil, 3, nil, 6, + nil, nil, 0, nil, 4, 5, -6, nil, 2, 8, + 8, 11, nil, 11, nil, 12 ] + +racc_action_default = [ + -1, -16, -2, -16, -3, -13, -4, -16, -6, -16, + -7, 26, -16, -15, -5, -16, -16, -14, -16, -8, + -16, -9, -11, -16, -10, -12 ] + +racc_goto_table = [ + 12, 22, 14, 4, 24, 6, 2, 8, 18, 19, + 10, 21, 1, nil, nil, nil, 25 ] + +racc_goto_check = [ + 5, 9, 5, 3, 9, 4, 2, 6, 5, 5, + 7, 8, 1, nil, nil, nil, 5 ] + +racc_goto_pointer = [ + nil, 12, 5, 2, 4, -7, 6, 9, -7, -17 ] + +racc_goto_default = [ + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil ] + +racc_token_table = { + false => 0, + Object.new => 1, + :COMMENT => 2, + :MSGID => 3, + :MSGCTXT => 4, + :MSGID_PLURAL => 5, + :MSGSTR => 6, + :STRING => 7, + :PLURAL_NUM => 8 } + +racc_use_result_var = true + +racc_nt_base = 9 + +Racc_arg = [ + racc_action_table, + racc_action_check, + racc_action_default, + racc_action_pointer, + racc_goto_table, + racc_goto_check, + racc_goto_default, + racc_goto_pointer, + racc_nt_base, + racc_reduce_table, + racc_token_table, + racc_shift_n, + racc_reduce_n, + racc_use_result_var ] + +Racc_token_to_s_table = [ +'$end', +'error', +'COMMENT', +'MSGID', +'MSGCTXT', +'MSGID_PLURAL', +'MSGSTR', +'STRING', +'PLURAL_NUM', +'$start', +'msgfmt', +'comment', +'msgctxt', +'message', +'string_list', +'single_message', +'plural_message', +'msgstr_plural', +'msgstr_plural_line'] + +Racc_debug_parser = true + +##### racc system variables end ##### + + # reduce 0 omitted + + # reduce 1 omitted + + # reduce 2 omitted + + # reduce 3 omitted + + # reduce 4 omitted + +module_eval <<'.,.,', 'src/poparser.ry', 25 + def _reduce_5( val, _values, result ) + @msgctxt = unescape(val[1]) + "\004" + result + end +.,., + + # reduce 6 omitted + + # reduce 7 omitted + +module_eval <<'.,.,', 'src/poparser.ry', 48 + def _reduce_8( val, _values, result ) + if @fuzzy and $ignore_fuzzy + if val[1] != "" + $stderr.print _("Warning: fuzzy message was ignored.\n") + $stderr.print " msgid '#{val[1]}'\n" + else + on_message('', unescape(val[3])) + end + @fuzzy = false + else + on_message(@msgctxt + unescape(val[1]), unescape(val[3])) + end + result = "" + result + end +.,., + +module_eval <<'.,.,', 'src/poparser.ry', 65 + def _reduce_9( val, _values, result ) + if @fuzzy and $ignore_fuzzy + if val[1] != "" + $stderr.print _("Warning: fuzzy message was ignored.\n") + $stderr.print "msgid = '#{val[1]}\n" + else + on_message('', unescape(val[3])) + end + @fuzzy = false + else + on_message(@msgctxt + unescape(val[1]) + "\000" + unescape(val[3]), unescape(val[4])) + end + result = "" + result + end +.,., + +module_eval <<'.,.,', 'src/poparser.ry', 76 + def _reduce_10( val, _values, result ) + if val[0].size > 0 + result = val[0] + "\000" + val[1] + else + result = "" + end + result + end +.,., + + # reduce 11 omitted + +module_eval <<'.,.,', 'src/poparser.ry', 84 + def _reduce_12( val, _values, result ) + result = val[2] + result + end +.,., + +module_eval <<'.,.,', 'src/poparser.ry', 91 + def _reduce_13( val, _values, result ) + on_comment(val[0]) + result + end +.,., + +module_eval <<'.,.,', 'src/poparser.ry', 99 + def _reduce_14( val, _values, result ) + result = val.delete_if{|item| item == ""}.join + result + end +.,., + +module_eval <<'.,.,', 'src/poparser.ry', 103 + def _reduce_15( val, _values, result ) + result = val[0] + result + end +.,., + + def _reduce_none( val, _values, result ) + result + end + + end # class PoParser + +end # module GetText diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/interpolate/ruby.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/interpolate/ruby.rb new file mode 100644 index 0000000..dab8f0e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/interpolate/ruby.rb @@ -0,0 +1,39 @@ +# heavily based on Masao Mutoh's gettext String interpolation extension +# http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb + +module I18n + DEFAULT_INTERPOLATION_PATTERNS = [ + /%%/, + /%\{([\w|]+)\}/, # matches placeholders like "%{foo} or %{foo|word}" + /%<(\w+)>([^\d]*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%.d" + ].freeze + INTERPOLATION_PATTERN = Regexp.union(DEFAULT_INTERPOLATION_PATTERNS) + deprecate_constant :INTERPOLATION_PATTERN + + class << self + # Return String or raises MissingInterpolationArgument exception. + # Missing argument's logic is handled by I18n.config.missing_interpolation_argument_handler. + def interpolate(string, values) + raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ I18n.reserved_keys_pattern + raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash) + interpolate_hash(string, values) + end + + def interpolate_hash(string, values) + string.gsub(Regexp.union(config.interpolation_patterns)) do |match| + if match == '%%' + '%' + else + key = ($1 || $2 || match.tr("%{}", "")).to_sym + value = if values.key?(key) + values[key] + else + config.missing_interpolation_argument_handler.call(key, values, string) + end + value = value.call(values) if value.respond_to?(:call) + $3 ? sprintf("%#{$3}", value) : value + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale.rb new file mode 100644 index 0000000..c4078e6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +module I18n + module Locale + autoload :Fallbacks, 'i18n/locale/fallbacks' + autoload :Tag, 'i18n/locale/tag' + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/fallbacks.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/fallbacks.rb new file mode 100644 index 0000000..e30acc4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/fallbacks.rb @@ -0,0 +1,97 @@ +# Locale Fallbacks +# +# Extends the I18n module to hold a fallbacks instance which is set to an +# instance of I18n::Locale::Fallbacks by default but can be swapped with a +# different implementation. +# +# Locale fallbacks will compute a number of fallback locales for a given locale. +# For example: +# +#

+# I18n.fallbacks[:"es-MX"] # => [:"es-MX", :es, :en] 
+# +# Locale fallbacks always fall back to +# +# * all parent locales of a given locale (e.g. :es for :"es-MX") first, +# * the current default locales and all of their parents second +# +# The default locales are set to [] by default but can be set to something else. +# +# One can additionally add any number of additional fallback locales manually. +# These will be added before the default locales to the fallback chain. For +# example: +# +# # using a custom locale as default fallback locale +# +# I18n.fallbacks = I18n::Locale::Fallbacks.new(:"en-GB", :"de-AT" => :de, :"de-CH" => :de) +# I18n.fallbacks[:"de-AT"] # => [:"de-AT", :de, :"en-GB", :en] +# I18n.fallbacks[:"de-CH"] # => [:"de-CH", :de, :"en-GB", :en] +# +# # mapping fallbacks to an existing instance +# +# # people speaking Catalan also speak Spanish as spoken in Spain +# fallbacks = I18n.fallbacks +# fallbacks.map(:ca => :"es-ES") +# fallbacks[:ca] # => [:ca, :"es-ES", :es, :"en-US", :en] +# +# # people speaking Arabian as spoken in Palestine also speak Hebrew as spoken in Israel +# fallbacks.map(:"ar-PS" => :"he-IL") +# fallbacks[:"ar-PS"] # => [:"ar-PS", :ar, :"he-IL", :he, :"en-US", :en] +# fallbacks[:"ar-EG"] # => [:"ar-EG", :ar, :"en-US", :en] +# +# # people speaking Sami as spoken in Finland also speak Swedish and Finnish as spoken in Finland +# fallbacks.map(:sms => [:"se-FI", :"fi-FI"]) +# fallbacks[:sms] # => [:sms, :"se-FI", :se, :"fi-FI", :fi, :"en-US", :en] + +module I18n + module Locale + class Fallbacks < Hash + def initialize(*mappings) + @map = {} + map(mappings.pop) if mappings.last.is_a?(Hash) + self.defaults = mappings.empty? ? [] : mappings + end + + def defaults=(defaults) + @defaults = defaults.flat_map { |default| compute(default, false) } + end + attr_reader :defaults + + def [](locale) + raise InvalidLocale.new(locale) if locale.nil? + raise Disabled.new('fallback#[]') if locale == false + locale = locale.to_sym + super || store(locale, compute(locale)) + end + + def map(*args, &block) + if args.count == 1 && !block_given? + mappings = args.first + mappings.each do |from, to| + from, to = from.to_sym, Array(to) + to.each do |_to| + @map[from] ||= [] + @map[from] << _to.to_sym + end + end + else + @map.map(*args, &block) + end + end + + protected + + def compute(tags, include_defaults = true, exclude = []) + result = Array(tags).flat_map do |tag| + tags = I18n::Locale::Tag.tag(tag).self_and_parents.map! { |t| t.to_sym } - exclude + tags.each { |_tag| tags += compute(@map[_tag], false, exclude + tags) if @map[_tag] } + tags + end + result.push(*defaults) if include_defaults + result.uniq! + result.compact! + result + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag.rb new file mode 100644 index 0000000..a640b44 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag.rb @@ -0,0 +1,28 @@ +# encoding: utf-8 + +module I18n + module Locale + module Tag + autoload :Parents, 'i18n/locale/tag/parents' + autoload :Rfc4646, 'i18n/locale/tag/rfc4646' + autoload :Simple, 'i18n/locale/tag/simple' + + class << self + # Returns the current locale tag implementation. Defaults to +I18n::Locale::Tag::Simple+. + def implementation + @@implementation ||= Simple + end + + # Sets the current locale tag implementation. Use this to set a different locale tag implementation. + def implementation=(implementation) + @@implementation = implementation + end + + # Factory method for locale tags. Delegates to the current locale tag implementation. + def tag(tag) + implementation.tag(tag) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag/parents.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag/parents.rb new file mode 100644 index 0000000..6283e66 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag/parents.rb @@ -0,0 +1,24 @@ +module I18n + module Locale + module Tag + module Parents + def parent + @parent ||= + begin + segs = to_a + segs.compact! + segs.length > 1 ? self.class.tag(*segs[0..(segs.length - 2)].join('-')) : nil + end + end + + def self_and_parents + @self_and_parents ||= [self].concat parents + end + + def parents + @parents ||= parent ? [parent].concat(parent.parents) : [] + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag/rfc4646.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag/rfc4646.rb new file mode 100644 index 0000000..4ce4c75 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag/rfc4646.rb @@ -0,0 +1,74 @@ +# RFC 4646/47 compliant Locale tag implementation that parses locale tags to +# subtags such as language, script, region, variant etc. +# +# For more information see by http://en.wikipedia.org/wiki/IETF_language_tag +# +# Rfc4646::Parser does not implement grandfathered tags. + +module I18n + module Locale + module Tag + RFC4646_SUBTAGS = [ :language, :script, :region, :variant, :extension, :privateuse, :grandfathered ] + RFC4646_FORMATS = { :language => :downcase, :script => :capitalize, :region => :upcase, :variant => :downcase } + + class Rfc4646 < Struct.new(*RFC4646_SUBTAGS) + class << self + # Parses the given tag and returns a Tag instance if it is valid. + # Returns false if the given tag is not valid according to RFC 4646. + def tag(tag) + matches = parser.match(tag) + new(*matches) if matches + end + + def parser + @@parser ||= Rfc4646::Parser + end + + def parser=(parser) + @@parser = parser + end + end + + include Parents + + RFC4646_FORMATS.each do |name, format| + define_method(name) { self[name].send(format) unless self[name].nil? } + end + + def to_sym + to_s.to_sym + end + + def to_s + @tag ||= to_a.compact.join("-") + end + + def to_a + members.collect { |attr| self.send(attr) } + end + + module Parser + PATTERN = %r{\A(?: + ([a-z]{2,3}(?:(?:-[a-z]{3}){0,3})?|[a-z]{4}|[a-z]{5,8}) # language + (?:-([a-z]{4}))? # script + (?:-([a-z]{2}|\d{3}))? # region + (?:-([0-9a-z]{5,8}|\d[0-9a-z]{3}))* # variant + (?:-([0-9a-wyz](?:-[0-9a-z]{2,8})+))* # extension + (?:-(x(?:-[0-9a-z]{1,8})+))?| # privateuse subtag + (x(?:-[0-9a-z]{1,8})+)| # privateuse tag + /* ([a-z]{1,3}(?:-[0-9a-z]{2,8}){1,2}) */ # grandfathered + )\z}xi + + class << self + def match(tag) + c = PATTERN.match(tag.to_s).captures + c[0..4] << (c[5].nil? ? c[6] : c[5]) << c[7] # TODO c[7] is grandfathered, throw a NotImplemented exception here? + rescue + false + end + end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag/simple.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag/simple.rb new file mode 100644 index 0000000..6d9ab56 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/locale/tag/simple.rb @@ -0,0 +1,39 @@ +# Simple Locale tag implementation that computes subtags by simply splitting +# the locale tag at '-' occurences. +module I18n + module Locale + module Tag + class Simple + class << self + def tag(tag) + new(tag) + end + end + + include Parents + + attr_reader :tag + + def initialize(*tag) + @tag = tag.join('-').to_sym + end + + def subtags + @subtags = tag.to_s.split('-').map!(&:to_s) + end + + def to_sym + tag + end + + def to_s + tag.to_s + end + + def to_a + subtags + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/middleware.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/middleware.rb new file mode 100644 index 0000000..59b377e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/middleware.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +module I18n + class Middleware + + def initialize(app) + @app = app + end + + def call(env) + @app.call(env) + ensure + Thread.current[:i18n_config] = I18n::Config.new + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests.rb new file mode 100644 index 0000000..30d0ed5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +module I18n + module Tests + autoload :Basics, 'i18n/tests/basics' + autoload :Defaults, 'i18n/tests/defaults' + autoload :Interpolation, 'i18n/tests/interpolation' + autoload :Link, 'i18n/tests/link' + autoload :Localization, 'i18n/tests/localization' + autoload :Lookup, 'i18n/tests/lookup' + autoload :Pluralization, 'i18n/tests/pluralization' + autoload :Procs, 'i18n/tests/procs' + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/basics.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/basics.rb new file mode 100644 index 0000000..be82430 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/basics.rb @@ -0,0 +1,58 @@ +module I18n + module Tests + module Basics + def teardown + I18n.available_locales = nil + end + + test "available_locales returns the available_locales produced by the backend, by default" do + I18n.backend.store_translations('de', :foo => 'bar') + I18n.backend.store_translations('en', :foo => 'foo') + + assert_equal I18n.available_locales, I18n.backend.available_locales + end + + test "available_locales can be set to something else independently from the actual locale data" do + I18n.backend.store_translations('de', :foo => 'bar') + I18n.backend.store_translations('en', :foo => 'foo') + + I18n.available_locales = :foo + assert_equal [:foo], I18n.available_locales + + I18n.available_locales = [:foo, 'bar'] + assert_equal [:foo, :bar], I18n.available_locales + + I18n.available_locales = nil + assert_equal I18n.available_locales, I18n.backend.available_locales + end + + test "available_locales memoizes when set explicitely" do + I18n.backend.expects(:available_locales).never + I18n.available_locales = [:foo] + I18n.backend.store_translations('de', :bar => 'baz') + I18n.reload! + assert_equal [:foo], I18n.available_locales + end + + test "available_locales delegates to the backend when not set explicitely" do + original_available_locales_value = I18n.backend.available_locales + I18n.backend.expects(:available_locales).returns(original_available_locales_value).twice + assert_equal I18n.backend.available_locales, I18n.available_locales + end + + test "exists? is implemented by the backend" do + I18n.backend.store_translations(:foo, :bar => 'baz') + assert I18n.exists?(:bar, :foo) + end + + test "storing a nil value as a translation removes it from the available locale data" do + I18n.backend.store_translations(:en, :to_be_deleted => 'bar') + assert_equal 'bar', I18n.t(:to_be_deleted, :default => 'baz') + + I18n.cache_store.clear if I18n.respond_to?(:cache_store) && I18n.cache_store + I18n.backend.store_translations(:en, :to_be_deleted => nil) + assert_equal 'baz', I18n.t(:to_be_deleted, :default => 'baz') + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/defaults.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/defaults.rb new file mode 100644 index 0000000..31fdb46 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/defaults.rb @@ -0,0 +1,52 @@ +# encoding: utf-8 + +module I18n + module Tests + module Defaults + def setup + super + I18n.backend.store_translations(:en, :foo => { :bar => 'bar', :baz => 'baz' }) + end + + test "defaults: given nil as a key it returns the given default" do + assert_equal 'default', I18n.t(nil, :default => 'default') + end + + test "defaults: given a symbol as a default it translates the symbol" do + assert_equal 'bar', I18n.t(nil, :default => :'foo.bar') + end + + test "defaults: given a symbol as a default and a scope it stays inside the scope when looking up the symbol" do + assert_equal 'bar', I18n.t(:missing, :default => :bar, :scope => :foo) + end + + test "defaults: given an array as a default it returns the first match" do + assert_equal 'bar', I18n.t(:does_not_exist, :default => [:does_not_exist_2, :'foo.bar']) + end + + test "defaults: given an array as a default with false it returns false" do + assert_equal false, I18n.t(:does_not_exist, :default => [false]) + end + + test "defaults: given false it returns false" do + assert_equal false, I18n.t(:does_not_exist, :default => false) + end + + test "defaults: given nil it returns nil" do + assert_nil I18n.t(:does_not_exist, :default => nil) + end + + test "defaults: given an array of missing keys it raises a MissingTranslationData exception" do + assert_raises I18n::MissingTranslationData do + I18n.t(:does_not_exist, :default => [:does_not_exist_2, :does_not_exist_3], :raise => true) + end + end + + test "defaults: using a custom scope separator" do + # data must have been stored using the custom separator when using the ActiveRecord backend + I18n.backend.store_translations(:en, { :foo => { :bar => 'bar' } }, { :separator => '|' }) + assert_equal 'bar', I18n.t(nil, :default => :'foo|bar', :separator => '|') + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/interpolation.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/interpolation.rb new file mode 100644 index 0000000..6bfe2e0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/interpolation.rb @@ -0,0 +1,163 @@ +# encoding: utf-8 + +module I18n + module Tests + module Interpolation + # If no interpolation parameter is not given, I18n should not alter the string. + # This behavior is due to three reasons: + # + # * Checking interpolation keys in all strings hits performance, badly; + # + # * This allows us to retrieve untouched values through I18n. For example + # I could have a middleware that returns I18n lookup results in JSON + # to be processed through Javascript. Leaving the keys untouched allows + # the interpolation to happen at the javascript level; + # + # * Security concerns: if I allow users to translate a web site, they can + # insert %{} in messages causing the I18n lookup to fail in every request. + # + test "interpolation: given no values it does not alter the string" do + assert_equal 'Hi %{name}!', interpolate(:default => 'Hi %{name}!') + end + + test "interpolation: given values it interpolates them into the string" do + assert_equal 'Hi David!', interpolate(:default => 'Hi %{name}!', :name => 'David') + end + + test "interpolation: works with a pipe" do + assert_equal 'Hi david!', interpolate(:default => 'Hi %{name|lowercase}!', :'name|lowercase' => 'david') + end + + test "interpolation: given a nil value it still interpolates it into the string" do + assert_equal 'Hi !', interpolate(:default => 'Hi %{name}!', :name => nil) + end + + test "interpolation: given a lambda as a value it calls it if the string contains the key" do + assert_equal 'Hi David!', interpolate(:default => 'Hi %{name}!', :name => lambda { |*args| 'David' }) + end + + test "interpolation: given a lambda as a value it does not call it if the string does not contain the key" do + assert_nothing_raised { interpolate(:default => 'Hi!', :name => lambda { |*args| raise 'fail' }) } + end + + test "interpolation: given values but missing a key it raises I18n::MissingInterpolationArgument" do + assert_raises(I18n::MissingInterpolationArgument) do + interpolate(:default => '%{foo}', :bar => 'bar') + end + end + + test "interpolation: it does not raise I18n::MissingInterpolationArgument for escaped variables" do + assert_nothing_raised do + assert_equal 'Barr %{foo}', interpolate(:default => '%{bar} %%{foo}', :bar => 'Barr') + end + end + + test "interpolation: it does not change the original, stored translation string" do + I18n.backend.store_translations(:en, :interpolate => 'Hi %{name}!') + assert_equal 'Hi David!', interpolate(:interpolate, :name => 'David') + assert_equal 'Hi Yehuda!', interpolate(:interpolate, :name => 'Yehuda') + end + + test "interpolation: given an array interpolates each element" do + I18n.backend.store_translations(:en, :array_interpolate => ['Hi', 'Mr. %{name}', 'or sir %{name}']) + assert_equal ['Hi', 'Mr. Bartuz', 'or sir Bartuz'], interpolate(:array_interpolate, :name => 'Bartuz') + end + + test "interpolation: given the translation is in utf-8 it still works" do + assert_equal 'Häi David!', interpolate(:default => 'Häi %{name}!', :name => 'David') + end + + test "interpolation: given the value is in utf-8 it still works" do + assert_equal 'Hi ゆきひろ!', interpolate(:default => 'Hi %{name}!', :name => 'ゆきひろ') + end + + test "interpolation: given the translation and the value are in utf-8 it still works" do + assert_equal 'こんにちは、ゆきひろさん!', interpolate(:default => 'こんにちは、%{name}さん!', :name => 'ゆきひろ') + end + + if Object.const_defined?(:Encoding) + test "interpolation: given a euc-jp translation and a utf-8 value it raises Encoding::CompatibilityError" do + assert_raises(Encoding::CompatibilityError) do + interpolate(:default => euc_jp('こんにちは、%{name}さん!'), :name => 'ゆきひろ') + end + end + + test "interpolation: given a utf-8 translation and a euc-jp value it raises Encoding::CompatibilityError" do + assert_raises(Encoding::CompatibilityError) do + interpolate(:default => 'こんにちは、%{name}さん!', :name => euc_jp('ゆきひろ')) + end + end + + test "interpolation: ASCII strings in the backend should be encoded to UTF8 if interpolation options are in UTF8" do + I18n.backend.store_translations 'en', 'encoding' => ('%{who} let me go'.force_encoding("ASCII")) + result = I18n.t 'encoding', :who => "måmmå miå" + assert_equal Encoding::UTF_8, result.encoding + end + + test "interpolation: UTF8 strings in the backend are still returned as UTF8 with ASCII interpolation" do + I18n.backend.store_translations 'en', 'encoding' => 'måmmå miå %{what}' + result = I18n.t 'encoding', :what => 'let me go'.force_encoding("ASCII") + assert_equal Encoding::UTF_8, result.encoding + end + + test "interpolation: UTF8 strings in the backend are still returned as UTF8 even with numbers interpolation" do + I18n.backend.store_translations 'en', 'encoding' => '%{count} times: måmmå miå' + result = I18n.t 'encoding', :count => 3 + assert_equal Encoding::UTF_8, result.encoding + end + end + + test "interpolation: given a translations containing a reserved key it raises I18n::ReservedInterpolationKey" do + assert_raises(I18n::ReservedInterpolationKey) { interpolate(:foo => :bar, :default => '%{exception_handler}') } + assert_raises(I18n::ReservedInterpolationKey) { interpolate(:foo => :bar, :default => '%{default}') } + assert_raises(I18n::ReservedInterpolationKey) { interpolate(:foo => :bar, :default => '%{separator}') } + assert_raises(I18n::ReservedInterpolationKey) { interpolate(:foo => :bar, :default => '%{scope}') } + end + + test "interpolation: deep interpolation for default string" do + assert_equal 'Hi %{name}!', interpolate(:default => 'Hi %{name}!', :deep_interpolation => true) + end + + test "interpolation: deep interpolation for interpolated string" do + assert_equal 'Hi Ann!', interpolate(:default => 'Hi %{name}!', :name => 'Ann', :deep_interpolation => true) + end + + test "interpolation: deep interpolation for Hash" do + people = { :people => { :ann => 'Ann is %{ann}', :john => 'John is %{john}' } } + interpolated_people = { :people => { :ann => 'Ann is good', :john => 'John is big' } } + assert_equal interpolated_people, interpolate(:default => people, :ann => 'good', :john => 'big', :deep_interpolation => true) + end + + test "interpolation: deep interpolation for Array" do + people = { :people => ['Ann is %{ann}', 'John is %{john}'] } + interpolated_people = { :people => ['Ann is good', 'John is big'] } + assert_equal interpolated_people, interpolate(:default => people, :ann => 'good', :john => 'big', :deep_interpolation => true) + end + + protected + + def capture(stream) + begin + stream = stream.to_s + eval "$#{stream} = StringIO.new" + yield + result = eval("$#{stream}").string + ensure + eval("$#{stream} = #{stream.upcase}") + end + + result + end + + def euc_jp(string) + string.encode!(Encoding::EUC_JP) + end + + def interpolate(*args) + options = args.last.is_a?(Hash) ? args.pop : {} + key = args.pop + I18n.backend.translate('en', key, options) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/link.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/link.rb new file mode 100644 index 0000000..d2f20e8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/link.rb @@ -0,0 +1,66 @@ +# encoding: utf-8 + +module I18n + module Tests + module Link + test "linked lookup: if a key resolves to a symbol it looks up the symbol" do + I18n.backend.store_translations 'en', { + :link => :linked, + :linked => 'linked' + } + assert_equal 'linked', I18n.backend.translate('en', :link) + end + + test "linked lookup: if a key resolves to a dot-separated symbol it looks up the symbol" do + I18n.backend.store_translations 'en', { + :link => :"foo.linked", + :foo => { :linked => 'linked' } + } + assert_equal('linked', I18n.backend.translate('en', :link)) + end + + test "linked lookup: if a dot-separated key resolves to a symbol it looks up the symbol" do + I18n.backend.store_translations 'en', { + :foo => { :link => :linked }, + :linked => 'linked' + } + assert_equal('linked', I18n.backend.translate('en', :'foo.link')) + end + + test "linked lookup: if a dot-separated key resolves to a dot-separated symbol it looks up the symbol" do + I18n.backend.store_translations 'en', { + :foo => { :link => :"bar.linked" }, + :bar => { :linked => 'linked' } + } + assert_equal('linked', I18n.backend.translate('en', :'foo.link')) + end + + test "linked lookup: links always refer to the absolute key" do + I18n.backend.store_translations 'en', { + :foo => { :link => :linked, :linked => 'linked in foo' }, + :linked => 'linked absolutely' + } + assert_equal 'linked absolutely', I18n.backend.translate('en', :link, :scope => :foo) + end + + test "linked lookup: a link can resolve to a namespace in the middle of a dot-separated key" do + I18n.backend.store_translations 'en', { + :activemodel => { :errors => { :messages => { :blank => "can't be blank" } } }, + :activerecord => { :errors => { :messages => :"activemodel.errors.messages" } } + } + assert_equal "can't be blank", I18n.t(:"activerecord.errors.messages.blank") + assert_equal "can't be blank", I18n.t(:"activerecord.errors.messages.blank") + end + + test "linked lookup: a link can resolve with option :count" do + I18n.backend.store_translations 'en', { + :counter => :counted, + :counted => { :foo => { :one => "one", :other => "other" }, :bar => "bar" } + } + assert_equal "one", I18n.t(:'counter.foo', count: 1) + assert_equal "other", I18n.t(:'counter.foo', count: 2) + assert_equal "bar", I18n.t(:'counter.bar', count: 3) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization.rb new file mode 100644 index 0000000..53b1502 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization.rb @@ -0,0 +1,19 @@ +module I18n + module Tests + module Localization + autoload :Date, 'i18n/tests/localization/date' + autoload :DateTime, 'i18n/tests/localization/date_time' + autoload :Time, 'i18n/tests/localization/time' + autoload :Procs, 'i18n/tests/localization/procs' + + def self.included(base) + base.class_eval do + include I18n::Tests::Localization::Date + include I18n::Tests::Localization::DateTime + include I18n::Tests::Localization::Procs + include I18n::Tests::Localization::Time + end + end + end + end +end \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/date.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/date.rb new file mode 100644 index 0000000..2a44371 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/date.rb @@ -0,0 +1,117 @@ +# encoding: utf-8 + +module I18n + module Tests + module Localization + module Date + def setup + super + setup_date_translations + @date = ::Date.new(2008, 3, 1) + end + + test "localize Date: given the short format it uses it" do + assert_equal '01. Mär', I18n.l(@date, :format => :short, :locale => :de) + end + + test "localize Date: given the long format it uses it" do + assert_equal '01. März 2008', I18n.l(@date, :format => :long, :locale => :de) + end + + test "localize Date: given the default format it uses it" do + assert_equal '01.03.2008', I18n.l(@date, :format => :default, :locale => :de) + end + + test "localize Date: given a day name format it returns the correct day name" do + assert_equal 'Samstag', I18n.l(@date, :format => '%A', :locale => :de) + end + + test "localize Date: given a uppercased day name format it returns the correct day name in upcase" do + assert_equal 'samstag'.upcase, I18n.l(@date, :format => '%^A', :locale => :de) + end + + test "localize Date: given an abbreviated day name format it returns the correct abbreviated day name" do + assert_equal 'Sa', I18n.l(@date, :format => '%a', :locale => :de) + end + + test "localize Date: given an abbreviated and uppercased day name format it returns the correct abbreviated day name in upcase" do + assert_equal 'sa'.upcase, I18n.l(@date, :format => '%^a', :locale => :de) + end + + test "localize Date: given a month name format it returns the correct month name" do + assert_equal 'März', I18n.l(@date, :format => '%B', :locale => :de) + end + + test "localize Date: given a uppercased month name format it returns the correct month name in upcase" do + assert_equal 'märz'.upcase, I18n.l(@date, :format => '%^B', :locale => :de) + end + + test "localize Date: given an abbreviated month name format it returns the correct abbreviated month name" do + assert_equal 'Mär', I18n.l(@date, :format => '%b', :locale => :de) + end + + test "localize Date: given an abbreviated and uppercased month name format it returns the correct abbreviated month name in upcase" do + assert_equal 'mär'.upcase, I18n.l(@date, :format => '%^b', :locale => :de) + end + + test "localize Date: given a date format with the month name upcased it returns the correct value" do + assert_equal '1. FEBRUAR 2008', I18n.l(::Date.new(2008, 2, 1), :format => "%-d. %^B %Y", :locale => :de) + end + + test "localize Date: given missing translations it returns the correct error message" do + assert_equal 'translation missing: fr.date.abbr_month_names', I18n.l(@date, :format => '%b', :locale => :fr) + end + + test "localize Date: given an unknown format it does not fail" do + assert_nothing_raised { I18n.l(@date, :format => '%x') } + end + + test "localize Date: does not modify the options hash" do + options = { :format => '%b', :locale => :de } + assert_equal 'Mär', I18n.l(@date, **options) + assert_equal({ :format => '%b', :locale => :de }, options) + assert_nothing_raised { I18n.l(@date, **options.freeze) } + end + + test "localize Date: given nil with default value it returns default" do + assert_equal 'default', I18n.l(nil, :default => 'default') + end + + test "localize Date: given nil it raises I18n::ArgumentError" do + assert_raises(I18n::ArgumentError) { I18n.l(nil) } + end + + test "localize Date: given a plain Object it raises I18n::ArgumentError" do + assert_raises(I18n::ArgumentError) { I18n.l(Object.new) } + end + + test "localize Date: given a format is missing it raises I18n::MissingTranslationData" do + assert_raises(I18n::MissingTranslationData) { I18n.l(@date, :format => :missing) } + end + + test "localize Date: it does not alter the format string" do + assert_equal '01. Februar 2009', I18n.l(::Date.parse('2009-02-01'), :format => :long, :locale => :de) + assert_equal '01. Oktober 2009', I18n.l(::Date.parse('2009-10-01'), :format => :long, :locale => :de) + end + + protected + + def setup_date_translations + I18n.backend.store_translations :de, { + :date => { + :formats => { + :default => "%d.%m.%Y", + :short => "%d. %b", + :long => "%d. %B %Y", + }, + :day_names => %w(Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag), + :abbr_day_names => %w(So Mo Di Mi Do Fr Sa), + :month_names => %w(Januar Februar März April Mai Juni Juli August September Oktober November Dezember).unshift(nil), + :abbr_month_names => %w(Jan Feb Mär Apr Mai Jun Jul Aug Sep Okt Nov Dez).unshift(nil) + } + } + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/date_time.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/date_time.rb new file mode 100644 index 0000000..b09b888 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/date_time.rb @@ -0,0 +1,103 @@ +# encoding: utf-8 + +module I18n + module Tests + module Localization + module DateTime + def setup + super + setup_datetime_translations + @datetime = ::DateTime.new(2008, 3, 1, 6) + @other_datetime = ::DateTime.new(2008, 3, 1, 18) + end + + test "localize DateTime: given the short format it uses it" do + assert_equal '01. Mär 06:00', I18n.l(@datetime, :format => :short, :locale => :de) + end + + test "localize DateTime: given the long format it uses it" do + assert_equal '01. März 2008 06:00', I18n.l(@datetime, :format => :long, :locale => :de) + end + + test "localize DateTime: given the default format it uses it" do + assert_equal 'Sa, 01. Mär 2008 06:00:00 +0000', I18n.l(@datetime, :format => :default, :locale => :de) + end + + test "localize DateTime: given a day name format it returns the correct day name" do + assert_equal 'Samstag', I18n.l(@datetime, :format => '%A', :locale => :de) + end + + test "localize DateTime: given a uppercased day name format it returns the correct day name in upcase" do + assert_equal 'samstag'.upcase, I18n.l(@datetime, :format => '%^A', :locale => :de) + end + + test "localize DateTime: given an abbreviated day name format it returns the correct abbreviated day name" do + assert_equal 'Sa', I18n.l(@datetime, :format => '%a', :locale => :de) + end + + test "localize DateTime: given an abbreviated and uppercased day name format it returns the correct abbreviated day name in upcase" do + assert_equal 'sa'.upcase, I18n.l(@datetime, :format => '%^a', :locale => :de) + end + + test "localize DateTime: given a month name format it returns the correct month name" do + assert_equal 'März', I18n.l(@datetime, :format => '%B', :locale => :de) + end + + test "localize DateTime: given a uppercased month name format it returns the correct month name in upcase" do + assert_equal 'märz'.upcase, I18n.l(@datetime, :format => '%^B', :locale => :de) + end + + test "localize DateTime: given an abbreviated month name format it returns the correct abbreviated month name" do + assert_equal 'Mär', I18n.l(@datetime, :format => '%b', :locale => :de) + end + + test "localize DateTime: given an abbreviated and uppercased month name format it returns the correct abbreviated month name in upcase" do + assert_equal 'mär'.upcase, I18n.l(@datetime, :format => '%^b', :locale => :de) + end + + test "localize DateTime: given a date format with the month name upcased it returns the correct value" do + assert_equal '1. FEBRUAR 2008', I18n.l(::DateTime.new(2008, 2, 1, 6), :format => "%-d. %^B %Y", :locale => :de) + end + + test "localize DateTime: given missing translations it returns the correct error message" do + assert_equal 'translation missing: fr.date.abbr_month_names', I18n.l(@datetime, :format => '%b', :locale => :fr) + end + + test "localize DateTime: given a meridian indicator format it returns the correct meridian indicator" do + assert_equal 'AM', I18n.l(@datetime, :format => '%p', :locale => :de) + assert_equal 'PM', I18n.l(@other_datetime, :format => '%p', :locale => :de) + end + + test "localize DateTime: given a meridian indicator format it returns the correct meridian indicator in downcase" do + assert_equal 'am', I18n.l(@datetime, :format => '%P', :locale => :de) + assert_equal 'pm', I18n.l(@other_datetime, :format => '%P', :locale => :de) + end + + test "localize DateTime: given an unknown format it does not fail" do + assert_nothing_raised { I18n.l(@datetime, :format => '%x') } + end + + test "localize DateTime: given a format is missing it raises I18n::MissingTranslationData" do + assert_raises(I18n::MissingTranslationData) { I18n.l(@datetime, :format => :missing) } + end + + protected + + def setup_datetime_translations + # time translations might have been set up in Tests::Api::Localization::Time + I18n.backend.store_translations :de, { + :time => { + :formats => { + :default => "%a, %d. %b %Y %H:%M:%S %z", + :short => "%d. %b %H:%M", + :long => "%d. %B %Y %H:%M" + }, + :am => 'am', + :pm => 'pm' + } + } + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/procs.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/procs.rb new file mode 100644 index 0000000..7db45d1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/procs.rb @@ -0,0 +1,118 @@ +# encoding: utf-8 + +module I18n + module Tests + module Localization + module Procs + test "localize: using day names from lambdas" do + setup_time_proc_translations + time = ::Time.utc(2008, 3, 1, 6, 0) + assert_match(/Суббота/, I18n.l(time, :format => "%A, %d %B", :locale => :ru)) + assert_match(/суббота/, I18n.l(time, :format => "%d %B (%A)", :locale => :ru)) + end + + test "localize: using month names from lambdas" do + setup_time_proc_translations + time = ::Time.utc(2008, 3, 1, 6, 0) + assert_match(/марта/, I18n.l(time, :format => "%d %B %Y", :locale => :ru)) + assert_match(/Март /, I18n.l(time, :format => "%B %Y", :locale => :ru)) + end + + test "localize: using abbreviated day names from lambdas" do + setup_time_proc_translations + time = ::Time.utc(2008, 3, 1, 6, 0) + assert_match(/марта/, I18n.l(time, :format => "%d %b %Y", :locale => :ru)) + assert_match(/март /, I18n.l(time, :format => "%b %Y", :locale => :ru)) + end + + test "localize Date: given a format that resolves to a Proc it calls the Proc with the object" do + setup_time_proc_translations + date = ::Date.new(2008, 3, 1) + assert_equal '[Sat, 01 Mar 2008, {}]', I18n.l(date, :format => :proc, :locale => :ru) + end + + test "localize Date: given a format that resolves to a Proc it calls the Proc with the object and extra options" do + setup_time_proc_translations + date = ::Date.new(2008, 3, 1) + assert_equal '[Sat, 01 Mar 2008, {:foo=>"foo"}]', I18n.l(date, :format => :proc, :foo => 'foo', :locale => :ru) + end + + test "localize DateTime: given a format that resolves to a Proc it calls the Proc with the object" do + setup_time_proc_translations + datetime = ::DateTime.new(2008, 3, 1, 6) + assert_equal '[Sat, 01 Mar 2008 06:00:00 +00:00, {}]', I18n.l(datetime, :format => :proc, :locale => :ru) + end + + test "localize DateTime: given a format that resolves to a Proc it calls the Proc with the object and extra options" do + setup_time_proc_translations + datetime = ::DateTime.new(2008, 3, 1, 6) + assert_equal '[Sat, 01 Mar 2008 06:00:00 +00:00, {:foo=>"foo"}]', I18n.l(datetime, :format => :proc, :foo => 'foo', :locale => :ru) + end + + test "localize Time: given a format that resolves to a Proc it calls the Proc with the object" do + setup_time_proc_translations + time = ::Time.utc(2008, 3, 1, 6, 0) + assert_equal I18n::Tests::Localization::Procs.inspect_args([time], {}), I18n.l(time, :format => :proc, :locale => :ru) + end + + test "localize Time: given a format that resolves to a Proc it calls the Proc with the object and extra options" do + setup_time_proc_translations + time = ::Time.utc(2008, 3, 1, 6, 0) + options = { :foo => 'foo' } + assert_equal I18n::Tests::Localization::Procs.inspect_args([time], options), I18n.l(time, **options.merge(:format => :proc, :locale => :ru)) + end + + protected + + def self.inspect_args(args, kwargs) + args << kwargs + args = args.map do |arg| + case arg + when ::Time, ::DateTime + arg.strftime('%a, %d %b %Y %H:%M:%S %Z').sub('+0000', '+00:00') + when ::Date + arg.strftime('%a, %d %b %Y') + when Hash + arg.delete(:fallback_in_progress) + arg.delete(:fallback_original_locale) + arg.inspect + else + arg.inspect + end + end + "[#{args.join(', ')}]" + end + + def setup_time_proc_translations + I18n.backend.store_translations :ru, { + :time => { + :formats => { + :proc => lambda { |*args, **kwargs| I18n::Tests::Localization::Procs.inspect_args(args, kwargs) } + } + }, + :date => { + :formats => { + :proc => lambda { |*args, **kwargs| I18n::Tests::Localization::Procs.inspect_args(args, kwargs) } + }, + :'day_names' => lambda { |key, options| + (options[:format] =~ /^%A/) ? + %w(Воскресенье Понедельник Вторник Среда Четверг Пятница Суббота) : + %w(воскресенье понедельник вторник среда четверг пятница суббота) + }, + :'month_names' => lambda { |key, options| + (options[:format] =~ /(%d|%e)(\s*)?(%B)/) ? + %w(января февраля марта апреля мая июня июля августа сентября октября ноября декабря).unshift(nil) : + %w(Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь).unshift(nil) + }, + :'abbr_month_names' => lambda { |key, options| + (options[:format] =~ /(%d|%e)(\s*)(%b)/) ? + %w(янв. февр. марта апр. мая июня июля авг. сент. окт. нояб. дек.).unshift(nil) : + %w(янв. февр. март апр. май июнь июль авг. сент. окт. нояб. дек.).unshift(nil) + }, + } + } + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/time.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/time.rb new file mode 100644 index 0000000..7afe176 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/localization/time.rb @@ -0,0 +1,103 @@ +# encoding: utf-8 + +module I18n + module Tests + module Localization + module Time + def setup + super + setup_time_translations + @time = ::Time.utc(2008, 3, 1, 6, 0) + @other_time = ::Time.utc(2008, 3, 1, 18, 0) + end + + test "localize Time: given the short format it uses it" do + assert_equal '01. Mär 06:00', I18n.l(@time, :format => :short, :locale => :de) + end + + test "localize Time: given the long format it uses it" do + assert_equal '01. März 2008 06:00', I18n.l(@time, :format => :long, :locale => :de) + end + + # TODO Seems to break on Windows because ENV['TZ'] is ignored. What's a better way to do this? + # def test_localize_given_the_default_format_it_uses_it + # assert_equal 'Sa, 01. Mar 2008 06:00:00 +0000', I18n.l(@time, :format => :default, :locale => :de) + # end + + test "localize Time: given a day name format it returns the correct day name" do + assert_equal 'Samstag', I18n.l(@time, :format => '%A', :locale => :de) + end + + test "localize Time: given a uppercased day name format it returns the correct day name in upcase" do + assert_equal 'samstag'.upcase, I18n.l(@time, :format => '%^A', :locale => :de) + end + + test "localize Time: given an abbreviated day name format it returns the correct abbreviated day name" do + assert_equal 'Sa', I18n.l(@time, :format => '%a', :locale => :de) + end + + test "localize Time: given an abbreviated and uppercased day name format it returns the correct abbreviated day name in upcase" do + assert_equal 'sa'.upcase, I18n.l(@time, :format => '%^a', :locale => :de) + end + + test "localize Time: given a month name format it returns the correct month name" do + assert_equal 'März', I18n.l(@time, :format => '%B', :locale => :de) + end + + test "localize Time: given a uppercased month name format it returns the correct month name in upcase" do + assert_equal 'märz'.upcase, I18n.l(@time, :format => '%^B', :locale => :de) + end + + test "localize Time: given an abbreviated month name format it returns the correct abbreviated month name" do + assert_equal 'Mär', I18n.l(@time, :format => '%b', :locale => :de) + end + + test "localize Time: given an abbreviated and uppercased month name format it returns the correct abbreviated month name in upcase" do + assert_equal 'mär'.upcase, I18n.l(@time, :format => '%^b', :locale => :de) + end + + test "localize Time: given a date format with the month name upcased it returns the correct value" do + assert_equal '1. FEBRUAR 2008', I18n.l(::Time.utc(2008, 2, 1, 6, 0), :format => "%-d. %^B %Y", :locale => :de) + end + + test "localize Time: given missing translations it returns the correct error message" do + assert_equal 'translation missing: fr.date.abbr_month_names', I18n.l(@time, :format => '%b', :locale => :fr) + end + + test "localize Time: given a meridian indicator format it returns the correct meridian indicator" do + assert_equal 'AM', I18n.l(@time, :format => '%p', :locale => :de) + assert_equal 'PM', I18n.l(@other_time, :format => '%p', :locale => :de) + end + + test "localize Time: given a meridian indicator format it returns the correct meridian indicator in upcase" do + assert_equal 'am', I18n.l(@time, :format => '%P', :locale => :de) + assert_equal 'pm', I18n.l(@other_time, :format => '%P', :locale => :de) + end + + test "localize Time: given an unknown format it does not fail" do + assert_nothing_raised { I18n.l(@time, :format => '%x') } + end + + test "localize Time: given a format is missing it raises I18n::MissingTranslationData" do + assert_raises(I18n::MissingTranslationData) { I18n.l(@time, :format => :missing) } + end + + protected + + def setup_time_translations + I18n.backend.store_translations :de, { + :time => { + :formats => { + :default => "%a, %d. %b %Y %H:%M:%S %z", + :short => "%d. %b %H:%M", + :long => "%d. %B %Y %H:%M", + }, + :am => 'am', + :pm => 'pm' + } + } + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/lookup.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/lookup.rb new file mode 100644 index 0000000..3bd46b8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/lookup.rb @@ -0,0 +1,81 @@ +# encoding: utf-8 + +module I18n + module Tests + module Lookup + def setup + super + I18n.backend.store_translations(:en, :foo => { :bar => 'bar', :baz => 'baz' }, :falsy => false, :truthy => true, + :string => "a", :array => %w(a b c), :hash => { "a" => "b" }) + end + + test "lookup: it returns a string" do + assert_equal("a", I18n.t(:string)) + end + + test "lookup: it returns hash" do + assert_equal({ :a => "b" }, I18n.t(:hash)) + end + + test "lookup: it returns an array" do + assert_equal(%w(a b c), I18n.t(:array)) + end + + test "lookup: it returns a native true" do + assert I18n.t(:truthy) === true + end + + test "lookup: it returns a native false" do + assert I18n.t(:falsy) === false + end + + test "lookup: given a missing key, no default and no raise option it returns an error message" do + assert_equal "translation missing: en.missing", I18n.t(:missing) + end + + test "lookup: given a missing key, no default and the raise option it raises MissingTranslationData" do + assert_raises(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) } + end + + test "lookup: does not raise an exception if no translation data is present for the given locale" do + assert_nothing_raised { I18n.t(:foo, :locale => :xx) } + end + + test "lookup: does not modify the options hash" do + options = {} + assert_equal "a", I18n.t(:string, **options) + assert_equal({}, options) + assert_nothing_raised { I18n.t(:string, **options.freeze) } + end + + test "lookup: given an array of keys it translates all of them" do + assert_equal %w(bar baz), I18n.t([:bar, :baz], :scope => [:foo]) + end + + test "lookup: using a custom scope separator" do + # data must have been stored using the custom separator when using the ActiveRecord backend + I18n.backend.store_translations(:en, { :foo => { :bar => 'bar' } }, { :separator => '|' }) + assert_equal 'bar', I18n.t('foo|bar', :separator => '|') + end + + # In fact it probably *should* fail but Rails currently relies on using the default locale instead. + # So we'll stick to this for now until we get it fixed in Rails. + test "lookup: given nil as a locale it does not raise but use the default locale" do + # assert_raises(I18n::InvalidLocale) { I18n.t(:bar, :locale => nil) } + assert_nothing_raised { I18n.t(:bar, :locale => nil) } + end + + test "lookup: a resulting String is not frozen" do + assert !I18n.t(:string).frozen? + end + + test "lookup: a resulting Array is not frozen" do + assert !I18n.t(:array).frozen? + end + + test "lookup: a resulting Hash is not frozen" do + assert !I18n.t(:hash).frozen? + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/pluralization.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/pluralization.rb new file mode 100644 index 0000000..19e73f3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/pluralization.rb @@ -0,0 +1,35 @@ +# encoding: utf-8 + +module I18n + module Tests + module Pluralization + test "pluralization: given 0 it returns the :zero translation if it is defined" do + assert_equal 'zero', I18n.t(:default => { :zero => 'zero' }, :count => 0) + end + + test "pluralization: given 0 it returns the :other translation if :zero is not defined" do + assert_equal 'bars', I18n.t(:default => { :other => 'bars' }, :count => 0) + end + + test "pluralization: given 1 it returns the singular translation" do + assert_equal 'bar', I18n.t(:default => { :one => 'bar' }, :count => 1) + end + + test "pluralization: given 2 it returns the :other translation" do + assert_equal 'bars', I18n.t(:default => { :other => 'bars' }, :count => 2) + end + + test "pluralization: given 3 it returns the :other translation" do + assert_equal 'bars', I18n.t(:default => { :other => 'bars' }, :count => 3) + end + + test "pluralization: given nil it returns the whole entry" do + assert_equal({ :one => 'bar' }, I18n.t(:default => { :one => 'bar' }, :count => nil)) + end + + test "pluralization: given incomplete pluralization data it raises I18n::InvalidPluralizationData" do + assert_raises(I18n::InvalidPluralizationData) { I18n.t(:default => { :one => 'bar' }, :count => 2) } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/procs.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/procs.rb new file mode 100644 index 0000000..6abd861 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/tests/procs.rb @@ -0,0 +1,66 @@ +# encoding: utf-8 + +module I18n + module Tests + module Procs + test "lookup: given a translation is a proc it calls the proc with the key and interpolation values" do + I18n.backend.store_translations(:en, :a_lambda => lambda { |*args| I18n::Tests::Procs.filter_args(*args) }) + assert_equal '[:a_lambda, {:foo=>"foo"}]', I18n.t(:a_lambda, :foo => 'foo') + end + + test "lookup: given a translation is a proc it passes the interpolation values as keyword arguments" do + I18n.backend.store_translations(:en, :a_lambda => lambda { |key, foo:, **| I18n::Tests::Procs.filter_args(key, foo: foo) }) + assert_equal '[:a_lambda, {:foo=>"foo"}]', I18n.t(:a_lambda, :foo => 'foo') + end + + test "defaults: given a default is a Proc it calls it with the key and interpolation values" do + proc = lambda { |*args| I18n::Tests::Procs.filter_args(*args) } + assert_equal '[nil, {:foo=>"foo"}]', I18n.t(nil, :default => proc, :foo => 'foo') + end + + test "defaults: given a default is a key that resolves to a Proc it calls it with the key and interpolation values" do + the_lambda = lambda { |*args| I18n::Tests::Procs.filter_args(*args) } + I18n.backend.store_translations(:en, :a_lambda => the_lambda) + assert_equal '[:a_lambda, {:foo=>"foo"}]', I18n.t(nil, :default => :a_lambda, :foo => 'foo') + assert_equal '[:a_lambda, {:foo=>"foo"}]', I18n.t(nil, :default => [nil, :a_lambda], :foo => 'foo') + end + + test "interpolation: given an interpolation value is a lambda it calls it with key and values before interpolating it" do + proc = lambda { |*args| I18n::Tests::Procs.filter_args(*args) } + assert_match %r(\[\{:foo=>#\}\]), I18n.t(nil, :default => '%{foo}', :foo => proc) + end + + test "interpolation: given a key resolves to a Proc that returns a string then interpolation still works" do + proc = lambda { |*args| "%{foo}: " + I18n::Tests::Procs.filter_args(*args) } + assert_equal 'foo: [nil, {:foo=>"foo"}]', I18n.t(nil, :default => proc, :foo => 'foo') + end + + test "pluralization: given a key resolves to a Proc that returns valid data then pluralization still works" do + proc = lambda { |*args| { :zero => 'zero', :one => 'one', :other => 'other' } } + assert_equal 'zero', I18n.t(:default => proc, :count => 0) + assert_equal 'one', I18n.t(:default => proc, :count => 1) + assert_equal 'other', I18n.t(:default => proc, :count => 2) + end + + test "lookup: given the option :resolve => false was passed it does not resolve proc translations" do + I18n.backend.store_translations(:en, :a_lambda => lambda { |*args| I18n::Tests::Procs.filter_args(*args) }) + assert_equal Proc, I18n.t(:a_lambda, :resolve => false).class + end + + test "lookup: given the option :resolve => false was passed it does not resolve proc default" do + assert_equal Proc, I18n.t(nil, :default => lambda { |*args| I18n::Tests::Procs.filter_args(*args) }, :resolve => false).class + end + + + def self.filter_args(*args) + args.map do |arg| + if arg.is_a?(Hash) + arg.delete(:fallback_in_progress) + arg.delete(:fallback_original_locale) + end + arg + end.inspect + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/utils.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/utils.rb new file mode 100644 index 0000000..8841561 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/utils.rb @@ -0,0 +1,55 @@ +# frozen_string_literal: true + +module I18n + module Utils + class << self + if Hash.method_defined?(:except) + def except(hash, *keys) + hash.except(*keys) + end + else + def except(hash, *keys) + hash = hash.dup + keys.each { |k| hash.delete(k) } + hash + end + end + + def deep_merge(hash, other_hash, &block) + deep_merge!(hash.dup, other_hash, &block) + end + + def deep_merge!(hash, other_hash, &block) + hash.merge!(other_hash) do |key, this_val, other_val| + if this_val.is_a?(Hash) && other_val.is_a?(Hash) + deep_merge(this_val, other_val, &block) + elsif block_given? + yield key, this_val, other_val + else + other_val + end + end + end + + def deep_symbolize_keys(hash) + hash.each_with_object({}) do |(key, value), result| + result[key.respond_to?(:to_sym) ? key.to_sym : key] = deep_symbolize_keys_in_object(value) + result + end + end + + private + + def deep_symbolize_keys_in_object(value) + case value + when Hash + deep_symbolize_keys(value) + when Array + value.map { |e| deep_symbolize_keys_in_object(e) } + else + value + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/version.rb b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/version.rb new file mode 100644 index 0000000..bc754ba --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/i18n-1.10.0/lib/i18n/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module I18n + VERSION = "1.10.0" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/.autotest b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/.autotest new file mode 100644 index 0000000..b6fbce5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/.autotest @@ -0,0 +1,34 @@ +# -*- ruby -*- + +require 'autotest/restart' +require 'autotest/rcov' if ENV['RCOV'] + +Autotest.add_hook :initialize do |at| + at.testlib = 'minitest/autorun' + + bench_tests = %w(TestMinitestBenchmark) + mock_tests = %w(TestMinitestMock TestMinitestStub) + spec_tests = %w(TestMinitestReporter TestMetaStatic TestMeta + TestSpecInTestCase) + unit_tests = %w(TestMinitestGuard TestMinitestRunnable + TestMinitestRunner TestMinitestTest TestMinitestUnit + TestMinitestUnitInherited TestMinitestUnitOrder + TestMinitestUnitRecording TestMinitestUnitTestCase) + + { + bench_tests => "test/minitest/test_minitest_benchmark.rb", + mock_tests => "test/minitest/test_minitest_mock.rb", + spec_tests => "test/minitest/test_minitest_reporter.rb", + unit_tests => "test/minitest/test_minitest_unit.rb", + }.each do |klasses, file| + klasses.each do |klass| + at.extra_class_map[klass] = file + end + end + + at.add_exception 'coverage.info' + at.add_exception 'coverage' +end + +# require 'autotest/rcov' +# Autotest::RCov.command = 'rcov_info' diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/History.rdoc b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/History.rdoc new file mode 100644 index 0000000..252a651 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/History.rdoc @@ -0,0 +1,1430 @@ +=== 5.15.0 / 2021-12-14 + +* 1 major enhancement: + + * assert_throws returns the value returned, if any. (volmer) + +* 3 minor enhancements: + + * Added -S option to skip reporting of certain types of output + * Enable Ruby deprecation warnings by default. (casperisfine) + * Use Etc.nprocessors by default in order to maximize cpu usage. (tonytonyjan) + +* 6 bug fixes: + + * Close then unlink tempfiles on Windows. (nobu) + * Fixed #skip_until for windows paths. (MSP-Greg) + * Fixed a bunch of tests for jruby and windows. (MSP-Greg) + * Fixed marshalling of specs if they error. (tenderlove, jeremyevans, et al) + * Updated deprecation message for block expectations. (blowmage) + * Use Kernel.warn directly in expectations in case CUT defines their own warn. (firien) + +=== 5.14.4 / 2021-02-23 + +* 1 bug fix: + + * Fixed deprecation warning using stub with methods using keyword arguments. (Nakilon) + +=== 5.14.3 / 2021-01-05 + +* 1 bug fix: + + * Bumped require_ruby_version to < 4 (trunk = 3.1). + +=== 5.14.2 / 2020-08-31 + +* 1 bug fix: + + * Bumped ruby version to include 3.0 (trunk). + +=== 5.14.1 / 2020-05-15 + +* 3 minor enhancements: + + * Minitest.filter_backtrace returns original backtrace if filter comes back empty. + * Minitest::BacktraceFilter now returns entire backtrace if $MT_DEBUG set in env. + * Return true on a successful refute. (jusleg) + +* 1 bug fix: + + * Fixed expectation doco to not use global expectations. + +=== 5.14.0 / 2020-01-11 + +* 2 minor enhancements: + + * Block-assertions (eg assert_output) now error if raised inside the block. (casperisfine) + * Changed assert_raises to only catch Assertion since that covers Skip and friends. + +* 3 bug fixes: + + * Added example for value wrapper with block to Expectations module. (stomar) + * Fixed use of must/wont_be_within_delta on Expectation instance. (stomar) + * Renamed UnexpectedError#exception to #error to avoid problems with reraising. (casperisfine) + +=== 5.13.0 / 2019-10-29 + +* 9 minor enhancements: + + * Added Minitest::Guard#osx? + * Added examples to documentation for assert_raises. (lxxxvi) + * Added expectations #path_must_exist and #path_wont_exist. Not thrilled with the names. + * Added fail_after(year, month, day, msg) to allow time-bombing after a deadline. + * Added skip_until(year, month, day, msg) to allow deferring until a deadline. + * Deprecated Minitest::Guard#maglev? + * Deprecated Minitest::Guard#rubinius? + * Finally added assert_path_exists and refute_path_exists. (deivid-rodriguez) + * Refactored and pulled Assertions#things_to_diff out of #diff. (BurdetteLamar) + +* 3 bug fixes: + + * Fix autorun bug that affects fork exit status in tests. (dylanahsmith/jhawthorn) + * Improved documentation for _/value/expect, especially for blocks. (svoop) + * Support new Proc#to_s format. (ko1) + +=== 5.12.2 / 2019-09-28 + +* 1 bug fix: + + * After chatting w/ @y-yagi and others, decided to lower support to include ruby 2.2. + +=== 5.12.1 / 2019-09-28 + +* 1 minor enhancement: + + * Added documentation for Reporter classes. (sshaw) + +* 3 bug fixes: + + * Avoid using 'match?' to support older ruby versions. (y-yagi) + * Fixed broken link to reference on goodness-of-fit testing. (havenwood) + * Update requirements in readme and Rakefile/hoe spec. + +=== 5.12.0 / 2019-09-22 + +* 8 minor enhancements: + + * Added a descriptive error if assert_output or assert_raises called without a block. (okuramasafumi) + * Changed mu_pp_for_diff to make having both \n and \\n easier to debug. + * Deprecated $N for specifying number of parallel test runners. Use MT_CPU. + * Deprecated use of global expectations. To be removed from MT6. + * Extended Assertions#mu_pp to encoding validity output for strings to improve diffs. + * Extended Assertions#mu_pp to output encoding and validity if invalid to improve diffs. + * Extended Assertions#mu_pp_for_diff to make escaped newlines more obvious in diffs. + * Fail gracefully when expectation used outside of `it`. + +* 3 bug fixes: + + * Check `option[:filter]` klass before match. Fixes 2.6 warning. (y-yagi) + * Fixed Assertions#diff from recalculating if set to nil + * Fixed spec section of readme to not use deprecated global expectations. (CheezItMan) + +=== 5.11.3 / 2018-01-26 + +* 1 bug fix: + + * Pushed #error? up to Reportable module. (composerinteralia) + +=== 5.11.2 / 2018-01-25 + +* 1 minor enhancement: + + * Reversed Test < Result. Back to < Runnable and using Reportable for shared code. + +* 2 bug fixes: + + * Fixed Result#location for instances of Test. (alexisbernard) + * Fixed deprecation message for Runnable#marshal_dump. (y-yagi) + +=== 5.11.1 / 2018-01-02 + +* 1 bug fix: + + * Fixed Result (a superclass of Test) overriding Runnable's name accessors. (y-yagi, MSP-Greg) + +=== 5.11.0 / 2018-01-01 + +* 2 major enhancements: + + * Added Minitest::Result and Minitest::Result.from(runnable). + * Changed Minitest::Test to subclass Result and refactored methods up. + +* 7 minor enhancements: + + * Added --no-plugins and MT_NO_PLUGINS to bypass MT plugin autoloading. Helps with bad actors installed globally. + * Added bench_performance_{logarithmic,power} for spec-style benchmarks. (rickhull) + * Added deprecation warning for Runnable#marshal_dump. + * Minitest.run_one_method now checks for instance of Result, not exact same class. + * Minitest::Test.run returns a Result version of self, not self. + * ProgressReporter#prerecord now explicitly prints klass.name. Allows for fakers. + +* 4 bug fixes: + + * Object.stub no longer calls the passed block if stubbed with a callable. + * Object.stub now passes blocks down to the callable result. + * Pushed Minitest::Test#time & #time_it up to Runnable. + * Test nil equality directly in assert_equal. Fixes #679. (voxik) + +=== 5.11.0b1 / 2017-12-20 + +* 2 major enhancements: + + * Added Minitest::Result and Minitest::Result.from(runnable). + * Changed Minitest::Test to subclass Result and refactored methods up. + +* 6 minor enhancements: + + * Added --no-plugins and MT_NO_PLUGINS to bypass MT plugin autoloading. Helps with bad actors installed globally. + * Added bench_performance_{logarithmic,power} for spec-style benchmarks. (rickhull) + * Minitest.run_one_method now checks for instance of Result, not exact same class. + * Minitest::Test.run returns a Result version of self, not self. + * ProgressReporter#prerecord now explicitly prints klass.name. Allows for fakers. + * Removed Runnable.marshal_dump/load. + +* 4 bug fixes: + + * Object.stub no longer calls the passed block if stubbed with a callable. + * Object.stub now passes blocks down to the callable result. + * Pushed Minitest::Test#time & #time_it up to Runnable. + * Test nil equality directly in assert_equal. Fixes #679. (voxik) + +=== 5.10.3 / 2017-07-21 + +* 1 minor enhancement: + + * Extended documentation for Mock#expect for multiple calls to mock object. (insti) + +* 2 bug fixes: + + * Finished off missing doco. + * Fixed verbose output on parallelize_me! classes. (chanks) + +=== 5.10.2 / 2017-05-09 + +* 1 minor enhancement: + + * Added suggestion in minitest/hell to install minitest/proveit. + +* 7 bug fixes: + + * Expand MT6 to Minitest 6. (xaviershay) + * Fixed location of assert_send deprecation. (rab) + * Fixed location of nil assert_equal deprecation to work with expectations. (jeremyevans) + * Fixed minitest/hell to use parallelize_me! (azul) + * Made deprecation use warn so -W0 will silence it. + * Workaround for rdoc nodoc generation bug that totally f'd up minitest doco. (Paxa) + * Write aggregated_results directly to the IO object to avoid mixed encoding errors. (tenderlove) + +=== 5.10.1 / 2016-12-01 + +* 1 bug fix: + + * Added a hack/kludge to deal with missing #prerecord on reporters that aren't properly subclassing AbstractReporter (I'm looking at you minitest-reporters) + +=== 5.10.0 / 2016-11-30 + +* 1 major enhancement: + + * Deprecated ruby 1.8, 1.9, possibly 2.0, assert_send, & old MiniTest namespace. + +* 3 minor enhancements: + + * Warn if assert_equal expects a nil. This will fail in minitest 6+. (tenderlove) + * Added AbstractReporter#prerecord and extended ProgressReporter and CompositeReporter to use it. + * Minor optimization: remove runnables with no runnable methods before run. + +* 3 bug fixes: + + * Fix assert_throw rescuing any NameError and ArgumentError. (waldyr) + * Clean up (most of the) last remaining vestiges of minitest/unit. + * 2.4: removed deprecation warnings when referring to Fixnum. + +=== 5.9.1 / 2016-09-25 + +* 2 bug fixes: + + * Re-release to refresh gem certificate signing. ugh. + * Fixed hoe/minitest to not augment load path if we're actually testing minitest. + +=== 5.9.0 / 2016-05-16 + +* 8 minor enhancements: + + * Added Minitest.info_signal accessors to customize signal for test run info. (nate) + * Added assert_mock to make it more clear that you're testing w/ them. + * Added negative filter by test name. (utilum) + * Added warning to README that 1.8 and 1.9 support will be dropped in minitest 6. + * Automatically activate minitest/hell if $MT_HELL is defined. + * Improved default error messages for assert and refute. (bhenderson) + * minitest/hell now tries to require minitest/proveit + * mu_pp for strings prints out non-standard encodings to improve assert_equal diffs. + +* 1 bug fix: + + * Removed Interrupt from PASSTHROUGH_EXCEPTIONS (already handled). (waldyr) + +=== 5.8.5 / 2016-09-25 + +* 2 bug fixes: + + * Re-release to refresh gem certificate signing. ugh. + * Fixed hoe/minitest to not augment load path if we're actually testing minitest. + +=== 5.8.4 / 2016-01-21 + +* 1 bug fix: + + * Allow Minitest::Assertion to pass through assert_raises so inner failures are dealt with first. + +=== 5.8.3 / 2015-11-17 + +* 1 minor enhancement: + + * Added extra note about mocks and threads to readme. (zamith) + +* 1 bug fix: + + * Fixed bug in Mock#verify. (pithub/zamith) + +=== 5.8.2 / 2015-10-26 + +* 1 bug fix: + + * Fixed using parallelize_me! and capture_io (or any locking io). (arlt/tenderlove) + +=== 5.8.1 / 2015-09-23 + +* 1 minor enhancement: + + * Refactor assert_raises to be cleaner and to pass SystemExit and SignalException. (bhenderson) + +=== 5.8.0 / 2015-08-06 + +* 2 minor enhancements: + + * Add optional delegation mechanism to extend object with a mock. (zamith) + * Return early if there are no filtered methods. (jeremyevans) + +* 1 bug fix: + + * Don't extend io with pride if io is not a tty. (toy) + +=== 5.7.0 / 2015-05-27 + +* 1 major enhancement: + + * assert_raises now matches subclasses of the expected exception types. (jeremyevans) + +* 3 minor enhancements: + + * Added :block type for minitest/spec's #infect_an_assertion. (jeremyevans) + * Inline verification error messages in minitest/mock for GC performance. (zamith) + * assert_raises defaults to RuntimeError if not specified. (jeremyevans) + +* 4 bug fixes: + + * Added 'class' to minitest/mock's overridden_methods list. (zamith) + * Added file/line to infect_an_assertion's class_eval call. (jeremyevans) + * Cleared UnexpectedError's mesg w/ generic string. + * Fixed non-proc-oriented expectations when used on proc target. (jeremyevans) + +=== 5.6.1 / 2015-04-27 + +* 2 bug fixes: + + * Added Minitest.clock_time and switched all Time.now to it. (tenderlove) + * Moved Minitest::Expectations#_ into Minitest::Spec::DSL. + +=== 5.6.0 / 2015-04-13 + +* 4 major enhancements: + + * Added Minitest::Expectation value monad. + * Added Minitest::Expectations#_ that returns an Expectation. Aliased to value. + * All expectations are added to Minitest::Expectation. + * At some point, the methods on Object will be deprecated and then removed. + +* 4 minor enhancements: + + * Added a note about bundle exec pitfall in ruby 2.2+. (searls) + * Lazily start the parallel executor. (tenderlove) + * Make mocks more debugger-friendly (edward) + * Print out the current test run on interrupt. (riffraff) + +* 3 bug fixes: + + * Fix failing test under Windows. (kimhmadsen) + * Record mocked calls before they happen so mocks can raise exceptions easier (tho I'm not a fan). (corecode) + * Tried to clarify mocks vs stubs terminology better. (kkirsche) + +=== 5.5.1 / 2015-01-09 + +* 1 bug fix: + + * Fixed doco problems. (zzak) + +=== 5.5.0 / 2014-12-12 // mri 2.2.0 (as a real gem) + +* 1 minor enhancement: + + * Allow seed to be given via ENV for rake test loader sadness: eg rake SEED=42. + +=== 5.4.3 / 2014-11-11 + +* 2 bug fixes: + + * Clarified requirements for ruby are now 1.8.7 or better. + * Force encode error output in case mal-encoded exception is raised. (jasonrclark) + +=== 5.4.2 / 2014-09-26 + +* 2 minor enhancements: + + * Extract teardown method list. + * Thanks to minitest-gcstats got a 5-10% speedup via reduced GC! + +=== 5.4.1 / 2014-08-28 + +* 1 bug fix: + + * Fixed specs hidden by nesting/ordering bug (blowmage/apotonick) + +=== 5.4.0 / 2014-07-07 + +* 2 minor enhancements: + + * Kernel#describe extended to splat additional_desc. + * Spec#spec_type extended to take a splat of additional items, passed to matcher procs. + +* 1 bug fix: + + * minitest/spec should require minitest/test, not minitest/unit. (doudou) + +=== 5.3.5 / 2014-06-17 + +* 1 minor enhancement: + + * Spit and polish (mostly spit). + +=== 5.3.4 / 2014-05-15 + +* 1 minor enhancement: + + * Test classes are randomized before running. (judofyr) + +=== 5.3.3 / 2014-04-14 + +* 1 bug fix: + + * Fixed using expectations w/ DSL in Test class w/o describe. (blowmage+others) + +=== 5.3.2 / 2014-04-02 + +* 1 bug fix: + + * Fixed doco on Assertions.assertions. (xaviershay) + +=== 5.3.1 / 2014-03-14 + +* 1 minor enhancement: + + * Modified verbage on bad 'let' names to be more helpful. (Archytaus) + +* 1 bug fix: + + * Fixed 2 cases still using MiniTest. (mikesea) + +=== 5.3.0 / 2014-02-25 + +* 1 minor enhancement: + + * Mocked methods can take a block to verify state. Seattle.rb 12 bday present from ernie! Thanks!! + +=== 5.2.3 / 2014-02-10 + +* 1 bug fix: + + * Fixed Spec#let check to allow overriding of other lets. (mvz) + +=== 5.2.2 / 2014-01-22 + +* 1 minor enhancement: + + * Spec#let raises ArgumentError if you override _any_ instance method (except subject). (rynr) + +* 1 bug fix: + + * Fixed up benchmark spec doco and added a test to demonstrate. (bhenderson) + +=== 5.2.1 / 2014-01-07 + +* 1 bug fix: + + * Properly deal with horrible mix of runtime load errors + other at_exit handlers. (dougo/chqr) + +=== 5.2.0 / 2013-12-13 + +* 1 minor enhancement: + + * Change expectations to allow calling most on procs (but not calling the proc). (bhenderson+others) + +=== 5.1.0 / 2013-12-05 + +* 1 minor enhancement: + + * Use a Queue for scheduling parallel tests. (tenderlove) + +* 1 bug fix: + + * Fixed misspelling in doco. (amatsuda) + +=== 5.0.8 / 2013-09-20 + +* 1 bug fix: + + * Fixed siginfo handler by rearranging reporters and fixing to_s. (tenderlove) + +=== 5.0.7 / 2013-09-05 + +* 2 minor enhancements: + + * Added clarification about the use of thread local variables in expectations. (jemc) + * Added extra message about skipped tests, if any. Disable globally with $MT_NO_SKIP_MSG. + +* 2 bug fixes: + + * Only require minitest, not minitest/autorun in pride_plugin. (judofyr) + * Require rubygems in load_plugins in case you're not using minitest/autorun. + +=== 5.0.6 / 2013-06-28 + +* 3 minor enhancements: + + * Allow stub to pass args to blocks. (swindsor) + * Improved warning message about minitest/autorun to address 1.9's minitest/autorun. + * Made minitest/test require minitest as needed. For lib writers. (erikh) + +* 1 bug fix: + + * Fixed missing require in minitest/test. (erikh) + +=== 4.7.5 / 2013-06-21 // mri 2.1.1 + +* 2 bug fixes: + + * Fix Spec#describe_stack to be thread local. + * Fix multithreaded test failures by defining Time local to mock test namespace + +=== 5.0.5 / 2013-06-20 + +* 6 bug fixes: + + * DOH! Fixed the rest of the new casing on Minitest. (splattael) + * Fixed typo on minitest/mock rdoc. (mrgilman/guiceolin) + * Make Spec::DSL.describe_stack thread local to avoid failing on my own tests. + * Make a fake Time.now local to the tests so they won't interfere with real reporter timings. + * Make everything mockable by wrapping all 'special' methods in a smarter wrapper. (bestie) + * Raise ArgumentError if let name starts with 'test'. (johnmaxwell) + +=== 5.0.4 / 2013-06-07 + +* 5 minor enhancements: + + * Added AbstractReporter, defining required Reporter API to quack properly. + * Added doco for writing reporters. + * Refactored Reporter into ProgressReporter and SummaryReporter. (idea: phiggins, code:me+scotch) + * Refactored SummaryReporter pushing up to StatisticsReporter. (phiggins) + * Removed Reporter#run_and_report... cleaner, but doesn't "fit" in the API. + +=== 5.0.3 / 2013-05-29 + +* 4 minor enhancements: + + * Added Runnable.with_info_handler and Runnable.on_signal. + * Moved io.sync restore to Reporter#run_and_report. + * Refactored inner loop of Reporter#report to #to_s. Callable for status updates. + * Restored MT4's mid-run report (^t). (tenderlove). + +=== 5.0.2 / 2013-05-20 + +* 3 bug fixes: + + * Gem.find_files is smarter than I remember... cause I wrote it that way. *sigh* I'm getting old. + * Pride wasn't doing puts through its #io. (tmiller/tenderlove) + * Replaced Runnable#dup and Test#dup with marshal_dump/load. Too many problems cropping up on untested rails code. (tenderlove/rubys) + +=== 5.0.1 / 2013-05-14 + +* 2 bug fixes: + + * Documented Assertions' need for @assertions to be defined by the includer. + * Only load one plugin version per name. Tries for latest. + +=== 5.0.0 / 2013-05-10 + +Oh god... here we go... + +Minitest 5: + +* 4 deaths in the family: + + * MiniTest.runner is dead. No more manager objects. + * MiniTest::Unit#record is dead. Use a Reporter instance instead. + * MiniTest::Unit._run_* is dead. Runnable things are responsible for their own runs. + * MiniTest::Unit.output is dead. No more centralized IO. + +* 12 major (oft incompatible) changes: + + * Renamed MiniTest to Minitest. Your pinkies will thank me. (aliased to MiniTest) + * Removed MiniTest::Unit entirely. No more manager objects. + * Added Minitest::Runnable. Everything minitest can run subclasses this. + * Renamed MiniTest::Unit::TestCase to Minitest::Test (subclassing Runnable). + * Added Minitest::Benchmark. + * Your benchmarks need to move to their own subclass. + * Benchmarks using the spec DSL have to have "Bench" somewhere in their describe. + * MiniTest::Unit.after_tests moved to Minitest.after_run + * MiniTest::Unit.autorun is now Minitest.autorun. Just require minitest/autorun pls. + * Removed ParallelEach#grep since it isn't used anywhere. + * Renamed Runnable#__name__ to Runnable#name (but uses @NAME internally). + * Runnable#run needs to return self. Allows for swapping of results as needed. + +* 8 minor moves: + + * Moved Assertions module to minitest/assertions.rb + * Moved Expectations module to minitest/expectations.rb + * Moved Test to minitest/test.rb + * Moved everything else in minitest/unit.rb to minitest.rb + * minitest/unit.rb is now just a small (user-test only) compatibility layer. + * Moved most of minitest/pride into minitest/pride_plugin. + * minitest/pride now just activates pride. + * Moved ParallelEach under Minitest. + +* 9 additions: + + * Added a plugin system that can extend command-line options. + * Added Minitest.extensions. + * Added Minitest.reporter (only available during startup). + * Added Minitest.run(args). This is the very top of any Minitest run. + * Added Minitest::Reporter. Everything minitest can report goes through here. + * Minitest.reporter is a composite so you can add your own. + * Added Minitest::CompositeReporter. Much easier to extend with your own reporters. + * Added UnexpectedError, an Assertion subclass, to wrap up errors. + * Minitest::Test#run is now freakin' beautiful. 47 -> 17 loc + +* 11 other: + + * Removed Object.infect_with_assertions (it was already dead code). + * Runnables are responsible for knowing their result_code (eg "." or "F"). + * Minitest.autorun now returns boolean, not exit code. + * Added FAQ entry for extending via modules. (phiggins) + * Implement Runnable#dup to cleanse state back to test results. Helps with serialization. pair:tenderlove + * Moved ParallelEach under Minitest. + * Runnable#run needs to return self. Allows for swapping of results as needed. + * Minitest.init_plugins passes down options. + * Minitest.load_plugins only loads once. + * Fixed minitest/pride to work with rake test loader again. (tmiller) + * Added count/size to ParallelEach to fix use w/in stdlib's test/unit. :( (btaitelb) + +* 5 voodoo: + + * Removed mutex from minitest.rb (phiggins) + * Removed mutex from test.rb (phiggins) + * Removed Minitest::Reporter.synchronize (phiggins) + * Removed Minitest::Test.synchronize (phiggins) + * Upon loading minitest/parallel_each, record, capture_io and capture_subprocess_io are doped with synchronization code. (phiggins) + +=== 4.7.4 / 2013-05-01 + +This is probably the last release of the 4.x series. It will be merged +to ruby and will be put into maintenance mode there. + +I'm not set in stone on this, but at this point further development of +minitest (5+) will be gem-only. It is just too hard to work w/in +ruby-core w/ test-unit compatibility holding minitest development +back. + +* 2 minor enhancements: + + * Added count/size to ParallelEach to fix use w/in stdlib's test/unit. :( (btaitelb) + * Allow disabling of info_signal handler in runner. (erikh) + +=== 4.7.3 / 2013-04-20 + +* 1 bug fix: + + * Reverted stubbing of module methods change. Stub the user, not the impl. (ab9/tyabe) + +=== 4.7.2 / 2013-04-18 + +* 2 bug fixes: + + * Fixed inconsistency in refute_in_delta/epsilon. I double negatived my logic. (nettsundere) + * Fixed stubbing of module methods (eg Kernel#sleep). (steveklabnik) + +=== 4.7.1 / 2013-04-09 + +* 1 minor enhancement: + + * Added FAQ section to README + +* 1 bug fix: + + * Fixed bug where guard runs tests bypassing minitest/autorun and an ivar isn't set right. (darrencauthon) + +=== 4.7.0 / 2013-03-18 + +* 1 major enhancement: + + * Refactored MiniTest::Spec into MiniTest::Spec::DSL. + +* 1 bug fix: + + * Removed $DEBUG handler that detected when test/unit and minitest were both loaded. (tenderlove) + +=== 4.6.2 / 2013-02-27 + +* 1 minor enhancement: + + * Change error output to match Class#method, making it easier to use -n filter. + +=== 4.6.1 / 2013-02-14 + +* 1 bug fix: + + * Fixed an option processing bug caused by test/unit's irresponsibly convoluted code. (floehopper) + +=== 4.6.0 / 2013-02-07 + +* 3 major enhancements: + + * Removed ::reset_setup_teardown_hooks + * Removed the long deprecated assert_block + * Removed the long deprecated lifecycle hooks: add_(setup|teardown)_hook + +* 1 minor enhancement: + + * Allow filtering tests by suite name as well as test name. (lazyatom) + +* 2 bug fixes: + + * Made hex handling (eg object_ids) in mu_pp_for_diff more specific. (maxim) + * nodoc top-level module. (zzak) + +=== 4.5.0 / 2013-01-22 + +* 1 major enhancement: + + * Rearranged minitest/unit.rb so NO parallelization code is loaded/used until you opt-in. + +* 4 minor enhancements: + + * Added TestCase#skipped? for teardown guards + * Added maglev? guard + * Document that record can be sent twice if teardown fails or errors (randycoulman) + * Errors in teardown are now recorded. (randycoulman) + +* 3 bug fixes: + + * Added hacks and skips to get clean test runs on maglev + * Modified float tests for maglev float output differences. Not sure this is right. Not sure I care. + * Test for existance of diff.exe instead of assuming they have devkit. (blowmage/Cumbayah) + +=== 4.4.0 / 2013-01-07 + +* 3 minor enhancements: + + * Added fit_logarithic and assert_performance_logarithmic. (ktheory) + * Merge processed options so others can mess with defaults. (tenderlove) + * TestCase#message can now take another proc to defer custom message cost. (ordinaryzelig/bhenderson) + +* 1 bug fix: + + * TestCase#passed? now true if test is skipped. (qanhd) + +=== 4.3.3 / 2012-12-06 + +* 1 bug fix: + + * Updated information about stubbing. (daviddavis) + +=== 4.3.2 / 2012-11-27 // mri 2.0.0 + +* 1 minor enhancement: + + * Improved assert_equals error message to point you at #== of member objects. (kcurtin) + +=== 4.3.1 / 2012-11-23 + +* 1 bug fix: + + * Moved test_children to serial testcase to prevent random failures. + +=== 4.3.0 / 2012-11-17 + +* 4 minor enhancements: + + * Allow #autorun to run even if loaded with other test libs that call exit. (sunaku) + * Do not include Expectations in Object if $MT_NO_EXPECTATIONS is set (experimental?) + * Gave some much needed love to assert_raises. + * Mock#expect can take a block to custom-validate args. (gmoothart) + +=== 4.2.0 / 2012-11-02 + +* 4 major enhancements: + + * Added minitest/hell - run all your tests through the ringer! + * Added support for :parallel test_order to run test cases in parallel. + * Removed last_error and refactored runner code to be threadsafe. + * _run_suites now runs suites in parallel if they opt-in. + +* 4 minor enhancements: + + * Added TestCase#synchronize + * Added TestCase.make_my_diffs_pretty! + * Added TestCase.parallelize_me! + * Lock on capture_io for thread safety (tenderlove) + +=== 4.1.0 / 2012-10-05 + +* 2 minor enhancements: + + * Added skip example to readme. (dissolved) + * Extracted backtrace filter to object. (tenderlove) + +* 1 bug fix: + + * OMG I'm so dumb. Fixed access to deprecated hook class methods. I hate ruby modules. (route) + +=== 4.0.0 / 2012-09-28 + +* 1 major enhancement: + + * The names of a privately-used undocumented constants are Super Important™. + +* 1 minor enhancement: + + * Support stubbing methods that would be handled via method_missing. (jhsu) + +* 3 bug fixes: + + * Add include_private param to MiniTest::Mock#respond_to? (rf-) + * Fixed use of minitest/pride with --help. (zw963) + * Made 'No visible difference.' message more clear. (ckrailo) + +=== 3.5.0 / 2012-09-21 + +* 1 minor enhancement: + + * Added #capture_subprocess_io. (route) + +=== 3.4.0 / 2012-09-05 + +* 2 minor enhancements: + + * assert_output can now take regexps for expected values. (suggested by stomar) + * Clarified that ruby 1.9/2.0's phony gems cause serious confusion for rubygems. + +=== 3.3.0 / 2012-07-26 + +* 1 major enhancement: + + * Deprecated add_(setup|teardown)_hook in favor of (before|after)_(setup|teardown) [2013-01-01] + +* 4 minor enhancements: + + * Refactored deprecated hook system into a module. + * Refactored lifecycle hooks into a module. + * Removed after_setup/before_teardown + run_X_hooks from Spec. + * Spec#before/after now do a simple define_method and call super. DUR. + +* 2 bug fixes: + + * Fixed #passed? when used against a test that called flunk. (floehopper) + * Fixed rdoc bug preventing doco for some expectations. (stomar). + +=== 3.2.0 / 2012-06-26 + +* 1 minor enhancement: + + * Stubs now yield self. (peterhellberg) + +* 1 bug fix: + + * Fixed verbose test that only fails when run in verbose mode. mmmm irony. + +=== 3.1.0 / 2012-06-13 + +* 2 minor enhancements: + + * Removed LONG deprecated Unit.out accessor + * Removed generated method name munging from minitest/spec. (ordinaryzelig/tenderlove) + +=== 3.0.1 / 2012-05-24 + +* 1 bug fix: + + * I'm a dumbass and refactored into Mock#call. Renamed to #__call so you can mock #call. (mschuerig) + +=== 3.0.0 / 2012-05-08 + +* 3 major enhancements: + + * Added Object#stub (in minitest/mock.rb). + * Mock#expect mocks are used in the order they're given. + * Mock#verify now strictly compares against expect calls. + +* 3 minor enhancements: + + * Added caller to deprecation message. + * Mock error messages are much prettier. + * Removed String check for RHS of assert/refute_match. This lets #to_str work properly. + +* 1 bug fix: + + * Support drive letter on Windows. Patch provided from MRI by Usaku NAKAMURA. (ayumin) + +=== 2.12.1 / 2012-04-10 + +* 1 minor enhancement: + + * Added ruby releases to History.txt to make it easier to see what you're missing + +* 1 bug fix: + + * Rolled my own deprecate msg to allow MT to work with rubygems < 1.7 + +=== 2.12.0 / 2012-04-03 + +* 4 minor enhancements: + + * ::it returns test method name (wojtekmach) + * Added #record method to runner so runner subclasses can cleanly gather data. + * Added Minitest alias for MiniTest because even I forget. + * Deprecated assert_block!! Yay!!! + +* 1 bug fix: + + * Fixed warning in i_suck_and_my_tests_are_order_dependent! (phiggins) + +=== 2.11.4 / 2012-03-20 + +* 2 minor enhancements: + + * Updated known extensions + * You got your unicode in my tests! You got your tests in my unicode! (fl00r) + +* 1 bug fix: + + * Fixed MiniTest::Mock example in the readme. (conradwt) + +=== 2.11.3 / 2012-02-29 + +* 2 bug fixes: + + * Clarified that assert_raises returns the exception for further testing + * Fixed assert_in_epsilon when both args are negative. (tamc) + +=== 2.11.2 / 2012-02-14 + +* 1 minor enhancement: + + * Display failures/errors on SIGINFO. (tenderlove) + +* 1 bug fix: + + * Fixed MiniTest::Unit.after_tests for Ruby 1.9.3. (ysbaddaden) + +=== 2.11.1 / 2012-02-01 + +* 3 bug fixes: + + * Improved description for --name argument. (drd) + * Ensure Mock#expect's expected args is an Array. (mperham) + * Ensure Mock#verify verifies multiple expects of the same method. (chastell) + +=== 2.11.0 / 2012-01-25 + +* 2 minor enhancements: + + * Added before / after hooks for setup and teardown. (tenderlove) + * Pushed run_setup_hooks down to Spec. (tenderlove) + +=== 2.10.1 / 2012-01-17 + +* 1 bug fix: + + * Fixed stupid 1.9 path handling grumble grumble. (graaff) + +=== 2.10.0 / 2011-12-20 + +* 3 minor enhancements: + + * Added specs for must/wont be_empty/respond_to/be_kind_of and others. + * Added tests for assert/refute predicate. + * Split minitest/excludes.rb out to its own gem. + +* 1 bug fix: + + * Fixed must_be_empty and wont_be_empty argument handling. (mrsimo) + +=== 2.9.1 / 2011-12-13 + +* 4 minor enhancements: + + * Added a ton of tests on spec error message output. + * Cleaned up consistency of msg handling on unary expectations. + * Improved error messages on assert/refute_in_delta. + * infect_an_assertion no longer checks arity and better handles args. + +* 1 bug fix: + + * Fixed error message on specs when 2+ args and custom message provided. (chastell) + +=== 2.9.0 / 2011-12-07 + +* 4 minor enhancements: + + * Added TestCase.exclude and load_excludes for programmatic filtering of tests. + * Added guard methods so you can cleanly skip based on platform/impl + * Holy crap! 100% doco! `rdoc -C` ftw + * Switch assert_output to test stderr before stdout to possibly improve debugging + +=== 2.8.1 / 2011-11-17 + +* 1 bug fix: + + * Ugh. 1.9's test/unit violates my internals. Added const_missing. + +=== 2.8.0 / 2011-11-08 + +* 2 minor enhancements: + + * Add a method so that code can be run around a particular test case (tenderlove) + * Turn off backtrace filtering if we're running inside a ruby checkout. (drbrain) + +* 2 bug fixes: + + * Fixed 2 typos and 2 doc glitches. (splattael) + * Remove unused block arguments to avoid creating Proc objects. (k-tsj) + +=== 2.7.0 / 2011-10-25 + +* 2 minor enhancements: + + * Include failed values in the expected arg output in MockExpectationError. (nono) + * Make minitest/pride work with other 256 color capable terms. (sunaku) + +* 2 bug fixes: + + * Clarified the documentation of minitest/benchmark (eregon) + * Fixed using expectations in regular unit tests. (sunaku) + +=== 2.6.2 / 2011-10-19 + +* 1 minor enhancement: + + * Added link to vim bundle. (sunaku) + +* 2 bug fixes: + + * Force gem activation in hoe minitest plugin + * Support RUBY_VERSION='2.0.0' (nagachika) + +=== 2.6.1 / 2011-09-27 + +* 2 bug fixes: + + * Alias Spec.name from Spec.to_s so it works when @name is nil (nathany) + * Fixed assert and refute_operator where second object has a bad == method. + +=== 2.6.0 / 2011-09-13 + +* 2 minor enhancements: + + * Added specify alias for it and made desc optional. + * Spec#must_be and #wont_be can be used with predicates (metaskills) + +* 1 bug fix: + + * Fixed Mock.respond_to?(var) to work with strings. (holli) + +=== 2.5.1 / 2011-08-27 // ruby 1.9.3: p0, p125, p34579 + +* 2 minor enhancements: + + * Added gem activation for minitest in minitest/autoload to help out 1.9 users + * Extended Spec.register_spec_type to allow for procs instead of just regexps. + +=== 2.5.0 / 2011-08-18 + +* 4 minor enhancements: + + * Added 2 more arguments against rspec: let & subject in 9 loc! (emmanuel/luis) + * Added TestCase.i_suck_and_my_tests_are_order_dependent! + * Extended describe to take an optional method name (2 line change!). (emmanuel) + * Refactored and extended minitest/pride to do full 256 color support. (lolcat) + +* 1 bug fix: + + * Doc fixes. (chastell) + +=== 2.4.0 / 2011-08-09 + +* 4 minor enhancements: + + * Added simple examples for all expectations. + * Improved Mock error output when args mismatch. + * Moved all expectations from Object to MiniTest::Expectations. + * infect_with_assertions has been removed due to excessive clever + +* 4 bug fixes: + + * Fix Assertions#mu_pp to deal with immutable encoded strings. (ferrous26) + * Fix minitest/pride for MacRuby (ferrous26) + * Made error output less fancy so it is more readable + * Mock shouldn't undef === and inspect. (dgraham) + +=== 2.3.1 / 2011-06-22 + +* 1 bug fix: + + * Fixed minitest hoe plugin to be a spermy dep and not depend on itself. + +=== 2.3.0 / 2011-06-15 + +* 5 minor enhancements: + + * Add setup and teardown hooks to MiniTest::TestCase. (phiggins) + * Added nicer error messages for MiniTest::Mock. (phiggins) + * Allow for less specific expected arguments in Mock. (bhenderson/phiggins) + * Made MiniTest::Mock a blank slate. (phiggins) + * Refactored minitest/spec to use the hooks instead of define_inheritable_method. (phiggins) + +* 2 bug fixes: + + * Fixed TestCase's inherited hook. (dchelimsky/phiggins/jamis, the 'good' neighbor) + * MiniTest::Assertions#refute_empty should use mu_pp in the default message. (whatthejeff) + +=== 2.2.2 / 2011-06-01 + +* 2 bug fixes: + + * Got rid of the trailing period in message for assert_equal. (tenderlove) + * Windows needs more flushing. (Akio Tajima) + +=== 2.2.1 / 2011-05-31 + +* 1 bug fix: + + * My _ONE_ non-rubygems-using minitest user goes to Seattle.rb! + +=== 2.2.0 / 2011-05-29 + +* 6 minor enhancements: + + * assert_equal (and must_equal) now tries to diff output where it makes sense. + * Added Assertions#diff(exp, act) to be used by assert_equal. + * Added Assertions#mu_pp_for_diff + * Added Assertions.diff and diff= + * Moved minitest hoe-plugin from hoe-seattlerb. (erikh) + * Skipped tests only output details in verbose mode. (tenderlove+zenspider=xoxo) + +=== 2.1.0 / 2011-04-11 + +* 5 minor enhancements: + + * Added MiniTest::Spec.register_spec_type(matcher, klass) and spec_type(desc) + * Added ability for specs to share code via subclassing of Spec. (metaskills) + * Clarified (or tried to) bench_performance_linear's use of threshold. + * MiniTest::Unit.runner=(runner) provides an easy way of creating custom test runners for specialized needs. (justinweiss) + * Reverse order of inheritance in teardowns of specs. (deepfryed) + +* 3 bug fixes: + + * FINALLY fixed problems of inheriting specs in describe/it/describe scenario. (MGPalmer) + * Fixed a new warning in 1.9.3. + * Fixed assert_block's message handling. (nobu) + +=== 2.0.2 / 2010-12-24 + +* 1 minor enhancement: + + * Completed doco on minitest/benchmark for specs. + +* 1 bug fix: + + * Benchmarks in specs that didn't call bench_range would die. (zzak). + +=== 2.0.1 / 2010-12-15 + +* 4 minor enhancements: + + * Do not filter backtrace if $DEBUG + * Exit autorun via nested at_exit handler, in case other libs call exit + * Make options accesor lazy. + * Split printing of test name and its time. (nurse) + +* 1 bug fix: + + * Fix bug when ^T is hit before runner start + +=== 2.0.0 / 2010-11-11 + +* 3 major enhancements: + + * Added minitest/benchmark! Assert your performance! YAY! + * Refactored runner to allow for more extensibility. See minitest/benchmark. + * This makes the runner backwards incompatible in some ways! + +* 9 minor enhancements: + + * Added MiniTest::Unit.after_tests { ... } + * Improved output by adding test rates and a more sortable verbose format + * Improved readme based on feedback from others + * Added io method to TestCase. If used, it'll supplant '.EF' output. + * Refactored IO in MiniTest::Unit. + * Refactored _run_anything to _run_suite to make it easier to wrap (ngauthier) + * Spec class names are now the unmunged descriptions (btakita) + * YAY for not having redundant rdoc/readmes! + * Help output is now generated from the flags you passed straight up. + +* 4 bug fixes: + + * Fixed scoping issue on minitest/mock (srbaker/prosperity) + * Fixed some of the assertion default messages + * Fixes autorun when on windows with ruby install on different drive (larsch) + * Fixed rdoc output bug in spec.rb + +=== 1.7.2 / 2010-09-23 + +* 3 bug fixes: + + * Fixed doco for expectations and Spec. + * Fixed test_capture_io on 1.9.3+ (sora_h) + * assert_raises now lets MiniTest::Skip through. (shyouhei) + +=== 1.7.1 / 2010-09-01 + +* 1 bug fix: + + * 1.9.2 fixes for spec tests + +=== 1.7.0 / 2010-07-15 + +* 5 minor enhancements: + + * Added assert_output (mapped to must_output). + * Added assert_silent (mapped to must_be_silent). + * Added examples to readme (Mike Dalessio) + * Added options output at the top of the run, for fatal run debugging (tenderlove) + * Spec's describe method returns created class + +=== 1.6.0 / 2010-03-27 // ruby 1.9.2-p290 + +* 10 minor enhancements: + + * Added --seed argument so you can reproduce a random order for debugging. + * Added documentation for assertions + * Added more rdoc and tons of :nodoc: + * Added output to give you all the options you need to reproduce that run. + * Added proper argument parsing to minitest. + * Added unique serial # to spec names so order can be preserved (needs tests). (phrogz) + * Empty 'it' fails with default msg. (phrogz) + * Remove previous method on expect to remove 1.9 warnings + * Spec#it is now order-proof wrt subclasses/nested describes. + * assert_same error message now reports in decimal, eg: oid=123. (mattkent) + +* 2 bug fixes: + + * Fixed message on refute_same to be consistent with assert_same. + * Fixed method randomization to be stable for testing. + +=== 1.5.0 / 2010-01-06 + +* 4 minor enhancements: + + * Added ability to specify what assertions should have their args flipped. + * Don't flip arguments on *include and *respond_to assertions. + * Refactored Module.infect_an_assertion from Module.infect_with_assertions. + * before/after :all now bitches and acts like :each + +* 3 bug fixes: + + * Nested describes now map to nested test classes to avoid namespace collision. + * Using undef_method instead of remove_method to clean out inherited specs. + * assert_raises was ignoring passed in message. + +=== 1.4.2 / 2009-06-25 + +* 1 bug fix: + + * Fixed info handler for systems that don't have siginfo. + +=== 1.4.1 / 2009-06-23 + +* 1 major enhancement: + + * Handle ^C and other fatal exceptions by failing + +* 1 minor enhancement: + + * Added something to catch mixed use of test/unit and minitest if $DEBUG + +* 1 bug fix: + + * Added SIGINFO handler for finding slow tests without verbose + +=== 1.4.0 / 2009-06-18 + +* 5 minor enhancement: + + * Added clarification doco. + * Added specs and mocks to autorun. + * Changed spec test class creation to be non-destructive. + * Updated rakefile for new hoe capabilities. + * describes are nestable (via subclass). before/after/def inherits, specs don't. + +* 3 bug fixes: + + * Fixed location on must/wont. + * Switched to __name__ to avoid common ivar name. + * Fixed indentation in test file (1.9). + +=== 1.3.1 / 2009-01-20 // ruby 1.9.1-p431 + +* 1 minor enhancement: + + * Added miniunit/autorun.rb as replacement for test/unit.rb's autorun. + +* 16 bug fixes: + + * 1.9 test fixes. + * Bug fixes from nobu and akira for really odd scenarios. They run ruby funny. + * Fixed (assert|refute)_match's argument order. + * Fixed LocalJumpError in autorun if exception thrown before at_exit. + * Fixed assert_in_delta (should be >=, not >). + * Fixed assert_raises to match Modules. + * Fixed capture_io to not dup IOs. + * Fixed indentation of capture_io for ruby 1.9 warning. + * Fixed location to deal better with custom assertions and load paths. (Yuki) + * Fixed order of (must|wont)_include in MiniTest::Spec. + * Fixed skip's backtrace. + * Got arg order wrong in *_match in tests, message wrong as a result. + * Made describe private. For some reason I thought that an attribute of Kernel. + * Removed disable_autorun method, added autorun.rb instead. + * assert_match escapes if passed string for pattern. + * instance_of? is different from ===, use instance_of. + +=== 1.3.0 / 2008-10-09 + +* 2 major enhancements: + + * renamed to minitest and pulled out test/unit compatibility. + * mini/test.rb is now minitest/unit.rb, everything else maps directly. + +* 12 minor enhancements: + + * assert_match now checks that act can call =~ and converts exp to a + regexp only if needed. + * Added assert_send... seems useless to me tho. + * message now forces to string... ruby-core likes to pass classes and arrays :( + * Added -v handling and switched to @verbose from $DEBUG. + * Verbose output now includes test class name and adds a sortable running time! + * Switched message generation into procs for message deferment. + * Added skip and renamed fail to flunk. + * Improved output failure messages for assert_instance_of, assert_kind_of + * Improved output for assert_respond_to, assert_same. + * at_exit now exits false instead of errors+failures. + * Made the tests happier and more readable imhfo. + * Switched index(s) == 0 to rindex(s, 0) on nobu's suggestion. Faster. + +* 5 bug fixes: + + * 1.9: Added encoding normalization in mu_pp. + * 1.9: Fixed backtrace filtering (BTs are expanded now) + * Added back exception_details to assert_raises. DOH. + * Fixed shadowed variable in mock.rb + * Fixed stupid muscle memory message bug in assert_send. + +=== 1.2.1 / 2008-06-10 + +* 7 minor enhancements: + + * Added deprecations everywhere in test/unit. + * Added test_order to TestCase. :random on mini, :sorted on test/unit (for now). + * Big cleanup in test/unit for rails. Thanks Jeremy Kemper! + * Minor readability cleanup. + * Pushed setup/run/teardown down to testcase allowing specialized testcases. + * Removed pp. Tests run 2x faster. :/ + * Renamed deprecation methods and moved to test/unit/deprecate.rb. + +=== 1.2.0 / 2008-06-09 + +* 2 major enhancements: + + * Added Mini::Spec. + * Added Mini::Mock. Thanks Steven Baker!! + +* 23 minor enhancements: + + * Added bin/use_miniunit to make it easy to test out miniunit. + * Added -n filtering, thanks to Phil Hagelberg! + * Added args argument to #run, takes ARGV from at_exit. + * Added test name output if $DEBUG. + * Added a refute (was deny) for every assert. + * Added capture_io and a bunch of nice assertions from zentest. + * Added deprecation mechanism for assert_no/not methods to test/unit/assertions. + * Added pp output when available. + * Added tests for all assertions. Pretty much maxed out coverage. + * Added tests to verify consistency and good naming. + * Aliased and deprecated all ugly assertions. + * Cleaned out test/unit. Moved autorun there. + * Code cleanup to make extensions easier. Thanks Chad! + * Got spec args reversed in all but a couple assertions. Much more readable. + * Improved error messages across the board. Adds your message to the default. + * Moved into Mini namespace, renamed to Mini::Test and Mini::Spec. + * Pulled the assertions into their own module... + * Removed as much code as I could while still maintaining full functionality. + * Moved filter_backtrace into MiniTest. + * Removed MiniTest::Unit::run. Unnecessary. + * Removed location_of_failure. Unnecessary. + * Rewrote test/unit's filter_backtrace. Flog from 37.0 to 18.1 + * Removed assert_send. Google says it is never used. + * Renamed MiniTest::Unit.autotest to #run. + * Renamed deny to refute. + * Rewrote some ugly/confusing default assertion messages. + * assert_in_delta now defaults to 0.001 precision. Makes specs prettier. + +* 9 bug fixes: + + * Fixed assert_raises to raise outside of the inner-begin/rescue. + * Fixed for ruby 1.9 and rubinius. + * No longer exits 0 if exception in code PRE-test run causes early exit. + * Removed implementors method list from mini/test.rb - too stale. + * assert_nothing_raised takes a class as an arg. wtf? STUPID + * ".EF" output is now unbuffered. + * Bunch of changes to get working with rails... UGH. + * Added stupid hacks to deal with rails not requiring their dependencies. + * Now bitch loudly if someone defines one of my classes instead of requiring. + * Fixed infect method to work better on 1.9. + * Fixed all shadowed variable warnings in 1.9. + +=== 1.1.0 / 2007-11-08 + +* 4 major enhancements: + + * Finished writing all missing assertions. + * Output matches original test/unit. + * Documented every method needed by language implementor. + * Fully switched over to self-testing setup. + +* 2 minor enhancements: + + * Added deny (assert ! test), our favorite extension to test/unit. + * Added .autotest and fairly complete unit tests. (thanks Chad for help here) + +=== 1.0.0 / 2006-10-30 + +* 1 major enhancement + + * Birthday! diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/Manifest.txt b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/Manifest.txt new file mode 100644 index 0000000..8e096ff --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/Manifest.txt @@ -0,0 +1,27 @@ +.autotest +History.rdoc +Manifest.txt +README.rdoc +Rakefile +design_rationale.rb +lib/hoe/minitest.rb +lib/minitest.rb +lib/minitest/assertions.rb +lib/minitest/autorun.rb +lib/minitest/benchmark.rb +lib/minitest/expectations.rb +lib/minitest/hell.rb +lib/minitest/mock.rb +lib/minitest/parallel.rb +lib/minitest/pride.rb +lib/minitest/pride_plugin.rb +lib/minitest/spec.rb +lib/minitest/test.rb +lib/minitest/unit.rb +test/minitest/metametameta.rb +test/minitest/test_minitest_assertions.rb +test/minitest/test_minitest_benchmark.rb +test/minitest/test_minitest_mock.rb +test/minitest/test_minitest_reporter.rb +test/minitest/test_minitest_spec.rb +test/minitest/test_minitest_test.rb diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/README.rdoc b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/README.rdoc new file mode 100644 index 0000000..f8cc32c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/README.rdoc @@ -0,0 +1,803 @@ += minitest/{test,spec,mock,benchmark} + +home :: https://github.com/seattlerb/minitest +bugs :: https://github.com/seattlerb/minitest/issues +rdoc :: http://docs.seattlerb.org/minitest +vim :: https://github.com/sunaku/vim-ruby-minitest +emacs:: https://github.com/arthurnn/minitest-emacs + +== DESCRIPTION: + +minitest provides a complete suite of testing facilities supporting +TDD, BDD, mocking, and benchmarking. + + "I had a class with Jim Weirich on testing last week and we were + allowed to choose our testing frameworks. Kirk Haines and I were + paired up and we cracked open the code for a few test + frameworks... + + I MUST say that minitest is *very* readable / understandable + compared to the 'other two' options we looked at. Nicely done and + thank you for helping us keep our mental sanity." + + -- Wayne E. Seguin + +minitest/test is a small and incredibly fast unit testing framework. +It provides a rich set of assertions to make your tests clean and +readable. + +minitest/spec is a functionally complete spec engine. It hooks onto +minitest/test and seamlessly bridges test assertions over to spec +expectations. + +minitest/benchmark is an awesome way to assert the performance of your +algorithms in a repeatable manner. Now you can assert that your newb +co-worker doesn't replace your linear algorithm with an exponential +one! + +minitest/mock by Steven Baker, is a beautifully tiny mock (and stub) +object framework. + +minitest/pride shows pride in testing and adds coloring to your test +output. I guess it is an example of how to write IO pipes too. :P + +minitest/test is meant to have a clean implementation for language +implementors that need a minimal set of methods to bootstrap a working +test suite. For example, there is no magic involved for test-case +discovery. + + "Again, I can't praise enough the idea of a testing/specing + framework that I can actually read in full in one sitting!" + + -- Piotr Szotkowski + +Comparing to rspec: + + rspec is a testing DSL. minitest is ruby. + + -- Adam Hawkins, "Bow Before MiniTest" + +minitest doesn't reinvent anything that ruby already provides, like: +classes, modules, inheritance, methods. This means you only have to +learn ruby to use minitest and all of your regular OO practices like +extract-method refactorings still apply. + +== FEATURES/PROBLEMS: + +* minitest/autorun - the easy and explicit way to run all your tests. +* minitest/test - a very fast, simple, and clean test system. +* minitest/spec - a very fast, simple, and clean spec system. +* minitest/mock - a simple and clean mock/stub system. +* minitest/benchmark - an awesome way to assert your algorithm's performance. +* minitest/pride - show your pride in testing! +* Incredibly small and fast runner, but no bells and whistles. +* Written by squishy human beings. Software can never be perfect. We will all eventually die. + +== RATIONALE: + +See design_rationale.rb to see how specs and tests work in minitest. + +== SYNOPSIS: + +Given that you'd like to test the following class: + + class Meme + def i_can_has_cheezburger? + "OHAI!" + end + + def will_it_blend? + "YES!" + end + end + +=== Unit tests + +Define your tests as methods beginning with +test_+. + + require "minitest/autorun" + + class TestMeme < Minitest::Test + def setup + @meme = Meme.new + end + + def test_that_kitty_can_eat + assert_equal "OHAI!", @meme.i_can_has_cheezburger? + end + + def test_that_it_will_not_blend + refute_match /^no/i, @meme.will_it_blend? + end + + def test_that_will_be_skipped + skip "test this later" + end + end + +=== Specs + + require "minitest/autorun" + + describe Meme do + before do + @meme = Meme.new + end + + describe "when asked about cheeseburgers" do + it "must respond positively" do + _(@meme.i_can_has_cheezburger?).must_equal "OHAI!" + end + end + + describe "when asked about blending possibilities" do + it "won't say no" do + _(@meme.will_it_blend?).wont_match /^no/i + end + end + end + +For matchers support check out: + +* https://github.com/wojtekmach/minitest-matchers +* https://github.com/rmm5t/minitest-matchers_vaccine + +=== Benchmarks + +Add benchmarks to your tests. + + # optionally run benchmarks, good for CI-only work! + require "minitest/benchmark" if ENV["BENCH"] + + class TestMeme < Minitest::Benchmark + # Override self.bench_range or default range is [1, 10, 100, 1_000, 10_000] + def bench_my_algorithm + assert_performance_linear 0.9999 do |n| # n is a range value + @obj.my_algorithm(n) + end + end + end + +Or add them to your specs. If you make benchmarks optional, you'll +need to wrap your benchmarks in a conditional since the methods won't +be defined. In minitest 5, the describe name needs to match +/Bench(mark)?$/. + + describe "Meme Benchmark" do + if ENV["BENCH"] then + bench_performance_linear "my_algorithm", 0.9999 do |n| + 100.times do + @obj.my_algorithm(n) + end + end + end + end + +outputs something like: + + # Running benchmarks: + + TestBlah 100 1000 10000 + bench_my_algorithm 0.006167 0.079279 0.786993 + bench_other_algorithm 0.061679 0.792797 7.869932 + +Output is tab-delimited to make it easy to paste into a spreadsheet. + +=== Mocks + +Mocks and stubs defined using terminology by Fowler & Meszaros at +http://www.martinfowler.com/bliki/TestDouble.html: + +"Mocks are pre-programmed with expectations which form a specification +of the calls they are expected to receive. They can throw an exception +if they receive a call they don't expect and are checked during +verification to ensure they got all the calls they were expecting." + + class MemeAsker + def initialize(meme) + @meme = meme + end + + def ask(question) + method = question.tr(" ", "_") + "?" + @meme.__send__(method) + end + end + + require "minitest/autorun" + + describe MemeAsker, :ask do + describe "when passed an unpunctuated question" do + it "should invoke the appropriate predicate method on the meme" do + @meme = Minitest::Mock.new + @meme_asker = MemeAsker.new @meme + @meme.expect :will_it_blend?, :return_value + + @meme_asker.ask "will it blend" + + @meme.verify + end + end + end + +==== Multi-threading and Mocks + +Minitest mocks do not support multi-threading. If it works, fine, if it doesn't +you can use regular ruby patterns and facilities like local variables. Here's +an example of asserting that code inside a thread is run: + + def test_called_inside_thread + called = false + pr = Proc.new { called = true } + thread = Thread.new(&pr) + thread.join + assert called, "proc not called" + end + +=== Stubs + +Mocks and stubs are defined using terminology by Fowler & Meszaros at +http://www.martinfowler.com/bliki/TestDouble.html: + +"Stubs provide canned answers to calls made during the test". + +Minitest's stub method overrides a single method for the duration of +the block. + + def test_stale_eh + obj_under_test = Something.new + + refute obj_under_test.stale? + + Time.stub :now, Time.at(0) do # stub goes away once the block is done + assert obj_under_test.stale? + end + end + +A note on stubbing: In order to stub a method, the method must +actually exist prior to stubbing. Use a singleton method to create a +new non-existing method: + + def obj_under_test.fake_method + ... + end + +=== Running Your Tests + +Ideally, you'll use a rake task to run your tests, either piecemeal or +all at once. Both rake and rails ship with rake tasks for running your +tests. BUT! You don't have to: + + % ruby -Ilib:test test/minitest/test_minitest_test.rb + Run options: --seed 37685 + + # Running: + + ...................................................................... (etc) + + Finished in 0.107130s, 1446.8403 runs/s, 2959.0217 assertions/s. + + 155 runs, 317 assertions, 0 failures, 0 errors, 0 skips + +There are runtime options available, both from minitest itself, and also +provided via plugins. To see them, simply run with +--help+: + + % ruby -Ilib:test test/minitest/test_minitest_test.rb --help + minitest options: + -h, --help Display this help. + -s, --seed SEED Sets random seed. Also via env. Eg: SEED=n rake + -v, --verbose Verbose. Show progress processing files. + -n, --name PATTERN Filter run on /regexp/ or string. + -e, --exclude PATTERN Exclude /regexp/ or string from run. + + Known extensions: pride, autotest + -p, --pride Pride. Show your testing pride! + -a, --autotest Connect to autotest server. + +You can set up a rake task to run all your tests by adding this to your Rakefile: + + require "rake/testtask" + + Rake::TestTask.new(:test) do |t| + t.libs << "test" + t.libs << "lib" + t.test_files = FileList["test/**/test_*.rb"] + end + + task :default => :test + +== Writing Extensions + +To define a plugin, add a file named minitest/XXX_plugin.rb to your +project/gem. That file must be discoverable via ruby's LOAD_PATH (via +rubygems or otherwise). Minitest will find and require that file using +Gem.find_files. It will then try to call +plugin_XXX_init+ during +startup. The option processor will also try to call +plugin_XXX_options+ +passing the OptionParser instance and the current options hash. This +lets you register your own command-line options. Here's a totally +bogus example: + + # minitest/bogus_plugin.rb: + + module Minitest + def self.plugin_bogus_options(opts, options) + opts.on "--myci", "Report results to my CI" do + options[:myci] = true + options[:myci_addr] = get_myci_addr + options[:myci_port] = get_myci_port + end + end + + def self.plugin_bogus_init(options) + self.reporter << MyCI.new(options) if options[:myci] + end + end + +=== Adding custom reporters + +Minitest uses composite reporter to output test results using multiple +reporter instances. You can add new reporters to the composite during +the init_plugins phase. As we saw in +plugin_bogus_init+ above, you +simply add your reporter instance to the composite via <<. + ++AbstractReporter+ defines the API for reporters. You may subclass it +and override any method you want to achieve your desired behavior. + +start :: Called when the run has started. +record :: Called for each result, passed or otherwise. +report :: Called at the end of the run. +passed? :: Called to see if you detected any problems. + +Using our example above, here is how we might implement MyCI: + + # minitest/bogus_plugin.rb + + module Minitest + class MyCI < AbstractReporter + attr_accessor :results, :addr, :port + + def initialize options + self.results = [] + self.addr = options[:myci_addr] + self.port = options[:myci_port] + end + + def record result + self.results << result + end + + def report + CI.connect(addr, port).send_results self.results + end + end + + # code from above... + end + +== FAQ + +=== What versions are compatible with what? Or what versions are supported? + +Minitest is a dependency of rails, which until fairly recently had an +overzealous backwards compatibility policy. As such, I'm stuck +supporting versions of ruby that are long past EOL. Once rails 5.2 is +dropped (hopefully April 2021), I get to drop a bunch of versions of +ruby that I have to currently test against. + +(As of 2021-01-31) + +Current versions of rails: (https://endoflife.date/rails) + + | rails | min ruby | rec ruby | minitest | status | + |-------+----------+----------+----------+----------| + | 7.0 | >= 2.7 | 3.0 | >= 5.1 | Future | + | 6.1 | >= 2.5 | 3.0 | >= 5.1 | Current | + | 6.0 | >= 2.5 | 2.6 | >= 5.1 | Security | + | 5.2 | >= 2.2.2 | 2.5 | ~> 5.1 | Security | EOL @railsconf 2021? + +Current versions of ruby: (https://endoflife.date/ruby) + + | ruby | Status | EOL Date | + |------+---------+------------| + | 3.0 | Current | 2024-03-31 | + | 2.7 | Maint | 2023-03-31 | + | 2.6 | Maint* | 2022-03-31 | + | 2.5 | EOL | 2021-03-31 | + | 2.4 | EOL | 2020-03-31 | + | 2.3 | EOL | 2019-03-31 | + | 2.2 | EOL | 2018-03-31 | + +See also: + +* https://www.fastruby.io/blog/ruby/rails/versions/compatibility-table.html +* https://jamesjeffersconsulting.com/ruby-rails-version-matrix/ + +=== How to test SimpleDelegates? + +The following implementation and test: + + class Worker < SimpleDelegator + def work + end + end + + describe Worker do + before do + @worker = Worker.new(Object.new) + end + + it "must respond to work" do + _(@worker).must_respond_to :work + end + end + +outputs a failure: + + 1) Failure: + Worker#test_0001_must respond to work [bug11.rb:16]: + Expected # (Object) to respond to #work. + +Worker is a SimpleDelegate which in 1.9+ is a subclass of BasicObject. +Expectations are put on Object (one level down) so the Worker +(SimpleDelegate) hits +method_missing+ and delegates down to the ++Object.new+ instance. That object doesn't respond to work so the test +fails. + +You can bypass SimpleDelegate#method_missing by extending the worker +with Minitest::Expectations. You can either do that in your setup at +the instance level, like: + + before do + @worker = Worker.new(Object.new) + @worker.extend Minitest::Expectations + end + +or you can extend the Worker class (within the test file!), like: + + class Worker + include ::Minitest::Expectations + end + +=== How to share code across test classes? + +Use a module. That's exactly what they're for: + + module UsefulStuff + def useful_method + # ... + end + end + + describe Blah do + include UsefulStuff + + def test_whatever + # useful_method available here + end + end + +Remember, +describe+ simply creates test classes. It's just ruby at +the end of the day and all your normal Good Ruby Rules (tm) apply. If +you want to extend your test using setup/teardown via a module, just +make sure you ALWAYS call super. before/after automatically call super +for you, so make sure you don't do it twice. + +=== How to run code before a group of tests? + +Use a constant with begin...end like this: + + describe Blah do + SETUP = begin + # ... this runs once when describe Blah starts + end + # ... + end + +This can be useful for expensive initializations or sharing state. +Remember, this is just ruby code, so you need to make sure this +technique and sharing state doesn't interfere with your tests. + +=== Why am I seeing uninitialized constant MiniTest::Test (NameError)? + +Are you running the test with Bundler (e.g. via bundle exec )? If so, +in order to require minitest, you must first add the gem 'minitest' +to your Gemfile and run +bundle+. Once it's installed, you should be +able to require minitest and run your tests. + +== Prominent Projects using Minitest: + +* arel +* journey +* mime-types +* nokogiri +* rails (active_support et al) +* rake +* rdoc +* ...and of course, everything from seattle.rb... + +== Developing Minitest: + +Minitest requires {Hoe}[https://rubygems.org/gems/hoe]. + +=== Minitest's own tests require UTF-8 external encoding. + +This is a common problem in Windows, where the default external Encoding is +often CP850, but can affect any platform. +Minitest can run test suites using any Encoding, but to run Minitest's +own tests you must have a default external Encoding of UTF-8. + +If your encoding is wrong, you'll see errors like: + + --- expected + +++ actual + @@ -1,2 +1,3 @@ + # encoding: UTF-8 + -"Expected /\\w+/ to not match \"blah blah blah\"." + +"Expected /\\w+/ to not match # encoding: UTF-8 + +\"blah blah blah\"." + +To check your current encoding, run: + + ruby -e 'puts Encoding.default_external' + +If your output is something other than UTF-8, you can set the RUBYOPTS +env variable to a value of '-Eutf-8'. Something like: + + RUBYOPT='-Eutf-8' ruby -e 'puts Encoding.default_external' + +Check your OS/shell documentation for the precise syntax (the above +will not work on a basic Windows CMD prompt, look for the SET command). +Once you've got it successfully outputing UTF-8, use the same setting +when running rake in Minitest. + +=== Minitest's own tests require GNU (or similar) diff. + +This is also a problem primarily affecting Windows developers. PowerShell +has a command called diff, but it is not suitable for use with Minitest. + +If you see failures like either of these, you are probably missing diff tool: + + 4) Failure: + TestMinitestUnitTestCase#test_assert_equal_different_long [D:/ruby/seattlerb/minitest/test/minitest/test_minitest_test.rb:936]: + Expected: "--- expected\n+++ actual\n@@ -1 +1 @@\n-\"hahahahahahahahahahahahahahahahahahahaha\"\n+\"blahblahblahblahblahblahblahblahblahblah\"\n" + Actual: "Expected: \"hahahahahahahahahahahahahahahahahahahaha\"\n Actual: \"blahblahblahblahblahblahblahblahblahblah\"" + + + 5) Failure: + TestMinitestUnitTestCase#test_assert_equal_different_collection_hash_hex_invisible [D:/ruby/seattlerb/minitest/test/minitest/test_minitest_test.rb:845]: + Expected: "No visible difference in the Hash#inspect output.\nYou should look at the implementation of #== on Hash or its members.\n + {1=>#}" + Actual: "Expected: {1=>#}\n Actual: {1=>#}" + + +If you use Cygwin or MSYS2 or similar there are packages that include a +GNU diff for Windows. If you don't, you can download GNU diffutils from +http://gnuwin32.sourceforge.net/packages/diffutils.htm +(make sure to add it to your PATH). + +You can make sure it's installed and path is configured properly with: + + diff.exe -v + +There are multiple lines of output, the first should be something like: + + diff (GNU diffutils) 2.8.1 + +If you are using PowerShell make sure you run diff.exe, not just diff, +which will invoke the PowerShell built in function. + +== Known Extensions: + +capybara_minitest_spec :: Bridge between Capybara RSpec matchers and + Minitest::Spec expectations (e.g. + page.must_have_content("Title")). +color_pound_spec_reporter :: Test names print Ruby Object types in color with + your Minitest Spec style tests. +minispec-metadata :: Metadata for describe/it blocks & CLI tag filter. + E.g. it "requires JS driver", js: true do & + ruby test.rb --tag js runs tests tagged :js. +minispec-rails :: Minimal support to use Spec style in Rails 5+. +mini-apivore :: for swagger based automated API testing. +minitest-around :: Around block for minitest. An alternative to + setup/teardown dance. +minitest-assert_errors :: Adds Minitest assertions to test for errors raised + or not raised by Minitest itself. +minitest-autotest :: autotest is a continuous testing facility meant to + be used during development. +minitest-bacon :: minitest-bacon extends minitest with bacon-like + functionality. +minitest-bang :: Adds support for RSpec-style let! to immediately + invoke let statements before each test. +minitest-bisect :: Helps you isolate and debug random test failures. +minitest-blink1_reporter :: Display test results with a Blink1. +minitest-capistrano :: Assertions and expectations for testing + Capistrano recipes. +minitest-capybara :: Capybara matchers support for minitest unit and + spec. +minitest-chef-handler :: Run Minitest suites as Chef report handlers +minitest-ci :: CI reporter plugin for Minitest. +minitest-context :: Defines contexts for code reuse in Minitest + specs that share common expectations. +minitest-debugger :: Wraps assert so failed assertions drop into + the ruby debugger. +minitest-display :: Patches Minitest to allow for an easily + configurable output. +minitest-documentation :: Minimal documentation format inspired by rspec's. +minitest-doc_reporter :: Detailed output inspired by rspec's documentation + format. +minitest-emoji :: Print out emoji for your test passes, fails, and + skips. +minitest-english :: Semantically symmetric aliases for assertions and + expectations. +minitest-excludes :: Clean API for excluding certain tests you + don't want to run under certain conditions. +minitest-fail-fast :: Reimplements RSpec's "fail fast" feature +minitest-filecontent :: Support unit tests with expectation results in files. + Differing results will be stored again in files. +minitest-filesystem :: Adds assertion and expectation to help testing + filesystem contents. +minitest-firemock :: Makes your Minitest mocks more resilient. +minitest-focus :: Focus on one test at a time. +minitest-gcstats :: A minitest plugin that adds a report of the top + tests by number of objects allocated. +minitest-global_expectations:: Support minitest expectation methods for all objects +minitest-great_expectations :: Generally useful additions to minitest's + assertions and expectations. +minitest-growl :: Test notifier for minitest via growl. +minitest-happy :: GLOBALLY ACTIVATE MINITEST PRIDE! RAWR! +minitest-have_tag :: Adds Minitest assertions to test for the existence of + HTML tags, including contents, within a provided string. +minitest-heat :: Reporting that builds a heat map of failure locations +minitest-hooks :: Around and before_all/after_all/around_all hooks +minitest-hyper :: Pretty, single-page HTML reports for your Minitest runs +minitest-implicit-subject :: Implicit declaration of the test subject. +minitest-instrument :: Instrument ActiveSupport::Notifications when + test method is executed. +minitest-instrument-db :: Store information about speed of test execution + provided by minitest-instrument in database. +minitest-junit :: JUnit-style XML reporter for minitest. +minitest-keyword :: Use Minitest assertions with keyword arguments. +minitest-libnotify :: Test notifier for minitest via libnotify. +minitest-line :: Run test at line number. +minitest-logger :: Define assert_log and enable minitest to test log messages. + Supports Logger and Log4r::Logger. +minitest-macruby :: Provides extensions to minitest for macruby UI + testing. +minitest-matchers :: Adds support for RSpec-style matchers to + minitest. +minitest-matchers_vaccine :: Adds assertions that adhere to the matcher spec, + but without any expectation infections. +minitest-metadata :: Annotate tests with metadata (key-value). +minitest-mock_expectations :: Provides method call assertions for minitest. +minitest-mongoid :: Mongoid assertion matchers for Minitest. +minitest-must_not :: Provides must_not as an alias for wont in + Minitest. +minitest-optional_retry :: Automatically retry failed test to help with flakiness. +minitest-osx :: Reporter for the Mac OS X notification center. +minitest-parallel_fork :: Fork-based parallelization +minitest-parallel-db :: Run tests in parallel with a single database. +minitest-power_assert :: PowerAssert for Minitest. +minitest-predicates :: Adds support for .predicate? methods. +minitest-profile :: List the 10 slowest tests in your suite. +minitest-rails :: Minitest integration for Rails 3.x. +minitest-rails-capybara :: Capybara integration for Minitest::Rails. +minitest-reporters :: Create customizable Minitest output formats. +minitest-rg :: Colored red/green output for Minitest. +minitest-rspec_mocks :: Use RSpec Mocks with Minitest. +minitest-server :: minitest-server provides a client/server setup + with your minitest process, allowing your test + run to send its results directly to a handler. +minitest-sequel :: Minitest assertions to speed-up development and + testing of Ruby Sequel database setups. +minitest-shared_description :: Support for shared specs and shared spec + subclasses +minitest-should_syntax :: RSpec-style x.should == y assertions for + Minitest. +minitest-shouldify :: Adding all manner of shoulds to Minitest (bad + idea) +minitest-snail :: Print a list of tests that take too long +minitest-spec-context :: Provides rspec-ish context method to + Minitest::Spec. +minitest-spec-expect :: Expect syntax for Minitest::Spec (e.g. + expect(sequences).to_include :celery_man). +minitest-spec-magic :: Minitest::Spec extensions for Rails and beyond. +minitest-spec-rails :: Drop in Minitest::Spec superclass for + ActiveSupport::TestCase. +minitest-sprint :: Runs (Get it? It's fast!) your tests and makes + it easier to rerun individual failures. +minitest-stately :: Find leaking state between tests +minitest-stub_any_instance :: Stub any instance of a method on the given class + for the duration of a block. +minitest-stub-const :: Stub constants for the duration of a block. +minitest-tags :: Add tags for minitest. +minitest-unordered :: Adds a new assertion to minitest for checking the + contents of a collection, ignoring element order. +minitest-vcr :: Automatic cassette managment with Minitest::Spec + and VCR. +minitest_log :: Adds structured logging, data explication, and verdicts. +minitest_owrapper :: Get tests results as a TestResult object. +minitest_should :: Shoulda style syntax for minitest test::unit. +minitest_tu_shim :: Bridges between test/unit and minitest. +mongoid-minitest :: Minitest matchers for Mongoid. +mutant-minitest :: Minitest integration for mutant. +pry-rescue :: A pry plugin w/ minitest support. See + pry-rescue/minitest.rb. +rematch :: Declutter your test files from large hardcoded data + and update them automatically when your code changes. +rspec2minitest :: Easily translate any RSpec matchers to Minitest + assertions and expectations. + +== Unknown Extensions: + +Authors... Please send me a pull request with a description of your minitest extension. + +* assay-minitest +* detroit-minitest +* em-minitest-spec +* flexmock-minitest +* guard-minitest +* guard-minitest-decisiv +* minitest-activemodel +* minitest-ar-assertions +* minitest-capybara-unit +* minitest-colorer +* minitest-deluxe +* minitest-extra-assertions +* minitest-rails-shoulda +* minitest-spec +* minitest-spec-should +* minitest-sugar +* spork-minitest + +== Minitest related goods + +* minitest/pride fabric: http://www.spoonflower.com/fabric/3928730-again-by-katie_allen + +== REQUIREMENTS: + +* Ruby 2.3+. No magic is involved. I hope. + +== INSTALL: + + sudo gem install minitest + +On 1.9, you already have it. To get newer candy you can still install +the gem, and then requiring "minitest/autorun" should automatically +pull it in. If not, you'll need to do it yourself: + + gem "minitest" # ensures you"re using the gem, and not the built-in MT + require "minitest/autorun" + + # ... usual testing stuffs ... + +DO NOTE: There is a serious problem with the way that ruby 1.9/2.0 +packages their own gems. They install a gem specification file, but +don't install the gem contents in the gem path. This messes up +Gem.find_files and many other things (gem which, gem contents, etc). + +Just install minitest as a gem for real and you'll be happier. + +== LICENSE: + +(The MIT License) + +Copyright (c) Ryan Davis, seattle.rb + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/Rakefile b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/Rakefile new file mode 100644 index 0000000..a09f9a6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/Rakefile @@ -0,0 +1,74 @@ +# -*- ruby -*- + +require "rubygems" +require "hoe" + +Hoe.plugin :seattlerb +Hoe.plugin :rdoc + +Hoe.spec "minitest" do + developer "Ryan Davis", "ryand-ruby@zenspider.com" + + license "MIT" + + require_ruby_version [">= 2.2", "< 4.0"] +end + +desc "Find missing expectations" +task :specs do + $:.unshift "lib" + require "minitest/test" + require "minitest/spec" + + pos_prefix, neg_prefix = "must", "wont" + skip_re = /^(must|wont)$|wont_(throw)|must_(block|not?_|nothing|send|raise$)/x + dont_flip_re = /(must|wont)_(include|respond_to)/ + + map = { + /(must_throw)s/ => '\1', + /(?!not)_same/ => "_be_same_as", + /_in_/ => "_be_within_", + /_operator/ => "_be", + /_includes/ => "_include", + /(must|wont)_(.*_of|nil|silent|empty)/ => '\1_be_\2', + /must_raises/ => "must_raise", + /(must|wont)_predicate/ => '\1_be', + /(must|wont)_path_exists/ => 'path_\1_exist', + } + + expectations = Minitest::Expectations.public_instance_methods.map(&:to_s) + assertions = Minitest::Assertions.public_instance_methods.map(&:to_s) + + assertions.sort.each do |assertion| + expectation = case assertion + when /^assert/ then + assertion.sub(/^assert/, pos_prefix.to_s) + when /^refute/ then + assertion.sub(/^refute/, neg_prefix.to_s) + end + + next unless expectation + next if expectation =~ skip_re + + regexp, replacement = map.find { |re, _| expectation =~ re } + expectation.sub! regexp, replacement if replacement + + next if expectations.include? expectation + + args = [assertion, expectation].map(&:to_sym).map(&:inspect) + args << :reverse if expectation =~ dont_flip_re + + puts + puts "##" + puts "# :method: #{expectation}" + puts "# See Minitest::Assertions##{assertion}" + puts + puts "infect_an_assertion #{args.join ", "}" + end +end + +task :bugs do + sh "for f in bug*.rb ; do echo $f; echo; #{Gem.ruby} -Ilib $f && rm $f ; done" +end + +# vim: syntax=Ruby diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/design_rationale.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/design_rationale.rb new file mode 100644 index 0000000..a3fcc37 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/design_rationale.rb @@ -0,0 +1,52 @@ +# Specs: # Equivalent Unit Tests: +############################################################################### +describe Thingy do # class TestThingy < Minitest::Test + before do # def setup + do_some_setup # super + end # do_some_setup + # end + it "should do the first thing" do # + 1.must_equal 1 # def test_first_thing + end # assert_equal 1, 1 + # end + describe SubThingy do # end + before do # + do_more_setup # class TestSubThingy < TestThingy + end # def setup + # super + it "should do the second thing" do # do_more_setup + 2.must_equal 2 # end + end # + end # def test_second_thing +end # assert_equal 2, 2 + # end + # end +############################################################################### +# runs 2 specs # runs 3 tests +############################################################################### +# The specs generate: + +class ThingySpec < Minitest::Spec + def setup + super + do_some_setup + end + + def test_should_do_the_first_thing + assert_equal 1, 1 + end +end + +class SubThingySpec < ThingySpec + def setup + super + do_more_setup + end + + # because only setup/teardown is inherited, not specs + remove_method :test_should_do_the_first_thing + + def test_should_do_the_second_thing + assert_equal 2, 2 + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/hoe/minitest.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/hoe/minitest.rb new file mode 100644 index 0000000..eadbf0b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/hoe/minitest.rb @@ -0,0 +1,28 @@ +# :stopdoc: + +class Hoe +end + +module Hoe::Minitest + def minitest? + self.name == "minitest" + end + + def initialize_minitest + unless minitest? then + dir = "../../minitest/dev/lib" + Hoe.add_include_dirs dir if File.directory? dir + end + + gem "minitest" + require "minitest" + version = Minitest::VERSION.split(/\./).first(2).join(".") + + dependency "minitest", "~> #{version}", :development unless + minitest? or ENV["MT_NO_ISOLATE"] + end + + def define_minitest_tasks + self.testlib = :minitest + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest.rb new file mode 100644 index 0000000..468b3ab --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest.rb @@ -0,0 +1,1069 @@ +require "optparse" +require "thread" +require "mutex_m" +require "minitest/parallel" +require "stringio" +require "etc" + +## +# :include: README.rdoc + +module Minitest + VERSION = "5.15.0" # :nodoc: + ENCS = "".respond_to? :encoding # :nodoc: + + @@installed_at_exit ||= false + @@after_run = [] + @extensions = [] + + mc = (class << self; self; end) + + ## + # Parallel test executor + + mc.send :attr_accessor, :parallel_executor + + warn "DEPRECATED: use MT_CPU instead of N for parallel test runs" if ENV["N"] + n_threads = (ENV["MT_CPU"] || ENV["N"] || Etc.nprocessors).to_i + self.parallel_executor = Parallel::Executor.new n_threads + + ## + # Filter object for backtraces. + + mc.send :attr_accessor, :backtrace_filter + + ## + # Reporter object to be used for all runs. + # + # NOTE: This accessor is only available during setup, not during runs. + + mc.send :attr_accessor, :reporter + + ## + # Names of known extension plugins. + + mc.send :attr_accessor, :extensions + + ## + # The signal to use for dumping information to STDERR. Defaults to "INFO". + + mc.send :attr_accessor, :info_signal + self.info_signal = "INFO" + + ## + # Registers Minitest to run at process exit + + def self.autorun + if Object.const_defined?(:Warning) && Warning.respond_to?(:[]=) + Warning[:deprecated] = true + end + + at_exit { + next if $! and not ($!.kind_of? SystemExit and $!.success?) + + exit_code = nil + + pid = Process.pid + at_exit { + next if Process.pid != pid + @@after_run.reverse_each(&:call) + exit exit_code || false + } + + exit_code = Minitest.run ARGV + } unless @@installed_at_exit + @@installed_at_exit = true + end + + ## + # A simple hook allowing you to run a block of code after everything + # is done running. Eg: + # + # Minitest.after_run { p $debugging_info } + + def self.after_run &block + @@after_run << block + end + + def self.init_plugins options # :nodoc: + self.extensions.each do |name| + msg = "plugin_#{name}_init" + send msg, options if self.respond_to? msg + end + end + + def self.load_plugins # :nodoc: + return unless self.extensions.empty? + + seen = {} + + require "rubygems" unless defined? Gem + + Gem.find_files("minitest/*_plugin.rb").each do |plugin_path| + name = File.basename plugin_path, "_plugin.rb" + + next if seen[name] + seen[name] = true + + require plugin_path + self.extensions << name + end + end + + ## + # This is the top-level run method. Everything starts from here. It + # tells each Runnable sub-class to run, and each of those are + # responsible for doing whatever they do. + # + # The overall structure of a run looks like this: + # + # Minitest.autorun + # Minitest.run(args) + # Minitest.__run(reporter, options) + # Runnable.runnables.each + # runnable.run(reporter, options) + # self.runnable_methods.each + # self.run_one_method(self, runnable_method, reporter) + # Minitest.run_one_method(klass, runnable_method) + # klass.new(runnable_method).run + + def self.run args = [] + self.load_plugins unless args.delete("--no-plugins") || ENV["MT_NO_PLUGINS"] + + options = process_args args + + reporter = CompositeReporter.new + reporter << SummaryReporter.new(options[:io], options) + reporter << ProgressReporter.new(options[:io], options) + + self.reporter = reporter # this makes it available to plugins + self.init_plugins options + self.reporter = nil # runnables shouldn't depend on the reporter, ever + + self.parallel_executor.start if parallel_executor.respond_to?(:start) + reporter.start + begin + __run reporter, options + rescue Interrupt + warn "Interrupted. Exiting..." + end + self.parallel_executor.shutdown + reporter.report + + reporter.passed? + end + + ## + # Internal run method. Responsible for telling all Runnable + # sub-classes to run. + + def self.__run reporter, options + suites = Runnable.runnables.reject { |s| s.runnable_methods.empty? }.shuffle + parallel, serial = suites.partition { |s| s.test_order == :parallel } + + # If we run the parallel tests before the serial tests, the parallel tests + # could run in parallel with the serial tests. This would be bad because + # the serial tests won't lock around Reporter#record. Run the serial tests + # first, so that after they complete, the parallel tests will lock when + # recording results. + serial.map { |suite| suite.run reporter, options } + + parallel.map { |suite| suite.run reporter, options } + end + + def self.process_args args = [] # :nodoc: + options = { + :io => $stdout, + } + orig_args = args.dup + + OptionParser.new do |opts| + opts.banner = "minitest options:" + opts.version = Minitest::VERSION + + opts.on "-h", "--help", "Display this help." do + puts opts + exit + end + + opts.on "--no-plugins", "Bypass minitest plugin auto-loading (or set $MT_NO_PLUGINS)." + + desc = "Sets random seed. Also via env. Eg: SEED=n rake" + opts.on "-s", "--seed SEED", Integer, desc do |m| + options[:seed] = m.to_i + end + + opts.on "-v", "--verbose", "Verbose. Show progress processing files." do + options[:verbose] = true + end + + opts.on "-n", "--name PATTERN", "Filter run on /regexp/ or string." do |a| + options[:filter] = a + end + + opts.on "-e", "--exclude PATTERN", "Exclude /regexp/ or string from run." do |a| + options[:exclude] = a + end + + opts.on "-S", "--skip CODES", String, "Skip reporting of certain types of results (eg E)." do |s| + options[:skip] = s.chars.to_a + end + + unless extensions.empty? + opts.separator "" + opts.separator "Known extensions: #{extensions.join(", ")}" + + extensions.each do |meth| + msg = "plugin_#{meth}_options" + send msg, opts, options if self.respond_to?(msg) + end + end + + begin + opts.parse! args + rescue OptionParser::InvalidOption => e + puts + puts e + puts + puts opts + exit 1 + end + + orig_args -= args + end + + unless options[:seed] then + srand + options[:seed] = (ENV["SEED"] || srand).to_i % 0xFFFF + orig_args << "--seed" << options[:seed].to_s + end + + srand options[:seed] + + options[:args] = orig_args.map { |s| + s =~ /[\s|&<>$()]/ ? s.inspect : s + }.join " " + + options + end + + def self.filter_backtrace bt # :nodoc: + result = backtrace_filter.filter bt + result = bt.dup if result.empty? + result + end + + ## + # Represents anything "runnable", like Test, Spec, Benchmark, or + # whatever you can dream up. + # + # Subclasses of this are automatically registered and available in + # Runnable.runnables. + + class Runnable + ## + # Number of assertions executed in this run. + + attr_accessor :assertions + + ## + # An assertion raised during the run, if any. + + attr_accessor :failures + + ## + # The time it took to run. + + attr_accessor :time + + def time_it # :nodoc: + t0 = Minitest.clock_time + + yield + ensure + self.time = Minitest.clock_time - t0 + end + + ## + # Name of the run. + + def name + @NAME + end + + ## + # Set the name of the run. + + def name= o + @NAME = o + end + + ## + # Returns all instance methods matching the pattern +re+. + + def self.methods_matching re + public_instance_methods(true).grep(re).map(&:to_s) + end + + def self.reset # :nodoc: + @@runnables = [] + end + + reset + + ## + # Responsible for running all runnable methods in a given class, + # each in its own instance. Each instance is passed to the + # reporter to record. + + def self.run reporter, options = {} + filter = options[:filter] || "/./" + filter = Regexp.new $1 if filter.is_a?(String) && filter =~ %r%/(.*)/% + + filtered_methods = self.runnable_methods.find_all { |m| + filter === m || filter === "#{self}##{m}" + } + + exclude = options[:exclude] + exclude = Regexp.new $1 if exclude =~ %r%/(.*)/% + + filtered_methods.delete_if { |m| + exclude === m || exclude === "#{self}##{m}" + } + + return if filtered_methods.empty? + + with_info_handler reporter do + filtered_methods.each do |method_name| + run_one_method self, method_name, reporter + end + end + end + + ## + # Runs a single method and has the reporter record the result. + # This was considered internal API but is factored out of run so + # that subclasses can specialize the running of an individual + # test. See Minitest::ParallelTest::ClassMethods for an example. + + def self.run_one_method klass, method_name, reporter + reporter.prerecord klass, method_name + reporter.record Minitest.run_one_method(klass, method_name) + end + + def self.with_info_handler reporter, &block # :nodoc: + handler = lambda do + unless reporter.passed? then + warn "Current results:" + warn "" + warn reporter.reporters.first + warn "" + end + end + + on_signal ::Minitest.info_signal, handler, &block + end + + SIGNALS = Signal.list # :nodoc: + + def self.on_signal name, action # :nodoc: + supported = SIGNALS[name] + + old_trap = trap name do + old_trap.call if old_trap.respond_to? :call + action.call + end if supported + + yield + ensure + trap name, old_trap if supported + end + + ## + # Each subclass of Runnable is responsible for overriding this + # method to return all runnable methods. See #methods_matching. + + def self.runnable_methods + raise NotImplementedError, "subclass responsibility" + end + + ## + # Returns all subclasses of Runnable. + + def self.runnables + @@runnables + end + + @@marshal_dump_warned = false + + def marshal_dump # :nodoc: + unless @@marshal_dump_warned then + warn ["Minitest::Runnable#marshal_dump is deprecated.", + "You might be violating internals. From", caller.first].join " " + @@marshal_dump_warned = true + end + + [self.name, self.failures, self.assertions, self.time] + end + + def marshal_load ary # :nodoc: + self.name, self.failures, self.assertions, self.time = ary + end + + def failure # :nodoc: + self.failures.first + end + + def initialize name # :nodoc: + self.name = name + self.failures = [] + self.assertions = 0 + end + + ## + # Runs a single method. Needs to return self. + + def run + raise NotImplementedError, "subclass responsibility" + end + + ## + # Did this run pass? + # + # Note: skipped runs are not considered passing, but they don't + # cause the process to exit non-zero. + + def passed? + raise NotImplementedError, "subclass responsibility" + end + + ## + # Returns a single character string to print based on the result + # of the run. One of ".", "F", + # "E" or "S". + + def result_code + raise NotImplementedError, "subclass responsibility" + end + + ## + # Was this run skipped? See #passed? for more information. + + def skipped? + raise NotImplementedError, "subclass responsibility" + end + end + + ## + # Shared code for anything that can get passed to a Reporter. See + # Minitest::Test & Minitest::Result. + + module Reportable + ## + # Did this run pass? + # + # Note: skipped runs are not considered passing, but they don't + # cause the process to exit non-zero. + + def passed? + not self.failure + end + + ## + # The location identifier of this test. Depends on a method + # existing called class_name. + + def location + loc = " [#{self.failure.location}]" unless passed? or error? + "#{self.class_name}##{self.name}#{loc}" + end + + def class_name # :nodoc: + raise NotImplementedError, "subclass responsibility" + end + + ## + # Returns ".", "F", or "E" based on the result of the run. + + def result_code + self.failure and self.failure.result_code or "." + end + + ## + # Was this run skipped? + + def skipped? + self.failure and Skip === self.failure + end + + ## + # Did this run error? + + def error? + self.failures.any? { |f| UnexpectedError === f } + end + end + + ## + # This represents a test result in a clean way that can be + # marshalled over a wire. Tests can do anything they want to the + # test instance and can create conditions that cause Marshal.dump to + # blow up. By using Result.from(a_test) you can be reasonably sure + # that the test result can be marshalled. + + class Result < Runnable + include Minitest::Reportable + + undef_method :marshal_dump + undef_method :marshal_load + + ## + # The class name of the test result. + + attr_accessor :klass + + ## + # The location of the test method. + + attr_accessor :source_location + + ## + # Create a new test result from a Runnable instance. + + def self.from runnable + o = runnable + + r = self.new o.name + r.klass = o.class.name + r.assertions = o.assertions + r.failures = o.failures.dup + r.time = o.time + + r.source_location = o.method(o.name).source_location rescue ["unknown", -1] + + r + end + + def class_name # :nodoc: + self.klass # for Minitest::Reportable + end + + def to_s # :nodoc: + return location if passed? and not skipped? + + failures.map { |failure| + "#{failure.result_label}:\n#{self.location}:\n#{failure.message}\n" + }.join "\n" + end + end + + ## + # Defines the API for Reporters. Subclass this and override whatever + # you want. Go nuts. + + class AbstractReporter + include Mutex_m + + ## + # Starts reporting on the run. + + def start + end + + ## + # About to start running a test. This allows a reporter to show + # that it is starting or that we are in the middle of a test run. + + def prerecord klass, name + end + + ## + # Output and record the result of the test. Call + # {result#result_code}[rdoc-ref:Runnable#result_code] to get the + # result character string. Stores the result of the run if the run + # did not pass. + + def record result + end + + ## + # Outputs the summary of the run. + + def report + end + + ## + # Did this run pass? + + def passed? + true + end + end + + class Reporter < AbstractReporter # :nodoc: + ## + # The IO used to report. + + attr_accessor :io + + ## + # Command-line options for this run. + + attr_accessor :options + + def initialize io = $stdout, options = {} # :nodoc: + super() + self.io = io + self.options = options + end + end + + ## + # A very simple reporter that prints the "dots" during the run. + # + # This is added to the top-level CompositeReporter at the start of + # the run. If you want to change the output of minitest via a + # plugin, pull this out of the composite and replace it with your + # own. + + class ProgressReporter < Reporter + def prerecord klass, name #:nodoc: + if options[:verbose] then + io.print "%s#%s = " % [klass.name, name] + io.flush + end + end + + def record result # :nodoc: + io.print "%.2f s = " % [result.time] if options[:verbose] + io.print result.result_code + io.puts if options[:verbose] + end + end + + ## + # A reporter that gathers statistics about a test run. Does not do + # any IO because meant to be used as a parent class for a reporter + # that does. + # + # If you want to create an entirely different type of output (eg, + # CI, HTML, etc), this is the place to start. + # + # Example: + # + # class JenkinsCIReporter < StatisticsReporter + # def report + # super # Needed to calculate some statistics + # + # print " 30 characters. + # 3. or: Strings are equal to each other (but maybe different encodings?). + # 4. and: we found a diff executable. + + def things_to_diff exp, act + expect = mu_pp_for_diff exp + butwas = mu_pp_for_diff act + + e1, e2 = expect.include?("\n"), expect.include?("\\n") + b1, b2 = butwas.include?("\n"), butwas.include?("\\n") + + need_to_diff = + (e1 ^ e2 || + b1 ^ b2 || + expect.size > 30 || + butwas.size > 30 || + expect == butwas) && + Minitest::Assertions.diff + + need_to_diff && [expect, butwas] + end + + ## + # This returns a human-readable version of +obj+. By default + # #inspect is called. You can override this to use #pretty_inspect + # if you want. + # + # See Minitest::Test.make_my_diffs_pretty! + + def mu_pp obj + s = obj.inspect + + if defined? Encoding then + s = s.encode Encoding.default_external + + if String === obj && (obj.encoding != Encoding.default_external || + !obj.valid_encoding?) then + enc = "# encoding: #{obj.encoding}" + val = "# valid: #{obj.valid_encoding?}" + s = "#{enc}\n#{val}\n#{s}" + end + end + + s + end + + ## + # This returns a diff-able more human-readable version of +obj+. + # This differs from the regular mu_pp because it expands escaped + # newlines and makes hex-values (like object_ids) generic. This + # uses mu_pp to do the first pass and then cleans it up. + + def mu_pp_for_diff obj + str = mu_pp obj + + # both '\n' & '\\n' (_after_ mu_pp (aka inspect)) + single = !!str.match(/(?exp == act
printing the difference between + # the two, if possible. + # + # If there is no visible difference but the assertion fails, you + # should suspect that your #== is buggy, or your inspect output is + # missing crucial details. For nicer structural diffing, set + # Minitest::Test.make_my_diffs_pretty! + # + # For floats use assert_in_delta. + # + # See also: Minitest::Assertions.diff + + def assert_equal exp, act, msg = nil + msg = message(msg, E) { diff exp, act } + result = assert exp == act, msg + + if nil == exp then + if Minitest::VERSION =~ /^6/ then + refute_nil exp, "Use assert_nil if expecting nil." + else + where = Minitest.filter_backtrace(caller).first + where = where.split(/:in /, 2).first # clean up noise + + warn "DEPRECATED: Use assert_nil if expecting nil from #{where}. This will fail in Minitest 6." + end + end + + result + end + + ## + # For comparing Floats. Fails unless +exp+ and +act+ are within +delta+ + # of each other. + # + # assert_in_delta Math::PI, (22.0 / 7.0), 0.01 + + def assert_in_delta exp, act, delta = 0.001, msg = nil + n = (exp - act).abs + msg = message(msg) { + "Expected |#{exp} - #{act}| (#{n}) to be <= #{delta}" + } + assert delta >= n, msg + end + + ## + # For comparing Floats. Fails unless +exp+ and +act+ have a relative + # error less than +epsilon+. + + def assert_in_epsilon exp, act, epsilon = 0.001, msg = nil + assert_in_delta exp, act, [exp.abs, act.abs].min * epsilon, msg + end + + ## + # Fails unless +collection+ includes +obj+. + + def assert_includes collection, obj, msg = nil + msg = message(msg) { + "Expected #{mu_pp(collection)} to include #{mu_pp(obj)}" + } + assert_respond_to collection, :include? + assert collection.include?(obj), msg + end + + ## + # Fails unless +obj+ is an instance of +cls+. + + def assert_instance_of cls, obj, msg = nil + msg = message(msg) { + "Expected #{mu_pp(obj)} to be an instance of #{cls}, not #{obj.class}" + } + + assert obj.instance_of?(cls), msg + end + + ## + # Fails unless +obj+ is a kind of +cls+. + + def assert_kind_of cls, obj, msg = nil + msg = message(msg) { + "Expected #{mu_pp(obj)} to be a kind of #{cls}, not #{obj.class}" } + + assert obj.kind_of?(cls), msg + end + + ## + # Fails unless +matcher+ =~ +obj+. + + def assert_match matcher, obj, msg = nil + msg = message(msg) { "Expected #{mu_pp matcher} to match #{mu_pp obj}" } + assert_respond_to matcher, :"=~" + matcher = Regexp.new Regexp.escape matcher if String === matcher + assert matcher =~ obj, msg + end + + ## + # Fails unless +obj+ is nil + + def assert_nil obj, msg = nil + msg = message(msg) { "Expected #{mu_pp(obj)} to be nil" } + assert obj.nil?, msg + end + + ## + # For testing with binary operators. Eg: + # + # assert_operator 5, :<=, 4 + + def assert_operator o1, op, o2 = UNDEFINED, msg = nil + return assert_predicate o1, op, msg if UNDEFINED == o2 + msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op} #{mu_pp(o2)}" } + assert o1.__send__(op, o2), msg + end + + ## + # Fails if stdout or stderr do not output the expected results. + # Pass in nil if you don't care about that streams output. Pass in + # "" if you require it to be silent. Pass in a regexp if you want + # to pattern match. + # + # assert_output(/hey/) { method_with_output } + # + # NOTE: this uses #capture_io, not #capture_subprocess_io. + # + # See also: #assert_silent + + def assert_output stdout = nil, stderr = nil + flunk "assert_output requires a block to capture output." unless + block_given? + + out, err = capture_io do + yield + end + + err_msg = Regexp === stderr ? :assert_match : :assert_equal if stderr + out_msg = Regexp === stdout ? :assert_match : :assert_equal if stdout + + y = send err_msg, stderr, err, "In stderr" if err_msg + x = send out_msg, stdout, out, "In stdout" if out_msg + + (!stdout || x) && (!stderr || y) + rescue Assertion + raise + rescue => e + raise UnexpectedError, e + end + + ## + # Fails unless +path+ exists. + + def assert_path_exists path, msg = nil + msg = message(msg) { "Expected path '#{path}' to exist" } + assert File.exist?(path), msg + end + + ## + # For testing with predicates. Eg: + # + # assert_predicate str, :empty? + # + # This is really meant for specs and is front-ended by assert_operator: + # + # str.must_be :empty? + + def assert_predicate o1, op, msg = nil + msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op}" } + assert o1.__send__(op), msg + end + + ## + # Fails unless the block raises one of +exp+. Returns the + # exception matched so you can check the message, attributes, etc. + # + # +exp+ takes an optional message on the end to help explain + # failures and defaults to StandardError if no exception class is + # passed. Eg: + # + # assert_raises(CustomError) { method_with_custom_error } + # + # With custom error message: + # + # assert_raises(CustomError, 'This should have raised CustomError') { method_with_custom_error } + # + # Using the returned object: + # + # error = assert_raises(CustomError) do + # raise CustomError, 'This is really bad' + # end + # + # assert_equal 'This is really bad', error.message + + def assert_raises *exp + flunk "assert_raises requires a block to capture errors." unless + block_given? + + msg = "#{exp.pop}.\n" if String === exp.last + exp << StandardError if exp.empty? + + begin + yield + rescue *exp => e + pass # count assertion + return e + rescue Minitest::Assertion # incl Skip & UnexpectedError + # don't count assertion + raise + rescue SignalException, SystemExit + raise + rescue Exception => e + flunk proc { + exception_details(e, "#{msg}#{mu_pp(exp)} exception expected, not") + } + end + + exp = exp.first if exp.size == 1 + + flunk "#{msg}#{mu_pp(exp)} expected but nothing was raised." + end + + ## + # Fails unless +obj+ responds to +meth+. + + def assert_respond_to obj, meth, msg = nil + msg = message(msg) { + "Expected #{mu_pp(obj)} (#{obj.class}) to respond to ##{meth}" + } + assert obj.respond_to?(meth), msg + end + + ## + # Fails unless +exp+ and +act+ are #equal? + + def assert_same exp, act, msg = nil + msg = message(msg) { + data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id] + "Expected %s (oid=%d) to be the same as %s (oid=%d)" % data + } + assert exp.equal?(act), msg + end + + ## + # +send_ary+ is a receiver, message and arguments. + # + # Fails unless the call returns a true value + + def assert_send send_ary, m = nil + where = Minitest.filter_backtrace(caller).first + where = where.split(/:in /, 2).first # clean up noise + warn "DEPRECATED: assert_send. From #{where}" + + recv, msg, *args = send_ary + m = message(m) { + "Expected #{mu_pp(recv)}.#{msg}(*#{mu_pp(args)}) to return true" } + assert recv.__send__(msg, *args), m + end + + ## + # Fails if the block outputs anything to stderr or stdout. + # + # See also: #assert_output + + def assert_silent + assert_output "", "" do + yield + end + end + + ## + # Fails unless the block throws +sym+ + + def assert_throws sym, msg = nil + default = "Expected #{mu_pp(sym)} to have been thrown" + caught = true + value = catch(sym) do + begin + yield + rescue ThreadError => e # wtf?!? 1.8 + threads == suck + default += ", not \:#{e.message[/uncaught throw \`(\w+?)\'/, 1]}" + rescue ArgumentError => e # 1.9 exception + raise e unless e.message.include?("uncaught throw") + default += ", not #{e.message.split(/ /).last}" + rescue NameError => e # 1.8 exception + raise e unless e.name == sym + default += ", not #{e.name.inspect}" + end + caught = false + end + + assert caught, message(msg) { default } + value + rescue Assertion + raise + rescue => e + raise UnexpectedError, e + end + + ## + # Captures $stdout and $stderr into strings: + # + # out, err = capture_io do + # puts "Some info" + # warn "You did a bad thing" + # end + # + # assert_match %r%info%, out + # assert_match %r%bad%, err + # + # NOTE: For efficiency, this method uses StringIO and does not + # capture IO for subprocesses. Use #capture_subprocess_io for + # that. + + def capture_io + _synchronize do + begin + captured_stdout, captured_stderr = StringIO.new, StringIO.new + + orig_stdout, orig_stderr = $stdout, $stderr + $stdout, $stderr = captured_stdout, captured_stderr + + yield + + return captured_stdout.string, captured_stderr.string + ensure + $stdout = orig_stdout + $stderr = orig_stderr + end + end + end + + ## + # Captures $stdout and $stderr into strings, using Tempfile to + # ensure that subprocess IO is captured as well. + # + # out, err = capture_subprocess_io do + # system "echo Some info" + # system "echo You did a bad thing 1>&2" + # end + # + # assert_match %r%info%, out + # assert_match %r%bad%, err + # + # NOTE: This method is approximately 10x slower than #capture_io so + # only use it when you need to test the output of a subprocess. + + def capture_subprocess_io + _synchronize do + begin + require "tempfile" + + captured_stdout, captured_stderr = Tempfile.new("out"), Tempfile.new("err") + + orig_stdout, orig_stderr = $stdout.dup, $stderr.dup + $stdout.reopen captured_stdout + $stderr.reopen captured_stderr + + yield + + $stdout.rewind + $stderr.rewind + + return captured_stdout.read, captured_stderr.read + ensure + $stdout.reopen orig_stdout + $stderr.reopen orig_stderr + + orig_stdout.close + orig_stderr.close + captured_stdout.close! + captured_stderr.close! + end + end + end + + ## + # Returns details for exception +e+ + + def exception_details e, msg + [ + "#{msg}", + "Class: <#{e.class}>", + "Message: <#{e.message.inspect}>", + "---Backtrace---", + "#{Minitest.filter_backtrace(e.backtrace).join("\n")}", + "---------------", + ].join "\n" + end + + ## + # Fails after a given date (in the local time zone). This allows + # you to put time-bombs in your tests if you need to keep + # something around until a later date lest you forget about it. + + def fail_after y,m,d,msg + flunk msg if Time.now > Time.local(y, m, d) + end + + ## + # Fails with +msg+. + + def flunk msg = nil + msg ||= "Epic Fail!" + assert false, msg + end + + ## + # Returns a proc that will output +msg+ along with the default message. + + def message msg = nil, ending = nil, &default + proc { + msg = msg.call.chomp(".") if Proc === msg + custom_message = "#{msg}.\n" unless msg.nil? or msg.to_s.empty? + "#{custom_message}#{default.call}#{ending || "."}" + } + end + + ## + # used for counting assertions + + def pass _msg = nil + assert true + end + + ## + # Fails if +test+ is truthy. + + def refute test, msg = nil + msg ||= message { "Expected #{mu_pp(test)} to not be truthy" } + assert !test, msg + end + + ## + # Fails if +obj+ is empty. + + def refute_empty obj, msg = nil + msg = message(msg) { "Expected #{mu_pp(obj)} to not be empty" } + assert_respond_to obj, :empty? + refute obj.empty?, msg + end + + ## + # Fails if exp == act. + # + # For floats use refute_in_delta. + + def refute_equal exp, act, msg = nil + msg = message(msg) { + "Expected #{mu_pp(act)} to not be equal to #{mu_pp(exp)}" + } + refute exp == act, msg + end + + ## + # For comparing Floats. Fails if +exp+ is within +delta+ of +act+. + # + # refute_in_delta Math::PI, (22.0 / 7.0) + + def refute_in_delta exp, act, delta = 0.001, msg = nil + n = (exp - act).abs + msg = message(msg) { + "Expected |#{exp} - #{act}| (#{n}) to not be <= #{delta}" + } + refute delta >= n, msg + end + + ## + # For comparing Floats. Fails if +exp+ and +act+ have a relative error + # less than +epsilon+. + + def refute_in_epsilon a, b, epsilon = 0.001, msg = nil + refute_in_delta a, b, a * epsilon, msg + end + + ## + # Fails if +collection+ includes +obj+. + + def refute_includes collection, obj, msg = nil + msg = message(msg) { + "Expected #{mu_pp(collection)} to not include #{mu_pp(obj)}" + } + assert_respond_to collection, :include? + refute collection.include?(obj), msg + end + + ## + # Fails if +obj+ is an instance of +cls+. + + def refute_instance_of cls, obj, msg = nil + msg = message(msg) { + "Expected #{mu_pp(obj)} to not be an instance of #{cls}" + } + refute obj.instance_of?(cls), msg + end + + ## + # Fails if +obj+ is a kind of +cls+. + + def refute_kind_of cls, obj, msg = nil + msg = message(msg) { "Expected #{mu_pp(obj)} to not be a kind of #{cls}" } + refute obj.kind_of?(cls), msg + end + + ## + # Fails if +matcher+ =~ +obj+. + + def refute_match matcher, obj, msg = nil + msg = message(msg) { "Expected #{mu_pp matcher} to not match #{mu_pp obj}" } + assert_respond_to matcher, :"=~" + matcher = Regexp.new Regexp.escape matcher if String === matcher + refute matcher =~ obj, msg + end + + ## + # Fails if +obj+ is nil. + + def refute_nil obj, msg = nil + msg = message(msg) { "Expected #{mu_pp(obj)} to not be nil" } + refute obj.nil?, msg + end + + ## + # Fails if +o1+ is not +op+ +o2+. Eg: + # + # refute_operator 1, :>, 2 #=> pass + # refute_operator 1, :<, 2 #=> fail + + def refute_operator o1, op, o2 = UNDEFINED, msg = nil + return refute_predicate o1, op, msg if UNDEFINED == o2 + msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op} #{mu_pp(o2)}" } + refute o1.__send__(op, o2), msg + end + + ## + # Fails if +path+ exists. + + def refute_path_exists path, msg = nil + msg = message(msg) { "Expected path '#{path}' to not exist" } + refute File.exist?(path), msg + end + + ## + # For testing with predicates. + # + # refute_predicate str, :empty? + # + # This is really meant for specs and is front-ended by refute_operator: + # + # str.wont_be :empty? + + def refute_predicate o1, op, msg = nil + msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op}" } + refute o1.__send__(op), msg + end + + ## + # Fails if +obj+ responds to the message +meth+. + + def refute_respond_to obj, meth, msg = nil + msg = message(msg) { "Expected #{mu_pp(obj)} to not respond to #{meth}" } + + refute obj.respond_to?(meth), msg + end + + ## + # Fails if +exp+ is the same (by object identity) as +act+. + + def refute_same exp, act, msg = nil + msg = message(msg) { + data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id] + "Expected %s (oid=%d) to not be the same as %s (oid=%d)" % data + } + refute exp.equal?(act), msg + end + + ## + # Skips the current run. If run in verbose-mode, the skipped run + # gets listed at the end of the run but doesn't cause a failure + # exit code. + + def skip msg = nil, bt = caller + msg ||= "Skipped, no message given" + @skip = true + raise Minitest::Skip, msg, bt + end + + ## + # Skips the current run until a given date (in the local time + # zone). This allows you to put some fixes on hold until a later + # date, but still holds you accountable and prevents you from + # forgetting it. + + def skip_until y,m,d,msg + skip msg if Time.now < Time.local(y, m, d) + where = caller.first.rpartition(':in').reject(&:empty?).first + warn "Stale skip_until %p at %s" % [msg, where] + end + + ## + # Was this testcase skipped? Meant for #teardown. + + def skipped? + defined?(@skip) and @skip + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/autorun.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/autorun.rb new file mode 100644 index 0000000..9409b04 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/autorun.rb @@ -0,0 +1,13 @@ +begin + require "rubygems" + gem "minitest" +rescue Gem::LoadError + # do nothing +end + +require "minitest" +require "minitest/spec" +require "minitest/mock" +require "minitest/hell" if ENV["MT_HELL"] + +Minitest.autorun diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/benchmark.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/benchmark.rb new file mode 100644 index 0000000..f2b2465 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/benchmark.rb @@ -0,0 +1,455 @@ +require "minitest/test" +require "minitest/spec" + +module Minitest + ## + # Subclass Benchmark to create your own benchmark runs. Methods + # starting with "bench_" get executed on a per-class. + # + # See Minitest::Assertions + + class Benchmark < Test + def self.io # :nodoc: + @io + end + + def io # :nodoc: + self.class.io + end + + def self.run reporter, options = {} # :nodoc: + @io = reporter.io + super + end + + def self.runnable_methods # :nodoc: + methods_matching(/^bench_/) + end + + ## + # Returns a set of ranges stepped exponentially from +min+ to + # +max+ by powers of +base+. Eg: + # + # bench_exp(2, 16, 2) # => [2, 4, 8, 16] + + def self.bench_exp min, max, base = 10 + min = (Math.log10(min) / Math.log10(base)).to_i + max = (Math.log10(max) / Math.log10(base)).to_i + + (min..max).map { |m| base ** m }.to_a + end + + ## + # Returns a set of ranges stepped linearly from +min+ to +max+ by + # +step+. Eg: + # + # bench_linear(20, 40, 10) # => [20, 30, 40] + + def self.bench_linear min, max, step = 10 + (min..max).step(step).to_a + rescue LocalJumpError # 1.8.6 + r = []; (min..max).step(step) { |n| r << n }; r + end + + ## + # Specifies the ranges used for benchmarking for that class. + # Defaults to exponential growth from 1 to 10k by powers of 10. + # Override if you need different ranges for your benchmarks. + # + # See also: ::bench_exp and ::bench_linear. + + def self.bench_range + bench_exp 1, 10_000 + end + + ## + # Runs the given +work+, gathering the times of each run. Range + # and times are then passed to a given +validation+ proc. Outputs + # the benchmark name and times in tab-separated format, making it + # easy to paste into a spreadsheet for graphing or further + # analysis. + # + # Ranges are specified by ::bench_range. + # + # Eg: + # + # def bench_algorithm + # validation = proc { |x, y| ... } + # assert_performance validation do |n| + # @obj.algorithm(n) + # end + # end + + def assert_performance validation, &work + range = self.class.bench_range + + io.print "#{self.name}" + + times = [] + + range.each do |x| + GC.start + t0 = Minitest.clock_time + instance_exec(x, &work) + t = Minitest.clock_time - t0 + + io.print "\t%9.6f" % t + times << t + end + io.puts + + validation[range, times] + end + + ## + # Runs the given +work+ and asserts that the times gathered fit to + # match a constant rate (eg, linear slope == 0) within a given + # +threshold+. Note: because we're testing for a slope of 0, R^2 + # is not a good determining factor for the fit, so the threshold + # is applied against the slope itself. As such, you probably want + # to tighten it from the default. + # + # See https://www.graphpad.com/guides/prism/8/curve-fitting/reg_intepretingnonlinr2.htm + # for more details. + # + # Fit is calculated by #fit_linear. + # + # Ranges are specified by ::bench_range. + # + # Eg: + # + # def bench_algorithm + # assert_performance_constant 0.9999 do |n| + # @obj.algorithm(n) + # end + # end + + def assert_performance_constant threshold = 0.99, &work + validation = proc do |range, times| + a, b, rr = fit_linear range, times + assert_in_delta 0, b, 1 - threshold + [a, b, rr] + end + + assert_performance validation, &work + end + + ## + # Runs the given +work+ and asserts that the times gathered fit to + # match a exponential curve within a given error +threshold+. + # + # Fit is calculated by #fit_exponential. + # + # Ranges are specified by ::bench_range. + # + # Eg: + # + # def bench_algorithm + # assert_performance_exponential 0.9999 do |n| + # @obj.algorithm(n) + # end + # end + + def assert_performance_exponential threshold = 0.99, &work + assert_performance validation_for_fit(:exponential, threshold), &work + end + + ## + # Runs the given +work+ and asserts that the times gathered fit to + # match a logarithmic curve within a given error +threshold+. + # + # Fit is calculated by #fit_logarithmic. + # + # Ranges are specified by ::bench_range. + # + # Eg: + # + # def bench_algorithm + # assert_performance_logarithmic 0.9999 do |n| + # @obj.algorithm(n) + # end + # end + + def assert_performance_logarithmic threshold = 0.99, &work + assert_performance validation_for_fit(:logarithmic, threshold), &work + end + + ## + # Runs the given +work+ and asserts that the times gathered fit to + # match a straight line within a given error +threshold+. + # + # Fit is calculated by #fit_linear. + # + # Ranges are specified by ::bench_range. + # + # Eg: + # + # def bench_algorithm + # assert_performance_linear 0.9999 do |n| + # @obj.algorithm(n) + # end + # end + + def assert_performance_linear threshold = 0.99, &work + assert_performance validation_for_fit(:linear, threshold), &work + end + + ## + # Runs the given +work+ and asserts that the times gathered curve + # fit to match a power curve within a given error +threshold+. + # + # Fit is calculated by #fit_power. + # + # Ranges are specified by ::bench_range. + # + # Eg: + # + # def bench_algorithm + # assert_performance_power 0.9999 do |x| + # @obj.algorithm + # end + # end + + def assert_performance_power threshold = 0.99, &work + assert_performance validation_for_fit(:power, threshold), &work + end + + ## + # Takes an array of x/y pairs and calculates the general R^2 value. + # + # See: http://en.wikipedia.org/wiki/Coefficient_of_determination + + def fit_error xys + y_bar = sigma(xys) { |_, y| y } / xys.size.to_f + ss_tot = sigma(xys) { |_, y| (y - y_bar) ** 2 } + ss_err = sigma(xys) { |x, y| (yield(x) - y) ** 2 } + + 1 - (ss_err / ss_tot) + end + + ## + # To fit a functional form: y = ae^(bx). + # + # Takes x and y values and returns [a, b, r^2]. + # + # See: http://mathworld.wolfram.com/LeastSquaresFittingExponential.html + + def fit_exponential xs, ys + n = xs.size + xys = xs.zip(ys) + sxlny = sigma(xys) { |x, y| x * Math.log(y) } + slny = sigma(xys) { |_, y| Math.log(y) } + sx2 = sigma(xys) { |x, _| x * x } + sx = sigma xs + + c = n * sx2 - sx ** 2 + a = (slny * sx2 - sx * sxlny) / c + b = ( n * sxlny - sx * slny ) / c + + return Math.exp(a), b, fit_error(xys) { |x| Math.exp(a + b * x) } + end + + ## + # To fit a functional form: y = a + b*ln(x). + # + # Takes x and y values and returns [a, b, r^2]. + # + # See: http://mathworld.wolfram.com/LeastSquaresFittingLogarithmic.html + + def fit_logarithmic xs, ys + n = xs.size + xys = xs.zip(ys) + slnx2 = sigma(xys) { |x, _| Math.log(x) ** 2 } + slnx = sigma(xys) { |x, _| Math.log(x) } + sylnx = sigma(xys) { |x, y| y * Math.log(x) } + sy = sigma(xys) { |_, y| y } + + c = n * slnx2 - slnx ** 2 + b = ( n * sylnx - sy * slnx ) / c + a = (sy - b * slnx) / n + + return a, b, fit_error(xys) { |x| a + b * Math.log(x) } + end + + ## + # Fits the functional form: a + bx. + # + # Takes x and y values and returns [a, b, r^2]. + # + # See: http://mathworld.wolfram.com/LeastSquaresFitting.html + + def fit_linear xs, ys + n = xs.size + xys = xs.zip(ys) + sx = sigma xs + sy = sigma ys + sx2 = sigma(xs) { |x| x ** 2 } + sxy = sigma(xys) { |x, y| x * y } + + c = n * sx2 - sx**2 + a = (sy * sx2 - sx * sxy) / c + b = ( n * sxy - sx * sy ) / c + + return a, b, fit_error(xys) { |x| a + b * x } + end + + ## + # To fit a functional form: y = ax^b. + # + # Takes x and y values and returns [a, b, r^2]. + # + # See: http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html + + def fit_power xs, ys + n = xs.size + xys = xs.zip(ys) + slnxlny = sigma(xys) { |x, y| Math.log(x) * Math.log(y) } + slnx = sigma(xs) { |x | Math.log(x) } + slny = sigma(ys) { | y| Math.log(y) } + slnx2 = sigma(xs) { |x | Math.log(x) ** 2 } + + b = (n * slnxlny - slnx * slny) / (n * slnx2 - slnx ** 2) + a = (slny - b * slnx) / n + + return Math.exp(a), b, fit_error(xys) { |x| (Math.exp(a) * (x ** b)) } + end + + ## + # Enumerates over +enum+ mapping +block+ if given, returning the + # sum of the result. Eg: + # + # sigma([1, 2, 3]) # => 1 + 2 + 3 => 6 + # sigma([1, 2, 3]) { |n| n ** 2 } # => 1 + 4 + 9 => 14 + + def sigma enum, &block + enum = enum.map(&block) if block + enum.inject { |sum, n| sum + n } + end + + ## + # Returns a proc that calls the specified fit method and asserts + # that the error is within a tolerable threshold. + + def validation_for_fit msg, threshold + proc do |range, times| + a, b, rr = send "fit_#{msg}", range, times + assert_operator rr, :>=, threshold + [a, b, rr] + end + end + end +end + +module Minitest + ## + # The spec version of Minitest::Benchmark. + + class BenchSpec < Benchmark + extend Minitest::Spec::DSL + + ## + # This is used to define a new benchmark method. You usually don't + # use this directly and is intended for those needing to write new + # performance curve fits (eg: you need a specific polynomial fit). + # + # See ::bench_performance_linear for an example of how to use this. + + def self.bench name, &block + define_method "bench_#{name.gsub(/\W+/, "_")}", &block + end + + ## + # Specifies the ranges used for benchmarking for that class. + # + # bench_range do + # bench_exp(2, 16, 2) + # end + # + # See Minitest::Benchmark#bench_range for more details. + + def self.bench_range &block + return super unless block + + meta = (class << self; self; end) + meta.send :define_method, "bench_range", &block + end + + ## + # Create a benchmark that verifies that the performance is linear. + # + # describe "my class Bench" do + # bench_performance_linear "fast_algorithm", 0.9999 do |n| + # @obj.fast_algorithm(n) + # end + # end + + def self.bench_performance_linear name, threshold = 0.99, &work + bench name do + assert_performance_linear threshold, &work + end + end + + ## + # Create a benchmark that verifies that the performance is constant. + # + # describe "my class Bench" do + # bench_performance_constant "zoom_algorithm!" do |n| + # @obj.zoom_algorithm!(n) + # end + # end + + def self.bench_performance_constant name, threshold = 0.99, &work + bench name do + assert_performance_constant threshold, &work + end + end + + ## + # Create a benchmark that verifies that the performance is exponential. + # + # describe "my class Bench" do + # bench_performance_exponential "algorithm" do |n| + # @obj.algorithm(n) + # end + # end + + def self.bench_performance_exponential name, threshold = 0.99, &work + bench name do + assert_performance_exponential threshold, &work + end + end + + + ## + # Create a benchmark that verifies that the performance is logarithmic. + # + # describe "my class Bench" do + # bench_performance_logarithmic "algorithm" do |n| + # @obj.algorithm(n) + # end + # end + + def self.bench_performance_logarithmic name, threshold = 0.99, &work + bench name do + assert_performance_logarithmic threshold, &work + end + end + + ## + # Create a benchmark that verifies that the performance is power. + # + # describe "my class Bench" do + # bench_performance_power "algorithm" do |n| + # @obj.algorithm(n) + # end + # end + + def self.bench_performance_power name, threshold = 0.99, &work + bench name do + assert_performance_power threshold, &work + end + end + end + + Minitest::Spec.register_spec_type(/Bench(mark)?$/, Minitest::BenchSpec) +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/expectations.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/expectations.rb new file mode 100644 index 0000000..fb4ec4d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/expectations.rb @@ -0,0 +1,303 @@ +## +# It's where you hide your "assertions". +# +# Please note, because of the way that expectations are implemented, +# all expectations (eg must_equal) are dependent upon a thread local +# variable +:current_spec+. If your specs rely on mixing threads into +# the specs themselves, you're better off using assertions or the new +# _(value) wrapper. For example: +# +# it "should still work in threads" do +# my_threaded_thingy do +# (1+1).must_equal 2 # bad +# assert_equal 2, 1+1 # good +# _(1 + 1).must_equal 2 # good +# value(1 + 1).must_equal 2 # good, also #expect +# _ { 1 + "1" }.must_raise TypeError # good +# end +# end + +module Minitest::Expectations + + ## + # See Minitest::Assertions#assert_empty. + # + # _(collection).must_be_empty + # + # :method: must_be_empty + + infect_an_assertion :assert_empty, :must_be_empty, :unary + + ## + # See Minitest::Assertions#assert_equal + # + # _(a).must_equal b + # + # :method: must_equal + + infect_an_assertion :assert_equal, :must_equal + + ## + # See Minitest::Assertions#assert_in_delta + # + # _(n).must_be_close_to m [, delta] + # + # :method: must_be_close_to + + infect_an_assertion :assert_in_delta, :must_be_close_to + + infect_an_assertion :assert_in_delta, :must_be_within_delta # :nodoc: + + ## + # See Minitest::Assertions#assert_in_epsilon + # + # _(n).must_be_within_epsilon m [, epsilon] + # + # :method: must_be_within_epsilon + + infect_an_assertion :assert_in_epsilon, :must_be_within_epsilon + + ## + # See Minitest::Assertions#assert_includes + # + # _(collection).must_include obj + # + # :method: must_include + + infect_an_assertion :assert_includes, :must_include, :reverse + + ## + # See Minitest::Assertions#assert_instance_of + # + # _(obj).must_be_instance_of klass + # + # :method: must_be_instance_of + + infect_an_assertion :assert_instance_of, :must_be_instance_of + + ## + # See Minitest::Assertions#assert_kind_of + # + # _(obj).must_be_kind_of mod + # + # :method: must_be_kind_of + + infect_an_assertion :assert_kind_of, :must_be_kind_of + + ## + # See Minitest::Assertions#assert_match + # + # _(a).must_match b + # + # :method: must_match + + infect_an_assertion :assert_match, :must_match + + ## + # See Minitest::Assertions#assert_nil + # + # _(obj).must_be_nil + # + # :method: must_be_nil + + infect_an_assertion :assert_nil, :must_be_nil, :unary + + ## + # See Minitest::Assertions#assert_operator + # + # _(n).must_be :<=, 42 + # + # This can also do predicates: + # + # _(str).must_be :empty? + # + # :method: must_be + + infect_an_assertion :assert_operator, :must_be, :reverse + + ## + # See Minitest::Assertions#assert_output + # + # _ { ... }.must_output out_or_nil [, err] + # + # :method: must_output + + infect_an_assertion :assert_output, :must_output, :block + + ## + # See Minitest::Assertions#assert_raises + # + # _ { ... }.must_raise exception + # + # :method: must_raise + + infect_an_assertion :assert_raises, :must_raise, :block + + ## + # See Minitest::Assertions#assert_respond_to + # + # _(obj).must_respond_to msg + # + # :method: must_respond_to + + infect_an_assertion :assert_respond_to, :must_respond_to, :reverse + + ## + # See Minitest::Assertions#assert_same + # + # _(a).must_be_same_as b + # + # :method: must_be_same_as + + infect_an_assertion :assert_same, :must_be_same_as + + ## + # See Minitest::Assertions#assert_silent + # + # _ { ... }.must_be_silent + # + # :method: must_be_silent + + infect_an_assertion :assert_silent, :must_be_silent, :block + + ## + # See Minitest::Assertions#assert_throws + # + # _ { ... }.must_throw sym + # + # :method: must_throw + + infect_an_assertion :assert_throws, :must_throw, :block + + ## + # See Minitest::Assertions#assert_path_exists + # + # _(some_path).path_must_exist + # + # :method: path_must_exist + + infect_an_assertion :assert_path_exists, :path_must_exist, :unary + + ## + # See Minitest::Assertions#refute_path_exists + # + # _(some_path).path_wont_exist + # + # :method: path_wont_exist + + infect_an_assertion :refute_path_exists, :path_wont_exist, :unary + + ## + # See Minitest::Assertions#refute_empty + # + # _(collection).wont_be_empty + # + # :method: wont_be_empty + + infect_an_assertion :refute_empty, :wont_be_empty, :unary + + ## + # See Minitest::Assertions#refute_equal + # + # _(a).wont_equal b + # + # :method: wont_equal + + infect_an_assertion :refute_equal, :wont_equal + + ## + # See Minitest::Assertions#refute_in_delta + # + # _(n).wont_be_close_to m [, delta] + # + # :method: wont_be_close_to + + infect_an_assertion :refute_in_delta, :wont_be_close_to + + infect_an_assertion :refute_in_delta, :wont_be_within_delta # :nodoc: + + ## + # See Minitest::Assertions#refute_in_epsilon + # + # _(n).wont_be_within_epsilon m [, epsilon] + # + # :method: wont_be_within_epsilon + + infect_an_assertion :refute_in_epsilon, :wont_be_within_epsilon + + ## + # See Minitest::Assertions#refute_includes + # + # _(collection).wont_include obj + # + # :method: wont_include + + infect_an_assertion :refute_includes, :wont_include, :reverse + + ## + # See Minitest::Assertions#refute_instance_of + # + # _(obj).wont_be_instance_of klass + # + # :method: wont_be_instance_of + + infect_an_assertion :refute_instance_of, :wont_be_instance_of + + ## + # See Minitest::Assertions#refute_kind_of + # + # _(obj).wont_be_kind_of mod + # + # :method: wont_be_kind_of + + infect_an_assertion :refute_kind_of, :wont_be_kind_of + + ## + # See Minitest::Assertions#refute_match + # + # _(a).wont_match b + # + # :method: wont_match + + infect_an_assertion :refute_match, :wont_match + + ## + # See Minitest::Assertions#refute_nil + # + # _(obj).wont_be_nil + # + # :method: wont_be_nil + + infect_an_assertion :refute_nil, :wont_be_nil, :unary + + ## + # See Minitest::Assertions#refute_operator + # + # _(n).wont_be :<=, 42 + # + # This can also do predicates: + # + # str.wont_be :empty? + # + # :method: wont_be + + infect_an_assertion :refute_operator, :wont_be, :reverse + + ## + # See Minitest::Assertions#refute_respond_to + # + # _(obj).wont_respond_to msg + # + # :method: wont_respond_to + + infect_an_assertion :refute_respond_to, :wont_respond_to, :reverse + + ## + # See Minitest::Assertions#refute_same + # + # _(a).wont_be_same_as b + # + # :method: wont_be_same_as + + infect_an_assertion :refute_same, :wont_be_same_as +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/hell.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/hell.rb new file mode 100644 index 0000000..73c88ac --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/hell.rb @@ -0,0 +1,11 @@ +require "minitest/parallel" + +class Minitest::Test + parallelize_me! +end + +begin + require "minitest/proveit" +rescue LoadError + warn "NOTE: `gem install minitest-proveit` for even more hellish tests" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/mock.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/mock.rb new file mode 100644 index 0000000..ddfc788 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/mock.rb @@ -0,0 +1,244 @@ +class MockExpectationError < StandardError; end # :nodoc: + +module Minitest # :nodoc: + + ## + # A simple and clean mock object framework. + # + # All mock objects are an instance of Mock + + class Mock + alias :__respond_to? :respond_to? + + overridden_methods = %w[ + === + class + inspect + instance_eval + instance_variables + object_id + public_send + respond_to_missing? + send + to_s + ] + + instance_methods.each do |m| + undef_method m unless overridden_methods.include?(m.to_s) || m =~ /^__/ + end + + overridden_methods.map(&:to_sym).each do |method_id| + define_method method_id do |*args, &b| + if @expected_calls.key? method_id then + method_missing(method_id, *args, &b) + else + super(*args, &b) + end + end + end + + def initialize delegator = nil # :nodoc: + @delegator = delegator + @expected_calls = Hash.new { |calls, name| calls[name] = [] } + @actual_calls = Hash.new { |calls, name| calls[name] = [] } + end + + ## + # Expect that method +name+ is called, optionally with +args+ or a + # +blk+, and returns +retval+. + # + # @mock.expect(:meaning_of_life, 42) + # @mock.meaning_of_life # => 42 + # + # @mock.expect(:do_something_with, true, [some_obj, true]) + # @mock.do_something_with(some_obj, true) # => true + # + # @mock.expect(:do_something_else, true) do |a1, a2| + # a1 == "buggs" && a2 == :bunny + # end + # + # +args+ is compared to the expected args using case equality (ie, the + # '===' operator), allowing for less specific expectations. + # + # @mock.expect(:uses_any_string, true, [String]) + # @mock.uses_any_string("foo") # => true + # @mock.verify # => true + # + # @mock.expect(:uses_one_string, true, ["foo"]) + # @mock.uses_one_string("bar") # => raises MockExpectationError + # + # If a method will be called multiple times, specify a new expect for each one. + # They will be used in the order you define them. + # + # @mock.expect(:ordinal_increment, 'first') + # @mock.expect(:ordinal_increment, 'second') + # + # @mock.ordinal_increment # => 'first' + # @mock.ordinal_increment # => 'second' + # @mock.ordinal_increment # => raises MockExpectationError "No more expects available for :ordinal_increment" + # + + def expect name, retval, args = [], &blk + name = name.to_sym + + if block_given? + raise ArgumentError, "args ignored when block given" unless args.empty? + @expected_calls[name] << { :retval => retval, :block => blk } + else + raise ArgumentError, "args must be an array" unless Array === args + @expected_calls[name] << { :retval => retval, :args => args } + end + self + end + + def __call name, data # :nodoc: + case data + when Hash then + "#{name}(#{data[:args].inspect[1..-2]}) => #{data[:retval].inspect}" + else + data.map { |d| __call name, d }.join ", " + end + end + + ## + # Verify that all methods were called as expected. Raises + # +MockExpectationError+ if the mock object was not called as + # expected. + + def verify + @expected_calls.each do |name, expected| + actual = @actual_calls.fetch(name, nil) + raise MockExpectationError, "expected #{__call name, expected[0]}" unless actual + raise MockExpectationError, "expected #{__call name, expected[actual.size]}, got [#{__call name, actual}]" if + actual.size < expected.size + end + true + end + + def method_missing sym, *args, &block # :nodoc: + unless @expected_calls.key?(sym) then + if @delegator && @delegator.respond_to?(sym) + return @delegator.public_send(sym, *args, &block) + else + raise NoMethodError, "unmocked method %p, expected one of %p" % + [sym, @expected_calls.keys.sort_by(&:to_s)] + end + end + + index = @actual_calls[sym].length + expected_call = @expected_calls[sym][index] + + unless expected_call then + raise MockExpectationError, "No more expects available for %p: %p" % + [sym, args] + end + + expected_args, retval, val_block = + expected_call.values_at(:args, :retval, :block) + + if val_block then + # keep "verify" happy + @actual_calls[sym] << expected_call + + raise MockExpectationError, "mocked method %p failed block w/ %p" % + [sym, args] unless val_block.call(*args, &block) + + return retval + end + + if expected_args.size != args.size then + raise ArgumentError, "mocked method %p expects %d arguments, got %d" % + [sym, expected_args.size, args.size] + end + + zipped_args = expected_args.zip(args) + fully_matched = zipped_args.all? { |mod, a| + mod === a or mod == a + } + + unless fully_matched then + raise MockExpectationError, "mocked method %p called with unexpected arguments %p" % + [sym, args] + end + + @actual_calls[sym] << { + :retval => retval, + :args => zipped_args.map! { |mod, a| mod === a ? mod : a }, + } + + retval + end + + def respond_to? sym, include_private = false # :nodoc: + return true if @expected_calls.key? sym.to_sym + return true if @delegator && @delegator.respond_to?(sym, include_private) + __respond_to?(sym, include_private) + end + end +end + +module Minitest::Assertions + ## + # Assert that the mock verifies correctly. + + def assert_mock mock + assert mock.verify + end +end + +## +# Object extensions for Minitest::Mock. + +class Object + + ## + # Add a temporary stubbed method replacing +name+ for the duration + # of the +block+. If +val_or_callable+ responds to #call, then it + # returns the result of calling it, otherwise returns the value + # as-is. If stubbed method yields a block, +block_args+ will be + # passed along. Cleans up the stub at the end of the +block+. The + # method +name+ must exist before stubbing. + # + # def test_stale_eh + # obj_under_test = Something.new + # refute obj_under_test.stale? + # + # Time.stub :now, Time.at(0) do + # assert obj_under_test.stale? + # end + # end + #-- + # NOTE: keyword args in callables are NOT checked for correctness + # against the existing method. Too many edge cases to be worth it. + + def stub name, val_or_callable, *block_args + new_name = "__minitest_stub__#{name}" + + metaclass = class << self; self; end + + if respond_to? name and not methods.map(&:to_s).include? name.to_s then + metaclass.send :define_method, name do |*args| + super(*args) + end + end + + metaclass.send :alias_method, new_name, name + + metaclass.send :define_method, name do |*args, &blk| + if val_or_callable.respond_to? :call then + val_or_callable.call(*args, &blk) + else + blk.call(*block_args) if blk + val_or_callable + end + end + + metaclass.send(:ruby2_keywords, name) if metaclass.respond_to?(:ruby2_keywords, true) + + yield self + ensure + metaclass.send :undef_method, name + metaclass.send :alias_method, name, new_name + metaclass.send :undef_method, new_name + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/parallel.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/parallel.rb new file mode 100644 index 0000000..40ac709 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/parallel.rb @@ -0,0 +1,70 @@ +module Minitest + module Parallel #:nodoc: + + ## + # The engine used to run multiple tests in parallel. + + class Executor + + ## + # The size of the pool of workers. + + attr_reader :size + + ## + # Create a parallel test executor of with +size+ workers. + + def initialize size + @size = size + @queue = Queue.new + @pool = nil + end + + ## + # Start the executor + + def start + @pool = size.times.map { + Thread.new(@queue) do |queue| + Thread.current.abort_on_exception = true + while (job = queue.pop) + klass, method, reporter = job + reporter.synchronize { reporter.prerecord klass, method } + result = Minitest.run_one_method klass, method + reporter.synchronize { reporter.record result } + end + end + } + end + + ## + # Add a job to the queue + + def << work; @queue << work; end + + ## + # Shuts down the pool of workers by signalling them to quit and + # waiting for them all to finish what they're currently working + # on. + + def shutdown + size.times { @queue << nil } + @pool.each(&:join) + end + end + + module Test # :nodoc: + def _synchronize; Minitest::Test.io_lock.synchronize { yield }; end # :nodoc: + + module ClassMethods # :nodoc: + def run_one_method klass, method_name, reporter + Minitest.parallel_executor << [klass, method_name, reporter] + end + + def test_order + :parallel + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/pride.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/pride.rb new file mode 100644 index 0000000..f3b8e47 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/pride.rb @@ -0,0 +1,4 @@ +require "minitest" + +Minitest.load_plugins +Minitest::PrideIO.pride! diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/pride_plugin.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/pride_plugin.rb new file mode 100644 index 0000000..aeef2b9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/pride_plugin.rb @@ -0,0 +1,142 @@ +require "minitest" + +module Minitest + def self.plugin_pride_options opts, _options # :nodoc: + opts.on "-p", "--pride", "Pride. Show your testing pride!" do + PrideIO.pride! + end + end + + def self.plugin_pride_init options # :nodoc: + if PrideIO.pride? then + klass = ENV["TERM"] =~ /^xterm|-256color$/ ? PrideLOL : PrideIO + io = klass.new options[:io] + + self.reporter.reporters.grep(Minitest::Reporter).each do |rep| + rep.io = io if rep.io.tty? + end + end + end + + ## + # Show your testing pride! + + class PrideIO + ## + # Activate the pride plugin. Called from both -p option and minitest/pride + + def self.pride! + @pride = true + end + + ## + # Are we showing our testing pride? + + def self.pride? + @pride ||= false + end + + # Start an escape sequence + ESC = "\e[" + + # End the escape sequence + NND = "#{ESC}0m" + + # The IO we're going to pipe through. + attr_reader :io + + def initialize io # :nodoc: + @io = io + # stolen from /System/Library/Perl/5.10.0/Term/ANSIColor.pm + # also reference http://en.wikipedia.org/wiki/ANSI_escape_code + @colors ||= (31..36).to_a + @size = @colors.size + @index = 0 + end + + ## + # Wrap print to colorize the output. + + def print o + case o + when "." then + io.print pride o + when "E", "F" then + io.print "#{ESC}41m#{ESC}37m#{o}#{NND}" + when "S" then + io.print pride o + else + io.print o + end + end + + def puts *o # :nodoc: + o.map! { |s| + s.to_s.sub(/Finished/) { + @index = 0 + "Fabulous run".split(//).map { |c| + pride(c) + }.join + } + } + + io.puts(*o) + end + + ## + # Color a string. + + def pride string + string = "*" if string == "." + c = @colors[@index % @size] + @index += 1 + "#{ESC}#{c}m#{string}#{NND}" + end + + def method_missing msg, *args # :nodoc: + io.send(msg, *args) + end + end + + ## + # If you thought the PrideIO was colorful... + # + # (Inspired by lolcat, but with clean math) + + class PrideLOL < PrideIO + PI_3 = Math::PI / 3 # :nodoc: + + def initialize io # :nodoc: + # walk red, green, and blue around a circle separated by equal thirds. + # + # To visualize, type this into wolfram-alpha: + # + # plot (3*sin(x)+3), (3*sin(x+2*pi/3)+3), (3*sin(x+4*pi/3)+3) + + # 6 has wide pretty gradients. 3 == lolcat, about half the width + @colors = (0...(6 * 7)).map { |n| + n *= 1.0 / 6 + r = (3 * Math.sin(n ) + 3).to_i + g = (3 * Math.sin(n + 2 * PI_3) + 3).to_i + b = (3 * Math.sin(n + 4 * PI_3) + 3).to_i + + # Then we take rgb and encode them in a single number using base 6. + # For some mysterious reason, we add 16... to clear the bottom 4 bits? + # Yes... they're ugly. + + 36 * r + 6 * g + b + 16 + } + + super + end + + ## + # Make the string even more colorful. Damnit. + + def pride string + c = @colors[@index % @size] + @index += 1 + "#{ESC}38;5;#{c}m#{string}#{NND}" + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/spec.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/spec.rb new file mode 100644 index 0000000..41deb55 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/spec.rb @@ -0,0 +1,343 @@ +require "minitest/test" + +class Module # :nodoc: + def infect_an_assertion meth, new_name, dont_flip = false # :nodoc: + block = dont_flip == :block + dont_flip = false if block + target_obj = block ? '_{obj.method}' : '_(obj)' + + # warn "%-22p -> %p %p" % [meth, new_name, dont_flip] + self.class_eval <<-EOM, __FILE__, __LINE__ + 1 + def #{new_name} *args + where = Minitest.filter_backtrace(caller).first + where = where.split(/:in /, 2).first # clean up noise + Kernel.warn "DEPRECATED: global use of #{new_name} from #\{where}. Use #{target_obj}.#{new_name} instead. This will fail in Minitest 6." + Minitest::Expectation.new(self, Minitest::Spec.current).#{new_name}(*args) + end + EOM + + Minitest::Expectation.class_eval <<-EOM, __FILE__, __LINE__ + 1 + def #{new_name} *args + raise "Calling ##{new_name} outside of test." unless ctx + case + when #{!!dont_flip} then + ctx.#{meth}(target, *args) + when #{block} && Proc === target then + ctx.#{meth}(*args, &target) + else + ctx.#{meth}(args.first, target, *args[1..-1]) + end + end + EOM + end +end + +Minitest::Expectation = Struct.new :target, :ctx # :nodoc: + +## +# Kernel extensions for minitest + +module Kernel + ## + # Describe a series of expectations for a given target +desc+. + # + # Defines a test class subclassing from either Minitest::Spec or + # from the surrounding describe's class. The surrounding class may + # subclass Minitest::Spec manually in order to easily share code: + # + # class MySpec < Minitest::Spec + # # ... shared code ... + # end + # + # class TestStuff < MySpec + # it "does stuff" do + # # shared code available here + # end + # describe "inner stuff" do + # it "still does stuff" do + # # ...and here + # end + # end + # end + # + # For more information on getting started with writing specs, see: + # + # http://www.rubyinside.com/a-minitestspec-tutorial-elegant-spec-style-testing-that-comes-with-ruby-5354.html + # + # For some suggestions on how to improve your specs, try: + # + # http://betterspecs.org + # + # but do note that several items there are debatable or specific to + # rspec. + # + # For more information about expectations, see Minitest::Expectations. + + def describe desc, *additional_desc, &block # :doc: + stack = Minitest::Spec.describe_stack + name = [stack.last, desc, *additional_desc].compact.join("::") + sclas = stack.last || if Class === self && kind_of?(Minitest::Spec::DSL) then + self + else + Minitest::Spec.spec_type desc, *additional_desc + end + + cls = sclas.create name, desc + + stack.push cls + cls.class_eval(&block) + stack.pop + cls + end + private :describe +end + +## +# Minitest::Spec -- The faster, better, less-magical spec framework! +# +# For a list of expectations, see Minitest::Expectations. + +class Minitest::Spec < Minitest::Test + + def self.current # :nodoc: + Thread.current[:current_spec] + end + + def initialize name # :nodoc: + super + Thread.current[:current_spec] = self + end + + ## + # Oh look! A Minitest::Spec::DSL module! Eat your heart out DHH. + + module DSL + ## + # Contains pairs of matchers and Spec classes to be used to + # calculate the superclass of a top-level describe. This allows for + # automatically customizable spec types. + # + # See: register_spec_type and spec_type + + TYPES = [[//, Minitest::Spec]] + + ## + # Register a new type of spec that matches the spec's description. + # This method can take either a Regexp and a spec class or a spec + # class and a block that takes the description and returns true if + # it matches. + # + # Eg: + # + # register_spec_type(/Controller$/, Minitest::Spec::Rails) + # + # or: + # + # register_spec_type(Minitest::Spec::RailsModel) do |desc| + # desc.superclass == ActiveRecord::Base + # end + + def register_spec_type *args, &block + if block then + matcher, klass = block, args.first + else + matcher, klass = *args + end + TYPES.unshift [matcher, klass] + end + + ## + # Figure out the spec class to use based on a spec's description. Eg: + # + # spec_type("BlahController") # => Minitest::Spec::Rails + + def spec_type desc, *additional + TYPES.find { |matcher, _klass| + if matcher.respond_to? :call then + matcher.call desc, *additional + else + matcher === desc.to_s + end + }.last + end + + def describe_stack # :nodoc: + Thread.current[:describe_stack] ||= [] + end + + def children # :nodoc: + @children ||= [] + end + + def nuke_test_methods! # :nodoc: + self.public_instance_methods.grep(/^test_/).each do |name| + self.send :undef_method, name + end + end + + ## + # Define a 'before' action. Inherits the way normal methods should. + # + # NOTE: +type+ is ignored and is only there to make porting easier. + # + # Equivalent to Minitest::Test#setup. + + def before _type = nil, &block + define_method :setup do + super() + self.instance_eval(&block) + end + end + + ## + # Define an 'after' action. Inherits the way normal methods should. + # + # NOTE: +type+ is ignored and is only there to make porting easier. + # + # Equivalent to Minitest::Test#teardown. + + def after _type = nil, &block + define_method :teardown do + self.instance_eval(&block) + super() + end + end + + ## + # Define an expectation with name +desc+. Name gets morphed to a + # proper test method name. For some freakish reason, people who + # write specs don't like class inheritance, so this goes way out of + # its way to make sure that expectations aren't inherited. + # + # This is also aliased to #specify and doesn't require a +desc+ arg. + # + # Hint: If you _do_ want inheritance, use minitest/test. You can mix + # and match between assertions and expectations as much as you want. + + def it desc = "anonymous", &block + block ||= proc { skip "(no tests defined)" } + + @specs ||= 0 + @specs += 1 + + name = "test_%04d_%s" % [ @specs, desc ] + + undef_klasses = self.children.reject { |c| c.public_method_defined? name } + + define_method name, &block + + undef_klasses.each do |undef_klass| + undef_klass.send :undef_method, name + end + + name + end + + ## + # Essentially, define an accessor for +name+ with +block+. + # + # Why use let instead of def? I honestly don't know. + + def let name, &block + name = name.to_s + pre, post = "let '#{name}' cannot ", ". Please use another name." + methods = Minitest::Spec.instance_methods.map(&:to_s) - %w[subject] + raise ArgumentError, "#{pre}begin with 'test'#{post}" if + name =~ /\Atest/ + raise ArgumentError, "#{pre}override a method in Minitest::Spec#{post}" if + methods.include? name + + define_method name do + @_memoized ||= {} + @_memoized.fetch(name) { |k| @_memoized[k] = instance_eval(&block) } + end + end + + ## + # Another lazy man's accessor generator. Made even more lazy by + # setting the name for you to +subject+. + + def subject &block + let :subject, &block + end + + def create name, desc # :nodoc: + cls = Class.new(self) do + @name = name + @desc = desc + + nuke_test_methods! + end + + children << cls + + cls + end + + def name # :nodoc: + defined?(@name) ? @name : super + end + + def to_s # :nodoc: + name # Can't alias due to 1.8.7, not sure why + end + + attr_reader :desc # :nodoc: + alias :specify :it + + ## + # Rdoc... why are you so dumb? + + module InstanceMethods + ## + # Takes a value or a block and returns a value monad that has + # all of Expectations methods available to it. + # + # _(1 + 1).must_equal 2 + # + # And for blocks: + # + # _ { 1 + "1" }.must_raise TypeError + # + # This method of expectation-based testing is preferable to + # straight-expectation methods (on Object) because it stores its + # test context, bypassing our hacky use of thread-local variables. + # + # NOTE: At some point, the methods on Object will be deprecated + # and then removed. + # + # It is also aliased to #value and #expect for your aesthetic + # pleasure: + # + # _(1 + 1).must_equal 2 + # value(1 + 1).must_equal 2 + # expect(1 + 1).must_equal 2 + + def _ value = nil, &block + Minitest::Expectation.new block || value, self + end + + alias value _ + alias expect _ + + def before_setup # :nodoc: + super + Thread.current[:current_spec] = self + end + end + + def self.extended obj # :nodoc: + obj.send :include, InstanceMethods + end + end + + extend DSL + + TYPES = DSL::TYPES # :nodoc: +end + +require "minitest/expectations" + +class Object # :nodoc: + include Minitest::Expectations unless ENV["MT_NO_EXPECTATIONS"] +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/test.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/test.rb new file mode 100644 index 0000000..8061230 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/test.rb @@ -0,0 +1,230 @@ +require "minitest" unless defined? Minitest::Runnable + +module Minitest + ## + # Subclass Test to create your own tests. Typically you'll want a + # Test subclass per implementation class. + # + # See Minitest::Assertions + + class Test < Runnable + require "minitest/assertions" + include Minitest::Assertions + include Minitest::Reportable + + def class_name # :nodoc: + self.class.name # for Minitest::Reportable + end + + PASSTHROUGH_EXCEPTIONS = [NoMemoryError, SignalException, SystemExit] # :nodoc: + + # :stopdoc: + class << self; attr_accessor :io_lock; end + self.io_lock = Mutex.new + # :startdoc: + + ## + # Call this at the top of your tests when you absolutely + # positively need to have ordered tests. In doing so, you're + # admitting that you suck and your tests are weak. + + def self.i_suck_and_my_tests_are_order_dependent! + class << self + undef_method :test_order if method_defined? :test_order + define_method :test_order do :alpha end + end + end + + ## + # Make diffs for this Test use #pretty_inspect so that diff + # in assert_equal can have more details. NOTE: this is much slower + # than the regular inspect but much more usable for complex + # objects. + + def self.make_my_diffs_pretty! + require "pp" + + define_method :mu_pp, &:pretty_inspect + end + + ## + # Call this at the top of your tests when you want to run your + # tests in parallel. In doing so, you're admitting that you rule + # and your tests are awesome. + + def self.parallelize_me! + include Minitest::Parallel::Test + extend Minitest::Parallel::Test::ClassMethods + end + + ## + # Returns all instance methods starting with "test_". Based on + # #test_order, the methods are either sorted, randomized + # (default), or run in parallel. + + def self.runnable_methods + methods = methods_matching(/^test_/) + + case self.test_order + when :random, :parallel then + max = methods.size + methods.sort.sort_by { rand max } + when :alpha, :sorted then + methods.sort + else + raise "Unknown test_order: #{self.test_order.inspect}" + end + end + + ## + # Defines the order to run tests (:random by default). Override + # this or use a convenience method to change it for your tests. + + def self.test_order + :random + end + + TEARDOWN_METHODS = %w[ before_teardown teardown after_teardown ] # :nodoc: + + ## + # Runs a single test with setup/teardown hooks. + + def run + with_info_handler do + time_it do + capture_exceptions do + before_setup; setup; after_setup + + self.send self.name + end + + TEARDOWN_METHODS.each do |hook| + capture_exceptions do + self.send hook + end + end + end + end + + Result.from self # per contract + end + + ## + # Provides before/after hooks for setup and teardown. These are + # meant for library writers, NOT for regular test authors. See + # #before_setup for an example. + + module LifecycleHooks + + ## + # Runs before every test, before setup. This hook is meant for + # libraries to extend minitest. It is not meant to be used by + # test developers. + # + # As a simplistic example: + # + # module MyMinitestPlugin + # def before_setup + # super + # # ... stuff to do before setup is run + # end + # + # def after_setup + # # ... stuff to do after setup is run + # super + # end + # + # def before_teardown + # super + # # ... stuff to do before teardown is run + # end + # + # def after_teardown + # # ... stuff to do after teardown is run + # super + # end + # end + # + # class MiniTest::Test + # include MyMinitestPlugin + # end + + def before_setup; end + + ## + # Runs before every test. Use this to set up before each test + # run. + + def setup; end + + ## + # Runs before every test, after setup. This hook is meant for + # libraries to extend minitest. It is not meant to be used by + # test developers. + # + # See #before_setup for an example. + + def after_setup; end + + ## + # Runs after every test, before teardown. This hook is meant for + # libraries to extend minitest. It is not meant to be used by + # test developers. + # + # See #before_setup for an example. + + def before_teardown; end + + ## + # Runs after every test. Use this to clean up after each test + # run. + + def teardown; end + + ## + # Runs after every test, after teardown. This hook is meant for + # libraries to extend minitest. It is not meant to be used by + # test developers. + # + # See #before_setup for an example. + + def after_teardown; end + end # LifecycleHooks + + def capture_exceptions # :nodoc: + yield + rescue *PASSTHROUGH_EXCEPTIONS + raise + rescue Assertion => e + self.failures << e + rescue Exception => e + self.failures << UnexpectedError.new(sanitize_exception e) + end + + def sanitize_exception e # :nodoc: + Marshal.dump e + e + rescue TypeError + bt = e.backtrace + e = RuntimeError.new "Wrapped undumpable exception for: #{e.class}: #{e.message}" + e.set_backtrace bt + e + end + + def with_info_handler &block # :nodoc: + t0 = Minitest.clock_time + + handler = lambda do + warn "\nCurrent: %s#%s %.2fs" % [self.class, self.name, Minitest.clock_time - t0] + end + + self.class.on_signal ::Minitest.info_signal, handler, &block + end + + include LifecycleHooks + include Guard + extend Guard + end # Test +end + +require "minitest/unit" unless defined?(MiniTest) # compatibility layer only diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/unit.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/unit.rb new file mode 100644 index 0000000..9a4eadf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/lib/minitest/unit.rb @@ -0,0 +1,45 @@ +# :stopdoc: + +unless defined?(Minitest) then + # all of this crap is just to avoid circular requires and is only + # needed if a user requires "minitest/unit" directly instead of + # "minitest/autorun", so we also warn + + from = caller.reject { |s| s =~ /rubygems/ }.join("\n ") + warn "Warning: you should require 'minitest/autorun' instead." + warn %(Warning: or add 'gem "minitest"' before 'require "minitest/autorun"') + warn "From:\n #{from}" + + module Minitest; end + MiniTest = Minitest # prevents minitest.rb from requiring back to us + require "minitest" +end + +MiniTest = Minitest unless defined?(MiniTest) + +module Minitest + class Unit + VERSION = Minitest::VERSION + class TestCase < Minitest::Test + def self.inherited klass # :nodoc: + from = caller.first + warn "MiniTest::Unit::TestCase is now Minitest::Test. From #{from}" + super + end + end + + def self.autorun # :nodoc: + from = caller.first + warn "MiniTest::Unit.autorun is now Minitest.autorun. From #{from}" + Minitest.autorun + end + + def self.after_tests &b # :nodoc: + from = caller.first + warn "MiniTest::Unit.after_tests is now Minitest.after_run. From #{from}" + Minitest.after_run(&b) + end + end +end + +# :startdoc: diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/metametameta.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/metametameta.rb new file mode 100644 index 0000000..6e75b9d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/metametameta.rb @@ -0,0 +1,136 @@ +require "tempfile" +require "stringio" +require "minitest/autorun" + +class Minitest::Test + def clean s + s.gsub(/^ {6}/, "") + end + + def with_empty_backtrace_filter + original = Minitest.backtrace_filter + + obj = Minitest::BacktraceFilter.new + def obj.filter _bt + [] + end + + Minitest::Test.io_lock.synchronize do # try not to trounce in parallel + begin + Minitest.backtrace_filter = obj + yield + ensure + Minitest.backtrace_filter = original + end + end + end +end + + +class FakeNamedTest < Minitest::Test + @@count = 0 + + def self.name + @fake_name ||= begin + @@count += 1 + "FakeNamedTest%02d" % @@count + end + end +end + +module MyModule; end +class AnError < StandardError; include MyModule; end + +class MetaMetaMetaTestCase < Minitest::Test + attr_accessor :reporter, :output, :tu + + def with_stderr err + old = $stderr + $stderr = err + yield + ensure + $stderr = old + end + + def run_tu_with_fresh_reporter flags = %w[--seed 42] + options = Minitest.process_args flags + + @output = StringIO.new("".encode('UTF-8')) + + self.reporter = Minitest::CompositeReporter.new + reporter << Minitest::SummaryReporter.new(@output, options) + reporter << Minitest::ProgressReporter.new(@output, options) + + with_stderr @output do + reporter.start + + yield(reporter) if block_given? + + @tus ||= [@tu] + @tus.each do |tu| + Minitest::Runnable.runnables.delete tu + + tu.run reporter, options + end + + reporter.report + end + end + + def first_reporter + reporter.reporters.first + end + + def assert_report expected, flags = %w[--seed 42], &block + header = clean <<-EOM + Run options: #{flags.map { |s| s =~ /\|/ ? s.inspect : s }.join " "} + + # Running: + + EOM + + run_tu_with_fresh_reporter flags, &block + + output = normalize_output @output.string.dup + + assert_equal header + expected, output + end + + def normalize_output output + output.sub!(/Finished in .*/, "Finished in 0.00") + output.sub!(/Loaded suite .*/, "Loaded suite blah") + + output.gsub!(/FakeNamedTest\d+/, "FakeNamedTestXX") + output.gsub!(/ = \d+.\d\d s = /, " = 0.00 s = ") + output.gsub!(/0x[A-Fa-f0-9]+/, "0xXXX") + output.gsub!(/ +$/, "") + + if windows? then + output.gsub!(/\[(?:[A-Za-z]:)?[^\]:]+:\d+\]/, "[FILE:LINE]") + output.gsub!(/^(\s+)(?:[A-Za-z]:)?[^:]+:\d+:in/, '\1FILE:LINE:in') + else + output.gsub!(/\[[^\]:]+:\d+\]/, "[FILE:LINE]") + output.gsub!(/^(\s+)[^:]+:\d+:in/, '\1FILE:LINE:in') + end + + output.gsub!(/( at )[^:]+:\d+/, '\1[FILE:LINE]') + + output + end + + def restore_env + old_value = ENV["MT_NO_SKIP_MSG"] + ENV.delete "MT_NO_SKIP_MSG" + + yield + ensure + ENV["MT_NO_SKIP_MSG"] = old_value + end + + def setup + super + srand 42 + Minitest::Test.reset + @tu = nil + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_assertions.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_assertions.rb new file mode 100644 index 0000000..283dff5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_assertions.rb @@ -0,0 +1,1588 @@ +# encoding: UTF-8 + +require "minitest/autorun" + +if defined? Encoding then + e = Encoding.default_external + if e != Encoding::UTF_8 then + warn "" + warn "" + warn "NOTE: External encoding #{e} is not UTF-8. Tests WILL fail." + warn " Run tests with `RUBYOPT=-Eutf-8 rake` to avoid errors." + warn "" + warn "" + end +end + +SomeError = Class.new Exception + +unless defined? MyModule then + module MyModule; end + class AnError < StandardError; include MyModule; end +end + +class TestMinitestAssertions < Minitest::Test + # do not call parallelize_me! - teardown accesses @tc._assertions + # which is not threadsafe. Nearly every method in here is an + # assertion test so it isn't worth splitting it out further. + + RUBY18 = !defined? Encoding + + # not included in JRuby + RE_LEVELS = /\(\d+ levels\) / + + class DummyTest + include Minitest::Assertions + # include Minitest::Reportable # TODO: why do I really need this? + + attr_accessor :assertions, :failure + + def initialize + self.assertions = 0 + self.failure = nil + end + end + + def setup + super + + Minitest::Test.reset + + @tc = DummyTest.new + @zomg = "zomg ponies!" # TODO: const + @assertion_count = 1 + end + + def teardown + assert_equal(@assertion_count, @tc.assertions, + "expected #{@assertion_count} assertions to be fired during the test, not #{@tc.assertions}") + end + + def assert_deprecated name + dep = /DEPRECATED: #{name}. From #{__FILE__}:\d+(?::.*)?/ + dep = "" if $-w.nil? + + assert_output nil, dep do + yield + end + end + + def assert_triggered expected, klass = Minitest::Assertion + e = assert_raises klass do + yield + end + + msg = e.message.sub(/(---Backtrace---).*/m, '\1') + msg.gsub!(/\(oid=[-0-9]+\)/, "(oid=N)") + msg.gsub!(/(\d\.\d{6})\d+/, '\1xxx') # normalize: ruby version, impl, platform + + assert_msg = Regexp === expected ? :assert_match : :assert_equal + self.send assert_msg, expected, msg + end + + def assert_unexpected expected + expected = Regexp.new expected if String === expected + + assert_triggered expected, Minitest::UnexpectedError do + yield + end + end + + def clean s + s.gsub(/^ {6,10}/, "") + end + + def non_verbose + orig_verbose = $VERBOSE + $VERBOSE = false + + yield + ensure + $VERBOSE = orig_verbose + end + + def test_assert + @assertion_count = 2 + + @tc.assert_equal true, @tc.assert(true), "returns true on success" + end + + def test_assert__triggered + assert_triggered "Expected false to be truthy." do + @tc.assert false + end + end + + def test_assert__triggered_message + assert_triggered @zomg do + @tc.assert false, @zomg + end + end + + def test_assert__triggered_lambda + assert_triggered "whoops" do + @tc.assert false, lambda { "whoops" } + end + end + + def test_assert_empty + @assertion_count = 2 + + @tc.assert_empty [] + end + + def test_assert_empty_triggered + @assertion_count = 2 + + assert_triggered "Expected [1] to be empty." do + @tc.assert_empty [1] + end + end + + def test_assert_equal + @tc.assert_equal 1, 1 + end + + def test_assert_equal_different_collection_array_hex_invisible + object1 = Object.new + object2 = Object.new + msg = "No visible difference in the Array#inspect output. + You should look at the implementation of #== on Array or its members. + [#]".gsub(/^ +/, "") + assert_triggered msg do + @tc.assert_equal [object1], [object2] + end + end + + def test_assert_equal_different_collection_hash_hex_invisible + h1, h2 = {}, {} + h1[1] = Object.new + h2[1] = Object.new + msg = "No visible difference in the Hash#inspect output. + You should look at the implementation of #== on Hash or its members. + {1=>#}".gsub(/^ +/, "") + + assert_triggered msg do + @tc.assert_equal h1, h2 + end + end + + def test_assert_equal_different_diff_deactivated + without_diff do + assert_triggered util_msg("haha" * 10, "blah" * 10) do + o1 = "haha" * 10 + o2 = "blah" * 10 + + @tc.assert_equal o1, o2 + end + end + end + + def test_assert_equal_different_message + assert_triggered "whoops.\nExpected: 1\n Actual: 2" do + @tc.assert_equal 1, 2, message { "whoops" } + end + end + + def test_assert_equal_different_lambda + assert_triggered "whoops.\nExpected: 1\n Actual: 2" do + @tc.assert_equal 1, 2, lambda { "whoops" } + end + end + + def test_assert_equal_different_hex + c = Class.new do + def initialize s; @name = s; end + end + + o1 = c.new "a" + o2 = c.new "b" + msg = clean <<-EOS + --- expected + +++ actual + @@ -1 +1 @@ + -#<#:0xXXXXXX @name=\"a\"> + +#<#:0xXXXXXX @name=\"b\"> + EOS + + assert_triggered msg do + @tc.assert_equal o1, o2 + end + end + + def test_assert_equal_different_hex_invisible + o1 = Object.new + o2 = Object.new + + msg = "No visible difference in the Object#inspect output. + You should look at the implementation of #== on Object or its members. + #".gsub(/^ +/, "") + + assert_triggered msg do + @tc.assert_equal o1, o2 + end + end + + def test_assert_equal_different_long + msg = "--- expected + +++ actual + @@ -1 +1 @@ + -\"hahahahahahahahahahahahahahahahahahahaha\" + +\"blahblahblahblahblahblahblahblahblahblah\" + ".gsub(/^ +/, "") + + assert_triggered msg do + o1 = "haha" * 10 + o2 = "blah" * 10 + + @tc.assert_equal o1, o2 + end + end + + def test_assert_equal_different_long_invisible + msg = "No visible difference in the String#inspect output. + You should look at the implementation of #== on String or its members. + \"blahblahblahblahblahblahblahblahblahblah\"".gsub(/^ +/, "") + + assert_triggered msg do + o1 = "blah" * 10 + o2 = "blah" * 10 + def o1.== _ + false + end + @tc.assert_equal o1, o2 + end + end + + def test_assert_equal_different_long_msg + msg = "message. + --- expected + +++ actual + @@ -1 +1 @@ + -\"hahahahahahahahahahahahahahahahahahahaha\" + +\"blahblahblahblahblahblahblahblahblahblah\" + ".gsub(/^ +/, "") + + assert_triggered msg do + o1 = "haha" * 10 + o2 = "blah" * 10 + @tc.assert_equal o1, o2, "message" + end + end + + def test_assert_equal_different_short + assert_triggered util_msg(1, 2) do + @tc.assert_equal 1, 2 + end + end + + def test_assert_equal_different_short_msg + assert_triggered util_msg(1, 2, "message") do + @tc.assert_equal 1, 2, "message" + end + end + + def test_assert_equal_different_short_multiline + msg = "--- expected\n+++ actual\n@@ -1,2 +1,2 @@\n \"a\n-b\"\n+c\"\n" + assert_triggered msg do + @tc.assert_equal "a\nb", "a\nc" + end + end + + def test_assert_equal_does_not_allow_lhs_nil + if Minitest::VERSION =~ /^6/ then + warn "Time to strip the MT5 test" + + @assertion_count += 1 + assert_triggered(/Use assert_nil if expecting nil/) do + @tc.assert_equal nil, nil + end + else + err_re = /Use assert_nil if expecting nil from .*test_minitest_\w+.rb/ + err_re = "" if $-w.nil? + + assert_output "", err_re do + @tc.assert_equal nil, nil + end + end + end + + def test_assert_equal_does_not_allow_lhs_nil_triggered + assert_triggered "Expected: nil\n Actual: false" do + @tc.assert_equal nil, false + end + end + + def test_assert_equal_string_bug791 + exp = <<-'EOF'.gsub(/^ {10}/, "") # note single quotes + --- expected + +++ actual + @@ -1,2 +1 @@ + -"\\n + -" + +"\\\" + EOF + + exp = "Expected: \"\\\\n\"\n Actual: \"\\\\\"" + assert_triggered exp do + @tc.assert_equal "\\n", "\\" + end + end + + def test_assert_equal_string_both_escaped_unescaped_newlines + msg = <<-EOM.gsub(/^ {10}/, "") + --- expected + +++ actual + @@ -1,2 +1 @@ + -\"A\\n + -B\" + +\"A\\n\\\\nB\" + EOM + + assert_triggered msg do + exp = "A\\nB" + act = "A\n\\nB" + + @tc.assert_equal exp, act + end + end + + def test_assert_equal_string_encodings + msg = <<-EOM.gsub(/^ {10}/, "") + --- expected + +++ actual + @@ -1,3 +1,3 @@ + -# encoding: UTF-8 + -# valid: false + +# encoding: ASCII-8BIT + +# valid: true + "bad-utf8-\\xF1.txt" + EOM + + assert_triggered msg do + x = "bad-utf8-\xF1.txt" + y = x.dup.force_encoding "binary" # TODO: switch to .b when 1.9 dropped + @tc.assert_equal x, y + end + end unless RUBY18 + + def test_assert_equal_string_encodings_both_different + msg = <<-EOM.gsub(/^ {10}/, "") + --- expected + +++ actual + @@ -1,3 +1,3 @@ + -# encoding: US-ASCII + -# valid: false + +# encoding: ASCII-8BIT + +# valid: true + "bad-utf8-\\xF1.txt" + EOM + + assert_triggered msg do + x = "bad-utf8-\xF1.txt".force_encoding "ASCII" + y = x.dup.force_encoding "binary" # TODO: switch to .b when 1.9 dropped + @tc.assert_equal x, y + end + end unless RUBY18 + + def test_assert_equal_unescape_newlines + msg = <<-'EOM'.gsub(/^ {10}/, "") # NOTE single quotes on heredoc + --- expected + +++ actual + @@ -1,2 +1,2 @@ + -"hello + +"hello\n + world" + EOM + + assert_triggered msg do + exp = "hello\nworld" + act = 'hello\nworld' # notice single quotes + + @tc.assert_equal exp, act + end + end + + def test_assert_in_delta + @tc.assert_in_delta 0.0, 1.0 / 1000, 0.1 + end + + def test_assert_in_delta_triggered + x = "1.0e-06" + assert_triggered "Expected |0.0 - 0.001| (0.001) to be <= #{x}." do + @tc.assert_in_delta 0.0, 1.0 / 1000, 0.000001 + end + end + + def test_assert_in_epsilon + @assertion_count = 10 + + @tc.assert_in_epsilon 10_000, 9991 + @tc.assert_in_epsilon 9991, 10_000 + @tc.assert_in_epsilon 1.0, 1.001 + @tc.assert_in_epsilon 1.001, 1.0 + + @tc.assert_in_epsilon 10_000, 9999.1, 0.0001 + @tc.assert_in_epsilon 9999.1, 10_000, 0.0001 + @tc.assert_in_epsilon 1.0, 1.0001, 0.0001 + @tc.assert_in_epsilon 1.0001, 1.0, 0.0001 + + @tc.assert_in_epsilon(-1, -1) + @tc.assert_in_epsilon(-10_000, -9991) + end + + def test_assert_in_epsilon_triggered + assert_triggered "Expected |10000 - 9990| (10) to be <= 9.99." do + @tc.assert_in_epsilon 10_000, 9990 + end + end + + def test_assert_in_epsilon_triggered_negative_case + x = (RUBY18 and not maglev?) ? "0.1" : "0.100000xxx" + y = "0.1" + assert_triggered "Expected |-1.1 - -1| (#{x}) to be <= #{y}." do + @tc.assert_in_epsilon(-1.1, -1, 0.1) + end + end + + def test_assert_includes + @assertion_count = 2 + + @tc.assert_includes [true], true + end + + def test_assert_includes_triggered + @assertion_count = 3 + + e = @tc.assert_raises Minitest::Assertion do + @tc.assert_includes [true], false + end + + expected = "Expected [true] to include false." + assert_equal expected, e.message + end + + def test_assert_instance_of + @tc.assert_instance_of String, "blah" + end + + def test_assert_instance_of_triggered + assert_triggered 'Expected "blah" to be an instance of Array, not String.' do + @tc.assert_instance_of Array, "blah" + end + end + + def test_assert_kind_of + @tc.assert_kind_of String, "blah" + end + + def test_assert_kind_of_triggered + assert_triggered 'Expected "blah" to be a kind of Array, not String.' do + @tc.assert_kind_of Array, "blah" + end + end + + def test_assert_match + @assertion_count = 2 + @tc.assert_match(/\w+/, "blah blah blah") + end + + def test_assert_match_matchee_to_str + @assertion_count = 2 + + obj = Object.new + def obj.to_str; "blah" end + + @tc.assert_match "blah", obj + end + + def test_assert_match_matcher_object + @assertion_count = 2 + + pattern = Object.new + def pattern.=~ _; true end + + @tc.assert_match pattern, 5 + end + + def test_assert_match_object_triggered + @assertion_count = 2 + + pattern = Object.new + def pattern.=~ _; false end + def pattern.inspect; "[Object]" end + + assert_triggered "Expected [Object] to match 5." do + @tc.assert_match pattern, 5 + end + end + + def test_assert_match_triggered + @assertion_count = 2 + assert_triggered 'Expected /\d+/ to match "blah blah blah".' do + @tc.assert_match(/\d+/, "blah blah blah") + end + end + + def test_assert_nil + @tc.assert_nil nil + end + + def test_assert_nil_triggered + assert_triggered "Expected 42 to be nil." do + @tc.assert_nil 42 + end + end + + def test_assert_operator + @tc.assert_operator 2, :>, 1 + end + + def test_assert_operator_bad_object + bad = Object.new + def bad.== _; true end + + @tc.assert_operator bad, :equal?, bad + end + + def test_assert_operator_triggered + assert_triggered "Expected 2 to be < 1." do + @tc.assert_operator 2, :<, 1 + end + end + + def test_assert_output_both + @assertion_count = 2 + + @tc.assert_output "yay", "blah" do + print "yay" + $stderr.print "blah" + end + end + + def test_assert_output_both_regexps + @assertion_count = 4 + + @tc.assert_output(/y.y/, /bl.h/) do + print "yay" + $stderr.print "blah" + end + end + + def test_assert_output_err + @tc.assert_output nil, "blah" do + $stderr.print "blah" + end + end + + def test_assert_output_neither + @assertion_count = 0 + + @tc.assert_output do + # do nothing + end + end + + def test_assert_output_out + @tc.assert_output "blah" do + print "blah" + end + end + + def test_assert_output_triggered_both + assert_triggered util_msg("blah", "blah blah", "In stderr") do + @tc.assert_output "yay", "blah" do + print "boo" + $stderr.print "blah blah" + end + end + end + + def test_assert_output_triggered_err + assert_triggered util_msg("blah", "blah blah", "In stderr") do + @tc.assert_output nil, "blah" do + $stderr.print "blah blah" + end + end + end + + def test_assert_output_triggered_out + assert_triggered util_msg("blah", "blah blah", "In stdout") do + @tc.assert_output "blah" do + print "blah blah" + end + end + end + + def test_assert_output_no_block + assert_triggered "assert_output requires a block to capture output." do + @tc.assert_output "blah" + end + end + + def test_assert_output_nested_assert_uncaught + @assertion_count = 1 + + assert_triggered "Epic Fail!" do + @tc.assert_output "blah\n" do + puts "blah" + @tc.flunk + end + end + end + + def test_assert_output_nested_raise + @assertion_count = 2 + + @tc.assert_output "blah\n" do + @tc.assert_raises RuntimeError do + puts "blah" + raise "boom!" + end + end + end + + def test_assert_output_nested_raise_bad + @assertion_count = 0 + + assert_unexpected "boom!" do + @tc.assert_raises do # 2) bypassed via UnexpectedError + @tc.assert_output "blah\n" do # 1) captures and raises UnexpectedError + puts "not_blah" + raise "boom!" + end + end + end + end + + def test_assert_output_nested_raise_mismatch + # this test is redundant, but illustrative + @assertion_count = 0 + + assert_unexpected "boom!" do + @tc.assert_raises RuntimeError do # 2) bypassed via UnexpectedError + @tc.assert_output "blah\n" do # 1) captures and raises UnexpectedError + puts "not_blah" + raise ArgumentError, "boom!" + end + end + end + end + + def test_assert_output_nested_throw_caught + @assertion_count = 2 + + @tc.assert_output "blah\n" do + @tc.assert_throws :boom! do + puts "blah" + throw :boom! + end + end + end + + def test_assert_output_nested_throw_caught_bad + @assertion_count = 1 # want 0; can't prevent throw from escaping :( + + @tc.assert_throws :boom! do # 2) captured via catch + @tc.assert_output "blah\n" do # 1) bypassed via throw + puts "not_blah" + throw :boom! + end + end + end + + def test_assert_output_nested_throw_mismatch + @assertion_count = 0 + + assert_unexpected "uncaught throw :boom!" do + @tc.assert_throws :not_boom! do # 2) captured via assert_throws+rescue + @tc.assert_output "blah\n" do # 1) bypassed via throw + puts "not_blah" + throw :boom! + end + end + end + end + + def test_assert_output_uncaught_raise + @assertion_count = 0 + + assert_unexpected "RuntimeError: boom!" do + @tc.assert_output "blah\n" do + puts "not_blah" + raise "boom!" + end + end + end + + def test_assert_output_uncaught_throw + @assertion_count = 0 + + assert_unexpected "uncaught throw :boom!" do + @tc.assert_output "blah\n" do + puts "not_blah" + throw :boom! + end + end + end + def test_assert_predicate + @tc.assert_predicate "", :empty? + end + + def test_assert_predicate_triggered + assert_triggered 'Expected "blah" to be empty?.' do + @tc.assert_predicate "blah", :empty? + end + end + + def test_assert_raises + @tc.assert_raises RuntimeError do + raise "blah" + end + end + + def test_assert_raises_default + @tc.assert_raises do + raise StandardError, "blah" + end + end + + def test_assert_raises_default_triggered + e = assert_raises Minitest::Assertion do + @tc.assert_raises do + raise SomeError, "blah" + end + end + + expected = clean <<-EOM.chomp + [StandardError] exception expected, not + Class: + Message: <\"blah\"> + ---Backtrace--- + FILE:LINE:in \`block in test_assert_raises_default_triggered\' + --------------- + EOM + + actual = e.message.gsub(/^.+:\d+/, "FILE:LINE") + actual.gsub!(RE_LEVELS, "") unless jruby? + + assert_equal expected, actual + end + + def test_assert_raises_exit + @tc.assert_raises SystemExit do + exit 1 + end + end + + def test_assert_raises_module + @tc.assert_raises MyModule do + raise AnError + end + end + + def test_assert_raises_signals + @tc.assert_raises SignalException do + raise SignalException, :INT + end + end + + def test_assert_raises_throw_nested_bad + @assertion_count = 0 + + assert_unexpected "RuntimeError: boom!" do + @tc.assert_raises do + @tc.assert_throws :blah do + raise "boom!" + throw :not_blah + end + end + end + end + + ## + # *sigh* This is quite an odd scenario, but it is from real (albeit + # ugly) test code in ruby-core: + + # http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=29259 + + def test_assert_raises_skip + @assertion_count = 0 + + assert_triggered "skipped", Minitest::Skip do + @tc.assert_raises ArgumentError do + begin + raise "blah" + rescue + skip "skipped" + end + end + end + end + + def test_assert_raises_subclass + @tc.assert_raises StandardError do + raise AnError + end + end + + def test_assert_raises_subclass_triggered + e = assert_raises Minitest::Assertion do + @tc.assert_raises SomeError do + raise AnError, "some message" + end + end + + expected = clean <<-EOM + [SomeError] exception expected, not + Class: + Message: <\"some message\"> + ---Backtrace--- + FILE:LINE:in \`block in test_assert_raises_subclass_triggered\' + --------------- + EOM + + actual = e.message.gsub(/^.+:\d+/, "FILE:LINE") + actual.gsub!(RE_LEVELS, "") unless jruby? + + assert_equal expected.chomp, actual + end + + def test_assert_raises_triggered_different + e = assert_raises Minitest::Assertion do + @tc.assert_raises RuntimeError do + raise SyntaxError, "icky" + end + end + + expected = clean <<-EOM.chomp + [RuntimeError] exception expected, not + Class: + Message: <\"icky\"> + ---Backtrace--- + FILE:LINE:in \`block in test_assert_raises_triggered_different\' + --------------- + EOM + + actual = e.message.gsub(/^.+:\d+/, "FILE:LINE") + actual.gsub!(RE_LEVELS, "") unless jruby? + + assert_equal expected, actual + end + + def test_assert_raises_triggered_different_msg + e = assert_raises Minitest::Assertion do + @tc.assert_raises RuntimeError, "XXX" do + raise SyntaxError, "icky" + end + end + + expected = clean <<-EOM + XXX. + [RuntimeError] exception expected, not + Class: + Message: <\"icky\"> + ---Backtrace--- + FILE:LINE:in \`block in test_assert_raises_triggered_different_msg\' + --------------- + EOM + + actual = e.message.gsub(/^.+:\d+/, "FILE:LINE") + actual.gsub!(RE_LEVELS, "") unless jruby? + + assert_equal expected.chomp, actual + end + + def test_assert_raises_triggered_none + e = assert_raises Minitest::Assertion do + @tc.assert_raises Minitest::Assertion do + # do nothing + end + end + + expected = "Minitest::Assertion expected but nothing was raised." + + assert_equal expected, e.message + end + + def test_assert_raises_triggered_none_msg + e = assert_raises Minitest::Assertion do + @tc.assert_raises Minitest::Assertion, "XXX" do + # do nothing + end + end + + expected = "XXX.\nMinitest::Assertion expected but nothing was raised." + + assert_equal expected, e.message + end + + def test_assert_raises_without_block + assert_triggered "assert_raises requires a block to capture errors." do + @tc.assert_raises StandardError + end + end + + def test_assert_respond_to + @tc.assert_respond_to "blah", :empty? + end + + def test_assert_respond_to_triggered + assert_triggered 'Expected "blah" (String) to respond to #rawr!.' do + @tc.assert_respond_to "blah", :rawr! + end + end + + def test_assert_same + @assertion_count = 3 + + o = "blah" + @tc.assert_same 1, 1 + @tc.assert_same :blah, :blah + @tc.assert_same o, o + end + + def test_assert_same_triggered + @assertion_count = 2 + + assert_triggered "Expected 2 (oid=N) to be the same as 1 (oid=N)." do + @tc.assert_same 1, 2 + end + + s1 = "blah" + s2 = "blah" + + assert_triggered 'Expected "blah" (oid=N) to be the same as "blah" (oid=N).' do + @tc.assert_same s1, s2 + end + end + + def test_assert_send + assert_deprecated :assert_send do + @tc.assert_send [1, :<, 2] + end + end + + def test_assert_send_bad + assert_deprecated :assert_send do + assert_triggered "Expected 1.>(*[2]) to return true." do + @tc.assert_send [1, :>, 2] + end + end + end + + def test_assert_silent + @assertion_count = 2 + + @tc.assert_silent do + # do nothing + end + end + + def test_assert_silent_triggered_err + assert_triggered util_msg("", "blah blah", "In stderr") do + @tc.assert_silent do + $stderr.print "blah blah" + end + end + end + + def test_assert_silent_triggered_out + @assertion_count = 2 + + assert_triggered util_msg("", "blah blah", "In stdout") do + @tc.assert_silent do + print "blah blah" + end + end + end + + def test_assert_throws + v = @tc.assert_throws :blah do + throw :blah + end + + assert_nil v + end + + def test_assert_throws_value + v = @tc.assert_throws :blah do + throw :blah, 42 + end + + assert_equal 42, v + end + + def test_assert_throws_argument_exception + @assertion_count = 0 + + assert_unexpected "ArgumentError" do + @tc.assert_throws :blah do + raise ArgumentError + end + end + end + + def test_assert_throws_different + assert_triggered "Expected :blah to have been thrown, not :not_blah." do + @tc.assert_throws :blah do + throw :not_blah + end + end + end + + def test_assert_throws_name_error + @assertion_count = 0 + + assert_unexpected "NameError" do + @tc.assert_throws :blah do + raise NameError + end + end + end + + def test_assert_throws_unthrown + assert_triggered "Expected :blah to have been thrown." do + @tc.assert_throws :blah do + # do nothing + end + end + end + + def test_assert_path_exists + @tc.assert_path_exists __FILE__ + end + + def test_assert_path_exists_triggered + assert_triggered "Expected path 'blah' to exist." do + @tc.assert_path_exists "blah" + end + end + + def test_capture_io + @assertion_count = 0 + + non_verbose do + out, err = capture_io do + puts "hi" + $stderr.puts "bye!" + end + + assert_equal "hi\n", out + assert_equal "bye!\n", err + end + end + + def test_capture_subprocess_io + @assertion_count = 0 + + non_verbose do + out, err = capture_subprocess_io do + system("echo hi") + system("echo bye! 1>&2") + end + + assert_equal "hi\n", out + assert_equal "bye!", err.strip + end + end + + def test_class_asserts_match_refutes + @assertion_count = 0 + + methods = Minitest::Assertions.public_instance_methods + methods.map!(&:to_s) if Symbol === methods.first + + # These don't have corresponding refutes _on purpose_. They're + # useless and will never be added, so don't bother. + ignores = %w[assert_output assert_raises assert_send + assert_silent assert_throws assert_mock] + + # These are test/unit methods. I'm not actually sure why they're still here + ignores += %w[assert_no_match assert_not_equal assert_not_nil + assert_not_same assert_nothing_raised + assert_nothing_thrown assert_raise] + + asserts = methods.grep(/^assert/).sort - ignores + refutes = methods.grep(/^refute/).sort - ignores + + assert_empty refutes.map { |n| n.sub(/^refute/, "assert") } - asserts + assert_empty asserts.map { |n| n.sub(/^assert/, "refute") } - refutes + end + + def test_delta_consistency + @assertion_count = 2 + + @tc.assert_in_delta 0, 1, 1 + + assert_triggered "Expected |0 - 1| (1) to not be <= 1." do + @tc.refute_in_delta 0, 1, 1 + end + end + + def test_epsilon_consistency + @assertion_count = 2 + + @tc.assert_in_epsilon 1.0, 1.001 + + msg = "Expected |1.0 - 1.001| (0.000999xxx) to not be <= 0.001." + assert_triggered msg do + @tc.refute_in_epsilon 1.0, 1.001 + end + end + + def assert_fail_after t + @tc.fail_after t.year, t.month, t.day, "remove the deprecations" + end + + def test_fail_after + d0 = Time.now + d1 = d0 + 86_400 # I am an idiot + + assert_silent do + assert_fail_after d1 + end + + assert_triggered "remove the deprecations" do + assert_fail_after d0 + end + end + + def test_flunk + assert_triggered "Epic Fail!" do + @tc.flunk + end + end + + def test_flunk_message + assert_triggered @zomg do + @tc.flunk @zomg + end + end + + def test_pass + @tc.pass + end + + def test_refute + @assertion_count = 2 + + @tc.assert_equal true, @tc.refute(false), "returns true on success" + end + + def test_refute_empty + @assertion_count = 2 + + @tc.refute_empty [1] + end + + def test_refute_empty_triggered + @assertion_count = 2 + + assert_triggered "Expected [] to not be empty." do + @tc.refute_empty [] + end + end + + def test_refute_equal + @tc.refute_equal "blah", "yay" + end + + def test_refute_equal_triggered + assert_triggered 'Expected "blah" to not be equal to "blah".' do + @tc.refute_equal "blah", "blah" + end + end + + def test_refute_in_delta + @tc.refute_in_delta 0.0, 1.0 / 1000, 0.000001 + end + + def test_refute_in_delta_triggered + x = "0.1" + assert_triggered "Expected |0.0 - 0.001| (0.001) to not be <= #{x}." do + @tc.refute_in_delta 0.0, 1.0 / 1000, 0.1 + end + end + + def test_refute_in_epsilon + @tc.refute_in_epsilon 10_000, 9990-1 + end + + def test_refute_in_epsilon_triggered + assert_triggered "Expected |10000 - 9990| (10) to not be <= 10.0." do + @tc.refute_in_epsilon 10_000, 9990 + flunk + end + end + + def test_refute_includes + @assertion_count = 2 + + @tc.refute_includes [true], false + end + + def test_refute_includes_triggered + @assertion_count = 3 + + e = @tc.assert_raises Minitest::Assertion do + @tc.refute_includes [true], true + end + + expected = "Expected [true] to not include true." + assert_equal expected, e.message + end + + def test_refute_instance_of + @tc.refute_instance_of Array, "blah" + end + + def test_refute_instance_of_triggered + assert_triggered 'Expected "blah" to not be an instance of String.' do + @tc.refute_instance_of String, "blah" + end + end + + def test_refute_kind_of + @tc.refute_kind_of Array, "blah" + end + + def test_refute_kind_of_triggered + assert_triggered 'Expected "blah" to not be a kind of String.' do + @tc.refute_kind_of String, "blah" + end + end + + def test_refute_match + @assertion_count = 2 + @tc.refute_match(/\d+/, "blah blah blah") + end + + def test_refute_match_matcher_object + @assertion_count = 2 + pattern = Object.new + def pattern.=~ _; false end + @tc.refute_match pattern, 5 + end + + def test_refute_match_object_triggered + @assertion_count = 2 + + pattern = Object.new + def pattern.=~ _; true end + def pattern.inspect; "[Object]" end + + assert_triggered "Expected [Object] to not match 5." do + @tc.refute_match pattern, 5 + end + end + + def test_refute_match_triggered + @assertion_count = 2 + assert_triggered 'Expected /\w+/ to not match "blah blah blah".' do + @tc.refute_match(/\w+/, "blah blah blah") + end + end + + def test_refute_nil + @tc.refute_nil 42 + end + + def test_refute_nil_triggered + assert_triggered "Expected nil to not be nil." do + @tc.refute_nil nil + end + end + + def test_refute_operator + @tc.refute_operator 2, :<, 1 + end + + def test_refute_operator_bad_object + bad = Object.new + def bad.== _; true end + + @tc.refute_operator true, :equal?, bad + end + + def test_refute_operator_triggered + assert_triggered "Expected 2 to not be > 1." do + @tc.refute_operator 2, :>, 1 + end + end + + def test_refute_predicate + @tc.refute_predicate "42", :empty? + end + + def test_refute_predicate_triggered + assert_triggered 'Expected "" to not be empty?.' do + @tc.refute_predicate "", :empty? + end + end + + def test_refute_respond_to + @tc.refute_respond_to "blah", :rawr! + end + + def test_refute_respond_to_triggered + assert_triggered 'Expected "blah" to not respond to empty?.' do + @tc.refute_respond_to "blah", :empty? + end + end + + def test_refute_same + @tc.refute_same 1, 2 + end + + def test_refute_same_triggered + assert_triggered "Expected 1 (oid=N) to not be the same as 1 (oid=N)." do + @tc.refute_same 1, 1 + end + end + + def test_refute_path_exists + @tc.refute_path_exists "blah" + end + + def test_refute_path_exists_triggered + assert_triggered "Expected path '#{__FILE__}' to not exist." do + @tc.refute_path_exists __FILE__ + end + end + + def test_skip + @assertion_count = 0 + + assert_triggered "haha!", Minitest::Skip do + @tc.skip "haha!" + end + end + + def assert_skip_until t, msg + @tc.skip_until t.year, t.month, t.day, msg + end + + def test_skip_until + @assertion_count = 0 + + d0 = Time.now + d1 = d0 + 86_400 # I am an idiot + + assert_output "", /Stale skip_until \"not yet\" at .*?:\d+$/ do + assert_skip_until d0, "not yet" + end + + assert_triggered "not ready yet", Minitest::Skip do + assert_skip_until d1, "not ready yet" + end + end + + def util_msg exp, act, msg = nil + s = "Expected: #{exp.inspect}\n Actual: #{act.inspect}" + s = "#{msg}.\n#{s}" if msg + s + end + + def without_diff + old_diff = Minitest::Assertions.diff + Minitest::Assertions.diff = nil + + yield + ensure + Minitest::Assertions.diff = old_diff + end +end + +class TestMinitestAssertionHelpers < Minitest::Test + def assert_mu_pp exp, input, raw = false + act = mu_pp input + + if String === input && !raw then + assert_equal "\"#{exp}\"", act + else + assert_equal exp, act + end + end + + def assert_mu_pp_for_diff exp, input, raw = false + act = mu_pp_for_diff input + + if String === input && !raw then + assert_equal "\"#{exp}\"", act + else + assert_equal exp, act + end + end + + def test_diff_equal + msg = "No visible difference in the String#inspect output. + You should look at the implementation of #== on String or its members. + \"blahblahblahblahblahblahblahblahblahblah\"".gsub(/^ +/, "") + + o1 = "blah" * 10 + o2 = "blah" * 10 + def o1.== _ + false + end + + assert_equal msg, diff(o1, o2) + end + + def test_diff_str_mixed + msg = <<-'EOM'.gsub(/^ {10}/, "") # NOTE single quotes on heredoc + --- expected + +++ actual + @@ -1 +1 @@ + -"A\\n\nB" + +"A\n\\nB" + EOM + + exp = "A\\n\nB" + act = "A\n\\nB" + + assert_equal msg, diff(exp, act) + end + + def test_diff_str_multiline + msg = <<-'EOM'.gsub(/^ {10}/, "") # NOTE single quotes on heredoc + --- expected + +++ actual + @@ -1,2 +1,2 @@ + "A + -B" + +C" + EOM + + exp = "A\nB" + act = "A\nC" + + assert_equal msg, diff(exp, act) + end + + def test_diff_str_simple + msg = <<-'EOM'.gsub(/^ {10}/, "").chomp # NOTE single quotes on heredoc + Expected: "A" + Actual: "B" + EOM + + exp = "A" + act = "B" + + assert_equal msg, diff(exp, act) + end + + def test_message + assert_equal "blah2.", message { "blah2" }.call + assert_equal "blah2.", message("") { "blah2" }.call + assert_equal "blah1.\nblah2.", message(:blah1) { "blah2" }.call + assert_equal "blah1.\nblah2.", message("blah1") { "blah2" }.call + + message = proc { "blah1" } + assert_equal "blah1.\nblah2.", message(message) { "blah2" }.call + + message = message { "blah1" } + assert_equal "blah1.\nblah2.", message(message) { "blah2" }.call + end + + def test_message_deferred + var = nil + + msg = message { var = "blah" } + + assert_nil var + + msg.call + + assert_equal "blah", var + end + + def test_mu_pp + assert_mu_pp 42.inspect, 42 + assert_mu_pp %w[a b c].inspect, %w[a b c] + assert_mu_pp "A B", "A B" + assert_mu_pp "A\\nB", "A\nB" + assert_mu_pp "A\\\\nB", 'A\nB' # notice single quotes + end + + def test_mu_pp_for_diff + assert_mu_pp_for_diff "#", Object.new + assert_mu_pp_for_diff "A B", "A B" + assert_mu_pp_for_diff [1, 2, 3].inspect, [1, 2, 3] + assert_mu_pp_for_diff "A\nB", "A\nB" + end + + def test_mu_pp_for_diff_str_bad_encoding + str = "\666".force_encoding Encoding::UTF_8 + exp = "# encoding: UTF-8\n# valid: false\n\"\\xB6\"" + + assert_mu_pp_for_diff exp, str, :raw + end + + def test_mu_pp_for_diff_str_bad_encoding_both + str = "\666A\\n\nB".force_encoding Encoding::UTF_8 + exp = "# encoding: UTF-8\n# valid: false\n\"\\xB6A\\\\n\\nB\"" + + assert_mu_pp_for_diff exp, str, :raw + end + + def test_mu_pp_for_diff_str_encoding + str = "A\nB".b + exp = "# encoding: ASCII-8BIT\n# valid: true\n\"A\nB\"" + + assert_mu_pp_for_diff exp, str, :raw + end + + def test_mu_pp_for_diff_str_encoding_both + str = "A\\n\nB".b + exp = "# encoding: ASCII-8BIT\n# valid: true\n\"A\\\\n\\nB\"" + + assert_mu_pp_for_diff exp, str, :raw + end + + def test_mu_pp_for_diff_str_nerd + assert_mu_pp_for_diff "A\\nB\\\\nC", "A\nB\\nC" + assert_mu_pp_for_diff "\\nB\\\\nC", "\nB\\nC" + assert_mu_pp_for_diff "\\nB\\\\n", "\nB\\n" + assert_mu_pp_for_diff "\\n\\\\n", "\n\\n" + assert_mu_pp_for_diff "\\\\n\\n", "\\n\n" + assert_mu_pp_for_diff "\\\\nB\\n", "\\nB\n" + assert_mu_pp_for_diff "\\\\nB\\nC", "\\nB\nC" + assert_mu_pp_for_diff "A\\\\n\\nB", "A\\n\nB" + assert_mu_pp_for_diff "A\\n\\\\nB", "A\n\\nB" + assert_mu_pp_for_diff "\\\\n\\n", "\\n\n" + assert_mu_pp_for_diff "\\n\\\\n", "\n\\n" + end + + def test_mu_pp_for_diff_str_normal + assert_mu_pp_for_diff "", "" + assert_mu_pp_for_diff "A\\n\n", "A\\n" + assert_mu_pp_for_diff "A\\n\nB", "A\\nB" + assert_mu_pp_for_diff "A\n", "A\n" + assert_mu_pp_for_diff "A\nB", "A\nB" + assert_mu_pp_for_diff "\\n\n", "\\n" + assert_mu_pp_for_diff "\n", "\n" + assert_mu_pp_for_diff "\\n\nA", "\\nA" + assert_mu_pp_for_diff "\nA", "\nA" + end + + def test_mu_pp_str_bad_encoding + str = "\666".force_encoding Encoding::UTF_8 + exp = "# encoding: UTF-8\n# valid: false\n\"\\xB6\"" + + assert_mu_pp exp, str, :raw + end + + def test_mu_pp_str_encoding + str = "A\nB".b + exp = "# encoding: ASCII-8BIT\n# valid: true\n\"A\\nB\"" + + assert_mu_pp exp, str, :raw + end + + def test_mu_pp_str_immutable + printer = Class.new { extend Minitest::Assertions } + str = "test".freeze + assert_equal '"test"', printer.mu_pp(str) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_benchmark.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_benchmark.rb new file mode 100644 index 0000000..88abf77 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_benchmark.rb @@ -0,0 +1,137 @@ +require "minitest/autorun" +require "minitest/benchmark" + +## +# Used to verify data: +# http://www.wolframalpha.com/examples/RegressionAnalysis.html + +class TestMinitestBenchmark < Minitest::Test + def test_cls_bench_exp + assert_equal [2, 4, 8, 16, 32], Minitest::Benchmark.bench_exp(2, 32, 2) + end + + def test_cls_bench_linear + assert_equal [2, 4, 6, 8, 10], Minitest::Benchmark.bench_linear(2, 10, 2) + end + + def test_cls_runnable_methods + assert_equal [], Minitest::Benchmark.runnable_methods + + c = Class.new(Minitest::Benchmark) do + def bench_blah + end + end + + assert_equal ["bench_blah"], c.runnable_methods + end + + def test_cls_bench_range + assert_equal [1, 10, 100, 1_000, 10_000], Minitest::Benchmark.bench_range + end + + def test_fit_exponential_clean + x = [1.0, 2.0, 3.0, 4.0, 5.0] + y = x.map { |n| 1.1 * Math.exp(2.1 * n) } + + assert_fit :exponential, x, y, 1.0, 1.1, 2.1 + end + + def test_fit_exponential_noisy + x = [1.0, 1.9, 2.6, 3.4, 5.0] + y = [12, 10, 8.2, 6.9, 5.9] + + # verified with Numbers and R + assert_fit :exponential, x, y, 0.95, 13.81148, -0.1820 + end + + def test_fit_logarithmic_clean + x = [1.0, 2.0, 3.0, 4.0, 5.0] + y = x.map { |n| 1.1 + 2.1 * Math.log(n) } + + assert_fit :logarithmic, x, y, 1.0, 1.1, 2.1 + end + + def test_fit_logarithmic_noisy + x = [1.0, 2.0, 3.0, 4.0, 5.0] + # Generated with + # y = x.map { |n| jitter = 0.999 + 0.002 * rand; (Math.log(n) ) * jitter } + y = [0.0, 0.6935, 1.0995, 1.3873, 1.6097] + + assert_fit :logarithmic, x, y, 0.95, 0, 1 + end + + def test_fit_constant_clean + x = (1..5).to_a + y = [5.0, 5.0, 5.0, 5.0, 5.0] + + assert_fit :linear, x, y, nil, 5.0, 0 + end + + def test_fit_constant_noisy + x = (1..5).to_a + y = [1.0, 1.2, 1.0, 0.8, 1.0] + + # verified in numbers and R + assert_fit :linear, x, y, nil, 1.12, -0.04 + end + + def test_fit_linear_clean + # y = m * x + b where m = 2.2, b = 3.1 + x = (1..5).to_a + y = x.map { |n| 2.2 * n + 3.1 } + + assert_fit :linear, x, y, 1.0, 3.1, 2.2 + end + + def test_fit_linear_noisy + x = [ 60, 61, 62, 63, 65] + y = [3.1, 3.6, 3.8, 4.0, 4.1] + + # verified in numbers and R + assert_fit :linear, x, y, 0.8315, -7.9635, 0.1878 + end + + def test_fit_power_clean + # y = A x ** B, where B = b and A = e ** a + # if, A = 1, B = 2, then + + x = [1.0, 2.0, 3.0, 4.0, 5.0] + y = [1.0, 4.0, 9.0, 16.0, 25.0] + + assert_fit :power, x, y, 1.0, 1.0, 2.0 + end + + def test_fit_power_noisy + # from www.engr.uidaho.edu/thompson/courses/ME330/lecture/least_squares.html + x = [10, 12, 15, 17, 20, 22, 25, 27, 30, 32, 35] + y = [95, 105, 125, 141, 173, 200, 253, 298, 385, 459, 602] + + # verified in numbers + assert_fit :power, x, y, 0.90, 2.6217, 1.4556 + + # income to % of households below income amount + # http://library.wolfram.com/infocenter/Conferences/6461/PowerLaws.nb + x = [15_000, 25_000, 35_000, 50_000, 75_000, 100_000] + y = [0.154, 0.283, 0.402, 0.55, 0.733, 0.843] + + # verified in numbers + assert_fit :power, x, y, 0.96, 3.119e-5, 0.8959 + end + + def assert_fit msg, x, y, fit, exp_a, exp_b + bench = Minitest::Benchmark.new :blah + + a, b, rr = bench.send "fit_#{msg}", x, y + + assert_operator rr, :>=, fit if fit + assert_in_delta exp_a, a + assert_in_delta exp_b, b + end +end + +describe "my class Bench" do + klass = self + it "should provide bench methods" do + klass.must_respond_to :bench + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_mock.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_mock.rb new file mode 100644 index 0000000..561b1a5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_mock.rb @@ -0,0 +1,885 @@ +require "minitest/autorun" + +class TestMinitestMock < Minitest::Test + parallelize_me! + + def setup + @mock = Minitest::Mock.new.expect(:foo, nil) + @mock.expect(:meaning_of_life, 42) + end + + def test_create_stub_method + assert_nil @mock.foo + end + + def test_allow_return_value_specification + assert_equal 42, @mock.meaning_of_life + end + + def test_blow_up_if_not_called + @mock.foo + + util_verify_bad "expected meaning_of_life() => 42" + end + + def test_not_blow_up_if_everything_called + @mock.foo + @mock.meaning_of_life + + assert_mock @mock + end + + def test_allow_expectations_to_be_added_after_creation + @mock.expect(:bar, true) + assert @mock.bar + end + + def test_not_verify_if_new_expected_method_is_not_called + @mock.foo + @mock.meaning_of_life + @mock.expect(:bar, true) + + util_verify_bad "expected bar() => true" + end + + def test_blow_up_on_wrong_number_of_arguments + @mock.foo + @mock.meaning_of_life + @mock.expect(:sum, 3, [1, 2]) + + e = assert_raises ArgumentError do + @mock.sum + end + + assert_equal "mocked method :sum expects 2 arguments, got 0", e.message + end + + def test_return_mock_does_not_raise + retval = Minitest::Mock.new + mock = Minitest::Mock.new + mock.expect(:foo, retval) + mock.foo + + assert_mock mock + end + + def test_mock_args_does_not_raise + arg = Minitest::Mock.new + mock = Minitest::Mock.new + mock.expect(:foo, nil, [arg]) + mock.foo(arg) + + assert_mock mock + end + + def test_set_expectation_on_special_methods + mock = Minitest::Mock.new + + mock.expect :object_id, "received object_id" + assert_equal "received object_id", mock.object_id + + mock.expect :respond_to_missing?, "received respond_to_missing?" + assert_equal "received respond_to_missing?", mock.respond_to_missing? + + mock.expect :===, "received ===" + assert_equal "received ===", mock.=== + + mock.expect :inspect, "received inspect" + assert_equal "received inspect", mock.inspect + + mock.expect :to_s, "received to_s" + assert_equal "received to_s", mock.to_s + + mock.expect :public_send, "received public_send" + assert_equal "received public_send", mock.public_send + + mock.expect :send, "received send" + assert_equal "received send", mock.send + + assert_mock mock + end + + def test_expectations_can_be_satisfied_via_send + @mock.send :foo + @mock.send :meaning_of_life + + assert_mock @mock + end + + def test_expectations_can_be_satisfied_via_public_send + skip "Doesn't run on 1.8" if RUBY_VERSION < "1.9" + + @mock.public_send :foo + @mock.public_send :meaning_of_life + + assert_mock @mock + end + + def test_blow_up_on_wrong_arguments + @mock.foo + @mock.meaning_of_life + @mock.expect(:sum, 3, [1, 2]) + + e = assert_raises MockExpectationError do + @mock.sum(2, 4) + end + + exp = "mocked method :sum called with unexpected arguments [2, 4]" + assert_equal exp, e.message + end + + def test_expect_with_non_array_args + e = assert_raises ArgumentError do + @mock.expect :blah, 3, false + end + + assert_match "args must be an array", e.message + end + + def test_respond_appropriately + assert @mock.respond_to?(:foo) + assert @mock.respond_to?(:foo, true) + assert @mock.respond_to?("foo") + assert !@mock.respond_to?(:bar) + end + + def test_no_method_error_on_unexpected_methods + e = assert_raises NoMethodError do + @mock.bar + end + + expected = "unmocked method :bar, expected one of [:foo, :meaning_of_life]" + + assert_match expected, e.message + end + + def test_assign_per_mock_return_values + a = Minitest::Mock.new + b = Minitest::Mock.new + + a.expect(:foo, :a) + b.expect(:foo, :b) + + assert_equal :a, a.foo + assert_equal :b, b.foo + end + + def test_do_not_create_stub_method_on_new_mocks + a = Minitest::Mock.new + a.expect(:foo, :a) + + assert !Minitest::Mock.new.respond_to?(:foo) + end + + def test_mock_is_a_blank_slate + @mock.expect :kind_of?, true, [String] + @mock.expect :==, true, [1] + + assert @mock.kind_of?(String), "didn't mock :kind_of\?" + assert @mock == 1, "didn't mock :==" + end + + def test_verify_allows_called_args_to_be_loosely_specified + mock = Minitest::Mock.new + mock.expect :loose_expectation, true, [Integer] + mock.loose_expectation 1 + + assert_mock mock + end + + def test_verify_raises_with_strict_args + mock = Minitest::Mock.new + mock.expect :strict_expectation, true, [2] + + e = assert_raises MockExpectationError do + mock.strict_expectation 1 + end + + exp = "mocked method :strict_expectation called with unexpected arguments [1]" + assert_equal exp, e.message + end + + def test_method_missing_empty + mock = Minitest::Mock.new + + mock.expect :a, nil + + mock.a + + e = assert_raises MockExpectationError do + mock.a + end + + assert_equal "No more expects available for :a: []", e.message + end + + def test_same_method_expects_are_verified_when_all_called + mock = Minitest::Mock.new + mock.expect :foo, nil, [:bar] + mock.expect :foo, nil, [:baz] + + mock.foo :bar + mock.foo :baz + + assert_mock mock + end + + def test_same_method_expects_blow_up_when_not_all_called + mock = Minitest::Mock.new + mock.expect :foo, nil, [:bar] + mock.expect :foo, nil, [:baz] + + mock.foo :bar + + e = assert_raises(MockExpectationError) { mock.verify } + + exp = "expected foo(:baz) => nil, got [foo(:bar) => nil]" + + assert_equal exp, e.message + end + + def test_same_method_expects_with_same_args_blow_up_when_not_all_called + mock = Minitest::Mock.new + mock.expect :foo, nil, [:bar] + mock.expect :foo, nil, [:bar] + + mock.foo :bar + + e = assert_raises(MockExpectationError) { mock.verify } + + exp = "expected foo(:bar) => nil, got [foo(:bar) => nil]" + + assert_equal exp, e.message + end + + def test_verify_passes_when_mock_block_returns_true + mock = Minitest::Mock.new + mock.expect :foo, nil do + true + end + + mock.foo + + assert_mock mock + end + + def test_mock_block_is_passed_function_params + arg1, arg2, arg3 = :bar, [1, 2, 3], { :a => "a" } + mock = Minitest::Mock.new + mock.expect :foo, nil do |a1, a2, a3| + a1 == arg1 && a2 == arg2 && a3 == arg3 + end + + mock.foo arg1, arg2, arg3 + + assert_mock mock + end + + def test_mock_block_is_passed_function_block + mock = Minitest::Mock.new + block = proc { "bar" } + mock.expect :foo, nil do |arg, &blk| + arg == "foo" && + blk == block + end + mock.foo "foo", &block + assert_mock mock + end + + def test_verify_fails_when_mock_block_returns_false + mock = Minitest::Mock.new + mock.expect :foo, nil do + false + end + + e = assert_raises(MockExpectationError) { mock.foo } + exp = "mocked method :foo failed block w/ []" + + assert_equal exp, e.message + end + + def test_mock_block_throws_if_args_passed + mock = Minitest::Mock.new + + e = assert_raises(ArgumentError) do + mock.expect :foo, nil, [:a, :b, :c] do + true + end + end + + exp = "args ignored when block given" + + assert_match exp, e.message + end + + def test_mock_returns_retval_when_called_with_block + mock = Minitest::Mock.new + mock.expect(:foo, 32) do + true + end + + rs = mock.foo + + assert_equal rs, 32 + end + + def util_verify_bad exp + e = assert_raises MockExpectationError do + @mock.verify + end + + assert_equal exp, e.message + end + + def test_mock_called_via_send + mock = Minitest::Mock.new + mock.expect(:foo, true) + + mock.send :foo + assert_mock mock + end + + def test_mock_called_via___send__ + mock = Minitest::Mock.new + mock.expect(:foo, true) + + mock.__send__ :foo + assert_mock mock + end + + def test_mock_called_via_send_with_args + mock = Minitest::Mock.new + mock.expect(:foo, true, [1, 2, 3]) + + mock.send(:foo, 1, 2, 3) + assert_mock mock + end + +end + +require "minitest/metametameta" + +class TestMinitestStub < Minitest::Test + # Do not parallelize since we're calling stub on class methods + + def setup + super + Minitest::Test.reset + + @tc = Minitest::Test.new "fake tc" + @assertion_count = 1 + end + + def teardown + super + assert_equal @assertion_count, @tc.assertions if self.passed? + end + + class Time + def self.now + 24 + end + end + + def assert_stub val_or_callable + @assertion_count += 1 + + t = Time.now.to_i + + Time.stub :now, val_or_callable do + @tc.assert_equal 42, Time.now + end + + @tc.assert_operator Time.now.to_i, :>=, t + end + + def test_stub_private_module_method + @assertion_count += 1 + + t0 = Time.now + + self.stub :sleep, nil do + @tc.assert_nil sleep(10) + end + + @tc.assert_operator Time.now - t0, :<=, 1 + end + + def test_stub_private_module_method_indirect + @assertion_count += 1 + + fail_clapper = Class.new do + def fail_clap + raise + :clap + end + end.new + + fail_clapper.stub :raise, nil do |safe_clapper| + @tc.assert_equal :clap, safe_clapper.fail_clap # either form works + @tc.assert_equal :clap, fail_clapper.fail_clap # yay closures + end + end + + def test_stub_public_module_method + Math.stub :log10, :stubbed do + @tc.assert_equal :stubbed, Math.log10(1000) + end + end + + def test_stub_value + assert_stub 42 + end + + def test_stub_block + assert_stub lambda { 42 } + end + + def test_stub_block_args + @assertion_count += 1 + + t = Time.now.to_i + + Time.stub :now, lambda { |n| n * 2 } do + @tc.assert_equal 42, Time.now(21) + end + + @tc.assert_operator Time.now.to_i, :>=, t + end + + def test_stub_callable + obj = Object.new + + def obj.call + 42 + end + + assert_stub obj + end + + def test_stub_yield_self + obj = "foo" + + val = obj.stub :to_s, "bar" do |s| + s.to_s + end + + @tc.assert_equal "bar", val + end + + def test_dynamic_method + @assertion_count = 2 + + dynamic = Class.new do + def self.respond_to? meth + meth == :found + end + + def self.method_missing meth, *args, &block + if meth == :found + false + else + super + end + end + end + + val = dynamic.stub(:found, true) do |s| + s.found + end + + @tc.assert_equal true, val + @tc.assert_equal false, dynamic.found + end + + def test_stub_NameError + e = @tc.assert_raises NameError do + Time.stub :nope_nope_nope, 42 do + # do nothing + end + end + + exp = jruby? ? /Undefined method nope_nope_nope for '#{self.class}::Time'/ : + /undefined method `nope_nope_nope' for( class)? `#{self.class}::Time'/ + assert_match exp, e.message + end + + def test_mock_with_yield + mock = Minitest::Mock.new + mock.expect(:write, true) do + true + end + rs = nil + + File.stub :open, true, mock do + File.open "foo.txt", "r" do |f| + rs = f.write + end + end + @tc.assert_equal true, rs + end + + alias test_stub_value__old test_stub_value # TODO: remove/rename + + ## Permutation Sets: + + # [:value, :lambda] + # [:*, :block, :block_call] + # [:**, :block_args] + # + # Where: + # + # :value = a normal value + # :lambda = callable or lambda + # :* = no block + # :block = normal block + # :block_call = :lambda invokes the block (N/A for :value) + # :** = no args + # :args = args passed to stub + + ## Permutations + + # [:call, :*, :**] =>5 callable+block FIX: CALL BOTH (bug) + # [:call, :*, :**] =>6 callable + + # [:lambda, :*, :**] => lambda result + + # [:lambda, :*, :args] => lambda result NO ARGS + + # [:lambda, :block, :**] =>5 lambda result FIX: CALL BOTH (bug) + # [:lambda, :block, :**] =>6 lambda result + + # [:lambda, :block, :args] =>5 lambda result FIX: CALL BOTH (bug) + # [:lambda, :block, :args] =>6 lambda result + # [:lambda, :block, :args] =>7 raise ArgumentError + + # [:lambda, :block_call, :**] =>5 lambda FIX: BUG!-not passed block to lambda + # [:lambda, :block_call, :**] =>6 lambda+block result + + # [:lambda, :block_call, :args] =>5 lambda FIX: BUG!-not passed block to lambda + # [:lambda, :block_call, :args] =>6 lambda+block result + + # [:value, :*, :**] => value + + # [:value, :*, :args] => value, ignore args + + # [:value, :block, :**] =>5 value, call block + # [:value, :block, :**] =>6 value + + # [:value, :block, :args] =>5 value, call block w/ args + # [:value, :block, :args] =>6 value, call block w/ args, deprecated + # [:value, :block, :args] =>7 raise ArgumentError + + # [:value, :block_call, :**] => N/A + + # [:value, :block_call, :args] => N/A + + class Bar + def call + puts "hi" + end + end + + class Foo + def self.blocking + yield + end + end + + class Thingy + def self.identity arg + arg + end + end + + class Keywords + def self.args req, kw1:, kw2:24 + [req, kw1, kw2] + end + end + + def test_stub_callable_keyword_args + Keywords.stub :args, ->(*args, **kws) { [args, kws] } do + @tc.assert_equal [["woot"], { kw1: 42 }], Keywords.args("woot", kw1: 42) + end + end + + def test_stub_callable_block_5 # from tenderlove + @assertion_count += 1 + Foo.stub5 :blocking, Bar.new do + @tc.assert_output "hi\n", "" do + Foo.blocking do + @tc.flunk "shouldn't ever hit this" + end + end + end + end + + def test_stub_callable_block_6 # from tenderlove + skip_stub6 + + @assertion_count += 1 + Foo.stub6 :blocking, Bar.new do + @tc.assert_output "hi\n", "" do + Foo.blocking do + @tc.flunk "shouldn't ever hit this" + end + end + end + end + + def test_stub_lambda + Thread.stub :new, lambda { 21+21 } do + @tc.assert_equal 42, Thread.new + end + end + + def test_stub_lambda_args + Thread.stub :new, lambda { 21+21 }, :wtf do + @tc.assert_equal 42, Thread.new + end + end + + def test_stub_lambda_block_5 + Thread.stub5 :new, lambda { 21+21 } do + result = Thread.new do + @tc.flunk "shouldn't ever hit this" + end + @tc.assert_equal 42, result + end + end + + def test_stub_lambda_block_6 + skip_stub6 + + Thread.stub6 :new, lambda { 21+21 } do + result = Thread.new do + @tc.flunk "shouldn't ever hit this" + end + @tc.assert_equal 42, result + end + end + + def test_stub_lambda_block_args_5 + @assertion_count += 1 + Thingy.stub5 :identity, lambda { |y| @tc.assert_equal :nope, y; 21+21 }, :WTF? do + result = Thingy.identity :nope do |x| + @tc.flunk "shouldn't reach this" + end + @tc.assert_equal 42, result + end + end + + def test_stub_lambda_block_args_6 + skip_stub6 + + @assertion_count += 1 + Thingy.stub6 :identity, lambda { |y| @tc.assert_equal :nope, y; 21+21 }, :WTF? do + result = Thingy.identity :nope do |x| + @tc.flunk "shouldn't reach this" + end + @tc.assert_equal 42, result + end + end + + def test_stub_lambda_block_args_6_2 + skip_stub6 + + @tc.assert_raises ArgumentError do + Thingy.stub6_2 :identity, lambda { |y| :__not_run__ }, :WTF? do + # doesn't matter + end + end + end + + def test_stub_lambda_block_call_5 + @assertion_count += 1 + rs = nil + io = StringIO.new "", "w" + File.stub5 :open, lambda { |p, m, &blk| blk and blk.call io } do + File.open "foo.txt", "r" do |f| + rs = f && f.write("woot") + end + end + @tc.assert_equal 4, rs + @tc.assert_equal "woot", io.string + end + + def test_stub_lambda_block_call_6 + skip_stub6 + + @assertion_count += 1 + rs = nil + io = StringIO.new "", "w" + File.stub6 :open, lambda { |p, m, &blk| blk.call io } do + File.open "foo.txt", "r" do |f| + rs = f.write("woot") + end + end + @tc.assert_equal 4, rs + @tc.assert_equal "woot", io.string + end + + def test_stub_lambda_block_call_args_5 + @assertion_count += 1 + rs = nil + io = StringIO.new "", "w" + File.stub5(:open, lambda { |p, m, &blk| blk and blk.call io }, :WTF?) do + File.open "foo.txt", "r" do |f| + rs = f.write("woot") + end + end + @tc.assert_equal 4, rs + @tc.assert_equal "woot", io.string + end + + def test_stub_lambda_block_call_args_6 + skip_stub6 + + @assertion_count += 1 + rs = nil + io = StringIO.new "", "w" + File.stub6(:open, lambda { |p, m, &blk| blk.call io }, :WTF?) do + File.open "foo.txt", "r" do |f| + rs = f.write("woot") + end + end + @tc.assert_equal 4, rs + @tc.assert_equal "woot", io.string + end + + def test_stub_lambda_block_call_args_6_2 + skip_stub6 + + @assertion_count += 2 + rs = nil + io = StringIO.new "", "w" + @tc.assert_raises ArgumentError do + File.stub6_2(:open, lambda { |p, m, &blk| blk.call io }, :WTF?) do + File.open "foo.txt", "r" do |f| + rs = f.write("woot") + end + end + end + @tc.assert_nil rs + @tc.assert_equal "", io.string + end + + def test_stub_value + Thread.stub :new, 42 do + result = Thread.new + @tc.assert_equal 42, result + end + end + + def test_stub_value_args + Thread.stub :new, 42, :WTF? do + result = Thread.new + @tc.assert_equal 42, result + end + end + + def test_stub_value_block_5 + @assertion_count += 1 + Thread.stub5 :new, 42 do + result = Thread.new do + @tc.assert true + end + @tc.assert_equal 42, result + end + end + + def test_stub_value_block_6 + skip_stub6 + + Thread.stub6 :new, 42 do + result = Thread.new do + @tc.flunk "shouldn't hit this" + end + @tc.assert_equal 42, result + end + end + + def test_stub_value_block_args_5 + @assertion_count += 2 + rs = nil + io = StringIO.new "", "w" + File.stub5 :open, :value, io do + result = File.open "foo.txt", "r" do |f| + rs = f.write("woot") + end + @tc.assert_equal :value, result + end + @tc.assert_equal 4, rs + @tc.assert_equal "woot", io.string + end + + def test_stub_value_block_args_5__break_if_not_passed + e = @tc.assert_raises NoMethodError do + File.stub5 :open, :return_value do # intentionally bad setup w/ no args + File.open "foo.txt", "r" do |f| + f.write "woot" + end + end + end + exp = "undefined method `write' for nil:NilClass" + assert_match exp, e.message + end + + def test_stub_value_block_args_6 + skip_stub6 + + @assertion_count += 2 + rs = nil + io = StringIO.new "", "w" + assert_deprecated do + File.stub6 :open, :value, io do + result = File.open "foo.txt", "r" do |f| + rs = f.write("woot") + end + @tc.assert_equal :value, result + end + end + @tc.assert_equal 4, rs + @tc.assert_equal "woot", io.string + end + + def test_stub_value_block_args_6_2 + skip_stub6 + + @assertion_count += 2 + rs = nil + io = StringIO.new "", "w" + @tc.assert_raises ArgumentError do + File.stub6_2 :open, :value, io do + result = File.open "foo.txt", "r" do |f| + @tc.flunk "shouldn't hit this" + end + @tc.assert_equal :value, result + end + end + @tc.assert_nil rs + @tc.assert_equal "", io.string + end + + def assert_deprecated re = /deprecated/ + assert_output "", re do + yield + end + end + + def skip_stub6 + skip "not yet" unless STUB6 + end +end + +STUB6 = ENV["STUB6"] + +if STUB6 then + require "minitest/mock6" if STUB6 +else + class Object + alias stub5 stub + alias stub6 stub + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_reporter.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_reporter.rb new file mode 100644 index 0000000..53d9588 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_reporter.rb @@ -0,0 +1,311 @@ +require "minitest/autorun" +require "minitest/metametameta" +require "forwardable" + +class Runnable + def woot + assert true + end +end + +class TestMinitestReporter < MetaMetaMetaTestCase + + attr_accessor :r, :io + + def new_composite_reporter + # Ruby bug in older versions of 2.2 & 2.3 on all platforms + # Latest Windows builds were 2.2.6 and 2.3.3. Latest Ruby releases were + # 2.2.10 and 2.3.8. + skip if windows? && RUBY_VERSION < '2.4' + reporter = Minitest::CompositeReporter.new + reporter << Minitest::SummaryReporter.new(self.io) + reporter << Minitest::ProgressReporter.new(self.io) + + # eg reporter.results -> reporters.first.results + reporter.extend Forwardable + reporter.delegate :first => :reporters + reporter.delegate %i[results count assertions options to_s] => :first + + reporter + end + + def setup + self.io = StringIO.new("") + self.r = new_composite_reporter + end + + def error_test + unless defined? @et then + @et = Minitest::Test.new(:woot) + @et.failures << Minitest::UnexpectedError.new(begin + raise "no" + rescue => e + e + end) + @et = Minitest::Result.from @et + end + @et + end + + def fail_test + unless defined? @ft then + @ft = Minitest::Test.new(:woot) + @ft.failures << begin + raise Minitest::Assertion, "boo" + rescue Minitest::Assertion => e + e + end + @ft = Minitest::Result.from @ft + end + @ft + end + + def passing_test + @pt ||= Minitest::Result.from Minitest::Test.new(:woot) + end + + def skip_test + unless defined? @st then + @st = Minitest::Test.new(:woot) + @st.failures << begin + raise Minitest::Skip + rescue Minitest::Assertion => e + e + end + @st = Minitest::Result.from @st + end + @st + end + + def test_to_s + r.record passing_test + r.record fail_test + assert_match "woot", r.to_s + end + + def test_options_skip_F + r.options[:skip] = "F" + + r.record passing_test + r.record fail_test + + refute_match "woot", r.to_s + end + + def test_options_skip_E + r.options[:skip] = "E" + + r.record passing_test + r.record error_test + + refute_match "RuntimeError: no", r.to_s + end + + def test_passed_eh_empty + assert_predicate r, :passed? + end + + def test_passed_eh_failure + r.results << fail_test + + refute_predicate r, :passed? + end + + SKIP_MSG = "\n\nYou have skipped tests. Run with --verbose for details." + + def test_passed_eh_error + r.start + + r.results << error_test + + refute_predicate r, :passed? + + r.report + + refute_match SKIP_MSG, io.string + end + + def test_passed_eh_skipped + r.start + r.results << skip_test + assert r.passed? + + restore_env do + r.report + end + + assert_match SKIP_MSG, io.string + end + + def test_passed_eh_skipped_verbose + r.options[:verbose] = true + + r.start + r.results << skip_test + assert r.passed? + r.report + + refute_match SKIP_MSG, io.string + end + + def test_start + r.start + + exp = "Run options: \n\n# Running:\n\n" + + assert_equal exp, io.string + end + + def test_record_pass + r.record passing_test + + assert_equal ".", io.string + assert_empty r.results + assert_equal 1, r.count + assert_equal 0, r.assertions + end + + def test_record_fail + fail_test = self.fail_test + r.record fail_test + + assert_equal "F", io.string + assert_equal [fail_test], r.results + assert_equal 1, r.count + assert_equal 0, r.assertions + end + + def test_record_error + error_test = self.error_test + r.record error_test + + assert_equal "E", io.string + assert_equal [error_test], r.results + assert_equal 1, r.count + assert_equal 0, r.assertions + end + + def test_record_skip + skip_test = self.skip_test + r.record skip_test + + assert_equal "S", io.string + assert_equal [skip_test], r.results + assert_equal 1, r.count + assert_equal 0, r.assertions + end + + def test_report_empty + r.start + r.report + + exp = clean <<-EOM + Run options: + + # Running: + + + + Finished in 0.00 + + 0 runs, 0 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_equal exp, normalize_output(io.string) + end + + def test_report_passing + r.start + r.record passing_test + r.report + + exp = clean <<-EOM + Run options: + + # Running: + + . + + Finished in 0.00 + + 1 runs, 0 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_equal exp, normalize_output(io.string) + end + + def test_report_failure + r.start + r.record fail_test + r.report + + exp = clean <<-EOM + Run options: + + # Running: + + F + + Finished in 0.00 + + 1) Failure: + Minitest::Test#woot [FILE:LINE]: + boo + + 1 runs, 0 assertions, 1 failures, 0 errors, 0 skips + EOM + + assert_equal exp, normalize_output(io.string) + end + + def test_report_error + r.start + r.record error_test + r.report + + exp = clean <<-EOM + Run options: + + # Running: + + E + + Finished in 0.00 + + 1) Error: + Minitest::Test#woot: + RuntimeError: no + FILE:LINE:in `error_test' + FILE:LINE:in `test_report_error' + + 1 runs, 0 assertions, 0 failures, 1 errors, 0 skips + EOM + + assert_equal exp, normalize_output(io.string) + end + + def test_report_skipped + r.start + r.record skip_test + + restore_env do + r.report + end + + exp = clean <<-EOM + Run options: + + # Running: + + S + + Finished in 0.00 + + 1 runs, 0 assertions, 0 failures, 0 errors, 1 skips + + You have skipped tests. Run with --verbose for details. + EOM + + assert_equal exp, normalize_output(io.string) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_spec.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_spec.rb new file mode 100644 index 0000000..201427d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_spec.rb @@ -0,0 +1,1062 @@ +# encoding: utf-8 +require "minitest/metametameta" +require "stringio" + +class MiniSpecA < Minitest::Spec; end +class MiniSpecB < Minitest::Test; extend Minitest::Spec::DSL; end +class MiniSpecC < MiniSpecB; end +class NamedExampleA < MiniSpecA; end +class NamedExampleB < MiniSpecB; end +class NamedExampleC < MiniSpecC; end +class ExampleA; end +class ExampleB < ExampleA; end + +describe Minitest::Spec do + # helps to deal with 2.4 deprecation of Fixnum for Integer + Int = 1.class + + # do not parallelize this suite... it just can"t handle it. + + def assert_triggered expected = "blah", klass = Minitest::Assertion + @assertion_count += 1 + + e = assert_raises(klass) do + yield + end + + msg = e.message.sub(/(---Backtrace---).*/m, '\1') + msg.gsub!(/\(oid=[-0-9]+\)/, "(oid=N)") + msg.gsub!(/(\d\.\d{6})\d+/, '\1xxx') # normalize: ruby version, impl, platform + msg.gsub!(/:0x[Xa-fA-F0-9]{4,}[ @].+?>/, ":0xXXXXXX@PATH>") + + if expected + @assertion_count += 1 + case expected + when String then + assert_equal expected, msg + when Regexp then + @assertion_count += 1 + assert_match expected, msg + else + flunk "Unknown: #{expected.inspect}" + end + end + end + + def assert_success spec + assert_equal true, spec + end + + before do + @assertion_count = 4 + end + + after do + _(self.assertions).must_equal @assertion_count if passed? and not skipped? + end + + it "needs to be able to catch a Minitest::Assertion exception" do + @assertion_count = 1 + + assert_triggered "Expected 1 to not be equal to 1." do + _(1).wont_equal 1 + end + end + + it "needs to check for file existence" do + @assertion_count = 3 + + assert_success _(__FILE__).path_must_exist + + assert_triggered "Expected path 'blah' to exist." do + _("blah").path_must_exist + end + end + + it "needs to check for file non-existence" do + @assertion_count = 3 + + assert_success _("blah").path_wont_exist + + assert_triggered "Expected path '#{__FILE__}' to not exist." do + _(__FILE__).path_wont_exist + end + end + + it "needs to be sensible about must_include order" do + @assertion_count += 3 # must_include is 2 assertions + + assert_success _([1, 2, 3]).must_include(2) + + assert_triggered "Expected [1, 2, 3] to include 5." do + _([1, 2, 3]).must_include 5 + end + + assert_triggered "msg.\nExpected [1, 2, 3] to include 5." do + _([1, 2, 3]).must_include 5, "msg" + end + end + + it "needs to be sensible about wont_include order" do + @assertion_count += 3 # wont_include is 2 assertions + + assert_success _([1, 2, 3]).wont_include(5) + + assert_triggered "Expected [1, 2, 3] to not include 2." do + _([1, 2, 3]).wont_include 2 + end + + assert_triggered "msg.\nExpected [1, 2, 3] to not include 2." do + _([1, 2, 3]).wont_include 2, "msg" + end + end + + it "needs to catch an expected exception" do + @assertion_count = 2 + + expect { raise "blah" }.must_raise RuntimeError + expect { raise Minitest::Assertion }.must_raise Minitest::Assertion + end + + it "needs to catch an unexpected exception" do + @assertion_count -= 2 # no positive + + msg = <<-EOM.gsub(/^ {6}/, "").chomp + [RuntimeError] exception expected, not + Class: + Message: <"woot"> + ---Backtrace--- + EOM + + assert_triggered msg do + expect { raise StandardError, "woot" }.must_raise RuntimeError + end + + assert_triggered "msg.\n#{msg}" do + expect { raise StandardError, "woot" }.must_raise RuntimeError, "msg" + end + end + + it "needs to ensure silence" do + @assertion_count -= 1 # no msg + @assertion_count += 2 # assert_output is 2 assertions + + assert_success expect {}.must_be_silent + + assert_triggered "In stdout.\nExpected: \"\"\n Actual: \"xxx\"" do + expect { print "xxx" }.must_be_silent + end + end + + it "needs to have all methods named well" do + skip "N/A" if ENV["MT_NO_EXPECTATIONS"] + + @assertion_count = 2 + + methods = Minitest::Expectations.public_instance_methods.grep(/must|wont/) + methods.map!(&:to_s) if Symbol === methods.first + + musts, wonts = methods.sort.partition { |m| m =~ /must/ } + + expected_musts = %w[must_be + must_be_close_to + must_be_empty + must_be_instance_of + must_be_kind_of + must_be_nil + must_be_same_as + must_be_silent + must_be_within_delta + must_be_within_epsilon + must_equal + must_include + must_match + must_output + must_raise + must_respond_to + must_throw + path_must_exist] + + bad = %w[not raise throw send output be_silent] + + expected_wonts = expected_musts.map { |m| m.sub(/must/, "wont") }.sort + expected_wonts.reject! { |m| m =~ /wont_#{Regexp.union(*bad)}/ } + + _(musts).must_equal expected_musts + _(wonts).must_equal expected_wonts + end + + it "needs to raise if an expected exception is not raised" do + @assertion_count -= 2 # no positive test + + assert_triggered "RuntimeError expected but nothing was raised." do + expect { 42 }.must_raise RuntimeError + end + + assert_triggered "msg.\nRuntimeError expected but nothing was raised." do + expect { 42 }.must_raise RuntimeError, "msg" + end + end + + it "needs to verify binary messages" do + assert_success _(42).wont_be(:<, 24) + + assert_triggered "Expected 24 to not be < 42." do + _(24).wont_be :<, 42 + end + + assert_triggered "msg.\nExpected 24 to not be < 42." do + _(24).wont_be :<, 42, "msg" + end + end + + it "needs to verify emptyness" do + @assertion_count += 3 # empty is 2 assertions + + assert_success _([]).must_be_empty + + assert_triggered "Expected [42] to be empty." do + _([42]).must_be_empty + end + + assert_triggered "msg.\nExpected [42] to be empty." do + _([42]).must_be_empty "msg" + end + end + + it "needs to verify equality" do + @assertion_count += 1 + + assert_success _(6 * 7).must_equal(42) + + assert_triggered "Expected: 42\n Actual: 54" do + _(6 * 9).must_equal 42 + end + + assert_triggered "msg.\nExpected: 42\n Actual: 54" do + _(6 * 9).must_equal 42, "msg" + end + + assert_triggered(/^-42\n\+#\n/) do + _(proc { 42 }).must_equal 42 # proc isn't called, so expectation fails + end + end + + it "needs to warn on equality with nil" do + @assertion_count += 1 # extra test + + out, err = capture_io do + assert_success _(nil).must_equal(nil) + end + + exp = "DEPRECATED: Use assert_nil if expecting nil from #{__FILE__}:#{__LINE__-3}. " \ + "This will fail in Minitest 6.\n" + exp = "" if $-w.nil? + + assert_empty out + assert_equal exp, err + end + + it "needs to verify floats outside a delta" do + @assertion_count += 1 # extra test + + assert_success _(24).wont_be_close_to(42) + + assert_triggered "Expected |42 - 42.0| (0.0) to not be <= 0.001." do + _(6 * 7.0).wont_be_close_to 42 + end + + x = "1.0e-05" + assert_triggered "Expected |42 - 42.0| (0.0) to not be <= #{x}." do + _(6 * 7.0).wont_be_close_to 42, 0.00001 + end + + assert_triggered "msg.\nExpected |42 - 42.0| (0.0) to not be <= #{x}." do + _(6 * 7.0).wont_be_close_to 42, 0.00001, "msg" + end + end + + it "needs to verify floats outside an epsilon" do + @assertion_count += 1 # extra test + + assert_success _(24).wont_be_within_epsilon(42) + + x = "0.042" + assert_triggered "Expected |42 - 42.0| (0.0) to not be <= #{x}." do + _(6 * 7.0).wont_be_within_epsilon 42 + end + + x = "0.00042" + assert_triggered "Expected |42 - 42.0| (0.0) to not be <= #{x}." do + _(6 * 7.0).wont_be_within_epsilon 42, 0.00001 + end + + assert_triggered "msg.\nExpected |42 - 42.0| (0.0) to not be <= #{x}." do + _(6 * 7.0).wont_be_within_epsilon 42, 0.00001, "msg" + end + end + + it "needs to verify floats within a delta" do + @assertion_count += 1 # extra test + + assert_success _(6.0 * 7).must_be_close_to(42.0) + + assert_triggered "Expected |0.0 - 0.01| (0.01) to be <= 0.001." do + _(1.0 / 100).must_be_close_to 0.0 + end + + x = "1.0e-06" + assert_triggered "Expected |0.0 - 0.001| (0.001) to be <= #{x}." do + _(1.0 / 1000).must_be_close_to 0.0, 0.000001 + end + + assert_triggered "msg.\nExpected |0.0 - 0.001| (0.001) to be <= #{x}." do + _(1.0 / 1000).must_be_close_to 0.0, 0.000001, "msg" + end + end + + it "needs to verify floats within an epsilon" do + @assertion_count += 1 # extra test + + assert_success _(6.0 * 7).must_be_within_epsilon(42.0) + + assert_triggered "Expected |0.0 - 0.01| (0.01) to be <= 0.0." do + _(1.0 / 100).must_be_within_epsilon 0.0 + end + + assert_triggered "Expected |0.0 - 0.001| (0.001) to be <= 0.0." do + _(1.0 / 1000).must_be_within_epsilon 0.0, 0.000001 + end + + assert_triggered "msg.\nExpected |0.0 - 0.001| (0.001) to be <= 0.0." do + _(1.0 / 1000).must_be_within_epsilon 0.0, 0.000001, "msg" + end + end + + it "needs to verify identity" do + assert_success _(1).must_be_same_as(1) + + assert_triggered "Expected 1 (oid=N) to be the same as 2 (oid=N)." do + _(1).must_be_same_as 2 + end + + assert_triggered "msg.\nExpected 1 (oid=N) to be the same as 2 (oid=N)." do + _(1).must_be_same_as 2, "msg" + end + end + + it "needs to verify inequality" do + @assertion_count += 2 + assert_success _(42).wont_equal(6 * 9) + assert_success _(proc {}).wont_equal(42) + + assert_triggered "Expected 1 to not be equal to 1." do + _(1).wont_equal 1 + end + + assert_triggered "msg.\nExpected 1 to not be equal to 1." do + _(1).wont_equal 1, "msg" + end + end + + it "needs to verify instances of a class" do + assert_success _(42).wont_be_instance_of(String) + + assert_triggered "Expected 42 to not be a kind of #{Int.name}." do + _(42).wont_be_kind_of Int + end + + assert_triggered "msg.\nExpected 42 to not be an instance of #{Int.name}." do + _(42).wont_be_instance_of Int, "msg" + end + end + + it "needs to verify kinds of a class" do + @assertion_count += 2 + + assert_success _(42).wont_be_kind_of(String) + assert_success _(proc {}).wont_be_kind_of(String) + + assert_triggered "Expected 42 to not be a kind of #{Int.name}." do + _(42).wont_be_kind_of Int + end + + assert_triggered "msg.\nExpected 42 to not be a kind of #{Int.name}." do + _(42).wont_be_kind_of Int, "msg" + end + end + + it "needs to verify kinds of objects" do + @assertion_count += 3 # extra test + + assert_success _(6 * 7).must_be_kind_of(Int) + assert_success _(6 * 7).must_be_kind_of(Numeric) + + assert_triggered "Expected 42 to be a kind of String, not #{Int.name}." do + _(6 * 7).must_be_kind_of String + end + + assert_triggered "msg.\nExpected 42 to be a kind of String, not #{Int.name}." do + _(6 * 7).must_be_kind_of String, "msg" + end + + exp = "Expected # to be a kind of String, not Proc." + assert_triggered exp do + _(proc {}).must_be_kind_of String + end + end + + it "needs to verify mismatch" do + @assertion_count += 3 # match is 2 + + assert_success _("blah").wont_match(/\d+/) + + assert_triggered "Expected /\\w+/ to not match \"blah\"." do + _("blah").wont_match(/\w+/) + end + + assert_triggered "msg.\nExpected /\\w+/ to not match \"blah\"." do + _("blah").wont_match(/\w+/, "msg") + end + end + + it "needs to verify nil" do + assert_success _(nil).must_be_nil + + assert_triggered "Expected 42 to be nil." do + _(42).must_be_nil + end + + assert_triggered "msg.\nExpected 42 to be nil." do + _(42).must_be_nil "msg" + end + end + + it "needs to verify non-emptyness" do + @assertion_count += 3 # empty is 2 assertions + + assert_success _(["some item"]).wont_be_empty + + assert_triggered "Expected [] to not be empty." do + _([]).wont_be_empty + end + + assert_triggered "msg.\nExpected [] to not be empty." do + _([]).wont_be_empty "msg" + end + end + + it "needs to verify non-identity" do + assert_success _(1).wont_be_same_as(2) + + assert_triggered "Expected 1 (oid=N) to not be the same as 1 (oid=N)." do + _(1).wont_be_same_as 1 + end + + assert_triggered "msg.\nExpected 1 (oid=N) to not be the same as 1 (oid=N)." do + _(1).wont_be_same_as 1, "msg" + end + end + + it "needs to verify non-nil" do + assert_success _(42).wont_be_nil + + assert_triggered "Expected nil to not be nil." do + _(nil).wont_be_nil + end + + assert_triggered "msg.\nExpected nil to not be nil." do + _(nil).wont_be_nil "msg" + end + end + + it "needs to verify objects not responding to a message" do + assert_success _("").wont_respond_to(:woot!) + + assert_triggered "Expected \"\" to not respond to to_s." do + _("").wont_respond_to :to_s + end + + assert_triggered "msg.\nExpected \"\" to not respond to to_s." do + _("").wont_respond_to :to_s, "msg" + end + end + + it "needs to verify output in stderr" do + @assertion_count -= 1 # no msg + + assert_success expect { $stderr.print "blah" }.must_output(nil, "blah") + + assert_triggered "In stderr.\nExpected: \"blah\"\n Actual: \"xxx\"" do + expect { $stderr.print "xxx" }.must_output(nil, "blah") + end + end + + it "needs to verify output in stdout" do + @assertion_count -= 1 # no msg + + assert_success expect { print "blah" }.must_output("blah") + + assert_triggered "In stdout.\nExpected: \"blah\"\n Actual: \"xxx\"" do + expect { print "xxx" }.must_output("blah") + end + end + + it "needs to verify regexp matches" do + @assertion_count += 3 # must_match is 2 assertions + + assert_success _("blah").must_match(/\w+/) + + assert_triggered "Expected /\\d+/ to match \"blah\"." do + _("blah").must_match(/\d+/) + end + + assert_triggered "msg.\nExpected /\\d+/ to match \"blah\"." do + _("blah").must_match(/\d+/, "msg") + end + end + + describe "expect" do + before do + @assertion_count -= 3 + end + + it "can use expect" do + _(1 + 1).must_equal 2 + end + + it "can use expect with a lambda" do + _ { raise "blah" }.must_raise RuntimeError + end + + it "can use expect in a thread" do + Thread.new { _(1 + 1).must_equal 2 }.join + end + + it "can NOT use must_equal in a thread. It must use expect in a thread" do + skip "N/A" if ENV["MT_NO_EXPECTATIONS"] + assert_raises RuntimeError do + capture_io do + Thread.new { (1 + 1).must_equal 2 }.join + end + end + end + + it "fails gracefully when expectation used outside of `it`" do + skip "N/A" if ENV["MT_NO_EXPECTATIONS"] + + @assertion_count += 1 + + e = assert_raises RuntimeError do + capture_io do + Thread.new { # forces ctx to be nil + describe("woot") do + (1 + 1).must_equal 2 + end + }.join + end + end + + assert_equal "Calling #must_equal outside of test.", e.message + end + + it "deprecates expectation used without _" do + skip "N/A" if ENV["MT_NO_EXPECTATIONS"] + + @assertion_count += 3 + + exp = /DEPRECATED: global use of must_equal from/ + + assert_output "", exp do + (1 + 1).must_equal 2 + end + end + + # https://github.com/seattlerb/minitest/issues/837 + # https://github.com/rails/rails/pull/39304 + it "deprecates expectation used without _ with empty backtrace_filter" do + skip "N/A" if ENV["MT_NO_EXPECTATIONS"] + + @assertion_count += 3 + + exp = /DEPRECATED: global use of must_equal from/ + + with_empty_backtrace_filter do + assert_output "", exp do + (1 + 1).must_equal 2 + end + end + end + end + + it "needs to verify throw" do + @assertion_count += 4 # 2 extra tests + + assert_nil expect { throw :blah }.must_throw(:blah) + assert_equal 42, expect { throw :blah, 42 }.must_throw(:blah) + + assert_triggered "Expected :blah to have been thrown." do + expect {}.must_throw :blah + end + + assert_triggered "Expected :blah to have been thrown, not :xxx." do + expect { throw :xxx }.must_throw :blah + end + + assert_triggered "msg.\nExpected :blah to have been thrown." do + expect {}.must_throw :blah, "msg" + end + + assert_triggered "msg.\nExpected :blah to have been thrown, not :xxx." do + expect { throw :xxx }.must_throw :blah, "msg" + end + end + + it "needs to verify types of objects" do + assert_success _(6 * 7).must_be_instance_of(Int) + + exp = "Expected 42 to be an instance of String, not #{Int.name}." + + assert_triggered exp do + _(6 * 7).must_be_instance_of String + end + + assert_triggered "msg.\n#{exp}" do + _(6 * 7).must_be_instance_of String, "msg" + end + end + + it "needs to verify using any (negative) predicate" do + @assertion_count -= 1 # doesn"t take a message + + assert_success _("blah").wont_be(:empty?) + + assert_triggered "Expected \"\" to not be empty?." do + _("").wont_be :empty? + end + end + + it "needs to verify using any binary operator" do + @assertion_count -= 1 # no msg + + assert_success _(41).must_be(:<, 42) + + assert_triggered "Expected 42 to be < 41." do + _(42).must_be(:<, 41) + end + end + + it "needs to verify using any predicate" do + @assertion_count -= 1 # no msg + + assert_success _("").must_be(:empty?) + + assert_triggered "Expected \"blah\" to be empty?." do + _("blah").must_be :empty? + end + end + + it "needs to verify using respond_to" do + assert_success _(42).must_respond_to(:+) + + assert_triggered "Expected 42 (#{Int.name}) to respond to #clear." do + _(42).must_respond_to :clear + end + + assert_triggered "msg.\nExpected 42 (#{Int.name}) to respond to #clear." do + _(42).must_respond_to :clear, "msg" + end + end +end + +describe Minitest::Spec, :let do + i_suck_and_my_tests_are_order_dependent! + + def _count + $let_count ||= 0 + end + + let :count do + $let_count += 1 + $let_count + end + + it "is evaluated once per example" do + _(_count).must_equal 0 + + _(count).must_equal 1 + _(count).must_equal 1 + + _(_count).must_equal 1 + end + + it "is REALLY evaluated once per example" do + _(_count).must_equal 1 + + _(count).must_equal 2 + _(count).must_equal 2 + + _(_count).must_equal 2 + end + + it 'raises an error if the name begins with "test"' do + expect { self.class.let(:test_value) { true } }.must_raise ArgumentError + end + + it "raises an error if the name shadows a normal instance method" do + expect { self.class.let(:message) { true } }.must_raise ArgumentError + end + + it "doesn't raise an error if it is just another let" do + v = proc do + describe :outer do + let(:bar) + describe :inner do + let(:bar) + end + end + :good + end.call + _(v).must_equal :good + end + + it "procs come after dont_flip" do + p = proc {} + assert_respond_to p, :call + _(p).must_respond_to :call + end +end + +describe Minitest::Spec, :subject do + attr_reader :subject_evaluation_count + + subject do + @subject_evaluation_count ||= 0 + @subject_evaluation_count += 1 + @subject_evaluation_count + end + + it "is evaluated once per example" do + _(subject).must_equal 1 + _(subject).must_equal 1 + _(subject_evaluation_count).must_equal 1 + end +end + +class TestMetaStatic < Minitest::Test + def test_children + Minitest::Spec.children.clear # prevents parallel run + + y = z = nil + x = describe "top-level thingy" do + y = describe "first thingy" do end + + it "top-level-it" do end + + z = describe "second thingy" do end + end + + assert_equal [x], Minitest::Spec.children + assert_equal [y, z], x.children + assert_equal [], y.children + assert_equal [], z.children + end + + def test_it_wont_remove_existing_child_test_methods + Minitest::Spec.children.clear # prevents parallel run + + inner = nil + outer = describe "outer" do + inner = describe "inner" do + it do + assert true + end + end + it do + assert true + end + end + + assert_equal 1, outer.public_instance_methods.grep(/^test_/).count + assert_equal 1, inner.public_instance_methods.grep(/^test_/).count + end + + def test_it_wont_add_test_methods_to_children + Minitest::Spec.children.clear # prevents parallel run + + inner = nil + outer = describe "outer" do + inner = describe "inner" do end + it do + assert true + end + end + + assert_equal 1, outer.public_instance_methods.grep(/^test_/).count + assert_equal 0, inner.public_instance_methods.grep(/^test_/).count + end +end + +class TestMeta < MetaMetaMetaTestCase + # do not call parallelize_me! here because specs use register_spec_type globally + + def util_structure + y = z = nil + before_list = [] + after_list = [] + x = describe "top-level thingy" do + before { before_list << 1 } + after { after_list << 1 } + + it "top-level-it" do end + + y = describe "inner thingy" do + before { before_list << 2 } + after { after_list << 2 } + it "inner-it" do end + + z = describe "very inner thingy" do + before { before_list << 3 } + after { after_list << 3 } + it "inner-it" do end + + it { } # ignore me + specify { } # anonymous it + end + end + end + + return x, y, z, before_list, after_list + end + + def test_register_spec_type + original_types = Minitest::Spec::TYPES.dup + + assert_includes Minitest::Spec::TYPES, [//, Minitest::Spec] + + Minitest::Spec.register_spec_type(/woot/, TestMeta) + + p = lambda do |_| true end + Minitest::Spec.register_spec_type TestMeta, &p + + keys = Minitest::Spec::TYPES.map(&:first) + + assert_includes keys, /woot/ + assert_includes keys, p + ensure + Minitest::Spec::TYPES.replace original_types + end + + def test_spec_type + original_types = Minitest::Spec::TYPES.dup + + Minitest::Spec.register_spec_type(/A$/, MiniSpecA) + Minitest::Spec.register_spec_type MiniSpecB do |desc| + desc.superclass == ExampleA + end + Minitest::Spec.register_spec_type MiniSpecC do |_desc, *addl| + addl.include? :woot + end + + assert_equal MiniSpecA, Minitest::Spec.spec_type(ExampleA) + assert_equal MiniSpecB, Minitest::Spec.spec_type(ExampleB) + assert_equal MiniSpecC, Minitest::Spec.spec_type(ExampleB, :woot) + ensure + Minitest::Spec::TYPES.replace original_types + end + + def test_bug_dsl_expectations + spec_class = Class.new MiniSpecB do + it "should work" do + _(0).must_equal 0 + end + end + + test_name = spec_class.instance_methods.sort.grep(/test/).first + + spec = spec_class.new test_name + + result = spec.run + + assert spec.passed? + assert result.passed? + assert_equal 1, result.assertions + end + + def test_name + spec_a = describe ExampleA do; end + spec_b = describe ExampleB, :random_method do; end + spec_c = describe ExampleB, :random_method, :addl_context do; end + + assert_equal "ExampleA", spec_a.name + assert_equal "ExampleB::random_method", spec_b.name + assert_equal "ExampleB::random_method::addl_context", spec_c.name + end + + def test_name2 + assert_equal "NamedExampleA", NamedExampleA.name + assert_equal "NamedExampleB", NamedExampleB.name + assert_equal "NamedExampleC", NamedExampleC.name + + spec_a = describe ExampleA do; end + spec_b = describe ExampleB, :random_method do; end + + assert_equal "ExampleA", spec_a.name + assert_equal "ExampleB::random_method", spec_b.name + end + + def test_structure + x, y, z, * = util_structure + + assert_equal "top-level thingy", x.to_s + assert_equal "top-level thingy::inner thingy", y.to_s + assert_equal "top-level thingy::inner thingy::very inner thingy", z.to_s + + assert_equal "top-level thingy", x.desc + assert_equal "inner thingy", y.desc + assert_equal "very inner thingy", z.desc + + top_methods = %w[setup teardown test_0001_top-level-it] + inner_methods1 = %w[setup teardown test_0001_inner-it] + inner_methods2 = inner_methods1 + + %w[test_0002_anonymous test_0003_anonymous] + + assert_equal top_methods, x.instance_methods(false).sort.map(&:to_s) + assert_equal inner_methods1, y.instance_methods(false).sort.map(&:to_s) + assert_equal inner_methods2, z.instance_methods(false).sort.map(&:to_s) + end + + def test_structure_postfix_it + z = nil + y = describe "outer" do + # NOT here, below the inner-describe! + # it "inner-it" do end + + z = describe "inner" do + it "inner-it" do end + end + + # defined AFTER inner describe means we'll try to wipe out the inner-it + it "inner-it" do end + end + + assert_equal %w[test_0001_inner-it], y.instance_methods(false).map(&:to_s) + assert_equal %w[test_0001_inner-it], z.instance_methods(false).map(&:to_s) + end + + def test_setup_teardown_behavior + _, _, z, before_list, after_list = util_structure + + @tu = z + + run_tu_with_fresh_reporter + + size = z.runnable_methods.size + assert_equal [1, 2, 3] * size, before_list + assert_equal [3, 2, 1] * size, after_list + end + + def test_describe_first_structure + x1 = x2 = y = z = nil + x = describe "top-level thingy" do + y = describe "first thingy" do end + + x1 = it "top level it" do end + x2 = it "не латинские &いった α, β, γ, δ, ε hello!!! world" do end + + z = describe "second thingy" do end + end + + test_methods = ["test_0001_top level it", + "test_0002_не латинские &いった α, β, γ, δ, ε hello!!! world", + ].sort + + assert_equal test_methods, [x1, x2] + assert_equal test_methods, x.instance_methods.grep(/^test/).map(&:to_s).sort + assert_equal [], y.instance_methods.grep(/^test/) + assert_equal [], z.instance_methods.grep(/^test/) + end + + def test_structure_subclasses + z = nil + x = Class.new Minitest::Spec do + def xyz; end + end + y = Class.new x do + z = describe("inner") { } + end + + assert_respond_to x.new(nil), "xyz" + assert_respond_to y.new(nil), "xyz" + assert_respond_to z.new(nil), "xyz" + end +end + +class TestSpecInTestCase < MetaMetaMetaTestCase + def setup + super + + Thread.current[:current_spec] = self + @tc = self + @assertion_count = 2 + end + + def assert_triggered expected, klass = Minitest::Assertion + @assertion_count += 1 + + e = assert_raises klass do + yield + end + + msg = e.message.sub(/(---Backtrace---).*/m, "\1") + msg.gsub!(/\(oid=[-0-9]+\)/, "(oid=N)") + + assert_equal expected, msg + end + + def teardown + msg = "expected #{@assertion_count} assertions, not #{@tc.assertions}" + assert_equal @assertion_count, @tc.assertions, msg + end + + def test_expectation + @tc.assert_equal true, _(1).must_equal(1) + end + + def test_expectation_triggered + assert_triggered "Expected: 2\n Actual: 1" do + _(1).must_equal 2 + end + end + + include Minitest::Spec::DSL::InstanceMethods + + def test_expectation_with_a_message + assert_triggered "woot.\nExpected: 2\n Actual: 1" do + _(1).must_equal 2, "woot" + end + end +end + +class ValueMonadTest < Minitest::Test + attr_accessor :struct + + def setup + @struct = { :_ => "a", :value => "b", :expect => "c" } + def @struct.method_missing k # think openstruct + self[k] + end + end + + def test_value_monad_method + assert_equal "a", struct._ + end + + def test_value_monad_value_alias + assert_equal "b", struct.value + end + + def test_value_monad_expect_alias + assert_equal "c", struct.expect + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_test.rb b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_test.rb new file mode 100644 index 0000000..7fbbf1f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/minitest-5.15.0/test/minitest/test_minitest_test.rb @@ -0,0 +1,1109 @@ +# encoding: UTF-8 + +require "pathname" +require "minitest/metametameta" + +if defined? Encoding then + e = Encoding.default_external + if e != Encoding::UTF_8 then + warn "" + warn "" + warn "NOTE: External encoding #{e} is not UTF-8. Tests WILL fail." + warn " Run tests with `RUBYOPT=-Eutf-8 rake` to avoid errors." + warn "" + warn "" + end +end + +class Minitest::Runnable + def whatever # faked for testing + assert true + end +end + +class TestMinitestUnit < MetaMetaMetaTestCase + parallelize_me! + + pwd = Pathname.new File.expand_path Dir.pwd + basedir = Pathname.new(File.expand_path "lib/minitest") + "mini" + basedir = basedir.relative_path_from(pwd).to_s + MINITEST_BASE_DIR = basedir[/\A\./] ? basedir : "./#{basedir}" + BT_MIDDLE = ["#{MINITEST_BASE_DIR}/test.rb:161:in `each'", + "#{MINITEST_BASE_DIR}/test.rb:158:in `each'", + "#{MINITEST_BASE_DIR}/test.rb:139:in `run'", + "#{MINITEST_BASE_DIR}/test.rb:106:in `run'"] + + def test_filter_backtrace + # this is a semi-lame mix of relative paths. + # I cheated by making the autotest parts not have ./ + bt = (["lib/autotest.rb:571:in `add_exception'", + "test/test_autotest.rb:62:in `test_add_exception'", + "#{MINITEST_BASE_DIR}/test.rb:165:in `__send__'"] + + BT_MIDDLE + + ["#{MINITEST_BASE_DIR}/test.rb:29", + "test/test_autotest.rb:422"]) + bt = util_expand_bt bt + + ex = ["lib/autotest.rb:571:in `add_exception'", + "test/test_autotest.rb:62:in `test_add_exception'"] + ex = util_expand_bt ex + + fu = Minitest.filter_backtrace(bt) + + assert_equal ex, fu + end + + def test_filter_backtrace_all_unit + bt = (["#{MINITEST_BASE_DIR}/test.rb:165:in `__send__'"] + + BT_MIDDLE + + ["#{MINITEST_BASE_DIR}/test.rb:29"]) + ex = bt.clone + fu = Minitest.filter_backtrace(bt) + assert_equal ex, fu + end + + def test_filter_backtrace_unit_starts + bt = (["#{MINITEST_BASE_DIR}/test.rb:165:in `__send__'"] + + BT_MIDDLE + + ["#{MINITEST_BASE_DIR}/mini/test.rb:29", + "-e:1"]) + + bt = util_expand_bt bt + + ex = ["-e:1"] + fu = Minitest.filter_backtrace bt + assert_equal ex, fu + end + + def test_filter_backtrace__empty + with_empty_backtrace_filter do + bt = %w[first second third] + fu = Minitest.filter_backtrace bt.dup + assert_equal bt, fu + end + end + + def test_infectious_binary_encoding + @tu = Class.new FakeNamedTest do + def test_this_is_not_ascii_assertion + assert_equal "ЁЁЁ", "ёёё" + end + + def test_this_is_non_ascii_failure_message + fail 'ЁЁЁ'.force_encoding('ASCII-8BIT') + end + end + + expected = clean <<-EOM + EF + + Finished in 0.00 + + 1) Error: + FakeNamedTestXX#test_this_is_non_ascii_failure_message: + RuntimeError: ЁЁЁ + FILE:LINE:in `test_this_is_non_ascii_failure_message' + + 2) Failure: + FakeNamedTestXX#test_this_is_not_ascii_assertion [FILE:LINE]: + Expected: \"ЁЁЁ\" + Actual: \"ёёё\" + + 2 runs, 1 assertions, 1 failures, 1 errors, 0 skips + EOM + + assert_report expected + end + + def test_passed_eh_teardown_good + test_class = Class.new FakeNamedTest do + def teardown; assert true; end + def test_omg; assert true; end + end + + test = test_class.new :test_omg + test.run + + refute_predicate test, :error? + assert_predicate test, :passed? + refute_predicate test, :skipped? + end + + def test_passed_eh_teardown_skipped + test_class = Class.new FakeNamedTest do + def teardown; assert true; end + def test_omg; skip "bork"; end + end + + test = test_class.new :test_omg + test.run + + refute_predicate test, :error? + refute_predicate test, :passed? + assert_predicate test, :skipped? + end + + def test_passed_eh_teardown_flunked + test_class = Class.new FakeNamedTest do + def teardown; flunk; end + def test_omg; assert true; end + end + + test = test_class.new :test_omg + test.run + + refute_predicate test, :error? + refute_predicate test, :passed? + refute_predicate test, :skipped? + end + + def util_expand_bt bt + if RUBY_VERSION >= "1.9.0" then + bt.map { |f| (f =~ /^\./) ? File.expand_path(f) : f } + else + bt + end + end +end + +class TestMinitestUnitInherited < MetaMetaMetaTestCase + def with_overridden_include + Class.class_eval do + def inherited_with_hacks _klass + throw :inherited_hook + end + + alias inherited_without_hacks inherited + alias inherited inherited_with_hacks + alias IGNORE_ME! inherited # 1.8 bug. god I love venture bros + end + + yield + ensure + Class.class_eval do + alias inherited inherited_without_hacks + + undef_method :inherited_with_hacks + undef_method :inherited_without_hacks + end + + refute_respond_to Class, :inherited_with_hacks + refute_respond_to Class, :inherited_without_hacks + end + + def test_inherited_hook_plays_nice_with_others + with_overridden_include do + assert_throws :inherited_hook do + Class.new FakeNamedTest + end + end + end +end + +class TestMinitestRunner < MetaMetaMetaTestCase + # do not parallelize this suite... it just can't handle it. + + def test_class_runnables + @assertion_count = 0 + + tc = Class.new(Minitest::Test) + + assert_equal 1, Minitest::Test.runnables.size + assert_equal [tc], Minitest::Test.runnables + end + + def test_run_test + @tu = + Class.new FakeNamedTest do + attr_reader :foo + + def run + @foo = "hi mom!" + r = super + @foo = "okay" + + r + end + + def test_something + assert_equal "hi mom!", foo + end + end + + expected = clean <<-EOM + . + + Finished in 0.00 + + 1 runs, 1 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_report expected + end + + def test_run_error + @tu = + Class.new FakeNamedTest do + def test_something + assert true + end + + def test_error + raise "unhandled exception" + end + end + + expected = clean <<-EOM + E. + + Finished in 0.00 + + 1) Error: + FakeNamedTestXX#test_error: + RuntimeError: unhandled exception + FILE:LINE:in \`test_error\' + + 2 runs, 1 assertions, 0 failures, 1 errors, 0 skips + EOM + + assert_report expected + end + + def test_run_error_teardown + @tu = + Class.new FakeNamedTest do + def test_something + assert true + end + + def teardown + raise "unhandled exception" + end + end + + expected = clean <<-EOM + E + + Finished in 0.00 + + 1) Error: + FakeNamedTestXX#test_something: + RuntimeError: unhandled exception + FILE:LINE:in \`teardown\' + + 1 runs, 1 assertions, 0 failures, 1 errors, 0 skips + EOM + + assert_report expected + end + + def test_run_failing + setup_basic_tu + + expected = clean <<-EOM + F. + + Finished in 0.00 + + 1) Failure: + FakeNamedTestXX#test_failure [FILE:LINE]: + Expected false to be truthy. + + 2 runs, 2 assertions, 1 failures, 0 errors, 0 skips + EOM + + assert_report expected + end + + def setup_basic_tu + @tu = + Class.new FakeNamedTest do + def test_something + assert true + end + + def test_failure + assert false + end + end + end + + def test_run_failing_filtered + setup_basic_tu + + expected = clean <<-EOM + . + + Finished in 0.00 + + 1 runs, 1 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_report expected, %w[--name /some|thing/ --seed 42] + end + + def assert_filtering filter, name, expected, a = false + args = %W[--#{filter} #{name} --seed 42] + + alpha = Class.new FakeNamedTest do + define_method :test_something do + assert a + end + end + Object.const_set(:Alpha, alpha) + + beta = Class.new FakeNamedTest do + define_method :test_something do + assert true + end + end + Object.const_set(:Beta, beta) + + @tus = [alpha, beta] + + assert_report expected, args + ensure + Object.send :remove_const, :Alpha + Object.send :remove_const, :Beta + end + + def test_run_filtered_including_suite_name + expected = clean <<-EOM + . + + Finished in 0.00 + + 1 runs, 1 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_filtering "name", "/Beta#test_something/", expected + end + + def test_run_filtered_including_suite_name_string + expected = clean <<-EOM + . + + Finished in 0.00 + + 1 runs, 1 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_filtering "name", "Beta#test_something", expected + end + + def test_run_filtered_string_method_only + expected = clean <<-EOM + .. + + Finished in 0.00 + + 2 runs, 2 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_filtering "name", "test_something", expected, :pass + end + + def test_run_failing_excluded + setup_basic_tu + + expected = clean <<-EOM + . + + Finished in 0.00 + + 1 runs, 1 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_report expected, %w[--exclude /failure/ --seed 42] + end + + def test_run_filtered_excluding_suite_name + expected = clean <<-EOM + . + + Finished in 0.00 + + 1 runs, 1 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_filtering "exclude", "/Alpha#test_something/", expected + end + + def test_run_filtered_excluding_suite_name_string + expected = clean <<-EOM + . + + Finished in 0.00 + + 1 runs, 1 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_filtering "exclude", "Alpha#test_something", expected + end + + def test_run_filtered_excluding_string_method_only + expected = clean <<-EOM + + + Finished in 0.00 + + 0 runs, 0 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_filtering "exclude", "test_something", expected, :pass + end + + def test_run_passing + @tu = + Class.new FakeNamedTest do + def test_something + assert true + end + end + + expected = clean <<-EOM + . + + Finished in 0.00 + + 1 runs, 1 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_report expected + end + + def test_run_skip + @tu = + Class.new FakeNamedTest do + def test_something + assert true + end + + def test_skip + skip "not yet" + end + end + + expected = clean <<-EOM + S. + + Finished in 0.00 + + 2 runs, 1 assertions, 0 failures, 0 errors, 1 skips + + You have skipped tests. Run with --verbose for details. + EOM + + restore_env do + assert_report expected + end + end + + def test_run_skip_verbose + @tu = + Class.new FakeNamedTest do + def test_something + assert true + end + + def test_skip + skip "not yet" + end + end + + expected = clean <<-EOM + FakeNamedTestXX#test_skip = 0.00 s = S + FakeNamedTestXX#test_something = 0.00 s = . + + Finished in 0.00 + + 1) Skipped: + FakeNamedTestXX#test_skip [FILE:LINE]: + not yet + + 2 runs, 1 assertions, 0 failures, 0 errors, 1 skips + EOM + + assert_report expected, %w[--seed 42 --verbose] + end + + def test_run_with_other_runner + @tu = + Class.new FakeNamedTest do + def self.run reporter, options = {} + @reporter = reporter + before_my_suite + super + end + + def self.name; "wacky!" end + + def self.before_my_suite + @reporter.io.puts "Running #{self.name} tests" + @@foo = 1 + end + + def test_something + assert_equal 1, @@foo + end + + def test_something_else + assert_equal 1, @@foo + end + end + + expected = clean <<-EOM + Running wacky! tests + .. + + Finished in 0.00 + + 2 runs, 2 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_report expected + end + + require "monitor" + + class Latch + def initialize count = 1 + @count = count + @lock = Monitor.new + @cv = @lock.new_cond + end + + def release + @lock.synchronize do + @count -= 1 if @count > 0 + @cv.broadcast if @count == 0 + end + end + + def await + @lock.synchronize { @cv.wait_while { @count > 0 } } + end + end + + def test_run_parallel + test_count = 2 + test_latch = Latch.new test_count + wait_latch = Latch.new test_count + main_latch = Latch.new + + thread = Thread.new { + Thread.current.abort_on_exception = true + + # This latch waits until both test latches have been released. Both + # latches can't be released unless done in separate threads because + # `main_latch` keeps the test method from finishing. + test_latch.await + main_latch.release + } + + @tu = + Class.new FakeNamedTest do + parallelize_me! + + test_count.times do |i| + define_method :"test_wait_on_main_thread_#{i}" do + test_latch.release + + # This latch blocks until the "main thread" releases it. The main + # thread can't release this latch until both test latches have + # been released. This forces the latches to be released in separate + # threads. + main_latch.await + assert true + end + end + end + + expected = clean <<-EOM + .. + + Finished in 0.00 + + 2 runs, 2 assertions, 0 failures, 0 errors, 0 skips + EOM + + assert_report(expected) do |reporter| + reporter.extend(Module.new { + define_method("record") do |result| + super(result) + wait_latch.release + end + + define_method("report") do + wait_latch.await + super() + end + }) + end + assert thread.join + end +end + +class TestMinitestUnitOrder < MetaMetaMetaTestCase + # do not parallelize this suite... it just can't handle it. + + def test_before_setup + call_order = [] + @tu = + Class.new FakeNamedTest do + define_method :setup do + super() + call_order << :setup + end + + define_method :before_setup do + call_order << :before_setup + end + + def test_omg; assert true; end + end + + run_tu_with_fresh_reporter + + expected = [:before_setup, :setup] + assert_equal expected, call_order + end + + def test_after_teardown + call_order = [] + @tu = + Class.new FakeNamedTest do + define_method :teardown do + super() + call_order << :teardown + end + + define_method :after_teardown do + call_order << :after_teardown + end + + def test_omg; assert true; end + end + + run_tu_with_fresh_reporter + + expected = [:teardown, :after_teardown] + assert_equal expected, call_order + end + + def test_all_teardowns_are_guaranteed_to_run + call_order = [] + @tu = + Class.new FakeNamedTest do + define_method :after_teardown do + super() + call_order << :after_teardown + raise + end + + define_method :teardown do + super() + call_order << :teardown + raise + end + + define_method :before_teardown do + super() + call_order << :before_teardown + raise + end + + def test_omg; assert true; end + end + + run_tu_with_fresh_reporter + + expected = [:before_teardown, :teardown, :after_teardown] + assert_equal expected, call_order + end + + def test_setup_and_teardown_survive_inheritance + call_order = [] + + @tu = Class.new FakeNamedTest do + define_method :setup do + call_order << :setup_method + end + + define_method :teardown do + call_order << :teardown_method + end + + define_method :test_something do + call_order << :test + end + end + + run_tu_with_fresh_reporter + + @tu = Class.new @tu + run_tu_with_fresh_reporter + + # Once for the parent class, once for the child + expected = [:setup_method, :test, :teardown_method] * 2 + + assert_equal expected, call_order + end +end + +class TestMinitestRunnable < Minitest::Test + def setup_marshal klass + tc = klass.new "whatever" + tc.assertions = 42 + tc.failures << "a failure" + + yield tc if block_given? + + def tc.setup + @blah = "blah" + end + tc.setup + + @tc = Minitest::Result.from tc + end + + def assert_marshal expected_ivars + new_tc = Marshal.load Marshal.dump @tc + + ivars = new_tc.instance_variables.map(&:to_s).sort + assert_equal expected_ivars, ivars + assert_equal "whatever", new_tc.name + assert_equal 42, new_tc.assertions + assert_equal ["a failure"], new_tc.failures + + yield new_tc if block_given? + end + + def test_marshal + setup_marshal Minitest::Runnable + + assert_marshal %w[@NAME @assertions @failures @klass @source_location @time] + end + + def test_spec_marshal + klass = describe("whatever") { it("passes") { assert true } } + rm = klass.runnable_methods.first + + # Run the test + @tc = klass.new(rm).run + + assert_kind_of Minitest::Result, @tc + + # Pass it over the wire + over_the_wire = Marshal.load Marshal.dump @tc + + assert_equal @tc.time, over_the_wire.time + assert_equal @tc.name, over_the_wire.name + assert_equal @tc.assertions, over_the_wire.assertions + assert_equal @tc.failures, over_the_wire.failures + assert_equal @tc.klass, over_the_wire.klass + end + + def test_spec_marshal_with_exception + klass = describe("whatever") { it("passes") { raise Class.new(StandardError)} } + rm = klass.runnable_methods.first + + # Run the test + @tc = klass.new(rm).run + + assert_kind_of Minitest::Result, @tc + + # Pass it over the wire + over_the_wire = Marshal.load Marshal.dump @tc + + assert_equal @tc.time, over_the_wire.time + assert_equal @tc.name, over_the_wire.name + assert_equal @tc.assertions, over_the_wire.assertions + assert_equal @tc.failures, over_the_wire.failures + assert_equal @tc.klass, over_the_wire.klass + end +end + +class TestMinitestTest < TestMinitestRunnable + def test_dup + setup_marshal Minitest::Test do |tc| + tc.time = 3.14 + end + + assert_marshal %w[@NAME @assertions @failures @klass @source_location @time] do |new_tc| + assert_in_epsilon 3.14, new_tc.time + end + end +end + +class TestMinitestUnitTestCase < Minitest::Test + # do not call parallelize_me! - teardown accesses @tc._assertions + # which is not threadsafe. Nearly every method in here is an + # assertion test so it isn't worth splitting it out further. + + RUBY18 = !defined? Encoding + + def setup + super + + Minitest::Test.reset + + @tc = Minitest::Test.new "fake tc" + @zomg = "zomg ponies!" + @assertion_count = 1 + end + + def teardown + assert_equal(@assertion_count, @tc.assertions, + "expected #{@assertion_count} assertions to be fired during the test, not #{@tc.assertions}") if @tc.passed? + end + + def non_verbose + orig_verbose = $VERBOSE + $VERBOSE = false + + yield + ensure + $VERBOSE = orig_verbose + end + + def sample_test_case(rand) + srand rand + Class.new FakeNamedTest do + 100.times do |i| + define_method("test_#{i}") { assert true } + end + end.runnable_methods + end + + # srand varies with OS + def test_runnable_methods_random + @assertion_count = 0 + + random_tests_1 = sample_test_case 42 + random_tests_2 = sample_test_case 42 + random_tests_3 = sample_test_case 1_000 + + assert_equal random_tests_1, random_tests_2 + refute_equal random_tests_1, random_tests_3 + end + + def test_runnable_methods_sorted + @assertion_count = 0 + + sample_test_case = Class.new FakeNamedTest do + def self.test_order; :sorted end + def test_test3; assert "does not matter" end + def test_test2; assert "does not matter" end + def test_test1; assert "does not matter" end + end + + expected = %w[test_test1 test_test2 test_test3] + assert_equal expected, sample_test_case.runnable_methods + end + + def test_i_suck_and_my_tests_are_order_dependent_bang_sets_test_order_alpha + @assertion_count = 0 + + shitty_test_case = Class.new FakeNamedTest + + shitty_test_case.i_suck_and_my_tests_are_order_dependent! + + assert_equal :alpha, shitty_test_case.test_order + end + + def test_i_suck_and_my_tests_are_order_dependent_bang_does_not_warn + @assertion_count = 0 + + shitty_test_case = Class.new FakeNamedTest + + def shitty_test_case.test_order; :lol end + + assert_silent do + shitty_test_case.i_suck_and_my_tests_are_order_dependent! + end + end + + def test_autorun_does_not_affect_fork_success_status + @assertion_count = 0 + skip "windows doesn't have skip" unless Process.respond_to?(:fork) + Process.waitpid(fork {}) + assert_equal true, $?.success? + end + + def test_autorun_does_not_affect_fork_exit_status + @assertion_count = 0 + skip "windows doesn't have skip" unless Process.respond_to?(:fork) + Process.waitpid(fork { exit 42 }) + assert_equal 42, $?.exitstatus + end +end + +class TestMinitestGuard < Minitest::Test + parallelize_me! + + def test_mri_eh + assert self.class.mri? "ruby blah" + assert self.mri? "ruby blah" + end + + def test_jruby_eh + assert self.class.jruby? "java" + assert self.jruby? "java" + end + + def test_rubinius_eh + assert_output "", /DEPRECATED/ do + assert self.class.rubinius? "rbx" + end + assert_output "", /DEPRECATED/ do + assert self.rubinius? "rbx" + end + end + + def test_maglev_eh + assert_output "", /DEPRECATED/ do + assert self.class.maglev? "maglev" + end + assert_output "", /DEPRECATED/ do + assert self.maglev? "maglev" + end + end + + def test_osx_eh + assert self.class.osx? "darwin" + assert self.osx? "darwin" + end + + def test_windows_eh + assert self.class.windows? "mswin" + assert self.windows? "mswin" + end +end + +class TestMinitestUnitRecording < MetaMetaMetaTestCase + # do not parallelize this suite... it just can't handle it. + + def assert_run_record *expected, &block + @tu = Class.new FakeNamedTest, &block + + run_tu_with_fresh_reporter + + recorded = first_reporter.results.map(&:failures).flatten.map { |f| f.error.class } + + assert_equal expected, recorded + end + + def test_run_with_bogus_reporter + # https://github.com/seattlerb/minitest/issues/659 + # TODO: remove test for minitest 6 + @tu = Class.new FakeNamedTest do + def test_method + assert true + end + end + + bogus_reporter = Class.new do # doesn't subclass AbstractReporter + def start; @success = false; end + # def prerecord klass, name; end # doesn't define full API + def record result; @success = true; end + def report; end + def passed?; end + def results; end + def success?; @success; end + end.new + + self.reporter = Minitest::CompositeReporter.new + reporter << bogus_reporter + + Minitest::Runnable.runnables.delete @tu + + @tu.run reporter, {} + + assert_predicate bogus_reporter, :success? + end + + def test_record_passing + assert_run_record do + def test_method + assert true + end + end + end + + def test_record_failing + assert_run_record Minitest::Assertion do + def test_method + assert false + end + end + end + + def test_record_error + assert_run_record RuntimeError do + def test_method + raise "unhandled exception" + end + end + end + + def test_record_error_teardown + assert_run_record RuntimeError do + def test_method + assert true + end + + def teardown + raise "unhandled exception" + end + end + end + + def test_record_error_in_test_and_teardown + assert_run_record AnError, RuntimeError do + def test_method + raise AnError + end + + def teardown + raise "unhandled exception" + end + end + end + + def test_to_s_error_in_test_and_teardown + @tu = Class.new FakeNamedTest do + def test_method + raise AnError + end + + def teardown + raise "unhandled exception" + end + end + + run_tu_with_fresh_reporter + + exp = clean " + Error: + FakeNamedTestXX#test_method: + AnError: AnError + FILE:LINE:in `test_method' + + Error: + FakeNamedTestXX#test_method: + RuntimeError: unhandled exception + FILE:LINE:in `teardown' + " + + assert_equal exp.strip, normalize_output(first_reporter.results.first.to_s).strip + end + + def test_record_skip + assert_run_record Minitest::Skip do + def test_method + skip "not yet" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/CHANGELOG.md b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/CHANGELOG.md new file mode 100644 index 0000000..3dd1b1e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/CHANGELOG.md @@ -0,0 +1,275 @@ +1.14.2 +------ + +* [Improve detection of json_gem adapter](https://github.com/intridea/multi_json/commit/62d54019b17ebf83b28c8deb871a02a122e7d9cf) + +1.14.1 +------ + +* [Fix a warning in Ruby 2.7](https://github.com/intridea/multi_json/commit/26a94ab8c78a394cc237e2ea292c1de4f6ed30d7) + +1.14.0 +------ + +* [Support Oj 3.x gem](https://github.com/intridea/multi_json/commit/5d8febdbebc428882811b90d514f3628617a61d5) + +1.13.1 +------ + +* [Fix missing stdlib set dependency in oj adapter](https://github.com/intridea/multi_json/commit/c4ff66e7bee6fb4f45e54429813d7fada1c152b8) + +1.13.0 +----- + +* [Make Oj adapter handle JSON::ParseError correctly](https://github.com/intridea/multi_json/commit/275e3ffd8169797c510d23d9ef5b8b07e64c3b42) + +1.12.2 +------ + +* [Renew gem certificate](https://github.com/intridea/multi_json/commit/57922d898c6eb587cc9a28ba5724c11e81724700) + +1.12.1 +------ + +* [Prevent memory leak in OptionsCache](https://github.com/intridea/multi_json/commit/aa7498199ad272f3d4a13750d7c568a66047e2ee) + +1.12.0 +------ + +* [Introduce global options cache to improve peroformance](https://github.com/intridea/multi_json/commit/7aaef2a1bc2b83c95e4208b12dad5d1d87ff20a6) + +1.11.2 +------ + +* [Only pass one argument to JrJackson when two is not supported](https://github.com/intridea/multi_json/commit/e798fa517c817fc706982d3f3c61129b6651d601) + +1.11.1 +------ + +* [Dump method passes options throught for JrJackson adapter](https://github.com/intridea/multi_json/commit/3c730fd12135c3e7bf212f878958004908f13909) + +1.11.0 +------ + +* [Make all adapters read IO object before load](https://github.com/intridea/multi_json/commit/167f559e18d4efee05e1f160a2661d16dbb215d4) + +1.10.1 +------ +* [Explicitly require stringio for Gson adapter](https://github.com/intridea/multi_json/commit/623ec8142d4a212fa0db763bb71295789a119929) +* [Do not read StringIO object before passing it to JrJackson](https://github.com/intridea/multi_json/commit/a6dc935df08e7b3d5d701fbb9298384c96df0fde) + +1.10.0 +------ +* [Performance tweaks](https://github.com/intridea/multi_json/commit/58724acfed31866d079eaafb1cd824e341ade287) + +1.9.3 +----- +* [Convert indent option to Fixnum before passing to Oj](https://github.com/intridea/multi_json/commit/826fc5535b863b74fc9f981dfdda3e26f1ee4e5b) + +1.9.2 +----- +* [Enable use_to_json option for Oj adapter by default](https://github.com/intridea/multi_json/commit/76a4aaf697b10bbabd5d535d83cf1149efcfe5c7) + +1.9.1 +----- +* [Remove unused LoadError file](https://github.com/intridea/multi_json/commit/65dedd84d59baeefc25c477fedf0bbe85e7ce2cd) + +1.9.0 +---- +* [Rename LoadError to ParseError](https://github.com/intridea/multi_json/commit/4abb98fe3a90b2a7b3d1594515c8a06042b4a27d) +* [Adapter load failure throws AdapterError instead of ArgumentError](https://github.com/intridea/multi_json/commit/4da612b617bd932bb6fa1cc4c43210327f98f271) + +1.8.4 +----- +* [Make Gson adapter explicitly read StringIO object](https://github.com/intridea/multi_json/commit/b58b498747ff6e94f41488c971b2a30a98760ef2) + +1.8.3 +----- +* [Make JrJackson explicitly read StringIO objects](https://github.com/intridea/multi_json/commit/e1f162d5b668e5e4db5afa175361a601a8aa2b05) +* [Prevent calling #downcase on alias symbols](https://github.com/intridea/multi_json/commit/c1cf075453ce0110f7decc4f906444b1233bb67c) + +1.8.2 +----- +* [Downcase adapter string name for OS compatibility](https://github.com/intridea/multi_json/commit/b8e15a032247a63f1410d21a18add05035f3fa66) + +1.8.1 +----- +* [Let the adapter handle strings with invalid encoding](https://github.com/intridea/multi_json/commit/6af2bf87b89f44eabf2ae9ca96779febc65ea94b) + +1.8.0 +----- +* [Raise MultiJson::LoadError on blank input](https://github.com/intridea/multi_json/commit/c44f9c928bb25fe672246ad394b3e5b991be32e6) + +1.7.9 +----- +* [Explicitly require json gem code even when constant is defined](https://github.com/intridea/multi_json/commit/36f7906c66477eb4b55b7afeaa3684b6db69eff2) + +1.7.8 +----- +* [Reorder JrJackson before json_gem](https://github.com/intridea/multi_json/commit/315b6e460b6e4dcdb6c82e04e4be8ee975d395da) +* [Update vendored OkJson to version 43](https://github.com/intridea/multi_json/commit/99a6b662f6ef4036e3ee94d7eb547fa72fb2ab50) + +1.7.7 +----- +* [Fix options caching issues](https://github.com/intridea/multi_json/commit/a3f14c3661688c5927638fa6088c7b46a67e875e) + +1.7.6 +----- +* [Bring back MultiJson::VERSION constant](https://github.com/intridea/multi_json/commit/31b990c2725e6673bf8ce57540fe66b57a751a72) + +1.7.5 +----- +* [Fix warning '*' interpreted as argument prefix](https://github.com/intridea/multi_json/commit/b698962c7f64430222a1f06430669706a47aff89) +* [Remove stdlib warning](https://github.com/intridea/multi_json/commit/d06eec6b7996ac8b4ff0e2229efd835379b0c30f) + +1.7.4 +----- +* [Cache options for better performance](https://github.com/intridea/multi_json/commit/8a26ee93140c4bed36194ed9fb887a1b6919257b) + +1.7.3 +----- +* [Require json/ext to ensure extension version gets loaded for json_gem](https://github.com/intridea/multi_json/commit/942686f7e8597418c6f90ee69e1d45242fac07b1) +* [Rename JrJackson](https://github.com/intridea/multi_json/commit/078de7ba8b6035343c3e96b4767549e9ec43369a) +* [Prefer JrJackson to JSON gem if present](https://github.com/intridea/multi_json/commit/af8bd9799a66855f04b3aff1c488485950cec7bf) +* [Print a warning if outdated gem versions are used](https://github.com/intridea/multi_json/commit/e7438e7ba2be0236cfa24c2bb9ad40ee821286d1) +* [Loosen required_rubygems_version for compatibility with Ubuntu 10.04](https://github.com/intridea/multi_json/commit/59fad014e8fe41dbc6f09485ea0dc21fc42fd7a7) + +1.7.2 +----- +* [Rename Jrjackson adapter to JrJackson](https://github.com/intridea/multi_json/commit/b36dc915fc0e6548cbad06b5db6f520e040c9c8b) +* [Implement jrjackson -> jr_jackson alias for back-compatability](https://github.com/intridea/multi_json/commit/aa50ab8b7bb646b8b75d5d65dfeadae8248a4f10) +* [Update vendored OkJson module](https://github.com/intridea/multi_json/commit/30a3f474e17dd86a697c3fab04f468d1a4fd69d7) + +1.7.1 +----- +* [Fix capitalization of JrJackson class](https://github.com/intridea/multi_json/commit/5373a5e38c647f02427a0477cb8e0e0dafad1b8d) + +1.7.0 +----- +* [Add load_options/dump_options to MultiJson](https://github.com/intridea/multi_json/commit/a153956be6b0df06ea1705ce3c1ff0b5b0e27ea5) +* [MultiJson does not modify arguments](https://github.com/intridea/multi_json/commit/58525b01c4c2f6635ba2ac13d6fd987b79f3962f) +* [Enable quirks_mode by default for json_gem/json_pure adapters](https://github.com/intridea/multi_json/commit/1fd4e6635c436515b7d7d5a0bee4548de8571520) +* [Add JrJackson adapter](https://github.com/intridea/multi_json/commit/4dd86fa96300aaaf6d762578b9b31ea82adb056d) +* [Raise ArgumentError on bad adapter input](https://github.com/intridea/multi_json/commit/911a3756bdff2cb5ac06497da3fa3e72199cb7ad) + +1.6.1 +----- +* [Revert "Use JSON.generate instead of #to_json"](https://github.com/intridea/multi_json/issues/86) + +1.6.0 +----- +* [Add gson.rb support](https://github.com/intridea/multi_json/pull/71) +* [Add MultiJson.default_options](https://github.com/intridea/multi_json/pull/70) +* [Add MultiJson.with_adapter](https://github.com/intridea/multi_json/pull/67) +* [Stringify all possible keys for ok_json](https://github.com/intridea/multi_json/pull/66) +* [Use JSON.generate instead of #to_json](https://github.com/intridea/multi_json/issues/73) +* [Alias `MultiJson::DecodeError` to `MultiJson::LoadError`](https://github.com/intridea/multi_json/pull/79) + +1.5.1 +----- +* [Do not allow Oj or JSON to create symbols by searching for classes](https://github.com/intridea/multi_json/commit/193e28cf4dc61b6e7b7b7d80f06f74c76df65c41) + +1.5.0 +----- +* [Add `MultiJson.with_adapter` method](https://github.com/intridea/multi_json/commit/d14c5d28cae96557a0421298621b9499e1f28104) +* [Stringify all possible keys for `ok_json`](https://github.com/intridea/multi_json/commit/73998074058e1e58c557ffa7b9541d486d6041fa) + +1.4.0 +----- +* [Allow `load`/`dump` of JSON fragments](https://github.com/intridea/multi_json/commit/707aae7d48d39c85b38febbd2c210ba87f6e4a36) + +1.3.7 +----- +* [Fix rescue clause for MagLev](https://github.com/intridea/multi_json/commit/39abdf50199828c50e85b2ce8f8ba31fcbbc9332) +* [Remove unnecessary check for string version of options key](https://github.com/intridea/multi_json/commit/660101b70e962b3c007d0b90d45944fa47d13ec4) +* [Explicitly set default adapter when adapter is set to `nil` or `false`](https://github.com/intridea/multi_json/commit/a9e587d5a63eafb4baee9fb211265e4dd96a26bc) +* [Fix Oj `ParseError` mapping for Oj 1.4.0](https://github.com/intridea/multi_json/commit/7d9045338cc9029401c16f3c409d54ce97f275e2) + +1.3.6 +----- +* [Allow adapter-specific options to be passed through to Oj](https://github.com/intridea/multi_json/commit/d0e5feeebcba0bc69400dd203a295f5c30971223) + +1.3.5 +----- +* [Add pretty support to Oj adapter](https://github.com/intridea/multi_json/commit/0c8f75f03020c53bcf4c6be258faf433d24b2c2b) + +1.3.4 +----- +* [Use `class << self` instead of `module_function` to create aliases](https://github.com/intridea/multi_json/commit/ba1451c4c48baa297e049889be241a424cb05980) + +1.3.3 +----- +* [Remove deprecation warnings](https://github.com/intridea/multi_json/commit/36b524e71544eb0186826a891bcc03b2820a008f) + +1.3.2 +----- +* [Add ability to use adapter per call](https://github.com/intridea/multi_json/commit/106bbec469d5d0a832bfa31fffcb8c0f0cdc9bd3) +* [Add and deprecate `default_engine` method](https://github.com/intridea/multi_json/commit/fc3df0c7a3e2ab9ce0c2c7e7617a4da97dd13f6e) + +1.3.1 +----- +* [Only warn once for each instance a deprecated method is called](https://github.com/intridea/multi_json/commit/e21d6eb7da74b3f283995c1d27d5880e75f0ae84) + +1.3.0 +----- +* [Implement `load`/`dump`; deprecate `decode`/`encode`](https://github.com/intridea/multi_json/commit/e90fd6cb1b0293eb0c73c2f4eb0f7a1764370216) +* [Rename engines to adapters](https://github.com/intridea/multi_json/commit/ae7fd144a7949a9c221dcaa446196ec23db908df) + +1.2.0 +----- +* [Add support for Oj](https://github.com/intridea/multi_json/commit/acd06b233edabe6c44f226873db7b49dab560c60) + +1.1.0 +----- +* [`NSJSONSerialization` support for MacRuby](https://github.com/intridea/multi_json/commit/f862e2fc966cac8867fe7da3997fc76e8a6cf5d4) + +1.0.4 +----- +* [Set data context to `DecodeError` exception](https://github.com/intridea/multi_json/commit/19ddafd44029c6681f66fae2a0f6eabfd0f85176) +* [Allow `ok_json` to fallback to `to_json`](https://github.com/intridea/multi_json/commit/c157240b1193b283d06d1bd4d4b5b06bcf3761f8) +* [Add warning when using `ok_json`](https://github.com/intridea/multi_json/commit/dd4b68810c84f826fb98f9713bfb29ab96888d57) +* [Options can be passed to an engine on encode](https://github.com/intridea/multi_json/commit/e0a7ff5d5ff621ffccc61617ed8aeec5816e81f7) + +1.0.3 +----- +* [`Array` support for `stringify_keys`](https://github.com/intridea/multi_json/commit/644d1c5c7c7f6a27663b11668527b346094e38b9) +* [`Array` support for `symbolize_keys`](https://github.com/intridea/multi_json/commit/c885377d47a2aa39cb0d971fea78db2d2fa479a7) + +1.0.2 +----- +* [Allow encoding of rootless JSON when `ok_json` is used](https://github.com/intridea/multi_json/commit/d1cde7de97cb0f6152aef8daf14037521cdce8c6) + +1.0.1 +----- +* [Correct an issue with `ok_json` not being returned as the default engine](https://github.com/intridea/multi_json/commit/d33c141619c54cccd770199694da8fd1bd8f449d) + +1.0.0 +----- +* [Remove `ActiveSupport::JSON` support](https://github.com/intridea/multi_json/commit/c2f4140141d785a24b3f56e58811b0e561b37f6a) +* [Fix `@engine` ivar warning](https://github.com/intridea/multi_json/commit/3b978a8995721a8dffedc3b75a7f49e5494ec553) +* [Only `rescue` from parsing errors during decoding, not any `StandardError`](https://github.com/intridea/multi_json/commit/391d00b5e85294d42d41347605d8d46b4a7f66cc) +* [Rename `okjson` engine and vendored lib to `ok_json`](https://github.com/intridea/multi_json/commit/5bd1afc977a8208ddb0443e1d57cb79665c019f1) +* [Add `StringIO` support to `json` gem and `ok_json`](https://github.com/intridea/multi_json/commit/1706b11568db7f50af451fce5f4d679aeb3bbe8f) + +0.0.5 +----- +* [Trap all JSON decoding errors; raise `MultiJson::DecodeError`](https://github.com/intridea/multi_json/commit/dea9a1aef6dd1212aa1e5a37ab1669f9b045b732) + +0.0.4 +----- +* [Fix default_engine check for `json` gem](https://github.com/intridea/multi_json/commit/caced0c4e8c795922a109ebc00c3c4fa8635bed8) +* [Make requirement mapper an `Array` to preserve order in Ruby versions < 1.9](https://github.com/intridea/multi_json/commit/526f5f29a42131574a088ad9bbb43d7f48439b2c) + +0.0.3 +----- +* [Improve defaulting and documentation](https://github.com/sferik/twitter/commit/3a0e41b9e4b0909201045fa47704b78c9d949b73) + +0.0.2 +----- + +* [Rename to `multi_json`](https://github.com/sferik/twitter/commit/461ab89ce071c8c9fabfc183581e0ec523788b62) + +0.0.1 +----- + +* [Initial commit](https://github.com/sferik/twitter/commit/518c21ab299c500527491e6c049ab2229e22a805) diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/CONTRIBUTING.md b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/CONTRIBUTING.md new file mode 100644 index 0000000..3e8bfd5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/CONTRIBUTING.md @@ -0,0 +1,46 @@ +## Contributing +In the spirit of [free software][free-sw], **everyone** is encouraged to help +improve this project. + +[free-sw]: http://www.fsf.org/licensing/essays/free-sw.html + +Here are some ways *you* can contribute: + +* by using alpha, beta, and prerelease versions +* by reporting bugs +* by suggesting new features +* by writing or editing documentation +* by writing specifications +* by writing code (**no patch is too small**: fix typos, add comments, clean up + inconsistent whitespace) +* by refactoring code +* by closing [issues][] +* by reviewing patches + +[issues]: https://github.com/intridea/multi_json/issues + +## Submitting an Issue +We use the [GitHub issue tracker][issues] to track bugs and features. Before +submitting a bug report or feature request, check to make sure it hasn't +already been submitted. When submitting a bug report, please include a [Gist][] +that includes a stack trace and any details that may be necessary to reproduce +the bug, including your gem version, Ruby version, and operating system. +Ideally, a bug report should include a pull request with failing specs. + +[gist]: https://gist.github.com/ + +## Submitting a Pull Request +1. [Fork the repository.][fork] +2. [Create a topic branch.][branch] +3. Add specs for your unimplemented feature or bug fix. +4. Run `bundle exec rake spec`. If your specs pass, return to step 3. +5. Implement your feature or bug fix. +6. Run `bundle exec rake spec`. If your specs fail, return to step 5. +7. Run `open coverage/index.html`. If your changes are not completely covered + by your tests, return to step 3. +8. Add, commit, and push your changes. +9. [Submit a pull request.][pr] + +[fork]: http://help.github.com/fork-a-repo/ +[branch]: http://learn.github.com/p/branching.html +[pr]: http://help.github.com/send-pull-requests/ diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/LICENSE.md b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/LICENSE.md new file mode 100644 index 0000000..1768f37 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/LICENSE.md @@ -0,0 +1,20 @@ +Copyright (c) 2010-2013 Michael Bleigh, Josh Kalderimis, Erik Michaels-Ober, Pavel Pravosud + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/README.md b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/README.md new file mode 100644 index 0000000..cf87849 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/README.md @@ -0,0 +1,121 @@ +# MultiJSON + +[![Gem Version](http://img.shields.io/gem/v/multi_json.svg)][gem] +[![Build Status](http://travis-ci.org/intridea/multi_json.svg)][travis] +[![Code Climate](https://codeclimate.com/github/intridea/multi_json.svg)][codeclimate] + +Lots of Ruby libraries parse JSON and everyone has their favorite JSON coder. +Instead of choosing a single JSON coder and forcing users of your library to be +stuck with it, you can use MultiJSON instead, which will simply choose the +fastest available JSON coder. Here's how to use it: + +```ruby +require 'multi_json' + +MultiJson.load('{"abc":"def"}') #=> {"abc" => "def"} +MultiJson.load('{"abc":"def"}', :symbolize_keys => true) #=> {:abc => "def"} +MultiJson.dump({:abc => 'def'}) # convert Ruby back to JSON +MultiJson.dump({:abc => 'def'}, :pretty => true) # encoded in a pretty form (if supported by the coder) +``` + +When loading invalid JSON, MultiJSON will throw a `MultiJson::ParseError`. `MultiJson::DecodeError` and `MultiJson::LoadError` are aliases for backwards compatibility. + +```ruby +begin + MultiJson.load('{invalid json}') +rescue MultiJson::ParseError => exception + exception.data # => "{invalid json}" + exception.cause # => JSON::ParserError: 795: unexpected token at '{invalid json}' +end +``` + +`ParseError` instance has `cause` reader which contains the original exception. +It also has `data` reader with the input that caused the problem. + +The `use` method, which sets the MultiJSON adapter, takes either a symbol or a +class (to allow for custom JSON parsers) that responds to both `.load` and `.dump` +at the class level. + +When MultiJSON fails to load the specified adapter, it'll throw `MultiJson::AdapterError` +which inherits from `ArgumentError`. + +MultiJSON tries to have intelligent defaulting. That is, if you have any of the +supported engines already loaded, it will utilize them before attempting to +load any. When loading, libraries are ordered by speed. First Oj, then Yajl, +then the JSON gem, then JSON pure. If no other JSON library is available, +MultiJSON falls back to [OkJson][], a simple, vendorable JSON parser. + +## Supported JSON Engines + +* [Oj][oj] Optimized JSON by Peter Ohler +* [Yajl][yajl] Yet Another JSON Library by Brian Lopez +* [JSON][json-gem] The default JSON gem with C-extensions (ships with Ruby 1.9+) +* [JSON Pure][json-gem] A Ruby variant of the JSON gem +* [NSJSONSerialization][nsjson] Wrapper for Apple's NSJSONSerialization in the Cocoa Framework (MacRuby only) +* [gson.rb][gson] A Ruby wrapper for google-gson library (JRuby only) +* [JrJackson][jrjackson] JRuby wrapper for Jackson (JRuby only) +* [OkJson][okjson] A simple, vendorable JSON parser + +## Supported Ruby Versions +This library aims to support and is [tested against][travis] the following Ruby +implementations: + +* Ruby 1.8 +* Ruby 1.9 +* Ruby 2.0 +* Ruby 2.1 +* Ruby 2.2 +* Ruby 2.4 +* Ruby 2.5 +* Ruby 2.6 +* Ruby 2.7 +* [JRuby][] + +If something doesn't work in one of these implementations, it's a bug. + +This library may inadvertently work (or seem to work) on other Ruby +implementations, however support will only be provided for the versions listed +above. + +If you would like this library to support another Ruby version, you may +volunteer to be a maintainer. Being a maintainer entails making sure all tests +run and pass on that implementation. When something breaks on your +implementation, you will be responsible for providing patches in a timely +fashion. If critical issues for a particular implementation exist at the time +of a major release, support for that Ruby version may be dropped. + +## Versioning + +This library aims to adhere to [Semantic Versioning 2.0.0][semver]. Violations +of this scheme should be reported as bugs. Specifically, if a minor or patch +version is released that breaks backward compatibility, that version should be +immediately yanked and/or a new version should be immediately released that +restores compatibility. Breaking changes to the public API will only be +introduced with new major versions. As a result of this policy, you can (and +should) specify a dependency on this gem using the [Pessimistic Version +Constraint][pvc] with two digits of precision. For example: + +```ruby +spec.add_dependency 'multi_json', '~> 1.0' +``` + +## Copyright +Copyright (c) 2010-2018 Michael Bleigh, Josh Kalderimis, Erik Michaels-Ober, +and Pavel Pravosud. See [LICENSE][] for details. + +[codeclimate]: https://codeclimate.com/github/intridea/multi_json +[gem]: https://rubygems.org/gems/multi_json +[gson]: https://github.com/avsej/gson.rb +[jrjackson]: https://github.com/guyboertje/jrjackson +[jruby]: http://www.jruby.org/ +[json-gem]: https://github.com/flori/json +[json-pure]: https://github.com/flori/json +[license]: LICENSE.md +[macruby]: http://www.macruby.org/ +[nsjson]: https://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html +[oj]: https://github.com/ohler55/oj +[okjson]: https://github.com/kr/okjson +[pvc]: http://docs.rubygems.org/read/chapter/16#page74 +[semver]: http://semver.org/ +[travis]: http://travis-ci.org/intridea/multi_json +[yajl]: https://github.com/brianmario/yajl-ruby diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json.rb new file mode 100644 index 0000000..5909370 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json.rb @@ -0,0 +1,161 @@ +require 'multi_json/options' +require 'multi_json/version' +require 'multi_json/adapter_error' +require 'multi_json/parse_error' +require 'multi_json/options_cache' + +module MultiJson + include Options + extend self + + def default_options=(value) + Kernel.warn "MultiJson.default_options setter is deprecated\n" \ + 'Use MultiJson.load_options and MultiJson.dump_options instead' + + self.load_options = self.dump_options = value + end + + def default_options + Kernel.warn "MultiJson.default_options is deprecated\n" \ + 'Use MultiJson.load_options or MultiJson.dump_options instead' + + load_options + end + + %w(cached_options reset_cached_options!).each do |method_name| + define_method method_name do |*| + Kernel.warn "MultiJson.#{method_name} method is deprecated and no longer used." + end + end + + ALIASES = {'jrjackson' => 'jr_jackson'} + + REQUIREMENT_MAP = [ + [:oj, 'oj'], + [:yajl, 'yajl'], + [:jr_jackson, 'jrjackson'], + [:json_gem, 'json/ext'], + [:gson, 'gson'], + [:json_pure, 'json/pure'], + ] + + # The default adapter based on what you currently + # have loaded and installed. First checks to see + # if any adapters are already loaded, then checks + # to see which are installed if none are loaded. + def default_adapter + return :oj if defined?(::Oj) + return :yajl if defined?(::Yajl) + return :jr_jackson if defined?(::JrJackson) + return :json_gem if defined?(::JSON::Ext::Parser) + return :gson if defined?(::Gson) + + REQUIREMENT_MAP.each do |adapter, library| + begin + require library + return adapter + rescue ::LoadError + next + end + end + + Kernel.warn '[WARNING] MultiJson is using the default adapter (ok_json). ' \ + 'We recommend loading a different JSON library to improve performance.' + + :ok_json + end + alias_method :default_engine, :default_adapter + + # Get the current adapter class. + def adapter + return @adapter if defined?(@adapter) && @adapter + + use nil # load default adapter + + @adapter + end + alias_method :engine, :adapter + + # Set the JSON parser utilizing a symbol, string, or class. + # Supported by default are: + # + # * :oj + # * :json_gem + # * :json_pure + # * :ok_json + # * :yajl + # * :nsjsonserialization (MacRuby only) + # * :gson (JRuby only) + # * :jr_jackson (JRuby only) + def use(new_adapter) + @adapter = load_adapter(new_adapter) + ensure + OptionsCache.reset + end + alias_method :adapter=, :use + alias_method :engine=, :use + + def load_adapter(new_adapter) + case new_adapter + when String, Symbol + load_adapter_from_string_name new_adapter.to_s + when NilClass, FalseClass + load_adapter default_adapter + when Class, Module + new_adapter + else + fail ::LoadError, new_adapter + end + rescue ::LoadError => exception + raise AdapterError.build(exception) + end + + # Decode a JSON string into Ruby. + # + # Options + # + # :symbolize_keys :: If true, will use symbols instead of strings for the keys. + # :adapter :: If set, the selected adapter will be used for this call. + def load(string, options = {}) + adapter = current_adapter(options) + begin + adapter.load(string, options) + rescue adapter::ParseError => exception + raise ParseError.build(exception, string) + end + end + alias_method :decode, :load + + def current_adapter(options = {}) + if (new_adapter = options[:adapter]) + load_adapter(new_adapter) + else + adapter + end + end + + # Encodes a Ruby object as JSON. + def dump(object, options = {}) + current_adapter(options).dump(object, options) + end + alias_method :encode, :dump + + # Executes passed block using specified adapter. + def with_adapter(new_adapter) + old_adapter = adapter + self.adapter = new_adapter + yield + ensure + self.adapter = old_adapter + end + alias_method :with_engine, :with_adapter + +private + + def load_adapter_from_string_name(name) + name = ALIASES.fetch(name, name) + require "multi_json/adapters/#{name.downcase}" + klass_name = name.to_s.split('_').map(&:capitalize) * '' + MultiJson::Adapters.const_get(klass_name) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapter.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapter.rb new file mode 100644 index 0000000..722be2f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapter.rb @@ -0,0 +1,49 @@ +require 'singleton' +require 'multi_json/options' + +module MultiJson + class Adapter + extend Options + include Singleton + + class << self + def defaults(action, value) + metaclass = class << self; self; end + + metaclass.instance_eval do + define_method("default_#{action}_options") { value } + end + end + + def load(string, options = {}) + string = string.read if string.respond_to?(:read) + fail self::ParseError if blank?(string) + instance.load(string, cached_load_options(options)) + end + + def dump(object, options = {}) + instance.dump(object, cached_dump_options(options)) + end + + private + + def blank?(input) + input.nil? || /\A\s*\z/ === input + rescue ArgumentError # invalid byte sequence in UTF-8 + false + end + + def cached_dump_options(options) + OptionsCache.fetch(:dump, options) do + dump_options(options).merge(MultiJson.dump_options(options)).merge!(options) + end + end + + def cached_load_options(options) + OptionsCache.fetch(:load, options) do + load_options(options).merge(MultiJson.load_options(options)).merge!(options) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapter_error.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapter_error.rb new file mode 100644 index 0000000..86902b6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapter_error.rb @@ -0,0 +1,15 @@ +module MultiJson + class AdapterError < ArgumentError + attr_reader :cause + + def self.build(original_exception) + message = "Did not recognize your adapter specification (#{original_exception.message})." + new(message).tap do |exception| + exception.instance_eval do + @cause = original_exception + set_backtrace original_exception.backtrace + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/gson.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/gson.rb new file mode 100644 index 0000000..797fbf4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/gson.rb @@ -0,0 +1,20 @@ +require 'gson' +require 'stringio' +require 'multi_json/adapter' + +module MultiJson + module Adapters + # Use the gson.rb library to dump/load. + class Gson < Adapter + ParseError = ::Gson::DecodeError + + def load(string, options = {}) + ::Gson::Decoder.new(options).decode(string) + end + + def dump(object, options = {}) + ::Gson::Encoder.new(options).encode(object) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/jr_jackson.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/jr_jackson.rb new file mode 100644 index 0000000..a7e6cd8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/jr_jackson.rb @@ -0,0 +1,25 @@ +require 'jrjackson' unless defined?(::JrJackson) +require 'multi_json/adapter' + +module MultiJson + module Adapters + # Use the jrjackson.rb library to dump/load. + class JrJackson < Adapter + ParseError = ::JrJackson::ParseError + + def load(string, options = {}) #:nodoc: + ::JrJackson::Json.load(string, options) + end + + if ::JrJackson::Json.method(:dump).arity == 1 + def dump(object, _) + ::JrJackson::Json.dump(object) + end + else + def dump(object, options = {}) + ::JrJackson::Json.dump(object, options) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/json_common.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/json_common.rb new file mode 100644 index 0000000..e188895 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/json_common.rb @@ -0,0 +1,23 @@ +require 'multi_json/adapter' + +module MultiJson + module Adapters + class JsonCommon < Adapter + defaults :load, :create_additions => false, :quirks_mode => true + + def load(string, options = {}) + if string.respond_to?(:force_encoding) + string = string.dup.force_encoding(::Encoding::ASCII_8BIT) + end + + options[:symbolize_names] = true if options.delete(:symbolize_keys) + ::JSON.parse(string, options) + end + + def dump(object, options = {}) + options.merge!(::JSON::PRETTY_STATE_PROTOTYPE.to_h) if options.delete(:pretty) + object.to_json(options) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/json_gem.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/json_gem.rb new file mode 100644 index 0000000..035de37 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/json_gem.rb @@ -0,0 +1,11 @@ +require 'json/ext' +require 'multi_json/adapters/json_common' + +module MultiJson + module Adapters + # Use the JSON gem to dump/load. + class JsonGem < JsonCommon + ParseError = ::JSON::ParserError + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/json_pure.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/json_pure.rb new file mode 100644 index 0000000..c5d7036 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/json_pure.rb @@ -0,0 +1,11 @@ +require 'json/pure' +require 'multi_json/adapters/json_common' + +module MultiJson + module Adapters + # Use JSON pure to dump/load. + class JsonPure < JsonCommon + ParseError = ::JSON::ParserError + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/nsjsonserialization.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/nsjsonserialization.rb new file mode 100644 index 0000000..1ae0850 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/nsjsonserialization.rb @@ -0,0 +1,35 @@ +# This adapter is here for legacy reasons. We can't really test it, so it's hard +# to tell if it's even working properly. If you're still using it, please +# consider migrating to any other adapter out there. +framework 'Foundation' +require 'multi_json/adapters/ok_json' + +module MultiJson + module Adapters + class Nsjsonserialization < MultiJson::Adapters::OkJson + ParseError = ::MultiJson::OkJson::Error + + def load(string, options = {}) + data = string.dataUsingEncoding(NSUTF8StringEncoding) + object = NSJSONSerialization.JSONObjectWithData(data, :options => NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves, :error => nil) + if object + object = symbolize_keys(object) if options[:symbolize_keys] + object + else + super(string, options) + end + end + + def dump(object, options = {}) + pretty = options[:pretty] ? NSJSONWritingPrettyPrinted : 0 + object = object.as_json if object.respond_to?(:as_json) + if NSJSONSerialization.isValidJSONObject(object) + data = NSJSONSerialization.dataWithJSONObject(object, :options => pretty, :error => nil) + NSMutableString.alloc.initWithData(data, :encoding => NSUTF8StringEncoding) + else + super(object, options) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/oj.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/oj.rb new file mode 100644 index 0000000..ea85e33 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/oj.rb @@ -0,0 +1,63 @@ +require 'set' +require 'oj' +require 'multi_json/adapter' + +module MultiJson + module Adapters + # Use the Oj library to dump/load. + class Oj < Adapter + defaults :load, :mode => :strict, :symbolize_keys => false + defaults :dump, :mode => :compat, :time_format => :ruby, :use_to_json => true + + # In certain cases OJ gem may throw JSON::ParserError exception instead + # of its own class. Also, we can't expect ::JSON::ParserError and + # ::Oj::ParseError to always be defined, since it's often not the case. + # Because of this, we can't reference those classes directly and have to + # do string comparison instead. This will not catch subclasses, but it + # shouldn't be a problem since the library is not known to be using it + # (at least for now). + class ParseError < ::SyntaxError + WRAPPED_CLASSES = %w[Oj::ParseError JSON::ParserError].to_set.freeze + + def self.===(exception) + case exception + when ::SyntaxError + true + else + WRAPPED_CLASSES.include?(exception.class.to_s) + end + end + end + + def load(string, options = {}) + options[:symbol_keys] = options[:symbolize_keys] + ::Oj.load(string, options) + end + + case ::Oj::VERSION + when /\A2\./ + def dump(object, options = {}) + options.merge!(:indent => 2) if options[:pretty] + options[:indent] = options[:indent].to_i if options[:indent] + ::Oj.dump(object, options) + end + when /\A3\./ + PRETTY_STATE_PROTOTYPE = { + :indent => " ", + :space => " ", + :space_before => "", + :object_nl => "\n", + :array_nl => "\n", + :ascii_only => false, + } + + def dump(object, options = {}) + options.merge!(PRETTY_STATE_PROTOTYPE.dup) if options.delete(:pretty) + ::Oj.dump(object, options) + end + else + fail "Unsupported Oj version: #{::Oj::VERSION}" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/ok_json.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/ok_json.rb new file mode 100644 index 0000000..7f51145 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/ok_json.rb @@ -0,0 +1,23 @@ +require 'multi_json/adapter' +require 'multi_json/convertible_hash_keys' +require 'multi_json/vendor/okjson' + +module MultiJson + module Adapters + class OkJson < Adapter + include ConvertibleHashKeys + ParseError = ::MultiJson::OkJson::Error + + def load(string, options = {}) + result = ::MultiJson::OkJson.decode("[#{string}]").first + options[:symbolize_keys] ? symbolize_keys(result) : result + rescue ArgumentError # invalid byte sequence in UTF-8 + raise ParseError + end + + def dump(object, _ = {}) + ::MultiJson::OkJson.valenc(stringify_keys(object)) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/yajl.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/yajl.rb new file mode 100644 index 0000000..1c297a5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/adapters/yajl.rb @@ -0,0 +1,19 @@ +require 'yajl' +require 'multi_json/adapter' + +module MultiJson + module Adapters + # Use the Yajl-Ruby library to dump/load. + class Yajl < Adapter + ParseError = ::Yajl::ParseError + + def load(string, options = {}) + ::Yajl::Parser.new(:symbolize_keys => options[:symbolize_keys]).parse(string) + end + + def dump(object, options = {}) + ::Yajl::Encoder.encode(object, options) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/convertible_hash_keys.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/convertible_hash_keys.rb new file mode 100644 index 0000000..1253e66 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/convertible_hash_keys.rb @@ -0,0 +1,43 @@ +module MultiJson + module ConvertibleHashKeys + private + + def symbolize_keys(hash) + prepare_hash(hash) do |key| + key.respond_to?(:to_sym) ? key.to_sym : key + end + end + + def stringify_keys(hash) + prepare_hash(hash) do |key| + key.respond_to?(:to_s) ? key.to_s : key + end + end + + def prepare_hash(hash, &key_modifier) + return hash unless block_given? + case hash + when Array + hash.map do |value| + prepare_hash(value, &key_modifier) + end + when Hash + hash.inject({}) do |result, (key, value)| + new_key = key_modifier.call(key) + new_value = prepare_hash(value, &key_modifier) + result.merge! new_key => new_value + end + when String, Numeric, true, false, nil + hash + else + if hash.respond_to?(:to_json) + hash + elsif hash.respond_to?(:to_s) + hash.to_s + else + hash + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/options.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/options.rb new file mode 100644 index 0000000..a56a90e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/options.rb @@ -0,0 +1,39 @@ +module MultiJson + module Options + def load_options=(options) + OptionsCache.reset + @load_options = options + end + + def dump_options=(options) + OptionsCache.reset + @dump_options = options + end + + def load_options(*args) + defined?(@load_options) && get_options(@load_options, *args) || default_load_options + end + + def dump_options(*args) + defined?(@dump_options) && get_options(@dump_options, *args) || default_dump_options + end + + def default_load_options + @default_load_options ||= {} + end + + def default_dump_options + @default_dump_options ||= {} + end + + private + + def get_options(options, *args) + if options.respond_to?(:call) && options.arity + options.arity == 0 ? options[] : options[*args] + elsif options.respond_to?(:to_hash) + options.to_hash + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/options_cache.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/options_cache.rb new file mode 100644 index 0000000..87fc9a0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/options_cache.rb @@ -0,0 +1,29 @@ +module MultiJson + module OptionsCache + extend self + + def reset + @dump_cache = {} + @load_cache = {} + end + + def fetch(type, key, &block) + cache = instance_variable_get("@#{type}_cache") + cache.key?(key) ? cache[key] : write(cache, key, &block) + end + + private + + # Normally MultiJson is used with a few option sets for both dump/load + # methods. When options are generated dynamically though, every call would + # cause a cache miss and the cache would grow indefinitely. To prevent + # this, we just reset the cache every time the number of keys outgrows + # 1000. + MAX_CACHE_SIZE = 1000 + + def write(cache, key) + cache.clear if cache.length >= MAX_CACHE_SIZE + cache[key] = yield + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/parse_error.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/parse_error.rb new file mode 100644 index 0000000..407a622 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/parse_error.rb @@ -0,0 +1,17 @@ +module MultiJson + class ParseError < StandardError + attr_reader :data, :cause + + def self.build(original_exception, data) + new(original_exception.message).tap do |exception| + exception.instance_eval do + @cause = original_exception + set_backtrace original_exception.backtrace + @data = data + end + end + end + end + + DecodeError = LoadError = ParseError # Legacy support +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/vendor/okjson.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/vendor/okjson.rb new file mode 100644 index 0000000..0d5f814 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/vendor/okjson.rb @@ -0,0 +1,606 @@ +# encoding: UTF-8 +# +# Copyright 2011, 2012 Keith Rarick +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +# See https://github.com/kr/okjson for updates. + +require 'stringio' + +module MultiJson + # Some parts adapted from + # https://golang.org/src/encoding/json/decode.go and + # https://golang.org/src/unicode/utf8/utf8.go + module OkJson + Upstream = '45' + extend self + + + # Decodes a json document in string s and + # returns the corresponding ruby value. + # String s must be valid UTF-8. If you have + # a string in some other encoding, convert + # it first. + # + # String values in the resulting structure + # will be UTF-8. + def decode(s) + ts = lex(s) + v, ts = textparse(ts) + if ts.length > 0 + raise Error, 'trailing garbage' + end + v + end + + + # Encodes x into a json text. It may contain only + # Array, Hash, String, Numeric, true, false, nil. + # (Note, this list excludes Symbol.) + # X itself must be an Array or a Hash. + # No other value can be encoded, and an error will + # be raised if x contains any other value, such as + # Nan, Infinity, Symbol, and Proc, or if a Hash key + # is not a String. + # Strings contained in x must be valid UTF-8. + def encode(x) + case x + when Hash then objenc(x) + when Array then arrenc(x) + else + raise Error, 'root value must be an Array or a Hash' + end + end + + + def valenc(x) + case x + when Hash then objenc(x) + when Array then arrenc(x) + when String then strenc(x) + when Numeric then numenc(x) + when true then "true" + when false then "false" + when nil then "null" + else + if x.respond_to?(:to_json) + x.to_json + else + raise Error, "cannot encode #{x.class}: #{x.inspect}" + end + end + end + + + private + + + # Parses a "json text" in the sense of RFC 4627. + # Returns the parsed value and any trailing tokens. + # Note: this is almost the same as valparse, + # except that it does not accept atomic values. + def textparse(ts) + if ts.length <= 0 + raise Error, 'empty' + end + + typ, _, val = ts[0] + case typ + when '{' then objparse(ts) + when '[' then arrparse(ts) + else + raise Error, "unexpected #{val.inspect}" + end + end + + + # Parses a "value" in the sense of RFC 4627. + # Returns the parsed value and any trailing tokens. + def valparse(ts) + if ts.length <= 0 + raise Error, 'empty' + end + + typ, _, val = ts[0] + case typ + when '{' then objparse(ts) + when '[' then arrparse(ts) + when :val,:str then [val, ts[1..-1]] + else + raise Error, "unexpected #{val.inspect}" + end + end + + + # Parses an "object" in the sense of RFC 4627. + # Returns the parsed value and any trailing tokens. + def objparse(ts) + ts = eat('{', ts) + obj = {} + + if ts[0][0] == '}' + return obj, ts[1..-1] + end + + k, v, ts = pairparse(ts) + obj[k] = v + + if ts[0][0] == '}' + return obj, ts[1..-1] + end + + loop do + ts = eat(',', ts) + + k, v, ts = pairparse(ts) + obj[k] = v + + if ts[0][0] == '}' + return obj, ts[1..-1] + end + end + end + + + # Parses a "member" in the sense of RFC 4627. + # Returns the parsed values and any trailing tokens. + def pairparse(ts) + (typ, _, k), ts = ts[0], ts[1..-1] + if typ != :str + raise Error, "unexpected #{k.inspect}" + end + ts = eat(':', ts) + v, ts = valparse(ts) + [k, v, ts] + end + + + # Parses an "array" in the sense of RFC 4627. + # Returns the parsed value and any trailing tokens. + def arrparse(ts) + ts = eat('[', ts) + arr = [] + + if ts[0][0] == ']' + return arr, ts[1..-1] + end + + v, ts = valparse(ts) + arr << v + + if ts[0][0] == ']' + return arr, ts[1..-1] + end + + loop do + ts = eat(',', ts) + + v, ts = valparse(ts) + arr << v + + if ts[0][0] == ']' + return arr, ts[1..-1] + end + end + end + + + def eat(typ, ts) + if ts[0][0] != typ + raise Error, "expected #{typ} (got #{ts[0].inspect})" + end + ts[1..-1] + end + + + # Scans s and returns a list of json tokens, + # excluding white space (as defined in RFC 4627). + def lex(s) + ts = [] + while s.length > 0 + typ, lexeme, val = tok(s) + if typ == nil + raise Error, "invalid character at #{s[0,10].inspect}" + end + if typ != :space + ts << [typ, lexeme, val] + end + s = s[lexeme.length..-1] + end + ts + end + + + # Scans the first token in s and + # returns a 3-element list, or nil + # if s does not begin with a valid token. + # + # The first list element is one of + # '{', '}', ':', ',', '[', ']', + # :val, :str, and :space. + # + # The second element is the lexeme. + # + # The third element is the value of the + # token for :val and :str, otherwise + # it is the lexeme. + def tok(s) + case s[0] + when ?{ then ['{', s[0,1], s[0,1]] + when ?} then ['}', s[0,1], s[0,1]] + when ?: then [':', s[0,1], s[0,1]] + when ?, then [',', s[0,1], s[0,1]] + when ?[ then ['[', s[0,1], s[0,1]] + when ?] then [']', s[0,1], s[0,1]] + when ?n then nulltok(s) + when ?t then truetok(s) + when ?f then falsetok(s) + when ?" then strtok(s) + when Spc, ?\t, ?\n, ?\r then [:space, s[0,1], s[0,1]] + else + numtok(s) + end + end + + + def nulltok(s); s[0,4] == 'null' ? [:val, 'null', nil] : [] end + def truetok(s); s[0,4] == 'true' ? [:val, 'true', true] : [] end + def falsetok(s); s[0,5] == 'false' ? [:val, 'false', false] : [] end + + + def numtok(s) + m = /(-?(?:[1-9][0-9]+|[0-9]))([.][0-9]+)?([eE][+-]?[0-9]+)?/.match(s) + if m && m.begin(0) == 0 + if !m[2] && !m[3] + [:val, m[0], Integer(m[0])] + elsif m[2] + [:val, m[0], Float(m[0])] + else + [:val, m[0], Integer(m[1])*(10**m[3][1..-1].to_i(10))] + end + else + [] + end + end + + + def strtok(s) + m = /"([^"\\]|\\["\/\\bfnrt]|\\u[0-9a-fA-F]{4})*"/.match(s) + if ! m + raise Error, "invalid string literal at #{abbrev(s)}" + end + [:str, m[0], unquote(m[0])] + end + + + def abbrev(s) + t = s[0,10] + p = t['`'] + t = t[0,p] if p + t = t + '...' if t.length < s.length + '`' + t + '`' + end + + + # Converts a quoted json string literal q into a UTF-8-encoded string. + # The rules are different than for Ruby, so we cannot use eval. + # Unquote will raise an error if q contains control characters. + def unquote(q) + q = q[1...-1] + a = q.dup # allocate a big enough string + # In ruby >= 1.9, a[w] is a codepoint, not a byte. + if rubydoesenc? + a.force_encoding('UTF-8') + end + r, w = 0, 0 + while r < q.length + c = q[r] + if c == ?\\ + r += 1 + if r >= q.length + raise Error, "string literal ends with a \"\\\": \"#{q}\"" + end + + case q[r] + when ?",?\\,?/,?' + a[w] = q[r] + r += 1 + w += 1 + when ?b,?f,?n,?r,?t + a[w] = Unesc[q[r]] + r += 1 + w += 1 + when ?u + r += 1 + uchar = begin + hexdec4(q[r,4]) + rescue RuntimeError => e + raise Error, "invalid escape sequence \\u#{q[r,4]}: #{e}" + end + r += 4 + if surrogate? uchar + if q.length >= r+6 + uchar1 = hexdec4(q[r+2,4]) + uchar = subst(uchar, uchar1) + if uchar != Ucharerr + # A valid pair; consume. + r += 6 + end + end + end + if rubydoesenc? + a[w] = '' << uchar + w += 1 + else + w += ucharenc(a, w, uchar) + end + else + raise Error, "invalid escape char #{q[r]} in \"#{q}\"" + end + elsif c == ?" || c < Spc + raise Error, "invalid character in string literal \"#{q}\"" + else + # Copy anything else byte-for-byte. + # Valid UTF-8 will remain valid UTF-8. + # Invalid UTF-8 will remain invalid UTF-8. + # In ruby >= 1.9, c is a codepoint, not a byte, + # in which case this is still what we want. + a[w] = c + r += 1 + w += 1 + end + end + a[0,w] + end + + + # Encodes unicode character u as UTF-8 + # bytes in string a at position i. + # Returns the number of bytes written. + def ucharenc(a, i, u) + if u <= Uchar1max + a[i] = (u & 0xff).chr + 1 + elsif u <= Uchar2max + a[i+0] = (Utag2 | ((u>>6)&0xff)).chr + a[i+1] = (Utagx | (u&Umaskx)).chr + 2 + elsif u <= Uchar3max + a[i+0] = (Utag3 | ((u>>12)&0xff)).chr + a[i+1] = (Utagx | ((u>>6)&Umaskx)).chr + a[i+2] = (Utagx | (u&Umaskx)).chr + 3 + else + a[i+0] = (Utag4 | ((u>>18)&0xff)).chr + a[i+1] = (Utagx | ((u>>12)&Umaskx)).chr + a[i+2] = (Utagx | ((u>>6)&Umaskx)).chr + a[i+3] = (Utagx | (u&Umaskx)).chr + 4 + end + end + + + def hexdec4(s) + if s.length != 4 + raise Error, 'short' + end + (nibble(s[0])<<12) | (nibble(s[1])<<8) | (nibble(s[2])<<4) | nibble(s[3]) + end + + + def subst(u1, u2) + if Usurr1 <= u1 && u1 < Usurr2 && Usurr2 <= u2 && u2 < Usurr3 + return ((u1-Usurr1)<<10) | (u2-Usurr2) + Usurrself + end + return Ucharerr + end + + + def surrogate?(u) + Usurr1 <= u && u < Usurr3 + end + + + def nibble(c) + if ?0 <= c && c <= ?9 then c.ord - ?0.ord + elsif ?a <= c && c <= ?z then c.ord - ?a.ord + 10 + elsif ?A <= c && c <= ?Z then c.ord - ?A.ord + 10 + else + raise Error, "invalid hex code #{c}" + end + end + + + def objenc(x) + '{' + x.map{|k,v| keyenc(k) + ':' + valenc(v)}.join(',') + '}' + end + + + def arrenc(a) + '[' + a.map{|x| valenc(x)}.join(',') + ']' + end + + + def keyenc(k) + case k + when String then strenc(k) + else + raise Error, "Hash key is not a string: #{k.inspect}" + end + end + + + def strenc(s) + t = StringIO.new + t.putc(?") + r = 0 + + while r < s.length + case s[r] + when ?" then t.print('\\"') + when ?\\ then t.print('\\\\') + when ?\b then t.print('\\b') + when ?\f then t.print('\\f') + when ?\n then t.print('\\n') + when ?\r then t.print('\\r') + when ?\t then t.print('\\t') + else + c = s[r] + # In ruby >= 1.9, s[r] is a codepoint, not a byte. + if rubydoesenc? + begin + # c.ord will raise an error if c is invalid UTF-8 + if c.ord < Spc.ord + c = "\\u%04x" % [c.ord] + end + t.write(c) + rescue + t.write(Ustrerr) + end + elsif c < Spc + t.write("\\u%04x" % c) + elsif Spc <= c && c <= ?~ + t.putc(c) + else + n = ucharcopy(t, s, r) # ensure valid UTF-8 output + r += n - 1 # r is incremented below + end + end + r += 1 + end + t.putc(?") + t.string + end + + + def numenc(x) + if ((x.nan? || x.infinite?) rescue false) + raise Error, "Numeric cannot be represented: #{x}" + end + "#{x}" + end + + + # Copies the valid UTF-8 bytes of a single character + # from string s at position i to I/O object t, and + # returns the number of bytes copied. + # If no valid UTF-8 char exists at position i, + # ucharcopy writes Ustrerr and returns 1. + def ucharcopy(t, s, i) + n = s.length - i + raise Utf8Error if n < 1 + + c0 = s[i].ord + + # 1-byte, 7-bit sequence? + if c0 < Utagx + t.putc(c0) + return 1 + end + + raise Utf8Error if c0 < Utag2 # unexpected continuation byte? + + raise Utf8Error if n < 2 # need continuation byte + c1 = s[i+1].ord + raise Utf8Error if c1 < Utagx || Utag2 <= c1 + + # 2-byte, 11-bit sequence? + if c0 < Utag3 + raise Utf8Error if ((c0&Umask2)<<6 | (c1&Umaskx)) <= Uchar1max + t.putc(c0) + t.putc(c1) + return 2 + end + + # need second continuation byte + raise Utf8Error if n < 3 + + c2 = s[i+2].ord + raise Utf8Error if c2 < Utagx || Utag2 <= c2 + + # 3-byte, 16-bit sequence? + if c0 < Utag4 + u = (c0&Umask3)<<12 | (c1&Umaskx)<<6 | (c2&Umaskx) + raise Utf8Error if u <= Uchar2max + t.putc(c0) + t.putc(c1) + t.putc(c2) + return 3 + end + + # need third continuation byte + raise Utf8Error if n < 4 + c3 = s[i+3].ord + raise Utf8Error if c3 < Utagx || Utag2 <= c3 + + # 4-byte, 21-bit sequence? + if c0 < Utag5 + u = (c0&Umask4)<<18 | (c1&Umaskx)<<12 | (c2&Umaskx)<<6 | (c3&Umaskx) + raise Utf8Error if u <= Uchar3max + t.putc(c0) + t.putc(c1) + t.putc(c2) + t.putc(c3) + return 4 + end + + raise Utf8Error + rescue Utf8Error + t.write(Ustrerr) + return 1 + end + + + def rubydoesenc? + ::String.method_defined?(:force_encoding) + end + + + class Utf8Error < ::StandardError + end + + + class Error < ::StandardError + end + + + Utagx = 0b1000_0000 + Utag2 = 0b1100_0000 + Utag3 = 0b1110_0000 + Utag4 = 0b1111_0000 + Utag5 = 0b1111_1000 + Umaskx = 0b0011_1111 + Umask2 = 0b0001_1111 + Umask3 = 0b0000_1111 + Umask4 = 0b0000_0111 + Uchar1max = (1<<7) - 1 + Uchar2max = (1<<11) - 1 + Uchar3max = (1<<16) - 1 + Ucharerr = 0xFFFD # unicode "replacement char" + Ustrerr = "\xef\xbf\xbd" # unicode "replacement char" + Usurrself = 0x10000 + Usurr1 = 0xd800 + Usurr2 = 0xdc00 + Usurr3 = 0xe000 + + Spc = ' '[0] + Unesc = {?b=>?\b, ?f=>?\f, ?n=>?\n, ?r=>?\r, ?t=>?\t} + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/version.rb b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/version.rb new file mode 100644 index 0000000..1fbe1db --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/multi_json-1.15.0/lib/multi_json/version.rb @@ -0,0 +1,17 @@ +module MultiJson + class Version + MAJOR = 1 unless defined? MultiJson::Version::MAJOR + MINOR = 15 unless defined? MultiJson::Version::MINOR + PATCH = 0 unless defined? MultiJson::Version::PATCH + PRE = nil unless defined? MultiJson::Version::PRE + + class << self + # @return [String] + def to_s + [MAJOR, MINOR, PATCH, PRE].compact.join('.') + end + end + end + + VERSION = Version.to_s.freeze +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/LICENSE b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/LICENSE new file mode 100644 index 0000000..bc53b03 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2013-2017 Konstantin Haase +Copyright (c) 2016-2017 Zachary Scott + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/README.md b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/README.md new file mode 100644 index 0000000..e8ec2e9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/README.md @@ -0,0 +1,853 @@ +# The Amazing Mustermann + +*Make sure you view the correct docs: [latest release](http://rubydoc.info/gems/mustermann/frames), [master](http://rubydoc.info/github/rkh/mustermann/master/frames).* + +Welcome to [Mustermann](http://en.wikipedia.org/wiki/List_of_placeholder_names_by_language#German). Mustermann is your personal string matching expert. As an expert in the field of strings and patterns, Mustermann keeps its runtime dependencies to a minimum and is fully covered with specs and documentation. + +Given a string pattern, Mustermann will turn it into an object that behaves like a regular expression and has comparable performance characteristics. + +``` ruby +if '/foo/bar' =~ Mustermann.new('/foo/*') + puts 'it works!' +end + +case 'something.png' +when Mustermann.new('foo/*') then puts "prefixed with foo" +when Mustermann.new('*.pdf') then puts "it's a PDF" +when Mustermann.new('*.png') then puts "it's an image" +end + +pattern = Mustermann.new('/:prefix/*.*') +pattern.params('/a/b.c') # => { "prefix" => "a", splat => ["b", "c"] } +``` + +## Overview + +### Features + +* **[Pattern Types](#-pattern-types):** Mustermann supports a wide variety of different pattern types, making it compatible with a large variety of existing software. +* **[Fine Grained Control](#-available-options):** You can easily adjust matching behavior and add constraints to the placeholders and capture groups. +* **[Binary Operators](#-binary-operators) and [Concatenation](#-concatenation):** Patterns can be combined into composite patterns using binary operators. +* **[Regexp Look Alike](#-regexp-look-alike):** Mustermann patterns can be used as a replacement for regular expressions. +* **[Parameter Parsing](#-parameter-parsing):** Mustermann can parse matched parameters into a Sinatra-style "params" hash, including type casting. +* **[Peeking](#-peeking):** Lets you check if the beginning of a string matches a pattern. +* **[Expanding](#-expanding):** Besides parsing a parameters from an input string, a pattern object can also be used to generate a string from a set of parameters. +* **[Generating Templates](#-generating-templates):** This comes in handy when wanting to hand on patterns rather than fully expanded strings as part of an external API. +* **[Proc Look Alike](#-proc-look-alike):** Pass on a pattern instead of a block. +* **[Duck Typing](#-duck-typing):** You can create your own pattern-like objects by implementing `to_pattern`. +* **[Performance](#-performance):** Patterns are implemented with both performance and a low memory footprint in mind. + +### Additional Tooling + +These features are included in the library, but not loaded by default + +* **[Mapper](#-mapper):** A simple tool for mapping one string to another based on patterns. +* **[Sinatra Integration](#-sinatra-integration):** Mustermann can be used as a [Sinatra](http://www.sinatrarb.com/) extension. Sinatra 2.0 and beyond will use Mustermann by default. + + +## Pattern Types + +Mustermann support multiple pattern types. A pattern type defines the syntax, matching semantics and whether certain features, like [expanding](#-expanding) and [generating templates](#-generating-templates), are available. + +You can create a pattern of a certain type by passing `type` option to `Mustermann.new`: + +``` ruby +require 'mustermann' +pattern = Mustermann.new('/*/**', type: :shell) +``` + +Note that this will use the type as suggestion: When passing in a string argument, it will create a pattern of the given type, but it might choose a different type for other objects (a regular expression argument will always result in a [regexp](#-pattern-details-regexp) pattern, a symbol always in a [sinatra](#-pattern-details-sinatra) pattern, etc). + +Alternatively, you can also load and instantiate the pattern type directly: + +``` ruby +require 'mustermann/shell' +pattern = Mustermann::Shell.new('/*/**') +``` + +Mustermann itself includes the [sinatra](#-sinatra-pattern), [identity](#-identity-pattern) and [regexp](#-regexp-pattern) pattern types. Other pattern types are available as separate gems. + + +## Binary Operators + +Patterns can be combined via binary operators. These are: + +* `|` (or): Resulting pattern matches if at least one of the input pattern matches. +* `&` (and): Resulting pattern matches if all input patterns match. +* `^` (xor): Resulting pattern matches if exactly one of the input pattern matches. + +``` ruby +require 'mustermann' + +first = Mustermann.new('/foo/:input') +second = Mustermann.new('/:input/bar') + +first | second === "/foo/foo" # => true +first | second === "/foo/bar" # => true + +first & second === "/foo/foo" # => false +first & second === "/foo/bar" # => true + +first ^ second === "/foo/foo" # => true +first ^ second === "/foo/bar" # => false +``` + +These resulting objects are fully functional pattern objects, allowing you to call methods like `params` or `to_proc` on them. Moreover, *or* patterns created solely from expandable patterns will also be expandable. The same logic also applies to generating templates from *or* patterns. + + +## Concatenation + +Similar to [Binary Operators](#-binary-operators), two patterns can be concatenated using `+`. + +``` ruby +require 'mustermann' + +prefix = Mustermann.new("/:prefix") +about = prefix + "/about" + +about.params("/main/about") # => {"prefix" => "main"} +``` + +Patterns of different types can be mixed. The availability of `to_templates` and `expand` depends on the patterns being concatenated. + + +## Regexp Look Alike + +Pattern objects mimic Ruby's `Regexp` class by implementing `match`, `=~`, `===`, `names` and `named_captures`. + +``` ruby +require 'mustermann' + +pattern = Mustermann.new('/:page') +pattern.match('/') # => nil +pattern.match('/home') # => # +pattern =~ '/home' # => 0 +pattern === '/home' # => true (this allows using it in case statements) +pattern.names # => ['page'] +pattern.names # => {"page"=>[1]} + +pattern = Mustermann.new('/home', type: :identity) +pattern.match('/') # => nil +pattern.match('/home') # => # +pattern =~ '/home' # => 0 +pattern === '/home' # => true (this allows using it in case statements) +pattern.names # => [] +pattern.names # => {} +``` + +Moreover, patterns based on regular expressions (all but `identity` and `shell`) automatically convert to regular expressions when needed: + +``` ruby +require 'mustermann' + +pattern = Mustermann.new('/:page') +union = Regexp.union(pattern, /^$/) + +union =~ "/foo" # => 0 +union =~ "" # => 0 + +Regexp.try_convert(pattern) # => /.../ +``` + +This way, unless some code explicitly checks the class for a regular expression, you should be able to pass in a pattern object instead even if the code in question was not written with Mustermann in mind. + + +## Parameter Parsing + +Besides being a `Regexp` look-alike, Mustermann also adds a `params` method, that will give you a Sinatra-style hash: + +``` ruby +require 'mustermann' + +pattern = Mustermann.new('/:prefix/*.*') +pattern.params('/a/b.c') # => { "prefix" => "a", splat => ["b", "c"] } +``` + +For patterns with typed captures, it will also automatically convert them: + +``` ruby +require 'mustermann' + +pattern = Mustermann.new('//', type: :flask) +pattern.params('/page/10') # => { "prefix" => "page", "id" => 10 } +``` + + +## Peeking + +Peeking gives the option to match a pattern against the beginning of a string rather the full string. Patterns come with four methods for peeking: + +* `peek` returns the matching substring. +* `peek_size` returns the number of characters matching. +* `peek_match` will return a `MatchData` or `Mustermann::SimpleMatch` (just like `match` does for the full string) +* `peek_params` will return the `params` hash parsed from the substring and the number of characters. + +All of the above will turn `nil` if there was no match. + +``` ruby +require 'mustermann' + +pattern = Mustermann.new('/:prefix') +pattern.peek('/foo/bar') # => '/foo' +pattern.peek_size('/foo/bar') # => 4 + +path_info = '/foo/bar' +params, size = patter.peek_params(path_info) # params == { "prefix" => "foo" } +rest = path_info[size..-1] # => "/bar" +``` + + +## Expanding + +Similarly to parsing, it is also possible to generate a string from a pattern by expanding it with a hash. +For simple expansions, you can use `Pattern#expand`. + +``` ruby +pattern = Mustermann.new('/:file(.:ext)?') +pattern.expand(file: 'pony') # => "/pony" +pattern.expand(file: 'pony', ext: 'jpg') # => "/pony.jpg" +pattern.expand(ext: 'jpg') # raises Mustermann::ExpandError +``` + +Expanding can be useful for instance when implementing link helpers. + +### Expander Objects + +To get fine-grained control over expansion, you can use `Mustermann::Expander` directly. + +You can create an expander object directly from a string: + +``` ruby +require 'mustermann/expander' +expander = Mustermann::Expander("/:file.jpg") +expander.expand(file: 'pony') # => "/pony.jpg" + +expander = Mustermann::Expander(":file(.:ext)", type: :rails) +expander.expand(file: 'pony', ext: 'jpg') # => "/pony.jpg" +``` + +Or you can pass it a pattern instance: + +``` ruby +require 'mustermann' +pattern = Mustermann.new("/:file") + +require 'mustermann/expander' +expander = Mustermann::Expander.new(pattern) +``` + +### Expanding Multiple Patterns + +You can add patterns to an expander object via `<<`: + +``` ruby +require 'mustermann' + +expander = Mustermann::Expander.new +expander << "/users/:user_id" +expander << "/pages/:page_id" + +expander.expand(user_id: 15) # => "/users/15" +expander.expand(page_id: 58) # => "/pages/58" +``` + +You can set pattern options when creating the expander: + +``` ruby +require 'mustermann' + +expander = Mustermann::Expander.new(type: :template) +expander << "/users/{user_id}" +expander << "/pages/{page_id}" +``` + +Additionally, it is possible to combine patterns of different types: + +``` ruby +require 'mustermann' + +expander = Mustermann::Expander.new +expander << Mustermann.new("/users/{user_id}", type: :template) +expander << Mustermann.new("/pages/:page_id", type: :rails) +``` + +### Handling Additional Values + +The handling of additional values passed in to `expand` can be changed by setting the `additional_values` option: + +``` ruby +require 'mustermann' + +expander = Mustermann::Expander.new("/:slug", additional_values: :raise) +expander.expand(slug: "foo", value: "bar") # raises Mustermann::ExpandError + +expander = Mustermann::Expander.new("/:slug", additional_values: :ignore) +expander.expand(slug: "foo", value: "bar") # => "/foo" + +expander = Mustermann::Expander.new("/:slug", additional_values: :append) +expander.expand(slug: "foo", value: "bar") # => "/foo?value=bar" +``` + +It is also possible to pass this directly to the `expand` call: + +``` ruby +require 'mustermann' + +pattern = Mustermann.new('/:slug') +pattern.expand(:append, slug: "foo", value: "bar") # => "/foo?value=bar" +``` + + +## Generating Templates + +You can generate a list of URI templates that correspond to a Mustermann pattern (it is a list rather than a single template, as most pattern types are significantly more expressive than URI templates). + +This comes in quite handy since URI templates are not made for pattern matching. That way you can easily use a more precise template syntax and have it automatically generate hypermedia links for you. + +Template generation is supported by almost all patterns (notable exceptions are `shell`, `regexp` and `simple` patterns). + +``` ruby +require 'mustermann' + +Mustermann.new("/:name").to_templates # => ["/{name}"] +Mustermann.new("/:foo(@:bar)?/*baz").to_templates # => ["/{foo}@{bar}/{+baz}", "/{foo}/{+baz}"] +Mustermann.new("/{name}", type: :template).to_templates # => ["/{name}" +``` + +Union Composite patterns (with the | operator) support template generation if all patterns they are composed of also support it. + +``` ruby +require 'mustermann' + +pattern = Mustermann.new('/:name') +pattern |= Mustermann.new('/{name}', type: :template) +pattern |= Mustermann.new('/example/*nested') +pattern.to_templates # => ["/{name}", "/example/{+nested}"] +``` + +If accepting arbitrary patterns, you can and should use `respond_to?` to check feature availability. + +``` ruby +if pattern.respond_to? :to_templates + pattern.to_templates +else + warn "does not support template generation" +end +``` + + +## Proc Look Alike + +Patterns implement `to_proc`: + +``` ruby +require 'mustermann' +pattern = Mustermann.new('/foo') +callback = pattern.to_proc # => # + +callback.call('/foo') # => true +callback.call('/bar') # => false +``` + +They can therefore be easily passed to methods expecting a block: + +``` ruby +require 'mustermann' + +list = ["foo", "example@email.com", "bar"] +pattern = Mustermann.new(":name@:domain.:tld") +email = list.detect(&pattern) # => "example@email.com" +``` + + +## Mapper + + +You can use a mapper to transform strings according to two or more mappings: + +``` ruby +require 'mustermann/mapper' + +mapper = Mustermann::Mapper.new("/:page(.:format)?" => ["/:page/view.:format", "/:page/view.html"]) +mapper['/foo'] # => "/foo/view.html" +mapper['/foo.xml'] # => "/foo/view.xml" +mapper['/foo/bar'] # => "/foo/bar" +``` + + +## Sinatra Integration + +All patterns implement `match`, which means they can be dropped into Sinatra and other Rack routers: + +``` ruby +require 'sinatra' +require 'mustermann' + +get Mustermann.new('/:foo') do + params[:foo] +end +``` + +In fact, since using this with Sinatra is the main use case, it comes with a build-in extension for **Sinatra 1.x**. + +``` ruby +require 'sinatra' +require 'mustermann' + +register Mustermann + +# this will use Mustermann rather than the built-in pattern matching +get '/:slug(.ext)?' do + params[:slug] +end +``` + +### Configuration + +You can change what pattern type you want to use for your app via the `pattern` option: + +``` ruby +require 'sinatra/base' +require 'mustermann' + +class MyApp < Sinatra::Base + register Mustermann + set :pattern, type: :shell + + get '/images/*.png' do + send_file request.path_info + end + + get '/index{.htm,.html,}' do + erb :index + end +end +``` + +You can use the same setting for options: + +``` ruby +require 'sinatra' +require 'mustermann' + +register Mustermann +set :pattern, capture: { ext: %w[png jpg html txt] } + +get '/:slug(.:ext)?' do + # slug will be 'foo' for '/foo.png' + # slug will be 'foo.bar' for '/foo.bar' + # slug will be 'foo.bar' for '/foo.bar.html' + params[:slug] +end +``` + +It is also possible to pass in options to a specific route: + +``` ruby +require 'sinatra' +require 'mustermann' + +register Mustermann + +get '/:slug(.:ext)?', pattern: { greedy: false } do + # slug will be 'foo' for '/foo.png' + # slug will be 'foo' for '/foo.bar' + # slug will be 'foo' for '/foo.bar.html' + params[:slug] +end +``` + +Of course, all of the above can be combined. +Moreover, the `capture` and the `except` option can be passed to route directly. +And yes, this also works with `before` and `after` filters. + +``` ruby +require 'sinatra/base' +require 'sinatra/respond_with' +require 'mustermann' + +class MyApp < Sinatra::Base + register Mustermann, Sinatra::RespondWith + set :pattern, capture: { id: /\d+/ } # id will only match digits + + # only capture extensions known to Rack + before '*:ext', capture: Rack::Mime::MIME_TYPES.keys do + content_type params[:ext] # set Content-Type + request.path_info = params[:splat].first # drop the extension + end + + get '/:id' do + not_found unless page = Page.find params[:id] + respond_with(page) + end +end +``` + +### Why would I want this? + +* It gives you fine grained control over the pattern matching +* Allows you to use different pattern styles in your app +* The default is more robust and powerful than the built-in patterns +* Sinatra 2.0 will use Mustermann internally +* Better exceptions for broken route syntax + +### Why not include this in Sinatra 1.x? + +* It would introduce breaking changes, even though these would be minor +* Like Sinatra 2.0, Mustermann requires Ruby 2.0 or newer + + +## Duck Typing + + +### `to_pattern` + +All methods converting string input to pattern objects will also accept any arbitrary object that implements `to_pattern`: + +``` ruby +require 'mustermann' + +class MyObject + def to_pattern(**options) + Mustermann.new("/foo", **options) + end +end + +object = MyObject.new +Mustermann.new(object, type: :rails) # => # +``` + +It might also be that you want to call `to_pattern` yourself instead of `Mustermann.new`. You can load `mustermann/to_pattern` to implement this method for strings, regular expressions and pattern objects: + +``` ruby +require 'mustermann/to_pattern' + +"/foo".to_pattern # => # +"/foo".to_pattern(type: :rails) # => # +%r{/foo}.to_pattern # => # +"/foo".to_pattern.to_pattern # => # +``` + +You can also use the `Mustermann::ToPattern` mixin to easily add `to_pattern` to your own objects: + +``` ruby +require 'mustermann/to_pattern' + +class MyObject + include Mustermann::ToPattern + + def to_s + "/foo" + end +end + +MyObject.new.to_pattern # => # +``` + + +### `respond_to?` + +You can and should use `respond_to?` to check if a pattern supports certain features. + +``` ruby +require 'mustermann' +pattern = Mustermann.new("/") + +puts "supports expanding" if pattern.respond_to? :expand +puts "supports generating templates" if pattern.respond_to? :to_templates +``` + +Alternatively, you can handle a `NotImplementedError` raised from such a method. + +``` ruby +require 'mustermann' +pattern = Mustermann.new("/") + +begin + p pattern.to_templates +rescue NotImplementedError + puts "does not support generating templates" +end +``` + +This behavior corresponds to what Ruby does, for instance for [`fork`](http://ruby-doc.org/core-2.1.1/NotImplementedError.html). + + +## Available Options + + +### `capture` + +Supported by: All types except `identity`, `shell` and `simple` patterns. + +Most pattern types support changing the strings named captures will match via the `capture` options. + +Possible values for a capture: + +``` ruby +# String: Matches the given string (or any URI encoded version of it) +Mustermann.new('/index.:ext', capture: 'png') + +# Regexp: Matches the Regular expression +Mustermann.new('/:id', capture: /\d+/) + +# Symbol: Matches POSIX character class +Mustermann.new('/:id', capture: :digit) + +# Array of the above: Matches anything in the array +Mustermann.new('/:id_or_slug', capture: [/\d+/, :word]) + +# Hash of the above: Looks up the hash entry by capture name and uses value for matching +Mustermann.new('/:id.:ext', capture: { id: /\d+/, ext: ['png', 'jpg'] }) +``` + +Available POSIX character classes are: `:alnum`, `:alpha`, `:blank`, `:cntrl`, `:digit`, `:graph`, `:lower`, `:print`, `:punct`, `:space`, `:upper`, `:xdigit`, `:word` and `:ascii`. + + +### `except` + +Supported by: All types except `identity`, `shell` and `simple` patterns. + +Given you supply a second pattern via the except option. Any string that would match the primary pattern but also matches the except pattern will not result in a successful match. Feel free to read that again. Or just take a look at this example: + +``` ruby +pattern = Mustermann.new('/auth/*', except: '/auth/login') +pattern === '/auth/dunno' # => true +pattern === '/auth/login' # => false +``` + +Now, as said above, `except` treats the value as a pattern: + +``` ruby +pattern = Mustermann.new('/*anything', type: :rails, except: '/*anything.png') +pattern === '/foo.jpg' # => true +pattern === '/foo.png' # => false +``` + + +### `greedy` + +Supported by: All types except `identity` and `shell` patterns. +Default value: `true` + +**Simple** patterns are greedy, meaning that for the pattern `:foo:bar?`, everything will be captured as `foo`, `bar` will always be `nil`. By setting `greedy` to `false`, `foo` will capture as little as possible (which in this case would only be the first letter), leaving the rest to `bar`. + +**All other** supported patterns are semi-greedy. This means `:foo(.:bar)?` (`:foo(.:bar)` for Rails patterns) will capture everything before the *last* dot as `foo`. For these two pattern types, you can switch into non-greedy mode by setting the `greedy` option to false. In that case `foo` will only capture the part before the *first* dot. + +Semi-greedy behavior is not specific to dots, it works with all characters or strings. For instance, `:a(foo:b)` will capture everything before the *last* `foo` as `a`, and `:foo(bar)?` will not capture a `bar` at the end. + +``` ruby +pattern = Mustermann.new(':a.:b', greedy: true) +pattern.match('a.b.c.d') # => # + +pattern = Mustermann.new(':a.:b', greedy: false) +pattern.match('a.b.c.d') # => # +``` + + +### `space_matches_plus` + +Supported by: All types except `identity`, `regexp` and `shell` patterns. +Default value: `true` + +Most pattern types will by default also match a plus sign for a space in the pattern: + +``` ruby +Mustermann.new('a b') === 'a+b' # => true +``` + +You can disable this behavior via `space_matches_plus`: + +``` ruby +Mustermann.new('a b', space_matches_plus: false) === 'a+b' # => false +``` + +**Important:** This setting has no effect on captures, captures will always keep plus signs as plus sings and spaces as spaces: + +``` ruby +pattern = Mustermann.new(':x') +pattern.match('a b')[:x] # => 'a b' +pattern.match('a+b')[:x] # => 'a+b' +```` + + +### `uri_decode` + +Supported by all pattern types. +Default value: `true` + +Usually, characters in the pattern will also match the URI encoded version of these characters: + +``` ruby +Mustermann.new('a b') === 'a b' # => true +Mustermann.new('a b') === 'a%20b' # => true +``` + +You can avoid this by setting `uri_decode` to `false`: + +``` ruby +Mustermann.new('a b', uri_decode: false) === 'a b' # => true +Mustermann.new('a b', uri_decode: false) === 'a%20b' # => false +``` + + +### `ignore_unknown_options` + +Supported by all patterns. +Default value: `false` + +If you pass an option in that is not supported by the specific pattern type, Mustermann will raise an `ArgumentError`. +By setting `ignore_unknown_options` to `true`, it will happily ignore the option. + + +## Performance + +It's generally a good idea to reuse pattern objects, since as much computation as possible is happening during object creation, so that the actual matching or expanding is quite fast. + +Pattern objects should be treated as immutable. Their internals have been designed for both performance and low memory usage. To reduce pattern compilation, `Mustermann.new` and `Mustermann::Pattern.new` might return the same instance when given the same arguments, if that instance has not yet been garbage collected. However, this is not guaranteed, so do not rely on object identity. + +### String Matching + +When using a pattern instead of a regular expression for string matching, performance will usually be comparable. + +In certain cases, Mustermann might outperform naive, equivalent regular expressions. It achieves this by using look-ahead and atomic groups in ways that work well with a backtracking, NFA-based regular expression engine (such as the Oniguruma/Onigmo engine used by Ruby). It can be difficult and error prone to construct complex regular expressions using these techniques by hand. This only applies to patterns generating an AST internally (all but [identity](#-pattern-details-identity), [shell](#-pattern-details-shell), [simple](#-pattern-details-simple) and [regexp](#-pattern-details-regexp) patterns). + +When using a Mustermann pattern as a direct Regexp replacement (ie, via methods like `=~`, `match` or `===`), the overhead will be a single method dispatch, which some Ruby implementations might even eliminate with method inlining. This only applies to patterns using a regular expression internally (all but [identity](#-pattern-details-identity) and [shell](#-pattern-details-shell) patterns). + +### Expanding + +Pattern expansion significantly outperforms other, widely used Ruby tools for generating URLs from URL patterns in most use cases. + +This comes with a few trade-offs: + +* As with pattern compilation, as much computation as possible has been shifted to compiling expansion rules. This will add compilation overhead, which is why patterns only generate these rules on the first invocation to `Mustermann::Pattern#expand`. Create a `Mustermann::Expander` instance yourself to get better control over the point in time this computation should happen. +* Memory is sacrificed in favor of performance: The size of the expander object will grow linear with the number of possible combination for expansion keys ("/:foo/:bar" has one such combination, but "/(:foo/)?:bar?" has four) +* Parsing a params hash from a string generated from another params hash might not result in two identical hashes, and vice versa. Specifically, expanding ignores capture constraints, type casting and greediness. +* Partial expansion is (currently) not supported. + +## Details on Pattern Types + + +### `identity` + +**Supported options:** +[`uri_decode`](#-available-options--uri_decode), +[`ignore_unknown_options`](#-available-options--ignore_unknown_options). + + + + + + + + + + + + + + +
Syntax ElementDescription
any characterMatches exactly that character or a URI escaped version of it.
+ + +### `regexp` + +**Supported options:** +[`uri_decode`](#-available-options--uri_decode), +[`ignore_unknown_options`](#-available-options--ignore_unknown_options), `check_anchors`. + +The pattern string (or actual Regexp instance) should not contain anchors (`^` outside of square brackets, `$`, `\A`, `\z`, or `\Z`). +Anchors will be injected where necessary by Mustermann. + +By default, Mustermann will raise a `Mustermann::CompileError` if an anchor is encountered. +If you still want it to contain anchors at your own risk, set the `check_anchors` option to `false`. + +Using anchors will break [peeking](#-peeking) and [concatenation](#-concatenation). + + + + + + + + + + + + + + +
Syntax ElementDescription
any stringInterpreted as regular expression.
+ + +### `sinatra` + +**Supported options:** +[`capture`](#-available-options--capture), +[`except`](#-available-options--except), +[`greedy`](#-available-options--greedy), +[`space_matches_plus`](#-available-options--space_matches_plus), +[`uri_decode`](#-available-options--uri_decode), +[`ignore_unknown_options`](#-available-options--ignore_unknown_options). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Syntax ElementDescription
:name or {name} + Captures anything but a forward slash in a semi-greedy fashion. Capture is named name. + Capture behavior can be modified with capture and greedy option. +
*name or {+name} + Captures anything in a non-greedy fashion. Capture is named name. +
* or {+splat} + Captures anything in a non-greedy fashion. Capture is named splat. + It is always an array of captures, as you can use it more than once in a pattern. +
(expression) + Enclosed expression is a group. Useful when combined with ? to make it optional, + or to separate two elements that would otherwise be parsed as one. +
expression|expression|... + Will match anything matching the nested expressions. May contain any other syntax element, including captures. +
x?Makes x optional. For instance, (foo)? matches foo or an empty string.
/ + Matches forward slash. Does not match URI encoded version of forward slash. +
\xMatches x or URI encoded version of x. For instance \* matches *.
any other characterMatches exactly that character or a URI encoded version of it.
diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/capturing.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/capturing.rb new file mode 100644 index 0000000..1bb186a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/capturing.rb @@ -0,0 +1,57 @@ +$:.unshift File.expand_path('../lib', __dir__) + +require 'benchmark' +require 'mustermann' +require 'mustermann/regexp_based' +require 'addressable/template' + + +Mustermann.register(:regexp, Class.new(Mustermann::RegexpBased) { + def compile(**options) + Regexp.new(@string) + end +}, load: false) + +Mustermann.register(:addressable, Class.new(Mustermann::RegexpBased) { + def compile(**options) + Addressable::Template.new(@string) + end +}, load: false) + +list = [ + [:sinatra, '/*/:name' ], + [:rails, '/*prefix/:name' ], + [:simple, '/*/:name' ], + [:template, '{/prefix*}/{name}' ], + [:regexp, '\A\/(?.*?)\/(?[^\/\?#]+)\Z' ], + [:addressable, '{/prefix*}/{name}' ] +] + +def self.assert(value) + fail unless value +end + +string = '/a/b/c/d' +name = 'd' + +GC.disable + +puts "Compilation:" +Benchmark.bmbm do |x| + list.each do |type, pattern| + x.report(type) { 1_000.times { Mustermann.new(pattern, type: type) } } + end +end + +puts "", "Matching with two captures (one splat, one normal):" +Benchmark.bmbm do |x| + list.each do |type, pattern| + pattern = Mustermann.new(pattern, type: type) + x.report type do + 10_000.times do + match = pattern.match(string) + assert match[:name] == name + end + end + end +end \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/regexp.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/regexp.rb new file mode 100644 index 0000000..86ca31b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/regexp.rb @@ -0,0 +1,21 @@ +require 'benchmark' + +puts " atomic vs normal segments ".center(52, '=') + +types = { + normal: /\A\/(?:a|%61)\/(?[^\/\?#]+)(?:\/(?[^\/\?#]+))?\Z/, + atomic: /\A\/(?:a|%61)\/(?(?>[^\/\?#]+))(?:\/(?(?>[^\/\?#]+)))?\Z/ +} + +Benchmark.bmbm do |x| + types.each do |name, regexp| + string = "/a/" << ?a * 10000 << "/" << ?a * 5000 + fail unless regexp.match(string) + string << "/" + fail if regexp.match(string) + + x.report name.to_s do + 100.times { regexp.match(string) } + end + end +end \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/simple_vs_sinatra.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/simple_vs_sinatra.rb new file mode 100644 index 0000000..c16da91 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/simple_vs_sinatra.rb @@ -0,0 +1,23 @@ +$:.unshift File.expand_path('../lib', __dir__) + +require 'benchmark' +require 'mustermann/simple' +require 'mustermann/sinatra' + +[Mustermann::Simple, Mustermann::Sinatra].each do |klass| + puts "", " #{klass} ".center(64, '=') + Benchmark.bmbm do |x| + no_capture = klass.new("/simple") + x.report("no captures, match") { 1_000.times { no_capture.match('/simple') } } + x.report("no captures, miss") { 1_000.times { no_capture.match('/miss') } } + + simple = klass.new("/:name") + x.report("simple, match") { 1_000.times { simple.match('/simple').captures } } + x.report("simple, miss") { 1_000.times { simple.match('/mi/ss') } } + + splat = klass.new("/*") + x.report("splat, match") { 1_000.times { splat.match("/a/b/c").captures } } + x.report("splat, miss") { 1_000.times { splat.match("/a/b/c.miss") } } + end + puts +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/template_vs_addressable.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/template_vs_addressable.rb new file mode 100644 index 0000000..48b5418 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/bench/template_vs_addressable.rb @@ -0,0 +1,26 @@ +$:.unshift File.expand_path('../lib', __dir__) + +require 'benchmark' +require 'mustermann/template' +require 'addressable/template' + +[Mustermann::Template, Addressable::Template].each do |klass| + puts "", " #{klass} ".center(64, '=') + Benchmark.bmbm do |x| + no_capture = klass.new("/simple") + x.report("no captures, match") { 1_000.times { no_capture.match('/simple') } } + x.report("no captures, miss") { 1_000.times { no_capture.match('/miss') } } + + simple = klass.new("/{match}") + x.report("simple, match") { 1_000.times { simple.match('/simple').captures } } + x.report("simple, miss") { 1_000.times { simple.match('/mi/ss') } } + + explode = klass.new("{/segments*}") + x.report("explode, match") { 1_000.times { explode.match("/a/b/c").captures } } + x.report("explode, miss") { 1_000.times { explode.match("/a/b/c.miss") } } + + expand = klass.new("/prefix/{foo}/something/{bar}") + x.report("expand") { 100.times { expand.expand(foo: 'foo', bar: 'bar').to_s } } + end + puts +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann.rb new file mode 100644 index 0000000..88c33b0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann.rb @@ -0,0 +1,134 @@ +# frozen_string_literal: true +require 'mustermann/pattern' +require 'mustermann/composite' +require 'mustermann/concat' +require 'thread' + +# Namespace and main entry point for the Mustermann library. +# +# Under normal circumstances the only external API entry point you should be using is {Mustermann.new}. +module Mustermann + # Type to use if no type is given. + # @api private + DEFAULT_TYPE = :sinatra + + # Creates a new pattern based on input. + # + # * From {Mustermann::Pattern}: returns given pattern. + # * From String: creates a pattern from the string, depending on type option (defaults to {Mustermann::Sinatra}) + # * From Regexp: creates a {Mustermann::Regular} pattern. + # * From Symbol: creates a {Mustermann::Sinatra} pattern with a single named capture named after the input. + # * From an Array or multiple inputs: creates a new pattern from each element, combines them to a {Mustermann::Composite}. + # * From anything else: Will try to call to_pattern on it or raise a TypeError. + # + # Note that if the input is a {Mustermann::Pattern}, Regexp or Symbol, the type option is ignored and if to_pattern is + # called on the object, the type will be handed on but might be ignored by the input object. + # + # If you want to enforce the pattern type, you should create them via their expected class. + # + # @example creating patterns + # require 'mustermann' + # + # Mustermann.new("/:name") # => # + # Mustermann.new("/{name}", type: :template) # => # + # Mustermann.new(/.*/) # => # + # Mustermann.new(:name, capture: :word) # => # + # Mustermann.new("/", "/*.jpg", type: :shell) # => # + # + # @example using custom #to_pattern + # require 'mustermann' + # + # class MyObject + # def to_pattern(**options) + # Mustermann.new("/:name", **options) + # end + # end + # + # Mustermann.new(MyObject.new, type: :rails) # => # + # + # @example enforcing type + # require 'mustermann/sinatra' + # + # Mustermann::Sinatra.new("/:name") + # + # @param [String, Pattern, Regexp, Symbol, #to_pattern, Array] + # input The representation of the pattern + # @param [Hash] options The options hash + # @return [Mustermann::Pattern] pattern corresponding to string. + # @raise (see []) + # @raise (see Mustermann::Pattern.new) + # @raise [TypeError] if the passed object cannot be converted to a pattern + # @see file:README.md#Types_and_Options "Types and Options" in the README + def self.new(*input, type: DEFAULT_TYPE, operator: :|, **options) + type ||= DEFAULT_TYPE + input = input.first if input.size < 2 + case input + when Pattern then input + when Regexp then self[:regexp].new(input, **options) + when String then self[type].new(input, **options) + when Symbol then self[:sinatra].new(input.inspect, **options) + when Array then input.map { |i| new(i, type: type, **options) }.inject(operator) + else + pattern = input.to_pattern(type: type, **options) if input.respond_to? :to_pattern + raise TypeError, "#{input.class} can't be coerced into Mustermann::Pattern" if pattern.nil? + pattern + end + end + + @mutex ||= Mutex.new + @types ||= {} + + # Maps a type to its factory. + # + # @example + # Mustermann[:sinatra] # => Mustermann::Sinatra + # + # @param [Symbol] name a pattern type identifier + # @raise [ArgumentError] if the type is not supported + # @return [Class, #new] pattern factory + def self.[](name) + return name if name.respond_to? :new + @types.fetch(normalized = normalized_type(name)) do + @mutex.synchronize do + error = try_require "mustermann/#{normalized}" + @types.fetch(normalized) { raise ArgumentError, "unsupported type %p#{" (#{error.message})" if error}" % name } + end + end + end + + # @return [LoadError, nil] + # @!visibility private + def self.try_require(path) + require(path) + nil + rescue LoadError => error + raise(error) unless error.path == path + error + end + + # @!visibility private + def self.register(name, type) + @types[normalized_type(name)] = type + end + + # @!visibility private + def self.normalized_type(type) + type.to_s.gsub('-', '_').downcase + end + + # @!visibility private + def self.extend_object(object) + return super unless defined? ::Sinatra::Base and object.is_a? Class and object < ::Sinatra::Base + require 'mustermann/extension' + object.register Extension + end +end + +# :nocov: +begin + require 'mustermann/visualizer' if defined?(Pry) or defined?(IRB) +rescue LoadError => error + raise error unless error.path == 'mustermann/visualizer' + $stderr.puts(error.message) if caller_locations[1].absolute_path =~ %r{/lib/pry/|/irb/|^\((?:irb|pry)\)$} +end +# :nocov: diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/boundaries.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/boundaries.rb new file mode 100644 index 0000000..79cd8fd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/boundaries.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true +require 'mustermann/ast/translator' + +module Mustermann + module AST + # Make sure #start and #stop is set on every node and within its parents #start and #stop. + # @!visibility private + class Boundaries < Translator + # @return [Mustermann::AST::Node] the ast passed as first argument + # @!visibility private + def self.set_boundaries(ast, string: nil, start: 0, stop: string.length) + new.translate(ast, start, stop) + ast + end + + translate(:node) do |start, stop| + t.set_boundaries(node, start, stop) + t(payload, node.start, node.stop) + end + + translate(:with_look_ahead) do |start, stop| + t.set_boundaries(node, start, stop) + t(head, node.start, node.stop) + t(payload, node.start, node.stop) + end + + translate(Array) do |start, stop| + each do |subnode| + t(subnode, start, stop) + start = subnode.stop + end + end + + translate(Object) { |*| node } + + # Checks that a node is within the given boundaries. + # @!visibility private + def set_boundaries(node, start, stop) + node.start = start if node.start.nil? or node.start < start + node.stop = node.start + node.min_size if node.stop.nil? or node.stop < node.start + node.stop = stop if node.stop > stop + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/compiler.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/compiler.rb new file mode 100644 index 0000000..c451438 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/compiler.rb @@ -0,0 +1,159 @@ +# frozen_string_literal: true +require 'mustermann/ast/translator' + +module Mustermann + # @see Mustermann::AST::Pattern + module AST + # Regexp compilation logic. + # @!visibility private + class Compiler < Translator + raises CompileError + + # Trivial compilations + translate(Array) { |**o| map { |e| t(e, **o) }.join } + translate(:node) { |**o| t(payload, **o) } + translate(:separator) { |**o| Regexp.escape(payload) } + translate(:optional) { |**o| "(?:%s)?" % t(payload, **o) } + translate(:char) { |**o| t.encoded(payload, **o) } + + translate :union do |**options| + "(?:%s)" % payload.map { |e| "(?:%s)" % t(e, **options) }.join(?|) + end + + translate :expression do |greedy: true, **options| + t(payload, allow_reserved: operator.allow_reserved, greedy: greedy && !operator.allow_reserved, + parametric: operator.parametric, separator: operator.separator, **options) + end + + translate :with_look_ahead do |**options| + lookahead = each_leaf.inject("") do |ahead, element| + ahead + t(element, skip_optional: true, lookahead: ahead, greedy: false, no_captures: true, **options).to_s + end + lookahead << (at_end ? '$' : '/') + t(head, lookahead: lookahead, **options) + t(payload, **options) + end + + # Capture compilation is complex. :( + # @!visibility private + class Capture < NodeTranslator + register :capture + + # @!visibility private + def translate(**options) + return pattern(**options) if options[:no_captures] + "(?<#{name}>#{translate(no_captures: true, **options)})" + end + + # @return [String] regexp without the named capture + # @!visibility private + def pattern(capture: nil, **options) + case capture + when Symbol then from_symbol(capture, **options) + when Array then from_array(capture, **options) + when Hash then from_hash(capture, **options) + when String then from_string(capture, **options) + when nil then from_nil(**options) + else capture + end + end + + private + def qualified(string, greedy: true, **options) "#{string}#{qualifier || "+#{?? unless greedy}"}" end + def with_lookahead(string, lookahead: nil, **options) lookahead ? "(?:(?!#{lookahead})#{string})" : string end + def from_hash(hash, **options) pattern(capture: hash[name.to_sym], **options) end + def from_array(array, **options) Regexp.union(*array.map { |e| pattern(capture: e, **options) }) end + def from_symbol(symbol, **options) qualified(with_lookahead("[[:#{symbol}:]]", **options), **options) end + def from_string(string, **options) Regexp.new(string.chars.map { |c| t.encoded(c, **options) }.join) end + def from_nil(**options) qualified(with_lookahead(default(**options), **options), **options) end + def default(**options) constraint || "[^/\\?#]" end + end + + # @!visibility private + class Splat < Capture + register :splat, :named_splat + # splats are always non-greedy + # @!visibility private + def pattern(**options) + constraint || ".*?" + end + end + + # @!visibility private + class Variable < Capture + register :variable + + # @!visibility private + def translate(**options) + return super(**options) if explode or not options[:parametric] + # Remove this line after fixing broken compatibility between 2.1 and 2.2 + options.delete(:parametric) if options.has_key?(:parametric) + parametric super(parametric: false, **options) + end + + # @!visibility private + def pattern(parametric: false, separator: nil, **options) + register_param(parametric: parametric, separator: separator, **options) + pattern = super(**options) + pattern = parametric(pattern) if parametric + pattern = "#{pattern}(?:#{Regexp.escape(separator)}#{pattern})*" if explode and separator + pattern + end + + # @!visibility private + def parametric(string) + "#{Regexp.escape(name)}(?:=#{string})?" + end + + # @!visibility private + def qualified(string, **options) + prefix ? "#{string}{1,#{prefix}}" : super(string, **options) + end + + # @!visibility private + def default(allow_reserved: false, **options) + allow_reserved ? '[\w\-\.~%\:/\?#\[\]@\!\$\&\'\(\)\*\+,;=]' : '[\w\-\.~%]' + end + + # @!visibility private + def register_param(parametric: false, split_params: nil, separator: nil, **options) + return unless explode and split_params + split_params[name] = { separator: separator, parametric: parametric } + end + end + + # @return [String] Regular expression for matching the given character in all representations + # @!visibility private + def encoded(char, uri_decode: true, space_matches_plus: true, **options) + return Regexp.escape(char) unless uri_decode + encoded = escape(char, escape: /./) + list = [escape(char), encoded.downcase, encoded.upcase].uniq.map { |c| Regexp.escape(c) } + if char == " " + list << encoded('+') if space_matches_plus + list << " " + end + "(?:%s)" % list.join("|") + end + + # Compiles an AST to a regular expression. + # @param [Mustermann::AST::Node] ast the tree + # @return [Regexp] corresponding regular expression. + # + # @!visibility private + def self.compile(ast, **options) + new.compile(ast, **options) + end + + # Compiles an AST to a regular expression. + # @param [Mustermann::AST::Node] ast the tree + # @return [Regexp] corresponding regular expression. + # + # @!visibility private + def compile(ast, except: nil, **options) + except &&= "(?!#{translate(except, no_captures: true, **options)}\\Z)" + Regexp.new("#{except}#{translate(ast, **options)}") + end + end + + private_constant :Compiler + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/expander.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/expander.rb new file mode 100644 index 0000000..1aa495d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/expander.rb @@ -0,0 +1,145 @@ +# frozen_string_literal: true +require 'mustermann/ast/translator' +require 'mustermann/ast/compiler' +require 'ruby2_keywords' + +module Mustermann + module AST + # Looks at an AST, remembers the important bits of information to do an + # ultra fast expansion. + # + # @!visibility private + class Expander < Translator + raises ExpandError + + translate Array do |*args| + inject(t.pattern) do |pattern, element| + t.add_to(pattern, t(element, *args)) + end + end + + translate :capture do |**options| + t.for_capture(node, **options) + end + + translate :named_splat, :splat do + t.pattern + t.for_capture(node) + end + + translate :expression do + t(payload, allow_reserved: operator.allow_reserved) + end + + translate :root, :group do + t(payload) + end + + translate :char do + t.pattern(t.escape(payload, also_escape: /[\/\?#\&\=%]/).gsub(?%, "%%")) + end + + translate :separator do + t.pattern(payload.gsub(?%, "%%")) + end + + translate :with_look_ahead do + t.add_to(t(head), t(payload)) + end + + translate :optional do + nested = t(payload) + nested += t.pattern unless nested.any? { |n| n.first.empty? } + nested + end + + translate :union do + payload.map { |e| t(e) }.inject(:+) + end + + # helper method for captures + # @!visibility private + def for_capture(node, **options) + name = node.name.to_sym + pattern('%s', name, name => /(?!#{pattern_for(node, **options)})./) + end + + # maps sorted key list to sprintf patterns and filters + # @!visibility private + def mappings + @mappings ||= {} + end + + # all the known keys + # @!visibility private + def keys + @keys ||= [] + end + + # add a tree for expansion + # @!visibility private + def add(ast) + translate(ast).each do |keys, pattern, filter| + self.keys.concat(keys).uniq! + mappings[keys.sort] ||= [keys, pattern, filter] + end + end + + # helper method for getting a capture's pattern. + # @!visibility private + def pattern_for(node, **options) + Compiler.new.decorator_for(node).pattern(**options) + end + + # @see Mustermann::Pattern#expand + # @!visibility private + def expand(values) + adjusted = values.each_with_object({}){ |(key, value), new_hash| + new_hash[value.instance_of?(Array) ? [key] * value.length : key] = value } + keys, pattern, filters = mappings.fetch(adjusted.keys.flatten.sort) { error_for(values) } + filters.each { |key, filter| adjusted[key] &&= escape(adjusted[key], also_escape: filter) } + pattern % (adjusted[keys] || adjusted.values_at(*keys)) + end + + # @see Mustermann::Pattern#expandable? + # @!visibility private + def expandable?(values) + values = values.keys if values.respond_to? :keys + values = values.sort if values.respond_to? :sort + mappings.include? values + end + + # @see Mustermann::Expander#with_rest + # @!visibility private + def expandable_keys(keys) + mappings.keys.select { |k| (k - keys).empty? }.max_by(&:size) || keys + end + + # helper method for raising an error for unexpandable values + # @!visibility private + def error_for(values) + expansions = mappings.keys.map(&:inspect).join(" or ") + raise error_class, "cannot expand with keys %p, possible expansions: %s" % [values.keys.sort, expansions] + end + + # @see Mustermann::AST::Translator#expand + # @!visibility private + ruby2_keywords def escape(string, *args) + # URI::Parser is pretty slow, let's not send every string to it, even if it's unnecessary + string =~ /\A\w*\Z/ ? string : super + end + + # Turns a sprintf pattern into our secret internal data structure. + # @!visibility private + def pattern(string = "", *keys, **filters) + [[keys, string, filters]] + end + + # Creates the product of two of our secret internal data structures. + # @!visibility private + def add_to(list, result) + list << [[], ""] if list.empty? + list.inject([]) { |l, (k1, p1, f1)| l + result.map { |k2, p2, f2| [k1+k2, p1+p2, f1.merge(f2)] } } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/node.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/node.rb new file mode 100644 index 0000000..50d28ef --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/node.rb @@ -0,0 +1,222 @@ +module Mustermann + # @see Mustermann::AST::Pattern + module AST + # @!visibility private + class Node + # @!visibility private + attr_accessor :payload, :start, :stop + + # @!visibility private + # @param [Symbol] name of the node + # @return [Class] factory for the node + def self.[](name) + @names ||= {} + @names[name] ||= begin + const_name = constant_name(name) + Object.const_get(const_name) if Object.const_defined?(const_name) + end + end + + # Turns a class name into a node identifier. + # @!visibility private + def self.type + name[/[^:]+$/].split(/(?<=.)(?=[A-Z])/).map(&:downcase).join(?_).to_sym + end + + # @!visibility private + # @param [Symbol] name of the node + # @return [String] qualified name of factory for the node + def self.constant_name(name) + return self.name if name.to_sym == :node + name = name.to_s.split(?_).map(&:capitalize).join + "#{self.name}::#{name}" + end + + # Helper for creating a new instance and calling #parse on it. + # @return [Mustermann::AST::Node] + # @!visibility private + def self.parse(*args, &block) + new(*args).tap { |n| n.parse(&block) } + end + + # @!visibility private + def initialize(payload = nil, **options) + options.each { |key, value| public_send("#{key}=", value) } + self.payload = payload + end + + # @!visibility private + def is_a?(type) + type = Node[type] if type.is_a? Symbol + super(type) + end + + # Double dispatch helper for reading from the buffer into the payload. + # @!visibility private + def parse + self.payload ||= [] + while element = yield + payload << element + end + end + + # Loop through all nodes that don't have child nodes. + # @!visibility private + def each_leaf(&block) + return enum_for(__method__) unless block_given? + called = false + Array(payload).each do |entry| + next unless entry.respond_to? :each_leaf + entry.each_leaf(&block) + called = true + end + yield(self) unless called + end + + # @return [Integer] length of the substring + # @!visibility private + def length + stop - start if start and stop + end + + # @return [Integer] minimum size for a node + # @!visibility private + def min_size + 0 + end + + # Turns a class name into a node identifier. + # @!visibility private + def type + self.class.type + end + + # @!visibility private + class Capture < Node + # @see Mustermann::AST::Compiler::Capture#default + # @!visibility private + attr_accessor :constraint + + # @see Mustermann::AST::Compiler::Capture#qualified + # @!visibility private + attr_accessor :qualifier + + # @see Mustermann::AST::Pattern#map_param + # @!visibility private + attr_accessor :convert + + # @see Mustermann::AST::Node#parse + # @!visibility private + def parse + self.payload ||= "" + super + end + + # @!visibility private + alias_method :name, :payload + end + + # @!visibility private + class Char < Node + # @return [Integer] minimum size for a node + # @!visibility private + def min_size + 1 + end + end + + # AST node for template expressions. + # @!visibility private + class Expression < Node + # @!visibility private + attr_accessor :operator + end + + # @!visibility private + class Composition < Node + # @!visibility private + def initialize(payload = nil, **options) + super(Array(payload), **options) + end + end + + # @!visibility private + class Group < Composition + end + + # @!visibility private + class Union < Composition + end + + # @!visibility private + class Optional < Node + end + + # @!visibility private + class Or < Node + end + + # @!visibility private + class Root < Node + # @!visibility private + attr_accessor :pattern + + # Will trigger transform. + # + # @see Mustermann::AST::Node.parse + # @!visibility private + def self.parse(string, &block) + root = new + root.pattern = string + root.parse(&block) + root + end + end + + # @!visibility private + class Separator < Node + # @return [Integer] minimum size for a node + # @!visibility private + def min_size + 1 + end + end + + # @!visibility private + class Splat < Capture + # @see Mustermann::AST::Node::Capture#name + # @!visibility private + def name + "splat" + end + end + + # @!visibility private + class NamedSplat < Splat + # @see Mustermann::AST::Node::Capture#name + # @!visibility private + alias_method :name, :payload + end + + # AST node for template variables. + # @!visibility private + class Variable < Capture + # @!visibility private + attr_accessor :prefix, :explode + end + + # @!visibility private + class WithLookAhead < Node + # @!visibility private + attr_accessor :head, :at_end + + # @!visibility private + def initialize(payload, at_end, **options) + super(**options) + self.head, *self.payload = Array(payload) + self.at_end = at_end + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/param_scanner.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/param_scanner.rb new file mode 100644 index 0000000..e220180 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/param_scanner.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true +require 'mustermann/ast/translator' + +module Mustermann + module AST + # Scans an AST for param converters. + # @!visibility private + # @see Mustermann::AST::Pattern#to_templates + class ParamScanner < Translator + # @!visibility private + def self.scan_params(ast) + new.translate(ast) + end + + translate(:node) { t(payload) } + translate(Array) { map { |e| t(e) }.inject(:merge) } + translate(Object) { {} } + translate(:capture) { convert ? { name => convert } : {} } + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/parser.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/parser.rb new file mode 100644 index 0000000..5a00d2b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/parser.rb @@ -0,0 +1,235 @@ +# frozen_string_literal: true +require 'mustermann/ast/node' +require 'forwardable' +require 'ruby2_keywords' +require 'strscan' + +module Mustermann + # @see Mustermann::AST::Pattern + module AST + # Simple, StringScanner based parser. + # @!visibility private + class Parser + # @param [String] string to be parsed + # @return [Mustermann::AST::Node] parse tree for string + # @!visibility private + def self.parse(string, **options) + new(**options).parse(string) + end + + # Defines another grammar rule for first character. + # + # @see Mustermann::Rails + # @see Mustermann::Sinatra + # @see Mustermann::Template + # @!visibility private + def self.on(*chars, &block) + chars.each do |char| + define_method("read %p" % char, &block) + end + end + + # Defines another grammar rule for a suffix. + # + # @see Mustermann::Sinatra + # @!visibility private + def self.suffix(pattern = /./, after: :node, &block) + @suffix ||= [] + @suffix << [pattern, after, block] if block + @suffix + end + + # @!visibility private + attr_reader :buffer, :string, :pattern + + extend Forwardable + def_delegators :buffer, :eos?, :getch, :pos + + # @!visibility private + def initialize(pattern: nil, **options) + @pattern = pattern + end + + # @param [String] string to be parsed + # @return [Mustermann::AST::Node] parse tree for string + # @!visibility private + def parse(string) + @string = string + @buffer = ::StringScanner.new(string) + node(:root, string) { read unless eos? } + end + + # @example + # node(:char, 'x').compile =~ 'x' # => true + # + # @param [Symbol] type node type + # @return [Mustermann::AST::Node] + # @!visibility private + ruby2_keywords def node(type, *args, &block) + type = Node[type] unless type.respond_to? :new + start = pos + node = block ? type.parse(*args, &block) : type.new(*args) + min_size(start, pos, node) + end + + # Create a node for a character we don't have an explicit rule for. + # + # @param [String] char the character + # @return [Mustermann::AST::Node] the node + # @!visibility private + def default_node(char) + char == ?/ ? node(:separator, char) : node(:char, char) + end + + # Reads the next element from the buffer. + # @return [Mustermann::AST::Node] next element + # @!visibility private + def read + start = pos + char = getch + method = "read %p" % char + element= respond_to?(method) ? send(method, char) : default_node(char) + min_size(start, pos, element) + read_suffix(element) + end + + # sets start on node to start if it's not set to a lower value. + # sets stop on node to stop if it's not set to a higher value. + # @return [Mustermann::AST::Node] the node passed as third argument + # @!visibility private + def min_size(start, stop, node) + stop ||= start + start ||= stop + node.start = start unless node.start and node.start < start + node.stop = stop unless node.stop and node.stop > stop + node + end + + # Checks for a potential suffix on the buffer. + # @param [Mustermann::AST::Node] element node without suffix + # @return [Mustermann::AST::Node] node with suffix + # @!visibility private + def read_suffix(element) + self.class.suffix.inject(element) do |ele, (regexp, after, callback)| + next ele unless ele.is_a?(after) and payload = scan(regexp) + content = instance_exec(payload, ele, &callback) + min_size(element.start, pos, content) + end + end + + # Wrapper around {StringScanner#scan} that turns strings into escaped + # regular expressions and returns a MatchData if the regexp has any + # named captures. + # + # @param [Regexp, String] regexp + # @see StringScanner#scan + # @return [String, MatchData, nil] + # @!visibility private + def scan(regexp) + regexp = Regexp.new(Regexp.escape(regexp)) unless regexp.is_a? Regexp + string = buffer.scan(regexp) + regexp.names.any? ? regexp.match(string) : string + end + + # Asserts a regular expression matches what's next on the buffer. + # Will return corresponding MatchData if regexp includes named captures. + # + # @param [Regexp] regexp expected to match + # @return [String, MatchData] the match + # @raise [Mustermann::ParseError] if expectation wasn't met + # @!visibility private + def expect(regexp, char: nil, **options) + scan(regexp) || unexpected(char, **options) + end + + # Allows to read a string inside brackets. It does not expect the string + # to start with an opening bracket. + # + # @example + # buffer.string = "fo>ba" + # read_brackets(?<, ?>) # => "fo" + # buffer.rest # => "ba" + # + # @!visibility private + def read_brackets(open, close, char: nil, escape: ?\\, quote: false, **options) + result = String.new + escape = false if escape.nil? + while (current = getch) + case current + when close then return result + when open then result << open << read_brackets(open, close) << close + when escape then result << escape << getch + else result << current + end + end + unexpected(char, **options) + end + + + # Reads an argument string of the format arg1,args2,key:value + # + # @!visibility private + def read_args(key_separator, close, separator: ?,, symbol_keys: true, **options) + list, map = [], {} + while buffer.peek(1) != close + scan(separator) + entries = read_list(close, separator, separator: key_separator, **options) + case entries.size + when 1 then list += entries + when 2 then map[symbol_keys ? entries.first.to_sym : entries.first] = entries.last + else unexpected(key_separator) + end + buffer.pos -= 1 + end + expect(close) + [list, map] + end + + # Reads a separated list with the ability to quote, escape and add spaces. + # + # @!visibility private + def read_list(*close, separator: ?,, escape: ?\\, quotes: [?", ?'], ignore: " ", **options) + result = [] + while current = getch + element = result.empty? ? result : result.last + case current + when *close then return result + when ignore then nil # do nothing + when separator then result << String.new + when escape then element << getch + when *quotes then element << read_escaped(current, escape: escape) + else element << current + end + end + unexpected(current, **options) + end + + # Read a string until a terminating character, ignoring escaped versions of said character. + # + # @!visibility private + def read_escaped(close, escape: ?\\, **options) + result = String.new + while current = getch + case current + when close then return result + when escape then result << getch + else result << current + end + end + unexpected(current, **options) + end + + # Helper for raising an exception for an unexpected character. + # Will read character from buffer if buffer is passed in. + # + # @param [String, nil] char the unexpected character + # @raise [Mustermann::ParseError, Exception] + # @!visibility private + def unexpected(char = nil, exception: ParseError) + char ||= getch + char = "space" if char == " " + raise exception, "unexpected #{char || "end of string"} while parsing #{string.inspect}" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/pattern.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/pattern.rb new file mode 100644 index 0000000..cfd6481 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/pattern.rb @@ -0,0 +1,136 @@ +# frozen_string_literal: true +require 'mustermann/ast/parser' +require 'mustermann/ast/boundaries' +require 'mustermann/ast/compiler' +require 'mustermann/ast/transformer' +require 'mustermann/ast/validation' +require 'mustermann/ast/template_generator' +require 'mustermann/ast/param_scanner' +require 'mustermann/regexp_based' +require 'mustermann/expander' +require 'mustermann/equality_map' + +module Mustermann + # @see Mustermann::AST::Pattern + module AST + # Superclass for pattern styles that parse an AST from the string pattern. + # @abstract + class Pattern < Mustermann::RegexpBased + supported_options :capture, :except, :greedy, :space_matches_plus + + extend Forwardable, SingleForwardable + single_delegate on: :parser, suffix: :parser + instance_delegate %i[parser compiler transformer validation template_generator param_scanner boundaries] => 'self.class' + instance_delegate parse: :parser, transform: :transformer, validate: :validation, + generate_templates: :template_generator, scan_params: :param_scanner, set_boundaries: :boundaries + + # @api private + # @return [#parse] parser object for pattern + # @!visibility private + def self.parser + return Parser if self == AST::Pattern + const_set :Parser, Class.new(superclass.parser) unless const_defined? :Parser, false + const_get :Parser + end + + # @api private + # @return [#compile] compiler object for pattern + # @!visibility private + def self.compiler + Compiler + end + + # @api private + # @return [#set_boundaries] translator making sure start and stop is set on all nodes + # @!visibility private + def self.boundaries + Boundaries + end + + # @api private + # @return [#transform] transformer object for pattern + # @!visibility private + def self.transformer + Transformer + end + + # @api private + # @return [#validate] validation object for pattern + # @!visibility private + def self.validation + Validation + end + + # @api private + # @return [#generate_templates] generates URI templates for pattern + # @!visibility private + def self.template_generator + TemplateGenerator + end + + # @api private + # @return [#scan_params] param scanner for pattern + # @!visibility private + def self.param_scanner + ParamScanner + end + + # @!visibility private + def compile(**options) + options[:except] &&= parse options[:except] + compiler.compile(to_ast, **options) + rescue CompileError => error + raise error.class, "#{error.message}: #{@string.inspect}", error.backtrace + end + + # Internal AST representation of pattern. + # @!visibility private + def to_ast + @ast_cache ||= EqualityMap.new + @ast_cache.fetch(@string) do + ast = parse(@string, pattern: self) + ast &&= transform(ast) + ast &&= set_boundaries(ast, string: @string) + validate(ast) + end + end + + # All AST-based pattern implementations support expanding. + # + # @example (see Mustermann::Pattern#expand) + # @param (see Mustermann::Pattern#expand) + # @return (see Mustermann::Pattern#expand) + # @raise (see Mustermann::Pattern#expand) + # @see Mustermann::Pattern#expand + # @see Mustermann::Expander + def expand(behavior = nil, values = {}) + @expander ||= Mustermann::Expander.new(self) + @expander.expand(behavior, values) + end + + # All AST-based pattern implementations support generating templates. + # + # @example (see Mustermann::Pattern#to_templates) + # @param (see Mustermann::Pattern#to_templates) + # @return (see Mustermann::Pattern#to_templates) + # @see Mustermann::Pattern#to_templates + def to_templates + @to_templates ||= generate_templates(to_ast) + end + + # @!visibility private + # @see Mustermann::Pattern#map_param + def map_param(key, value) + return super unless param_converters.include? key + param_converters[key][super] + end + + # @!visibility private + def param_converters + @param_converters ||= scan_params(to_ast) + end + + private :compile, :parse, :transform, :validate, :generate_templates, :param_converters, :scan_params, :set_boundaries + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/template_generator.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/template_generator.rb new file mode 100644 index 0000000..763086e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/template_generator.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true +require 'mustermann/ast/translator' + +module Mustermann + module AST + # Turns an AST into an Array of URI templates representing the AST. + # @!visibility private + # @see Mustermann::AST::Pattern#to_templates + class TemplateGenerator < Translator + # @!visibility private + def self.generate_templates(ast) + new.translate(ast).uniq + end + + # translate(:expression) is not needed, since template patterns simply call to_s + translate(:root, :group) { t(payload) || [""] } + translate(:separator, :char) { t.escape(payload) } + translate(:capture) { "{#{name}}" } + translate(:optional) { [t(payload), ""] } + translate(:named_splat, :splat) { "{+#{name}}" } + translate(:with_look_ahead) { t([head, payload]) } + translate(:union) { payload.flat_map { |e| t(e) } } + + translate(Array) do + map { |e| Array(t(e)) }.inject { |first, second| first.product(second).map(&:join) } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/transformer.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/transformer.rb new file mode 100644 index 0000000..f21f8f3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/transformer.rb @@ -0,0 +1,179 @@ +# frozen_string_literal: true +require 'mustermann/ast/translator' + +module Mustermann + module AST + # Takes a tree, turns it into an even better tree. + # @!visibility private + class Transformer < Translator + + # Transforms a tree. + # @note might mutate handed in tree instead of creating a new one + # @param [Mustermann::AST::Node] tree to be transformed + # @return [Mustermann::AST::Node] transformed tree + # @!visibility private + def self.transform(tree) + new.translate(tree) + end + + # recursive descent + translate(:node) do + node.payload = t(payload) + node + end + + # ignore unknown objects on the tree + translate(Object) { node } + + # turn a group containing or nodes into a union + # @!visibility private + class GroupTransformer < NodeTranslator + register :group + + # @!visibility private + def translate + payload.flatten! if payload.is_a?(Array) + return union if payload.any? { |e| e.is_a? :or } + self.payload = t(payload) + self + end + + # @!visibility private + def union + groups = split_payload.map { |g| group(g) } + Node[:union].new(groups, start: node.start, stop: node.stop) + end + + # @!visibility private + def group(elements) + return t(elements.first) if elements.size == 1 + start, stop = elements.first.start, elements.last.stop if elements.any? + Node[:group].new(t(elements), start: start, stop: stop) + end + + # @!visibility private + def split_payload + groups = [[]] + payload.each { |e| e.is_a?(:or) ? groups << [] : groups.last << e } + groups.map! + end + end + + # inject a union node right inside the root node if it contains or nodes + # @!visibility private + class RootTransformer < GroupTransformer + register :root + + # @!visibility private + def union + self.payload = [super] + self + end + end + + # URI expression transformations depending on operator + # @!visibility private + class ExpressionTransform < NodeTranslator + register :expression + + # @!visibility private + Operator ||= Struct.new(:separator, :allow_reserved, :prefix, :parametric) + + # Operators available for expressions. + # @!visibility private + OPERATORS ||= { + nil => Operator.new(?,, false, false, false), ?+ => Operator.new(?,, true, false, false), + ?# => Operator.new(?,, true, ?#, false), ?. => Operator.new(?., false, ?., false), + ?/ => Operator.new(?/, false, ?/, false), ?; => Operator.new(?;, false, ?;, true), + ?? => Operator.new(?&, false, ??, true), ?& => Operator.new(?&, false, ?&, true) + } + + # Sets operator and inserts separators in between variables. + # @!visibility private + def translate + self.operator = OPERATORS.fetch(operator) { raise CompileError, "#{operator} operator not supported" } + separator = Node[:separator].new(operator.separator) + prefix = Node[:separator].new(operator.prefix) + self.payload = Array(payload.inject { |list, element| Array(list) << t(separator.dup) << t(element) }) + payload.unshift(prefix) if operator.prefix + self + end + end + + # Inserts with_look_ahead nodes wherever appropriate + # @!visibility private + class ArrayTransform < NodeTranslator + register Array + + # the new array + # @!visibility private + def payload + @payload ||= [] + end + + # buffer for potential look ahead + # @!visibility private + def lookahead_buffer + @lookahead_buffer ||= [] + end + + # transform the array + # @!visibility private + def translate + each { |e| track t(e) } + payload.concat create_lookahead(lookahead_buffer, true) + end + + # handle a single element from the array + # @!visibility private + def track(element) + return list_for(element) << element if lookahead_buffer.empty? + return lookahead_buffer << element if lookahead? element + + lookahead = lookahead_buffer.dup + lookahead = create_lookahead(lookahead, false) if element.is_a? Node[:separator] + lookahead_buffer.clear + + payload.concat(lookahead) << element + end + + # turn look ahead buffer into look ahead node + # @!visibility private + def create_lookahead(elements, *args) + return elements unless elements.size > 1 + [Node[:with_look_ahead].new(elements, *args, start: elements.first.start, stop: elements.last.stop)] + end + + # can the given element be used in a look-ahead? + # @!visibility private + def lookahead?(element, in_lookahead = false) + case element + when Node[:char] then in_lookahead + when Node[:group] then lookahead_payload?(element.payload, in_lookahead) + when Node[:optional] then lookahead?(element.payload, true) or expect_lookahead?(element.payload) + end + end + + # does the list of elements look look-ahead-ish to you? + # @!visibility private + def lookahead_payload?(payload, in_lookahead) + return unless payload[0..-2].all? { |e| lookahead?(e, in_lookahead) } + expect_lookahead?(payload.last) or lookahead?(payload.last, in_lookahead) + end + + # can the current element deal with a look-ahead? + # @!visibility private + def expect_lookahead?(element) + return element.class == Node[:capture] unless element.is_a? Node[:group] + element.payload.all? { |e| expect_lookahead?(e) } + end + + # helper method for deciding where to put an element for now + # @!visibility private + def list_for(element) + expect_lookahead?(element) ? lookahead_buffer : payload + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/translator.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/translator.rb new file mode 100644 index 0000000..596e362 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/translator.rb @@ -0,0 +1,127 @@ +# frozen_string_literal: true +require 'mustermann/ast/node' +require 'mustermann/error' +require 'ruby2_keywords' +require 'delegate' + +module Mustermann + module AST + # Implements translator pattern + # + # @abstract + # @!visibility private + class Translator + # Encapsulates a single node translation + # @!visibility private + class NodeTranslator < DelegateClass(Node) + # @param [Array] types list of types to register for. + # @!visibility private + def self.register(*types) + types.each do |type| + type = Node.constant_name(type) if type.is_a? Symbol + translator.dispatch_table[type.to_s] = self + end + end + + # @param node [Mustermann::AST::Node, Object] + # @param translator [Mustermann::AST::Translator] + # + # @!visibility private + def initialize(node, translator) + @translator = translator + super(node) + end + + # @!visibility private + attr_reader :translator + + # shorthand for translating a nested object + # @!visibility private + ruby2_keywords def t(*args, &block) + return translator unless args.any? + translator.translate(*args, &block) + end + + # @!visibility private + alias_method :node, :__getobj__ + end + + # maps types to translations + # @!visibility private + def self.dispatch_table + @dispatch_table ||= {} + end + + # some magic sauce so {NodeTranslator}s know whom to talk to for {#register} + # @!visibility private + def self.inherited(subclass) + node_translator = Class.new(NodeTranslator) + node_translator.define_singleton_method(:translator) { subclass } + subclass.const_set(:NodeTranslator, node_translator) + super + end + + # DSL-ish method for specifying the exception class to use. + # @!visibility private + def self.raises(error) + define_method(:error_class) { error } + end + + # DSL method for defining single method translations. + # @!visibility private + def self.translate(*types, &block) + Class.new(const_get(:NodeTranslator)) do + register(*types) + define_method(:translate, &block) + end + end + + # Enables quick creation of a translator object. + # + # @example + # require 'mustermann' + # require 'mustermann/ast/translator' + # + # translator = Mustermann::AST::Translator.create do + # translate(:node) { [type, *t(payload)].flatten.compact } + # translate(Array) { map { |e| t(e) } } + # translate(Object) { } + # end + # + # ast = Mustermann.new('/:name').to_ast + # translator.translate(ast) # => [:root, :separator, :capture] + # + # @!visibility private + def self.create(&block) + Class.new(self, &block).new + end + + raises Mustermann::Error + + # @param [Mustermann::AST::Node, Object] node to translate + # @return decorator encapsulating translation + # + # @!visibility private + def decorator_for(node) + factory = node.class.ancestors.inject(nil) { |d,a| d || self.class.dispatch_table[a.name] } + raise error_class, "#{self.class}: Cannot translate #{node.class}" unless factory + factory.new(node, self) + end + + # Start the translation dance for a (sub)tree. + # @!visibility private + ruby2_keywords def translate(node, *args, &block) + result = decorator_for(node).translate(*args, &block) + result = result.node while result.is_a? NodeTranslator + result + end + + # @return [String] escaped character + # @!visibility private + def escape(char, parser: URI::DEFAULT_PARSER, escape: parser.regexp[:UNSAFE], also_escape: nil) + escape = Regexp.union(also_escape, escape) if also_escape + char =~ escape ? parser.escape(char, Regexp.union(*escape)) : char + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/validation.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/validation.rb new file mode 100644 index 0000000..3e09177 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/ast/validation.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true +require 'mustermann/ast/translator' + +module Mustermann + module AST + # Checks the AST for certain validations, like correct capture names. + # + # Internally a poor man's visitor (abusing translator to not have to implement a visitor). + # @!visibility private + class Validation < Translator + # Runs validations. + # + # @param [Mustermann::AST::Node] ast to be validated + # @return [Mustermann::AST::Node] the validated ast + # @raise [Mustermann::AST::CompileError] if validation fails + # @!visibility private + def self.validate(ast) + new.translate(ast) + ast + end + + translate(Object, :splat) {} + translate(:node) { t(payload) } + translate(Array) { each { |p| t(p)} } + translate(:capture) { t.check_name(name, forbidden: ['captures', 'splat'])} + translate(:variable, :named_splat) { t.check_name(name, forbidden: 'captures')} + + # @raise [Mustermann::CompileError] if name is not acceptable + # @!visibility private + def check_name(name, forbidden: []) + raise CompileError, "capture name can't be empty" if name.nil? or name.empty? + raise CompileError, "capture name must start with underscore or lower case letter" unless name =~ /^[a-z_]/ + raise CompileError, "capture name can't be #{name}" if Array(forbidden).include? name + raise CompileError, "can't use the same capture name twice" if names.include? name + names << name + end + + # @return [Array] list of capture names in tree + # @!visibility private + def names + @names ||= [] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/caster.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/caster.rb new file mode 100644 index 0000000..a066f95 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/caster.rb @@ -0,0 +1,109 @@ +# frozen_string_literal: true +require 'delegate' + +module Mustermann + # Class for defining and running simple Hash transformations. + # + # @example + # caster = Mustermann::Caster.new + # caster.register(:foo) { |value| { bar: value.upcase } } + # caster.cast(foo: "hello", baz: "world") # => { bar: "HELLO", baz: "world" } + # + # @see Mustermann::Expander#cast + # + # @!visibility private + class Caster < DelegateClass(Array) + # @param (see #register) + # @!visibility private + def initialize(*types, &block) + super([]) + register(*types, &block) + end + + # @param [Array] types identifier for cast type (some need block) + # @!visibility private + def register(*types, &block) + return if types.empty? and block.nil? + types << Any.new(&block) if types.empty? + types.each { |type| self << caster_for(type, &block) } + end + + # @param [Symbol, Regexp, #cast, #===] type identifier for cast type (some need block) + # @return [#cast] specific cast operation + # @!visibility private + def caster_for(type, &block) + case type + when Symbol, Regexp then Key.new(type, &block) + else type.respond_to?(:cast) ? type : Value.new(type, &block) + end + end + + # Transforms a Hash. + # @param [Hash] hash pre-transform Hash + # @return [Hash] post-transform Hash + # @!visibility private + def cast(hash) + return hash if empty? + merge = {} + hash.delete_if do |key, value| + next unless casted = lazy.map { |e| e.cast(key, value) }.detect { |e| e } + casted = { key => casted } unless casted.respond_to? :to_hash + merge.update(casted.to_hash) + end + hash.update(merge) + end + + # Class for block based casts that are triggered for every key/value pair. + # @!visibility private + class Any + # @!visibility private + def initialize(&block) + @block = block + end + + # @see Mustermann::Caster#cast + # @!visibility private + def cast(key, value) + case @block.arity + when 0 then @block.call + when 1 then @block.call(value) + else @block.call(key, value) + end + end + end + + # Class for block based casts that are triggered for key/value pairs with a matching value. + # @!visibility private + class Value < Any + # @param [#===] type used for matching values + # @!visibility private + def initialize(type, &block) + @type = type + super(&block) + end + + # @see Mustermann::Caster#cast + # @!visibility private + def cast(key, value) + super if @type === value + end + end + + # Class for block based casts that are triggered for key/value pairs with a matching key. + # @!visibility private + class Key < Any + # @param [#===] type used for matching keys + # @!visibility private + def initialize(type, &block) + @type = type + super(&block) + end + + # @see Mustermann::Caster#cast + # @!visibility private + def cast(key, value) + super if @type === key + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/composite.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/composite.rb new file mode 100644 index 0000000..280c77d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/composite.rb @@ -0,0 +1,112 @@ +# frozen_string_literal: true +module Mustermann + # Class for pattern objects composed of multiple patterns using binary logic. + # @see Mustermann::Pattern#& + # @see Mustermann::Pattern#| + # @see Mustermann::Pattern#^ + class Composite < Pattern + attr_reader :patterns, :operator + supported_options :operator, :type + + # @see Mustermann::Pattern.supported? + def self.supported?(option, type: nil, **options) + return true if super + Mustermann[type || Mustermann::DEFAULT_TYPE].supported?(option, **options) + end + + # @return [Mustermann::Pattern] a new composite pattern + def self.new(*patterns, **options) + patterns = patterns.flatten + case patterns.size + when 0 then raise ArgumentError, 'cannot create empty composite pattern' + when 1 then patterns.first + else super(patterns, **options) + end + end + + def initialize(patterns, operator: :|, **options) + @operator = operator.to_sym + @patterns = patterns.flat_map { |p| patterns_from(p, **options) } + end + + # @see Mustermann::Pattern#== + def ==(pattern) + patterns == patterns_from(pattern) + end + + # @see Mustermann::Pattern#eql? + def eql?(pattern) + patterns.eql? patterns_from(pattern) + end + + # @see Mustermann::Pattern#hash + def hash + patterns.hash | operator.hash + end + + # @see Mustermann::Pattern#=== + def ===(string) + patterns.map { |p| p === string }.inject(operator) + end + + # @see Mustermann::Pattern#params + def params(string) + with_matching(string, :params) + end + + # @see Mustermann::Pattern#match + def match(string) + with_matching(string, :match) + end + + # @!visibility private + def respond_to_special?(method) + return false unless operator == :| + patterns.all? { |p| p.respond_to?(method) } + end + + # (see Mustermann::Pattern#expand) + def expand(behavior = nil, values = {}) + raise NotImplementedError, 'expanding not supported' unless respond_to? :expand + @expander ||= Mustermann::Expander.new(*patterns) + @expander.expand(behavior, values) + end + + # (see Mustermann::Pattern#to_templates) + def to_templates + raise NotImplementedError, 'template generation not supported' unless respond_to? :to_templates + patterns.flat_map(&:to_templates).uniq + end + + # @return [String] the string representation of the pattern + def to_s + simple_inspect + end + + # @!visibility private + def inspect + "#<%p:%s>" % [self.class, simple_inspect] + end + + # @!visibility private + def simple_inspect + pattern_strings = patterns.map { |p| p.simple_inspect } + "(#{pattern_strings.join(" #{operator} ")})" + end + + # @!visibility private + def with_matching(string, method) + return unless self === string + pattern = patterns.detect { |p| p === string } + pattern.public_send(method, string) if pattern + end + + # @!visibility private + def patterns_from(pattern, **options) + return pattern.patterns if pattern.is_a? Composite and pattern.operator == self.operator + [options.empty? && pattern.is_a?(Pattern) ? pattern : Mustermann.new(pattern, **options)] + end + + private :with_matching, :patterns_from + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/concat.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/concat.rb new file mode 100644 index 0000000..7d38c56 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/concat.rb @@ -0,0 +1,136 @@ +# frozen_string_literal: true +module Mustermann + # Class for pattern objects that are a concatenation of other patterns. + # @see Mustermann::Pattern#+ + class Concat < Composite + # Mixin for patterns to support native concatenation. + # @!visibility private + module Native + # @see Mustermann::Pattern#+ + # @!visibility private + def +(other) + other &&= Mustermann.new(other, type: :identity, **options) + if (patterns = look_ahead(other)) && !patterns.empty? + concat = (self + patterns.inject(:+)) + concat + other.patterns.slice(patterns.length..-1).inject(:+) + else + return super unless native = native_concat(other) + self.class.new(native, **options) + end + end + + # @!visibility private + def look_ahead(other) + return unless other.is_a?(Concat) + other.patterns.take_while(&method(:native_concat?)) + end + + # @!visibility private + def native_concat(other) + "#{self}#{other}" if native_concat?(other) + end + + # @!visibility private + def native_concat?(other) + other.class == self.class and other.options == options + end + + private :native_concat, :native_concat? + end + + # Should not be used directly. + # @!visibility private + def initialize(*, **) + super + AST::Validation.validate(combined_ast) if respond_to? :expand + end + + # @see Mustermann::Composite#operator + # @return [Symbol] always :+ + def operator + :+ + end + + # @see Mustermann::Pattern#=== + def ===(string) + peek_size(string) == string.size + end + + # @see Mustermann::Pattern#match + def match(string) + peeked = peek_match(string) + peeked if peeked.to_s == string + end + + # @see Mustermann::Pattern#params + def params(string) + params, size = peek_params(string) + params if size == string.size + end + + # @see Mustermann::Pattern#peek_size + def peek_size(string) + pump(string) { |p,s| p.peek_size(s) } + end + + # @see Mustermann::Pattern#peek_match + def peek_match(string) + pump(string, initial: SimpleMatch.new) do |pattern, substring| + return unless match = pattern.peek_match(substring) + [match, match.to_s.size] + end + end + + # @see Mustermann::Pattern#peek_params + def peek_params(string) + pump(string, inject_with: :merge, with_size: true) { |p, s| p.peek_params(s) } + end + + # (see Mustermann::Pattern#expand) + def expand(behavior = nil, values = {}) + raise NotImplementedError, 'expanding not supported' unless respond_to? :expand + @expander ||= Mustermann::Expander.new(self) { combined_ast } + @expander.expand(behavior, values) + end + + # (see Mustermann::Pattern#to_templates) + def to_templates + raise NotImplementedError, 'template generation not supported' unless respond_to? :to_templates + @to_templates ||= patterns.inject(['']) { |list, pattern| list.product(pattern.to_templates).map(&:join) }.uniq + end + + # @!visibility private + def respond_to_special?(method) + method = :to_ast if method.to_sym == :expand + patterns.all? { |p| p.respond_to?(method) } + end + + # used to generate results for various methods by scanning through an input string + # @!visibility private + def pump(string, inject_with: :+, initial: nil, with_size: false) + substring = string + results = Array(initial) + + patterns.each do |pattern| + result, size = yield(pattern, substring) + return unless result + results << result + size ||= result + substring = substring[size..-1] + end + + results = results.inject(inject_with) + with_size ? [results, string.size - substring.size] : results + end + + # generates one big AST from all patterns + # will not check if patterns support AST generation + # @!visibility private + def combined_ast + payload = patterns.map { |p| AST::Node[:group].new(p.to_ast.payload) } + AST::Node[:root].new(payload) + end + + private :combined_ast, :pump + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/equality_map.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/equality_map.rb new file mode 100644 index 0000000..8ec4cf3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/equality_map.rb @@ -0,0 +1,66 @@ +# frozen_string_literal: true +module Mustermann + # A simple wrapper around ObjectSpace::WeakMap that allows matching keys by equality rather than identity. + # Used for caching. Note that `fetch` is not guaranteed to return the object, even if it has not been + # garbage collected yet, especially when used concurrently. Therefore, the block passed to `fetch` has to + # be idempotent. + # + # @example + # class ExpensiveComputation + # @map = Mustermann::EqualityMap.new + # + # def self.new(*args) + # @map.fetch(args) { super } + # end + # end + # + # @see #fetch + class EqualityMap + attr_reader :map + + def self.new + defined?(ObjectSpace::WeakMap) ? super : {} + end + + def initialize + @keys = {} + @map = ObjectSpace::WeakMap.new + end + + # @param [#hash] key for caching + # @yield block that will be called to populate entry if missing (has to be idempotent) + # @return value stored in map or result of block + def fetch(key) + identity = @keys[key.hash] + if identity == key + key = identity + elsif key.frozen? + key = key.dup + end + + # it is ok that this is not thread-safe, worst case it has double cost in + # generating, object equality is not guaranteed anyways + @map[key] ||= track(key, yield) + end + + # @param [#hash] key for identifying the object + # @param [Object] object to be stored + # @return [Object] same as the second parameter + def track(key, object) + object = object.dup if object.frozen? + ObjectSpace.define_finalizer(object, finalizer(key.hash)) + @keys[key.hash] = key + object + end + + # Finalizer proc needs to be generated in different scope so it doesn't keep a reference to the object. + # + # @param [Integer] hash for key + # @return [Proc] finalizer callback + def finalizer(hash) + proc { @keys.delete(hash) } + end + + private :track, :finalizer + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/error.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/error.rb new file mode 100644 index 0000000..d1fd52e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/error.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true +module Mustermann + unless defined?(Mustermann::Error) + Error = Class.new(StandardError) # Raised if anything goes wrong while generating a {Pattern}. + CompileError = Class.new(Error) # Raised if anything goes wrong while compiling a {Pattern}. + ParseError = Class.new(Error) # Raised if anything goes wrong while parsing a {Pattern}. + ExpandError = Class.new(Error) # Raised if anything goes wrong while expanding a {Pattern}. + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/expander.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/expander.rb new file mode 100644 index 0000000..fe8cc29 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/expander.rb @@ -0,0 +1,209 @@ +# frozen_string_literal: true +require 'mustermann/ast/expander' +require 'mustermann/caster' +require 'mustermann' + +module Mustermann + # Allows fine-grained control over pattern expansion. + # + # @example + # expander = Mustermann::Expander.new(additional_values: :append) + # expander << "/users/:user_id" + # expander << "/pages/:page_id" + # + # expander.expand(page_id: 58, format: :html5) # => "/pages/58?format=html5" + class Expander + attr_reader :patterns, :additional_values, :caster + + # @param [Array<#to_str, Mustermann::Pattern>] patterns list of patterns to expand, see {#add}. + # @param [Symbol] additional_values behavior when encountering additional values, see {#expand}. + # @param [Hash] options used when creating/expanding patterns, see {Mustermann.new}. + def initialize(*patterns, additional_values: :raise, **options, &block) + unless additional_values == :raise or additional_values == :ignore or additional_values == :append + raise ArgumentError, "Illegal value %p for additional_values" % additional_values + end + + @patterns = [] + @api_expander = AST::Expander.new + @additional_values = additional_values + @options = options + @caster = Caster.new + add(*patterns, &block) + end + + # Add patterns to expand. + # + # @example + # expander = Mustermann::Expander.new + # expander.add("/:a.jpg", "/:b.png") + # expander.expand(a: "pony") # => "/pony.jpg" + # + # @param [Array<#to_str, Mustermann::Pattern>] patterns list of to add for expansion, Strings will be compiled to patterns. + # @return [Mustermann::Expander] the expander + def add(*patterns) + patterns.each do |pattern| + pattern = Mustermann.new(pattern, **@options) + if block_given? + @api_expander.add(yield(pattern)) + else + raise NotImplementedError, "expanding not supported for #{pattern.class}" unless pattern.respond_to? :to_ast + @api_expander.add(pattern.to_ast) + end + @patterns << pattern + end + self + end + + alias_method :<<, :add + + # Register a block as simple hash transformation that runs before expanding the pattern. + # @return [Mustermann::Expander] the expander + # + # @overload cast + # Register a block as simple hash transformation that runs before expanding the pattern for all entries. + # + # @example casting everything that implements to_param to param + # expander.cast { |o| o.to_param if o.respond_to? :to_param } + # + # @yield every key/value pair + # @yieldparam key [Symbol] omitted if block takes less than 2 + # @yieldparam value [Object] omitted if block takes no arguments + # @yieldreturn [Hash{Symbol: Object}] will replace key/value pair with returned hash + # @yieldreturn [nil, false] will keep key/value pair in hash + # @yieldreturn [Object] will replace value with returned object + # + # @overload cast(*type_matchers) + # Register a block as simple hash transformation that runs before expanding the pattern for certain entries. + # + # @example convert user to user_id + # expander = Mustermann::Expander.new('/users/:user_id') + # expand.cast(:user) { |user| { user_id: user.id } } + # + # expand.expand(user: User.current) # => "/users/42" + # + # @example convert user, page, image to user_id, page_id, image_id + # expander = Mustermann::Expander.new('/users/:user_id', '/pages/:page_id', '/:image_id.jpg') + # expand.cast(:user, :page, :image) { |key, value| { "#{key}_id".to_sym => value.id } } + # + # expand.expand(user: User.current) # => "/users/42" + # + # @example casting to multiple key/value pairs + # expander = Mustermann::Expander.new('/users/:user_id/:image_id.:format') + # expander.cast(:image) { |i| { user_id: i.owner.id, image_id: i.id, format: i.format } } + # + # expander.expander(image: User.current.avatar) # => "/users/42/avatar.jpg" + # + # @example casting all ActiveRecord objects to param + # expander.cast(ActiveRecord::Base, &:to_param) + # + # @param [Array] type_matchers + # To identify key/value pairs to match against. + # Regexps and Symbols match against key, everything else matches against value. + # + # @yield every key/value pair + # @yieldparam key [Symbol] omitted if block takes less than 2 + # @yieldparam value [Object] omitted if block takes no arguments + # @yieldreturn [Hash{Symbol: Object}] will replace key/value pair with returned hash + # @yieldreturn [nil, false] will keep key/value pair in hash + # @yieldreturn [Object] will replace value with returned object + # + # @overload cast(*cast_objects) + # + # @param [Array<#cast>] cast_objects + # Before expanding, will call #cast on these objects for each key/value pair. + # Return value will be treated same as block return values described above. + def cast(*types, &block) + caster.register(*types, &block) + self + end + + # @example Expanding a pattern + # pattern = Mustermann::Expander.new('/:name', '/:name.:ext') + # pattern.expand(name: 'hello') # => "/hello" + # pattern.expand(name: 'hello', ext: 'png') # => "/hello.png" + # + # @example Handling additional values + # pattern = Mustermann::Expander.new('/:name', '/:name.:ext') + # pattern.expand(:ignore, name: 'hello', ext: 'png', scale: '2x') # => "/hello.png" + # pattern.expand(:append, name: 'hello', ext: 'png', scale: '2x') # => "/hello.png?scale=2x" + # pattern.expand(:raise, name: 'hello', ext: 'png', scale: '2x') # raises Mustermann::ExpandError + # + # @example Setting additional values behavior for the expander object + # pattern = Mustermann::Expander.new('/:name', '/:name.:ext', additional_values: :append) + # pattern.expand(name: 'hello', ext: 'png', scale: '2x') # => "/hello.png?scale=2x" + # + # @param [Symbol] behavior + # What to do with additional key/value pairs not present in the values hash. + # Possible options: :raise, :ignore, :append. + # + # @param [Hash{Symbol: #to_s, Array<#to_s>}] values + # Values to use for expansion. + # + # @return [String] expanded string + # @raise [NotImplementedError] raised if expand is not supported. + # @raise [Mustermann::ExpandError] raised if a value is missing or unknown + def expand(behavior = nil, values = {}) + behavior, values = nil, behavior if behavior.is_a? Hash + values = map_values(values) + + case behavior || additional_values + when :raise then @api_expander.expand(values) + when :ignore then with_rest(values) { |uri, rest| uri } + when :append then with_rest(values) { |uri, rest| append(uri, rest) } + else raise ArgumentError, "unknown behavior %p" % behavior + end + end + + # @see Object#== + def ==(other) + return false unless other.class == self.class + other.patterns == patterns and other.additional_values == additional_values + end + + # @see Object#eql? + def eql?(other) + return false unless other.class == self.class + other.patterns.eql? patterns and other.additional_values.eql? additional_values + end + + # @see Object#hash + def hash + patterns.hash + additional_values.hash + end + + def expandable?(values) + return false unless values + expandable, _ = split_values(map_values(values)) + @api_expander.expandable? expandable + end + + def with_rest(values) + expandable, non_expandable = split_values(values) + yield expand(:raise, slice(values, expandable)), slice(values, non_expandable) + end + + def split_values(values) + expandable = @api_expander.expandable_keys(values.keys) + non_expandable = values.keys - expandable + [expandable, non_expandable] + end + + def slice(hash, keys) + Hash[keys.map { |k| [k, hash[k]] }] + end + + def append(uri, values) + return uri unless values and values.any? + entries = values.map { |pair| pair.map { |e| @api_expander.escape(e, also_escape: /[\/\?#\&\=%]/) }.join(?=) } + "#{ uri }#{ uri[??]??&:?? }#{ entries.join(?&) }" + end + + def map_values(values) + values = values.dup + @api_expander.keys.each { |key| values[key] ||= values.delete(key.to_s) if values.include? key.to_s } + caster.cast(values).delete_if { |k, v| v.nil? } + end + + private :with_rest, :slice, :append, :caster, :map_values, :split_values + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/extension.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/extension.rb new file mode 100644 index 0000000..789d43e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/extension.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true +require 'sinatra/version' +fail "no need to load the Mustermann extension for #{::Sinatra::VERSION}" if ::Sinatra::VERSION >= '2.0.0' + +require 'mustermann' + +module Mustermann + # Sinatra 1.x extension switching default pattern parsing over to Mustermann. + # + # @example With classic Sinatra application + # require 'sinatra' + # require 'mustermann' + # + # register Mustermann + # get('/:id', capture: /\d+/) { ... } + # + # @example With modular Sinatra application + # require 'sinatra/base' + # require 'mustermann' + # + # class MyApp < Sinatra::Base + # register Mustermann + # get('/:id', capture: /\d+/) { ... } + # end + # + # @see file:README.md#Sinatra_Integration "Sinatra Integration" in the README + module Extension + def compile!(verb, path, block, except: nil, capture: nil, pattern: { }, **options) + if path.respond_to? :to_str + pattern[:except] = except if except + pattern[:capture] = capture if capture + + if settings.respond_to? :pattern and settings.pattern? + pattern.merge! settings.pattern do |key, local, global| + next local unless local.is_a? Hash + next global.merge(local) if global.is_a? Hash + Hash.new(global).merge! local + end + end + + path = Mustermann.new(path, **pattern) + condition { params.merge! path.params(captures: Array(params[:captures]), offset: -1) } + end + + super(verb, path, block, options) + end + + private :compile! + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/identity.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/identity.rb new file mode 100644 index 0000000..8045e67 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/identity.rb @@ -0,0 +1,77 @@ +# frozen_string_literal: true +require 'mustermann' +require 'mustermann/pattern' +require 'mustermann/ast/node' + +module Mustermann + # Matches strings that are identical to the pattern. + # + # @example + # Mustermann.new('/:foo', type: :identity) === '/bar' # => false + # + # @see Mustermann::Pattern + # @see file:README.md#identity Syntax description in the README + class Identity < Pattern + include Concat::Native + register :identity + + # @param (see Mustermann::Pattern#===) + # @return (see Mustermann::Pattern#===) + # @see (see Mustermann::Pattern#===) + def ===(string) + unescape(string) == @string + end + + # @param (see Mustermann::Pattern#peek_size) + # @return (see Mustermann::Pattern#peek_size) + # @see (see Mustermann::Pattern#peek_size) + def peek_size(string) + return unless unescape(string).start_with? @string + return @string.size if string.start_with? @string # optimization + @string.each_char.with_index.inject(0) do |count, (char, index)| + char_size = 1 + escaped = @@uri.escape(char, /./) + char_size = escaped.size if string[index, escaped.size].downcase == escaped.downcase + count + char_size + end + end + + # URI templates support generating templates (the logic is quite complex, though). + # + # @example (see Mustermann::Pattern#to_templates) + # @param (see Mustermann::Pattern#to_templates) + # @return (see Mustermann::Pattern#to_templates) + # @see Mustermann::Pattern#to_templates + def to_templates + [@@uri.escape(to_s)] + end + + # Generates an AST so it's compatible with {Mustermann::AST::Pattern}. + # Not used internally by {Mustermann::Identity}. + # @!visibility private + def to_ast + payload = @string.each_char.with_index.map { |c, i| AST::Node[c == ?/ ? :separator : :char].new(c, start: i, stop: i+1) } + AST::Node[:root].new(payload, pattern: @string, start: 0, stop: @string.length) + end + + # Identity patterns support expanding. + # + # This implementation does not use {Mustermann::Expander} internally to save memory and + # compilation time. + # + # @example (see Mustermann::Pattern#expand) + # @param (see Mustermann::Pattern#expand) + # @return (see Mustermann::Pattern#expand) + # @raise (see Mustermann::Pattern#expand) + # @see Mustermann::Pattern#expand + # @see Mustermann::Expander + def expand(behavior = nil, values = {}) + return to_s if values.empty? or behavior == :ignore + raise ExpandError, "cannot expand with keys %p" % values.keys.sort if behavior == :raise + raise ArgumentError, "unknown behavior %p" % behavior if behavior != :append + params = values.map { |key, value| @@uri.escape(key.to_s) + "=" + @@uri.escape(value.to_s, /[^\w]/) } + separator = @string.include?(??) ? ?& : ?? + @string + separator + params.join(?&) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/mapper.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/mapper.rb new file mode 100644 index 0000000..d2cc5f5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/mapper.rb @@ -0,0 +1,91 @@ +# frozen_string_literal: true +require 'mustermann' +require 'mustermann/expander' + +module Mustermann + # A mapper allows mapping one string to another based on pattern parsing and expanding. + # + # @example + # require 'mustermann/mapper' + # mapper = Mustermann::Mapper.new("/:foo" => "/:foo.html") + # mapper['/example'] # => "/example.html" + class Mapper + # Creates a new mapper. + # + # @overload initialize(**options) + # @param options [Hash] options The options hash + # @yield block for generating mappings as a hash + # @yieldreturn [Hash] see {#update} + # + # @example + # require 'mustermann/mapper' + # Mustermann::Mapper.new(type: :rails) {{ + # "/:foo" => ["/:foo.html", "/:foo.:format"] + # }} + # + # @overload initialize(**options) + # @param options [Hash] options The options hash + # @yield block for generating mappings as a hash + # @yieldparam mapper [Mustermann::Mapper] the mapper instance + # + # @example + # require 'mustermann/mapper' + # Mustermann::Mapper.new(type: :rails) do |mapper| + # mapper["/:foo"] = ["/:foo.html", "/:foo.:format"] + # end + # + # @overload initialize(map = {}, **options) + # @param map [Hash] see {#update} + # @param [Hash] options The options hash + # + # @example map before options + # require 'mustermann/mapper' + # Mustermann::Mapper.new({"/:foo" => "/:foo.html"}, type: :rails) + def initialize(map = {}, additional_values: :ignore, **options, &block) + @map = [] + @options = options + @additional_values = additional_values + block.arity == 0 ? update(yield) : yield(self) if block + update(map) if map + end + + # Add multiple mappings. + # + # @param map [Hash{String, Pattern: String, Pattern, Arry, Expander}] the mapping + def update(map) + map.to_h.each_pair do |input, output| + input = Mustermann.new(input, **@options) + output = Expander.new(*output, additional_values: @additional_values, **@options) unless output.is_a? Expander + @map << [input, output] + end + end + + # @return [Hash{Patttern: Expander}] Hash version of the mapper. + def to_h + Hash[@map] + end + + # Convert a string according to mappings. You can pass in additional params. + # + # @example mapping with and without additional parameters + # mapper = Mustermann::Mapper.new("/:example" => "(/:prefix)?/:example.html") + # + def convert(input, values = {}) + @map.inject(input) do |current, (pattern, expander)| + params = pattern.params(current) + params &&= Hash[values.merge(params).map { |k,v| [k.to_s, v] }] + expander.expandable?(params) ? expander.expand(params) : current + end + end + + # Add a single mapping. + # + # @param key [String, Pattern] format of the input string + # @param value [String, Pattern, Arry, Expander] format of the output string + def []=(key, value) + update key => value + end + + alias_method :[], :convert + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/pattern.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/pattern.rb new file mode 100644 index 0000000..cc15187 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/pattern.rb @@ -0,0 +1,398 @@ +# frozen_string_literal: true +require 'mustermann/error' +require 'mustermann/simple_match' +require 'mustermann/equality_map' +require 'uri' + +module Mustermann + # Superclass for all pattern implementations. + # @abstract + class Pattern + include Mustermann + @@uri ||= URI::Parser.new + + # List of supported options. + # + # @overload supported_options + # @return [Array] list of supported options + # @overload supported_options(*list) + # Adds options to the list. + # + # @api private + # @param [Symbol] *list adds options to the list of supported options + # @return [Array] list of supported options + def self.supported_options(*list) + @supported_options ||= [] + options = @supported_options.concat(list) + options += superclass.supported_options if self < Pattern + options + end + + # Registers the pattern with Mustermann. + # @see Mustermann.register + # @!visibility private + def self.register(*names) + names.each { |name| Mustermann.register(name, self) } + end + + # @param [Symbol] option The option to check. + # @return [Boolean] Whether or not option is supported. + def self.supported?(option, **options) + supported_options.include? option + end + + # @overload new(string, **options) + # @param (see #initialize) + # @raise (see #initialize) + # @raise [ArgumentError] if some option is not supported + # @return [Mustermann::Pattern] a new instance of Mustermann::Pattern + # @see #initialize + def self.new(string, ignore_unknown_options: false, **options) + if ignore_unknown_options + options = options.select { |key, value| supported?(key, **options) if key != :ignore_unknown_options } + else + unsupported = options.keys.detect { |key| not supported?(key, **options) } + raise ArgumentError, "unsupported option %p for %p" % [unsupported, self] if unsupported + end + + @map ||= EqualityMap.new + @map.fetch([string, options]) { super(string, **options) { options } } + end + + supported_options :uri_decode, :ignore_unknown_options + attr_reader :uri_decode + + # options hash passed to new (with unsupported options removed) + # @!visibility private + attr_reader :options + + # @overload initialize(string, **options) + # @param [String] string the string representation of the pattern + # @param [Hash] options options for fine-tuning the pattern behavior + # @raise [Mustermann::Error] if the pattern can't be generated from the string + # @see file:README.md#Types_and_Options "Types and Options" in the README + # @see Mustermann.new + def initialize(string, uri_decode: true, **options) + @uri_decode = uri_decode + @string = string.to_s.dup + @options = yield.freeze if block_given? + end + + # @return [String] the string representation of the pattern + def to_s + @string.dup + end + + # @param [String] string The string to match against + # @return [MatchData, Mustermann::SimpleMatch, nil] MatchData or similar object if the pattern matches. + # @see http://ruby-doc.org/core-2.0/Regexp.html#method-i-match Regexp#match + # @see http://ruby-doc.org/core-2.0/MatchData.html MatchData + # @see Mustermann::SimpleMatch + def match(string) + SimpleMatch.new(string) if self === string + end + + # @param [String] string The string to match against + # @return [Integer, nil] nil if pattern does not match the string, zero if it does. + # @see http://ruby-doc.org/core-2.0/Regexp.html#method-i-3D-7E Regexp#=~ + def =~(string) + 0 if self === string + end + + # @param [String] string The string to match against + # @return [Boolean] Whether or not the pattern matches the given string + # @note Needs to be overridden by subclass. + # @see http://ruby-doc.org/core-2.0/Regexp.html#method-i-3D-3D-3D Regexp#=== + def ===(string) + raise NotImplementedError, 'subclass responsibility' + end + + # Used by Ruby internally for hashing. + # @return [Integer] same has value for patterns that are equal + def hash + self.class.hash | @string.hash | options.hash + end + + # Two patterns are considered equal if they are of the same type, have the same pattern string + # and the same options. + # @return [true, false] + def ==(other) + other.class == self.class and other.to_s == @string and other.options == options + end + + # Two patterns are considered equal if they are of the same type, have the same pattern string + # and the same options. + # @return [true, false] + def eql?(other) + other.class.eql?(self.class) and other.to_s.eql?(@string) and other.options.eql?(options) + end + + # Tries to match the pattern against the beginning of the string (as opposed to the full string). + # Will return the count of the matching characters if it matches. + # + # @example + # pattern = Mustermann.new('/:name') + # pattern.size("/Frank/Sinatra") # => 6 + # + # @param [String] string The string to match against + # @return [Integer, nil] the number of characters that match + def peek_size(string) + # this is a very naive, unperformant implementation + string.size.downto(0).detect { |s| self === string[0, s] } + end + + # Tries to match the pattern against the beginning of the string (as opposed to the full string). + # Will return the substring if it matches. + # + # @example + # pattern = Mustermann.new('/:name') + # pattern.peek("/Frank/Sinatra") # => "/Frank" + # + # @param [String] string The string to match against + # @return [String, nil] matched subsctring + def peek(string) + size = peek_size(string) + string[0, size] if size + end + + # Tries to match the pattern against the beginning of the string (as opposed to the full string). + # Will return a MatchData or similar instance for the matched substring. + # + # @example + # pattern = Mustermann.new('/:name') + # pattern.peek("/Frank/Sinatra") # => # + # + # @param [String] string The string to match against + # @return [MatchData, Mustermann::SimpleMatch, nil] MatchData or similar object if the pattern matches. + # @see #peek_params + def peek_match(string) + matched = peek(string) + match(matched) if matched + end + + # Tries to match the pattern against the beginning of the string (as opposed to the full string). + # Will return a two element Array with the params parsed from the substring as first entry and the length of + # the substring as second. + # + # @example + # pattern = Mustermann.new('/:name') + # params, _ = pattern.peek_params("/Frank/Sinatra") + # + # puts "Hello, #{params['name']}!" # Hello, Frank! + # + # @param [String] string The string to match against + # @return [Array, nil] Array with params hash and length of substing if matched, nil otherwise + def peek_params(string) + match = peek_match(string) + [params(captures: match), match.to_s.size] if match + end + + # @return [Hash{String: Array}] capture names mapped to capture index. + # @see http://ruby-doc.org/core-2.0/Regexp.html#method-i-named_captures Regexp#named_captures + def named_captures + {} + end + + # @return [Array] capture names. + # @see http://ruby-doc.org/core-2.0/Regexp.html#method-i-names Regexp#names + def names + [] + end + + # @param [String] string the string to match against + # @return [Hash{String: String, Array}, nil] Sinatra style params if pattern matches. + def params(string = nil, captures: nil, offset: 0) + return unless captures ||= match(string) + params = named_captures.map do |name, positions| + values = positions.map { |pos| map_param(name, captures[pos + offset]) }.flatten + values = values.first if values.size < 2 and not always_array? name + [name, values] + end + + Hash[params] + end + + # @note This method is only implemented by certain subclasses. + # + # @example Expanding a pattern + # pattern = Mustermann.new('/:name(.:ext)?') + # pattern.expand(name: 'hello') # => "/hello" + # pattern.expand(name: 'hello', ext: 'png') # => "/hello.png" + # + # @example Checking if a pattern supports expanding + # if pattern.respond_to? :expand + # pattern.expand(name: "foo") + # else + # warn "does not support expanding" + # end + # + # Expanding is supported by almost all patterns (notable exceptions are {Mustermann::Shell}, + # {Mustermann::Regular} and {Mustermann::Simple}). + # + # Union {Mustermann::Composite} patterns (with the | operator) support expanding if all + # patterns they are composed of also support it. + # + # @param (see Mustermann::Expander#expand) + # @return [String] expanded string + # @raise [NotImplementedError] raised if expand is not supported. + # @raise [Mustermann::ExpandError] raised if a value is missing or unknown + # @see Mustermann::Expander + def expand(behavior = nil, values = {}) + raise NotImplementedError, "expanding not supported by #{self.class}" + end + + # @note This method is only implemented by certain subclasses. + # + # Generates a list of URI template strings representing the pattern. + # + # Note that this transformation is lossy and the strings matching these + # templates might not match the pattern (and vice versa). + # + # This comes in quite handy since URI templates are not made for pattern matching. + # That way you can easily use a more precise template syntax and have it automatically + # generate hypermedia links for you. + # + # @example generating templates + # Mustermann.new("/:name").to_templates # => ["/{name}"] + # Mustermann.new("/:foo(@:bar)?/*baz").to_templates # => ["/{foo}@{bar}/{+baz}", "/{foo}/{+baz}"] + # Mustermann.new("/{name}", type: :template).to_templates # => ["/{name}"] + # + # @example generating templates from composite patterns + # pattern = Mustermann.new('/:name') + # pattern |= Mustermann.new('/{name}', type: :template) + # pattern |= Mustermann.new('/example/*nested') + # pattern.to_templates # => ["/{name}", "/example/{+nested}"] + # + # Template generation is supported by almost all patterns (notable exceptions are + # {Mustermann::Shell}, {Mustermann::Regular} and {Mustermann::Simple}). + # Union {Mustermann::Composite} patterns (with the | operator) support template generation + # if all patterns they are composed of also support it. + # + # @example Checking if a pattern supports expanding + # if pattern.respond_to? :to_templates + # pattern.to_templates + # else + # warn "does not support template generation" + # end + # + # @return [Array] list of URI templates + def to_templates + raise NotImplementedError, "template generation not supported by #{self.class}" + end + + # @overload |(other) + # Creates a pattern that matches any string matching either one of the patterns. + # If a string is supplied, it is treated as an identity pattern. + # + # @example + # pattern = Mustermann.new('/foo/:name') | Mustermann.new('/:first/:second') + # pattern === '/foo/bar' # => true + # pattern === '/fox/bar' # => true + # pattern === '/foo' # => false + # + # @overload &(other) + # Creates a pattern that matches any string matching both of the patterns. + # If a string is supplied, it is treated as an identity pattern. + # + # @example + # pattern = Mustermann.new('/foo/:name') & Mustermann.new('/:first/:second') + # pattern === '/foo/bar' # => true + # pattern === '/fox/bar' # => false + # pattern === '/foo' # => false + # + # @overload ^(other) + # Creates a pattern that matches any string matching exactly one of the patterns. + # If a string is supplied, it is treated as an identity pattern. + # + # @example + # pattern = Mustermann.new('/foo/:name') ^ Mustermann.new('/:first/:second') + # pattern === '/foo/bar' # => false + # pattern === '/fox/bar' # => true + # pattern === '/foo' # => false + # + # @param [Mustermann::Pattern, String] other the other pattern + # @return [Mustermann::Pattern] a composite pattern + def |(other) + Mustermann::Composite.new(self, other, operator: __callee__, type: :identity) + end + + alias_method :&, :| + alias_method :^, :| + + # @example + # require 'mustermann' + # prefix = Mustermann.new("/:prefix") + # about = prefix + "/about" + # about.params("/main/about") # => {"prefix" => "main"} + # + # Creates a concatenated pattern by combingin self with the other pattern supplied. + # Patterns of different types can be mixed. The availability of `to_templates` and + # `expand` depends on the patterns being concatenated. + # + # String input is treated as identity pattern. + # + # @param [Mustermann::Pattern, String] other pattern to be appended + # @return [Mustermann::Pattern] concatenated pattern + def +(other) + Concat.new(self, other, type: :identity) + end + + # @example + # pattern = Mustermann.new('/:a/:b') + # strings = ["foo/bar", "/foo/bar", "/foo/bar/"] + # strings.detect(&pattern) # => "/foo/bar" + # + # @return [Proc] proc wrapping {#===} + def to_proc + @to_proc ||= method(:===).to_proc + end + + # @!visibility private + # @return [Boolean] + # @see Object#respond_to? + def respond_to?(method, *args) + return super unless %i[expand to_templates].include? method + respond_to_special?(method) + end + + # @!visibility private + # @return [Boolean] + # @see #respond_to? + def respond_to_special?(method) + method(method).owner != Mustermann::Pattern + end + + # @!visibility private + def inspect + "#<%p:%p>" % [self.class, @string] + end + + # @!visibility private + def simple_inspect + type = self.class.name[/[^:]+$/].downcase + "%s:%p" % [type, @string] + end + + # @!visibility private + def map_param(key, value) + unescape(value, true) + end + + # @!visibility private + def unescape(string, decode = uri_decode) + return string unless decode and string + @@uri.unescape(string) + end + + # @!visibility private + ALWAYS_ARRAY = %w[splat captures] + + # @!visibility private + def always_array?(key) + ALWAYS_ARRAY.include? key + end + + private :unescape, :map_param, :respond_to_special? + private_constant :ALWAYS_ARRAY + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/pattern_cache.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/pattern_cache.rb new file mode 100644 index 0000000..cdab88d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/pattern_cache.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true +require 'set' +require 'thread' +require 'mustermann' + +module Mustermann + # A simple, persistent cache for creating repositories. + # + # @example + # require 'mustermann/pattern_cache' + # cache = Mustermann::PatternCache.new + # + # # use this instead of Mustermann.new + # pattern = cache.create_pattern("/:name", type: :rails) + # + # @note + # {Mustermann::Pattern.new} (which is used by {Mustermann.new}) will reuse instances that have + # not yet been garbage collected. You only need an extra cache if you do not keep a reference to + # the patterns around. + # + # @api private + class PatternCache + # @param [Hash] pattern_options default options used for {#create_pattern} + def initialize(**pattern_options) + @cached = Set.new + @mutex = Mutex.new + @pattern_options = pattern_options + end + + # @param (see Mustermann.new) + # @return (see Mustermann.new) + # @raise (see Mustermann.new) + # @see Mustermann.new + def create_pattern(string, **pattern_options) + pattern = Mustermann.new(string, **pattern_options, **@pattern_options) + @mutex.synchronize { @cached.add(pattern) } unless @cached.include? pattern + pattern + end + + # Removes all pattern instances from the cache. + def clear + @mutex.synchronize { @cached.clear } + end + + # @return [Integer] number of currently cached patterns + def size + @mutex.synchronize { @cached.size } + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/regexp.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/regexp.rb new file mode 100644 index 0000000..66d995b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/regexp.rb @@ -0,0 +1 @@ +require 'mustermann/regular' diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/regexp_based.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/regexp_based.rb new file mode 100644 index 0000000..b17113b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/regexp_based.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true +require 'mustermann/pattern' +require 'forwardable' + +module Mustermann + # Superclass for patterns that internally compile to a regular expression. + # @see Mustermann::Pattern + # @abstract + class RegexpBased < Pattern + # @return [Regexp] regular expression equivalent to the pattern. + attr_reader :regexp + alias_method :to_regexp, :regexp + + # @param (see Mustermann::Pattern#initialize) + # @return (see Mustermann::Pattern#initialize) + # @see (see Mustermann::Pattern#initialize) + def initialize(string, **options) + super + regexp = compile(**options) + @peek_regexp = /\A#{regexp}/ + @regexp = /\A#{regexp}\Z/ + end + + # @param (see Mustermann::Pattern#peek_size) + # @return (see Mustermann::Pattern#peek_size) + # @see (see Mustermann::Pattern#peek_size) + def peek_size(string) + return unless match = peek_match(string) + match.to_s.size + end + + # @param (see Mustermann::Pattern#peek_match) + # @return (see Mustermann::Pattern#peek_match) + # @see (see Mustermann::Pattern#peek_match) + def peek_match(string) + @peek_regexp.match(string) + end + + extend Forwardable + def_delegators :regexp, :===, :=~, :match, :names, :named_captures + + def compile(**options) + raise NotImplementedError, 'subclass responsibility' + end + + private :compile + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/regular.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/regular.rb new file mode 100644 index 0000000..53b7c7e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/regular.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true +require 'mustermann' +require 'mustermann/regexp_based' +require 'strscan' + +module Mustermann + # Regexp pattern implementation. + # + # @example + # Mustermann.new('/.*', type: :regexp) === '/bar' # => true + # + # @see Mustermann::Pattern + # @see file:README.md#simple Syntax description in the README + class Regular < RegexpBased + include Concat::Native + register :regexp, :regular + supported_options :check_anchors + + # @param (see Mustermann::Pattern#initialize) + # @return (see Mustermann::Pattern#initialize) + # @see (see Mustermann::Pattern#initialize) + def initialize(string, check_anchors: true, **options) + string = $1 if string.to_s =~ /\A\(\?\-mix\:(.*)\)\Z/ && string.inspect == "/#$1/" + string = string.source.gsub!(/(?] empty array for imitating MatchData interface + def names + @names.dup + end + + # @return [Array] empty array for imitating MatchData interface + def captures + @captures.dup + end + + # @return [nil] imitates MatchData interface + def [](*args) + args.map! do |arg| + next arg unless arg.is_a? Symbol or arg.is_a? String + names.index(arg.to_s) + end + @captures[*args] + end + + # @!visibility private + def +(other) + SimpleMatch.new(@string + other.to_s, + names: @names + other.names, + captures: @captures + other.captures) + end + + # @return [String] string representation + def inspect + "#<%p %p>" % [self.class, @string] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra.rb new file mode 100644 index 0000000..33fa870 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra.rb @@ -0,0 +1,88 @@ +# frozen_string_literal: true +require 'mustermann' +require 'mustermann/identity' +require 'mustermann/ast/pattern' +require 'mustermann/sinatra/parser' +require 'mustermann/sinatra/safe_renderer' +require 'mustermann/sinatra/try_convert' + +module Mustermann + # Sinatra 2.0 style pattern implementation. + # + # @example + # Mustermann.new('/:foo') === '/bar' # => true + # + # @see Mustermann::Pattern + # @see file:README.md#sinatra Syntax description in the README + class Sinatra < AST::Pattern + include Concat::Native + register :sinatra + + # Takes a string and espaces any characters that have special meaning for Sinatra patterns. + # + # @example + # require 'mustermann/sinatra' + # Mustermann::Sinatra.escape("/:name") # => "/\\:name" + # + # @param [#to_s] string the input string + # @return [String] the escaped string + def self.escape(string) + string.to_s.gsub(/[\?\(\)\*:\\\|\{\}]/) { |c| "\\#{c}" } + end + + # Tries to convert the given input object to a Sinatra pattern with the given options, without + # changing its parsing semantics. + # @return [Mustermann::Sinatra, nil] the converted pattern, if possible + # @!visibility private + def self.try_convert(input, **options) + TryConvert.convert(input, **options) + end + + # Creates a pattern that matches any string matching either one of the patterns. + # If a string is supplied, it is treated as a fully escaped Sinatra pattern. + # + # If the other pattern is also a Sintara pattern, it might join the two to a third + # sinatra pattern instead of generating a composite for efficiency reasons. + # + # This only happens if the sinatra pattern behaves exactly the same as a composite + # would in regards to matching, parsing, expanding and template generation. + # + # @example + # pattern = Mustermann.new('/foo/:name') | Mustermann.new('/:first/:second') + # pattern === '/foo/bar' # => true + # pattern === '/fox/bar' # => true + # pattern === '/foo' # => false + # + # @param [Mustermann::Pattern, String] other the other pattern + # @return [Mustermann::Pattern] a composite pattern + # @see Mustermann::Pattern#| + def |(other) + return super unless converted = self.class.try_convert(other, **options) + return super unless converted.names.empty? or names.empty? + self.class.new(safe_string + "|" + converted.safe_string, **options) + end + + # Generates a string represenation of the pattern that can safely be used for def interpolation + # without changing its semantics. + # + # @example + # require 'mustermann' + # unsafe = Mustermann.new("/:name") + # + # Mustermann.new("#{unsafe}bar").params("/foobar") # => { "namebar" => "foobar" } + # Mustermann.new("#{unsafe.safe_string}bar").params("/foobar") # => { "name" => "bar" } + # + # @return [String] string representatin of the pattern + def safe_string + @safe_string ||= SafeRenderer.translate(to_ast) + end + + # @!visibility private + def native_concat(other) + return unless converted = self.class.try_convert(other, **options) + safe_string + converted.safe_string + end + + private :native_concat + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra/parser.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra/parser.rb new file mode 100644 index 0000000..9dbb216 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra/parser.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true +module Mustermann + class Sinatra < AST::Pattern + # Sinatra syntax definition. + # @!visibility private + class Parser < AST::Parser + on(nil, ??, ?)) { |c| unexpected(c) } + + on(?*) { |c| scan(/\w+/) ? node(:named_splat, buffer.matched) : node(:splat) } + on(?:) { |c| node(:capture) { scan(/\w+/) } } + on(?\\) { |c| node(:char, expect(/./)) } + on(?() { |c| node(:group) { read unless scan(?)) } } + on(?|) { |c| node(:or) } + + on ?{ do |char| + current_pos = buffer.pos + type = scan(?+) ? :named_splat : :capture + name = expect(/[\w\.]+/) + if type == :capture && scan(?|) + buffer.pos = current_pos + capture = proc do + start = pos + match = expect(/(?[^\|}]+)/) + node(:capture, match[:capture], start: start) + end + grouped_captures = node(:group, [capture[]]) do + if scan(?|) + [min_size(pos - 1, pos, node(:or)), capture[]] + end + end + grouped_captures if expect(?}) + else + type = :splat if type == :named_splat and name == 'splat' + expect(?}) + node(type, name) + end + end + + suffix ?? do |char, element| + node(:optional, element) + end + end + + private_constant :Parser + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra/safe_renderer.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra/safe_renderer.rb new file mode 100644 index 0000000..41a722f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra/safe_renderer.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true +module Mustermann + class Sinatra < AST::Pattern + # Generates a string that can safely be concatenated with other strings + # without chaning its semantics + # @see #safe_string + # @!visibility private + SafeRenderer = AST::Translator.create do + translate(:splat, :named_splat) { "{+#{name}}" } + translate(:char, :separator) { Sinatra.escape(payload) } + translate(:root) { t(payload) } + translate(:group) { "(#{t(payload)})" } + translate(:union) { "(#{t(payload, join: ?|)})" } + translate(:optional) { "#{t(payload)}?" } + translate(:with_look_ahead) { t([head, payload]) } + translate(Array) { |join: ""| map { |e| t(e) }.join(join) } + + translate(:capture) do + raise Mustermann::Error, 'cannot render variables' if node.is_a? :variable + raise Mustermann::Error, 'cannot translate constraints' if constraint or qualifier or convert + prefix = node.is_a?(:splat) ? "+" : "" + "{#{prefix}#{name}}" + end + end + + private_constant :SafeRenderer + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra/try_convert.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra/try_convert.rb new file mode 100644 index 0000000..f45bcda --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/sinatra/try_convert.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true +module Mustermann + class Sinatra < AST::Pattern + # Tries to translate objects to Sinatra patterns. + # @!visibility private + class TryConvert < AST::Translator + # @return [Mustermann::Sinatra, nil] + # @!visibility private + def self.convert(input, **options) + new(options).translate(input) + end + + # Expected options for the resulting pattern. + # @!visibility private + attr_reader :options + + # @!visibility private + def initialize(options) + @options = options + end + + # @return [Mustermann::Sinatra] + # @!visibility private + def new(input, escape = false) + input = Mustermann::Sinatra.escape(input) if escape + Mustermann::Sinatra.new(input, **options) + end + + # @return [true, false] whether or not expected pattern should have uri_decode option set + # @!visibility private + def uri_decode + options.fetch(:uri_decode, true) + end + + translate(Object) { nil } + translate(String) { t.new(self, true) } + + translate(Identity) { t.new(self, true) if uri_decode == t.uri_decode } + translate(Sinatra) { node if options == t.options } + + translate AST::Pattern do + next unless options == t.options + t.new(SafeRenderer.translate(to_ast)) rescue nil + end + end + + private_constant :TryConvert + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/to_pattern.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/to_pattern.rb new file mode 100644 index 0000000..2e41889 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/to_pattern.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true +require 'mustermann' + +module Mustermann + # Mixin for adding {#to_pattern} ducktyping to objects. + # + # @example + # require 'mustermann/to_pattern' + # + # class Foo + # include Mustermann::ToPattern + # + # def to_s + # ":foo/:bar" + # end + # end + # + # Foo.new.to_pattern # => # + # + # By default included into String, Symbol, Regexp, Array and {Mustermann::Pattern}. + module ToPattern + PRIMITIVES = [String, Symbol, Array, Regexp, Mustermann::Pattern] + private_constant :PRIMITIVES + + # Converts the object into a {Mustermann::Pattern}. + # + # @example converting a string + # ":name.png".to_pattern # => # + # + # @example converting a string with options + # "/*path".to_pattern(type: :rails) # => # + # + # @example converting a regexp + # /.*/.to_pattern # => # + # + # @example converting a pattern + # Mustermann.new("foo").to_pattern # => # + # + # @param [Hash] options The options hash. + # @return [Mustermann::Pattern] pattern corresponding to object. + def to_pattern(**options) + input = self if PRIMITIVES.any? { |p| self.is_a? p } + input ||= __getobj__ if respond_to?(:__getobj__) + Mustermann.new(input || to_s, **options) + end + + PRIMITIVES.each do |klass| + append_features(klass) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/version.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/version.rb new file mode 100644 index 0000000..f8a3996 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/lib/mustermann/version.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true +module Mustermann + VERSION ||= '1.1.1' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/mustermann.gemspec b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/mustermann.gemspec new file mode 100644 index 0000000..fd61b41 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/mustermann.gemspec @@ -0,0 +1,19 @@ +$:.unshift File.expand_path("../lib", __FILE__) +require "mustermann/version" + +Gem::Specification.new do |s| + s.name = "mustermann" + s.version = Mustermann::VERSION + s.authors = ["Konstantin Haase", "Zachary Scott"] + s.email = "sinatrarb@googlegroups.com" + s.homepage = "https://github.com/sinatra/mustermann" + s.summary = %q{Your personal string matching expert.} + s.description = %q{A library implementing patterns that behave like regular expressions.} + s.license = 'MIT' + s.required_ruby_version = '>= 2.2.0' + s.files = `git ls-files`.split("\n") + s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") + s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } + + s.add_runtime_dependency('ruby2_keywords', '~> 0.0.1') +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/ast_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/ast_spec.rb new file mode 100644 index 0000000..d04f58e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/ast_spec.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann/ast/node' + +describe Mustermann::AST do + describe :type do + example { Mustermann::AST::Node[:char].type .should be == :char } + example { Mustermann::AST::Node[:char].new.type .should be == :char } + end + + describe :min_size do + example { Mustermann::AST::Node[:char].new.min_size.should be == 1 } + example { Mustermann::AST::Node[:node].new.min_size.should be == 0 } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/composite_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/composite_spec.rb new file mode 100644 index 0000000..bfc10dd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/composite_spec.rb @@ -0,0 +1,163 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann' + +describe Mustermann::Composite do + describe :new do + example 'with no argument' do + expect { Mustermann::Composite.new }. + to raise_error(ArgumentError, 'cannot create empty composite pattern') + end + + example 'with one argument' do + pattern = Mustermann.new('/foo') + Mustermann::Composite.new(pattern).should be == pattern + end + + example 'with supported type specific arguments' do + Mustermann::Composite.new("/a", "/b", greedy: true) + end + + example 'with unsupported type specific arguments' do + expect { Mustermann::Composite.new("/a", "/b", greedy: true, type: :identity) }.to raise_error(ArgumentError) + end + end + + context :| do + subject(:pattern) { Mustermann.new('/foo/:name', '/:first/:second') } + + describe :== do + example { subject.should be == subject } + example { subject.should be == Mustermann.new('/foo/:name', '/:first/:second') } + example { subject.should_not be == Mustermann.new('/foo/:name') } + example { subject.should_not be == Mustermann.new('/foo/:name', '/:first/:second', operator: :&) } + end + + describe :=== do + example { subject.should be === "/foo/bar" } + example { subject.should be === "/fox/bar" } + example { subject.should_not be === "/foo" } + end + + describe :params do + example { subject.params("/foo/bar") .should be == { "name" => "bar" } } + example { subject.params("/fox/bar") .should be == { "first" => "fox", "second" => "bar" } } + example { subject.params("/foo") .should be_nil } + end + + describe :=== do + example { subject.should match("/foo/bar") } + example { subject.should match("/fox/bar") } + example { subject.should_not match("/foo") } + end + + describe :expand do + example { subject.should respond_to(:expand) } + example { subject.expand(name: 'bar') .should be == '/foo/bar' } + example { subject.expand(first: 'fox', second: 'bar') .should be == '/fox/bar' } + + context "without expandable patterns" do + subject(:pattern) { Mustermann.new('/foo/:name', '/:first/:second', type: :simple) } + example { subject.should_not respond_to(:expand) } + example { expect { subject.expand(name: 'bar') }.to raise_error(NotImplementedError) } + end + end + + describe :to_templates do + example { should respond_to(:to_templates) } + example { should generate_templates('/foo/{name}', '/{first}/{second}') } + + context "without patterns implementing to_templates" do + subject(:pattern) { Mustermann.new('/foo/:name', '/:first/:second', type: :simple) } + example { should_not respond_to(:to_templates) } + example { expect { subject.to_templates }.to raise_error(NotImplementedError) } + end + end + + describe :eql? do + example { should be_eql(pattern) } + example { should be_eql(Mustermann.new('/foo/:name', '/:first/:second', operator: :|)) } + example { should_not be_eql(Mustermann.new('/bar/:name', '/:first/:second', operator: :|)) } + example { should_not be_eql(Mustermann.new('/foo/:name', '/:first/:second', operator: :&)) } + end + end + + context :& do + subject(:pattern) { Mustermann.new('/foo/:name', '/:first/:second', operator: :&) } + + describe :== do + example { subject.should be == subject } + example { subject.should be == Mustermann.new('/foo/:name', '/:first/:second', operator: :&) } + example { subject.should_not be == Mustermann.new('/foo/:name') } + example { subject.should_not be == Mustermann.new('/foo/:name', '/:first/:second') } + end + + describe :=== do + example { subject.should be === "/foo/bar" } + example { subject.should_not be === "/fox/bar" } + example { subject.should_not be === "/foo" } + end + + describe :params do + example { subject.params("/foo/bar") .should be == { "name" => "bar" } } + example { subject.params("/fox/bar") .should be_nil } + example { subject.params("/foo") .should be_nil } + end + + describe :match do + example { subject.should match("/foo/bar") } + example { subject.should_not match("/fox/bar") } + example { subject.should_not match("/foo") } + end + + describe :expand do + example { subject.should_not respond_to(:expand) } + example { expect { subject.expand(name: 'bar') }.to raise_error(NotImplementedError) } + end + end + + context :^ do + subject(:pattern) { Mustermann.new('/foo/:name', '/:first/:second', operator: :^) } + + describe :== do + example { subject.should be == subject } + example { subject.should_not be == Mustermann.new('/foo/:name', '/:first/:second') } + example { subject.should_not be == Mustermann.new('/foo/:name') } + example { subject.should_not be == Mustermann.new('/foo/:name', '/:first/:second', operator: :&) } + end + + describe :=== do + example { subject.should_not be === "/foo/bar" } + example { subject.should be === "/fox/bar" } + example { subject.should_not be === "/foo" } + end + + describe :params do + example { subject.params("/foo/bar") .should be_nil } + example { subject.params("/fox/bar") .should be == { "first" => "fox", "second" => "bar" } } + example { subject.params("/foo") .should be_nil } + end + + describe :match do + example { subject.should_not match("/foo/bar") } + example { subject.should match("/fox/bar") } + example { subject.should_not match("/foo") } + end + + describe :expand do + example { subject.should_not respond_to(:expand) } + example { expect { subject.expand(name: 'bar') }.to raise_error(NotImplementedError) } + end + end + + describe :inspect do + let(:sinatra) { Mustermann.new('x') } + let(:shell) { Mustermann.new('x', type: :shell) } + let(:identity) { Mustermann.new('x', type: :identity) } + + example { (sinatra | shell) .inspect.should include('(sinatra:"x" | shell:"x")') } + example { (sinatra ^ shell) .inspect.should include('(sinatra:"x" ^ shell:"x")') } + example { (sinatra | shell | identity) .inspect.should include('(sinatra:"x" | shell:"x" | identity:"x")') } + example { (sinatra | shell & identity) .inspect.should include('(sinatra:"x" | (shell:"x" & identity:"x"))') } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/concat_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/concat_spec.rb new file mode 100644 index 0000000..aea59a4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/concat_spec.rb @@ -0,0 +1,127 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann' + +describe Mustermann::Concat do + describe Mustermann::Concat::Native do + context "sinatra + sinatra" do + subject(:pattern) { Mustermann.new("/:foo") + Mustermann.new("/:bar") } + its(:class) { should be == Mustermann::Sinatra } + its(:to_s) { should be == "/{foo}/{bar}" } + end + + context "sinatra + string" do + subject(:pattern) { Mustermann.new("/:foo") + "/:bar" } + its(:class) { should be == Mustermann::Sinatra } + its(:to_s) { should be == "/{foo}/\\:bar" } + end + + context "regular + regular" do + subject(:pattern) { Mustermann.new(/foo/) + Mustermann.new(/bar/) } + its(:class) { should be == Mustermann::Regular } + its(:to_s) { should be == "foobar" } + end + + context "sinatra + rails" do + subject(:pattern) { Mustermann.new("/:foo") + Mustermann.new("/:bar", type: :rails) } + its(:class) { should be == Mustermann::Sinatra } + its(:to_s) { should be == "/{foo}/{bar}" } + end + + context "sinatra + flask" do + subject(:pattern) { Mustermann.new("/:foo") + Mustermann.new("/", type: :flask) } + its(:class) { should be == Mustermann::Sinatra } + its(:to_s) { should be == "/{foo}/{bar}" } + end + + context "sinatra + flask (typed)" do + subject(:pattern) { Mustermann.new("/:foo") + Mustermann.new("/", type: :flask) } + its(:class) { should be == Mustermann::Concat } + its(:to_s) { should be == '(sinatra:"/:foo" + flask:"/")' } + end + + context "sinatra + sinatra (different options)" do + subject(:pattern) { Mustermann.new("/:foo") + Mustermann.new("/:bar", uri_decode: false) } + its(:class) { should be == Mustermann::Concat } + its(:to_s) { should be == '(sinatra:"/:foo" + sinatra:"/:bar")' } + end + + context "sinatra + rails (different options)" do + subject(:pattern) { Mustermann.new("/:foo") + Mustermann.new("/:bar", type: :rails, uri_decode: false) } + its(:class) { should be == Mustermann::Concat } + its(:to_s) { should be == '(sinatra:"/:foo" + rails:"/:bar")' } + end + + context "sinatra + rails (different options) + sinatra" do + subject(:pattern) { Mustermann.new("/:foo") + Mustermann.new("/:bar", type: :rails, uri_decode: false) + Mustermann.new("/:baz") } + its(:class) { should be == Mustermann::Concat } + its(:to_s) { should be == '(sinatra:"/:foo" + rails:"/:bar" + sinatra:"/:baz")' } + end + + context "sinatra + (sinatra + regular)" do + subject(:pattern) { Mustermann.new("/foo") + (Mustermann.new("/bar") + Mustermann.new(/baz/)) } + its(:class) { should be == Mustermann::Concat } + its(:to_s) { should be == '(sinatra:"/foo/bar" + regular:"baz")' } + end + + context "sinatra + (sinatra + rails (different options) + sinatra)" do + subject(:pattern) { Mustermann.new("/foo") + (Mustermann.new("/bar") + Mustermann.new("/baz", type: :rails, uri_decode: false) + Mustermann.new("/boo")) } + its(:class) { should be == Mustermann::Concat } + its(:to_s) { should be == '(sinatra:"/foo/bar" + rails:"/baz" + sinatra:"/boo")' } + end + end + + subject(:pattern) { Mustermann::Concat.new("/:foo", "/:bar") } + + describe :=== do + example { (pattern === "/foo/bar") .should be true } + example { (pattern === "/foo/bar/") .should be false } + example { (pattern === "/foo") .should be false } + end + + describe :match do + it { should match("/foo/bar").capturing(foo: "foo", bar: "bar") } + it { should_not match("/foo/bar/") } + it { should_not match("/foo/") } + end + + describe :params do + example { pattern.params("/foo/bar") .should be == { "foo" => "foo", "bar" => "bar" }} + example { pattern.params("/foo/bar/") .should be_nil } + example { pattern.params("/foo") .should be_nil } + end + + describe :peek do + example { pattern.peek("/foo/bar/baz") .should be == "/foo/bar" } + example { pattern.peek("/foo") .should be_nil } + end + + describe :peek_params do + example { pattern.peek_params("/foo/bar/baz") .should be == [{ "foo" => "foo", "bar" => "bar" }, 8]} + example { pattern.peek_params("/foo") .should be_nil } + end + + describe :peek_match do + example { pattern.peek_match("/foo/bar/baz").to_s .should be == "/foo/bar" } + example { pattern.peek_match("/foo") .should be_nil } + end + + describe :peek_size do + example { pattern.peek_size("/foo/bar/baz") .should be == 8 } + example { pattern.peek_size("/foo") .should be_nil } + end + + describe :expand do + it { should expand(foo: :bar, bar: :foo) .to('/bar/foo') } + it { should expand(:append, foo: :bar, bar: :foo, baz: 42) .to('/bar/foo?baz=42') } + it { should_not expand(foo: :bar) } + end + + describe :to_templates do + subject(:pattern) { Mustermann::Concat.new("/:foo|:bar", "(/:baz)?") } + it { should generate_template("/{foo}/{baz}") } + it { should generate_template("{bar}/{baz}") } + it { should generate_template("/{foo}") } + it { should generate_template("{bar}") } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/equality_map_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/equality_map_spec.rb new file mode 100644 index 0000000..6aa982c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/equality_map_spec.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann/equality_map' + +RSpec.describe Mustermann::EqualityMap do + before { GC.disable } + after { GC.enable } + + describe :fetch do + subject { Mustermann::EqualityMap.new } + specify 'with existing entry' do + next if subject.is_a? Hash + subject.fetch("foo") { "foo" } + result = subject.fetch("foo") { "bar" } + expect(result).to be == "foo" + end + + specify 'with GC-removed entry' do + next if subject.is_a? Hash + subject.fetch(String.new('foo')) { "foo" } + expect(subject.map).to receive(:[]).and_return(nil) + result = subject.fetch(String.new('foo')) { "bar" } + expect(result).to be == "bar" + end + + specify 'allows a frozen key and value' do + next if subject.is_a? Hash + key = "foo".freeze + value = "bar".freeze + subject.fetch(key) { value } + result = subject.fetch("foo".dup) { raise "not executed" } + expect(result).to be == value + expect(result).not_to equal value + end + + specify 'allows only a single argument to be compatible with Hash#fetch' do + expect { + subject.fetch("foo", "bar", "baz") { "value" } + }.to raise_error(ArgumentError) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/expander_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/expander_spec.rb new file mode 100644 index 0000000..ae418ea --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/expander_spec.rb @@ -0,0 +1,123 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann/expander' + +describe Mustermann::Expander do + it 'expands a pattern' do + expander = Mustermann::Expander.new("/:foo.jpg") + expander.expand(foo: 42).should be == "/42.jpg" + end + + it 'expands multiple patterns' do + expander = Mustermann::Expander.new << "/:foo.:ext" << "/:foo" + expander.expand(foo: 42, ext: 'jpg').should be == "/42.jpg" + expander.expand(foo: 23).should be == "/23" + end + + it 'supports setting pattern options' do + expander = Mustermann::Expander.new(type: :rails) << "/:foo(.:ext)" << "/:bar" + expander.expand(foo: 42, ext: 'jpg').should be == "/42.jpg" + expander.expand(foo: 42).should be == "/42" + end + + it 'supports combining different pattern styles' do + expander = Mustermann::Expander.new << Mustermann.new("/:foo(.:ext)", type: :rails) << Mustermann.new("/:bar", type: :sinatra) + expander.expand(foo: 'pony', ext: 'jpg').should be == '/pony.jpg' + expander.expand(bar: 23).should be == "/23" + end + + it 'ignores nil values' do + expander = Mustermann::Expander.new << Mustermann.new("/:foo(.:ext)?") + expander.expand(foo: 'pony', ext: nil).should be == '/pony' + end + + it 'supports splat' do + expander = Mustermann::Expander.new << Mustermann.new("/foo/*/baz") + expander.expand(splat: 'bar').should be == '/foo/bar/baz' + end + + it 'supports multiple splats' do + expander = Mustermann::Expander.new << Mustermann.new("/foo/*/bar/*") + expander.expand(splat: [123, 456]).should be == '/foo/123/bar/456' + end + + it 'supports identity patterns' do + expander = Mustermann::Expander.new('/:foo', type: :identity) + expander.expand.should be == '/:foo' + end + + describe :additional_values do + context "illegal value" do + example { expect { Mustermann::Expander.new(additional_values: :foo) }.to raise_error(ArgumentError) } + example { expect { Mustermann::Expander.new('/').expand(:foo, a: 10) }.to raise_error(ArgumentError) } + end + + context :raise do + subject(:expander) { Mustermann::Expander.new('/:a', additional_values: :raise) } + example { expander.expand(a: ?a).should be == '/a' } + example { expect { expander.expand(a: ?a, b: ?b) }.to raise_error(Mustermann::ExpandError) } + example { expect { expander.expand(b: ?b) }.to raise_error(Mustermann::ExpandError) } + end + + context :ignore do + subject(:expander) { Mustermann::Expander.new('/:a', additional_values: :ignore) } + example { expander.expand(a: ?a).should be == '/a' } + example { expander.expand(a: ?a, b: ?b).should be == '/a' } + example { expect { expander.expand(b: ?b) }.to raise_error(Mustermann::ExpandError) } + example { expect { expander.expand(b: ?b, c: []) }.to raise_error(Mustermann::ExpandError) } + example { expect { expander.expand(b: ?b, c: [], d: ?d) }.to raise_error(Mustermann::ExpandError) } + end + + context :append do + subject(:expander) { Mustermann::Expander.new('/:a', additional_values: :append) } + example { expander.expand(a: ?a).should be == '/a' } + example { expander.expand(a: ?a, b: ?b).should be == '/a?b=b' } + example { expect { expander.expand(b: ?b) }.to raise_error(Mustermann::ExpandError) } + end + end + + describe :cast do + subject(:expander) { Mustermann::Expander.new('/:a(/:b)?') } + + example { expander.cast { "FOOBAR" }.expand(a: "foo") .should be == "/FOOBAR" } + example { expander.cast { |v| v.upcase }.expand(a: "foo") .should be == "/FOO" } + example { expander.cast { |v| v.upcase }.expand(a: "foo", b: "bar") .should be == "/FOO/BAR" } + example { expander.cast(:a) { |v| v.upcase }.expand(a: "foo", b: "bar") .should be == "/FOO/bar" } + example { expander.cast(:a, :b) { |v| v.upcase }.expand(a: "foo", b: "bar") .should be == "/FOO/BAR" } + example { expander.cast(Integer) { |k,v| "#{k}_#{v}" }.expand(a: "foo", b: 42) .should be == "/foo/b_42" } + + example do + expander.cast(:a) { |v| v.upcase } + expander.cast(:b) { |v| v.downcase } + expander.expand(a: "fOo", b: "bAr").should be == "/FOO/bar" + end + end + + describe :== do + example { Mustermann::Expander.new('/foo') .should be == Mustermann::Expander.new('/foo') } + example { Mustermann::Expander.new('/foo') .should_not be == Mustermann::Expander.new('/bar') } + example { Mustermann::Expander.new('/foo', type: :rails) .should be == Mustermann::Expander.new('/foo', type: :rails) } + example { Mustermann::Expander.new('/foo', type: :rails) .should_not be == Mustermann::Expander.new('/foo', type: :sinatra) } + end + + describe :hash do + example { Mustermann::Expander.new('/foo') .hash.should be == Mustermann::Expander.new('/foo').hash } + example { Mustermann::Expander.new('/foo') .hash.should_not be == Mustermann::Expander.new('/bar').hash } + example { Mustermann::Expander.new('/foo', type: :rails) .hash.should be == Mustermann::Expander.new('/foo', type: :rails).hash } + example { Mustermann::Expander.new('/foo', type: :rails) .hash.should_not be == Mustermann::Expander.new('/foo', type: :sinatra).hash } + end + + describe :eql? do + example { Mustermann::Expander.new('/foo') .should be_eql Mustermann::Expander.new('/foo') } + example { Mustermann::Expander.new('/foo') .should_not be_eql Mustermann::Expander.new('/bar') } + example { Mustermann::Expander.new('/foo', type: :rails) .should be_eql Mustermann::Expander.new('/foo', type: :rails) } + example { Mustermann::Expander.new('/foo', type: :rails) .should_not be_eql Mustermann::Expander.new('/foo', type: :sinatra) } + end + + describe :equal? do + example { Mustermann::Expander.new('/foo') .should_not be_equal Mustermann::Expander.new('/foo') } + example { Mustermann::Expander.new('/foo') .should_not be_equal Mustermann::Expander.new('/bar') } + example { Mustermann::Expander.new('/foo', type: :rails) .should_not be_equal Mustermann::Expander.new('/foo', type: :rails) } + example { Mustermann::Expander.new('/foo', type: :rails) .should_not be_equal Mustermann::Expander.new('/foo', type: :sinatra) } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/extension_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/extension_spec.rb new file mode 100644 index 0000000..c1a7686 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/extension_spec.rb @@ -0,0 +1,297 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann/extension' +require 'sinatra/base' +require 'rack/test' + +describe Mustermann::Extension do + include Rack::Test::Methods + + subject :app do + Sinatra.new do + set :environment, :test + register Mustermann + end + end + + it 'sets up the extension' do + app.should be_a(Mustermann::Extension) + end + + context 'uses Sinatra-style patterns by default' do + before { app.get('/:slug(.:extension)?') { params[:slug] } } + example { get('/foo') .body.should be == 'foo' } + example { get('/foo.') .body.should be == 'foo.' } + example { get('/foo.bar') .body.should be == 'foo' } + example { get('/a%20b') .body.should be == 'a b' } + end + + describe :except do + before { app.get('/auth/*', except: '/auth/login') { 'ok' } } + example { get('/auth/dunno').should be_ok } + example { get('/auth/login').should_not be_ok } + end + + describe :capture do + context 'global' do + before do + app.set(:pattern, capture: { ext: %w[png jpg gif] }) + app.get('/:slug(.:ext)?') { params[:slug] } + end + + example { get('/foo.bar').body.should be == 'foo.bar' } + example { get('/foo.png').body.should be == 'foo' } + end + + context 'route local' do + before do + app.set(:pattern, nil) + app.get('/:id', capture: /\d+/) { 'ok' } + end + + example { get('/42').should be_ok } + example { get('/foo').should_not be_ok } + end + + context 'global and route local' do + context 'global is a hash' do + before do + app.set(:pattern, capture: { id: /\d+/ }) + app.get('/:id(.:ext)?', capture: { ext: 'png' }) { ?a } + app.get('/:id', capture: { id: 'foo' }) { ?b } + app.get('/:id', capture: :alpha) { ?c } + end + + example { get('/20') .body.should be == ?a } + example { get('/20.png') .body.should be == ?a } + example { get('/foo') .body.should be == ?b } + example { get('/bar') .body.should be == ?c } + end + + context 'global is not a hash' do + before do + app.set(:pattern, capture: /\d+/) + app.get('/:slug(.:ext)?', capture: { ext: 'png' }) { params[:slug] } + app.get('/:slug', capture: :alpha) { 'ok' } + end + + example { get('/20.png').should be_ok } + example { get('/foo.png').should_not be_ok } + example { get('/foo').should be_ok } + + example { get('/20.png') .body.should be == '20' } + example { get('/42') .body.should be == '42' } + example { get('/foo') .body.should be == 'ok' } + end + end + end + + describe :pattern do + describe :except do + before { app.get('/auth/*', pattern: { except: '/auth/login' }) { 'ok' } } + example { get('/auth/dunno').should be_ok } + example { get('/auth/login').should_not be_ok } + end + + describe :capture do + context 'route local' do + before do + app.set(:pattern, nil) + app.get('/:id', pattern: { capture: /\d+/ }) { 'ok' } + end + + example { get('/42').should be_ok } + example { get('/foo').should_not be_ok } + end + + context 'global and route local' do + context 'global is a hash' do + before do + app.set(:pattern, capture: { id: /\d+/ }) + app.get('/:id(.:ext)?', pattern: { capture: { ext: 'png' }}) { ?a } + app.get('/:id', pattern: { capture: { id: 'foo' }}) { ?b } + app.get('/:id', pattern: { capture: :alpha }) { ?c } + end + + example { get('/20') .body.should be == ?a } + example { get('/20.png') .body.should be == ?a } + example { get('/foo') .body.should be == ?b } + example { get('/bar') .body.should be == ?c } + end + + context 'global is not a hash' do + before do + app.set(:pattern, capture: /\d+/) + app.get('/:slug(.:ext)?', pattern: { capture: { ext: 'png' }}) { params[:slug] } + app.get('/:slug', pattern: { capture: :alpha }) { 'ok' } + end + + example { get('/20.png').should be_ok } + example { get('/foo.png').should_not be_ok } + example { get('/foo').should be_ok } + + example { get('/20.png') .body.should be == '20' } + example { get('/42') .body.should be == '42' } + example { get('/foo') .body.should be == 'ok' } + end + end + end + + describe :greedy do + context 'default' do + before { app.get('/:name.:ext') { params[:name] }} + example { get('/foo.bar') .body.should be == 'foo' } + example { get('/foo.bar.baz') .body.should be == 'foo.bar' } + end + + context 'enabled' do + before { app.get('/:name.:ext', pattern: { greedy: true }) { params[:name] }} + example { get('/foo.bar') .body.should be == 'foo' } + example { get('/foo.bar.baz') .body.should be == 'foo.bar' } + end + + context 'disabled' do + before { app.get('/:name.:ext', pattern: { greedy: false }) { params[:name] }} + example { get('/foo.bar') .body.should be == 'foo' } + example { get('/foo.bar.baz') .body.should be == 'foo' } + end + + context 'global' do + before do + app.set(:pattern, greedy: false) + app.get('/:name.:ext') { params[:name] } + end + + example { get('/foo.bar') .body.should be == 'foo' } + example { get('/foo.bar.baz') .body.should be == 'foo' } + end + end + + describe :space_matches_plus do + context 'default' do + before { app.get('/foo bar') { 'ok' }} + example { get('/foo%20bar') .should be_ok } + example { get('/foo+bar') .should be_ok } + end + + context 'enabled' do + before { app.get('/foo bar', pattern: { space_matches_plus: true }) { 'ok' }} + example { get('/foo%20bar') .should be_ok } + example { get('/foo+bar') .should be_ok } + end + + context 'disabled' do + before { app.get('/foo bar', pattern: { space_matches_plus: false }) { 'ok' }} + example { get('/foo%20bar') .should be_ok } + example { get('/foo+bar') .should_not be_ok } + end + + context 'global' do + before do + app.set(:pattern, space_matches_plus: false) + app.get('/foo bar') { 'ok' } + end + + example { get('/foo%20bar') .should be_ok } + example { get('/foo+bar') .should_not be_ok } + end + end + + describe :uri_decode do + context 'default' do + before { app.get('/&') { 'ok' }} + example { get('/&') .should be_ok } + example { get('/%26') .should be_ok } + end + + context 'enabled' do + before { app.get('/&', pattern: { uri_decode: true }) { 'ok' }} + example { get('/&') .should be_ok } + example { get('/%26') .should be_ok } + end + + context 'disabled' do + before { app.get('/&', pattern: { uri_decode: false }) { 'ok' }} + example { get('/&') .should be_ok } + example { get('/%26') .should_not be_ok } + end + + context 'global' do + before do + app.set(:pattern, uri_decode: false) + app.get('/&') { 'ok' } + end + + example { get('/&') .should be_ok } + example { get('/%26') .should_not be_ok } + end + end + end + + describe :type do + describe :identity do + before do + app.set(:pattern, type: :identity) + app.get('/:foo') { 'ok' } + end + + example { get('/:foo').should be_ok } + example { get('/foo').should_not be_ok } + end + + describe :rails do + before do + app.set(:pattern, type: :rails) + app.get('/:slug(.:extension)') { params[:slug] } + end + + example { get('/foo') .body.should be == 'foo' } + example { get('/foo.') .body.should be == 'foo.' } + example { get('/foo.bar') .body.should be == 'foo' } + example { get('/a%20b') .body.should be == 'a b' } + end + + describe :shell do + before do + app.set(:pattern, type: :shell) + app.get('/{foo,bar}') { 'ok' } + end + + example { get('/foo').should be_ok } + example { get('/bar').should be_ok } + end + + describe :simple do + before do + app.set(:pattern, type: :simple) + app.get('/(a)') { 'ok' } + end + + example { get('/(a)').should be_ok } + example { get('/a').should_not be_ok } + end + + describe :simple do + before do + app.set(:pattern, type: :template) + app.get('/foo{/segments*}{.ext}') { "%p %p" % [params[:segments], params[:ext]] } + end + + example { get('/foo/a.png').should be_ok } + example { get('/foo/a').should_not be_ok } + + example { get('/foo/a.png').body.should be == '["a"] "png"' } + example { get('/foo/a/b.png').body.should be == '["a", "b"] "png"' } + end + end + + context 'works with filters' do + before do + app.before('/auth/*', except: '/auth/login') { halt 'auth required' } + app.get('/auth/login') { 'please log in' } + end + + example { get('/auth/dunno').body.should be == 'auth required' } + example { get('/auth/login').body.should be == 'please log in' } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/identity_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/identity_spec.rb new file mode 100644 index 0000000..6873df8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/identity_spec.rb @@ -0,0 +1,127 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann/identity' + +describe Mustermann::Identity do + extend Support::Pattern + + pattern '' do + it { should match('') } + it { should_not match('/') } + + it { should respond_to(:expand) } + it { should respond_to(:to_templates) } + + + it { should generate_template('') } + it { should expand.to('') } + it { should expand(:ignore, a: 10).to('') } + it { should expand(:append, a: 10).to('?a=10') } + it { should_not expand(:raise, a: 10) } + it { should_not expand(a: 10) } + + example do + pattern.match('').inspect.should be == '#' + end + end + + pattern '/' do + it { should match('/') } + it { should_not match('/foo') } + + example { pattern.params('/').should be == {} } + example { pattern.params('').should be_nil } + + it { should generate_template('/') } + it { should expand.to('/') } + end + + pattern '/foo' do + it { should match('/foo') } + it { should_not match('/bar') } + it { should_not match('/foo.bar') } + end + + pattern '/foo/bar' do + it { should match('/foo/bar') } + it { should match('/foo%2Fbar') } + it { should match('/foo%2fbar') } + end + + pattern '/:foo' do + it { should match('/:foo') } + it { should match('/%3Afoo') } + it { should_not match('/foo') } + it { should_not match('/foo?') } + it { should_not match('/foo/bar') } + it { should_not match('/') } + it { should_not match('/foo/') } + + it { should generate_template('/:foo') } + it { should expand.to('/:foo') } + end + + pattern '/föö' do + it { should match("/f%C3%B6%C3%B6") } + end + + pattern '/test$/' do + it { should match('/test$/') } + end + + pattern '/te+st/' do + it { should match('/te+st/') } + it { should_not match('/test/') } + it { should_not match('/teest/') } + end + + pattern "/path with spaces" do + it { should match('/path%20with%20spaces') } + it { should_not match('/path%2Bwith%2Bspaces') } + it { should_not match('/path+with+spaces') } + it { should generate_template('/path%20with%20spaces') } + end + + pattern '/foo&bar' do + it { should match('/foo&bar') } + end + + pattern '/test.bar' do + it { should match('/test.bar') } + it { should_not match('/test0bar') } + end + + pattern '/foo/bar', uri_decode: false do + it { should match('/foo/bar') } + it { should_not match('/foo%2Fbar') } + it { should_not match('/foo%2fbar') } + end + + pattern "/path with spaces", uri_decode: false do + it { should_not match('/path%20with%20spaces') } + it { should_not match('/path%2Bwith%2Bspaces') } + it { should_not match('/path+with+spaces') } + end + + context "peeking" do + subject(:pattern) { Mustermann::Identity.new("foo bar") } + + describe :peek_size do + example { pattern.peek_size("foo bar blah") .should be == "foo bar".size } + example { pattern.peek_size("foo%20bar blah") .should be == "foo%20bar".size } + example { pattern.peek_size("foobar") .should be_nil } + end + + describe :peek_match do + example { pattern.peek_match("foo bar blah").to_s .should be == "foo bar" } + example { pattern.peek_match("foo%20bar blah").to_s .should be == "foo%20bar" } + example { pattern.peek_match("foobar") .should be_nil } + end + + describe :peek_params do + example { pattern.peek_params("foo bar blah") .should be == [{}, "foo bar".size] } + example { pattern.peek_params("foo%20bar blah") .should be == [{}, "foo%20bar".size] } + example { pattern.peek_params("foobar") .should be_nil } + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/mapper_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/mapper_spec.rb new file mode 100644 index 0000000..ced3eca --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/mapper_spec.rb @@ -0,0 +1,77 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann/mapper' + +describe Mustermann::Mapper do + describe :initialize do + context 'accepts a block with no arguments, using the return value' do + subject(:mapper) { Mustermann::Mapper.new(additional_values: :raise) {{ "/foo" => "/bar" }}} + its(:to_h) { should be == { Mustermann.new("/foo") => Mustermann::Expander.new("/bar") } } + example { mapper['/foo'].should be == '/bar' } + example { mapper['/fox'].should be == '/fox' } + end + + context 'accepts a block with argument, passes instance to it' do + subject(:mapper) { Mustermann::Mapper.new(additional_values: :raise) { |m| m["/foo"] = "/bar" }} + its(:to_h) { should be == { Mustermann.new("/foo") => Mustermann::Expander.new("/bar") } } + example { mapper['/foo'].should be == '/bar' } + example { mapper['/fox'].should be == '/fox' } + end + + context 'accepts mappings followed by options' do + subject(:mapper) { Mustermann::Mapper.new({ "/foo" => "/bar" }, additional_values: :raise) } + its(:to_h) { should be == { Mustermann.new("/foo") => Mustermann::Expander.new("/bar") } } + example { mapper['/foo'].should be == '/bar' } + example { mapper['/fox'].should be == '/fox' } + end + + context 'allows specifying type' do + subject(:mapper) { Mustermann::Mapper.new({ "/foo" => "/bar" }, additional_values: :raise, type: :rails) } + its(:to_h) { should be == { Mustermann.new("/foo", type: :rails) => Mustermann::Expander.new("/bar", type: :rails) } } + example { mapper['/foo'].should be == '/bar' } + example { mapper['/fox'].should be == '/fox' } + end + end + + describe :convert do + subject(:mapper) { Mustermann::Mapper.new } + + context 'it maps params' do + before { mapper["/:a"] = "/:a.html" } + example { mapper["/foo"] .should be == "/foo.html" } + example { mapper["/foo/bar"] .should be == "/foo/bar" } + end + + context 'it supports named splats' do + before { mapper["/*a"] = "/*a.html" } + example { mapper["/foo"] .should be == "/foo.html" } + example { mapper["/foo/bar"] .should be == "/foo/bar.html" } + end + + context 'can map from patterns' do + before { mapper[Mustermann.new("/:a")] = "/:a.html" } + example { mapper["/foo"] .should be == "/foo.html" } + example { mapper["/foo/bar"] .should be == "/foo/bar" } + end + + context 'can map to patterns' do + before { mapper[Mustermann.new("/:a")] = Mustermann.new("/:a.html") } + example { mapper["/foo"] .should be == "/foo.html" } + example { mapper["/foo/bar"] .should be == "/foo/bar" } + end + + context 'can map to expanders' do + before { mapper[Mustermann.new("/:a")] = Mustermann::Expander.new("/:a.html") } + example { mapper["/foo"] .should be == "/foo.html" } + example { mapper["/foo/bar"] .should be == "/foo/bar" } + end + + context 'can map to array' do + before { mapper["/:a"] = ["/:a.html", "/:a.:f"] } + example { mapper["/foo"] .should be == "/foo.html" } + example { mapper["/foo", "f" => 'x'] .should be == "/foo.x" } + example { mapper["/foo", f: 'x'] .should be == "/foo.x" } + example { mapper["/foo/bar"] .should be == "/foo/bar" } + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/mustermann_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/mustermann_spec.rb new file mode 100644 index 0000000..804d063 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/mustermann_spec.rb @@ -0,0 +1,84 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann' +require 'mustermann/extension' +require 'sinatra/base' + +describe Mustermann do + describe :new do + context "string argument" do + example { Mustermann.new('') .should be_a(Mustermann::Sinatra) } + example { Mustermann.new('', type: :identity) .should be_a(Mustermann::Identity) } + example { Mustermann.new('', type: :rails) .should be_a(Mustermann::Rails) } + example { Mustermann.new('', type: :shell) .should be_a(Mustermann::Shell) } + example { Mustermann.new('', type: :sinatra) .should be_a(Mustermann::Sinatra) } + example { Mustermann.new('', type: :simple) .should be_a(Mustermann::Simple) } + example { Mustermann.new('', type: :template) .should be_a(Mustermann::Template) } + + example { expect { Mustermann.new('', foo: :bar) }.to raise_error(ArgumentError, "unsupported option :foo for Mustermann::Sinatra") } + example { expect { Mustermann.new('', type: :ast) }.to raise_error(ArgumentError, "unsupported type :ast (cannot load such file -- mustermann/ast)") } + end + + context "pattern argument" do + subject(:pattern) { Mustermann.new('') } + example { Mustermann.new(pattern).should be == pattern } + example { Mustermann.new(pattern, type: :rails).should be_a(Mustermann::Sinatra) } + end + + context "regexp argument" do + example { Mustermann.new(//) .should be_a(Mustermann::Regular) } + example { Mustermann.new(//, type: :rails) .should be_a(Mustermann::Regular) } + end + + context "argument implementing #to_pattern" do + subject(:pattern) { Class.new { def to_pattern(**o) Mustermann.new('foo', **o) end }.new } + example { Mustermann.new(pattern) .should be_a(Mustermann::Sinatra) } + example { Mustermann.new(pattern, type: :rails) .should be_a(Mustermann::Rails) } + example { Mustermann.new(pattern).to_s.should be == 'foo' } + end + + context "multiple arguments" do + example { Mustermann.new(':a', ':b/:a') .should be_a(Mustermann::Composite) } + example { Mustermann.new(':a', ':b/:a').patterns.first .should be_a(Mustermann::Sinatra) } + example { Mustermann.new(':a', ':b/:a').operator .should be == :| } + example { Mustermann.new(':a', ':b/:a', operator: :&).operator .should be == :& } + example { Mustermann.new(':a', ':b/:a', greedy: true) .should be_a(Mustermann::Composite) } + + example { Mustermann.new('/foo', ':bar') .should be_a(Mustermann::Sinatra) } + example { Mustermann.new('/foo', ':bar').to_s .should be == "/foo|{bar}" } + end + + context "invalid arguments" do + it "raise a TypeError for unsupported types" do + expect { Mustermann.new(10) }.to raise_error(TypeError, /(Integer|Fixnum) can't be coerced into Mustermann::Pattern/) + end + end + end + + describe :[] do + example { Mustermann[:identity] .should be == Mustermann::Identity } + example { Mustermann[:rails] .should be == Mustermann::Rails } + example { Mustermann[:shell] .should be == Mustermann::Shell } + example { Mustermann[:sinatra] .should be == Mustermann::Sinatra } + example { Mustermann[:simple] .should be == Mustermann::Simple } + example { Mustermann[:template] .should be == Mustermann::Template } + + example { expect { Mustermann[:ast] }.to raise_error(ArgumentError, "unsupported type :ast (cannot load such file -- mustermann/ast)") } + example { expect { Mustermann[:expander] }.to raise_error(ArgumentError, "unsupported type :expander") } + end + + describe :extend_object do + context 'special behavior for Sinatra only' do + example { Object .new.extend(Mustermann).should be_a(Mustermann) } + example { Object .new.extend(Mustermann).should_not be_a(Mustermann::Extension) } + example { Class .new.extend(Mustermann).should be_a(Mustermann) } + example { Class .new.extend(Mustermann).should_not be_a(Mustermann::Extension) } + example { Sinatra .new.extend(Mustermann).should_not be_a(Mustermann) } + example { Sinatra .new.extend(Mustermann).should be_a(Mustermann::Extension) } + end + end + + describe :=== do + example { Mustermann.should be === Mustermann.new("") } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/pattern_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/pattern_spec.rb new file mode 100644 index 0000000..8f8db33 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/pattern_spec.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann/pattern' +require 'mustermann/sinatra' +require 'mustermann/rails' + +describe Mustermann::Pattern do + describe :=== do + it 'raises a NotImplementedError when used directly' do + expect { Mustermann::Pattern.new("") === "" }.to raise_error(NotImplementedError) + end + end + + describe :initialize do + it 'raises an ArgumentError for unknown options' do + expect { Mustermann::Pattern.new("", foo: :bar) }.to raise_error(ArgumentError) + end + + it 'does not complain about unknown options if ignore_unknown_options is enabled' do + expect { Mustermann::Pattern.new("", foo: :bar, ignore_unknown_options: true) }.not_to raise_error + end + end + + describe :respond_to? do + subject(:pattern) { Mustermann::Pattern.new("") } + + it { should_not respond_to(:expand) } + it { should_not respond_to(:to_templates) } + + it { expect { pattern.expand } .to raise_error(NotImplementedError) } + it { expect { pattern.to_templates } .to raise_error(NotImplementedError) } + end + + describe :== do + example { Mustermann::Pattern.new('/foo') .should be == Mustermann::Pattern.new('/foo') } + example { Mustermann::Pattern.new('/foo') .should_not be == Mustermann::Pattern.new('/bar') } + example { Mustermann::Sinatra.new('/foo') .should be == Mustermann::Sinatra.new('/foo') } + example { Mustermann::Rails.new('/foo') .should_not be == Mustermann::Sinatra.new('/foo') } + end + + describe :eql? do + example { Mustermann::Pattern.new('/foo') .should be_eql Mustermann::Pattern.new('/foo') } + example { Mustermann::Pattern.new('/foo') .should_not be_eql Mustermann::Pattern.new('/bar') } + example { Mustermann::Sinatra.new('/foo') .should be_eql Mustermann::Sinatra.new('/foo') } + example { Mustermann::Rails.new('/foo') .should_not be_eql Mustermann::Sinatra.new('/foo') } + end + + describe :equal? do + example { Mustermann::Pattern.new('/foo') .should be_equal Mustermann::Pattern.new('/foo') } + example { Mustermann::Pattern.new('/foo') .should_not be_equal Mustermann::Pattern.new('/bar') } + example { Mustermann::Sinatra.new('/foo') .should be_equal Mustermann::Sinatra.new('/foo') } + example { Mustermann::Rails.new('/foo') .should_not be_equal Mustermann::Sinatra.new('/foo') } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/regexp_based_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/regexp_based_spec.rb new file mode 100644 index 0000000..bc25fd5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/regexp_based_spec.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann/regexp_based' + +describe Mustermann::RegexpBased do + it 'raises a NotImplementedError when used directly' do + expect { Mustermann::RegexpBased.new("") === "" }.to raise_error(NotImplementedError) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/regular_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/regular_spec.rb new file mode 100644 index 0000000..198a00b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/regular_spec.rb @@ -0,0 +1,119 @@ +# frozen_string_literal: true +require 'support' +require 'timeout' +require 'mustermann/regular' + +describe Mustermann::Regular do + extend Support::Pattern + + pattern '' do + it { should match('') } + it { should_not match('/') } + + it { should_not respond_to(:expand) } + it { should_not respond_to(:to_templates) } + end + + pattern '/' do + it { should match('/') } + it { should_not match('/foo') } + end + + pattern '/foo' do + it { should match('/foo') } + it { should_not match('/bar') } + it { should_not match('/foo.bar') } + end + + pattern '/foo/bar' do + it { should match('/foo/bar') } + it { should_not match('/foo%2Fbar') } + it { should_not match('/foo%2fbar') } + end + + pattern '/(?.*)' do + it { should match('/foo') .capturing foo: 'foo' } + it { should match('/bar') .capturing foo: 'bar' } + it { should match('/foo.bar') .capturing foo: 'foo.bar' } + it { should match('/%0Afoo') .capturing foo: '%0Afoo' } + it { should match('/foo%2Fbar') .capturing foo: 'foo%2Fbar' } + end + + + context 'with Regexp::EXTENDED' do + let(:pattern) { + %r{ + \/compare\/ # match any URL beginning with \/compare\/ + (.+) # extract the full path (including any directories) + \/ # match the final slash + ([^.]+) # match the first SHA1 + \.{2,3} # match .. or ... + (.+) # match the second SHA1 + }x + } + example { expect { Timeout.timeout(1){ Mustermann::Regular.new(pattern) }}.not_to raise_error } + it { expect(Mustermann::Regular.new(pattern)).to match('/compare/foo/bar..baz') } + end + + describe :check_achnors do + context 'raises on anchors' do + example { expect { Mustermann::Regular.new('^foo') }.to raise_error(Mustermann::CompileError) } + example { expect { Mustermann::Regular.new('foo$') }.to raise_error(Mustermann::CompileError) } + example { expect { Mustermann::Regular.new('\Afoo') }.to raise_error(Mustermann::CompileError) } + example { expect { Mustermann::Regular.new('foo\Z') }.to raise_error(Mustermann::CompileError) } + example { expect { Mustermann::Regular.new('foo\z') }.to raise_error(Mustermann::CompileError) } + example { expect { Mustermann::Regular.new(/^foo/) }.to raise_error(Mustermann::CompileError) } + example { expect { Mustermann::Regular.new(/foo$/) }.to raise_error(Mustermann::CompileError) } + example { expect { Mustermann::Regular.new(/\Afoo/) }.to raise_error(Mustermann::CompileError) } + example { expect { Mustermann::Regular.new(/foo\Z/) }.to raise_error(Mustermann::CompileError) } + example { expect { Mustermann::Regular.new(/foo\z/) }.to raise_error(Mustermann::CompileError) } + example { expect { Mustermann::Regular.new('[^f]') }.not_to raise_error } + example { expect { Mustermann::Regular.new('\\\A') }.not_to raise_error } + example { expect { Mustermann::Regular.new('[[:digit:]]') }.not_to raise_error } + example { expect { Mustermann::Regular.new(/[^f]/) }.not_to raise_error } + example { expect { Mustermann::Regular.new(/\\A/) }.not_to raise_error } + example { expect { Mustermann::Regular.new(/[[:digit:]]/) }.not_to raise_error } + end + + context 'with check_anchors disabled' do + example { expect { Mustermann::Regular.new('^foo', check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new('foo$', check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new('\Afoo', check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new('foo\Z', check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new('foo\z', check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new(/^foo/, check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new(/foo$/, check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new(/\Afoo/, check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new(/foo\Z/, check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new(/foo\z/, check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new('[^f]', check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new('\\\A', check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new('[[:digit:]]', check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new(/[^f]/, check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new(/\\A/, check_anchors: false) }.not_to raise_error } + example { expect { Mustermann::Regular.new(/[[:digit:]]/, check_anchors: false) }.not_to raise_error } + end + end + + context "peeking" do + subject(:pattern) { Mustermann::Regular.new("(?[^/]+)") } + + describe :peek_size do + example { pattern.peek_size("foo bar/blah") .should be == "foo bar".size } + example { pattern.peek_size("foo%20bar/blah") .should be == "foo%20bar".size } + example { pattern.peek_size("/foo bar") .should be_nil } + end + + describe :peek_match do + example { pattern.peek_match("foo bar/blah") .to_s .should be == "foo bar" } + example { pattern.peek_match("foo%20bar/blah") .to_s .should be == "foo%20bar" } + example { pattern.peek_match("/foo bar") .should be_nil } + end + + describe :peek_params do + example { pattern.peek_params("foo bar/blah") .should be == [{"name" => "foo bar"}, "foo bar".size] } + example { pattern.peek_params("foo%20bar/blah") .should be == [{"name" => "foo bar"}, "foo%20bar".size] } + example { pattern.peek_params("/foo bar") .should be_nil } + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/simple_match_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/simple_match_spec.rb new file mode 100644 index 0000000..21955b4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/simple_match_spec.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann/simple_match' + +describe Mustermann::SimpleMatch do + subject { Mustermann::SimpleMatch.new('example') } + its(:to_s) { should be == 'example' } + its(:names) { should be == [] } + its(:captures) { should be == [] } + example { subject[1].should be == nil } +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/sinatra_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/sinatra_spec.rb new file mode 100644 index 0000000..58139ba --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/sinatra_spec.rb @@ -0,0 +1,836 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann/sinatra' + +describe Mustermann::Sinatra do + extend Support::Pattern + + pattern '' do + it { should match('') } + it { should_not match('/') } + + it { should generate_template('') } + + it { should respond_to(:expand) } + it { should respond_to(:to_templates) } + end + + pattern '/' do + it { should match('/') } + it { should_not match('/foo') } + end + + pattern '/foo' do + it { should match('/foo') } + it { should_not match('/bar') } + it { should_not match('/foo.bar') } + end + + pattern '/foo/bar' do + it { should match('/foo/bar') } + it { should_not match('/foo%2Fbar') } + it { should_not match('/foo%2fbar') } + end + + pattern '/foo\/bar' do + it { should match('/foo/bar') } + it { should match('/foo%2Fbar') } + it { should match('/foo%2fbar') } + end + + pattern '/:foo' do + it { should match('/foo') .capturing foo: 'foo' } + it { should match('/bar') .capturing foo: 'bar' } + it { should match('/foo.bar') .capturing foo: 'foo.bar' } + it { should match('/%0Afoo') .capturing foo: '%0Afoo' } + it { should match('/foo%2Fbar') .capturing foo: 'foo%2Fbar' } + + it { should_not match('/foo?') } + it { should_not match('/foo/bar') } + it { should_not match('/') } + it { should_not match('/foo/') } + + it { should generate_template('/{foo}') } + end + + pattern '/föö' do + it { should match("/f%C3%B6%C3%B6") } + end + + pattern "/:foo/:bar" do + it { should match('/foo/bar') .capturing foo: 'foo', bar: 'bar' } + it { should match('/foo.bar/bar.foo') .capturing foo: 'foo.bar', bar: 'bar.foo' } + it { should match('/user@example.com/name') .capturing foo: 'user@example.com', bar: 'name' } + it { should match('/10.1/te.st') .capturing foo: '10.1', bar: 'te.st' } + it { should match('/10.1.2/te.st') .capturing foo: '10.1.2', bar: 'te.st' } + + it { should_not match('/foo%2Fbar') } + it { should_not match('/foo%2fbar') } + + example { pattern.params('/bar/foo').should be == {"foo" => "bar", "bar" => "foo"} } + example { pattern.params('').should be_nil } + + it { should generate_template('/{foo}/{bar}') } + end + + pattern "/{foo}/{bar}" do + it { should match('/foo/bar') .capturing foo: 'foo', bar: 'bar' } + it { should match('/foo.bar/bar.foo') .capturing foo: 'foo.bar', bar: 'bar.foo' } + it { should match('/user@example.com/name') .capturing foo: 'user@example.com', bar: 'name' } + it { should match('/10.1/te.st') .capturing foo: '10.1', bar: 'te.st' } + it { should match('/10.1.2/te.st') .capturing foo: '10.1.2', bar: 'te.st' } + + it { should_not match('/foo%2Fbar') } + it { should_not match('/foo%2fbar') } + + example { pattern.params('/bar/foo').should be == {"foo" => "bar", "bar" => "foo"} } + example { pattern.params('').should be_nil } + + it { should generate_template('/{foo}/{bar}') } + end + + pattern '/hello/:person' do + it { should match('/hello/Frank').capturing person: 'Frank' } + it { should generate_template('/hello/{person}') } + end + + pattern '/hello/{person}' do + it { should match('/hello/Frank').capturing person: 'Frank' } + it { should generate_template('/hello/{person}') } + end + + pattern '/?:foo?/?:bar?' do + it { should match('/hello/world') .capturing foo: 'hello', bar: 'world' } + it { should match('/hello') .capturing foo: 'hello', bar: nil } + it { should match('/') .capturing foo: nil, bar: nil } + it { should match('') .capturing foo: nil, bar: nil } + + it { should expand(foo: 'hello') .to('/hello/') } + it { should expand(foo: 'hello', bar: 'world') .to('/hello/world') } + it { should expand(bar: 'world') .to('//world') } + it { should expand .to('//') } + it { should_not expand(baz: '') } + + it { should_not match('/hello/world/') } + it { should generate_templates("", "/", "//", "//{bar}", "/{bar}", "/{foo}", "/{foo}/", "/{foo}/{bar}", "/{foo}{bar}", "{bar}", "{foo}", "{foo}/", "{foo}/{bar}", "{foo}{bar}") } + end + + pattern '/:foo_bar' do + it { should match('/hello').capturing foo_bar: 'hello' } + it { should generate_template('/{foo_bar}') } + end + + pattern '/{foo.bar}' do + it { should match('/hello').capturing :"foo.bar" => 'hello' } + it { should generate_template('/{foo.bar}') } + end + + pattern '/*' do + it { should match('/') .capturing splat: '' } + it { should match('/foo') .capturing splat: 'foo' } + it { should match('/foo/bar') .capturing splat: 'foo/bar' } + it { should generate_template('/{+splat}') } + + example { pattern.params('/foo').should be == {"splat" => ["foo"]} } + end + + pattern '/{+splat}' do + it { should match('/') .capturing splat: '' } + it { should match('/foo') .capturing splat: 'foo' } + it { should match('/foo/bar') .capturing splat: 'foo/bar' } + it { should generate_template('/{+splat}') } + + example { pattern.params('/foo').should be == {"splat" => ["foo"]} } + end + + pattern '/*foo' do + it { should match('/') .capturing foo: '' } + it { should match('/foo') .capturing foo: 'foo' } + it { should match('/foo/bar') .capturing foo: 'foo/bar' } + it { should generate_template('/{+foo}') } + + example { pattern.params('/foo') .should be == {"foo" => "foo" } } + example { pattern.params('/foo/bar') .should be == {"foo" => "foo/bar" } } + end + + pattern '/{+foo}' do + it { should match('/') .capturing foo: '' } + it { should match('/foo') .capturing foo: 'foo' } + it { should match('/foo/bar') .capturing foo: 'foo/bar' } + it { should generate_template('/{+foo}') } + + example { pattern.params('/foo') .should be == {"foo" => "foo" } } + example { pattern.params('/foo/bar') .should be == {"foo" => "foo/bar" } } + end + + pattern '/*foo/*bar' do + it { should match('/foo/bar') .capturing foo: 'foo', bar: 'bar' } + it { should generate_template('/{+foo}/{+bar}') } + end + + pattern '/{+foo}/{+bar}' do + it { should match('/foo/bar') .capturing foo: 'foo', bar: 'bar' } + it { should generate_template('/{+foo}/{+bar}') } + end + + pattern '/:foo/*' do + it { should match("/foo/bar/baz") .capturing foo: 'foo', splat: 'bar/baz' } + it { should match("/foo/") .capturing foo: 'foo', splat: '' } + it { should match('/h%20w/h%20a%20y') .capturing foo: 'h%20w', splat: 'h%20a%20y' } + it { should_not match('/foo') } + it { should generate_template('/{foo}/{+splat}') } + + example { pattern.params('/bar/foo').should be == {"splat" => ["foo"], "foo" => "bar"} } + example { pattern.params('/bar/foo/f%20o').should be == {"splat" => ["foo/f o"], "foo" => "bar"} } + end + + pattern '/{foo}/*' do + it { should match("/foo/bar/baz") .capturing foo: 'foo', splat: 'bar/baz' } + it { should match("/foo/") .capturing foo: 'foo', splat: '' } + it { should match('/h%20w/h%20a%20y') .capturing foo: 'h%20w', splat: 'h%20a%20y' } + it { should_not match('/foo') } + it { should generate_template('/{foo}/{+splat}') } + + example { pattern.params('/bar/foo').should be == {"splat" => ["foo"], "foo" => "bar"} } + example { pattern.params('/bar/foo/f%20o').should be == {"splat" => ["foo/f o"], "foo" => "bar"} } + end + + pattern '/test$/' do + it { should match('/test$/') } + end + + pattern '/te+st/' do + it { should match('/te+st/') } + it { should_not match('/test/') } + it { should_not match('/teest/') } + end + + pattern "/path with spaces" do + it { should match('/path%20with%20spaces') } + it { should match('/path%2Bwith%2Bspaces') } + it { should match('/path+with+spaces') } + + it { should generate_template('/path%20with%20spaces') } + end + + pattern '/foo&bar' do + it { should match('/foo&bar') } + end + + pattern '/foo\{bar' do + it { should match('/foo%7Bbar') } + end + + pattern '/*/:foo/*/*' do + it { should match('/bar/foo/bling/baz/boom') } + + it "should capture all splat parts" do + match = pattern.match('/bar/foo/bling/baz/boom') + match.captures.should be == ['bar', 'foo', 'bling', 'baz/boom'] + match.names.should be == ['splat', 'foo'] + end + + it 'should map to proper params' do + pattern.params('/bar/foo/bling/baz/boom').should be == { + "foo" => "foo", "splat" => ['bar', 'bling', 'baz/boom'] + } + end + end + + pattern '/{+splat}/{foo}/{+splat}/{+splat}' do + it { should match('/bar/foo/bling/baz/boom') } + + it "should capture all splat parts" do + match = pattern.match('/bar/foo/bling/baz/boom') + match.captures.should be == ['bar', 'foo', 'bling', 'baz/boom'] + match.names.should be == ['splat', 'foo'] + end + + it 'should map to proper params' do + pattern.params('/bar/foo/bling/baz/boom').should be == { + "foo" => "foo", "splat" => ['bar', 'bling', 'baz/boom'] + } + end + end + + pattern '/test.bar' do + it { should match('/test.bar') } + it { should_not match('/test0bar') } + end + + pattern '/:file.:ext' do + it { should match('/pony.jpg') .capturing file: 'pony', ext: 'jpg' } + it { should match('/pony%2Ejpg') .capturing file: 'pony', ext: 'jpg' } + it { should match('/pony%2ejpg') .capturing file: 'pony', ext: 'jpg' } + + it { should match('/pony%E6%AD%A3%2Ejpg') .capturing file: 'pony%E6%AD%A3', ext: 'jpg' } + it { should match('/pony%e6%ad%a3%2ejpg') .capturing file: 'pony%e6%ad%a3', ext: 'jpg' } + it { should match('/pony正%2Ejpg') .capturing file: 'pony正', ext: 'jpg' } + it { should match('/pony正%2ejpg') .capturing file: 'pony正', ext: 'jpg' } + it { should match('/pony正..jpg') .capturing file: 'pony正.', ext: 'jpg' } + + it { should_not match('/.jpg') } + end + + pattern '/(:a)x?' do + it { should match('/a') .capturing a: 'a' } + it { should match('/xa') .capturing a: 'xa' } + it { should match('/axa') .capturing a: 'axa' } + it { should match('/ax') .capturing a: 'a' } + it { should match('/axax') .capturing a: 'axa' } + it { should match('/axaxx') .capturing a: 'axax' } + + it { should generate_template('/{a}x') } + it { should generate_template('/{a}') } + end + + pattern '/:user(@:host)?' do + it { should match('/foo@bar') .capturing user: 'foo', host: 'bar' } + it { should match('/foo.foo@bar') .capturing user: 'foo.foo', host: 'bar' } + it { should match('/foo@bar.bar') .capturing user: 'foo', host: 'bar.bar' } + + it { should generate_template('/{user}') } + it { should generate_template('/{user}@{host}') } + end + + pattern '/:file(.:ext)?' do + it { should match('/pony') .capturing file: 'pony', ext: nil } + it { should match('/pony.jpg') .capturing file: 'pony', ext: 'jpg' } + it { should match('/pony%2Ejpg') .capturing file: 'pony', ext: 'jpg' } + it { should match('/pony%2ejpg') .capturing file: 'pony', ext: 'jpg' } + it { should match('/pony.png.jpg') .capturing file: 'pony.png', ext: 'jpg' } + it { should match('/pony.') .capturing file: 'pony.' } + it { should_not match('/.jpg') } + + it { should generate_template('/{file}') } + it { should generate_template('/{file}.{ext}') } + it { should_not generate_template('/{file}.') } + end + + pattern '/:id/test.bar' do + it { should match('/3/test.bar') .capturing id: '3' } + it { should match('/2/test.bar') .capturing id: '2' } + it { should match('/2E/test.bar') .capturing id: '2E' } + it { should match('/2e/test.bar') .capturing id: '2e' } + it { should match('/%2E/test.bar') .capturing id: '%2E' } + end + + pattern '/10/:id' do + it { should match('/10/test') .capturing id: 'test' } + it { should match('/10/te.st') .capturing id: 'te.st' } + end + + pattern '/10.1/:id' do + it { should match('/10.1/test') .capturing id: 'test' } + it { should match('/10.1/te.st') .capturing id: 'te.st' } + end + + pattern '/:foo.:bar/:id' do + it { should match('/10.1/te.st') .capturing foo: "10", bar: "1", id: "te.st" } + it { should match('/10.1.2/te.st') .capturing foo: "10.1", bar: "2", id: "te.st" } + end + + pattern '/:a/:b.?:c?' do + it { should match('/a/b') .capturing a: 'a', b: 'b', c: nil } + it { should match('/a/b.c') .capturing a: 'a', b: 'b', c: 'c' } + it { should match('/a.b/c') .capturing a: 'a.b', b: 'c', c: nil } + it { should match('/a.b/c.d') .capturing a: 'a.b', b: 'c', c: 'd' } + it { should_not match('/a.b/c.d/e') } + end + + pattern '/:a(foo:b)?' do + it { should match('/barfoobar') .capturing a: 'bar', b: 'bar' } + it { should match('/barfoobarfoobar') .capturing a: 'barfoobar', b: 'bar' } + it { should match('/bar') .capturing a: 'bar', b: nil } + it { should_not match('/') } + end + + pattern '/foo?' do + it { should match('/fo') } + it { should match('/foo') } + it { should_not match('') } + it { should_not match('/') } + it { should_not match('/f') } + it { should_not match('/fooo') } + end + + pattern '/foo\?' do + it { should match('/foo?') } + it { should_not match('/foo\?') } + it { should_not match('/fo') } + it { should_not match('/foo') } + it { should_not match('') } + it { should_not match('/') } + it { should_not match('/f') } + it { should_not match('/fooo') } + end + + pattern '/foo\\\?' do + it { should match('/foo%5c') } + it { should match('/foo') } + it { should_not match('/foo\?') } + it { should_not match('/fo') } + it { should_not match('') } + it { should_not match('/') } + it { should_not match('/f') } + it { should_not match('/fooo') } + end + + pattern '/\(' do + it { should match('/(') } + end + + pattern '/\(?' do + it { should match('/(') } + it { should match('/') } + end + + pattern '/(\()?' do + it { should match('/(') } + it { should match('/') } + end + + pattern '/(\(\))?' do + it { should match('/') } + it { should match('/()') } + it { should_not match('/(') } + end + + pattern '/\(\)?' do + it { should match('/(') } + it { should match('/()') } + it { should_not match('/') } + end + + pattern '/\*' do + it { should match('/*') } + it { should_not match('/a') } + end + + pattern '/\*/*' do + it { should match('/*/b/c') } + it { should_not match('/a/b/c') } + end + + pattern '/\:foo' do + it { should match('/:foo') } + it { should_not match('/foo') } + end + + pattern '/:fOO' do + it { should match('/a').capturing fOO: 'a' } + end + + pattern '/:_X' do + it { should match('/a').capturing _X: 'a' } + end + + pattern '/:f00' do + it { should match('/a').capturing f00: 'a' } + end + + pattern '/:foo(/:bar)?/:baz?' do + it { should match('/foo/bar/baz').capturing foo: 'foo', bar: 'bar', baz: 'baz' } + end + + pattern "/(foo|bar)" do + it { should match("/foo") } + it { should match("/bar") } + + it { should generate_template('/foo') } + it { should generate_template('/bar') } + end + + pattern "/(foo\\|bar)" do + it { should match "/foo%7Cbar" } + it { should generate_template "/foo%7Cbar" } + + it { should_not match("/foo") } + it { should_not match("/bar") } + + it { should_not generate_template('/foo') } + it { should_not generate_template('/bar') } + end + + pattern "/(:a/:b|:c)" do + it { should match("/foo") .capturing c: 'foo' } + it { should match("/foo/bar") .capturing a: 'foo', b: 'bar' } + + it { should generate_template('/{a}/{b}') } + it { should generate_template('/{c}') } + + it { should expand(a: 'foo', b: 'bar') .to('/foo/bar') } + it { should expand(c: 'foo') .to('/foo') } + it { should_not expand(a: 'foo', b: 'bar', c: 'baz') } + end + + pattern "/:a/:b|:c" do + it { should match("foo") .capturing c: 'foo' } + it { should match("/foo/bar") .capturing a: 'foo', b: 'bar' } + + it { should generate_template('/{a}/{b}') } + it { should generate_template('{c}') } + + it { should expand(a: 'foo', b: 'bar') .to('/foo/bar') } + it { should expand(c: 'foo') .to('foo') } + it { should_not expand(a: 'foo', b: 'bar', c: 'baz') } + end + + pattern "/({foo}|{bar})", capture: { foo: /\d+/, bar: /\w+/ } do + it { should match("/a") .capturing foo: nil, bar: 'a' } + it { should match("/1234") .capturing foo: "1234", bar: nil } + + it { should_not match("/a/b") } + end + + pattern "/{foo|bar}", capture: { foo: /\d+/, bar: /\w+/ } do + it { should match("/a") .capturing foo: nil, bar: 'a' } + it { should match("/1234") .capturing foo: "1234", bar: nil } + + it { should_not match("/a/b") } + end + + pattern "/{foo|bar|baz}", capture: { foo: /\d+/, bar: /[ab]+/, baz: /[cde]+/ } do + it { should match("/ab") .capturing foo: nil, bar: 'ab', baz: nil } + it { should match("/1234") .capturing foo: "1234", bar: nil, baz: nil } + it { should match("/ccddee") .capturing foo: nil, bar: nil, baz: "ccddee" } + + it { should_not match("/a/b") } + end + + pattern '/:foo', capture: /\d+/ do + it { should match('/1') .capturing foo: '1' } + it { should match('/123') .capturing foo: '123' } + + it { should_not match('/') } + it { should_not match('/foo') } + end + + pattern '/:foo', capture: /\d+/ do + it { should match('/1') .capturing foo: '1' } + it { should match('/123') .capturing foo: '123' } + + it { should_not match('/') } + it { should_not match('/foo') } + end + + pattern '/:foo', capture: '1' do + it { should match('/1').capturing foo: '1' } + + it { should_not match('/') } + it { should_not match('/foo') } + it { should_not match('/123') } + end + + pattern '/:foo', capture: 'a.b' do + it { should match('/a.b') .capturing foo: 'a.b' } + it { should match('/a%2Eb') .capturing foo: 'a%2Eb' } + it { should match('/a%2eb') .capturing foo: 'a%2eb' } + + it { should_not match('/ab') } + it { should_not match('/afb') } + it { should_not match('/a1b') } + it { should_not match('/a.bc') } + end + + pattern '/:foo(/:bar)?', capture: :alpha do + it { should match('/abc') .capturing foo: 'abc', bar: nil } + it { should match('/a/b') .capturing foo: 'a', bar: 'b' } + it { should match('/a') .capturing foo: 'a', bar: nil } + + it { should_not match('/1/2') } + it { should_not match('/a/2') } + it { should_not match('/1/b') } + it { should_not match('/1') } + it { should_not match('/1/') } + it { should_not match('/a/') } + it { should_not match('//a') } + end + + pattern '/:foo', capture: ['foo', 'bar', /\d+/] do + it { should match('/1') .capturing foo: '1' } + it { should match('/123') .capturing foo: '123' } + it { should match('/foo') .capturing foo: 'foo' } + it { should match('/bar') .capturing foo: 'bar' } + + it { should_not match('/') } + it { should_not match('/baz') } + it { should_not match('/foo1') } + end + + pattern '/:foo:bar:baz', capture: { foo: :alpha, bar: /\d+/ } do + it { should match('/ab123xy-1') .capturing foo: 'ab', bar: '123', baz: 'xy-1' } + it { should match('/ab123') .capturing foo: 'ab', bar: '12', baz: '3' } + it { should_not match('/123abcxy-1') } + it { should_not match('/abcxy-1') } + it { should_not match('/abc1') } + end + + pattern '/:foo', capture: { foo: ['foo', 'bar', /\d+/] } do + it { should match('/1') .capturing foo: '1' } + it { should match('/123') .capturing foo: '123' } + it { should match('/foo') .capturing foo: 'foo' } + it { should match('/bar') .capturing foo: 'bar' } + + it { should_not match('/') } + it { should_not match('/baz') } + it { should_not match('/foo1') } + end + + pattern '/:file(.:ext)?', capture: { ext: ['jpg', 'png'] } do + it { should match('/pony') .capturing file: 'pony', ext: nil } + it { should match('/pony.jpg') .capturing file: 'pony', ext: 'jpg' } + it { should match('/pony%2Ejpg') .capturing file: 'pony', ext: 'jpg' } + it { should match('/pony%2ejpg') .capturing file: 'pony', ext: 'jpg' } + it { should match('/pony.png') .capturing file: 'pony', ext: 'png' } + it { should match('/pony%2Epng') .capturing file: 'pony', ext: 'png' } + it { should match('/pony%2epng') .capturing file: 'pony', ext: 'png' } + it { should match('/pony.png.jpg') .capturing file: 'pony.png', ext: 'jpg' } + it { should match('/pony.jpg.png') .capturing file: 'pony.jpg', ext: 'png' } + it { should match('/pony.gif') .capturing file: 'pony.gif', ext: nil } + it { should match('/pony.') .capturing file: 'pony.', ext: nil } + it { should_not match('.jpg') } + end + + pattern '/:file:ext?', capture: { ext: ['.jpg', '.png', '.tar.gz'] } do + it { should match('/pony') .capturing file: 'pony', ext: nil } + it { should match('/pony.jpg') .capturing file: 'pony', ext: '.jpg' } + it { should match('/pony.png') .capturing file: 'pony', ext: '.png' } + it { should match('/pony.png.jpg') .capturing file: 'pony.png', ext: '.jpg' } + it { should match('/pony.jpg.png') .capturing file: 'pony.jpg', ext: '.png' } + it { should match('/pony.tar.gz') .capturing file: 'pony', ext: '.tar.gz' } + it { should match('/pony.gif') .capturing file: 'pony.gif', ext: nil } + it { should match('/pony.') .capturing file: 'pony.', ext: nil } + it { should_not match('/.jpg') } + end + + pattern '/:a(@:b)?', capture: { b: /\d+/ } do + it { should match('/a') .capturing a: 'a', b: nil } + it { should match('/a@1') .capturing a: 'a', b: '1' } + it { should match('/a@b') .capturing a: 'a@b', b: nil } + it { should match('/a@1@2') .capturing a: 'a@1', b: '2' } + end + + pattern '/(:a)b?', greedy: false do + it { should match('/ab').capturing a: 'a' } + end + + pattern '/:file(.:ext)?', greedy: false do + it { should match('/pony') .capturing file: 'pony', ext: nil } + it { should match('/pony.jpg') .capturing file: 'pony', ext: 'jpg' } + it { should match('/pony.png.jpg') .capturing file: 'pony', ext: 'png.jpg' } + end + + pattern '/auth/*', except: '/auth/login' do + it { should match('/auth/admin') } + it { should match('/auth/foobar') } + it { should_not match('/auth/login') } + end + + pattern '/:foo/:bar', except: '/:bar/20' do + it { should match('/foo/bar').capturing foo: 'foo', bar: 'bar' } + it { should_not match('/20/20') } + end + + pattern '/foo?', uri_decode: false do + it { should match('/foo') } + it { should match('/fo') } + it { should_not match('/foo?') } + end + + pattern '/foo/bar', uri_decode: false do + it { should match('/foo/bar') } + it { should_not match('/foo%2Fbar') } + it { should_not match('/foo%2fbar') } + end + + pattern "/path with spaces", uri_decode: false do + it { should match('/path with spaces') } + it { should_not match('/path%20with%20spaces') } + it { should_not match('/path%2Bwith%2Bspaces') } + it { should_not match('/path+with+spaces') } + end + + pattern "/path with spaces", space_matches_plus: false do + it { should match('/path%20with%20spaces') } + it { should_not match('/path%2Bwith%2Bspaces') } + it { should_not match('/path+with+spaces') } + end + + context 'invalid syntax' do + example 'unexpected closing parenthesis' do + expect { Mustermann::Sinatra.new('foo)bar') }. + to raise_error(Mustermann::ParseError, 'unexpected ) while parsing "foo)bar"') + end + + example 'missing closing parenthesis' do + expect { Mustermann::Sinatra.new('foo(bar') }. + to raise_error(Mustermann::ParseError, 'unexpected end of string while parsing "foo(bar"') + end + + example 'missing unescaped closing parenthesis' do + expect { Mustermann::Sinatra.new('foo(bar\)') }. + to raise_error(Mustermann::ParseError, 'unexpected end of string while parsing "foo(bar\\\\)"') + end + + example '? at beginning of route' do + expect { Mustermann::Sinatra.new('?foobar') }. + to raise_error(Mustermann::ParseError, 'unexpected ? while parsing "?foobar"') + end + + example 'double ?' do + expect { Mustermann::Sinatra.new('foo??bar') }. + to raise_error(Mustermann::ParseError, 'unexpected ? while parsing "foo??bar"') + end + + example 'dangling escape' do + expect { Mustermann::Sinatra.new('foo\\') }. + to raise_error(Mustermann::ParseError, 'unexpected end of string while parsing "foo\\\\"') + end + end + + context 'invalid capture names' do + example 'empty name' do + expect { Mustermann::Sinatra.new('/:/') }. + to raise_error(Mustermann::CompileError, "capture name can't be empty: \"/:/\"") + end + + example 'named splat' do + expect { Mustermann::Sinatra.new('/:splat/') }. + to raise_error(Mustermann::CompileError, "capture name can't be splat: \"/:splat/\"") + end + + example 'named captures' do + expect { Mustermann::Sinatra.new('/:captures/') }. + to raise_error(Mustermann::CompileError, "capture name can't be captures: \"/:captures/\"") + end + + example 'with capital letter' do + expect { Mustermann::Sinatra.new('/:Foo/') }. + to raise_error(Mustermann::CompileError, "capture name must start with underscore or lower case letter: \"/:Foo/\"") + end + + example 'with integer' do + expect { Mustermann::Sinatra.new('/:1a/') }. + to raise_error(Mustermann::CompileError, "capture name must start with underscore or lower case letter: \"/:1a/\"") + end + + example 'same name twice' do + expect { Mustermann::Sinatra.new('/:foo(/:bar)?/:bar?') }. + to raise_error(Mustermann::CompileError, "can't use the same capture name twice: \"/:foo(/:bar)?/:bar?\"") + end + end + + context 'Regexp compatibility' do + describe :=== do + example('non-matching') { Mustermann::Sinatra.new("/") .should_not be === '/foo' } + example('matching') { Mustermann::Sinatra.new("/:foo") .should be === '/foo' } + end + + describe :=~ do + example('non-matching') { Mustermann::Sinatra.new("/") .should_not be =~ '/foo' } + example('matching') { Mustermann::Sinatra.new("/:foo") .should be =~ '/foo' } + + context 'String#=~' do + example('non-matching') { "/foo".should_not be =~ Mustermann::Sinatra.new("/") } + example('matching') { "/foo".should be =~ Mustermann::Sinatra.new("/:foo") } + end + end + + describe :to_regexp do + example('empty pattern') { Mustermann::Sinatra.new('').to_regexp.should be == /\A(?-mix:)\Z/ } + + context 'Regexp.try_convert' do + example('empty pattern') { Regexp.try_convert(Mustermann::Sinatra.new('')).should be == /\A(?-mix:)\Z/ } + end + end + end + + context 'Proc compatibility' do + describe :to_proc do + example { Mustermann::Sinatra.new("/").to_proc.should be_a(Proc) } + example('non-matching') { Mustermann::Sinatra.new("/") .to_proc.call('/foo').should be == false } + example('matching') { Mustermann::Sinatra.new("/:foo") .to_proc.call('/foo').should be == true } + end + end + + context "peeking" do + subject(:pattern) { Mustermann::Sinatra.new(":name") } + + describe :peek_size do + example { pattern.peek_size("foo bar/blah") .should be == "foo bar".size } + example { pattern.peek_size("foo%20bar/blah") .should be == "foo%20bar".size } + example { pattern.peek_size("/foo bar") .should be_nil } + end + + describe :peek_match do + example { pattern.peek_match("foo bar/blah") .to_s .should be == "foo bar" } + example { pattern.peek_match("foo%20bar/blah") .to_s .should be == "foo%20bar" } + example { pattern.peek_match("/foo bar") .should be_nil } + end + + describe :peek_params do + example { pattern.peek_params("foo bar/blah") .should be == [{"name" => "foo bar"}, "foo bar".size] } + example { pattern.peek_params("foo%20bar/blah") .should be == [{"name" => "foo bar"}, "foo%20bar".size] } + example { pattern.peek_params("/foo bar") .should be_nil } + end + end + + describe :| do + let(:first) { Mustermann.new("a") } + let(:second) { Mustermann.new("b") } + subject(:composite) { first | second } + + context "with no capture names" do + its(:class) { should be == Mustermann::Sinatra } + its(:to_s) { should be == "a|b" } + end + + context "only first has captures" do + let(:first) { Mustermann.new(":a") } + its(:class) { should be == Mustermann::Sinatra } + its(:to_s) { should be == "{a}|b" } + end + + context "only second has captures" do + let(:second) { Mustermann.new(":b") } + its(:class) { should be == Mustermann::Sinatra } + its(:to_s) { should be == "a|{b}" } + end + + context "both have captures" do + let(:first) { Mustermann.new(":a") } + let(:second) { Mustermann.new(":b") } + its(:class) { should be == Mustermann::Composite } + end + + context "options mismatch" do + let(:second) { Mustermann.new(":b", greedy: false) } + its(:class) { should be == Mustermann::Composite } + end + + context "argument is a string" do + let(:second) { ":b" } + its(:class) { should be == Mustermann::Sinatra } + its(:to_s) { should be == "a|\\:b" } + end + + context "argument is an identity pattern" do + let(:second) { Mustermann::Identity.new(":b") } + its(:class) { should be == Mustermann::Sinatra } + its(:to_s) { should be == "a|\\:b" } + end + + context "argument is an identity pattern, but options mismatch" do + let(:second) { Mustermann::Identity.new(":b", uri_decode: false) } + its(:class) { should be == Mustermann::Composite } + end + end + + describe "native concatination" do + subject { Mustermann.new(prefix) + Mustermann.new(pattern) } + let(:prefix) { "/a" } + let(:pattern) { "/:b(.:c)?" } + it { should match("/a/b.json") } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/to_pattern_spec.rb b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/to_pattern_spec.rb new file mode 100644 index 0000000..0668f19 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/mustermann-1.1.1/spec/to_pattern_spec.rb @@ -0,0 +1,70 @@ +# frozen_string_literal: true +require 'support' +require 'mustermann/to_pattern' +require 'delegate' + +describe Mustermann::ToPattern do + context String do + example { "".to_pattern .should be_a(Mustermann::Sinatra) } + example { "".to_pattern(type: :rails) .should be_a(Mustermann::Rails) } + end + + context Regexp do + example { //.to_pattern .should be_a(Mustermann::Regular) } + example { //.to_pattern(type: :rails) .should be_a(Mustermann::Regular) } + end + + context Symbol do + example { :foo.to_pattern .should be_a(Mustermann::Sinatra) } + example { :foo.to_pattern(type: :rails) .should be_a(Mustermann::Sinatra) } + end + + context Array do + example { [:foo, :bar].to_pattern .should be_a(Mustermann::Composite) } + example { [:foo, :bar].to_pattern(type: :rails) .should be_a(Mustermann::Composite) } + end + + context Mustermann::Pattern do + subject(:pattern) { Mustermann.new('') } + example { pattern.to_pattern.should be == pattern } + example { pattern.to_pattern(type: :rails).should be_a(Mustermann::Sinatra) } + end + + context 'custom class' do + let(:example_class) do + Class.new do + include Mustermann::ToPattern + def to_s + ":foo/:bar" + end + end + end + + example { example_class.new.to_pattern .should be_a(Mustermann::Sinatra) } + example { example_class.new.to_pattern(type: :rails) .should be_a(Mustermann::Rails) } + example { Mustermann.new(example_class.new) .should be_a(Mustermann::Sinatra) } + example { Mustermann.new(example_class.new, type: :rails) .should be_a(Mustermann::Rails) } + end + + context 'primitive delegate' do + let(:example_class) do + Class.new(DelegateClass(Array)) do + include Mustermann::ToPattern + end + end + + example { example_class.new([:foo, :bar]).to_pattern .should be_a(Mustermann::Composite) } + example { example_class.new([:foo, :bar]).to_pattern(type: :rails) .should be_a(Mustermann::Composite) } + end + + context 'primitive subclass' do + let(:example_class) do + Class.new(Array) do + include Mustermann::ToPattern + end + end + + example { example_class.new([:foo, :bar]).to_pattern .should be_a(Mustermann::Composite) } + example { example_class.new([:foo, :bar]).to_pattern(type: :rails) .should be_a(Mustermann::Composite) } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/.gitignore b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/.gitignore new file mode 100644 index 0000000..5fdfdf3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/.gitignore @@ -0,0 +1,16 @@ +*.swp +*.bundle +*.so +*.jar +*.class +.mvn +/.bundle/ +/.yardoc +/Gemfile.lock +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ +/vendor diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/Gemfile b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/Gemfile new file mode 100644 index 0000000..1835a5b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/Gemfile @@ -0,0 +1,9 @@ +source 'https://rubygems.org' + +gemspec + +group :development do + gem 'rake-compiler', ">= 0.4.1" + gem 'test-unit' + gem 'ruby-maven', :platforms => :jruby +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/LICENSE b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/LICENSE new file mode 100644 index 0000000..7609df5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2009 Aaron Patterson, et al. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/Mavenfile b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/Mavenfile new file mode 100644 index 0000000..b6d2dd0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/Mavenfile @@ -0,0 +1,7 @@ +#-*- mode: ruby -*- + +jar 'org.yaml:snakeyaml:${snakeyaml.version}' + +plugin :dependency, '2.8', :outputFile => 'pkg/classpath' + +# vim: syntax=Ruby diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/README.md b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/README.md new file mode 100644 index 0000000..405e955 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/README.md @@ -0,0 +1,72 @@ +# Psych + +* https://github.com/ruby/psych + +## Description + +Psych is a YAML parser and emitter. Psych leverages +[libyaml](https://pyyaml.org/wiki/LibYAML) for its YAML parsing and emitting +capabilities. In addition to wrapping libyaml, Psych also knows how to +serialize and de-serialize most Ruby objects to and from the YAML format. + +## Examples + +```ruby +# Safely load YAML in to a Ruby object +Psych.safe_load('--- foo') # => 'foo' + +# Emit YAML from a Ruby object +Psych.dump("foo") # => "--- foo\n...\n" +``` + +## Dependencies + +* libyaml + +## Installation + +Psych has been included with MRI since 1.9.2, and is the default YAML parser +in 1.9.3. + +If you want a newer gem release of Psych, you can use rubygems: + + gem install psych + +In order to use the gem release in your app, and not the stdlib version, +you'll need the following: + + gem 'psych' + require 'psych' + +Or if you use Bundler add this to your `Gemfile`: + + gem 'psych' + +JRuby ships with a pure Java implementation of Psych. + +If you're on Rubinius, Psych is available in 1.9 mode, please refer to the +Language Modes section of the [Rubinius +README](https://github.com/rubinius/rubinius#readme) for more information on +building and 1.9 mode. + +## License + +Copyright 2009 Aaron Patterson, et al. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the 'Software'), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/Rakefile b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/Rakefile new file mode 100644 index 0000000..55551b8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/Rakefile @@ -0,0 +1,41 @@ +require "bundler" +Bundler::GemHelper.install_tasks + +require "rake/testtask" +Rake::TestTask.new(:test) do |t| + t.libs << "test/lib" << "test" + t.ruby_opts << "-rhelper" + t.test_files = FileList['test/**/test_*.rb'] + t.verbose = true + t.warning = true +end + +if RUBY_PLATFORM =~ /java/ + require 'rake/javaextensiontask' + Rake::JavaExtensionTask.new("psych") do |ext| + require 'maven/ruby/maven' + # force load of versions to overwrite constants with values from repo. + load './lib/psych/versions.rb' + # uses Mavenfile to write classpath into pkg/classpath + # and tell maven via system properties the snakeyaml version + # this is basically the same as running from the commandline: + # rmvn dependency:build-classpath -Dsnakeyaml.version='use version from Psych::DEFAULT_SNAKEYAML_VERSION here' + Maven::Ruby::Maven.new.exec('dependency:build-classpath', "-Dsnakeyaml.version=#{Psych::DEFAULT_SNAKEYAML_VERSION}", '-Dverbose=true') + ext.source_version = '1.7' + ext.target_version = '1.7' + ext.classpath = File.read('pkg/classpath') + ext.ext_dir = 'ext/java' + end +else + require 'rake/extensiontask' + Rake::ExtensionTask.new("psych") +end + +task :sync_tool do + require 'fileutils' + FileUtils.cp "../ruby/tool/lib/core_assertions.rb", "./test/lib" + FileUtils.cp "../ruby/tool/lib/envutil.rb", "./test/lib" + FileUtils.cp "../ruby/tool/lib/find_executable.rb", "./test/lib" +end + +task :default => [:compile, :test] diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/bin/console b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/bin/console new file mode 100755 index 0000000..86c5a21 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/bin/console @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby + +require "bundler/setup" +require "psych" + +require "irb" +IRB.start diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/bin/setup b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/bin/setup new file mode 100755 index 0000000..cf4ad25 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/bin/setup @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/.sitearchdir.time b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/.sitearchdir.time new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/Makefile b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/Makefile new file mode 100644 index 0000000..3ab09d1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/Makefile @@ -0,0 +1,273 @@ + +SHELL = /bin/sh + +# V=0 quiet, V=1 verbose. other values don't work. +V = 0 +Q1 = $(V:1=) +Q = $(Q1:0=@) +ECHO1 = $(V:1=@ :) +ECHO = $(ECHO1:0=@ echo) +NULLCMD = : + +#### Start of system configuration section. #### + +srcdir = . +topdir = /usr/include/ruby-3.0.0 +hdrdir = $(topdir) +arch_hdrdir = /usr/include/ruby-3.0.0/x86_64-linux +PATH_SEPARATOR = : +VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby +prefix = $(DESTDIR)/usr +rubysitearchprefix = $(rubylibprefix)/$(sitearch) +rubyarchprefix = $(rubylibprefix)/$(arch) +rubylibprefix = $(libdir)/$(RUBY_BASE_NAME) +exec_prefix = $(prefix) +vendorarchhdrdir = $(vendorhdrdir)/$(sitearch) +sitearchhdrdir = $(sitehdrdir)/$(sitearch) +rubyarchhdrdir = $(rubyhdrdir)/$(arch) +vendorhdrdir = $(rubyhdrdir)/vendor_ruby +sitehdrdir = $(rubyhdrdir)/site_ruby +rubyhdrdir = $(includedir)/$(RUBY_VERSION_NAME) +vendorarchdir = $(vendorlibdir)/$(sitearch) +vendorlibdir = $(vendordir)/$(ruby_version) +vendordir = $(rubylibprefix)/vendor_ruby +sitearchdir = $(DESTDIR)./.gem.20220424-672384-uh7xmc +sitelibdir = $(DESTDIR)./.gem.20220424-672384-uh7xmc +sitedir = $(rubylibprefix)/site_ruby +rubyarchdir = $(rubylibdir)/$(arch) +rubylibdir = $(rubylibprefix)/$(ruby_version) +sitearchincludedir = $(includedir)/$(sitearch) +archincludedir = $(includedir)/$(arch) +sitearchlibdir = $(libdir)/$(sitearch) +archlibdir = $(libdir)/$(arch) +ridir = $(datarootdir)/$(RI_BASE_NAME) +mandir = $(datarootdir)/man +localedir = $(datarootdir)/locale +libdir = $(exec_prefix)/lib +psdir = $(docdir) +pdfdir = $(docdir) +dvidir = $(docdir) +htmldir = $(docdir) +infodir = $(datarootdir)/info +docdir = $(datarootdir)/doc/$(PACKAGE) +oldincludedir = $(DESTDIR)/usr/include +includedir = $(prefix)/include +runstatedir = $(localstatedir)/run +localstatedir = $(DESTDIR)/var +sharedstatedir = $(DESTDIR)/var/lib +sysconfdir = $(DESTDIR)/etc +datadir = $(datarootdir) +datarootdir = $(prefix)/share +libexecdir = $(DESTDIR)/usr/lib/ruby +sbindir = $(exec_prefix)/sbin +bindir = $(exec_prefix)/bin +archdir = $(rubyarchdir) + + +CC_WRAPPER = +CC = gcc +CXX = g++ +LIBRUBY = $(LIBRUBY_SO) +LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a +LIBRUBYARG_SHARED = -l$(RUBY_SO_NAME) +LIBRUBYARG_STATIC = -l$(RUBY_SO_NAME)-static $(MAINLIBS) +empty = +OUTFLAG = -o $(empty) +COUTFLAG = -o $(empty) +CSRCFLAG = $(empty) + +RUBY_EXTCONF_H = +cflags = $(optflags) $(debugflags) $(warnflags) +cxxflags = +optflags = -O3 +debugflags = -ggdb3 +warnflags = -Wall -Wextra -Wdeprecated-declarations -Wduplicated-cond -Wimplicit-function-declaration -Wimplicit-int -Wmisleading-indentation -Wpointer-arith -Wwrite-strings -Wimplicit-fallthrough=0 -Wmissing-noreturn -Wno-cast-function-type -Wno-constant-logical-operand -Wno-long-long -Wno-missing-field-initializers -Wno-overlength-strings -Wno-packed-bitfield-compat -Wno-parentheses-equality -Wno-self-assign -Wno-tautological-compare -Wno-unused-parameter -Wno-unused-value -Wsuggest-attribute=format -Wsuggest-attribute=noreturn -Wunused-variable +cppflags = +CCDLFLAGS = -fPIC +CFLAGS = $(CCDLFLAGS) -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC $(ARCH_FLAG) +INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir) +DEFS = +CPPFLAGS = $(DEFS) $(cppflags) +CXXFLAGS = $(CCDLFLAGS) -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -Wp,-D_GLIBCXX_ASSERTIONS $(ARCH_FLAG) +ldflags = -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed +dldflags = -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -Wl,--compress-debug-sections=zlib +ARCH_FLAG = +DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG) +LDSHARED = $(CC) -shared +LDSHAREDXX = $(CXX) -shared +AR = gcc-ar +EXEEXT = + +RUBY_INSTALL_NAME = $(RUBY_BASE_NAME) +RUBY_SO_NAME = ruby +RUBYW_INSTALL_NAME = +RUBY_VERSION_NAME = $(RUBY_BASE_NAME)-$(ruby_version) +RUBYW_BASE_NAME = rubyw +RUBY_BASE_NAME = ruby + +arch = x86_64-linux +sitearch = $(arch) +ruby_version = 3.0.0 +ruby = $(bindir)/$(RUBY_BASE_NAME) +RUBY = $(ruby) +ruby_headers = $(hdrdir)/ruby.h $(hdrdir)/ruby/backward.h $(hdrdir)/ruby/ruby.h $(hdrdir)/ruby/defines.h $(hdrdir)/ruby/missing.h $(hdrdir)/ruby/intern.h $(hdrdir)/ruby/st.h $(hdrdir)/ruby/subst.h $(arch_hdrdir)/ruby/config.h + +RM = rm -f +RM_RF = $(RUBY) -run -e rm -- -rf +RMDIRS = rmdir --ignore-fail-on-non-empty -p +MAKEDIRS = /usr/bin/mkdir -p +INSTALL = /usr/bin/install -c +INSTALL_PROG = $(INSTALL) -m 0755 +INSTALL_DATA = $(INSTALL) -m 644 +COPY = cp +TOUCH = exit > + +#### End of system configuration section. #### + +preload = +libpath = . $(libdir) +LIBPATH = -L. -L$(libdir) +DEFFILE = + +CLEANFILES = mkmf.log +DISTCLEANFILES = +DISTCLEANDIRS = + +extout = +extout_prefix = +target_prefix = +LOCAL_LIBS = +LIBS = $(LIBRUBYARG_SHARED) -lyaml -lm -lc +ORIG_SRCS = psych.c psych_emitter.c psych_parser.c psych_to_ruby.c psych_yaml_tree.c +SRCS = $(ORIG_SRCS) +OBJS = psych.o psych_emitter.o psych_parser.o psych_to_ruby.o psych_yaml_tree.o +HDRS = $(srcdir)/psych.h $(srcdir)/psych_emitter.h $(srcdir)/psych_parser.h $(srcdir)/psych_to_ruby.h $(srcdir)/psych_yaml_tree.h +LOCAL_HDRS = +TARGET = psych +TARGET_NAME = psych +TARGET_ENTRY = Init_$(TARGET_NAME) +DLLIB = $(TARGET).so +EXTSTATIC = +STATIC_LIB = + +TIMESTAMP_DIR = . +BINDIR = $(bindir) +RUBYCOMMONDIR = $(sitedir)$(target_prefix) +RUBYLIBDIR = $(sitelibdir)$(target_prefix) +RUBYARCHDIR = $(sitearchdir)$(target_prefix) +HDRDIR = $(sitehdrdir)$(target_prefix) +ARCHHDRDIR = $(sitearchhdrdir)$(target_prefix) +TARGET_SO_DIR = +TARGET_SO = $(TARGET_SO_DIR)$(DLLIB) +CLEANLIBS = $(TARGET_SO) +CLEANOBJS = *.o *.bak +YAML_H = + + +all: $(DLLIB) +static: $(STATIC_LIB) +.PHONY: all install static install-so install-rb +.PHONY: clean clean-so clean-static clean-rb + +clean-static:: +clean-rb-default:: +clean-rb:: +clean-so:: +clean: clean-so clean-static clean-rb-default clean-rb + -$(Q)$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES) .*.time + +distclean-rb-default:: +distclean-rb:: +distclean-so:: +distclean-static:: +distclean: clean distclean-so distclean-static distclean-rb-default distclean-rb + -$(Q)$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log + -$(Q)$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES) + -$(Q)$(RMDIRS) $(DISTCLEANDIRS) 2> /dev/null || true + +realclean: distclean +install: install-so install-rb + +install-so: $(DLLIB) $(TIMESTAMP_DIR)/.sitearchdir.time + $(INSTALL_PROG) $(DLLIB) $(RUBYARCHDIR) +clean-static:: + -$(Q)$(RM) $(STATIC_LIB) +install-rb: pre-install-rb do-install-rb install-rb-default +install-rb-default: pre-install-rb-default do-install-rb-default +pre-install-rb: Makefile +pre-install-rb-default: Makefile +do-install-rb: +do-install-rb-default: +pre-install-rb-default: + @$(NULLCMD) +$(TIMESTAMP_DIR)/.sitearchdir.time: + $(Q) $(MAKEDIRS) $(@D) $(RUBYARCHDIR) + $(Q) $(TOUCH) $@ + +site-install: site-install-so site-install-rb +site-install-so: install-so +site-install-rb: install-rb + +.SUFFIXES: .c .m .cc .mm .cxx .cpp .o .S + +.cc.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cc.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.mm.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.mm.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.cxx.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cxx.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.cpp.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cpp.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.c.o: + $(ECHO) compiling $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.c.S: + $(ECHO) translating $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.m.o: + $(ECHO) compiling $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.m.S: + $(ECHO) translating $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +$(TARGET_SO): $(OBJS) Makefile + $(ECHO) linking shared-object $(DLLIB) + -$(Q)$(RM) $(@) + $(Q) $(LDSHARED) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS) + + + +### +$(OBJS): $(YAML_H) + +$(OBJS): $(HDRS) $(ruby_headers) \ + $(hdrdir)/ruby/encoding.h \ + $(hdrdir)/ruby/oniguruma.h diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/depend b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/depend new file mode 100644 index 0000000..10d643c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/depend @@ -0,0 +1,5 @@ +$(OBJS): $(YAML_H) + +$(OBJS): $(HDRS) $(ruby_headers) \ + $(hdrdir)/ruby/encoding.h \ + $(hdrdir)/ruby/oniguruma.h diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/extconf.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/extconf.rb new file mode 100644 index 0000000..857f8e6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/extconf.rb @@ -0,0 +1,43 @@ +# -*- coding: us-ascii -*- +# frozen_string_literal: true +require 'mkmf' +require 'fileutils' + +# :stopdoc: + +dir_config 'libyaml' + +if enable_config("bundled-libyaml", false) || !(find_header('yaml.h') && find_library('yaml', 'yaml_get_version')) + # Embed libyaml since we could not find it. + + $VPATH << "$(srcdir)/yaml" + $INCFLAGS << " -I$(srcdir)/yaml" + + $srcs = Dir.glob("#{$srcdir}/{,yaml/}*.c").map {|n| File.basename(n)}.sort + + header = 'yaml/yaml.h' + header = "{$(VPATH)}#{header}" if $nmake + if have_macro("_WIN32") + $CPPFLAGS << " -DYAML_DECLARE_STATIC -DHAVE_CONFIG_H" + end + + have_header 'dlfcn.h' + have_header 'inttypes.h' + have_header 'memory.h' + have_header 'stdint.h' + have_header 'stdlib.h' + have_header 'strings.h' + have_header 'string.h' + have_header 'sys/stat.h' + have_header 'sys/types.h' + have_header 'unistd.h' + + find_header 'yaml.h' + have_header 'config.h' +end + +create_makefile 'psych' do |mk| + mk << "YAML_H = #{header}".strip << "\n" +end + +# :startdoc: diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych.c new file mode 100644 index 0000000..8af0bb6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych.c @@ -0,0 +1,37 @@ +#include + +/* call-seq: Psych.libyaml_version + * + * Returns the version of libyaml being used + */ +static VALUE libyaml_version(VALUE module) +{ + int major, minor, patch; + VALUE list[3]; + + yaml_get_version(&major, &minor, &patch); + + list[0] = INT2NUM(major); + list[1] = INT2NUM(minor); + list[2] = INT2NUM(patch); + + return rb_ary_new4((long)3, list); +} + +VALUE mPsych; + +void Init_psych(void) +{ + #ifdef HAVE_RB_EXT_RACTOR_SAFE + RB_EXT_RACTOR_SAFE(true); + #endif + mPsych = rb_define_module("Psych"); + + rb_define_singleton_method(mPsych, "libyaml_version", libyaml_version, 0); + + Init_psych_parser(); + Init_psych_emitter(); + Init_psych_to_ruby(); + Init_psych_yaml_tree(); +} +/* vim: set noet sws=4 sw=4: */ diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych.h b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych.h new file mode 100644 index 0000000..6b3d63f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych.h @@ -0,0 +1,17 @@ +#ifndef PSYCH_H +#define PSYCH_H + +#include +#include + +#include + +#include +#include +#include +#include + +extern VALUE mPsych; + + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych.o b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych.o new file mode 100644 index 0000000..961bdf8 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_emitter.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_emitter.c new file mode 100644 index 0000000..022ffa0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_emitter.c @@ -0,0 +1,555 @@ +#include + +#if !defined(RARRAY_CONST_PTR) +#define RARRAY_CONST_PTR(s) (const VALUE *)RARRAY_PTR(s) +#endif +#if !defined(RARRAY_AREF) +#define RARRAY_AREF(a, i) RARRAY_CONST_PTR(a)[i] +#endif + +VALUE cPsychEmitter; +static ID id_io; +static ID id_write; +static ID id_line_width; +static ID id_indentation; +static ID id_canonical; + +static void emit(yaml_emitter_t * emitter, yaml_event_t * event) +{ + if(!yaml_emitter_emit(emitter, event)) + rb_raise(rb_eRuntimeError, "%s", emitter->problem); +} + +static int writer(void *ctx, unsigned char *buffer, size_t size) +{ + VALUE self = (VALUE)ctx, io = rb_attr_get(self, id_io); + VALUE str = rb_enc_str_new((const char *)buffer, (long)size, rb_utf8_encoding()); + VALUE wrote = rb_funcall(io, id_write, 1, str); + return (int)NUM2INT(wrote); +} + +static void dealloc(void * ptr) +{ + yaml_emitter_t * emitter; + + emitter = (yaml_emitter_t *)ptr; + yaml_emitter_delete(emitter); + xfree(emitter); +} + +#if 0 +static size_t memsize(const void *ptr) +{ + const yaml_emitter_t *emitter = ptr; + /* TODO: calculate emitter's size */ + return 0; +} +#endif + +static const rb_data_type_t psych_emitter_type = { + "Psych/emitter", + {0, dealloc, 0,}, + 0, 0, +#ifdef RUBY_TYPED_FREE_IMMEDIATELY + RUBY_TYPED_FREE_IMMEDIATELY, +#endif +}; + +static VALUE allocate(VALUE klass) +{ + yaml_emitter_t * emitter; + VALUE obj = TypedData_Make_Struct(klass, yaml_emitter_t, &psych_emitter_type, emitter); + + yaml_emitter_initialize(emitter); + yaml_emitter_set_unicode(emitter, 1); + yaml_emitter_set_indent(emitter, 2); + + return obj; +} + +/* call-seq: Psych::Emitter.new(io, options = Psych::Emitter::OPTIONS) + * + * Create a new Psych::Emitter that writes to +io+. + */ +static VALUE initialize(int argc, VALUE *argv, VALUE self) +{ + yaml_emitter_t * emitter; + VALUE io, options; + VALUE line_width; + VALUE indent; + VALUE canonical; + + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + if (rb_scan_args(argc, argv, "11", &io, &options) == 2) { + line_width = rb_funcall(options, id_line_width, 0); + indent = rb_funcall(options, id_indentation, 0); + canonical = rb_funcall(options, id_canonical, 0); + + yaml_emitter_set_width(emitter, NUM2INT(line_width)); + yaml_emitter_set_indent(emitter, NUM2INT(indent)); + yaml_emitter_set_canonical(emitter, Qtrue == canonical ? 1 : 0); + } + + rb_ivar_set(self, id_io, io); + yaml_emitter_set_output(emitter, writer, (void *)self); + + return self; +} + +/* call-seq: emitter.start_stream(encoding) + * + * Start a stream emission with +encoding+ + * + * See Psych::Handler#start_stream + */ +static VALUE start_stream(VALUE self, VALUE encoding) +{ + yaml_emitter_t * emitter; + yaml_event_t event; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + Check_Type(encoding, T_FIXNUM); + + yaml_stream_start_event_initialize(&event, (yaml_encoding_t)NUM2INT(encoding)); + + emit(emitter, &event); + + return self; +} + +/* call-seq: emitter.end_stream + * + * End a stream emission + * + * See Psych::Handler#end_stream + */ +static VALUE end_stream(VALUE self) +{ + yaml_emitter_t * emitter; + yaml_event_t event; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + yaml_stream_end_event_initialize(&event); + + emit(emitter, &event); + + return self; +} + +/* call-seq: emitter.start_document(version, tags, implicit) + * + * Start a document emission with YAML +version+, +tags+, and an +implicit+ + * start. + * + * See Psych::Handler#start_document + */ +static VALUE start_document(VALUE self, VALUE version, VALUE tags, VALUE imp) +{ + yaml_emitter_t * emitter; + yaml_tag_directive_t * head = NULL; + yaml_tag_directive_t * tail = NULL; + yaml_event_t event; + yaml_version_directive_t version_directive; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + + Check_Type(version, T_ARRAY); + + if(RARRAY_LEN(version) > 0) { + VALUE major = rb_ary_entry(version, (long)0); + VALUE minor = rb_ary_entry(version, (long)1); + + version_directive.major = NUM2INT(major); + version_directive.minor = NUM2INT(minor); + } + + if(RTEST(tags)) { + long i = 0; + long len; + rb_encoding * encoding = rb_utf8_encoding(); + + Check_Type(tags, T_ARRAY); + + len = RARRAY_LEN(tags); + head = xcalloc((size_t)len, sizeof(yaml_tag_directive_t)); + tail = head; + + for(i = 0; i < len && i < RARRAY_LEN(tags); i++) { + VALUE tuple = RARRAY_AREF(tags, i); + VALUE name; + VALUE value; + + Check_Type(tuple, T_ARRAY); + + if(RARRAY_LEN(tuple) < 2) { + xfree(head); + rb_raise(rb_eRuntimeError, "tag tuple must be of length 2"); + } + name = RARRAY_AREF(tuple, 0); + value = RARRAY_AREF(tuple, 1); + StringValue(name); + StringValue(value); + name = rb_str_export_to_enc(name, encoding); + value = rb_str_export_to_enc(value, encoding); + + tail->handle = (yaml_char_t *)StringValueCStr(name); + tail->prefix = (yaml_char_t *)StringValueCStr(value); + + tail++; + } + } + + yaml_document_start_event_initialize( + &event, + (RARRAY_LEN(version) > 0) ? &version_directive : NULL, + head, + tail, + imp ? 1 : 0 + ); + + emit(emitter, &event); + + if(head) xfree(head); + + return self; +} + +/* call-seq: emitter.end_document(implicit) + * + * End a document emission with an +implicit+ ending. + * + * See Psych::Handler#end_document + */ +static VALUE end_document(VALUE self, VALUE imp) +{ + yaml_emitter_t * emitter; + yaml_event_t event; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + yaml_document_end_event_initialize(&event, imp ? 1 : 0); + + emit(emitter, &event); + + return self; +} + +/* call-seq: emitter.scalar(value, anchor, tag, plain, quoted, style) + * + * Emit a scalar with +value+, +anchor+, +tag+, and a +plain+ or +quoted+ + * string type with +style+. + * + * See Psych::Handler#scalar + */ +static VALUE scalar( + VALUE self, + VALUE value, + VALUE anchor, + VALUE tag, + VALUE plain, + VALUE quoted, + VALUE style + ) { + yaml_emitter_t * emitter; + yaml_event_t event; + rb_encoding *encoding; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + Check_Type(value, T_STRING); + + encoding = rb_utf8_encoding(); + + value = rb_str_export_to_enc(value, encoding); + + if(!NIL_P(anchor)) { + Check_Type(anchor, T_STRING); + anchor = rb_str_export_to_enc(anchor, encoding); + } + + if(!NIL_P(tag)) { + Check_Type(tag, T_STRING); + tag = rb_str_export_to_enc(tag, encoding); + } + + yaml_scalar_event_initialize( + &event, + (yaml_char_t *)(NIL_P(anchor) ? NULL : StringValueCStr(anchor)), + (yaml_char_t *)(NIL_P(tag) ? NULL : StringValueCStr(tag)), + (yaml_char_t*)StringValuePtr(value), + (int)RSTRING_LEN(value), + plain ? 1 : 0, + quoted ? 1 : 0, + (yaml_scalar_style_t)NUM2INT(style) + ); + + emit(emitter, &event); + + return self; +} + +/* call-seq: emitter.start_sequence(anchor, tag, implicit, style) + * + * Start emitting a sequence with +anchor+, a +tag+, +implicit+ sequence + * start and end, along with +style+. + * + * See Psych::Handler#start_sequence + */ +static VALUE start_sequence( + VALUE self, + VALUE anchor, + VALUE tag, + VALUE implicit, + VALUE style + ) { + yaml_emitter_t * emitter; + yaml_event_t event; + + rb_encoding * encoding = rb_utf8_encoding(); + + if(!NIL_P(anchor)) { + Check_Type(anchor, T_STRING); + anchor = rb_str_export_to_enc(anchor, encoding); + } + + if(!NIL_P(tag)) { + Check_Type(tag, T_STRING); + tag = rb_str_export_to_enc(tag, encoding); + } + + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + yaml_sequence_start_event_initialize( + &event, + (yaml_char_t *)(NIL_P(anchor) ? NULL : StringValueCStr(anchor)), + (yaml_char_t *)(NIL_P(tag) ? NULL : StringValueCStr(tag)), + implicit ? 1 : 0, + (yaml_sequence_style_t)NUM2INT(style) + ); + + emit(emitter, &event); + + return self; +} + +/* call-seq: emitter.end_sequence + * + * End sequence emission. + * + * See Psych::Handler#end_sequence + */ +static VALUE end_sequence(VALUE self) +{ + yaml_emitter_t * emitter; + yaml_event_t event; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + yaml_sequence_end_event_initialize(&event); + + emit(emitter, &event); + + return self; +} + +/* call-seq: emitter.start_mapping(anchor, tag, implicit, style) + * + * Start emitting a YAML map with +anchor+, +tag+, an +implicit+ start + * and end, and +style+. + * + * See Psych::Handler#start_mapping + */ +static VALUE start_mapping( + VALUE self, + VALUE anchor, + VALUE tag, + VALUE implicit, + VALUE style + ) { + yaml_emitter_t * emitter; + yaml_event_t event; + rb_encoding *encoding; + + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + encoding = rb_utf8_encoding(); + + if(!NIL_P(anchor)) { + Check_Type(anchor, T_STRING); + anchor = rb_str_export_to_enc(anchor, encoding); + } + + if(!NIL_P(tag)) { + Check_Type(tag, T_STRING); + tag = rb_str_export_to_enc(tag, encoding); + } + + yaml_mapping_start_event_initialize( + &event, + (yaml_char_t *)(NIL_P(anchor) ? NULL : StringValueCStr(anchor)), + (yaml_char_t *)(NIL_P(tag) ? NULL : StringValueCStr(tag)), + implicit ? 1 : 0, + (yaml_mapping_style_t)NUM2INT(style) + ); + + emit(emitter, &event); + + return self; +} + +/* call-seq: emitter.end_mapping + * + * Emit the end of a mapping. + * + * See Psych::Handler#end_mapping + */ +static VALUE end_mapping(VALUE self) +{ + yaml_emitter_t * emitter; + yaml_event_t event; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + yaml_mapping_end_event_initialize(&event); + + emit(emitter, &event); + + return self; +} + +/* call-seq: emitter.alias(anchor) + * + * Emit an alias with +anchor+. + * + * See Psych::Handler#alias + */ +static VALUE alias(VALUE self, VALUE anchor) +{ + yaml_emitter_t * emitter; + yaml_event_t event; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + if(!NIL_P(anchor)) { + Check_Type(anchor, T_STRING); + anchor = rb_str_export_to_enc(anchor, rb_utf8_encoding()); + } + + yaml_alias_event_initialize( + &event, + (yaml_char_t *)(NIL_P(anchor) ? NULL : StringValueCStr(anchor)) + ); + + emit(emitter, &event); + + return self; +} + +/* call-seq: emitter.canonical = true + * + * Set the output style to canonical, or not. + */ +static VALUE set_canonical(VALUE self, VALUE style) +{ + yaml_emitter_t * emitter; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + yaml_emitter_set_canonical(emitter, Qtrue == style ? 1 : 0); + + return style; +} + +/* call-seq: emitter.canonical + * + * Get the output style, canonical or not. + */ +static VALUE canonical(VALUE self) +{ + yaml_emitter_t * emitter; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + return (emitter->canonical == 0) ? Qfalse : Qtrue; +} + +/* call-seq: emitter.indentation = level + * + * Set the indentation level to +level+. The level must be less than 10 and + * greater than 1. + */ +static VALUE set_indentation(VALUE self, VALUE level) +{ + yaml_emitter_t * emitter; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + yaml_emitter_set_indent(emitter, NUM2INT(level)); + + return level; +} + +/* call-seq: emitter.indentation + * + * Get the indentation level. + */ +static VALUE indentation(VALUE self) +{ + yaml_emitter_t * emitter; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + return INT2NUM(emitter->best_indent); +} + +/* call-seq: emitter.line_width + * + * Get the preferred line width. + */ +static VALUE line_width(VALUE self) +{ + yaml_emitter_t * emitter; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + return INT2NUM(emitter->best_width); +} + +/* call-seq: emitter.line_width = width + * + * Set the preferred line with to +width+. + */ +static VALUE set_line_width(VALUE self, VALUE width) +{ + yaml_emitter_t * emitter; + TypedData_Get_Struct(self, yaml_emitter_t, &psych_emitter_type, emitter); + + yaml_emitter_set_width(emitter, NUM2INT(width)); + + return width; +} + +void Init_psych_emitter(void) +{ +#undef rb_intern + VALUE psych = rb_define_module("Psych"); + VALUE handler = rb_define_class_under(psych, "Handler", rb_cObject); + cPsychEmitter = rb_define_class_under(psych, "Emitter", handler); + + rb_define_alloc_func(cPsychEmitter, allocate); + + rb_define_method(cPsychEmitter, "initialize", initialize, -1); + rb_define_method(cPsychEmitter, "start_stream", start_stream, 1); + rb_define_method(cPsychEmitter, "end_stream", end_stream, 0); + rb_define_method(cPsychEmitter, "start_document", start_document, 3); + rb_define_method(cPsychEmitter, "end_document", end_document, 1); + rb_define_method(cPsychEmitter, "scalar", scalar, 6); + rb_define_method(cPsychEmitter, "start_sequence", start_sequence, 4); + rb_define_method(cPsychEmitter, "end_sequence", end_sequence, 0); + rb_define_method(cPsychEmitter, "start_mapping", start_mapping, 4); + rb_define_method(cPsychEmitter, "end_mapping", end_mapping, 0); + rb_define_method(cPsychEmitter, "alias", alias, 1); + rb_define_method(cPsychEmitter, "canonical", canonical, 0); + rb_define_method(cPsychEmitter, "canonical=", set_canonical, 1); + rb_define_method(cPsychEmitter, "indentation", indentation, 0); + rb_define_method(cPsychEmitter, "indentation=", set_indentation, 1); + rb_define_method(cPsychEmitter, "line_width", line_width, 0); + rb_define_method(cPsychEmitter, "line_width=", set_line_width, 1); + + id_io = rb_intern("io"); + id_write = rb_intern("write"); + id_line_width = rb_intern("line_width"); + id_indentation = rb_intern("indentation"); + id_canonical = rb_intern("canonical"); +} +/* vim: set noet sws=4 sw=4: */ diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_emitter.h b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_emitter.h new file mode 100644 index 0000000..4c1482a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_emitter.h @@ -0,0 +1,8 @@ +#ifndef PSYCH_EMITTER_H +#define PSYCH_EMITTER_H + +#include + +void Init_psych_emitter(void); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_emitter.o b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_emitter.o new file mode 100644 index 0000000..702cb54 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_emitter.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_parser.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_parser.c new file mode 100644 index 0000000..fd550b6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_parser.c @@ -0,0 +1,579 @@ +#include + +VALUE cPsychParser; + +static ID id_read; +static ID id_path; +static ID id_empty; +static ID id_start_stream; +static ID id_end_stream; +static ID id_start_document; +static ID id_end_document; +static ID id_alias; +static ID id_scalar; +static ID id_start_sequence; +static ID id_end_sequence; +static ID id_start_mapping; +static ID id_end_mapping; +static ID id_event_location; + +#define PSYCH_TRANSCODE(_str, _yaml_enc, _internal_enc) \ + do { \ + rb_enc_associate_index((_str), (_yaml_enc)); \ + if(_internal_enc) \ + (_str) = rb_str_export_to_enc((_str), (_internal_enc)); \ + } while (0) + +static int io_reader(void * data, unsigned char *buf, size_t size, size_t *read) +{ + VALUE io = (VALUE)data; + VALUE string = rb_funcall(io, id_read, 1, SIZET2NUM(size)); + + *read = 0; + + if(! NIL_P(string)) { + void * str = (void *)StringValuePtr(string); + *read = (size_t)RSTRING_LEN(string); + memcpy(buf, str, *read); + } + + return 1; +} + +static void dealloc(void * ptr) +{ + yaml_parser_t * parser; + + parser = (yaml_parser_t *)ptr; + yaml_parser_delete(parser); + xfree(parser); +} + +#if 0 +static size_t memsize(const void *ptr) +{ + const yaml_parser_t *parser = ptr; + /* TODO: calculate parser's size */ + return 0; +} +#endif + +static const rb_data_type_t psych_parser_type = { + "Psych/parser", + {0, dealloc, 0,}, + 0, 0, +#ifdef RUBY_TYPED_FREE_IMMEDIATELY + RUBY_TYPED_FREE_IMMEDIATELY, +#endif +}; + +static VALUE allocate(VALUE klass) +{ + yaml_parser_t * parser; + VALUE obj = TypedData_Make_Struct(klass, yaml_parser_t, &psych_parser_type, parser); + + yaml_parser_initialize(parser); + + return obj; +} + +static VALUE make_exception(yaml_parser_t * parser, VALUE path) +{ + size_t line, column; + VALUE ePsychSyntaxError; + + line = parser->context_mark.line + 1; + column = parser->context_mark.column + 1; + + ePsychSyntaxError = rb_const_get(mPsych, rb_intern("SyntaxError")); + + return rb_funcall(ePsychSyntaxError, rb_intern("new"), 6, + path, + SIZET2NUM(line), + SIZET2NUM(column), + SIZET2NUM(parser->problem_offset), + parser->problem ? rb_usascii_str_new2(parser->problem) : Qnil, + parser->context ? rb_usascii_str_new2(parser->context) : Qnil); +} + +static VALUE transcode_string(VALUE src, int * parser_encoding) +{ + int utf8 = rb_utf8_encindex(); + int utf16le = rb_enc_find_index("UTF-16LE"); + int utf16be = rb_enc_find_index("UTF-16BE"); + int source_encoding = rb_enc_get_index(src); + + if (source_encoding == utf8) { + *parser_encoding = YAML_UTF8_ENCODING; + return src; + } + + if (source_encoding == utf16le) { + *parser_encoding = YAML_UTF16LE_ENCODING; + return src; + } + + if (source_encoding == utf16be) { + *parser_encoding = YAML_UTF16BE_ENCODING; + return src; + } + + src = rb_str_export_to_enc(src, rb_utf8_encoding()); + RB_GC_GUARD(src); + + *parser_encoding = YAML_UTF8_ENCODING; + return src; +} + +static VALUE transcode_io(VALUE src, int * parser_encoding) +{ + VALUE io_external_encoding; + int io_external_enc_index; + + io_external_encoding = rb_funcall(src, rb_intern("external_encoding"), 0); + + /* if no encoding is returned, assume ascii8bit. */ + if (NIL_P(io_external_encoding)) { + io_external_enc_index = rb_ascii8bit_encindex(); + } else { + io_external_enc_index = rb_to_encoding_index(io_external_encoding); + } + + /* Treat US-ASCII as utf_8 */ + if (io_external_enc_index == rb_usascii_encindex()) { + *parser_encoding = YAML_UTF8_ENCODING; + return src; + } + + if (io_external_enc_index == rb_utf8_encindex()) { + *parser_encoding = YAML_UTF8_ENCODING; + return src; + } + + if (io_external_enc_index == rb_enc_find_index("UTF-16LE")) { + *parser_encoding = YAML_UTF16LE_ENCODING; + return src; + } + + if (io_external_enc_index == rb_enc_find_index("UTF-16BE")) { + *parser_encoding = YAML_UTF16BE_ENCODING; + return src; + } + + /* Just guess on ASCII-8BIT */ + if (io_external_enc_index == rb_ascii8bit_encindex()) { + *parser_encoding = YAML_ANY_ENCODING; + return src; + } + + /* If the external encoding is something we don't know how to handle, + * fall back to YAML_ANY_ENCODING. */ + *parser_encoding = YAML_ANY_ENCODING; + + return src; +} + +static VALUE protected_start_stream(VALUE pointer) +{ + VALUE *args = (VALUE *)pointer; + return rb_funcall(args[0], id_start_stream, 1, args[1]); +} + +static VALUE protected_start_document(VALUE pointer) +{ + VALUE *args = (VALUE *)pointer; + return rb_funcall3(args[0], id_start_document, 3, args + 1); +} + +static VALUE protected_end_document(VALUE pointer) +{ + VALUE *args = (VALUE *)pointer; + return rb_funcall(args[0], id_end_document, 1, args[1]); +} + +static VALUE protected_alias(VALUE pointer) +{ + VALUE *args = (VALUE *)pointer; + return rb_funcall(args[0], id_alias, 1, args[1]); +} + +static VALUE protected_scalar(VALUE pointer) +{ + VALUE *args = (VALUE *)pointer; + return rb_funcall3(args[0], id_scalar, 6, args + 1); +} + +static VALUE protected_start_sequence(VALUE pointer) +{ + VALUE *args = (VALUE *)pointer; + return rb_funcall3(args[0], id_start_sequence, 4, args + 1); +} + +static VALUE protected_end_sequence(VALUE handler) +{ + return rb_funcall(handler, id_end_sequence, 0); +} + +static VALUE protected_start_mapping(VALUE pointer) +{ + VALUE *args = (VALUE *)pointer; + return rb_funcall3(args[0], id_start_mapping, 4, args + 1); +} + +static VALUE protected_end_mapping(VALUE handler) +{ + return rb_funcall(handler, id_end_mapping, 0); +} + +static VALUE protected_empty(VALUE handler) +{ + return rb_funcall(handler, id_empty, 0); +} + +static VALUE protected_end_stream(VALUE handler) +{ + return rb_funcall(handler, id_end_stream, 0); +} + +static VALUE protected_event_location(VALUE pointer) +{ + VALUE *args = (VALUE *)pointer; + return rb_funcall3(args[0], id_event_location, 4, args + 1); +} + +/* + * call-seq: + * parser.parse(yaml) + * + * Parse the YAML document contained in +yaml+. Events will be called on + * the handler set on the parser instance. + * + * See Psych::Parser and Psych::Parser#handler + */ +static VALUE parse(int argc, VALUE *argv, VALUE self) +{ + VALUE yaml, path; + yaml_parser_t * parser; + yaml_event_t event; + int done = 0; + int state = 0; + int parser_encoding = YAML_ANY_ENCODING; + int encoding = rb_utf8_encindex(); + rb_encoding * internal_enc = rb_default_internal_encoding(); + VALUE handler = rb_iv_get(self, "@handler"); + + if (rb_scan_args(argc, argv, "11", &yaml, &path) == 1) { + if(rb_respond_to(yaml, id_path)) + path = rb_funcall(yaml, id_path, 0); + else + path = rb_str_new2(""); + } + + TypedData_Get_Struct(self, yaml_parser_t, &psych_parser_type, parser); + + yaml_parser_delete(parser); + yaml_parser_initialize(parser); + + if (rb_respond_to(yaml, id_read)) { + yaml = transcode_io(yaml, &parser_encoding); + yaml_parser_set_encoding(parser, parser_encoding); + yaml_parser_set_input(parser, io_reader, (void *)yaml); + } else { + StringValue(yaml); + yaml = transcode_string(yaml, &parser_encoding); + yaml_parser_set_encoding(parser, parser_encoding); + yaml_parser_set_input_string( + parser, + (const unsigned char *)RSTRING_PTR(yaml), + (size_t)RSTRING_LEN(yaml) + ); + } + + while(!done) { + VALUE event_args[5]; + VALUE start_line, start_column, end_line, end_column; + + if(!yaml_parser_parse(parser, &event)) { + VALUE exception; + + exception = make_exception(parser, path); + yaml_parser_delete(parser); + yaml_parser_initialize(parser); + + rb_exc_raise(exception); + } + + start_line = SIZET2NUM(event.start_mark.line); + start_column = SIZET2NUM(event.start_mark.column); + end_line = SIZET2NUM(event.end_mark.line); + end_column = SIZET2NUM(event.end_mark.column); + + event_args[0] = handler; + event_args[1] = start_line; + event_args[2] = start_column; + event_args[3] = end_line; + event_args[4] = end_column; + rb_protect(protected_event_location, (VALUE)event_args, &state); + + switch(event.type) { + case YAML_STREAM_START_EVENT: + { + VALUE args[2]; + + args[0] = handler; + args[1] = INT2NUM(event.data.stream_start.encoding); + rb_protect(protected_start_stream, (VALUE)args, &state); + } + break; + case YAML_DOCUMENT_START_EVENT: + { + VALUE args[4]; + /* Get a list of tag directives (if any) */ + VALUE tag_directives = rb_ary_new(); + /* Grab the document version */ + VALUE version = event.data.document_start.version_directive ? + rb_ary_new3( + (long)2, + INT2NUM(event.data.document_start.version_directive->major), + INT2NUM(event.data.document_start.version_directive->minor) + ) : rb_ary_new(); + + if(event.data.document_start.tag_directives.start) { + yaml_tag_directive_t *start = + event.data.document_start.tag_directives.start; + yaml_tag_directive_t *end = + event.data.document_start.tag_directives.end; + for(; start != end; start++) { + VALUE handle = Qnil; + VALUE prefix = Qnil; + if(start->handle) { + handle = rb_str_new2((const char *)start->handle); + PSYCH_TRANSCODE(handle, encoding, internal_enc); + } + + if(start->prefix) { + prefix = rb_str_new2((const char *)start->prefix); + PSYCH_TRANSCODE(prefix, encoding, internal_enc); + } + + rb_ary_push(tag_directives, rb_ary_new3((long)2, handle, prefix)); + } + } + args[0] = handler; + args[1] = version; + args[2] = tag_directives; + args[3] = event.data.document_start.implicit == 1 ? Qtrue : Qfalse; + rb_protect(protected_start_document, (VALUE)args, &state); + } + break; + case YAML_DOCUMENT_END_EVENT: + { + VALUE args[2]; + + args[0] = handler; + args[1] = event.data.document_end.implicit == 1 ? Qtrue : Qfalse; + rb_protect(protected_end_document, (VALUE)args, &state); + } + break; + case YAML_ALIAS_EVENT: + { + VALUE args[2]; + VALUE alias = Qnil; + if(event.data.alias.anchor) { + alias = rb_str_new2((const char *)event.data.alias.anchor); + PSYCH_TRANSCODE(alias, encoding, internal_enc); + } + + args[0] = handler; + args[1] = alias; + rb_protect(protected_alias, (VALUE)args, &state); + } + break; + case YAML_SCALAR_EVENT: + { + VALUE args[7]; + VALUE anchor = Qnil; + VALUE tag = Qnil; + VALUE plain_implicit, quoted_implicit, style; + VALUE val = rb_str_new( + (const char *)event.data.scalar.value, + (long)event.data.scalar.length + ); + + PSYCH_TRANSCODE(val, encoding, internal_enc); + + if(event.data.scalar.anchor) { + anchor = rb_str_new2((const char *)event.data.scalar.anchor); + PSYCH_TRANSCODE(anchor, encoding, internal_enc); + } + + if(event.data.scalar.tag) { + tag = rb_str_new2((const char *)event.data.scalar.tag); + PSYCH_TRANSCODE(tag, encoding, internal_enc); + } + + plain_implicit = + event.data.scalar.plain_implicit == 0 ? Qfalse : Qtrue; + + quoted_implicit = + event.data.scalar.quoted_implicit == 0 ? Qfalse : Qtrue; + + style = INT2NUM(event.data.scalar.style); + + args[0] = handler; + args[1] = val; + args[2] = anchor; + args[3] = tag; + args[4] = plain_implicit; + args[5] = quoted_implicit; + args[6] = style; + rb_protect(protected_scalar, (VALUE)args, &state); + } + break; + case YAML_SEQUENCE_START_EVENT: + { + VALUE args[5]; + VALUE anchor = Qnil; + VALUE tag = Qnil; + VALUE implicit, style; + if(event.data.sequence_start.anchor) { + anchor = rb_str_new2((const char *)event.data.sequence_start.anchor); + PSYCH_TRANSCODE(anchor, encoding, internal_enc); + } + + tag = Qnil; + if(event.data.sequence_start.tag) { + tag = rb_str_new2((const char *)event.data.sequence_start.tag); + PSYCH_TRANSCODE(tag, encoding, internal_enc); + } + + implicit = + event.data.sequence_start.implicit == 0 ? Qfalse : Qtrue; + + style = INT2NUM(event.data.sequence_start.style); + + args[0] = handler; + args[1] = anchor; + args[2] = tag; + args[3] = implicit; + args[4] = style; + + rb_protect(protected_start_sequence, (VALUE)args, &state); + } + break; + case YAML_SEQUENCE_END_EVENT: + rb_protect(protected_end_sequence, handler, &state); + break; + case YAML_MAPPING_START_EVENT: + { + VALUE args[5]; + VALUE anchor = Qnil; + VALUE tag = Qnil; + VALUE implicit, style; + if(event.data.mapping_start.anchor) { + anchor = rb_str_new2((const char *)event.data.mapping_start.anchor); + PSYCH_TRANSCODE(anchor, encoding, internal_enc); + } + + if(event.data.mapping_start.tag) { + tag = rb_str_new2((const char *)event.data.mapping_start.tag); + PSYCH_TRANSCODE(tag, encoding, internal_enc); + } + + implicit = + event.data.mapping_start.implicit == 0 ? Qfalse : Qtrue; + + style = INT2NUM(event.data.mapping_start.style); + + args[0] = handler; + args[1] = anchor; + args[2] = tag; + args[3] = implicit; + args[4] = style; + + rb_protect(protected_start_mapping, (VALUE)args, &state); + } + break; + case YAML_MAPPING_END_EVENT: + rb_protect(protected_end_mapping, handler, &state); + break; + case YAML_NO_EVENT: + rb_protect(protected_empty, handler, &state); + break; + case YAML_STREAM_END_EVENT: + rb_protect(protected_end_stream, handler, &state); + done = 1; + break; + } + yaml_event_delete(&event); + if (state) rb_jump_tag(state); + } + + return self; +} + +/* + * call-seq: + * parser.mark # => # + * + * Returns a Psych::Parser::Mark object that contains line, column, and index + * information. + */ +static VALUE mark(VALUE self) +{ + VALUE mark_klass; + VALUE args[3]; + yaml_parser_t * parser; + + TypedData_Get_Struct(self, yaml_parser_t, &psych_parser_type, parser); + mark_klass = rb_const_get_at(cPsychParser, rb_intern("Mark")); + args[0] = SIZET2NUM(parser->mark.index); + args[1] = SIZET2NUM(parser->mark.line); + args[2] = SIZET2NUM(parser->mark.column); + + return rb_class_new_instance(3, args, mark_klass); +} + +void Init_psych_parser(void) +{ +#undef rb_intern +#if 0 + mPsych = rb_define_module("Psych"); +#endif + + cPsychParser = rb_define_class_under(mPsych, "Parser", rb_cObject); + rb_define_alloc_func(cPsychParser, allocate); + + /* Any encoding: Let the parser choose the encoding */ + rb_define_const(cPsychParser, "ANY", INT2NUM(YAML_ANY_ENCODING)); + + /* UTF-8 Encoding */ + rb_define_const(cPsychParser, "UTF8", INT2NUM(YAML_UTF8_ENCODING)); + + /* UTF-16-LE Encoding with BOM */ + rb_define_const(cPsychParser, "UTF16LE", INT2NUM(YAML_UTF16LE_ENCODING)); + + /* UTF-16-BE Encoding with BOM */ + rb_define_const(cPsychParser, "UTF16BE", INT2NUM(YAML_UTF16BE_ENCODING)); + + rb_require("psych/syntax_error"); + + rb_define_method(cPsychParser, "parse", parse, -1); + rb_define_method(cPsychParser, "mark", mark, 0); + + id_read = rb_intern("read"); + id_path = rb_intern("path"); + id_empty = rb_intern("empty"); + id_start_stream = rb_intern("start_stream"); + id_end_stream = rb_intern("end_stream"); + id_start_document = rb_intern("start_document"); + id_end_document = rb_intern("end_document"); + id_alias = rb_intern("alias"); + id_scalar = rb_intern("scalar"); + id_start_sequence = rb_intern("start_sequence"); + id_end_sequence = rb_intern("end_sequence"); + id_start_mapping = rb_intern("start_mapping"); + id_end_mapping = rb_intern("end_mapping"); + id_event_location = rb_intern("event_location"); +} +/* vim: set noet sws=4 sw=4: */ diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_parser.h b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_parser.h new file mode 100644 index 0000000..beb3dd0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_parser.h @@ -0,0 +1,6 @@ +#ifndef PSYCH_PARSER_H +#define PSYCH_PARSER_H + +void Init_psych_parser(void); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_parser.o b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_parser.o new file mode 100644 index 0000000..9aebcd8 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_parser.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_to_ruby.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_to_ruby.c new file mode 100644 index 0000000..b388ff7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_to_ruby.c @@ -0,0 +1,39 @@ +#include + +VALUE cPsychVisitorsToRuby; + +/* call-seq: vis.build_exception(klass, message) + * + * Create an exception with class +klass+ and +message+ + */ +static VALUE build_exception(VALUE self, VALUE klass, VALUE mesg) +{ + VALUE e = rb_obj_alloc(klass); + + rb_iv_set(e, "mesg", mesg); + + return e; +} + +/* call-seq: vis.path2class(path) + * + * Convert +path+ string to a class + */ +static VALUE path2class(VALUE self, VALUE path) +{ + return rb_path_to_class(path); +} + +void Init_psych_to_ruby(void) +{ + VALUE psych = rb_define_module("Psych"); + VALUE class_loader = rb_define_class_under(psych, "ClassLoader", rb_cObject); + + VALUE visitors = rb_define_module_under(psych, "Visitors"); + VALUE visitor = rb_define_class_under(visitors, "Visitor", rb_cObject); + cPsychVisitorsToRuby = rb_define_class_under(visitors, "ToRuby", visitor); + + rb_define_private_method(cPsychVisitorsToRuby, "build_exception", build_exception, 2); + rb_define_private_method(class_loader, "path2class", path2class, 1); +} +/* vim: set noet sws=4 sw=4: */ diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_to_ruby.h b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_to_ruby.h new file mode 100644 index 0000000..7b8e757 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_to_ruby.h @@ -0,0 +1,8 @@ +#ifndef PSYCH_TO_RUBY_H +#define PSYCH_TO_RUBY_H + +#include + +void Init_psych_to_ruby(void); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_to_ruby.o b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_to_ruby.o new file mode 100644 index 0000000..3a83076 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_to_ruby.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_yaml_tree.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_yaml_tree.c new file mode 100644 index 0000000..225655d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_yaml_tree.c @@ -0,0 +1,12 @@ +#include + +VALUE cPsychVisitorsYamlTree; + +void Init_psych_yaml_tree(void) +{ + VALUE psych = rb_define_module("Psych"); + VALUE visitors = rb_define_module_under(psych, "Visitors"); + VALUE visitor = rb_define_class_under(visitors, "Visitor", rb_cObject); + cPsychVisitorsYamlTree = rb_define_class_under(visitors, "YAMLTree", visitor); +} +/* vim: set noet sws=4 sw=4: */ diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_yaml_tree.h b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_yaml_tree.h new file mode 100644 index 0000000..4628a69 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_yaml_tree.h @@ -0,0 +1,8 @@ +#ifndef PSYCH_YAML_TREE_H +#define PSYCH_YAML_TREE_H + +#include + +void Init_psych_yaml_tree(void); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_yaml_tree.o b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_yaml_tree.o new file mode 100644 index 0000000..d40c153 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/psych_yaml_tree.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/LICENSE b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/LICENSE new file mode 100644 index 0000000..050ced2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2006 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/api.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/api.c new file mode 100644 index 0000000..6add8b2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/api.c @@ -0,0 +1,1393 @@ + +#include "yaml_private.h" + +/* + * Get the library version. + */ + +YAML_DECLARE(const char *) +yaml_get_version_string(void) +{ + return YAML_VERSION_STRING; +} + +/* + * Get the library version numbers. + */ + +YAML_DECLARE(void) +yaml_get_version(int *major, int *minor, int *patch) +{ + *major = YAML_VERSION_MAJOR; + *minor = YAML_VERSION_MINOR; + *patch = YAML_VERSION_PATCH; +} + +/* + * Allocate a dynamic memory block. + */ + +YAML_DECLARE(void *) +yaml_malloc(size_t size) +{ + return malloc(size ? size : 1); +} + +/* + * Reallocate a dynamic memory block. + */ + +YAML_DECLARE(void *) +yaml_realloc(void *ptr, size_t size) +{ + return ptr ? realloc(ptr, size ? size : 1) : malloc(size ? size : 1); +} + +/* + * Free a dynamic memory block. + */ + +YAML_DECLARE(void) +yaml_free(void *ptr) +{ + if (ptr) free(ptr); +} + +/* + * Duplicate a string. + */ + +YAML_DECLARE(yaml_char_t *) +yaml_strdup(const yaml_char_t *str) +{ + if (!str) + return NULL; + + return (yaml_char_t *)strdup((char *)str); +} + +/* + * Extend a string. + */ + +YAML_DECLARE(int) +yaml_string_extend(yaml_char_t **start, + yaml_char_t **pointer, yaml_char_t **end) +{ + yaml_char_t *new_start = (yaml_char_t *)yaml_realloc((void*)*start, (*end - *start)*2); + + if (!new_start) return 0; + + memset(new_start + (*end - *start), 0, *end - *start); + + *pointer = new_start + (*pointer - *start); + *end = new_start + (*end - *start)*2; + *start = new_start; + + return 1; +} + +/* + * Append a string B to a string A. + */ + +YAML_DECLARE(int) +yaml_string_join( + yaml_char_t **a_start, yaml_char_t **a_pointer, yaml_char_t **a_end, + yaml_char_t **b_start, yaml_char_t **b_pointer, SHIM(yaml_char_t **b_end)) +{ + UNUSED_PARAM(b_end) + if (*b_start == *b_pointer) + return 1; + + while (*a_end - *a_pointer <= *b_pointer - *b_start) { + if (!yaml_string_extend(a_start, a_pointer, a_end)) + return 0; + } + + memcpy(*a_pointer, *b_start, *b_pointer - *b_start); + *a_pointer += *b_pointer - *b_start; + + return 1; +} + +/* + * Extend a stack. + */ + +YAML_DECLARE(int) +yaml_stack_extend(void **start, void **top, void **end) +{ + void *new_start; + + if ((char *)*end - (char *)*start >= INT_MAX / 2) + return 0; + + new_start = yaml_realloc(*start, ((char *)*end - (char *)*start)*2); + + if (!new_start) return 0; + + *top = (char *)new_start + ((char *)*top - (char *)*start); + *end = (char *)new_start + ((char *)*end - (char *)*start)*2; + *start = new_start; + + return 1; +} + +/* + * Extend or move a queue. + */ + +YAML_DECLARE(int) +yaml_queue_extend(void **start, void **head, void **tail, void **end) +{ + /* Check if we need to resize the queue. */ + + if (*start == *head && *tail == *end) { + void *new_start = yaml_realloc(*start, + ((char *)*end - (char *)*start)*2); + + if (!new_start) return 0; + + *head = (char *)new_start + ((char *)*head - (char *)*start); + *tail = (char *)new_start + ((char *)*tail - (char *)*start); + *end = (char *)new_start + ((char *)*end - (char *)*start)*2; + *start = new_start; + } + + /* Check if we need to move the queue at the beginning of the buffer. */ + + if (*tail == *end) { + if (*head != *tail) { + memmove(*start, *head, (char *)*tail - (char *)*head); + } + *tail = (char *)*tail - (char *)*head + (char *)*start; + *head = *start; + } + + return 1; +} + + +/* + * Create a new parser object. + */ + +YAML_DECLARE(int) +yaml_parser_initialize(yaml_parser_t *parser) +{ + assert(parser); /* Non-NULL parser object expected. */ + + memset(parser, 0, sizeof(yaml_parser_t)); + if (!BUFFER_INIT(parser, parser->raw_buffer, INPUT_RAW_BUFFER_SIZE)) + goto error; + if (!BUFFER_INIT(parser, parser->buffer, INPUT_BUFFER_SIZE)) + goto error; + if (!QUEUE_INIT(parser, parser->tokens, INITIAL_QUEUE_SIZE, yaml_token_t*)) + goto error; + if (!STACK_INIT(parser, parser->indents, int*)) + goto error; + if (!STACK_INIT(parser, parser->simple_keys, yaml_simple_key_t*)) + goto error; + if (!STACK_INIT(parser, parser->states, yaml_parser_state_t*)) + goto error; + if (!STACK_INIT(parser, parser->marks, yaml_mark_t*)) + goto error; + if (!STACK_INIT(parser, parser->tag_directives, yaml_tag_directive_t*)) + goto error; + + return 1; + +error: + + BUFFER_DEL(parser, parser->raw_buffer); + BUFFER_DEL(parser, parser->buffer); + QUEUE_DEL(parser, parser->tokens); + STACK_DEL(parser, parser->indents); + STACK_DEL(parser, parser->simple_keys); + STACK_DEL(parser, parser->states); + STACK_DEL(parser, parser->marks); + STACK_DEL(parser, parser->tag_directives); + + return 0; +} + +/* + * Destroy a parser object. + */ + +YAML_DECLARE(void) +yaml_parser_delete(yaml_parser_t *parser) +{ + assert(parser); /* Non-NULL parser object expected. */ + + BUFFER_DEL(parser, parser->raw_buffer); + BUFFER_DEL(parser, parser->buffer); + while (!QUEUE_EMPTY(parser, parser->tokens)) { + yaml_token_delete(&DEQUEUE(parser, parser->tokens)); + } + QUEUE_DEL(parser, parser->tokens); + STACK_DEL(parser, parser->indents); + STACK_DEL(parser, parser->simple_keys); + STACK_DEL(parser, parser->states); + STACK_DEL(parser, parser->marks); + while (!STACK_EMPTY(parser, parser->tag_directives)) { + yaml_tag_directive_t tag_directive = POP(parser, parser->tag_directives); + yaml_free(tag_directive.handle); + yaml_free(tag_directive.prefix); + } + STACK_DEL(parser, parser->tag_directives); + + memset(parser, 0, sizeof(yaml_parser_t)); +} + +/* + * String read handler. + */ + +static int +yaml_string_read_handler(void *data, unsigned char *buffer, size_t size, + size_t *size_read) +{ + yaml_parser_t *parser = (yaml_parser_t *)data; + + if (parser->input.string.current == parser->input.string.end) { + *size_read = 0; + return 1; + } + + if (size > (size_t)(parser->input.string.end + - parser->input.string.current)) { + size = parser->input.string.end - parser->input.string.current; + } + + memcpy(buffer, parser->input.string.current, size); + parser->input.string.current += size; + *size_read = size; + return 1; +} + +/* + * File read handler. + */ + +static int +yaml_file_read_handler(void *data, unsigned char *buffer, size_t size, + size_t *size_read) +{ + yaml_parser_t *parser = (yaml_parser_t *)data; + + *size_read = fread(buffer, 1, size, parser->input.file); + return !ferror(parser->input.file); +} + +/* + * Set a string input. + */ + +YAML_DECLARE(void) +yaml_parser_set_input_string(yaml_parser_t *parser, + const unsigned char *input, size_t size) +{ + assert(parser); /* Non-NULL parser object expected. */ + assert(!parser->read_handler); /* You can set the source only once. */ + assert(input); /* Non-NULL input string expected. */ + + parser->read_handler = yaml_string_read_handler; + parser->read_handler_data = parser; + + parser->input.string.start = input; + parser->input.string.current = input; + parser->input.string.end = input+size; +} + +/* + * Set a file input. + */ + +YAML_DECLARE(void) +yaml_parser_set_input_file(yaml_parser_t *parser, FILE *file) +{ + assert(parser); /* Non-NULL parser object expected. */ + assert(!parser->read_handler); /* You can set the source only once. */ + assert(file); /* Non-NULL file object expected. */ + + parser->read_handler = yaml_file_read_handler; + parser->read_handler_data = parser; + + parser->input.file = file; +} + +/* + * Set a generic input. + */ + +YAML_DECLARE(void) +yaml_parser_set_input(yaml_parser_t *parser, + yaml_read_handler_t *handler, void *data) +{ + assert(parser); /* Non-NULL parser object expected. */ + assert(!parser->read_handler); /* You can set the source only once. */ + assert(handler); /* Non-NULL read handler expected. */ + + parser->read_handler = handler; + parser->read_handler_data = data; +} + +/* + * Set the source encoding. + */ + +YAML_DECLARE(void) +yaml_parser_set_encoding(yaml_parser_t *parser, yaml_encoding_t encoding) +{ + assert(parser); /* Non-NULL parser object expected. */ + assert(!parser->encoding); /* Encoding is already set or detected. */ + + parser->encoding = encoding; +} + +/* + * Create a new emitter object. + */ + +YAML_DECLARE(int) +yaml_emitter_initialize(yaml_emitter_t *emitter) +{ + assert(emitter); /* Non-NULL emitter object expected. */ + + memset(emitter, 0, sizeof(yaml_emitter_t)); + if (!BUFFER_INIT(emitter, emitter->buffer, OUTPUT_BUFFER_SIZE)) + goto error; + if (!BUFFER_INIT(emitter, emitter->raw_buffer, OUTPUT_RAW_BUFFER_SIZE)) + goto error; + if (!STACK_INIT(emitter, emitter->states, yaml_emitter_state_t*)) + goto error; + if (!QUEUE_INIT(emitter, emitter->events, INITIAL_QUEUE_SIZE, yaml_event_t*)) + goto error; + if (!STACK_INIT(emitter, emitter->indents, int*)) + goto error; + if (!STACK_INIT(emitter, emitter->tag_directives, yaml_tag_directive_t*)) + goto error; + + return 1; + +error: + + BUFFER_DEL(emitter, emitter->buffer); + BUFFER_DEL(emitter, emitter->raw_buffer); + STACK_DEL(emitter, emitter->states); + QUEUE_DEL(emitter, emitter->events); + STACK_DEL(emitter, emitter->indents); + STACK_DEL(emitter, emitter->tag_directives); + + return 0; +} + +/* + * Destroy an emitter object. + */ + +YAML_DECLARE(void) +yaml_emitter_delete(yaml_emitter_t *emitter) +{ + assert(emitter); /* Non-NULL emitter object expected. */ + + BUFFER_DEL(emitter, emitter->buffer); + BUFFER_DEL(emitter, emitter->raw_buffer); + STACK_DEL(emitter, emitter->states); + while (!QUEUE_EMPTY(emitter, emitter->events)) { + yaml_event_delete(&DEQUEUE(emitter, emitter->events)); + } + QUEUE_DEL(emitter, emitter->events); + STACK_DEL(emitter, emitter->indents); + while (!STACK_EMPTY(empty, emitter->tag_directives)) { + yaml_tag_directive_t tag_directive = POP(emitter, emitter->tag_directives); + yaml_free(tag_directive.handle); + yaml_free(tag_directive.prefix); + } + STACK_DEL(emitter, emitter->tag_directives); + yaml_free(emitter->anchors); + + memset(emitter, 0, sizeof(yaml_emitter_t)); +} + +/* + * String write handler. + */ + +static int +yaml_string_write_handler(void *data, unsigned char *buffer, size_t size) +{ + yaml_emitter_t *emitter = (yaml_emitter_t *)data; + + if (emitter->output.string.size - *emitter->output.string.size_written + < size) { + memcpy(emitter->output.string.buffer + + *emitter->output.string.size_written, + buffer, + emitter->output.string.size + - *emitter->output.string.size_written); + *emitter->output.string.size_written = emitter->output.string.size; + return 0; + } + + memcpy(emitter->output.string.buffer + + *emitter->output.string.size_written, buffer, size); + *emitter->output.string.size_written += size; + return 1; +} + +/* + * File write handler. + */ + +static int +yaml_file_write_handler(void *data, unsigned char *buffer, size_t size) +{ + yaml_emitter_t *emitter = (yaml_emitter_t *)data; + + return (fwrite(buffer, 1, size, emitter->output.file) == size); +} +/* + * Set a string output. + */ + +YAML_DECLARE(void) +yaml_emitter_set_output_string(yaml_emitter_t *emitter, + unsigned char *output, size_t size, size_t *size_written) +{ + assert(emitter); /* Non-NULL emitter object expected. */ + assert(!emitter->write_handler); /* You can set the output only once. */ + assert(output); /* Non-NULL output string expected. */ + + emitter->write_handler = yaml_string_write_handler; + emitter->write_handler_data = emitter; + + emitter->output.string.buffer = output; + emitter->output.string.size = size; + emitter->output.string.size_written = size_written; + *size_written = 0; +} + +/* + * Set a file output. + */ + +YAML_DECLARE(void) +yaml_emitter_set_output_file(yaml_emitter_t *emitter, FILE *file) +{ + assert(emitter); /* Non-NULL emitter object expected. */ + assert(!emitter->write_handler); /* You can set the output only once. */ + assert(file); /* Non-NULL file object expected. */ + + emitter->write_handler = yaml_file_write_handler; + emitter->write_handler_data = emitter; + + emitter->output.file = file; +} + +/* + * Set a generic output handler. + */ + +YAML_DECLARE(void) +yaml_emitter_set_output(yaml_emitter_t *emitter, + yaml_write_handler_t *handler, void *data) +{ + assert(emitter); /* Non-NULL emitter object expected. */ + assert(!emitter->write_handler); /* You can set the output only once. */ + assert(handler); /* Non-NULL handler object expected. */ + + emitter->write_handler = handler; + emitter->write_handler_data = data; +} + +/* + * Set the output encoding. + */ + +YAML_DECLARE(void) +yaml_emitter_set_encoding(yaml_emitter_t *emitter, yaml_encoding_t encoding) +{ + assert(emitter); /* Non-NULL emitter object expected. */ + assert(!emitter->encoding); /* You can set encoding only once. */ + + emitter->encoding = encoding; +} + +/* + * Set the canonical output style. + */ + +YAML_DECLARE(void) +yaml_emitter_set_canonical(yaml_emitter_t *emitter, int canonical) +{ + assert(emitter); /* Non-NULL emitter object expected. */ + + emitter->canonical = (canonical != 0); +} + +/* + * Set the indentation increment. + */ + +YAML_DECLARE(void) +yaml_emitter_set_indent(yaml_emitter_t *emitter, int indent) +{ + assert(emitter); /* Non-NULL emitter object expected. */ + + emitter->best_indent = (1 < indent && indent < 10) ? indent : 2; +} + +/* + * Set the preferred line width. + */ + +YAML_DECLARE(void) +yaml_emitter_set_width(yaml_emitter_t *emitter, int width) +{ + assert(emitter); /* Non-NULL emitter object expected. */ + + emitter->best_width = (width >= 0) ? width : -1; +} + +/* + * Set if unescaped non-ASCII characters are allowed. + */ + +YAML_DECLARE(void) +yaml_emitter_set_unicode(yaml_emitter_t *emitter, int unicode) +{ + assert(emitter); /* Non-NULL emitter object expected. */ + + emitter->unicode = (unicode != 0); +} + +/* + * Set the preferred line break character. + */ + +YAML_DECLARE(void) +yaml_emitter_set_break(yaml_emitter_t *emitter, yaml_break_t line_break) +{ + assert(emitter); /* Non-NULL emitter object expected. */ + + emitter->line_break = line_break; +} + +/* + * Destroy a token object. + */ + +YAML_DECLARE(void) +yaml_token_delete(yaml_token_t *token) +{ + assert(token); /* Non-NULL token object expected. */ + + switch (token->type) + { + case YAML_TAG_DIRECTIVE_TOKEN: + yaml_free(token->data.tag_directive.handle); + yaml_free(token->data.tag_directive.prefix); + break; + + case YAML_ALIAS_TOKEN: + yaml_free(token->data.alias.value); + break; + + case YAML_ANCHOR_TOKEN: + yaml_free(token->data.anchor.value); + break; + + case YAML_TAG_TOKEN: + yaml_free(token->data.tag.handle); + yaml_free(token->data.tag.suffix); + break; + + case YAML_SCALAR_TOKEN: + yaml_free(token->data.scalar.value); + break; + + default: + break; + } + + memset(token, 0, sizeof(yaml_token_t)); +} + +/* + * Check if a string is a valid UTF-8 sequence. + * + * Check 'reader.c' for more details on UTF-8 encoding. + */ + +static int +yaml_check_utf8(const yaml_char_t *start, size_t length) +{ + const yaml_char_t *end = start+length; + const yaml_char_t *pointer = start; + + while (pointer < end) { + unsigned char octet; + unsigned int width; + unsigned int value; + size_t k; + + octet = pointer[0]; + width = (octet & 0x80) == 0x00 ? 1 : + (octet & 0xE0) == 0xC0 ? 2 : + (octet & 0xF0) == 0xE0 ? 3 : + (octet & 0xF8) == 0xF0 ? 4 : 0; + value = (octet & 0x80) == 0x00 ? octet & 0x7F : + (octet & 0xE0) == 0xC0 ? octet & 0x1F : + (octet & 0xF0) == 0xE0 ? octet & 0x0F : + (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; + if (!width) return 0; + if (pointer+width > end) return 0; + for (k = 1; k < width; k ++) { + octet = pointer[k]; + if ((octet & 0xC0) != 0x80) return 0; + value = (value << 6) + (octet & 0x3F); + } + if (!((width == 1) || + (width == 2 && value >= 0x80) || + (width == 3 && value >= 0x800) || + (width == 4 && value >= 0x10000))) return 0; + + pointer += width; + } + + return 1; +} + +/* + * Create STREAM-START. + */ + +YAML_DECLARE(int) +yaml_stream_start_event_initialize(yaml_event_t *event, + yaml_encoding_t encoding) +{ + yaml_mark_t mark = { 0, 0, 0 }; + + assert(event); /* Non-NULL event object is expected. */ + + STREAM_START_EVENT_INIT(*event, encoding, mark, mark); + + return 1; +} + +/* + * Create STREAM-END. + */ + +YAML_DECLARE(int) +yaml_stream_end_event_initialize(yaml_event_t *event) +{ + yaml_mark_t mark = { 0, 0, 0 }; + + assert(event); /* Non-NULL event object is expected. */ + + STREAM_END_EVENT_INIT(*event, mark, mark); + + return 1; +} + +/* + * Create DOCUMENT-START. + */ + +YAML_DECLARE(int) +yaml_document_start_event_initialize(yaml_event_t *event, + yaml_version_directive_t *version_directive, + yaml_tag_directive_t *tag_directives_start, + yaml_tag_directive_t *tag_directives_end, + int implicit) +{ + struct { + yaml_error_type_t error; + } context; + yaml_mark_t mark = { 0, 0, 0 }; + yaml_version_directive_t *version_directive_copy = NULL; + struct { + yaml_tag_directive_t *start; + yaml_tag_directive_t *end; + yaml_tag_directive_t *top; + } tag_directives_copy = { NULL, NULL, NULL }; + yaml_tag_directive_t value = { NULL, NULL }; + + assert(event); /* Non-NULL event object is expected. */ + assert((tag_directives_start && tag_directives_end) || + (tag_directives_start == tag_directives_end)); + /* Valid tag directives are expected. */ + + if (version_directive) { + version_directive_copy = YAML_MALLOC_STATIC(yaml_version_directive_t); + if (!version_directive_copy) goto error; + version_directive_copy->major = version_directive->major; + version_directive_copy->minor = version_directive->minor; + } + + if (tag_directives_start != tag_directives_end) { + yaml_tag_directive_t *tag_directive; + if (!STACK_INIT(&context, tag_directives_copy, yaml_tag_directive_t*)) + goto error; + for (tag_directive = tag_directives_start; + tag_directive != tag_directives_end; tag_directive ++) { + assert(tag_directive->handle); + assert(tag_directive->prefix); + if (!yaml_check_utf8(tag_directive->handle, + strlen((char *)tag_directive->handle))) + goto error; + if (!yaml_check_utf8(tag_directive->prefix, + strlen((char *)tag_directive->prefix))) + goto error; + value.handle = yaml_strdup(tag_directive->handle); + value.prefix = yaml_strdup(tag_directive->prefix); + if (!value.handle || !value.prefix) goto error; + if (!PUSH(&context, tag_directives_copy, value)) + goto error; + value.handle = NULL; + value.prefix = NULL; + } + } + + DOCUMENT_START_EVENT_INIT(*event, version_directive_copy, + tag_directives_copy.start, tag_directives_copy.top, + implicit, mark, mark); + + return 1; + +error: + yaml_free(version_directive_copy); + while (!STACK_EMPTY(context, tag_directives_copy)) { + yaml_tag_directive_t value = POP(context, tag_directives_copy); + yaml_free(value.handle); + yaml_free(value.prefix); + } + STACK_DEL(context, tag_directives_copy); + yaml_free(value.handle); + yaml_free(value.prefix); + + return 0; +} + +/* + * Create DOCUMENT-END. + */ + +YAML_DECLARE(int) +yaml_document_end_event_initialize(yaml_event_t *event, int implicit) +{ + yaml_mark_t mark = { 0, 0, 0 }; + + assert(event); /* Non-NULL emitter object is expected. */ + + DOCUMENT_END_EVENT_INIT(*event, implicit, mark, mark); + + return 1; +} + +/* + * Create ALIAS. + */ + +YAML_DECLARE(int) +yaml_alias_event_initialize(yaml_event_t *event, const yaml_char_t *anchor) +{ + yaml_mark_t mark = { 0, 0, 0 }; + yaml_char_t *anchor_copy = NULL; + + assert(event); /* Non-NULL event object is expected. */ + assert(anchor); /* Non-NULL anchor is expected. */ + + if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0; + + anchor_copy = yaml_strdup(anchor); + if (!anchor_copy) + return 0; + + ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark); + + return 1; +} + +/* + * Create SCALAR. + */ + +YAML_DECLARE(int) +yaml_scalar_event_initialize(yaml_event_t *event, + const yaml_char_t *anchor, const yaml_char_t *tag, + const yaml_char_t *value, int length, + int plain_implicit, int quoted_implicit, + yaml_scalar_style_t style) +{ + yaml_mark_t mark = { 0, 0, 0 }; + yaml_char_t *anchor_copy = NULL; + yaml_char_t *tag_copy = NULL; + yaml_char_t *value_copy = NULL; + + assert(event); /* Non-NULL event object is expected. */ + assert(value); /* Non-NULL anchor is expected. */ + + if (anchor) { + if (!yaml_check_utf8(anchor, strlen((char *)anchor))) goto error; + anchor_copy = yaml_strdup(anchor); + if (!anchor_copy) goto error; + } + + if (tag) { + if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error; + tag_copy = yaml_strdup(tag); + if (!tag_copy) goto error; + } + + if (length < 0) { + length = (int)strlen((char *)value); + } + + if (!yaml_check_utf8(value, length)) goto error; + value_copy = YAML_MALLOC(length+1); + if (!value_copy) goto error; + memcpy(value_copy, value, length); + value_copy[length] = '\0'; + + SCALAR_EVENT_INIT(*event, anchor_copy, tag_copy, value_copy, length, + plain_implicit, quoted_implicit, style, mark, mark); + + return 1; + +error: + yaml_free(anchor_copy); + yaml_free(tag_copy); + yaml_free(value_copy); + + return 0; +} + +/* + * Create SEQUENCE-START. + */ + +YAML_DECLARE(int) +yaml_sequence_start_event_initialize(yaml_event_t *event, + const yaml_char_t *anchor, const yaml_char_t *tag, int implicit, + yaml_sequence_style_t style) +{ + yaml_mark_t mark = { 0, 0, 0 }; + yaml_char_t *anchor_copy = NULL; + yaml_char_t *tag_copy = NULL; + + assert(event); /* Non-NULL event object is expected. */ + + if (anchor) { + if (!yaml_check_utf8(anchor, strlen((char *)anchor))) goto error; + anchor_copy = yaml_strdup(anchor); + if (!anchor_copy) goto error; + } + + if (tag) { + if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error; + tag_copy = yaml_strdup(tag); + if (!tag_copy) goto error; + } + + SEQUENCE_START_EVENT_INIT(*event, anchor_copy, tag_copy, + implicit, style, mark, mark); + + return 1; + +error: + yaml_free(anchor_copy); + yaml_free(tag_copy); + + return 0; +} + +/* + * Create SEQUENCE-END. + */ + +YAML_DECLARE(int) +yaml_sequence_end_event_initialize(yaml_event_t *event) +{ + yaml_mark_t mark = { 0, 0, 0 }; + + assert(event); /* Non-NULL event object is expected. */ + + SEQUENCE_END_EVENT_INIT(*event, mark, mark); + + return 1; +} + +/* + * Create MAPPING-START. + */ + +YAML_DECLARE(int) +yaml_mapping_start_event_initialize(yaml_event_t *event, + const yaml_char_t *anchor, const yaml_char_t *tag, int implicit, + yaml_mapping_style_t style) +{ + yaml_mark_t mark = { 0, 0, 0 }; + yaml_char_t *anchor_copy = NULL; + yaml_char_t *tag_copy = NULL; + + assert(event); /* Non-NULL event object is expected. */ + + if (anchor) { + if (!yaml_check_utf8(anchor, strlen((char *)anchor))) goto error; + anchor_copy = yaml_strdup(anchor); + if (!anchor_copy) goto error; + } + + if (tag) { + if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error; + tag_copy = yaml_strdup(tag); + if (!tag_copy) goto error; + } + + MAPPING_START_EVENT_INIT(*event, anchor_copy, tag_copy, + implicit, style, mark, mark); + + return 1; + +error: + yaml_free(anchor_copy); + yaml_free(tag_copy); + + return 0; +} + +/* + * Create MAPPING-END. + */ + +YAML_DECLARE(int) +yaml_mapping_end_event_initialize(yaml_event_t *event) +{ + yaml_mark_t mark = { 0, 0, 0 }; + + assert(event); /* Non-NULL event object is expected. */ + + MAPPING_END_EVENT_INIT(*event, mark, mark); + + return 1; +} + +/* + * Destroy an event object. + */ + +YAML_DECLARE(void) +yaml_event_delete(yaml_event_t *event) +{ + yaml_tag_directive_t *tag_directive; + + assert(event); /* Non-NULL event object expected. */ + + switch (event->type) + { + case YAML_DOCUMENT_START_EVENT: + yaml_free(event->data.document_start.version_directive); + for (tag_directive = event->data.document_start.tag_directives.start; + tag_directive != event->data.document_start.tag_directives.end; + tag_directive++) { + yaml_free(tag_directive->handle); + yaml_free(tag_directive->prefix); + } + yaml_free(event->data.document_start.tag_directives.start); + break; + + case YAML_ALIAS_EVENT: + yaml_free(event->data.alias.anchor); + break; + + case YAML_SCALAR_EVENT: + yaml_free(event->data.scalar.anchor); + yaml_free(event->data.scalar.tag); + yaml_free(event->data.scalar.value); + break; + + case YAML_SEQUENCE_START_EVENT: + yaml_free(event->data.sequence_start.anchor); + yaml_free(event->data.sequence_start.tag); + break; + + case YAML_MAPPING_START_EVENT: + yaml_free(event->data.mapping_start.anchor); + yaml_free(event->data.mapping_start.tag); + break; + + default: + break; + } + + memset(event, 0, sizeof(yaml_event_t)); +} + +/* + * Create a document object. + */ + +YAML_DECLARE(int) +yaml_document_initialize(yaml_document_t *document, + yaml_version_directive_t *version_directive, + yaml_tag_directive_t *tag_directives_start, + yaml_tag_directive_t *tag_directives_end, + int start_implicit, int end_implicit) +{ + struct { + yaml_error_type_t error; + } context; + struct { + yaml_node_t *start; + yaml_node_t *end; + yaml_node_t *top; + } nodes = { NULL, NULL, NULL }; + yaml_version_directive_t *version_directive_copy = NULL; + struct { + yaml_tag_directive_t *start; + yaml_tag_directive_t *end; + yaml_tag_directive_t *top; + } tag_directives_copy = { NULL, NULL, NULL }; + yaml_tag_directive_t value = { NULL, NULL }; + yaml_mark_t mark = { 0, 0, 0 }; + + assert(document); /* Non-NULL document object is expected. */ + assert((tag_directives_start && tag_directives_end) || + (tag_directives_start == tag_directives_end)); + /* Valid tag directives are expected. */ + + if (!STACK_INIT(&context, nodes, yaml_node_t*)) goto error; + + if (version_directive) { + version_directive_copy = YAML_MALLOC_STATIC(yaml_version_directive_t); + if (!version_directive_copy) goto error; + version_directive_copy->major = version_directive->major; + version_directive_copy->minor = version_directive->minor; + } + + if (tag_directives_start != tag_directives_end) { + yaml_tag_directive_t *tag_directive; + if (!STACK_INIT(&context, tag_directives_copy, yaml_tag_directive_t*)) + goto error; + for (tag_directive = tag_directives_start; + tag_directive != tag_directives_end; tag_directive ++) { + assert(tag_directive->handle); + assert(tag_directive->prefix); + if (!yaml_check_utf8(tag_directive->handle, + strlen((char *)tag_directive->handle))) + goto error; + if (!yaml_check_utf8(tag_directive->prefix, + strlen((char *)tag_directive->prefix))) + goto error; + value.handle = yaml_strdup(tag_directive->handle); + value.prefix = yaml_strdup(tag_directive->prefix); + if (!value.handle || !value.prefix) goto error; + if (!PUSH(&context, tag_directives_copy, value)) + goto error; + value.handle = NULL; + value.prefix = NULL; + } + } + + DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, + tag_directives_copy.start, tag_directives_copy.top, + start_implicit, end_implicit, mark, mark); + + return 1; + +error: + STACK_DEL(&context, nodes); + yaml_free(version_directive_copy); + while (!STACK_EMPTY(&context, tag_directives_copy)) { + yaml_tag_directive_t value = POP(&context, tag_directives_copy); + yaml_free(value.handle); + yaml_free(value.prefix); + } + STACK_DEL(&context, tag_directives_copy); + yaml_free(value.handle); + yaml_free(value.prefix); + + return 0; +} + +/* + * Destroy a document object. + */ + +YAML_DECLARE(void) +yaml_document_delete(yaml_document_t *document) +{ + yaml_tag_directive_t *tag_directive; + + assert(document); /* Non-NULL document object is expected. */ + + while (!STACK_EMPTY(&context, document->nodes)) { + yaml_node_t node = POP(&context, document->nodes); + yaml_free(node.tag); + switch (node.type) { + case YAML_SCALAR_NODE: + yaml_free(node.data.scalar.value); + break; + case YAML_SEQUENCE_NODE: + STACK_DEL(&context, node.data.sequence.items); + break; + case YAML_MAPPING_NODE: + STACK_DEL(&context, node.data.mapping.pairs); + break; + default: + assert(0); /* Should not happen. */ + } + } + STACK_DEL(&context, document->nodes); + + yaml_free(document->version_directive); + for (tag_directive = document->tag_directives.start; + tag_directive != document->tag_directives.end; + tag_directive++) { + yaml_free(tag_directive->handle); + yaml_free(tag_directive->prefix); + } + yaml_free(document->tag_directives.start); + + memset(document, 0, sizeof(yaml_document_t)); +} + +/** + * Get a document node. + */ + +YAML_DECLARE(yaml_node_t *) +yaml_document_get_node(yaml_document_t *document, int index) +{ + assert(document); /* Non-NULL document object is expected. */ + + if (index > 0 && document->nodes.start + index <= document->nodes.top) { + return document->nodes.start + index - 1; + } + return NULL; +} + +/** + * Get the root object. + */ + +YAML_DECLARE(yaml_node_t *) +yaml_document_get_root_node(yaml_document_t *document) +{ + assert(document); /* Non-NULL document object is expected. */ + + if (document->nodes.top != document->nodes.start) { + return document->nodes.start; + } + return NULL; +} + +/* + * Add a scalar node to a document. + */ + +YAML_DECLARE(int) +yaml_document_add_scalar(yaml_document_t *document, + const yaml_char_t *tag, const yaml_char_t *value, int length, + yaml_scalar_style_t style) +{ + struct { + yaml_error_type_t error; + } context; + yaml_mark_t mark = { 0, 0, 0 }; + yaml_char_t *tag_copy = NULL; + yaml_char_t *value_copy = NULL; + yaml_node_t node; + + assert(document); /* Non-NULL document object is expected. */ + assert(value); /* Non-NULL value is expected. */ + + if (!tag) { + tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG; + } + + if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error; + tag_copy = yaml_strdup(tag); + if (!tag_copy) goto error; + + if (length < 0) { + length = (int)strlen((char *)value); + } + + if (!yaml_check_utf8(value, length)) goto error; + value_copy = YAML_MALLOC(length+1); + if (!value_copy) goto error; + memcpy(value_copy, value, length); + value_copy[length] = '\0'; + + SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark); + if (!PUSH(&context, document->nodes, node)) goto error; + + return (int)(document->nodes.top - document->nodes.start); + +error: + yaml_free(tag_copy); + yaml_free(value_copy); + + return 0; +} + +/* + * Add a sequence node to a document. + */ + +YAML_DECLARE(int) +yaml_document_add_sequence(yaml_document_t *document, + const yaml_char_t *tag, yaml_sequence_style_t style) +{ + struct { + yaml_error_type_t error; + } context; + yaml_mark_t mark = { 0, 0, 0 }; + yaml_char_t *tag_copy = NULL; + struct { + yaml_node_item_t *start; + yaml_node_item_t *end; + yaml_node_item_t *top; + } items = { NULL, NULL, NULL }; + yaml_node_t node; + + assert(document); /* Non-NULL document object is expected. */ + + if (!tag) { + tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG; + } + + if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error; + tag_copy = yaml_strdup(tag); + if (!tag_copy) goto error; + + if (!STACK_INIT(&context, items, yaml_node_item_t*)) goto error; + + SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, + style, mark, mark); + if (!PUSH(&context, document->nodes, node)) goto error; + + return (int)(document->nodes.top - document->nodes.start); + +error: + STACK_DEL(&context, items); + yaml_free(tag_copy); + + return 0; +} + +/* + * Add a mapping node to a document. + */ + +YAML_DECLARE(int) +yaml_document_add_mapping(yaml_document_t *document, + const yaml_char_t *tag, yaml_mapping_style_t style) +{ + struct { + yaml_error_type_t error; + } context; + yaml_mark_t mark = { 0, 0, 0 }; + yaml_char_t *tag_copy = NULL; + struct { + yaml_node_pair_t *start; + yaml_node_pair_t *end; + yaml_node_pair_t *top; + } pairs = { NULL, NULL, NULL }; + yaml_node_t node; + + assert(document); /* Non-NULL document object is expected. */ + + if (!tag) { + tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG; + } + + if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error; + tag_copy = yaml_strdup(tag); + if (!tag_copy) goto error; + + if (!STACK_INIT(&context, pairs, yaml_node_pair_t*)) goto error; + + MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, + style, mark, mark); + if (!PUSH(&context, document->nodes, node)) goto error; + + return (int)(document->nodes.top - document->nodes.start); + +error: + STACK_DEL(&context, pairs); + yaml_free(tag_copy); + + return 0; +} + +/* + * Append an item to a sequence node. + */ + +YAML_DECLARE(int) +yaml_document_append_sequence_item(yaml_document_t *document, + int sequence, int item) +{ + struct { + yaml_error_type_t error; + } context; + + assert(document); /* Non-NULL document is required. */ + assert(sequence > 0 + && document->nodes.start + sequence <= document->nodes.top); + /* Valid sequence id is required. */ + assert(document->nodes.start[sequence-1].type == YAML_SEQUENCE_NODE); + /* A sequence node is required. */ + assert(item > 0 && document->nodes.start + item <= document->nodes.top); + /* Valid item id is required. */ + + if (!PUSH(&context, + document->nodes.start[sequence-1].data.sequence.items, item)) + return 0; + + return 1; +} + +/* + * Append a pair of a key and a value to a mapping node. + */ + +YAML_DECLARE(int) +yaml_document_append_mapping_pair(yaml_document_t *document, + int mapping, int key, int value) +{ + struct { + yaml_error_type_t error; + } context; + + yaml_node_pair_t pair; + + assert(document); /* Non-NULL document is required. */ + assert(mapping > 0 + && document->nodes.start + mapping <= document->nodes.top); + /* Valid mapping id is required. */ + assert(document->nodes.start[mapping-1].type == YAML_MAPPING_NODE); + /* A mapping node is required. */ + assert(key > 0 && document->nodes.start + key <= document->nodes.top); + /* Valid key id is required. */ + assert(value > 0 && document->nodes.start + value <= document->nodes.top); + /* Valid value id is required. */ + + pair.key = key; + pair.value = value; + + if (!PUSH(&context, + document->nodes.start[mapping-1].data.mapping.pairs, pair)) + return 0; + + return 1; +} + + diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/config.h b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/config.h new file mode 100644 index 0000000..4b1150f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/config.h @@ -0,0 +1,80 @@ +/* include/config.h. Generated from config.h.in by configure. */ +/* include/config.h.in. Generated from configure.ac by autoheader. */ + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to the sub-directory where libtool stores uninstalled libraries. */ +#define LT_OBJDIR ".libs/" + +/* Name of package */ +#define PACKAGE "yaml" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "https://github.com/yaml/libyaml/issues/new" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "yaml" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "yaml 0.2.5" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "yaml" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "0.2.5" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Version number of package */ +#define VERSION "0.2.5" + +/* Define the major version number. */ +#define YAML_VERSION_MAJOR 0 + +/* Define the minor version number. */ +#define YAML_VERSION_MINOR 2 + +/* Define the patch version number. */ +#define YAML_VERSION_PATCH 5 + +/* Define the version string. */ +#define YAML_VERSION_STRING "0.2.5" + +/* Define to empty if `const' does not conform to ANSI C. */ +/* #undef const */ + +/* Define to `unsigned int' if does not define. */ +/* #undef size_t */ diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/dumper.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/dumper.c new file mode 100644 index 0000000..1fe940b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/dumper.c @@ -0,0 +1,394 @@ + +#include "yaml_private.h" + +/* + * API functions. + */ + +YAML_DECLARE(int) +yaml_emitter_open(yaml_emitter_t *emitter); + +YAML_DECLARE(int) +yaml_emitter_close(yaml_emitter_t *emitter); + +YAML_DECLARE(int) +yaml_emitter_dump(yaml_emitter_t *emitter, yaml_document_t *document); + +/* + * Clean up functions. + */ + +static void +yaml_emitter_delete_document_and_anchors(yaml_emitter_t *emitter); + +/* + * Anchor functions. + */ + +static void +yaml_emitter_anchor_node(yaml_emitter_t *emitter, int index); + +static yaml_char_t * +yaml_emitter_generate_anchor(yaml_emitter_t *emitter, int anchor_id); + + +/* + * Serialize functions. + */ + +static int +yaml_emitter_dump_node(yaml_emitter_t *emitter, int index); + +static int +yaml_emitter_dump_alias(yaml_emitter_t *emitter, yaml_char_t *anchor); + +static int +yaml_emitter_dump_scalar(yaml_emitter_t *emitter, yaml_node_t *node, + yaml_char_t *anchor); + +static int +yaml_emitter_dump_sequence(yaml_emitter_t *emitter, yaml_node_t *node, + yaml_char_t *anchor); + +static int +yaml_emitter_dump_mapping(yaml_emitter_t *emitter, yaml_node_t *node, + yaml_char_t *anchor); + +/* + * Issue a STREAM-START event. + */ + +YAML_DECLARE(int) +yaml_emitter_open(yaml_emitter_t *emitter) +{ + yaml_event_t event; + yaml_mark_t mark = { 0, 0, 0 }; + + assert(emitter); /* Non-NULL emitter object is required. */ + assert(!emitter->opened); /* Emitter should not be opened yet. */ + + STREAM_START_EVENT_INIT(event, YAML_ANY_ENCODING, mark, mark); + + if (!yaml_emitter_emit(emitter, &event)) { + return 0; + } + + emitter->opened = 1; + + return 1; +} + +/* + * Issue a STREAM-END event. + */ + +YAML_DECLARE(int) +yaml_emitter_close(yaml_emitter_t *emitter) +{ + yaml_event_t event; + yaml_mark_t mark = { 0, 0, 0 }; + + assert(emitter); /* Non-NULL emitter object is required. */ + assert(emitter->opened); /* Emitter should be opened. */ + + if (emitter->closed) return 1; + + STREAM_END_EVENT_INIT(event, mark, mark); + + if (!yaml_emitter_emit(emitter, &event)) { + return 0; + } + + emitter->closed = 1; + + return 1; +} + +/* + * Dump a YAML document. + */ + +YAML_DECLARE(int) +yaml_emitter_dump(yaml_emitter_t *emitter, yaml_document_t *document) +{ + yaml_event_t event; + yaml_mark_t mark = { 0, 0, 0 }; + + assert(emitter); /* Non-NULL emitter object is required. */ + assert(document); /* Non-NULL emitter object is expected. */ + + emitter->document = document; + + if (!emitter->opened) { + if (!yaml_emitter_open(emitter)) goto error; + } + + if (STACK_EMPTY(emitter, document->nodes)) { + if (!yaml_emitter_close(emitter)) goto error; + yaml_emitter_delete_document_and_anchors(emitter); + return 1; + } + + assert(emitter->opened); /* Emitter should be opened. */ + + emitter->anchors = (yaml_anchors_t*)yaml_malloc(sizeof(*(emitter->anchors)) + * (document->nodes.top - document->nodes.start)); + if (!emitter->anchors) goto error; + memset(emitter->anchors, 0, sizeof(*(emitter->anchors)) + * (document->nodes.top - document->nodes.start)); + + DOCUMENT_START_EVENT_INIT(event, document->version_directive, + document->tag_directives.start, document->tag_directives.end, + document->start_implicit, mark, mark); + if (!yaml_emitter_emit(emitter, &event)) goto error; + + yaml_emitter_anchor_node(emitter, 1); + if (!yaml_emitter_dump_node(emitter, 1)) goto error; + + DOCUMENT_END_EVENT_INIT(event, document->end_implicit, mark, mark); + if (!yaml_emitter_emit(emitter, &event)) goto error; + + yaml_emitter_delete_document_and_anchors(emitter); + + return 1; + +error: + + yaml_emitter_delete_document_and_anchors(emitter); + + return 0; +} + +/* + * Clean up the emitter object after a document is dumped. + */ + +static void +yaml_emitter_delete_document_and_anchors(yaml_emitter_t *emitter) +{ + int index; + + if (!emitter->anchors) { + yaml_document_delete(emitter->document); + emitter->document = NULL; + return; + } + + for (index = 0; emitter->document->nodes.start + index + < emitter->document->nodes.top; index ++) { + yaml_node_t node = emitter->document->nodes.start[index]; + if (!emitter->anchors[index].serialized) { + yaml_free(node.tag); + if (node.type == YAML_SCALAR_NODE) { + yaml_free(node.data.scalar.value); + } + } + if (node.type == YAML_SEQUENCE_NODE) { + STACK_DEL(emitter, node.data.sequence.items); + } + if (node.type == YAML_MAPPING_NODE) { + STACK_DEL(emitter, node.data.mapping.pairs); + } + } + + STACK_DEL(emitter, emitter->document->nodes); + yaml_free(emitter->anchors); + + emitter->anchors = NULL; + emitter->last_anchor_id = 0; + emitter->document = NULL; +} + +/* + * Check the references of a node and assign the anchor id if needed. + */ + +static void +yaml_emitter_anchor_node(yaml_emitter_t *emitter, int index) +{ + yaml_node_t *node = emitter->document->nodes.start + index - 1; + yaml_node_item_t *item; + yaml_node_pair_t *pair; + + emitter->anchors[index-1].references ++; + + if (emitter->anchors[index-1].references == 1) { + switch (node->type) { + case YAML_SEQUENCE_NODE: + for (item = node->data.sequence.items.start; + item < node->data.sequence.items.top; item ++) { + yaml_emitter_anchor_node(emitter, *item); + } + break; + case YAML_MAPPING_NODE: + for (pair = node->data.mapping.pairs.start; + pair < node->data.mapping.pairs.top; pair ++) { + yaml_emitter_anchor_node(emitter, pair->key); + yaml_emitter_anchor_node(emitter, pair->value); + } + break; + default: + break; + } + } + + else if (emitter->anchors[index-1].references == 2) { + emitter->anchors[index-1].anchor = (++ emitter->last_anchor_id); + } +} + +/* + * Generate a textual representation for an anchor. + */ + +#define ANCHOR_TEMPLATE "id%03d" +#define ANCHOR_TEMPLATE_LENGTH 16 + +static yaml_char_t * +yaml_emitter_generate_anchor(SHIM(yaml_emitter_t *emitter), int anchor_id) +{ + yaml_char_t *anchor = YAML_MALLOC(ANCHOR_TEMPLATE_LENGTH); + + if (!anchor) return NULL; + + sprintf((char *)anchor, ANCHOR_TEMPLATE, anchor_id); + + return anchor; +} + +/* + * Serialize a node. + */ + +static int +yaml_emitter_dump_node(yaml_emitter_t *emitter, int index) +{ + yaml_node_t *node = emitter->document->nodes.start + index - 1; + int anchor_id = emitter->anchors[index-1].anchor; + yaml_char_t *anchor = NULL; + + if (anchor_id) { + anchor = yaml_emitter_generate_anchor(emitter, anchor_id); + if (!anchor) return 0; + } + + if (emitter->anchors[index-1].serialized) { + return yaml_emitter_dump_alias(emitter, anchor); + } + + emitter->anchors[index-1].serialized = 1; + + switch (node->type) { + case YAML_SCALAR_NODE: + return yaml_emitter_dump_scalar(emitter, node, anchor); + case YAML_SEQUENCE_NODE: + return yaml_emitter_dump_sequence(emitter, node, anchor); + case YAML_MAPPING_NODE: + return yaml_emitter_dump_mapping(emitter, node, anchor); + default: + assert(0); /* Could not happen. */ + break; + } + + return 0; /* Could not happen. */ +} + +/* + * Serialize an alias. + */ + +static int +yaml_emitter_dump_alias(yaml_emitter_t *emitter, yaml_char_t *anchor) +{ + yaml_event_t event; + yaml_mark_t mark = { 0, 0, 0 }; + + ALIAS_EVENT_INIT(event, anchor, mark, mark); + + return yaml_emitter_emit(emitter, &event); +} + +/* + * Serialize a scalar. + */ + +static int +yaml_emitter_dump_scalar(yaml_emitter_t *emitter, yaml_node_t *node, + yaml_char_t *anchor) +{ + yaml_event_t event; + yaml_mark_t mark = { 0, 0, 0 }; + + int plain_implicit = (strcmp((char *)node->tag, + YAML_DEFAULT_SCALAR_TAG) == 0); + int quoted_implicit = (strcmp((char *)node->tag, + YAML_DEFAULT_SCALAR_TAG) == 0); + + SCALAR_EVENT_INIT(event, anchor, node->tag, node->data.scalar.value, + node->data.scalar.length, plain_implicit, quoted_implicit, + node->data.scalar.style, mark, mark); + + return yaml_emitter_emit(emitter, &event); +} + +/* + * Serialize a sequence. + */ + +static int +yaml_emitter_dump_sequence(yaml_emitter_t *emitter, yaml_node_t *node, + yaml_char_t *anchor) +{ + yaml_event_t event; + yaml_mark_t mark = { 0, 0, 0 }; + + int implicit = (strcmp((char *)node->tag, YAML_DEFAULT_SEQUENCE_TAG) == 0); + + yaml_node_item_t *item; + + SEQUENCE_START_EVENT_INIT(event, anchor, node->tag, implicit, + node->data.sequence.style, mark, mark); + if (!yaml_emitter_emit(emitter, &event)) return 0; + + for (item = node->data.sequence.items.start; + item < node->data.sequence.items.top; item ++) { + if (!yaml_emitter_dump_node(emitter, *item)) return 0; + } + + SEQUENCE_END_EVENT_INIT(event, mark, mark); + if (!yaml_emitter_emit(emitter, &event)) return 0; + + return 1; +} + +/* + * Serialize a mapping. + */ + +static int +yaml_emitter_dump_mapping(yaml_emitter_t *emitter, yaml_node_t *node, + yaml_char_t *anchor) +{ + yaml_event_t event; + yaml_mark_t mark = { 0, 0, 0 }; + + int implicit = (strcmp((char *)node->tag, YAML_DEFAULT_MAPPING_TAG) == 0); + + yaml_node_pair_t *pair; + + MAPPING_START_EVENT_INIT(event, anchor, node->tag, implicit, + node->data.mapping.style, mark, mark); + if (!yaml_emitter_emit(emitter, &event)) return 0; + + for (pair = node->data.mapping.pairs.start; + pair < node->data.mapping.pairs.top; pair ++) { + if (!yaml_emitter_dump_node(emitter, pair->key)) return 0; + if (!yaml_emitter_dump_node(emitter, pair->value)) return 0; + } + + MAPPING_END_EVENT_INIT(event, mark, mark); + if (!yaml_emitter_emit(emitter, &event)) return 0; + + return 1; +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/emitter.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/emitter.c new file mode 100644 index 0000000..796294c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/emitter.c @@ -0,0 +1,2358 @@ + +#include "yaml_private.h" + +/* + * Flush the buffer if needed. + */ + +#define FLUSH(emitter) \ + ((emitter->buffer.pointer+5 < emitter->buffer.end) \ + || yaml_emitter_flush(emitter)) + +/* + * Put a character to the output buffer. + */ + +#define PUT(emitter,value) \ + (FLUSH(emitter) \ + && (*(emitter->buffer.pointer++) = (yaml_char_t)(value), \ + emitter->column++, \ + 1)) + +/* + * Put a line break to the output buffer. + */ + +#define PUT_BREAK(emitter) \ + (FLUSH(emitter) ? \ + ((emitter->line_break == YAML_CR_BREAK ? \ + (*(emitter->buffer.pointer++) = (yaml_char_t) '\r') : \ + emitter->line_break == YAML_LN_BREAK ? \ + (*(emitter->buffer.pointer++) = (yaml_char_t) '\n') : \ + emitter->line_break == YAML_CRLN_BREAK ? \ + (*(emitter->buffer.pointer++) = (yaml_char_t) '\r', \ + *(emitter->buffer.pointer++) = (yaml_char_t) '\n') : 0), \ + emitter->column = 0, \ + emitter->line ++, \ + 1) : 0) + +/* + * Copy a character from a string into buffer. + */ + +#define WRITE(emitter,string) \ + (FLUSH(emitter) \ + && (COPY(emitter->buffer,string), \ + emitter->column ++, \ + 1)) + +/* + * Copy a line break character from a string into buffer. + */ + +#define WRITE_BREAK(emitter,string) \ + (FLUSH(emitter) \ + && (CHECK(string,'\n') ? \ + (PUT_BREAK(emitter), \ + string.pointer ++, \ + 1) : \ + (COPY(emitter->buffer,string), \ + emitter->column = 0, \ + emitter->line ++, \ + 1))) + +/* + * API functions. + */ + +YAML_DECLARE(int) +yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event); + +/* + * Utility functions. + */ + +static int +yaml_emitter_set_emitter_error(yaml_emitter_t *emitter, const char *problem); + +static int +yaml_emitter_need_more_events(yaml_emitter_t *emitter); + +static int +yaml_emitter_append_tag_directive(yaml_emitter_t *emitter, + yaml_tag_directive_t value, int allow_duplicates); + +static int +yaml_emitter_increase_indent(yaml_emitter_t *emitter, + int flow, int indentless); + +/* + * State functions. + */ + +static int +yaml_emitter_state_machine(yaml_emitter_t *emitter, yaml_event_t *event); + +static int +yaml_emitter_emit_stream_start(yaml_emitter_t *emitter, + yaml_event_t *event); + +static int +yaml_emitter_emit_document_start(yaml_emitter_t *emitter, + yaml_event_t *event, int first); + +static int +yaml_emitter_emit_document_content(yaml_emitter_t *emitter, + yaml_event_t *event); + +static int +yaml_emitter_emit_document_end(yaml_emitter_t *emitter, + yaml_event_t *event); + +static int +yaml_emitter_emit_flow_sequence_item(yaml_emitter_t *emitter, + yaml_event_t *event, int first); + +static int +yaml_emitter_emit_flow_mapping_key(yaml_emitter_t *emitter, + yaml_event_t *event, int first); + +static int +yaml_emitter_emit_flow_mapping_value(yaml_emitter_t *emitter, + yaml_event_t *event, int simple); + +static int +yaml_emitter_emit_block_sequence_item(yaml_emitter_t *emitter, + yaml_event_t *event, int first); + +static int +yaml_emitter_emit_block_mapping_key(yaml_emitter_t *emitter, + yaml_event_t *event, int first); + +static int +yaml_emitter_emit_block_mapping_value(yaml_emitter_t *emitter, + yaml_event_t *event, int simple); + +static int +yaml_emitter_emit_node(yaml_emitter_t *emitter, yaml_event_t *event, + int root, int sequence, int mapping, int simple_key); + +static int +yaml_emitter_emit_alias(yaml_emitter_t *emitter, yaml_event_t *event); + +static int +yaml_emitter_emit_scalar(yaml_emitter_t *emitter, yaml_event_t *event); + +static int +yaml_emitter_emit_sequence_start(yaml_emitter_t *emitter, yaml_event_t *event); + +static int +yaml_emitter_emit_mapping_start(yaml_emitter_t *emitter, yaml_event_t *event); + +/* + * Checkers. + */ + +static int +yaml_emitter_check_empty_document(yaml_emitter_t *emitter); + +static int +yaml_emitter_check_empty_sequence(yaml_emitter_t *emitter); + +static int +yaml_emitter_check_empty_mapping(yaml_emitter_t *emitter); + +static int +yaml_emitter_check_simple_key(yaml_emitter_t *emitter); + +static int +yaml_emitter_select_scalar_style(yaml_emitter_t *emitter, yaml_event_t *event); + +/* + * Processors. + */ + +static int +yaml_emitter_process_anchor(yaml_emitter_t *emitter); + +static int +yaml_emitter_process_tag(yaml_emitter_t *emitter); + +static int +yaml_emitter_process_scalar(yaml_emitter_t *emitter); + +/* + * Analyzers. + */ + +static int +yaml_emitter_analyze_version_directive(yaml_emitter_t *emitter, + yaml_version_directive_t version_directive); + +static int +yaml_emitter_analyze_tag_directive(yaml_emitter_t *emitter, + yaml_tag_directive_t tag_directive); + +static int +yaml_emitter_analyze_anchor(yaml_emitter_t *emitter, + yaml_char_t *anchor, int alias); + +static int +yaml_emitter_analyze_tag(yaml_emitter_t *emitter, + yaml_char_t *tag); + +static int +yaml_emitter_analyze_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length); + +static int +yaml_emitter_analyze_event(yaml_emitter_t *emitter, + yaml_event_t *event); + +/* + * Writers. + */ + +static int +yaml_emitter_write_bom(yaml_emitter_t *emitter); + +static int +yaml_emitter_write_indent(yaml_emitter_t *emitter); + +static int +yaml_emitter_write_indicator(yaml_emitter_t *emitter, + const char *indicator, int need_whitespace, + int is_whitespace, int is_indention); + +static int +yaml_emitter_write_anchor(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length); + +static int +yaml_emitter_write_tag_handle(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length); + +static int +yaml_emitter_write_tag_content(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length, int need_whitespace); + +static int +yaml_emitter_write_plain_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length, int allow_breaks); + +static int +yaml_emitter_write_single_quoted_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length, int allow_breaks); + +static int +yaml_emitter_write_double_quoted_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length, int allow_breaks); + +static int +yaml_emitter_write_block_scalar_hints(yaml_emitter_t *emitter, + yaml_string_t string); + +static int +yaml_emitter_write_literal_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length); + +static int +yaml_emitter_write_folded_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length); + +/* + * Set an emitter error and return 0. + */ + +static int +yaml_emitter_set_emitter_error(yaml_emitter_t *emitter, const char *problem) +{ + emitter->error = YAML_EMITTER_ERROR; + emitter->problem = problem; + + return 0; +} + +/* + * Emit an event. + */ + +YAML_DECLARE(int) +yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event) +{ + if (!ENQUEUE(emitter, emitter->events, *event)) { + yaml_event_delete(event); + return 0; + } + + while (!yaml_emitter_need_more_events(emitter)) { + if (!yaml_emitter_analyze_event(emitter, emitter->events.head)) + return 0; + if (!yaml_emitter_state_machine(emitter, emitter->events.head)) + return 0; + yaml_event_delete(&DEQUEUE(emitter, emitter->events)); + } + + return 1; +} + +/* + * Check if we need to accumulate more events before emitting. + * + * We accumulate extra + * - 1 event for DOCUMENT-START + * - 2 events for SEQUENCE-START + * - 3 events for MAPPING-START + */ + +static int +yaml_emitter_need_more_events(yaml_emitter_t *emitter) +{ + int level = 0; + int accumulate = 0; + yaml_event_t *event; + + if (QUEUE_EMPTY(emitter, emitter->events)) + return 1; + + switch (emitter->events.head->type) { + case YAML_DOCUMENT_START_EVENT: + accumulate = 1; + break; + case YAML_SEQUENCE_START_EVENT: + accumulate = 2; + break; + case YAML_MAPPING_START_EVENT: + accumulate = 3; + break; + default: + return 0; + } + + if (emitter->events.tail - emitter->events.head > accumulate) + return 0; + + for (event = emitter->events.head; event != emitter->events.tail; event ++) { + switch (event->type) { + case YAML_STREAM_START_EVENT: + case YAML_DOCUMENT_START_EVENT: + case YAML_SEQUENCE_START_EVENT: + case YAML_MAPPING_START_EVENT: + level += 1; + break; + case YAML_STREAM_END_EVENT: + case YAML_DOCUMENT_END_EVENT: + case YAML_SEQUENCE_END_EVENT: + case YAML_MAPPING_END_EVENT: + level -= 1; + break; + default: + break; + } + if (!level) + return 0; + } + + return 1; +} + +/* + * Append a directive to the directives stack. + */ + +static int +yaml_emitter_append_tag_directive(yaml_emitter_t *emitter, + yaml_tag_directive_t value, int allow_duplicates) +{ + yaml_tag_directive_t *tag_directive; + yaml_tag_directive_t copy = { NULL, NULL }; + + for (tag_directive = emitter->tag_directives.start; + tag_directive != emitter->tag_directives.top; tag_directive ++) { + if (strcmp((char *)value.handle, (char *)tag_directive->handle) == 0) { + if (allow_duplicates) + return 1; + return yaml_emitter_set_emitter_error(emitter, + "duplicate %TAG directive"); + } + } + + copy.handle = yaml_strdup(value.handle); + copy.prefix = yaml_strdup(value.prefix); + if (!copy.handle || !copy.prefix) { + emitter->error = YAML_MEMORY_ERROR; + goto error; + } + + if (!PUSH(emitter, emitter->tag_directives, copy)) + goto error; + + return 1; + +error: + yaml_free(copy.handle); + yaml_free(copy.prefix); + return 0; +} + +/* + * Increase the indentation level. + */ + +static int +yaml_emitter_increase_indent(yaml_emitter_t *emitter, + int flow, int indentless) +{ + if (!PUSH(emitter, emitter->indents, emitter->indent)) + return 0; + + if (emitter->indent < 0) { + emitter->indent = flow ? emitter->best_indent : 0; + } + else if (!indentless) { + emitter->indent += emitter->best_indent; + } + + return 1; +} + +/* + * State dispatcher. + */ + +static int +yaml_emitter_state_machine(yaml_emitter_t *emitter, yaml_event_t *event) +{ + switch (emitter->state) + { + case YAML_EMIT_STREAM_START_STATE: + return yaml_emitter_emit_stream_start(emitter, event); + + case YAML_EMIT_FIRST_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, 1); + + case YAML_EMIT_DOCUMENT_START_STATE: + return yaml_emitter_emit_document_start(emitter, event, 0); + + case YAML_EMIT_DOCUMENT_CONTENT_STATE: + return yaml_emitter_emit_document_content(emitter, event); + + case YAML_EMIT_DOCUMENT_END_STATE: + return yaml_emitter_emit_document_end(emitter, event); + + case YAML_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, 1); + + case YAML_EMIT_FLOW_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, 0); + + case YAML_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, 1); + + case YAML_EMIT_FLOW_MAPPING_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, 0); + + case YAML_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, 1); + + case YAML_EMIT_FLOW_MAPPING_VALUE_STATE: + return yaml_emitter_emit_flow_mapping_value(emitter, event, 0); + + case YAML_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, 1); + + case YAML_EMIT_BLOCK_SEQUENCE_ITEM_STATE: + return yaml_emitter_emit_block_sequence_item(emitter, event, 0); + + case YAML_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, 1); + + case YAML_EMIT_BLOCK_MAPPING_KEY_STATE: + return yaml_emitter_emit_block_mapping_key(emitter, event, 0); + + case YAML_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, 1); + + case YAML_EMIT_BLOCK_MAPPING_VALUE_STATE: + return yaml_emitter_emit_block_mapping_value(emitter, event, 0); + + case YAML_EMIT_END_STATE: + return yaml_emitter_set_emitter_error(emitter, + "expected nothing after STREAM-END"); + + default: + assert(1); /* Invalid state. */ + } + + return 0; +} + +/* + * Expect STREAM-START. + */ + +static int +yaml_emitter_emit_stream_start(yaml_emitter_t *emitter, + yaml_event_t *event) +{ + emitter->open_ended = 0; + if (event->type == YAML_STREAM_START_EVENT) + { + if (!emitter->encoding) { + emitter->encoding = event->data.stream_start.encoding; + } + + if (!emitter->encoding) { + emitter->encoding = YAML_UTF8_ENCODING; + } + + if (emitter->best_indent < 2 || emitter->best_indent > 9) { + emitter->best_indent = 2; + } + + if (emitter->best_width >= 0 + && emitter->best_width <= emitter->best_indent*2) { + emitter->best_width = 80; + } + + if (emitter->best_width < 0) { + emitter->best_width = INT_MAX; + } + + if (!emitter->line_break) { + emitter->line_break = YAML_LN_BREAK; + } + + emitter->indent = -1; + + emitter->line = 0; + emitter->column = 0; + emitter->whitespace = 1; + emitter->indention = 1; + + if (emitter->encoding != YAML_UTF8_ENCODING) { + if (!yaml_emitter_write_bom(emitter)) + return 0; + } + + emitter->state = YAML_EMIT_FIRST_DOCUMENT_START_STATE; + + return 1; + } + + return yaml_emitter_set_emitter_error(emitter, + "expected STREAM-START"); +} + +/* + * Expect DOCUMENT-START or STREAM-END. + */ + +static int +yaml_emitter_emit_document_start(yaml_emitter_t *emitter, + yaml_event_t *event, int first) +{ + if (event->type == YAML_DOCUMENT_START_EVENT) + { + yaml_tag_directive_t default_tag_directives[] = { + {(yaml_char_t *)"!", (yaml_char_t *)"!"}, + {(yaml_char_t *)"!!", (yaml_char_t *)"tag:yaml.org,2002:"}, + {NULL, NULL} + }; + yaml_tag_directive_t *tag_directive; + int implicit; + + if (event->data.document_start.version_directive) { + if (!yaml_emitter_analyze_version_directive(emitter, + *event->data.document_start.version_directive)) + return 0; + } + + for (tag_directive = event->data.document_start.tag_directives.start; + tag_directive != event->data.document_start.tag_directives.end; + tag_directive ++) { + if (!yaml_emitter_analyze_tag_directive(emitter, *tag_directive)) + return 0; + if (!yaml_emitter_append_tag_directive(emitter, *tag_directive, 0)) + return 0; + } + + for (tag_directive = default_tag_directives; + tag_directive->handle; tag_directive ++) { + if (!yaml_emitter_append_tag_directive(emitter, *tag_directive, 1)) + return 0; + } + + implicit = event->data.document_start.implicit; + if (!first || emitter->canonical) { + implicit = 0; + } + + if ((event->data.document_start.version_directive || + (event->data.document_start.tag_directives.start + != event->data.document_start.tag_directives.end)) && + emitter->open_ended) + { + if (!yaml_emitter_write_indicator(emitter, "...", 1, 0, 0)) + return 0; + if (!yaml_emitter_write_indent(emitter)) + return 0; + } + emitter->open_ended = 0; + + if (event->data.document_start.version_directive) { + implicit = 0; + if (!yaml_emitter_write_indicator(emitter, "%YAML", 1, 0, 0)) + return 0; + if (event->data.document_start.version_directive->minor == 1) { + if (!yaml_emitter_write_indicator(emitter, "1.1", 1, 0, 0)) + return 0; + } + else { + if (!yaml_emitter_write_indicator(emitter, "1.2", 1, 0, 0)) + return 0; + } + if (!yaml_emitter_write_indent(emitter)) + return 0; + } + + if (event->data.document_start.tag_directives.start + != event->data.document_start.tag_directives.end) { + implicit = 0; + for (tag_directive = event->data.document_start.tag_directives.start; + tag_directive != event->data.document_start.tag_directives.end; + tag_directive ++) { + if (!yaml_emitter_write_indicator(emitter, "%TAG", 1, 0, 0)) + return 0; + if (!yaml_emitter_write_tag_handle(emitter, tag_directive->handle, + strlen((char *)tag_directive->handle))) + return 0; + if (!yaml_emitter_write_tag_content(emitter, tag_directive->prefix, + strlen((char *)tag_directive->prefix), 1)) + return 0; + if (!yaml_emitter_write_indent(emitter)) + return 0; + } + } + + if (yaml_emitter_check_empty_document(emitter)) { + implicit = 0; + } + + if (!implicit) { + if (!yaml_emitter_write_indent(emitter)) + return 0; + if (!yaml_emitter_write_indicator(emitter, "---", 1, 0, 0)) + return 0; + if (emitter->canonical) { + if (!yaml_emitter_write_indent(emitter)) + return 0; + } + } + + emitter->state = YAML_EMIT_DOCUMENT_CONTENT_STATE; + + emitter->open_ended = 0; + return 1; + } + + else if (event->type == YAML_STREAM_END_EVENT) + { + + /** + * This can happen if a block scalar with trailing empty lines + * is at the end of the stream + */ + if (emitter->open_ended == 2) + { + if (!yaml_emitter_write_indicator(emitter, "...", 1, 0, 0)) + return 0; + emitter->open_ended = 0; + if (!yaml_emitter_write_indent(emitter)) + return 0; + } + if (!yaml_emitter_flush(emitter)) + return 0; + + emitter->state = YAML_EMIT_END_STATE; + + return 1; + } + + return yaml_emitter_set_emitter_error(emitter, + "expected DOCUMENT-START or STREAM-END"); +} + +/* + * Expect the root node. + */ + +static int +yaml_emitter_emit_document_content(yaml_emitter_t *emitter, + yaml_event_t *event) +{ + if (!PUSH(emitter, emitter->states, YAML_EMIT_DOCUMENT_END_STATE)) + return 0; + + return yaml_emitter_emit_node(emitter, event, 1, 0, 0, 0); +} + +/* + * Expect DOCUMENT-END. + */ + +static int +yaml_emitter_emit_document_end(yaml_emitter_t *emitter, + yaml_event_t *event) +{ + if (event->type == YAML_DOCUMENT_END_EVENT) + { + if (!yaml_emitter_write_indent(emitter)) + return 0; + if (!event->data.document_end.implicit) { + if (!yaml_emitter_write_indicator(emitter, "...", 1, 0, 0)) + return 0; + emitter->open_ended = 0; + if (!yaml_emitter_write_indent(emitter)) + return 0; + } + else if (!emitter->open_ended) + emitter->open_ended = 1; + if (!yaml_emitter_flush(emitter)) + return 0; + + emitter->state = YAML_EMIT_DOCUMENT_START_STATE; + + while (!STACK_EMPTY(emitter, emitter->tag_directives)) { + yaml_tag_directive_t tag_directive = POP(emitter, + emitter->tag_directives); + yaml_free(tag_directive.handle); + yaml_free(tag_directive.prefix); + } + + return 1; + } + + return yaml_emitter_set_emitter_error(emitter, + "expected DOCUMENT-END"); +} + +/* + * + * Expect a flow item node. + */ + +static int +yaml_emitter_emit_flow_sequence_item(yaml_emitter_t *emitter, + yaml_event_t *event, int first) +{ + if (first) + { + if (!yaml_emitter_write_indicator(emitter, "[", 1, 1, 0)) + return 0; + if (!yaml_emitter_increase_indent(emitter, 1, 0)) + return 0; + emitter->flow_level ++; + } + + if (event->type == YAML_SEQUENCE_END_EVENT) + { + emitter->flow_level --; + emitter->indent = POP(emitter, emitter->indents); + if (emitter->canonical && !first) { + if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0)) + return 0; + if (!yaml_emitter_write_indent(emitter)) + return 0; + } + if (!yaml_emitter_write_indicator(emitter, "]", 0, 0, 0)) + return 0; + emitter->state = POP(emitter, emitter->states); + + return 1; + } + + if (!first) { + if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0)) + return 0; + } + + if (emitter->canonical || emitter->column > emitter->best_width) { + if (!yaml_emitter_write_indent(emitter)) + return 0; + } + if (!PUSH(emitter, emitter->states, YAML_EMIT_FLOW_SEQUENCE_ITEM_STATE)) + return 0; + + return yaml_emitter_emit_node(emitter, event, 0, 1, 0, 0); +} + +/* + * Expect a flow key node. + */ + +static int +yaml_emitter_emit_flow_mapping_key(yaml_emitter_t *emitter, + yaml_event_t *event, int first) +{ + if (first) + { + if (!yaml_emitter_write_indicator(emitter, "{", 1, 1, 0)) + return 0; + if (!yaml_emitter_increase_indent(emitter, 1, 0)) + return 0; + emitter->flow_level ++; + } + + if (event->type == YAML_MAPPING_END_EVENT) + { + emitter->flow_level --; + emitter->indent = POP(emitter, emitter->indents); + if (emitter->canonical && !first) { + if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0)) + return 0; + if (!yaml_emitter_write_indent(emitter)) + return 0; + } + if (!yaml_emitter_write_indicator(emitter, "}", 0, 0, 0)) + return 0; + emitter->state = POP(emitter, emitter->states); + + return 1; + } + + if (!first) { + if (!yaml_emitter_write_indicator(emitter, ",", 0, 0, 0)) + return 0; + } + if (emitter->canonical || emitter->column > emitter->best_width) { + if (!yaml_emitter_write_indent(emitter)) + return 0; + } + + if (!emitter->canonical && yaml_emitter_check_simple_key(emitter)) + { + if (!PUSH(emitter, emitter->states, + YAML_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE)) + return 0; + + return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 1); + } + else + { + if (!yaml_emitter_write_indicator(emitter, "?", 1, 0, 0)) + return 0; + if (!PUSH(emitter, emitter->states, + YAML_EMIT_FLOW_MAPPING_VALUE_STATE)) + return 0; + + return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0); + } +} + +/* + * Expect a flow value node. + */ + +static int +yaml_emitter_emit_flow_mapping_value(yaml_emitter_t *emitter, + yaml_event_t *event, int simple) +{ + if (simple) { + if (!yaml_emitter_write_indicator(emitter, ":", 0, 0, 0)) + return 0; + } + else { + if (emitter->canonical || emitter->column > emitter->best_width) { + if (!yaml_emitter_write_indent(emitter)) + return 0; + } + if (!yaml_emitter_write_indicator(emitter, ":", 1, 0, 0)) + return 0; + } + if (!PUSH(emitter, emitter->states, YAML_EMIT_FLOW_MAPPING_KEY_STATE)) + return 0; + return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0); +} + +/* + * Expect a block item node. + */ + +static int +yaml_emitter_emit_block_sequence_item(yaml_emitter_t *emitter, + yaml_event_t *event, int first) +{ + if (first) + { + if (!yaml_emitter_increase_indent(emitter, 0, + (emitter->mapping_context && !emitter->indention))) + return 0; + } + + if (event->type == YAML_SEQUENCE_END_EVENT) + { + emitter->indent = POP(emitter, emitter->indents); + emitter->state = POP(emitter, emitter->states); + + return 1; + } + + if (!yaml_emitter_write_indent(emitter)) + return 0; + if (!yaml_emitter_write_indicator(emitter, "-", 1, 0, 1)) + return 0; + if (!PUSH(emitter, emitter->states, + YAML_EMIT_BLOCK_SEQUENCE_ITEM_STATE)) + return 0; + + return yaml_emitter_emit_node(emitter, event, 0, 1, 0, 0); +} + +/* + * Expect a block key node. + */ + +static int +yaml_emitter_emit_block_mapping_key(yaml_emitter_t *emitter, + yaml_event_t *event, int first) +{ + if (first) + { + if (!yaml_emitter_increase_indent(emitter, 0, 0)) + return 0; + } + + if (event->type == YAML_MAPPING_END_EVENT) + { + emitter->indent = POP(emitter, emitter->indents); + emitter->state = POP(emitter, emitter->states); + + return 1; + } + + if (!yaml_emitter_write_indent(emitter)) + return 0; + + if (yaml_emitter_check_simple_key(emitter)) + { + if (!PUSH(emitter, emitter->states, + YAML_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE)) + return 0; + + return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 1); + } + else + { + if (!yaml_emitter_write_indicator(emitter, "?", 1, 0, 1)) + return 0; + if (!PUSH(emitter, emitter->states, + YAML_EMIT_BLOCK_MAPPING_VALUE_STATE)) + return 0; + + return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0); + } +} + +/* + * Expect a block value node. + */ + +static int +yaml_emitter_emit_block_mapping_value(yaml_emitter_t *emitter, + yaml_event_t *event, int simple) +{ + if (simple) { + if (!yaml_emitter_write_indicator(emitter, ":", 0, 0, 0)) + return 0; + } + else { + if (!yaml_emitter_write_indent(emitter)) + return 0; + if (!yaml_emitter_write_indicator(emitter, ":", 1, 0, 1)) + return 0; + } + if (!PUSH(emitter, emitter->states, + YAML_EMIT_BLOCK_MAPPING_KEY_STATE)) + return 0; + + return yaml_emitter_emit_node(emitter, event, 0, 0, 1, 0); +} + +/* + * Expect a node. + */ + +static int +yaml_emitter_emit_node(yaml_emitter_t *emitter, yaml_event_t *event, + int root, int sequence, int mapping, int simple_key) +{ + emitter->root_context = root; + emitter->sequence_context = sequence; + emitter->mapping_context = mapping; + emitter->simple_key_context = simple_key; + + switch (event->type) + { + case YAML_ALIAS_EVENT: + return yaml_emitter_emit_alias(emitter, event); + + case YAML_SCALAR_EVENT: + return yaml_emitter_emit_scalar(emitter, event); + + case YAML_SEQUENCE_START_EVENT: + return yaml_emitter_emit_sequence_start(emitter, event); + + case YAML_MAPPING_START_EVENT: + return yaml_emitter_emit_mapping_start(emitter, event); + + default: + return yaml_emitter_set_emitter_error(emitter, + "expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS"); + } + + return 0; +} + +/* + * Expect ALIAS. + */ + +static int +yaml_emitter_emit_alias(yaml_emitter_t *emitter, SHIM(yaml_event_t *event)) +{ + if (!yaml_emitter_process_anchor(emitter)) + return 0; + if (emitter->simple_key_context) + if (!PUT(emitter, ' ')) return 0; + emitter->state = POP(emitter, emitter->states); + + return 1; +} + +/* + * Expect SCALAR. + */ + +static int +yaml_emitter_emit_scalar(yaml_emitter_t *emitter, yaml_event_t *event) +{ + if (!yaml_emitter_select_scalar_style(emitter, event)) + return 0; + if (!yaml_emitter_process_anchor(emitter)) + return 0; + if (!yaml_emitter_process_tag(emitter)) + return 0; + if (!yaml_emitter_increase_indent(emitter, 1, 0)) + return 0; + if (!yaml_emitter_process_scalar(emitter)) + return 0; + emitter->indent = POP(emitter, emitter->indents); + emitter->state = POP(emitter, emitter->states); + + return 1; +} + +/* + * Expect SEQUENCE-START. + */ + +static int +yaml_emitter_emit_sequence_start(yaml_emitter_t *emitter, yaml_event_t *event) +{ + if (!yaml_emitter_process_anchor(emitter)) + return 0; + if (!yaml_emitter_process_tag(emitter)) + return 0; + + if (emitter->flow_level || emitter->canonical + || event->data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE + || yaml_emitter_check_empty_sequence(emitter)) { + emitter->state = YAML_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE; + } + else { + emitter->state = YAML_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE; + } + + return 1; +} + +/* + * Expect MAPPING-START. + */ + +static int +yaml_emitter_emit_mapping_start(yaml_emitter_t *emitter, yaml_event_t *event) +{ + if (!yaml_emitter_process_anchor(emitter)) + return 0; + if (!yaml_emitter_process_tag(emitter)) + return 0; + + if (emitter->flow_level || emitter->canonical + || event->data.mapping_start.style == YAML_FLOW_MAPPING_STYLE + || yaml_emitter_check_empty_mapping(emitter)) { + emitter->state = YAML_EMIT_FLOW_MAPPING_FIRST_KEY_STATE; + } + else { + emitter->state = YAML_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE; + } + + return 1; +} + +/* + * Check if the document content is an empty scalar. + */ + +static int +yaml_emitter_check_empty_document(SHIM(yaml_emitter_t *emitter)) +{ + return 0; +} + +/* + * Check if the next events represent an empty sequence. + */ + +static int +yaml_emitter_check_empty_sequence(yaml_emitter_t *emitter) +{ + if (emitter->events.tail - emitter->events.head < 2) + return 0; + + return (emitter->events.head[0].type == YAML_SEQUENCE_START_EVENT + && emitter->events.head[1].type == YAML_SEQUENCE_END_EVENT); +} + +/* + * Check if the next events represent an empty mapping. + */ + +static int +yaml_emitter_check_empty_mapping(yaml_emitter_t *emitter) +{ + if (emitter->events.tail - emitter->events.head < 2) + return 0; + + return (emitter->events.head[0].type == YAML_MAPPING_START_EVENT + && emitter->events.head[1].type == YAML_MAPPING_END_EVENT); +} + +/* + * Check if the next node can be expressed as a simple key. + */ + +static int +yaml_emitter_check_simple_key(yaml_emitter_t *emitter) +{ + yaml_event_t *event = emitter->events.head; + size_t length = 0; + + switch (event->type) + { + case YAML_ALIAS_EVENT: + length += emitter->anchor_data.anchor_length; + break; + + case YAML_SCALAR_EVENT: + if (emitter->scalar_data.multiline) + return 0; + length += emitter->anchor_data.anchor_length + + emitter->tag_data.handle_length + + emitter->tag_data.suffix_length + + emitter->scalar_data.length; + break; + + case YAML_SEQUENCE_START_EVENT: + if (!yaml_emitter_check_empty_sequence(emitter)) + return 0; + length += emitter->anchor_data.anchor_length + + emitter->tag_data.handle_length + + emitter->tag_data.suffix_length; + break; + + case YAML_MAPPING_START_EVENT: + if (!yaml_emitter_check_empty_mapping(emitter)) + return 0; + length += emitter->anchor_data.anchor_length + + emitter->tag_data.handle_length + + emitter->tag_data.suffix_length; + break; + + default: + return 0; + } + + if (length > 128) + return 0; + + return 1; +} + +/* + * Determine an acceptable scalar style. + */ + +static int +yaml_emitter_select_scalar_style(yaml_emitter_t *emitter, yaml_event_t *event) +{ + yaml_scalar_style_t style = event->data.scalar.style; + int no_tag = (!emitter->tag_data.handle && !emitter->tag_data.suffix); + + if (no_tag && !event->data.scalar.plain_implicit + && !event->data.scalar.quoted_implicit) { + return yaml_emitter_set_emitter_error(emitter, + "neither tag nor implicit flags are specified"); + } + + if (style == YAML_ANY_SCALAR_STYLE) + style = YAML_PLAIN_SCALAR_STYLE; + + if (emitter->canonical) + style = YAML_DOUBLE_QUOTED_SCALAR_STYLE; + + if (emitter->simple_key_context && emitter->scalar_data.multiline) + style = YAML_DOUBLE_QUOTED_SCALAR_STYLE; + + if (style == YAML_PLAIN_SCALAR_STYLE) + { + if ((emitter->flow_level && !emitter->scalar_data.flow_plain_allowed) + || (!emitter->flow_level && !emitter->scalar_data.block_plain_allowed)) + style = YAML_SINGLE_QUOTED_SCALAR_STYLE; + if (!emitter->scalar_data.length + && (emitter->flow_level || emitter->simple_key_context)) + style = YAML_SINGLE_QUOTED_SCALAR_STYLE; + if (no_tag && !event->data.scalar.plain_implicit) + style = YAML_SINGLE_QUOTED_SCALAR_STYLE; + } + + if (style == YAML_SINGLE_QUOTED_SCALAR_STYLE) + { + if (!emitter->scalar_data.single_quoted_allowed) + style = YAML_DOUBLE_QUOTED_SCALAR_STYLE; + } + + if (style == YAML_LITERAL_SCALAR_STYLE || style == YAML_FOLDED_SCALAR_STYLE) + { + if (!emitter->scalar_data.block_allowed + || emitter->flow_level || emitter->simple_key_context) + style = YAML_DOUBLE_QUOTED_SCALAR_STYLE; + } + + if (no_tag && !event->data.scalar.quoted_implicit + && style != YAML_PLAIN_SCALAR_STYLE) + { + emitter->tag_data.handle = (yaml_char_t *)"!"; + emitter->tag_data.handle_length = 1; + } + + emitter->scalar_data.style = style; + + return 1; +} + +/* + * Write an anchor. + */ + +static int +yaml_emitter_process_anchor(yaml_emitter_t *emitter) +{ + if (!emitter->anchor_data.anchor) + return 1; + + if (!yaml_emitter_write_indicator(emitter, + (emitter->anchor_data.alias ? "*" : "&"), 1, 0, 0)) + return 0; + + return yaml_emitter_write_anchor(emitter, + emitter->anchor_data.anchor, emitter->anchor_data.anchor_length); +} + +/* + * Write a tag. + */ + +static int +yaml_emitter_process_tag(yaml_emitter_t *emitter) +{ + if (!emitter->tag_data.handle && !emitter->tag_data.suffix) + return 1; + + if (emitter->tag_data.handle) + { + if (!yaml_emitter_write_tag_handle(emitter, emitter->tag_data.handle, + emitter->tag_data.handle_length)) + return 0; + if (emitter->tag_data.suffix) { + if (!yaml_emitter_write_tag_content(emitter, emitter->tag_data.suffix, + emitter->tag_data.suffix_length, 0)) + return 0; + } + } + else + { + if (!yaml_emitter_write_indicator(emitter, "!<", 1, 0, 0)) + return 0; + if (!yaml_emitter_write_tag_content(emitter, emitter->tag_data.suffix, + emitter->tag_data.suffix_length, 0)) + return 0; + if (!yaml_emitter_write_indicator(emitter, ">", 0, 0, 0)) + return 0; + } + + return 1; +} + +/* + * Write a scalar. + */ + +static int +yaml_emitter_process_scalar(yaml_emitter_t *emitter) +{ + switch (emitter->scalar_data.style) + { + case YAML_PLAIN_SCALAR_STYLE: + return yaml_emitter_write_plain_scalar(emitter, + emitter->scalar_data.value, emitter->scalar_data.length, + !emitter->simple_key_context); + + case YAML_SINGLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_single_quoted_scalar(emitter, + emitter->scalar_data.value, emitter->scalar_data.length, + !emitter->simple_key_context); + + case YAML_DOUBLE_QUOTED_SCALAR_STYLE: + return yaml_emitter_write_double_quoted_scalar(emitter, + emitter->scalar_data.value, emitter->scalar_data.length, + !emitter->simple_key_context); + + case YAML_LITERAL_SCALAR_STYLE: + return yaml_emitter_write_literal_scalar(emitter, + emitter->scalar_data.value, emitter->scalar_data.length); + + case YAML_FOLDED_SCALAR_STYLE: + return yaml_emitter_write_folded_scalar(emitter, + emitter->scalar_data.value, emitter->scalar_data.length); + + default: + assert(1); /* Impossible. */ + } + + return 0; +} + +/* + * Check if a %YAML directive is valid. + */ + +static int +yaml_emitter_analyze_version_directive(yaml_emitter_t *emitter, + yaml_version_directive_t version_directive) +{ + if (version_directive.major != 1 || ( + version_directive.minor != 1 + && version_directive.minor != 2 + )) { + return yaml_emitter_set_emitter_error(emitter, + "incompatible %YAML directive"); + } + + return 1; +} + +/* + * Check if a %TAG directive is valid. + */ + +static int +yaml_emitter_analyze_tag_directive(yaml_emitter_t *emitter, + yaml_tag_directive_t tag_directive) +{ + yaml_string_t handle; + yaml_string_t prefix; + size_t handle_length; + size_t prefix_length; + + handle_length = strlen((char *)tag_directive.handle); + prefix_length = strlen((char *)tag_directive.prefix); + STRING_ASSIGN(handle, tag_directive.handle, handle_length); + STRING_ASSIGN(prefix, tag_directive.prefix, prefix_length); + + if (handle.start == handle.end) { + return yaml_emitter_set_emitter_error(emitter, + "tag handle must not be empty"); + } + + if (handle.start[0] != '!') { + return yaml_emitter_set_emitter_error(emitter, + "tag handle must start with '!'"); + } + + if (handle.end[-1] != '!') { + return yaml_emitter_set_emitter_error(emitter, + "tag handle must end with '!'"); + } + + handle.pointer ++; + + while (handle.pointer < handle.end-1) { + if (!IS_ALPHA(handle)) { + return yaml_emitter_set_emitter_error(emitter, + "tag handle must contain alphanumerical characters only"); + } + MOVE(handle); + } + + if (prefix.start == prefix.end) { + return yaml_emitter_set_emitter_error(emitter, + "tag prefix must not be empty"); + } + + return 1; +} + +/* + * Check if an anchor is valid. + */ + +static int +yaml_emitter_analyze_anchor(yaml_emitter_t *emitter, + yaml_char_t *anchor, int alias) +{ + size_t anchor_length; + yaml_string_t string; + + anchor_length = strlen((char *)anchor); + STRING_ASSIGN(string, anchor, anchor_length); + + if (string.start == string.end) { + return yaml_emitter_set_emitter_error(emitter, alias ? + "alias value must not be empty" : + "anchor value must not be empty"); + } + + while (string.pointer != string.end) { + if (!IS_ALPHA(string)) { + return yaml_emitter_set_emitter_error(emitter, alias ? + "alias value must contain alphanumerical characters only" : + "anchor value must contain alphanumerical characters only"); + } + MOVE(string); + } + + emitter->anchor_data.anchor = string.start; + emitter->anchor_data.anchor_length = string.end - string.start; + emitter->anchor_data.alias = alias; + + return 1; +} + +/* + * Check if a tag is valid. + */ + +static int +yaml_emitter_analyze_tag(yaml_emitter_t *emitter, + yaml_char_t *tag) +{ + size_t tag_length; + yaml_string_t string; + yaml_tag_directive_t *tag_directive; + + tag_length = strlen((char *)tag); + STRING_ASSIGN(string, tag, tag_length); + + if (string.start == string.end) { + return yaml_emitter_set_emitter_error(emitter, + "tag value must not be empty"); + } + + for (tag_directive = emitter->tag_directives.start; + tag_directive != emitter->tag_directives.top; tag_directive ++) { + size_t prefix_length = strlen((char *)tag_directive->prefix); + if (prefix_length < (size_t)(string.end - string.start) + && strncmp((char *)tag_directive->prefix, (char *)string.start, + prefix_length) == 0) + { + emitter->tag_data.handle = tag_directive->handle; + emitter->tag_data.handle_length = + strlen((char *)tag_directive->handle); + emitter->tag_data.suffix = string.start + prefix_length; + emitter->tag_data.suffix_length = + (string.end - string.start) - prefix_length; + return 1; + } + } + + emitter->tag_data.suffix = string.start; + emitter->tag_data.suffix_length = string.end - string.start; + + return 1; +} + +/* + * Check if a scalar is valid. + */ + +static int +yaml_emitter_analyze_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length) +{ + yaml_string_t string; + + int block_indicators = 0; + int flow_indicators = 0; + int line_breaks = 0; + int special_characters = 0; + + int leading_space = 0; + int leading_break = 0; + int trailing_space = 0; + int trailing_break = 0; + int break_space = 0; + int space_break = 0; + + int preceded_by_whitespace = 0; + int followed_by_whitespace = 0; + int previous_space = 0; + int previous_break = 0; + + STRING_ASSIGN(string, value, length); + + emitter->scalar_data.value = value; + emitter->scalar_data.length = length; + + if (string.start == string.end) + { + emitter->scalar_data.multiline = 0; + emitter->scalar_data.flow_plain_allowed = 0; + emitter->scalar_data.block_plain_allowed = 1; + emitter->scalar_data.single_quoted_allowed = 1; + emitter->scalar_data.block_allowed = 0; + + return 1; + } + + if ((CHECK_AT(string, '-', 0) + && CHECK_AT(string, '-', 1) + && CHECK_AT(string, '-', 2)) + || (CHECK_AT(string, '.', 0) + && CHECK_AT(string, '.', 1) + && CHECK_AT(string, '.', 2))) { + block_indicators = 1; + flow_indicators = 1; + } + + preceded_by_whitespace = 1; + followed_by_whitespace = IS_BLANKZ_AT(string, WIDTH(string)); + + while (string.pointer != string.end) + { + if (string.start == string.pointer) + { + if (CHECK(string, '#') || CHECK(string, ',') + || CHECK(string, '[') || CHECK(string, ']') + || CHECK(string, '{') || CHECK(string, '}') + || CHECK(string, '&') || CHECK(string, '*') + || CHECK(string, '!') || CHECK(string, '|') + || CHECK(string, '>') || CHECK(string, '\'') + || CHECK(string, '"') || CHECK(string, '%') + || CHECK(string, '@') || CHECK(string, '`')) { + flow_indicators = 1; + block_indicators = 1; + } + + if (CHECK(string, '?') || CHECK(string, ':')) { + flow_indicators = 1; + if (followed_by_whitespace) { + block_indicators = 1; + } + } + + if (CHECK(string, '-') && followed_by_whitespace) { + flow_indicators = 1; + block_indicators = 1; + } + } + else + { + if (CHECK(string, ',') || CHECK(string, '?') + || CHECK(string, '[') || CHECK(string, ']') + || CHECK(string, '{') || CHECK(string, '}')) { + flow_indicators = 1; + } + + if (CHECK(string, ':')) { + flow_indicators = 1; + if (followed_by_whitespace) { + block_indicators = 1; + } + } + + if (CHECK(string, '#') && preceded_by_whitespace) { + flow_indicators = 1; + block_indicators = 1; + } + } + + if (!IS_PRINTABLE(string) + || (!IS_ASCII(string) && !emitter->unicode)) { + special_characters = 1; + } + + if (IS_BREAK(string)) { + line_breaks = 1; + } + + if (IS_SPACE(string)) + { + if (string.start == string.pointer) { + leading_space = 1; + } + if (string.pointer+WIDTH(string) == string.end) { + trailing_space = 1; + } + if (previous_break) { + break_space = 1; + } + previous_space = 1; + previous_break = 0; + } + else if (IS_BREAK(string)) + { + if (string.start == string.pointer) { + leading_break = 1; + } + if (string.pointer+WIDTH(string) == string.end) { + trailing_break = 1; + } + if (previous_space) { + space_break = 1; + } + previous_space = 0; + previous_break = 1; + } + else + { + previous_space = 0; + previous_break = 0; + } + + preceded_by_whitespace = IS_BLANKZ(string); + MOVE(string); + if (string.pointer != string.end) { + followed_by_whitespace = IS_BLANKZ_AT(string, WIDTH(string)); + } + } + + emitter->scalar_data.multiline = line_breaks; + + emitter->scalar_data.flow_plain_allowed = 1; + emitter->scalar_data.block_plain_allowed = 1; + emitter->scalar_data.single_quoted_allowed = 1; + emitter->scalar_data.block_allowed = 1; + + if (leading_space || leading_break || trailing_space || trailing_break) { + emitter->scalar_data.flow_plain_allowed = 0; + emitter->scalar_data.block_plain_allowed = 0; + } + + if (trailing_space) { + emitter->scalar_data.block_allowed = 0; + } + + if (break_space) { + emitter->scalar_data.flow_plain_allowed = 0; + emitter->scalar_data.block_plain_allowed = 0; + emitter->scalar_data.single_quoted_allowed = 0; + } + + if (space_break || special_characters) { + emitter->scalar_data.flow_plain_allowed = 0; + emitter->scalar_data.block_plain_allowed = 0; + emitter->scalar_data.single_quoted_allowed = 0; + emitter->scalar_data.block_allowed = 0; + } + + if (line_breaks) { + emitter->scalar_data.flow_plain_allowed = 0; + emitter->scalar_data.block_plain_allowed = 0; + } + + if (flow_indicators) { + emitter->scalar_data.flow_plain_allowed = 0; + } + + if (block_indicators) { + emitter->scalar_data.block_plain_allowed = 0; + } + + return 1; +} + +/* + * Check if the event data is valid. + */ + +static int +yaml_emitter_analyze_event(yaml_emitter_t *emitter, + yaml_event_t *event) +{ + emitter->anchor_data.anchor = NULL; + emitter->anchor_data.anchor_length = 0; + emitter->tag_data.handle = NULL; + emitter->tag_data.handle_length = 0; + emitter->tag_data.suffix = NULL; + emitter->tag_data.suffix_length = 0; + emitter->scalar_data.value = NULL; + emitter->scalar_data.length = 0; + + switch (event->type) + { + case YAML_ALIAS_EVENT: + if (!yaml_emitter_analyze_anchor(emitter, + event->data.alias.anchor, 1)) + return 0; + return 1; + + case YAML_SCALAR_EVENT: + if (event->data.scalar.anchor) { + if (!yaml_emitter_analyze_anchor(emitter, + event->data.scalar.anchor, 0)) + return 0; + } + if (event->data.scalar.tag && (emitter->canonical || + (!event->data.scalar.plain_implicit + && !event->data.scalar.quoted_implicit))) { + if (!yaml_emitter_analyze_tag(emitter, event->data.scalar.tag)) + return 0; + } + if (!yaml_emitter_analyze_scalar(emitter, + event->data.scalar.value, event->data.scalar.length)) + return 0; + return 1; + + case YAML_SEQUENCE_START_EVENT: + if (event->data.sequence_start.anchor) { + if (!yaml_emitter_analyze_anchor(emitter, + event->data.sequence_start.anchor, 0)) + return 0; + } + if (event->data.sequence_start.tag && (emitter->canonical || + !event->data.sequence_start.implicit)) { + if (!yaml_emitter_analyze_tag(emitter, + event->data.sequence_start.tag)) + return 0; + } + return 1; + + case YAML_MAPPING_START_EVENT: + if (event->data.mapping_start.anchor) { + if (!yaml_emitter_analyze_anchor(emitter, + event->data.mapping_start.anchor, 0)) + return 0; + } + if (event->data.mapping_start.tag && (emitter->canonical || + !event->data.mapping_start.implicit)) { + if (!yaml_emitter_analyze_tag(emitter, + event->data.mapping_start.tag)) + return 0; + } + return 1; + + default: + return 1; + } +} + +/* + * Write the BOM character. + */ + +static int +yaml_emitter_write_bom(yaml_emitter_t *emitter) +{ + if (!FLUSH(emitter)) return 0; + + *(emitter->buffer.pointer++) = (yaml_char_t) '\xEF'; + *(emitter->buffer.pointer++) = (yaml_char_t) '\xBB'; + *(emitter->buffer.pointer++) = (yaml_char_t) '\xBF'; + + return 1; +} + +static int +yaml_emitter_write_indent(yaml_emitter_t *emitter) +{ + int indent = (emitter->indent >= 0) ? emitter->indent : 0; + + if (!emitter->indention || emitter->column > indent + || (emitter->column == indent && !emitter->whitespace)) { + if (!PUT_BREAK(emitter)) return 0; + } + + while (emitter->column < indent) { + if (!PUT(emitter, ' ')) return 0; + } + + emitter->whitespace = 1; + emitter->indention = 1; + + return 1; +} + +static int +yaml_emitter_write_indicator(yaml_emitter_t *emitter, + const char *indicator, int need_whitespace, + int is_whitespace, int is_indention) +{ + size_t indicator_length; + yaml_string_t string; + + indicator_length = strlen(indicator); + STRING_ASSIGN(string, (yaml_char_t *)indicator, indicator_length); + + if (need_whitespace && !emitter->whitespace) { + if (!PUT(emitter, ' ')) return 0; + } + + while (string.pointer != string.end) { + if (!WRITE(emitter, string)) return 0; + } + + emitter->whitespace = is_whitespace; + emitter->indention = (emitter->indention && is_indention); + + return 1; +} + +static int +yaml_emitter_write_anchor(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length) +{ + yaml_string_t string; + STRING_ASSIGN(string, value, length); + + while (string.pointer != string.end) { + if (!WRITE(emitter, string)) return 0; + } + + emitter->whitespace = 0; + emitter->indention = 0; + + return 1; +} + +static int +yaml_emitter_write_tag_handle(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length) +{ + yaml_string_t string; + STRING_ASSIGN(string, value, length); + + if (!emitter->whitespace) { + if (!PUT(emitter, ' ')) return 0; + } + + while (string.pointer != string.end) { + if (!WRITE(emitter, string)) return 0; + } + + emitter->whitespace = 0; + emitter->indention = 0; + + return 1; +} + +static int +yaml_emitter_write_tag_content(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length, + int need_whitespace) +{ + yaml_string_t string; + STRING_ASSIGN(string, value, length); + + if (need_whitespace && !emitter->whitespace) { + if (!PUT(emitter, ' ')) return 0; + } + + while (string.pointer != string.end) { + if (IS_ALPHA(string) + || CHECK(string, ';') || CHECK(string, '/') + || CHECK(string, '?') || CHECK(string, ':') + || CHECK(string, '@') || CHECK(string, '&') + || CHECK(string, '=') || CHECK(string, '+') + || CHECK(string, '$') || CHECK(string, ',') + || CHECK(string, '_') || CHECK(string, '.') + || CHECK(string, '~') || CHECK(string, '*') + || CHECK(string, '\'') || CHECK(string, '(') + || CHECK(string, ')') || CHECK(string, '[') + || CHECK(string, ']')) { + if (!WRITE(emitter, string)) return 0; + } + else { + int width = WIDTH(string); + unsigned int value; + while (width --) { + value = *(string.pointer++); + if (!PUT(emitter, '%')) return 0; + if (!PUT(emitter, (value >> 4) + + ((value >> 4) < 10 ? '0' : 'A' - 10))) + return 0; + if (!PUT(emitter, (value & 0x0F) + + ((value & 0x0F) < 10 ? '0' : 'A' - 10))) + return 0; + } + } + } + + emitter->whitespace = 0; + emitter->indention = 0; + + return 1; +} + +static int +yaml_emitter_write_plain_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length, int allow_breaks) +{ + yaml_string_t string; + int spaces = 0; + int breaks = 0; + + STRING_ASSIGN(string, value, length); + + /** + * Avoid trailing spaces for empty values in block mode. + * In flow mode, we still want the space to prevent ambiguous things + * like {a:}. + * Currently, the emitter forbids any plain empty scalar in flow mode + * (e.g. it outputs {a: ''} instead), so emitter->flow_level will + * never be true here. + * But if the emitter is ever changed to allow emitting empty values, + * the check for flow_level is already here. + */ + if (!emitter->whitespace && (length || emitter->flow_level)) { + if (!PUT(emitter, ' ')) return 0; + } + + while (string.pointer != string.end) + { + if (IS_SPACE(string)) + { + if (allow_breaks && !spaces + && emitter->column > emitter->best_width + && !IS_SPACE_AT(string, 1)) { + if (!yaml_emitter_write_indent(emitter)) return 0; + MOVE(string); + } + else { + if (!WRITE(emitter, string)) return 0; + } + spaces = 1; + } + else if (IS_BREAK(string)) + { + if (!breaks && CHECK(string, '\n')) { + if (!PUT_BREAK(emitter)) return 0; + } + if (!WRITE_BREAK(emitter, string)) return 0; + emitter->indention = 1; + breaks = 1; + } + else + { + if (breaks) { + if (!yaml_emitter_write_indent(emitter)) return 0; + } + if (!WRITE(emitter, string)) return 0; + emitter->indention = 0; + spaces = 0; + breaks = 0; + } + } + + emitter->whitespace = 0; + emitter->indention = 0; + + return 1; +} + +static int +yaml_emitter_write_single_quoted_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length, int allow_breaks) +{ + yaml_string_t string; + int spaces = 0; + int breaks = 0; + + STRING_ASSIGN(string, value, length); + + if (!yaml_emitter_write_indicator(emitter, "'", 1, 0, 0)) + return 0; + + while (string.pointer != string.end) + { + if (IS_SPACE(string)) + { + if (allow_breaks && !spaces + && emitter->column > emitter->best_width + && string.pointer != string.start + && string.pointer != string.end - 1 + && !IS_SPACE_AT(string, 1)) { + if (!yaml_emitter_write_indent(emitter)) return 0; + MOVE(string); + } + else { + if (!WRITE(emitter, string)) return 0; + } + spaces = 1; + } + else if (IS_BREAK(string)) + { + if (!breaks && CHECK(string, '\n')) { + if (!PUT_BREAK(emitter)) return 0; + } + if (!WRITE_BREAK(emitter, string)) return 0; + emitter->indention = 1; + breaks = 1; + } + else + { + if (breaks) { + if (!yaml_emitter_write_indent(emitter)) return 0; + } + if (CHECK(string, '\'')) { + if (!PUT(emitter, '\'')) return 0; + } + if (!WRITE(emitter, string)) return 0; + emitter->indention = 0; + spaces = 0; + breaks = 0; + } + } + + if (breaks) + if (!yaml_emitter_write_indent(emitter)) return 0; + + if (!yaml_emitter_write_indicator(emitter, "'", 0, 0, 0)) + return 0; + + emitter->whitespace = 0; + emitter->indention = 0; + + return 1; +} + +static int +yaml_emitter_write_double_quoted_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length, int allow_breaks) +{ + yaml_string_t string; + int spaces = 0; + + STRING_ASSIGN(string, value, length); + + if (!yaml_emitter_write_indicator(emitter, "\"", 1, 0, 0)) + return 0; + + while (string.pointer != string.end) + { + if (!IS_PRINTABLE(string) || (!emitter->unicode && !IS_ASCII(string)) + || IS_BOM(string) || IS_BREAK(string) + || CHECK(string, '"') || CHECK(string, '\\')) + { + unsigned char octet; + unsigned int width; + unsigned int value; + int k; + + octet = string.pointer[0]; + width = (octet & 0x80) == 0x00 ? 1 : + (octet & 0xE0) == 0xC0 ? 2 : + (octet & 0xF0) == 0xE0 ? 3 : + (octet & 0xF8) == 0xF0 ? 4 : 0; + value = (octet & 0x80) == 0x00 ? octet & 0x7F : + (octet & 0xE0) == 0xC0 ? octet & 0x1F : + (octet & 0xF0) == 0xE0 ? octet & 0x0F : + (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; + for (k = 1; k < (int)width; k ++) { + octet = string.pointer[k]; + value = (value << 6) + (octet & 0x3F); + } + string.pointer += width; + + if (!PUT(emitter, '\\')) return 0; + + switch (value) + { + case 0x00: + if (!PUT(emitter, '0')) return 0; + break; + + case 0x07: + if (!PUT(emitter, 'a')) return 0; + break; + + case 0x08: + if (!PUT(emitter, 'b')) return 0; + break; + + case 0x09: + if (!PUT(emitter, 't')) return 0; + break; + + case 0x0A: + if (!PUT(emitter, 'n')) return 0; + break; + + case 0x0B: + if (!PUT(emitter, 'v')) return 0; + break; + + case 0x0C: + if (!PUT(emitter, 'f')) return 0; + break; + + case 0x0D: + if (!PUT(emitter, 'r')) return 0; + break; + + case 0x1B: + if (!PUT(emitter, 'e')) return 0; + break; + + case 0x22: + if (!PUT(emitter, '\"')) return 0; + break; + + case 0x5C: + if (!PUT(emitter, '\\')) return 0; + break; + + case 0x85: + if (!PUT(emitter, 'N')) return 0; + break; + + case 0xA0: + if (!PUT(emitter, '_')) return 0; + break; + + case 0x2028: + if (!PUT(emitter, 'L')) return 0; + break; + + case 0x2029: + if (!PUT(emitter, 'P')) return 0; + break; + + default: + if (value <= 0xFF) { + if (!PUT(emitter, 'x')) return 0; + width = 2; + } + else if (value <= 0xFFFF) { + if (!PUT(emitter, 'u')) return 0; + width = 4; + } + else { + if (!PUT(emitter, 'U')) return 0; + width = 8; + } + for (k = (width-1)*4; k >= 0; k -= 4) { + int digit = (value >> k) & 0x0F; + if (!PUT(emitter, digit + (digit < 10 ? '0' : 'A'-10))) + return 0; + } + } + spaces = 0; + } + else if (IS_SPACE(string)) + { + if (allow_breaks && !spaces + && emitter->column > emitter->best_width + && string.pointer != string.start + && string.pointer != string.end - 1) { + if (!yaml_emitter_write_indent(emitter)) return 0; + if (IS_SPACE_AT(string, 1)) { + if (!PUT(emitter, '\\')) return 0; + } + MOVE(string); + } + else { + if (!WRITE(emitter, string)) return 0; + } + spaces = 1; + } + else + { + if (!WRITE(emitter, string)) return 0; + spaces = 0; + } + } + + if (!yaml_emitter_write_indicator(emitter, "\"", 0, 0, 0)) + return 0; + + emitter->whitespace = 0; + emitter->indention = 0; + + return 1; +} + +static int +yaml_emitter_write_block_scalar_hints(yaml_emitter_t *emitter, + yaml_string_t string) +{ + char indent_hint[2]; + const char *chomp_hint = NULL; + + if (IS_SPACE(string) || IS_BREAK(string)) + { + indent_hint[0] = '0' + (char)emitter->best_indent; + indent_hint[1] = '\0'; + if (!yaml_emitter_write_indicator(emitter, indent_hint, 0, 0, 0)) + return 0; + } + + emitter->open_ended = 0; + + string.pointer = string.end; + if (string.start == string.pointer) + { + chomp_hint = "-"; + } + else + { + do { + string.pointer --; + } while ((*string.pointer & 0xC0) == 0x80); + if (!IS_BREAK(string)) + { + chomp_hint = "-"; + } + else if (string.start == string.pointer) + { + chomp_hint = "+"; + emitter->open_ended = 2; + } + else + { + do { + string.pointer --; + } while ((*string.pointer & 0xC0) == 0x80); + if (IS_BREAK(string)) + { + chomp_hint = "+"; + emitter->open_ended = 2; + } + } + } + + if (chomp_hint) + { + if (!yaml_emitter_write_indicator(emitter, chomp_hint, 0, 0, 0)) + return 0; + } + + return 1; +} + +static int +yaml_emitter_write_literal_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length) +{ + yaml_string_t string; + int breaks = 1; + + STRING_ASSIGN(string, value, length); + + if (!yaml_emitter_write_indicator(emitter, "|", 1, 0, 0)) + return 0; + if (!yaml_emitter_write_block_scalar_hints(emitter, string)) + return 0; + if (!PUT_BREAK(emitter)) return 0; + emitter->indention = 1; + emitter->whitespace = 1; + + while (string.pointer != string.end) + { + if (IS_BREAK(string)) + { + if (!WRITE_BREAK(emitter, string)) return 0; + emitter->indention = 1; + breaks = 1; + } + else + { + if (breaks) { + if (!yaml_emitter_write_indent(emitter)) return 0; + } + if (!WRITE(emitter, string)) return 0; + emitter->indention = 0; + breaks = 0; + } + } + + return 1; +} + +static int +yaml_emitter_write_folded_scalar(yaml_emitter_t *emitter, + yaml_char_t *value, size_t length) +{ + yaml_string_t string; + int breaks = 1; + int leading_spaces = 1; + + STRING_ASSIGN(string, value, length); + + if (!yaml_emitter_write_indicator(emitter, ">", 1, 0, 0)) + return 0; + if (!yaml_emitter_write_block_scalar_hints(emitter, string)) + return 0; + if (!PUT_BREAK(emitter)) return 0; + emitter->indention = 1; + emitter->whitespace = 1; + + while (string.pointer != string.end) + { + if (IS_BREAK(string)) + { + if (!breaks && !leading_spaces && CHECK(string, '\n')) { + int k = 0; + while (IS_BREAK_AT(string, k)) { + k += WIDTH_AT(string, k); + } + if (!IS_BLANKZ_AT(string, k)) { + if (!PUT_BREAK(emitter)) return 0; + } + } + if (!WRITE_BREAK(emitter, string)) return 0; + emitter->indention = 1; + breaks = 1; + } + else + { + if (breaks) { + if (!yaml_emitter_write_indent(emitter)) return 0; + leading_spaces = IS_BLANK(string); + } + if (!breaks && IS_SPACE(string) && !IS_SPACE_AT(string, 1) + && emitter->column > emitter->best_width) { + if (!yaml_emitter_write_indent(emitter)) return 0; + MOVE(string); + } + else { + if (!WRITE(emitter, string)) return 0; + } + emitter->indention = 0; + breaks = 0; + } + } + + return 1; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/loader.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/loader.c new file mode 100644 index 0000000..bcf3aee --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/loader.c @@ -0,0 +1,544 @@ + +#include "yaml_private.h" + +/* + * API functions. + */ + +YAML_DECLARE(int) +yaml_parser_load(yaml_parser_t *parser, yaml_document_t *document); + +/* + * Error handling. + */ + +static int +yaml_parser_set_composer_error(yaml_parser_t *parser, + const char *problem, yaml_mark_t problem_mark); + +static int +yaml_parser_set_composer_error_context(yaml_parser_t *parser, + const char *context, yaml_mark_t context_mark, + const char *problem, yaml_mark_t problem_mark); + + +/* + * Alias handling. + */ + +static int +yaml_parser_register_anchor(yaml_parser_t *parser, + int index, yaml_char_t *anchor); + +/* + * Clean up functions. + */ + +static void +yaml_parser_delete_aliases(yaml_parser_t *parser); + +/* + * Document loading context. + */ +struct loader_ctx { + int *start; + int *end; + int *top; +}; + +/* + * Composer functions. + */ +static int +yaml_parser_load_nodes(yaml_parser_t *parser, struct loader_ctx *ctx); + +static int +yaml_parser_load_document(yaml_parser_t *parser, yaml_event_t *event); + +static int +yaml_parser_load_alias(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx); + +static int +yaml_parser_load_scalar(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx); + +static int +yaml_parser_load_sequence(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx); + +static int +yaml_parser_load_mapping(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx); + +static int +yaml_parser_load_sequence_end(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx); + +static int +yaml_parser_load_mapping_end(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx); + +/* + * Load the next document of the stream. + */ + +YAML_DECLARE(int) +yaml_parser_load(yaml_parser_t *parser, yaml_document_t *document) +{ + yaml_event_t event; + + assert(parser); /* Non-NULL parser object is expected. */ + assert(document); /* Non-NULL document object is expected. */ + + memset(document, 0, sizeof(yaml_document_t)); + if (!STACK_INIT(parser, document->nodes, yaml_node_t*)) + goto error; + + if (!parser->stream_start_produced) { + if (!yaml_parser_parse(parser, &event)) goto error; + assert(event.type == YAML_STREAM_START_EVENT); + /* STREAM-START is expected. */ + } + + if (parser->stream_end_produced) { + return 1; + } + + if (!yaml_parser_parse(parser, &event)) goto error; + if (event.type == YAML_STREAM_END_EVENT) { + return 1; + } + + if (!STACK_INIT(parser, parser->aliases, yaml_alias_data_t*)) + goto error; + + parser->document = document; + + if (!yaml_parser_load_document(parser, &event)) goto error; + + yaml_parser_delete_aliases(parser); + parser->document = NULL; + + return 1; + +error: + + yaml_parser_delete_aliases(parser); + yaml_document_delete(document); + parser->document = NULL; + + return 0; +} + +/* + * Set composer error. + */ + +static int +yaml_parser_set_composer_error(yaml_parser_t *parser, + const char *problem, yaml_mark_t problem_mark) +{ + parser->error = YAML_COMPOSER_ERROR; + parser->problem = problem; + parser->problem_mark = problem_mark; + + return 0; +} + +/* + * Set composer error with context. + */ + +static int +yaml_parser_set_composer_error_context(yaml_parser_t *parser, + const char *context, yaml_mark_t context_mark, + const char *problem, yaml_mark_t problem_mark) +{ + parser->error = YAML_COMPOSER_ERROR; + parser->context = context; + parser->context_mark = context_mark; + parser->problem = problem; + parser->problem_mark = problem_mark; + + return 0; +} + +/* + * Delete the stack of aliases. + */ + +static void +yaml_parser_delete_aliases(yaml_parser_t *parser) +{ + while (!STACK_EMPTY(parser, parser->aliases)) { + yaml_free(POP(parser, parser->aliases).anchor); + } + STACK_DEL(parser, parser->aliases); +} + +/* + * Compose a document object. + */ + +static int +yaml_parser_load_document(yaml_parser_t *parser, yaml_event_t *event) +{ + struct loader_ctx ctx = { NULL, NULL, NULL }; + + assert(event->type == YAML_DOCUMENT_START_EVENT); + /* DOCUMENT-START is expected. */ + + parser->document->version_directive + = event->data.document_start.version_directive; + parser->document->tag_directives.start + = event->data.document_start.tag_directives.start; + parser->document->tag_directives.end + = event->data.document_start.tag_directives.end; + parser->document->start_implicit + = event->data.document_start.implicit; + parser->document->start_mark = event->start_mark; + + if (!STACK_INIT(parser, ctx, int*)) return 0; + if (!yaml_parser_load_nodes(parser, &ctx)) { + STACK_DEL(parser, ctx); + return 0; + } + STACK_DEL(parser, ctx); + + return 1; +} + +/* + * Compose a node tree. + */ + +static int +yaml_parser_load_nodes(yaml_parser_t *parser, struct loader_ctx *ctx) +{ + yaml_event_t event; + + do { + if (!yaml_parser_parse(parser, &event)) return 0; + + switch (event.type) { + case YAML_ALIAS_EVENT: + if (!yaml_parser_load_alias(parser, &event, ctx)) return 0; + break; + case YAML_SCALAR_EVENT: + if (!yaml_parser_load_scalar(parser, &event, ctx)) return 0; + break; + case YAML_SEQUENCE_START_EVENT: + if (!yaml_parser_load_sequence(parser, &event, ctx)) return 0; + break; + case YAML_SEQUENCE_END_EVENT: + if (!yaml_parser_load_sequence_end(parser, &event, ctx)) + return 0; + break; + case YAML_MAPPING_START_EVENT: + if (!yaml_parser_load_mapping(parser, &event, ctx)) return 0; + break; + case YAML_MAPPING_END_EVENT: + if (!yaml_parser_load_mapping_end(parser, &event, ctx)) + return 0; + break; + default: + assert(0); /* Could not happen. */ + return 0; + case YAML_DOCUMENT_END_EVENT: + break; + } + } while (event.type != YAML_DOCUMENT_END_EVENT); + + parser->document->end_implicit = event.data.document_end.implicit; + parser->document->end_mark = event.end_mark; + + return 1; +} + +/* + * Add an anchor. + */ + +static int +yaml_parser_register_anchor(yaml_parser_t *parser, + int index, yaml_char_t *anchor) +{ + yaml_alias_data_t data; + yaml_alias_data_t *alias_data; + + if (!anchor) return 1; + + data.anchor = anchor; + data.index = index; + data.mark = parser->document->nodes.start[index-1].start_mark; + + for (alias_data = parser->aliases.start; + alias_data != parser->aliases.top; alias_data ++) { + if (strcmp((char *)alias_data->anchor, (char *)anchor) == 0) { + yaml_free(anchor); + return yaml_parser_set_composer_error_context(parser, + "found duplicate anchor; first occurrence", + alias_data->mark, "second occurrence", data.mark); + } + } + + if (!PUSH(parser, parser->aliases, data)) { + yaml_free(anchor); + return 0; + } + + return 1; +} + +/* + * Compose node into its parent in the stree. + */ + +static int +yaml_parser_load_node_add(yaml_parser_t *parser, struct loader_ctx *ctx, + int index) +{ + struct yaml_node_s *parent; + int parent_index; + + if (STACK_EMPTY(parser, *ctx)) { + /* This is the root node, there's no tree to add it to. */ + return 1; + } + + parent_index = *((*ctx).top - 1); + parent = &parser->document->nodes.start[parent_index-1]; + + switch (parent->type) { + case YAML_SEQUENCE_NODE: + if (!STACK_LIMIT(parser, parent->data.sequence.items, INT_MAX-1)) + return 0; + if (!PUSH(parser, parent->data.sequence.items, index)) + return 0; + break; + case YAML_MAPPING_NODE: { + yaml_node_pair_t pair; + if (!STACK_EMPTY(parser, parent->data.mapping.pairs)) { + yaml_node_pair_t *p = parent->data.mapping.pairs.top - 1; + if (p->key != 0 && p->value == 0) { + p->value = index; + break; + } + } + + pair.key = index; + pair.value = 0; + if (!STACK_LIMIT(parser, parent->data.mapping.pairs, INT_MAX-1)) + return 0; + if (!PUSH(parser, parent->data.mapping.pairs, pair)) + return 0; + + break; + } + default: + assert(0); /* Could not happen. */ + return 0; + } + return 1; +} + +/* + * Compose a node corresponding to an alias. + */ + +static int +yaml_parser_load_alias(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx) +{ + yaml_char_t *anchor = event->data.alias.anchor; + yaml_alias_data_t *alias_data; + + for (alias_data = parser->aliases.start; + alias_data != parser->aliases.top; alias_data ++) { + if (strcmp((char *)alias_data->anchor, (char *)anchor) == 0) { + yaml_free(anchor); + return yaml_parser_load_node_add(parser, ctx, alias_data->index); + } + } + + yaml_free(anchor); + return yaml_parser_set_composer_error(parser, "found undefined alias", + event->start_mark); +} + +/* + * Compose a scalar node. + */ + +static int +yaml_parser_load_scalar(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx) +{ + yaml_node_t node; + int index; + yaml_char_t *tag = event->data.scalar.tag; + + if (!STACK_LIMIT(parser, parser->document->nodes, INT_MAX-1)) goto error; + + if (!tag || strcmp((char *)tag, "!") == 0) { + yaml_free(tag); + tag = yaml_strdup((yaml_char_t *)YAML_DEFAULT_SCALAR_TAG); + if (!tag) goto error; + } + + SCALAR_NODE_INIT(node, tag, event->data.scalar.value, + event->data.scalar.length, event->data.scalar.style, + event->start_mark, event->end_mark); + + if (!PUSH(parser, parser->document->nodes, node)) goto error; + + index = (int)(parser->document->nodes.top - parser->document->nodes.start); + + if (!yaml_parser_register_anchor(parser, index, + event->data.scalar.anchor)) return 0; + + return yaml_parser_load_node_add(parser, ctx, index); + +error: + yaml_free(tag); + yaml_free(event->data.scalar.anchor); + yaml_free(event->data.scalar.value); + return 0; +} + +/* + * Compose a sequence node. + */ + +static int +yaml_parser_load_sequence(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx) +{ + yaml_node_t node; + struct { + yaml_node_item_t *start; + yaml_node_item_t *end; + yaml_node_item_t *top; + } items = { NULL, NULL, NULL }; + int index; + yaml_char_t *tag = event->data.sequence_start.tag; + + if (!STACK_LIMIT(parser, parser->document->nodes, INT_MAX-1)) goto error; + + if (!tag || strcmp((char *)tag, "!") == 0) { + yaml_free(tag); + tag = yaml_strdup((yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG); + if (!tag) goto error; + } + + if (!STACK_INIT(parser, items, yaml_node_item_t*)) goto error; + + SEQUENCE_NODE_INIT(node, tag, items.start, items.end, + event->data.sequence_start.style, + event->start_mark, event->end_mark); + + if (!PUSH(parser, parser->document->nodes, node)) goto error; + + index = (int)(parser->document->nodes.top - parser->document->nodes.start); + + if (!yaml_parser_register_anchor(parser, index, + event->data.sequence_start.anchor)) return 0; + + if (!yaml_parser_load_node_add(parser, ctx, index)) return 0; + + if (!STACK_LIMIT(parser, *ctx, INT_MAX-1)) return 0; + if (!PUSH(parser, *ctx, index)) return 0; + + return 1; + +error: + yaml_free(tag); + yaml_free(event->data.sequence_start.anchor); + return 0; +} + +static int +yaml_parser_load_sequence_end(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx) +{ + int index; + + assert(((*ctx).top - (*ctx).start) > 0); + + index = *((*ctx).top - 1); + assert(parser->document->nodes.start[index-1].type == YAML_SEQUENCE_NODE); + parser->document->nodes.start[index-1].end_mark = event->end_mark; + + (void)POP(parser, *ctx); + + return 1; +} + +/* + * Compose a mapping node. + */ + +static int +yaml_parser_load_mapping(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx) +{ + yaml_node_t node; + struct { + yaml_node_pair_t *start; + yaml_node_pair_t *end; + yaml_node_pair_t *top; + } pairs = { NULL, NULL, NULL }; + int index; + yaml_char_t *tag = event->data.mapping_start.tag; + + if (!STACK_LIMIT(parser, parser->document->nodes, INT_MAX-1)) goto error; + + if (!tag || strcmp((char *)tag, "!") == 0) { + yaml_free(tag); + tag = yaml_strdup((yaml_char_t *)YAML_DEFAULT_MAPPING_TAG); + if (!tag) goto error; + } + + if (!STACK_INIT(parser, pairs, yaml_node_pair_t*)) goto error; + + MAPPING_NODE_INIT(node, tag, pairs.start, pairs.end, + event->data.mapping_start.style, + event->start_mark, event->end_mark); + + if (!PUSH(parser, parser->document->nodes, node)) goto error; + + index = (int)(parser->document->nodes.top - parser->document->nodes.start); + + if (!yaml_parser_register_anchor(parser, index, + event->data.mapping_start.anchor)) return 0; + + if (!yaml_parser_load_node_add(parser, ctx, index)) return 0; + + if (!STACK_LIMIT(parser, *ctx, INT_MAX-1)) return 0; + if (!PUSH(parser, *ctx, index)) return 0; + + return 1; + +error: + yaml_free(tag); + yaml_free(event->data.mapping_start.anchor); + return 0; +} + +static int +yaml_parser_load_mapping_end(yaml_parser_t *parser, yaml_event_t *event, + struct loader_ctx *ctx) +{ + int index; + + assert(((*ctx).top - (*ctx).start) > 0); + + index = *((*ctx).top - 1); + assert(parser->document->nodes.start[index-1].type == YAML_MAPPING_NODE); + parser->document->nodes.start[index-1].end_mark = event->end_mark; + + (void)POP(parser, *ctx); + + return 1; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/parser.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/parser.c new file mode 100644 index 0000000..ec2f8d3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/parser.c @@ -0,0 +1,1375 @@ + +/* + * The parser implements the following grammar: + * + * stream ::= STREAM-START implicit_document? explicit_document* STREAM-END + * implicit_document ::= block_node DOCUMENT-END* + * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* + * block_node_or_indentless_sequence ::= + * ALIAS + * | properties (block_content | indentless_block_sequence)? + * | block_content + * | indentless_block_sequence + * block_node ::= ALIAS + * | properties block_content? + * | block_content + * flow_node ::= ALIAS + * | properties flow_content? + * | flow_content + * properties ::= TAG ANCHOR? | ANCHOR TAG? + * block_content ::= block_collection | flow_collection | SCALAR + * flow_content ::= flow_collection | SCALAR + * block_collection ::= block_sequence | block_mapping + * flow_collection ::= flow_sequence | flow_mapping + * block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END + * indentless_sequence ::= (BLOCK-ENTRY block_node?)+ + * block_mapping ::= BLOCK-MAPPING_START + * ((KEY block_node_or_indentless_sequence?)? + * (VALUE block_node_or_indentless_sequence?)?)* + * BLOCK-END + * flow_sequence ::= FLOW-SEQUENCE-START + * (flow_sequence_entry FLOW-ENTRY)* + * flow_sequence_entry? + * FLOW-SEQUENCE-END + * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + * flow_mapping ::= FLOW-MAPPING-START + * (flow_mapping_entry FLOW-ENTRY)* + * flow_mapping_entry? + * FLOW-MAPPING-END + * flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + */ + +#include "yaml_private.h" + +/* + * Peek the next token in the token queue. + */ + +#define PEEK_TOKEN(parser) \ + ((parser->token_available || yaml_parser_fetch_more_tokens(parser)) ? \ + parser->tokens.head : NULL) + +/* + * Remove the next token from the queue (must be called after PEEK_TOKEN). + */ + +#define SKIP_TOKEN(parser) \ + (parser->token_available = 0, \ + parser->tokens_parsed ++, \ + parser->stream_end_produced = \ + (parser->tokens.head->type == YAML_STREAM_END_TOKEN), \ + parser->tokens.head ++) + +/* + * Public API declarations. + */ + +YAML_DECLARE(int) +yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event); + +/* + * Error handling. + */ + +static int +yaml_parser_set_parser_error(yaml_parser_t *parser, + const char *problem, yaml_mark_t problem_mark); + +static int +yaml_parser_set_parser_error_context(yaml_parser_t *parser, + const char *context, yaml_mark_t context_mark, + const char *problem, yaml_mark_t problem_mark); + +/* + * State functions. + */ + +static int +yaml_parser_state_machine(yaml_parser_t *parser, yaml_event_t *event); + +static int +yaml_parser_parse_stream_start(yaml_parser_t *parser, yaml_event_t *event); + +static int +yaml_parser_parse_document_start(yaml_parser_t *parser, yaml_event_t *event, + int implicit); + +static int +yaml_parser_parse_document_content(yaml_parser_t *parser, yaml_event_t *event); + +static int +yaml_parser_parse_document_end(yaml_parser_t *parser, yaml_event_t *event); + +static int +yaml_parser_parse_node(yaml_parser_t *parser, yaml_event_t *event, + int block, int indentless_sequence); + +static int +yaml_parser_parse_block_sequence_entry(yaml_parser_t *parser, + yaml_event_t *event, int first); + +static int +yaml_parser_parse_indentless_sequence_entry(yaml_parser_t *parser, + yaml_event_t *event); + +static int +yaml_parser_parse_block_mapping_key(yaml_parser_t *parser, + yaml_event_t *event, int first); + +static int +yaml_parser_parse_block_mapping_value(yaml_parser_t *parser, + yaml_event_t *event); + +static int +yaml_parser_parse_flow_sequence_entry(yaml_parser_t *parser, + yaml_event_t *event, int first); + +static int +yaml_parser_parse_flow_sequence_entry_mapping_key(yaml_parser_t *parser, + yaml_event_t *event); + +static int +yaml_parser_parse_flow_sequence_entry_mapping_value(yaml_parser_t *parser, + yaml_event_t *event); + +static int +yaml_parser_parse_flow_sequence_entry_mapping_end(yaml_parser_t *parser, + yaml_event_t *event); + +static int +yaml_parser_parse_flow_mapping_key(yaml_parser_t *parser, + yaml_event_t *event, int first); + +static int +yaml_parser_parse_flow_mapping_value(yaml_parser_t *parser, + yaml_event_t *event, int empty); + +/* + * Utility functions. + */ + +static int +yaml_parser_process_empty_scalar(yaml_parser_t *parser, + yaml_event_t *event, yaml_mark_t mark); + +static int +yaml_parser_process_directives(yaml_parser_t *parser, + yaml_version_directive_t **version_directive_ref, + yaml_tag_directive_t **tag_directives_start_ref, + yaml_tag_directive_t **tag_directives_end_ref); + +static int +yaml_parser_append_tag_directive(yaml_parser_t *parser, + yaml_tag_directive_t value, int allow_duplicates, yaml_mark_t mark); + +/* + * Get the next event. + */ + +YAML_DECLARE(int) +yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event) +{ + assert(parser); /* Non-NULL parser object is expected. */ + assert(event); /* Non-NULL event object is expected. */ + + /* Erase the event object. */ + + memset(event, 0, sizeof(yaml_event_t)); + + /* No events after the end of the stream or error. */ + + if (parser->stream_end_produced || parser->error || + parser->state == YAML_PARSE_END_STATE) { + return 1; + } + + /* Generate the next event. */ + + return yaml_parser_state_machine(parser, event); +} + +/* + * Set parser error. + */ + +static int +yaml_parser_set_parser_error(yaml_parser_t *parser, + const char *problem, yaml_mark_t problem_mark) +{ + parser->error = YAML_PARSER_ERROR; + parser->problem = problem; + parser->problem_mark = problem_mark; + + return 0; +} + +static int +yaml_parser_set_parser_error_context(yaml_parser_t *parser, + const char *context, yaml_mark_t context_mark, + const char *problem, yaml_mark_t problem_mark) +{ + parser->error = YAML_PARSER_ERROR; + parser->context = context; + parser->context_mark = context_mark; + parser->problem = problem; + parser->problem_mark = problem_mark; + + return 0; +} + + +/* + * State dispatcher. + */ + +static int +yaml_parser_state_machine(yaml_parser_t *parser, yaml_event_t *event) +{ + switch (parser->state) + { + case YAML_PARSE_STREAM_START_STATE: + return yaml_parser_parse_stream_start(parser, event); + + case YAML_PARSE_IMPLICIT_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, 1); + + case YAML_PARSE_DOCUMENT_START_STATE: + return yaml_parser_parse_document_start(parser, event, 0); + + case YAML_PARSE_DOCUMENT_CONTENT_STATE: + return yaml_parser_parse_document_content(parser, event); + + case YAML_PARSE_DOCUMENT_END_STATE: + return yaml_parser_parse_document_end(parser, event); + + case YAML_PARSE_BLOCK_NODE_STATE: + return yaml_parser_parse_node(parser, event, 1, 0); + + case YAML_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: + return yaml_parser_parse_node(parser, event, 1, 1); + + case YAML_PARSE_FLOW_NODE_STATE: + return yaml_parser_parse_node(parser, event, 0, 0); + + case YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, 1); + + case YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_block_sequence_entry(parser, event, 0); + + case YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_indentless_sequence_entry(parser, event); + + case YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, 1); + + case YAML_PARSE_BLOCK_MAPPING_KEY_STATE: + return yaml_parser_parse_block_mapping_key(parser, event, 0); + + case YAML_PARSE_BLOCK_MAPPING_VALUE_STATE: + return yaml_parser_parse_block_mapping_value(parser, event); + + case YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, 1); + + case YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE: + return yaml_parser_parse_flow_sequence_entry(parser, event, 0); + + case YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event); + + case YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event); + + case YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: + return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event); + + case YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, 1); + + case YAML_PARSE_FLOW_MAPPING_KEY_STATE: + return yaml_parser_parse_flow_mapping_key(parser, event, 0); + + case YAML_PARSE_FLOW_MAPPING_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, 0); + + case YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: + return yaml_parser_parse_flow_mapping_value(parser, event, 1); + + default: + assert(1); /* Invalid state. */ + } + + return 0; +} + +/* + * Parse the production: + * stream ::= STREAM-START implicit_document? explicit_document* STREAM-END + * ************ + */ + +static int +yaml_parser_parse_stream_start(yaml_parser_t *parser, yaml_event_t *event) +{ + yaml_token_t *token; + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (token->type != YAML_STREAM_START_TOKEN) { + return yaml_parser_set_parser_error(parser, + "did not find expected ", token->start_mark); + } + + parser->state = YAML_PARSE_IMPLICIT_DOCUMENT_START_STATE; + STREAM_START_EVENT_INIT(*event, token->data.stream_start.encoding, + token->start_mark, token->start_mark); + SKIP_TOKEN(parser); + + return 1; +} + +/* + * Parse the productions: + * implicit_document ::= block_node DOCUMENT-END* + * * + * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* + * ************************* + */ + +static int +yaml_parser_parse_document_start(yaml_parser_t *parser, yaml_event_t *event, + int implicit) +{ + yaml_token_t *token; + yaml_version_directive_t *version_directive = NULL; + struct { + yaml_tag_directive_t *start; + yaml_tag_directive_t *end; + } tag_directives = { NULL, NULL }; + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + /* Parse extra document end indicators. */ + + if (!implicit) + { + while (token->type == YAML_DOCUMENT_END_TOKEN) { + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) return 0; + } + } + + /* Parse an implicit document. */ + + if (implicit && token->type != YAML_VERSION_DIRECTIVE_TOKEN && + token->type != YAML_TAG_DIRECTIVE_TOKEN && + token->type != YAML_DOCUMENT_START_TOKEN && + token->type != YAML_STREAM_END_TOKEN) + { + if (!yaml_parser_process_directives(parser, NULL, NULL, NULL)) + return 0; + if (!PUSH(parser, parser->states, YAML_PARSE_DOCUMENT_END_STATE)) + return 0; + parser->state = YAML_PARSE_BLOCK_NODE_STATE; + DOCUMENT_START_EVENT_INIT(*event, NULL, NULL, NULL, 1, + token->start_mark, token->start_mark); + return 1; + } + + /* Parse an explicit document. */ + + else if (token->type != YAML_STREAM_END_TOKEN) + { + yaml_mark_t start_mark, end_mark; + start_mark = token->start_mark; + if (!yaml_parser_process_directives(parser, &version_directive, + &tag_directives.start, &tag_directives.end)) + return 0; + token = PEEK_TOKEN(parser); + if (!token) goto error; + if (token->type != YAML_DOCUMENT_START_TOKEN) { + yaml_parser_set_parser_error(parser, + "did not find expected ", token->start_mark); + goto error; + } + if (!PUSH(parser, parser->states, YAML_PARSE_DOCUMENT_END_STATE)) + goto error; + parser->state = YAML_PARSE_DOCUMENT_CONTENT_STATE; + end_mark = token->end_mark; + DOCUMENT_START_EVENT_INIT(*event, version_directive, + tag_directives.start, tag_directives.end, 0, + start_mark, end_mark); + SKIP_TOKEN(parser); + version_directive = NULL; + tag_directives.start = tag_directives.end = NULL; + return 1; + } + + /* Parse the stream end. */ + + else + { + parser->state = YAML_PARSE_END_STATE; + STREAM_END_EVENT_INIT(*event, token->start_mark, token->end_mark); + SKIP_TOKEN(parser); + return 1; + } + +error: + yaml_free(version_directive); + while (tag_directives.start != tag_directives.end) { + yaml_free(tag_directives.end[-1].handle); + yaml_free(tag_directives.end[-1].prefix); + tag_directives.end --; + } + yaml_free(tag_directives.start); + return 0; +} + +/* + * Parse the productions: + * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* + * *********** + */ + +static int +yaml_parser_parse_document_content(yaml_parser_t *parser, yaml_event_t *event) +{ + yaml_token_t *token; + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (token->type == YAML_VERSION_DIRECTIVE_TOKEN || + token->type == YAML_TAG_DIRECTIVE_TOKEN || + token->type == YAML_DOCUMENT_START_TOKEN || + token->type == YAML_DOCUMENT_END_TOKEN || + token->type == YAML_STREAM_END_TOKEN) { + parser->state = POP(parser, parser->states); + return yaml_parser_process_empty_scalar(parser, event, + token->start_mark); + } + else { + return yaml_parser_parse_node(parser, event, 1, 0); + } +} + +/* + * Parse the productions: + * implicit_document ::= block_node DOCUMENT-END* + * ************* + * explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* + * ************* + */ + +static int +yaml_parser_parse_document_end(yaml_parser_t *parser, yaml_event_t *event) +{ + yaml_token_t *token; + yaml_mark_t start_mark, end_mark; + int implicit = 1; + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + start_mark = end_mark = token->start_mark; + + if (token->type == YAML_DOCUMENT_END_TOKEN) { + end_mark = token->end_mark; + SKIP_TOKEN(parser); + implicit = 0; + } + + while (!STACK_EMPTY(parser, parser->tag_directives)) { + yaml_tag_directive_t tag_directive = POP(parser, parser->tag_directives); + yaml_free(tag_directive.handle); + yaml_free(tag_directive.prefix); + } + + parser->state = YAML_PARSE_DOCUMENT_START_STATE; + DOCUMENT_END_EVENT_INIT(*event, implicit, start_mark, end_mark); + + return 1; +} + +/* + * Parse the productions: + * block_node_or_indentless_sequence ::= + * ALIAS + * ***** + * | properties (block_content | indentless_block_sequence)? + * ********** * + * | block_content | indentless_block_sequence + * * + * block_node ::= ALIAS + * ***** + * | properties block_content? + * ********** * + * | block_content + * * + * flow_node ::= ALIAS + * ***** + * | properties flow_content? + * ********** * + * | flow_content + * * + * properties ::= TAG ANCHOR? | ANCHOR TAG? + * ************************* + * block_content ::= block_collection | flow_collection | SCALAR + * ****** + * flow_content ::= flow_collection | SCALAR + * ****** + */ + +static int +yaml_parser_parse_node(yaml_parser_t *parser, yaml_event_t *event, + int block, int indentless_sequence) +{ + yaml_token_t *token; + yaml_char_t *anchor = NULL; + yaml_char_t *tag_handle = NULL; + yaml_char_t *tag_suffix = NULL; + yaml_char_t *tag = NULL; + yaml_mark_t start_mark, end_mark, tag_mark; + int implicit; + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (token->type == YAML_ALIAS_TOKEN) + { + parser->state = POP(parser, parser->states); + ALIAS_EVENT_INIT(*event, token->data.alias.value, + token->start_mark, token->end_mark); + SKIP_TOKEN(parser); + return 1; + } + + else + { + start_mark = end_mark = token->start_mark; + + if (token->type == YAML_ANCHOR_TOKEN) + { + anchor = token->data.anchor.value; + start_mark = token->start_mark; + end_mark = token->end_mark; + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) goto error; + if (token->type == YAML_TAG_TOKEN) + { + tag_handle = token->data.tag.handle; + tag_suffix = token->data.tag.suffix; + tag_mark = token->start_mark; + end_mark = token->end_mark; + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) goto error; + } + } + else if (token->type == YAML_TAG_TOKEN) + { + tag_handle = token->data.tag.handle; + tag_suffix = token->data.tag.suffix; + start_mark = tag_mark = token->start_mark; + end_mark = token->end_mark; + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) goto error; + if (token->type == YAML_ANCHOR_TOKEN) + { + anchor = token->data.anchor.value; + end_mark = token->end_mark; + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) goto error; + } + } + + if (tag_handle) { + if (!*tag_handle) { + tag = tag_suffix; + yaml_free(tag_handle); + tag_handle = tag_suffix = NULL; + } + else { + yaml_tag_directive_t *tag_directive; + for (tag_directive = parser->tag_directives.start; + tag_directive != parser->tag_directives.top; + tag_directive ++) { + if (strcmp((char *)tag_directive->handle, (char *)tag_handle) == 0) { + size_t prefix_len = strlen((char *)tag_directive->prefix); + size_t suffix_len = strlen((char *)tag_suffix); + tag = YAML_MALLOC(prefix_len+suffix_len+1); + if (!tag) { + parser->error = YAML_MEMORY_ERROR; + goto error; + } + memcpy(tag, tag_directive->prefix, prefix_len); + memcpy(tag+prefix_len, tag_suffix, suffix_len); + tag[prefix_len+suffix_len] = '\0'; + yaml_free(tag_handle); + yaml_free(tag_suffix); + tag_handle = tag_suffix = NULL; + break; + } + } + if (!tag) { + yaml_parser_set_parser_error_context(parser, + "while parsing a node", start_mark, + "found undefined tag handle", tag_mark); + goto error; + } + } + } + + implicit = (!tag || !*tag); + if (indentless_sequence && token->type == YAML_BLOCK_ENTRY_TOKEN) { + end_mark = token->end_mark; + parser->state = YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE; + SEQUENCE_START_EVENT_INIT(*event, anchor, tag, implicit, + YAML_BLOCK_SEQUENCE_STYLE, start_mark, end_mark); + return 1; + } + else { + if (token->type == YAML_SCALAR_TOKEN) { + int plain_implicit = 0; + int quoted_implicit = 0; + end_mark = token->end_mark; + if ((token->data.scalar.style == YAML_PLAIN_SCALAR_STYLE && !tag) + || (tag && strcmp((char *)tag, "!") == 0)) { + plain_implicit = 1; + } + else if (!tag) { + quoted_implicit = 1; + } + parser->state = POP(parser, parser->states); + SCALAR_EVENT_INIT(*event, anchor, tag, + token->data.scalar.value, token->data.scalar.length, + plain_implicit, quoted_implicit, + token->data.scalar.style, start_mark, end_mark); + SKIP_TOKEN(parser); + return 1; + } + else if (token->type == YAML_FLOW_SEQUENCE_START_TOKEN) { + end_mark = token->end_mark; + parser->state = YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE; + SEQUENCE_START_EVENT_INIT(*event, anchor, tag, implicit, + YAML_FLOW_SEQUENCE_STYLE, start_mark, end_mark); + return 1; + } + else if (token->type == YAML_FLOW_MAPPING_START_TOKEN) { + end_mark = token->end_mark; + parser->state = YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE; + MAPPING_START_EVENT_INIT(*event, anchor, tag, implicit, + YAML_FLOW_MAPPING_STYLE, start_mark, end_mark); + return 1; + } + else if (block && token->type == YAML_BLOCK_SEQUENCE_START_TOKEN) { + end_mark = token->end_mark; + parser->state = YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE; + SEQUENCE_START_EVENT_INIT(*event, anchor, tag, implicit, + YAML_BLOCK_SEQUENCE_STYLE, start_mark, end_mark); + return 1; + } + else if (block && token->type == YAML_BLOCK_MAPPING_START_TOKEN) { + end_mark = token->end_mark; + parser->state = YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE; + MAPPING_START_EVENT_INIT(*event, anchor, tag, implicit, + YAML_BLOCK_MAPPING_STYLE, start_mark, end_mark); + return 1; + } + else if (anchor || tag) { + yaml_char_t *value = YAML_MALLOC(1); + if (!value) { + parser->error = YAML_MEMORY_ERROR; + goto error; + } + value[0] = '\0'; + parser->state = POP(parser, parser->states); + SCALAR_EVENT_INIT(*event, anchor, tag, value, 0, + implicit, 0, YAML_PLAIN_SCALAR_STYLE, + start_mark, end_mark); + return 1; + } + else { + yaml_parser_set_parser_error_context(parser, + (block ? "while parsing a block node" + : "while parsing a flow node"), start_mark, + "did not find expected node content", token->start_mark); + goto error; + } + } + } + +error: + yaml_free(anchor); + yaml_free(tag_handle); + yaml_free(tag_suffix); + yaml_free(tag); + + return 0; +} + +/* + * Parse the productions: + * block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END + * ******************** *********** * ********* + */ + +static int +yaml_parser_parse_block_sequence_entry(yaml_parser_t *parser, + yaml_event_t *event, int first) +{ + yaml_token_t *token; + + if (first) { + token = PEEK_TOKEN(parser); + if (!PUSH(parser, parser->marks, token->start_mark)) + return 0; + SKIP_TOKEN(parser); + } + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (token->type == YAML_BLOCK_ENTRY_TOKEN) + { + yaml_mark_t mark = token->end_mark; + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) return 0; + if (token->type != YAML_BLOCK_ENTRY_TOKEN && + token->type != YAML_BLOCK_END_TOKEN) { + if (!PUSH(parser, parser->states, + YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE)) + return 0; + return yaml_parser_parse_node(parser, event, 1, 0); + } + else { + parser->state = YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE; + return yaml_parser_process_empty_scalar(parser, event, mark); + } + } + + else if (token->type == YAML_BLOCK_END_TOKEN) + { + parser->state = POP(parser, parser->states); + (void)POP(parser, parser->marks); + SEQUENCE_END_EVENT_INIT(*event, token->start_mark, token->end_mark); + SKIP_TOKEN(parser); + return 1; + } + + else + { + return yaml_parser_set_parser_error_context(parser, + "while parsing a block collection", POP(parser, parser->marks), + "did not find expected '-' indicator", token->start_mark); + } +} + +/* + * Parse the productions: + * indentless_sequence ::= (BLOCK-ENTRY block_node?)+ + * *********** * + */ + +static int +yaml_parser_parse_indentless_sequence_entry(yaml_parser_t *parser, + yaml_event_t *event) +{ + yaml_token_t *token; + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (token->type == YAML_BLOCK_ENTRY_TOKEN) + { + yaml_mark_t mark = token->end_mark; + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) return 0; + if (token->type != YAML_BLOCK_ENTRY_TOKEN && + token->type != YAML_KEY_TOKEN && + token->type != YAML_VALUE_TOKEN && + token->type != YAML_BLOCK_END_TOKEN) { + if (!PUSH(parser, parser->states, + YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE)) + return 0; + return yaml_parser_parse_node(parser, event, 1, 0); + } + else { + parser->state = YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE; + return yaml_parser_process_empty_scalar(parser, event, mark); + } + } + + else + { + parser->state = POP(parser, parser->states); + SEQUENCE_END_EVENT_INIT(*event, token->start_mark, token->start_mark); + return 1; + } +} + +/* + * Parse the productions: + * block_mapping ::= BLOCK-MAPPING_START + * ******************* + * ((KEY block_node_or_indentless_sequence?)? + * *** * + * (VALUE block_node_or_indentless_sequence?)?)* + * + * BLOCK-END + * ********* + */ + +static int +yaml_parser_parse_block_mapping_key(yaml_parser_t *parser, + yaml_event_t *event, int first) +{ + yaml_token_t *token; + + if (first) { + token = PEEK_TOKEN(parser); + if (!PUSH(parser, parser->marks, token->start_mark)) + return 0; + SKIP_TOKEN(parser); + } + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (token->type == YAML_KEY_TOKEN) + { + yaml_mark_t mark = token->end_mark; + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) return 0; + if (token->type != YAML_KEY_TOKEN && + token->type != YAML_VALUE_TOKEN && + token->type != YAML_BLOCK_END_TOKEN) { + if (!PUSH(parser, parser->states, + YAML_PARSE_BLOCK_MAPPING_VALUE_STATE)) + return 0; + return yaml_parser_parse_node(parser, event, 1, 1); + } + else { + parser->state = YAML_PARSE_BLOCK_MAPPING_VALUE_STATE; + return yaml_parser_process_empty_scalar(parser, event, mark); + } + } + + else if (token->type == YAML_BLOCK_END_TOKEN) + { + parser->state = POP(parser, parser->states); + (void)POP(parser, parser->marks); + MAPPING_END_EVENT_INIT(*event, token->start_mark, token->end_mark); + SKIP_TOKEN(parser); + return 1; + } + + else + { + return yaml_parser_set_parser_error_context(parser, + "while parsing a block mapping", POP(parser, parser->marks), + "did not find expected key", token->start_mark); + } +} + +/* + * Parse the productions: + * block_mapping ::= BLOCK-MAPPING_START + * + * ((KEY block_node_or_indentless_sequence?)? + * + * (VALUE block_node_or_indentless_sequence?)?)* + * ***** * + * BLOCK-END + * + */ + +static int +yaml_parser_parse_block_mapping_value(yaml_parser_t *parser, + yaml_event_t *event) +{ + yaml_token_t *token; + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (token->type == YAML_VALUE_TOKEN) + { + yaml_mark_t mark = token->end_mark; + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) return 0; + if (token->type != YAML_KEY_TOKEN && + token->type != YAML_VALUE_TOKEN && + token->type != YAML_BLOCK_END_TOKEN) { + if (!PUSH(parser, parser->states, + YAML_PARSE_BLOCK_MAPPING_KEY_STATE)) + return 0; + return yaml_parser_parse_node(parser, event, 1, 1); + } + else { + parser->state = YAML_PARSE_BLOCK_MAPPING_KEY_STATE; + return yaml_parser_process_empty_scalar(parser, event, mark); + } + } + + else + { + parser->state = YAML_PARSE_BLOCK_MAPPING_KEY_STATE; + return yaml_parser_process_empty_scalar(parser, event, token->start_mark); + } +} + +/* + * Parse the productions: + * flow_sequence ::= FLOW-SEQUENCE-START + * ******************* + * (flow_sequence_entry FLOW-ENTRY)* + * * ********** + * flow_sequence_entry? + * * + * FLOW-SEQUENCE-END + * ***************** + * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + * * + */ + +static int +yaml_parser_parse_flow_sequence_entry(yaml_parser_t *parser, + yaml_event_t *event, int first) +{ + yaml_token_t *token; + + if (first) { + token = PEEK_TOKEN(parser); + if (!PUSH(parser, parser->marks, token->start_mark)) + return 0; + SKIP_TOKEN(parser); + } + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (token->type != YAML_FLOW_SEQUENCE_END_TOKEN) + { + if (!first) { + if (token->type == YAML_FLOW_ENTRY_TOKEN) { + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) return 0; + } + else { + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow sequence", POP(parser, parser->marks), + "did not find expected ',' or ']'", token->start_mark); + } + } + + if (token->type == YAML_KEY_TOKEN) { + parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE; + MAPPING_START_EVENT_INIT(*event, NULL, NULL, + 1, YAML_FLOW_MAPPING_STYLE, + token->start_mark, token->end_mark); + SKIP_TOKEN(parser); + return 1; + } + + else if (token->type != YAML_FLOW_SEQUENCE_END_TOKEN) { + if (!PUSH(parser, parser->states, + YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE)) + return 0; + return yaml_parser_parse_node(parser, event, 0, 0); + } + } + + parser->state = POP(parser, parser->states); + (void)POP(parser, parser->marks); + SEQUENCE_END_EVENT_INIT(*event, token->start_mark, token->end_mark); + SKIP_TOKEN(parser); + return 1; +} + +/* + * Parse the productions: + * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + * *** * + */ + +static int +yaml_parser_parse_flow_sequence_entry_mapping_key(yaml_parser_t *parser, + yaml_event_t *event) +{ + yaml_token_t *token; + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (token->type != YAML_VALUE_TOKEN && token->type != YAML_FLOW_ENTRY_TOKEN + && token->type != YAML_FLOW_SEQUENCE_END_TOKEN) { + if (!PUSH(parser, parser->states, + YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE)) + return 0; + return yaml_parser_parse_node(parser, event, 0, 0); + } + else { + yaml_mark_t mark = token->end_mark; + SKIP_TOKEN(parser); + parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE; + return yaml_parser_process_empty_scalar(parser, event, mark); + } +} + +/* + * Parse the productions: + * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + * ***** * + */ + +static int +yaml_parser_parse_flow_sequence_entry_mapping_value(yaml_parser_t *parser, + yaml_event_t *event) +{ + yaml_token_t *token; + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (token->type == YAML_VALUE_TOKEN) { + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) return 0; + if (token->type != YAML_FLOW_ENTRY_TOKEN + && token->type != YAML_FLOW_SEQUENCE_END_TOKEN) { + if (!PUSH(parser, parser->states, + YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE)) + return 0; + return yaml_parser_parse_node(parser, event, 0, 0); + } + } + parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE; + return yaml_parser_process_empty_scalar(parser, event, token->start_mark); +} + +/* + * Parse the productions: + * flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + * * + */ + +static int +yaml_parser_parse_flow_sequence_entry_mapping_end(yaml_parser_t *parser, + yaml_event_t *event) +{ + yaml_token_t *token; + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + parser->state = YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE; + + MAPPING_END_EVENT_INIT(*event, token->start_mark, token->start_mark); + return 1; +} + +/* + * Parse the productions: + * flow_mapping ::= FLOW-MAPPING-START + * ****************** + * (flow_mapping_entry FLOW-ENTRY)* + * * ********** + * flow_mapping_entry? + * ****************** + * FLOW-MAPPING-END + * **************** + * flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + * * *** * + */ + +static int +yaml_parser_parse_flow_mapping_key(yaml_parser_t *parser, + yaml_event_t *event, int first) +{ + yaml_token_t *token; + + if (first) { + token = PEEK_TOKEN(parser); + if (!PUSH(parser, parser->marks, token->start_mark)) + return 0; + SKIP_TOKEN(parser); + } + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (token->type != YAML_FLOW_MAPPING_END_TOKEN) + { + if (!first) { + if (token->type == YAML_FLOW_ENTRY_TOKEN) { + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) return 0; + } + else { + return yaml_parser_set_parser_error_context(parser, + "while parsing a flow mapping", POP(parser, parser->marks), + "did not find expected ',' or '}'", token->start_mark); + } + } + + if (token->type == YAML_KEY_TOKEN) { + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) return 0; + if (token->type != YAML_VALUE_TOKEN + && token->type != YAML_FLOW_ENTRY_TOKEN + && token->type != YAML_FLOW_MAPPING_END_TOKEN) { + if (!PUSH(parser, parser->states, + YAML_PARSE_FLOW_MAPPING_VALUE_STATE)) + return 0; + return yaml_parser_parse_node(parser, event, 0, 0); + } + else { + parser->state = YAML_PARSE_FLOW_MAPPING_VALUE_STATE; + return yaml_parser_process_empty_scalar(parser, event, + token->start_mark); + } + } + else if (token->type != YAML_FLOW_MAPPING_END_TOKEN) { + if (!PUSH(parser, parser->states, + YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE)) + return 0; + return yaml_parser_parse_node(parser, event, 0, 0); + } + } + + parser->state = POP(parser, parser->states); + (void)POP(parser, parser->marks); + MAPPING_END_EVENT_INIT(*event, token->start_mark, token->end_mark); + SKIP_TOKEN(parser); + return 1; +} + +/* + * Parse the productions: + * flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + * * ***** * + */ + +static int +yaml_parser_parse_flow_mapping_value(yaml_parser_t *parser, + yaml_event_t *event, int empty) +{ + yaml_token_t *token; + + token = PEEK_TOKEN(parser); + if (!token) return 0; + + if (empty) { + parser->state = YAML_PARSE_FLOW_MAPPING_KEY_STATE; + return yaml_parser_process_empty_scalar(parser, event, + token->start_mark); + } + + if (token->type == YAML_VALUE_TOKEN) { + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) return 0; + if (token->type != YAML_FLOW_ENTRY_TOKEN + && token->type != YAML_FLOW_MAPPING_END_TOKEN) { + if (!PUSH(parser, parser->states, + YAML_PARSE_FLOW_MAPPING_KEY_STATE)) + return 0; + return yaml_parser_parse_node(parser, event, 0, 0); + } + } + + parser->state = YAML_PARSE_FLOW_MAPPING_KEY_STATE; + return yaml_parser_process_empty_scalar(parser, event, token->start_mark); +} + +/* + * Generate an empty scalar event. + */ + +static int +yaml_parser_process_empty_scalar(yaml_parser_t *parser, yaml_event_t *event, + yaml_mark_t mark) +{ + yaml_char_t *value; + + value = YAML_MALLOC(1); + if (!value) { + parser->error = YAML_MEMORY_ERROR; + return 0; + } + value[0] = '\0'; + + SCALAR_EVENT_INIT(*event, NULL, NULL, value, 0, + 1, 0, YAML_PLAIN_SCALAR_STYLE, mark, mark); + + return 1; +} + +/* + * Parse directives. + */ + +static int +yaml_parser_process_directives(yaml_parser_t *parser, + yaml_version_directive_t **version_directive_ref, + yaml_tag_directive_t **tag_directives_start_ref, + yaml_tag_directive_t **tag_directives_end_ref) +{ + yaml_tag_directive_t default_tag_directives[] = { + {(yaml_char_t *)"!", (yaml_char_t *)"!"}, + {(yaml_char_t *)"!!", (yaml_char_t *)"tag:yaml.org,2002:"}, + {NULL, NULL} + }; + yaml_tag_directive_t *default_tag_directive; + yaml_version_directive_t *version_directive = NULL; + struct { + yaml_tag_directive_t *start; + yaml_tag_directive_t *end; + yaml_tag_directive_t *top; + } tag_directives = { NULL, NULL, NULL }; + yaml_token_t *token; + + if (!STACK_INIT(parser, tag_directives, yaml_tag_directive_t*)) + goto error; + + token = PEEK_TOKEN(parser); + if (!token) goto error; + + while (token->type == YAML_VERSION_DIRECTIVE_TOKEN || + token->type == YAML_TAG_DIRECTIVE_TOKEN) + { + if (token->type == YAML_VERSION_DIRECTIVE_TOKEN) { + if (version_directive) { + yaml_parser_set_parser_error(parser, + "found duplicate %YAML directive", token->start_mark); + goto error; + } + if (token->data.version_directive.major != 1 + || ( + token->data.version_directive.minor != 1 + && token->data.version_directive.minor != 2 + )) { + yaml_parser_set_parser_error(parser, + "found incompatible YAML document", token->start_mark); + goto error; + } + version_directive = YAML_MALLOC_STATIC(yaml_version_directive_t); + if (!version_directive) { + parser->error = YAML_MEMORY_ERROR; + goto error; + } + version_directive->major = token->data.version_directive.major; + version_directive->minor = token->data.version_directive.minor; + } + + else if (token->type == YAML_TAG_DIRECTIVE_TOKEN) { + yaml_tag_directive_t value; + value.handle = token->data.tag_directive.handle; + value.prefix = token->data.tag_directive.prefix; + + if (!yaml_parser_append_tag_directive(parser, value, 0, + token->start_mark)) + goto error; + if (!PUSH(parser, tag_directives, value)) + goto error; + } + + SKIP_TOKEN(parser); + token = PEEK_TOKEN(parser); + if (!token) goto error; + } + + for (default_tag_directive = default_tag_directives; + default_tag_directive->handle; default_tag_directive++) { + if (!yaml_parser_append_tag_directive(parser, *default_tag_directive, 1, + token->start_mark)) + goto error; + } + + if (version_directive_ref) { + *version_directive_ref = version_directive; + } + if (tag_directives_start_ref) { + if (STACK_EMPTY(parser, tag_directives)) { + *tag_directives_start_ref = *tag_directives_end_ref = NULL; + STACK_DEL(parser, tag_directives); + } + else { + *tag_directives_start_ref = tag_directives.start; + *tag_directives_end_ref = tag_directives.top; + } + } + else { + STACK_DEL(parser, tag_directives); + } + + if (!version_directive_ref) + yaml_free(version_directive); + return 1; + +error: + yaml_free(version_directive); + while (!STACK_EMPTY(parser, tag_directives)) { + yaml_tag_directive_t tag_directive = POP(parser, tag_directives); + yaml_free(tag_directive.handle); + yaml_free(tag_directive.prefix); + } + STACK_DEL(parser, tag_directives); + return 0; +} + +/* + * Append a tag directive to the directives stack. + */ + +static int +yaml_parser_append_tag_directive(yaml_parser_t *parser, + yaml_tag_directive_t value, int allow_duplicates, yaml_mark_t mark) +{ + yaml_tag_directive_t *tag_directive; + yaml_tag_directive_t copy = { NULL, NULL }; + + for (tag_directive = parser->tag_directives.start; + tag_directive != parser->tag_directives.top; tag_directive ++) { + if (strcmp((char *)value.handle, (char *)tag_directive->handle) == 0) { + if (allow_duplicates) + return 1; + return yaml_parser_set_parser_error(parser, + "found duplicate %TAG directive", mark); + } + } + + copy.handle = yaml_strdup(value.handle); + copy.prefix = yaml_strdup(value.prefix); + if (!copy.handle || !copy.prefix) { + parser->error = YAML_MEMORY_ERROR; + goto error; + } + + if (!PUSH(parser, parser->tag_directives, copy)) + goto error; + + return 1; + +error: + yaml_free(copy.handle); + yaml_free(copy.prefix); + return 0; +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/reader.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/reader.c new file mode 100644 index 0000000..f3ac54c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/reader.c @@ -0,0 +1,469 @@ + +#include "yaml_private.h" + +/* + * Declarations. + */ + +static int +yaml_parser_set_reader_error(yaml_parser_t *parser, const char *problem, + size_t offset, int value); + +static int +yaml_parser_update_raw_buffer(yaml_parser_t *parser); + +static int +yaml_parser_determine_encoding(yaml_parser_t *parser); + +YAML_DECLARE(int) +yaml_parser_update_buffer(yaml_parser_t *parser, size_t length); + +/* + * Set the reader error and return 0. + */ + +static int +yaml_parser_set_reader_error(yaml_parser_t *parser, const char *problem, + size_t offset, int value) +{ + parser->error = YAML_READER_ERROR; + parser->problem = problem; + parser->problem_offset = offset; + parser->problem_value = value; + + return 0; +} + +/* + * Byte order marks. + */ + +#define BOM_UTF8 "\xef\xbb\xbf" +#define BOM_UTF16LE "\xff\xfe" +#define BOM_UTF16BE "\xfe\xff" + +/* + * Determine the input stream encoding by checking the BOM symbol. If no BOM is + * found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. + */ + +static int +yaml_parser_determine_encoding(yaml_parser_t *parser) +{ + /* Ensure that we had enough bytes in the raw buffer. */ + + while (!parser->eof + && parser->raw_buffer.last - parser->raw_buffer.pointer < 3) { + if (!yaml_parser_update_raw_buffer(parser)) { + return 0; + } + } + + /* Determine the encoding. */ + + if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 2 + && !memcmp(parser->raw_buffer.pointer, BOM_UTF16LE, 2)) { + parser->encoding = YAML_UTF16LE_ENCODING; + parser->raw_buffer.pointer += 2; + parser->offset += 2; + } + else if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 2 + && !memcmp(parser->raw_buffer.pointer, BOM_UTF16BE, 2)) { + parser->encoding = YAML_UTF16BE_ENCODING; + parser->raw_buffer.pointer += 2; + parser->offset += 2; + } + else if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 3 + && !memcmp(parser->raw_buffer.pointer, BOM_UTF8, 3)) { + parser->encoding = YAML_UTF8_ENCODING; + parser->raw_buffer.pointer += 3; + parser->offset += 3; + } + else { + parser->encoding = YAML_UTF8_ENCODING; + } + + return 1; +} + +/* + * Update the raw buffer. + */ + +static int +yaml_parser_update_raw_buffer(yaml_parser_t *parser) +{ + size_t size_read = 0; + + /* Return if the raw buffer is full. */ + + if (parser->raw_buffer.start == parser->raw_buffer.pointer + && parser->raw_buffer.last == parser->raw_buffer.end) + return 1; + + /* Return on EOF. */ + + if (parser->eof) return 1; + + /* Move the remaining bytes in the raw buffer to the beginning. */ + + if (parser->raw_buffer.start < parser->raw_buffer.pointer + && parser->raw_buffer.pointer < parser->raw_buffer.last) { + memmove(parser->raw_buffer.start, parser->raw_buffer.pointer, + parser->raw_buffer.last - parser->raw_buffer.pointer); + } + parser->raw_buffer.last -= + parser->raw_buffer.pointer - parser->raw_buffer.start; + parser->raw_buffer.pointer = parser->raw_buffer.start; + + /* Call the read handler to fill the buffer. */ + + if (!parser->read_handler(parser->read_handler_data, parser->raw_buffer.last, + parser->raw_buffer.end - parser->raw_buffer.last, &size_read)) { + return yaml_parser_set_reader_error(parser, "input error", + parser->offset, -1); + } + parser->raw_buffer.last += size_read; + if (!size_read) { + parser->eof = 1; + } + + return 1; +} + +/* + * Ensure that the buffer contains at least `length` characters. + * Return 1 on success, 0 on failure. + * + * The length is supposed to be significantly less that the buffer size. + */ + +YAML_DECLARE(int) +yaml_parser_update_buffer(yaml_parser_t *parser, size_t length) +{ + int first = 1; + + assert(parser->read_handler); /* Read handler must be set. */ + + /* If the EOF flag is set and the raw buffer is empty, do nothing. */ + + if (parser->eof && parser->raw_buffer.pointer == parser->raw_buffer.last) + return 1; + + /* Return if the buffer contains enough characters. */ + + if (parser->unread >= length) + return 1; + + /* Determine the input encoding if it is not known yet. */ + + if (!parser->encoding) { + if (!yaml_parser_determine_encoding(parser)) + return 0; + } + + /* Move the unread characters to the beginning of the buffer. */ + + if (parser->buffer.start < parser->buffer.pointer + && parser->buffer.pointer < parser->buffer.last) { + size_t size = parser->buffer.last - parser->buffer.pointer; + memmove(parser->buffer.start, parser->buffer.pointer, size); + parser->buffer.pointer = parser->buffer.start; + parser->buffer.last = parser->buffer.start + size; + } + else if (parser->buffer.pointer == parser->buffer.last) { + parser->buffer.pointer = parser->buffer.start; + parser->buffer.last = parser->buffer.start; + } + + /* Fill the buffer until it has enough characters. */ + + while (parser->unread < length) + { + /* Fill the raw buffer if necessary. */ + + if (!first || parser->raw_buffer.pointer == parser->raw_buffer.last) { + if (!yaml_parser_update_raw_buffer(parser)) return 0; + } + first = 0; + + /* Decode the raw buffer. */ + + while (parser->raw_buffer.pointer != parser->raw_buffer.last) + { + unsigned int value = 0, value2 = 0; + int incomplete = 0; + unsigned char octet; + unsigned int width = 0; + int low, high; + size_t k; + size_t raw_unread = parser->raw_buffer.last - parser->raw_buffer.pointer; + + /* Decode the next character. */ + + switch (parser->encoding) + { + case YAML_UTF8_ENCODING: + + /* + * Decode a UTF-8 character. Check RFC 3629 + * (http://www.ietf.org/rfc/rfc3629.txt) for more details. + * + * The following table (taken from the RFC) is used for + * decoding. + * + * Char. number range | UTF-8 octet sequence + * (hexadecimal) | (binary) + * --------------------+------------------------------------ + * 0000 0000-0000 007F | 0xxxxxxx + * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx + * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx + * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + * + * Additionally, the characters in the range 0xD800-0xDFFF + * are prohibited as they are reserved for use with UTF-16 + * surrogate pairs. + */ + + /* Determine the length of the UTF-8 sequence. */ + + octet = parser->raw_buffer.pointer[0]; + width = (octet & 0x80) == 0x00 ? 1 : + (octet & 0xE0) == 0xC0 ? 2 : + (octet & 0xF0) == 0xE0 ? 3 : + (octet & 0xF8) == 0xF0 ? 4 : 0; + + /* Check if the leading octet is valid. */ + + if (!width) + return yaml_parser_set_reader_error(parser, + "invalid leading UTF-8 octet", + parser->offset, octet); + + /* Check if the raw buffer contains an incomplete character. */ + + if (width > raw_unread) { + if (parser->eof) { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-8 octet sequence", + parser->offset, -1); + } + incomplete = 1; + break; + } + + /* Decode the leading octet. */ + + value = (octet & 0x80) == 0x00 ? octet & 0x7F : + (octet & 0xE0) == 0xC0 ? octet & 0x1F : + (octet & 0xF0) == 0xE0 ? octet & 0x0F : + (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; + + /* Check and decode the trailing octets. */ + + for (k = 1; k < width; k ++) + { + octet = parser->raw_buffer.pointer[k]; + + /* Check if the octet is valid. */ + + if ((octet & 0xC0) != 0x80) + return yaml_parser_set_reader_error(parser, + "invalid trailing UTF-8 octet", + parser->offset+k, octet); + + /* Decode the octet. */ + + value = (value << 6) + (octet & 0x3F); + } + + /* Check the length of the sequence against the value. */ + + if (!((width == 1) || + (width == 2 && value >= 0x80) || + (width == 3 && value >= 0x800) || + (width == 4 && value >= 0x10000))) + return yaml_parser_set_reader_error(parser, + "invalid length of a UTF-8 sequence", + parser->offset, -1); + + /* Check the range of the value. */ + + if ((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) + return yaml_parser_set_reader_error(parser, + "invalid Unicode character", + parser->offset, value); + + break; + + case YAML_UTF16LE_ENCODING: + case YAML_UTF16BE_ENCODING: + + low = (parser->encoding == YAML_UTF16LE_ENCODING ? 0 : 1); + high = (parser->encoding == YAML_UTF16LE_ENCODING ? 1 : 0); + + /* + * The UTF-16 encoding is not as simple as one might + * naively think. Check RFC 2781 + * (http://www.ietf.org/rfc/rfc2781.txt). + * + * Normally, two subsequent bytes describe a Unicode + * character. However a special technique (called a + * surrogate pair) is used for specifying character + * values larger than 0xFFFF. + * + * A surrogate pair consists of two pseudo-characters: + * high surrogate area (0xD800-0xDBFF) + * low surrogate area (0xDC00-0xDFFF) + * + * The following formulas are used for decoding + * and encoding characters using surrogate pairs: + * + * U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) + * U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) + * W1 = 110110yyyyyyyyyy + * W2 = 110111xxxxxxxxxx + * + * where U is the character value, W1 is the high surrogate + * area, W2 is the low surrogate area. + */ + + /* Check for incomplete UTF-16 character. */ + + if (raw_unread < 2) { + if (parser->eof) { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 character", + parser->offset, -1); + } + incomplete = 1; + break; + } + + /* Get the character. */ + + value = parser->raw_buffer.pointer[low] + + (parser->raw_buffer.pointer[high] << 8); + + /* Check for unexpected low surrogate area. */ + + if ((value & 0xFC00) == 0xDC00) + return yaml_parser_set_reader_error(parser, + "unexpected low surrogate area", + parser->offset, value); + + /* Check for a high surrogate area. */ + + if ((value & 0xFC00) == 0xD800) { + + width = 4; + + /* Check for incomplete surrogate pair. */ + + if (raw_unread < 4) { + if (parser->eof) { + return yaml_parser_set_reader_error(parser, + "incomplete UTF-16 surrogate pair", + parser->offset, -1); + } + incomplete = 1; + break; + } + + /* Get the next character. */ + + value2 = parser->raw_buffer.pointer[low+2] + + (parser->raw_buffer.pointer[high+2] << 8); + + /* Check for a low surrogate area. */ + + if ((value2 & 0xFC00) != 0xDC00) + return yaml_parser_set_reader_error(parser, + "expected low surrogate area", + parser->offset+2, value2); + + /* Generate the value of the surrogate pair. */ + + value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF); + } + + else { + width = 2; + } + + break; + + default: + assert(1); /* Impossible. */ + } + + /* Check if the raw buffer contains enough bytes to form a character. */ + + if (incomplete) break; + + /* + * Check if the character is in the allowed range: + * #x9 | #xA | #xD | [#x20-#x7E] (8 bit) + * | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) + * | [#x10000-#x10FFFF] (32 bit) + */ + + if (! (value == 0x09 || value == 0x0A || value == 0x0D + || (value >= 0x20 && value <= 0x7E) + || (value == 0x85) || (value >= 0xA0 && value <= 0xD7FF) + || (value >= 0xE000 && value <= 0xFFFD) + || (value >= 0x10000 && value <= 0x10FFFF))) + return yaml_parser_set_reader_error(parser, + "control characters are not allowed", + parser->offset, value); + + /* Move the raw pointers. */ + + parser->raw_buffer.pointer += width; + parser->offset += width; + + /* Finally put the character into the buffer. */ + + /* 0000 0000-0000 007F -> 0xxxxxxx */ + if (value <= 0x7F) { + *(parser->buffer.last++) = value; + } + /* 0000 0080-0000 07FF -> 110xxxxx 10xxxxxx */ + else if (value <= 0x7FF) { + *(parser->buffer.last++) = 0xC0 + (value >> 6); + *(parser->buffer.last++) = 0x80 + (value & 0x3F); + } + /* 0000 0800-0000 FFFF -> 1110xxxx 10xxxxxx 10xxxxxx */ + else if (value <= 0xFFFF) { + *(parser->buffer.last++) = 0xE0 + (value >> 12); + *(parser->buffer.last++) = 0x80 + ((value >> 6) & 0x3F); + *(parser->buffer.last++) = 0x80 + (value & 0x3F); + } + /* 0001 0000-0010 FFFF -> 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + else { + *(parser->buffer.last++) = 0xF0 + (value >> 18); + *(parser->buffer.last++) = 0x80 + ((value >> 12) & 0x3F); + *(parser->buffer.last++) = 0x80 + ((value >> 6) & 0x3F); + *(parser->buffer.last++) = 0x80 + (value & 0x3F); + } + + parser->unread ++; + } + + /* On EOF, put NUL into the buffer and return. */ + + if (parser->eof) { + *(parser->buffer.last++) = '\0'; + parser->unread ++; + return 1; + } + + } + + if (parser->offset >= MAX_FILE_SIZE) { + return yaml_parser_set_reader_error(parser, "input is too long", + parser->offset, -1); + } + + return 1; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/scanner.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/scanner.c new file mode 100644 index 0000000..bb5d201 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/scanner.c @@ -0,0 +1,3598 @@ + +/* + * Introduction + * ************ + * + * The following notes assume that you are familiar with the YAML specification + * (http://yaml.org/spec/cvs/current.html). We mostly follow it, although in + * some cases we are less restrictive that it requires. + * + * The process of transforming a YAML stream into a sequence of events is + * divided on two steps: Scanning and Parsing. + * + * The Scanner transforms the input stream into a sequence of tokens, while the + * parser transform the sequence of tokens produced by the Scanner into a + * sequence of parsing events. + * + * The Scanner is rather clever and complicated. The Parser, on the contrary, + * is a straightforward implementation of a recursive-descendant parser (or, + * LL(1) parser, as it is usually called). + * + * Actually there are two issues of Scanning that might be called "clever", the + * rest is quite straightforward. The issues are "block collection start" and + * "simple keys". Both issues are explained below in details. + * + * Here the Scanning step is explained and implemented. We start with the list + * of all the tokens produced by the Scanner together with short descriptions. + * + * Now, tokens: + * + * STREAM-START(encoding) # The stream start. + * STREAM-END # The stream end. + * VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. + * TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. + * DOCUMENT-START # '---' + * DOCUMENT-END # '...' + * BLOCK-SEQUENCE-START # Indentation increase denoting a block + * BLOCK-MAPPING-START # sequence or a block mapping. + * BLOCK-END # Indentation decrease. + * FLOW-SEQUENCE-START # '[' + * FLOW-SEQUENCE-END # ']' + * FLOW-MAPPING-START # '{' + * FLOW-MAPPING-END # '}' + * BLOCK-ENTRY # '-' + * FLOW-ENTRY # ',' + * KEY # '?' or nothing (simple keys). + * VALUE # ':' + * ALIAS(anchor) # '*anchor' + * ANCHOR(anchor) # '&anchor' + * TAG(handle,suffix) # '!handle!suffix' + * SCALAR(value,style) # A scalar. + * + * The following two tokens are "virtual" tokens denoting the beginning and the + * end of the stream: + * + * STREAM-START(encoding) + * STREAM-END + * + * We pass the information about the input stream encoding with the + * STREAM-START token. + * + * The next two tokens are responsible for tags: + * + * VERSION-DIRECTIVE(major,minor) + * TAG-DIRECTIVE(handle,prefix) + * + * Example: + * + * %YAML 1.1 + * %TAG ! !foo + * %TAG !yaml! tag:yaml.org,2002: + * --- + * + * The corresponding sequence of tokens: + * + * STREAM-START(utf-8) + * VERSION-DIRECTIVE(1,1) + * TAG-DIRECTIVE("!","!foo") + * TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") + * DOCUMENT-START + * STREAM-END + * + * Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole + * line. + * + * The document start and end indicators are represented by: + * + * DOCUMENT-START + * DOCUMENT-END + * + * Note that if a YAML stream contains an implicit document (without '---' + * and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be + * produced. + * + * In the following examples, we present whole documents together with the + * produced tokens. + * + * 1. An implicit document: + * + * 'a scalar' + * + * Tokens: + * + * STREAM-START(utf-8) + * SCALAR("a scalar",single-quoted) + * STREAM-END + * + * 2. An explicit document: + * + * --- + * 'a scalar' + * ... + * + * Tokens: + * + * STREAM-START(utf-8) + * DOCUMENT-START + * SCALAR("a scalar",single-quoted) + * DOCUMENT-END + * STREAM-END + * + * 3. Several documents in a stream: + * + * 'a scalar' + * --- + * 'another scalar' + * --- + * 'yet another scalar' + * + * Tokens: + * + * STREAM-START(utf-8) + * SCALAR("a scalar",single-quoted) + * DOCUMENT-START + * SCALAR("another scalar",single-quoted) + * DOCUMENT-START + * SCALAR("yet another scalar",single-quoted) + * STREAM-END + * + * We have already introduced the SCALAR token above. The following tokens are + * used to describe aliases, anchors, tag, and scalars: + * + * ALIAS(anchor) + * ANCHOR(anchor) + * TAG(handle,suffix) + * SCALAR(value,style) + * + * The following series of examples illustrate the usage of these tokens: + * + * 1. A recursive sequence: + * + * &A [ *A ] + * + * Tokens: + * + * STREAM-START(utf-8) + * ANCHOR("A") + * FLOW-SEQUENCE-START + * ALIAS("A") + * FLOW-SEQUENCE-END + * STREAM-END + * + * 2. A tagged scalar: + * + * !!float "3.14" # A good approximation. + * + * Tokens: + * + * STREAM-START(utf-8) + * TAG("!!","float") + * SCALAR("3.14",double-quoted) + * STREAM-END + * + * 3. Various scalar styles: + * + * --- # Implicit empty plain scalars do not produce tokens. + * --- a plain scalar + * --- 'a single-quoted scalar' + * --- "a double-quoted scalar" + * --- |- + * a literal scalar + * --- >- + * a folded + * scalar + * + * Tokens: + * + * STREAM-START(utf-8) + * DOCUMENT-START + * DOCUMENT-START + * SCALAR("a plain scalar",plain) + * DOCUMENT-START + * SCALAR("a single-quoted scalar",single-quoted) + * DOCUMENT-START + * SCALAR("a double-quoted scalar",double-quoted) + * DOCUMENT-START + * SCALAR("a literal scalar",literal) + * DOCUMENT-START + * SCALAR("a folded scalar",folded) + * STREAM-END + * + * Now it's time to review collection-related tokens. We will start with + * flow collections: + * + * FLOW-SEQUENCE-START + * FLOW-SEQUENCE-END + * FLOW-MAPPING-START + * FLOW-MAPPING-END + * FLOW-ENTRY + * KEY + * VALUE + * + * The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and + * FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' + * correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the + * indicators '?' and ':', which are used for denoting mapping keys and values, + * are represented by the KEY and VALUE tokens. + * + * The following examples show flow collections: + * + * 1. A flow sequence: + * + * [item 1, item 2, item 3] + * + * Tokens: + * + * STREAM-START(utf-8) + * FLOW-SEQUENCE-START + * SCALAR("item 1",plain) + * FLOW-ENTRY + * SCALAR("item 2",plain) + * FLOW-ENTRY + * SCALAR("item 3",plain) + * FLOW-SEQUENCE-END + * STREAM-END + * + * 2. A flow mapping: + * + * { + * a simple key: a value, # Note that the KEY token is produced. + * ? a complex key: another value, + * } + * + * Tokens: + * + * STREAM-START(utf-8) + * FLOW-MAPPING-START + * KEY + * SCALAR("a simple key",plain) + * VALUE + * SCALAR("a value",plain) + * FLOW-ENTRY + * KEY + * SCALAR("a complex key",plain) + * VALUE + * SCALAR("another value",plain) + * FLOW-ENTRY + * FLOW-MAPPING-END + * STREAM-END + * + * A simple key is a key which is not denoted by the '?' indicator. Note that + * the Scanner still produce the KEY token whenever it encounters a simple key. + * + * For scanning block collections, the following tokens are used (note that we + * repeat KEY and VALUE here): + * + * BLOCK-SEQUENCE-START + * BLOCK-MAPPING-START + * BLOCK-END + * BLOCK-ENTRY + * KEY + * VALUE + * + * The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation + * increase that precedes a block collection (cf. the INDENT token in Python). + * The token BLOCK-END denote indentation decrease that ends a block collection + * (cf. the DEDENT token in Python). However YAML has some syntax peculiarities + * that makes detections of these tokens more complex. + * + * The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators + * '-', '?', and ':' correspondingly. + * + * The following examples show how the tokens BLOCK-SEQUENCE-START, + * BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: + * + * 1. Block sequences: + * + * - item 1 + * - item 2 + * - + * - item 3.1 + * - item 3.2 + * - + * key 1: value 1 + * key 2: value 2 + * + * Tokens: + * + * STREAM-START(utf-8) + * BLOCK-SEQUENCE-START + * BLOCK-ENTRY + * SCALAR("item 1",plain) + * BLOCK-ENTRY + * SCALAR("item 2",plain) + * BLOCK-ENTRY + * BLOCK-SEQUENCE-START + * BLOCK-ENTRY + * SCALAR("item 3.1",plain) + * BLOCK-ENTRY + * SCALAR("item 3.2",plain) + * BLOCK-END + * BLOCK-ENTRY + * BLOCK-MAPPING-START + * KEY + * SCALAR("key 1",plain) + * VALUE + * SCALAR("value 1",plain) + * KEY + * SCALAR("key 2",plain) + * VALUE + * SCALAR("value 2",plain) + * BLOCK-END + * BLOCK-END + * STREAM-END + * + * 2. Block mappings: + * + * a simple key: a value # The KEY token is produced here. + * ? a complex key + * : another value + * a mapping: + * key 1: value 1 + * key 2: value 2 + * a sequence: + * - item 1 + * - item 2 + * + * Tokens: + * + * STREAM-START(utf-8) + * BLOCK-MAPPING-START + * KEY + * SCALAR("a simple key",plain) + * VALUE + * SCALAR("a value",plain) + * KEY + * SCALAR("a complex key",plain) + * VALUE + * SCALAR("another value",plain) + * KEY + * SCALAR("a mapping",plain) + * VALUE + * BLOCK-MAPPING-START + * KEY + * SCALAR("key 1",plain) + * VALUE + * SCALAR("value 1",plain) + * KEY + * SCALAR("key 2",plain) + * VALUE + * SCALAR("value 2",plain) + * BLOCK-END + * KEY + * SCALAR("a sequence",plain) + * VALUE + * BLOCK-SEQUENCE-START + * BLOCK-ENTRY + * SCALAR("item 1",plain) + * BLOCK-ENTRY + * SCALAR("item 2",plain) + * BLOCK-END + * BLOCK-END + * STREAM-END + * + * YAML does not always require to start a new block collection from a new + * line. If the current line contains only '-', '?', and ':' indicators, a new + * block collection may start at the current line. The following examples + * illustrate this case: + * + * 1. Collections in a sequence: + * + * - - item 1 + * - item 2 + * - key 1: value 1 + * key 2: value 2 + * - ? complex key + * : complex value + * + * Tokens: + * + * STREAM-START(utf-8) + * BLOCK-SEQUENCE-START + * BLOCK-ENTRY + * BLOCK-SEQUENCE-START + * BLOCK-ENTRY + * SCALAR("item 1",plain) + * BLOCK-ENTRY + * SCALAR("item 2",plain) + * BLOCK-END + * BLOCK-ENTRY + * BLOCK-MAPPING-START + * KEY + * SCALAR("key 1",plain) + * VALUE + * SCALAR("value 1",plain) + * KEY + * SCALAR("key 2",plain) + * VALUE + * SCALAR("value 2",plain) + * BLOCK-END + * BLOCK-ENTRY + * BLOCK-MAPPING-START + * KEY + * SCALAR("complex key") + * VALUE + * SCALAR("complex value") + * BLOCK-END + * BLOCK-END + * STREAM-END + * + * 2. Collections in a mapping: + * + * ? a sequence + * : - item 1 + * - item 2 + * ? a mapping + * : key 1: value 1 + * key 2: value 2 + * + * Tokens: + * + * STREAM-START(utf-8) + * BLOCK-MAPPING-START + * KEY + * SCALAR("a sequence",plain) + * VALUE + * BLOCK-SEQUENCE-START + * BLOCK-ENTRY + * SCALAR("item 1",plain) + * BLOCK-ENTRY + * SCALAR("item 2",plain) + * BLOCK-END + * KEY + * SCALAR("a mapping",plain) + * VALUE + * BLOCK-MAPPING-START + * KEY + * SCALAR("key 1",plain) + * VALUE + * SCALAR("value 1",plain) + * KEY + * SCALAR("key 2",plain) + * VALUE + * SCALAR("value 2",plain) + * BLOCK-END + * BLOCK-END + * STREAM-END + * + * YAML also permits non-indented sequences if they are included into a block + * mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: + * + * key: + * - item 1 # BLOCK-SEQUENCE-START is NOT produced here. + * - item 2 + * + * Tokens: + * + * STREAM-START(utf-8) + * BLOCK-MAPPING-START + * KEY + * SCALAR("key",plain) + * VALUE + * BLOCK-ENTRY + * SCALAR("item 1",plain) + * BLOCK-ENTRY + * SCALAR("item 2",plain) + * BLOCK-END + */ + +#include "yaml_private.h" + +/* + * Ensure that the buffer contains the required number of characters. + * Return 1 on success, 0 on failure (reader error or memory error). + */ + +#define CACHE(parser,length) \ + (parser->unread >= (length) \ + ? 1 \ + : yaml_parser_update_buffer(parser, (length))) + +/* + * Advance the buffer pointer. + */ + +#define SKIP(parser) \ + (parser->mark.index ++, \ + parser->mark.column ++, \ + parser->unread --, \ + parser->buffer.pointer += WIDTH(parser->buffer)) + +#define SKIP_LINE(parser) \ + (IS_CRLF(parser->buffer) ? \ + (parser->mark.index += 2, \ + parser->mark.column = 0, \ + parser->mark.line ++, \ + parser->unread -= 2, \ + parser->buffer.pointer += 2) : \ + IS_BREAK(parser->buffer) ? \ + (parser->mark.index ++, \ + parser->mark.column = 0, \ + parser->mark.line ++, \ + parser->unread --, \ + parser->buffer.pointer += WIDTH(parser->buffer)) : 0) + +/* + * Copy a character to a string buffer and advance pointers. + */ + +#define READ(parser,string) \ + (STRING_EXTEND(parser,string) ? \ + (COPY(string,parser->buffer), \ + parser->mark.index ++, \ + parser->mark.column ++, \ + parser->unread --, \ + 1) : 0) + +/* + * Copy a line break character to a string buffer and advance pointers. + */ + +#define READ_LINE(parser,string) \ + (STRING_EXTEND(parser,string) ? \ + (((CHECK_AT(parser->buffer,'\r',0) \ + && CHECK_AT(parser->buffer,'\n',1)) ? /* CR LF -> LF */ \ + (*((string).pointer++) = (yaml_char_t) '\n', \ + parser->buffer.pointer += 2, \ + parser->mark.index += 2, \ + parser->mark.column = 0, \ + parser->mark.line ++, \ + parser->unread -= 2) : \ + (CHECK_AT(parser->buffer,'\r',0) \ + || CHECK_AT(parser->buffer,'\n',0)) ? /* CR|LF -> LF */ \ + (*((string).pointer++) = (yaml_char_t) '\n', \ + parser->buffer.pointer ++, \ + parser->mark.index ++, \ + parser->mark.column = 0, \ + parser->mark.line ++, \ + parser->unread --) : \ + (CHECK_AT(parser->buffer,'\xC2',0) \ + && CHECK_AT(parser->buffer,'\x85',1)) ? /* NEL -> LF */ \ + (*((string).pointer++) = (yaml_char_t) '\n', \ + parser->buffer.pointer += 2, \ + parser->mark.index ++, \ + parser->mark.column = 0, \ + parser->mark.line ++, \ + parser->unread --) : \ + (CHECK_AT(parser->buffer,'\xE2',0) && \ + CHECK_AT(parser->buffer,'\x80',1) && \ + (CHECK_AT(parser->buffer,'\xA8',2) || \ + CHECK_AT(parser->buffer,'\xA9',2))) ? /* LS|PS -> LS|PS */ \ + (*((string).pointer++) = *(parser->buffer.pointer++), \ + *((string).pointer++) = *(parser->buffer.pointer++), \ + *((string).pointer++) = *(parser->buffer.pointer++), \ + parser->mark.index ++, \ + parser->mark.column = 0, \ + parser->mark.line ++, \ + parser->unread --) : 0), \ + 1) : 0) + +/* + * Public API declarations. + */ + +YAML_DECLARE(int) +yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token); + +/* + * Error handling. + */ + +static int +yaml_parser_set_scanner_error(yaml_parser_t *parser, const char *context, + yaml_mark_t context_mark, const char *problem); + +/* + * High-level token API. + */ + +YAML_DECLARE(int) +yaml_parser_fetch_more_tokens(yaml_parser_t *parser); + +static int +yaml_parser_fetch_next_token(yaml_parser_t *parser); + +/* + * Potential simple keys. + */ + +static int +yaml_parser_stale_simple_keys(yaml_parser_t *parser); + +static int +yaml_parser_save_simple_key(yaml_parser_t *parser); + +static int +yaml_parser_remove_simple_key(yaml_parser_t *parser); + +static int +yaml_parser_increase_flow_level(yaml_parser_t *parser); + +static int +yaml_parser_decrease_flow_level(yaml_parser_t *parser); + +/* + * Indentation treatment. + */ + +static int +yaml_parser_roll_indent(yaml_parser_t *parser, ptrdiff_t column, + ptrdiff_t number, yaml_token_type_t type, yaml_mark_t mark); + +static int +yaml_parser_unroll_indent(yaml_parser_t *parser, ptrdiff_t column); + +/* + * Token fetchers. + */ + +static int +yaml_parser_fetch_stream_start(yaml_parser_t *parser); + +static int +yaml_parser_fetch_stream_end(yaml_parser_t *parser); + +static int +yaml_parser_fetch_directive(yaml_parser_t *parser); + +static int +yaml_parser_fetch_document_indicator(yaml_parser_t *parser, + yaml_token_type_t type); + +static int +yaml_parser_fetch_flow_collection_start(yaml_parser_t *parser, + yaml_token_type_t type); + +static int +yaml_parser_fetch_flow_collection_end(yaml_parser_t *parser, + yaml_token_type_t type); + +static int +yaml_parser_fetch_flow_entry(yaml_parser_t *parser); + +static int +yaml_parser_fetch_block_entry(yaml_parser_t *parser); + +static int +yaml_parser_fetch_key(yaml_parser_t *parser); + +static int +yaml_parser_fetch_value(yaml_parser_t *parser); + +static int +yaml_parser_fetch_anchor(yaml_parser_t *parser, yaml_token_type_t type); + +static int +yaml_parser_fetch_tag(yaml_parser_t *parser); + +static int +yaml_parser_fetch_block_scalar(yaml_parser_t *parser, int literal); + +static int +yaml_parser_fetch_flow_scalar(yaml_parser_t *parser, int single); + +static int +yaml_parser_fetch_plain_scalar(yaml_parser_t *parser); + +/* + * Token scanners. + */ + +static int +yaml_parser_scan_to_next_token(yaml_parser_t *parser); + +static int +yaml_parser_scan_directive(yaml_parser_t *parser, yaml_token_t *token); + +static int +yaml_parser_scan_directive_name(yaml_parser_t *parser, + yaml_mark_t start_mark, yaml_char_t **name); + +static int +yaml_parser_scan_version_directive_value(yaml_parser_t *parser, + yaml_mark_t start_mark, int *major, int *minor); + +static int +yaml_parser_scan_version_directive_number(yaml_parser_t *parser, + yaml_mark_t start_mark, int *number); + +static int +yaml_parser_scan_tag_directive_value(yaml_parser_t *parser, + yaml_mark_t mark, yaml_char_t **handle, yaml_char_t **prefix); + +static int +yaml_parser_scan_anchor(yaml_parser_t *parser, yaml_token_t *token, + yaml_token_type_t type); + +static int +yaml_parser_scan_tag(yaml_parser_t *parser, yaml_token_t *token); + +static int +yaml_parser_scan_tag_handle(yaml_parser_t *parser, int directive, + yaml_mark_t start_mark, yaml_char_t **handle); + +static int +yaml_parser_scan_tag_uri(yaml_parser_t *parser, int uri_char, int directive, + yaml_char_t *head, yaml_mark_t start_mark, yaml_char_t **uri); + +static int +yaml_parser_scan_uri_escapes(yaml_parser_t *parser, int directive, + yaml_mark_t start_mark, yaml_string_t *string); + +static int +yaml_parser_scan_block_scalar(yaml_parser_t *parser, yaml_token_t *token, + int literal); + +static int +yaml_parser_scan_block_scalar_breaks(yaml_parser_t *parser, + int *indent, yaml_string_t *breaks, + yaml_mark_t start_mark, yaml_mark_t *end_mark); + +static int +yaml_parser_scan_flow_scalar(yaml_parser_t *parser, yaml_token_t *token, + int single); + +static int +yaml_parser_scan_plain_scalar(yaml_parser_t *parser, yaml_token_t *token); + +/* + * Get the next token. + */ + +YAML_DECLARE(int) +yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token) +{ + assert(parser); /* Non-NULL parser object is expected. */ + assert(token); /* Non-NULL token object is expected. */ + + /* Erase the token object. */ + + memset(token, 0, sizeof(yaml_token_t)); + + /* No tokens after STREAM-END or error. */ + + if (parser->stream_end_produced || parser->error) { + return 1; + } + + /* Ensure that the tokens queue contains enough tokens. */ + + if (!parser->token_available) { + if (!yaml_parser_fetch_more_tokens(parser)) + return 0; + } + + /* Fetch the next token from the queue. */ + + *token = DEQUEUE(parser, parser->tokens); + parser->token_available = 0; + parser->tokens_parsed ++; + + if (token->type == YAML_STREAM_END_TOKEN) { + parser->stream_end_produced = 1; + } + + return 1; +} + +/* + * Set the scanner error and return 0. + */ + +static int +yaml_parser_set_scanner_error(yaml_parser_t *parser, const char *context, + yaml_mark_t context_mark, const char *problem) +{ + parser->error = YAML_SCANNER_ERROR; + parser->context = context; + parser->context_mark = context_mark; + parser->problem = problem; + parser->problem_mark = parser->mark; + + return 0; +} + +/* + * Ensure that the tokens queue contains at least one token which can be + * returned to the Parser. + */ + +YAML_DECLARE(int) +yaml_parser_fetch_more_tokens(yaml_parser_t *parser) +{ + int need_more_tokens; + + /* While we need more tokens to fetch, do it. */ + + while (1) + { + /* + * Check if we really need to fetch more tokens. + */ + + need_more_tokens = 0; + + if (parser->tokens.head == parser->tokens.tail) + { + /* Queue is empty. */ + + need_more_tokens = 1; + } + else + { + yaml_simple_key_t *simple_key; + + /* Check if any potential simple key may occupy the head position. */ + + if (!yaml_parser_stale_simple_keys(parser)) + return 0; + + for (simple_key = parser->simple_keys.start; + simple_key != parser->simple_keys.top; simple_key++) { + if (simple_key->possible + && simple_key->token_number == parser->tokens_parsed) { + need_more_tokens = 1; + break; + } + } + } + + /* We are finished. */ + + if (!need_more_tokens) + break; + + /* Fetch the next token. */ + + if (!yaml_parser_fetch_next_token(parser)) + return 0; + } + + parser->token_available = 1; + + return 1; +} + +/* + * The dispatcher for token fetchers. + */ + +static int +yaml_parser_fetch_next_token(yaml_parser_t *parser) +{ + /* Ensure that the buffer is initialized. */ + + if (!CACHE(parser, 1)) + return 0; + + /* Check if we just started scanning. Fetch STREAM-START then. */ + + if (!parser->stream_start_produced) + return yaml_parser_fetch_stream_start(parser); + + /* Eat whitespaces and comments until we reach the next token. */ + + if (!yaml_parser_scan_to_next_token(parser)) + return 0; + + /* Remove obsolete potential simple keys. */ + + if (!yaml_parser_stale_simple_keys(parser)) + return 0; + + /* Check the indentation level against the current column. */ + + if (!yaml_parser_unroll_indent(parser, parser->mark.column)) + return 0; + + /* + * Ensure that the buffer contains at least 4 characters. 4 is the length + * of the longest indicators ('--- ' and '... '). + */ + + if (!CACHE(parser, 4)) + return 0; + + /* Is it the end of the stream? */ + + if (IS_Z(parser->buffer)) + return yaml_parser_fetch_stream_end(parser); + + /* Is it a directive? */ + + if (parser->mark.column == 0 && CHECK(parser->buffer, '%')) + return yaml_parser_fetch_directive(parser); + + /* Is it the document start indicator? */ + + if (parser->mark.column == 0 + && CHECK_AT(parser->buffer, '-', 0) + && CHECK_AT(parser->buffer, '-', 1) + && CHECK_AT(parser->buffer, '-', 2) + && IS_BLANKZ_AT(parser->buffer, 3)) + return yaml_parser_fetch_document_indicator(parser, + YAML_DOCUMENT_START_TOKEN); + + /* Is it the document end indicator? */ + + if (parser->mark.column == 0 + && CHECK_AT(parser->buffer, '.', 0) + && CHECK_AT(parser->buffer, '.', 1) + && CHECK_AT(parser->buffer, '.', 2) + && IS_BLANKZ_AT(parser->buffer, 3)) + return yaml_parser_fetch_document_indicator(parser, + YAML_DOCUMENT_END_TOKEN); + + /* Is it the flow sequence start indicator? */ + + if (CHECK(parser->buffer, '[')) + return yaml_parser_fetch_flow_collection_start(parser, + YAML_FLOW_SEQUENCE_START_TOKEN); + + /* Is it the flow mapping start indicator? */ + + if (CHECK(parser->buffer, '{')) + return yaml_parser_fetch_flow_collection_start(parser, + YAML_FLOW_MAPPING_START_TOKEN); + + /* Is it the flow sequence end indicator? */ + + if (CHECK(parser->buffer, ']')) + return yaml_parser_fetch_flow_collection_end(parser, + YAML_FLOW_SEQUENCE_END_TOKEN); + + /* Is it the flow mapping end indicator? */ + + if (CHECK(parser->buffer, '}')) + return yaml_parser_fetch_flow_collection_end(parser, + YAML_FLOW_MAPPING_END_TOKEN); + + /* Is it the flow entry indicator? */ + + if (CHECK(parser->buffer, ',')) + return yaml_parser_fetch_flow_entry(parser); + + /* Is it the block entry indicator? */ + + if (CHECK(parser->buffer, '-') && IS_BLANKZ_AT(parser->buffer, 1)) + return yaml_parser_fetch_block_entry(parser); + + /* Is it the key indicator? */ + + if (CHECK(parser->buffer, '?') + && (parser->flow_level || IS_BLANKZ_AT(parser->buffer, 1))) + return yaml_parser_fetch_key(parser); + + /* Is it the value indicator? */ + + if (CHECK(parser->buffer, ':') + && (parser->flow_level || IS_BLANKZ_AT(parser->buffer, 1))) + return yaml_parser_fetch_value(parser); + + /* Is it an alias? */ + + if (CHECK(parser->buffer, '*')) + return yaml_parser_fetch_anchor(parser, YAML_ALIAS_TOKEN); + + /* Is it an anchor? */ + + if (CHECK(parser->buffer, '&')) + return yaml_parser_fetch_anchor(parser, YAML_ANCHOR_TOKEN); + + /* Is it a tag? */ + + if (CHECK(parser->buffer, '!')) + return yaml_parser_fetch_tag(parser); + + /* Is it a literal scalar? */ + + if (CHECK(parser->buffer, '|') && !parser->flow_level) + return yaml_parser_fetch_block_scalar(parser, 1); + + /* Is it a folded scalar? */ + + if (CHECK(parser->buffer, '>') && !parser->flow_level) + return yaml_parser_fetch_block_scalar(parser, 0); + + /* Is it a single-quoted scalar? */ + + if (CHECK(parser->buffer, '\'')) + return yaml_parser_fetch_flow_scalar(parser, 1); + + /* Is it a double-quoted scalar? */ + + if (CHECK(parser->buffer, '"')) + return yaml_parser_fetch_flow_scalar(parser, 0); + + /* + * Is it a plain scalar? + * + * A plain scalar may start with any non-blank characters except + * + * '-', '?', ':', ',', '[', ']', '{', '}', + * '#', '&', '*', '!', '|', '>', '\'', '\"', + * '%', '@', '`'. + * + * In the block context (and, for the '-' indicator, in the flow context + * too), it may also start with the characters + * + * '-', '?', ':' + * + * if it is followed by a non-space character. + * + * The last rule is more restrictive than the specification requires. + */ + + if (!(IS_BLANKZ(parser->buffer) || CHECK(parser->buffer, '-') + || CHECK(parser->buffer, '?') || CHECK(parser->buffer, ':') + || CHECK(parser->buffer, ',') || CHECK(parser->buffer, '[') + || CHECK(parser->buffer, ']') || CHECK(parser->buffer, '{') + || CHECK(parser->buffer, '}') || CHECK(parser->buffer, '#') + || CHECK(parser->buffer, '&') || CHECK(parser->buffer, '*') + || CHECK(parser->buffer, '!') || CHECK(parser->buffer, '|') + || CHECK(parser->buffer, '>') || CHECK(parser->buffer, '\'') + || CHECK(parser->buffer, '"') || CHECK(parser->buffer, '%') + || CHECK(parser->buffer, '@') || CHECK(parser->buffer, '`')) || + (CHECK(parser->buffer, '-') && !IS_BLANK_AT(parser->buffer, 1)) || + (!parser->flow_level && + (CHECK(parser->buffer, '?') || CHECK(parser->buffer, ':')) + && !IS_BLANKZ_AT(parser->buffer, 1))) + return yaml_parser_fetch_plain_scalar(parser); + + /* + * If we don't determine the token type so far, it is an error. + */ + + return yaml_parser_set_scanner_error(parser, + "while scanning for the next token", parser->mark, + "found character that cannot start any token"); +} + +/* + * Check the list of potential simple keys and remove the positions that + * cannot contain simple keys anymore. + */ + +static int +yaml_parser_stale_simple_keys(yaml_parser_t *parser) +{ + yaml_simple_key_t *simple_key; + + /* Check for a potential simple key for each flow level. */ + + for (simple_key = parser->simple_keys.start; + simple_key != parser->simple_keys.top; simple_key ++) + { + /* + * The specification requires that a simple key + * + * - is limited to a single line, + * - is shorter than 1024 characters. + */ + + if (simple_key->possible + && (simple_key->mark.line < parser->mark.line + || simple_key->mark.index+1024 < parser->mark.index)) { + + /* Check if the potential simple key to be removed is required. */ + + if (simple_key->required) { + return yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key->mark, + "could not find expected ':'"); + } + + simple_key->possible = 0; + } + } + + return 1; +} + +/* + * Check if a simple key may start at the current position and add it if + * needed. + */ + +static int +yaml_parser_save_simple_key(yaml_parser_t *parser) +{ + /* + * A simple key is required at the current position if the scanner is in + * the block context and the current column coincides with the indentation + * level. + */ + + int required = (!parser->flow_level + && parser->indent == (ptrdiff_t)parser->mark.column); + + /* + * If the current position may start a simple key, save it. + */ + + if (parser->simple_key_allowed) + { + yaml_simple_key_t simple_key; + simple_key.possible = 1; + simple_key.required = required; + simple_key.token_number = + parser->tokens_parsed + (parser->tokens.tail - parser->tokens.head); + simple_key.mark = parser->mark; + + if (!yaml_parser_remove_simple_key(parser)) return 0; + + *(parser->simple_keys.top-1) = simple_key; + } + + return 1; +} + +/* + * Remove a potential simple key at the current flow level. + */ + +static int +yaml_parser_remove_simple_key(yaml_parser_t *parser) +{ + yaml_simple_key_t *simple_key = parser->simple_keys.top-1; + + if (simple_key->possible) + { + /* If the key is required, it is an error. */ + + if (simple_key->required) { + return yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key->mark, + "could not find expected ':'"); + } + } + + /* Remove the key from the stack. */ + + simple_key->possible = 0; + + return 1; +} + +/* + * Increase the flow level and resize the simple key list if needed. + */ + +static int +yaml_parser_increase_flow_level(yaml_parser_t *parser) +{ + yaml_simple_key_t empty_simple_key = { 0, 0, 0, { 0, 0, 0 } }; + + /* Reset the simple key on the next level. */ + + if (!PUSH(parser, parser->simple_keys, empty_simple_key)) + return 0; + + /* Increase the flow level. */ + + if (parser->flow_level == INT_MAX) { + parser->error = YAML_MEMORY_ERROR; + return 0; + } + + parser->flow_level++; + + return 1; +} + +/* + * Decrease the flow level. + */ + +static int +yaml_parser_decrease_flow_level(yaml_parser_t *parser) +{ + if (parser->flow_level) { + parser->flow_level --; + (void)POP(parser, parser->simple_keys); + } + + return 1; +} + +/* + * Push the current indentation level to the stack and set the new level + * the current column is greater than the indentation level. In this case, + * append or insert the specified token into the token queue. + * + */ + +static int +yaml_parser_roll_indent(yaml_parser_t *parser, ptrdiff_t column, + ptrdiff_t number, yaml_token_type_t type, yaml_mark_t mark) +{ + yaml_token_t token; + + /* In the flow context, do nothing. */ + + if (parser->flow_level) + return 1; + + if (parser->indent < column) + { + /* + * Push the current indentation level to the stack and set the new + * indentation level. + */ + + if (!PUSH(parser, parser->indents, parser->indent)) + return 0; + + if (column > INT_MAX) { + parser->error = YAML_MEMORY_ERROR; + return 0; + } + + parser->indent = (int)column; + + /* Create a token and insert it into the queue. */ + + TOKEN_INIT(token, type, mark, mark); + + if (number == -1) { + if (!ENQUEUE(parser, parser->tokens, token)) + return 0; + } + else { + if (!QUEUE_INSERT(parser, + parser->tokens, number - parser->tokens_parsed, token)) + return 0; + } + } + + return 1; +} + +/* + * Pop indentation levels from the indents stack until the current level + * becomes less or equal to the column. For each indentation level, append + * the BLOCK-END token. + */ + + +static int +yaml_parser_unroll_indent(yaml_parser_t *parser, ptrdiff_t column) +{ + yaml_token_t token; + + /* In the flow context, do nothing. */ + + if (parser->flow_level) + return 1; + + /* Loop through the indentation levels in the stack. */ + + while (parser->indent > column) + { + /* Create a token and append it to the queue. */ + + TOKEN_INIT(token, YAML_BLOCK_END_TOKEN, parser->mark, parser->mark); + + if (!ENQUEUE(parser, parser->tokens, token)) + return 0; + + /* Pop the indentation level. */ + + parser->indent = POP(parser, parser->indents); + } + + return 1; +} + +/* + * Initialize the scanner and produce the STREAM-START token. + */ + +static int +yaml_parser_fetch_stream_start(yaml_parser_t *parser) +{ + yaml_simple_key_t simple_key = { 0, 0, 0, { 0, 0, 0 } }; + yaml_token_t token; + + /* Set the initial indentation. */ + + parser->indent = -1; + + /* Initialize the simple key stack. */ + + if (!PUSH(parser, parser->simple_keys, simple_key)) + return 0; + + /* A simple key is allowed at the beginning of the stream. */ + + parser->simple_key_allowed = 1; + + /* We have started. */ + + parser->stream_start_produced = 1; + + /* Create the STREAM-START token and append it to the queue. */ + + STREAM_START_TOKEN_INIT(token, parser->encoding, + parser->mark, parser->mark); + + if (!ENQUEUE(parser, parser->tokens, token)) + return 0; + + return 1; +} + +/* + * Produce the STREAM-END token and shut down the scanner. + */ + +static int +yaml_parser_fetch_stream_end(yaml_parser_t *parser) +{ + yaml_token_t token; + + /* Force new line. */ + + if (parser->mark.column != 0) { + parser->mark.column = 0; + parser->mark.line ++; + } + + /* Reset the indentation level. */ + + if (!yaml_parser_unroll_indent(parser, -1)) + return 0; + + /* Reset simple keys. */ + + if (!yaml_parser_remove_simple_key(parser)) + return 0; + + parser->simple_key_allowed = 0; + + /* Create the STREAM-END token and append it to the queue. */ + + STREAM_END_TOKEN_INIT(token, parser->mark, parser->mark); + + if (!ENQUEUE(parser, parser->tokens, token)) + return 0; + + return 1; +} + +/* + * Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. + */ + +static int +yaml_parser_fetch_directive(yaml_parser_t *parser) +{ + yaml_token_t token; + + /* Reset the indentation level. */ + + if (!yaml_parser_unroll_indent(parser, -1)) + return 0; + + /* Reset simple keys. */ + + if (!yaml_parser_remove_simple_key(parser)) + return 0; + + parser->simple_key_allowed = 0; + + /* Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. */ + + if (!yaml_parser_scan_directive(parser, &token)) + return 0; + + /* Append the token to the queue. */ + + if (!ENQUEUE(parser, parser->tokens, token)) { + yaml_token_delete(&token); + return 0; + } + + return 1; +} + +/* + * Produce the DOCUMENT-START or DOCUMENT-END token. + */ + +static int +yaml_parser_fetch_document_indicator(yaml_parser_t *parser, + yaml_token_type_t type) +{ + yaml_mark_t start_mark, end_mark; + yaml_token_t token; + + /* Reset the indentation level. */ + + if (!yaml_parser_unroll_indent(parser, -1)) + return 0; + + /* Reset simple keys. */ + + if (!yaml_parser_remove_simple_key(parser)) + return 0; + + parser->simple_key_allowed = 0; + + /* Consume the token. */ + + start_mark = parser->mark; + + SKIP(parser); + SKIP(parser); + SKIP(parser); + + end_mark = parser->mark; + + /* Create the DOCUMENT-START or DOCUMENT-END token. */ + + TOKEN_INIT(token, type, start_mark, end_mark); + + /* Append the token to the queue. */ + + if (!ENQUEUE(parser, parser->tokens, token)) + return 0; + + return 1; +} + +/* + * Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. + */ + +static int +yaml_parser_fetch_flow_collection_start(yaml_parser_t *parser, + yaml_token_type_t type) +{ + yaml_mark_t start_mark, end_mark; + yaml_token_t token; + + /* The indicators '[' and '{' may start a simple key. */ + + if (!yaml_parser_save_simple_key(parser)) + return 0; + + /* Increase the flow level. */ + + if (!yaml_parser_increase_flow_level(parser)) + return 0; + + /* A simple key may follow the indicators '[' and '{'. */ + + parser->simple_key_allowed = 1; + + /* Consume the token. */ + + start_mark = parser->mark; + SKIP(parser); + end_mark = parser->mark; + + /* Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. */ + + TOKEN_INIT(token, type, start_mark, end_mark); + + /* Append the token to the queue. */ + + if (!ENQUEUE(parser, parser->tokens, token)) + return 0; + + return 1; +} + +/* + * Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. + */ + +static int +yaml_parser_fetch_flow_collection_end(yaml_parser_t *parser, + yaml_token_type_t type) +{ + yaml_mark_t start_mark, end_mark; + yaml_token_t token; + + /* Reset any potential simple key on the current flow level. */ + + if (!yaml_parser_remove_simple_key(parser)) + return 0; + + /* Decrease the flow level. */ + + if (!yaml_parser_decrease_flow_level(parser)) + return 0; + + /* No simple keys after the indicators ']' and '}'. */ + + parser->simple_key_allowed = 0; + + /* Consume the token. */ + + start_mark = parser->mark; + SKIP(parser); + end_mark = parser->mark; + + /* Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. */ + + TOKEN_INIT(token, type, start_mark, end_mark); + + /* Append the token to the queue. */ + + if (!ENQUEUE(parser, parser->tokens, token)) + return 0; + + return 1; +} + +/* + * Produce the FLOW-ENTRY token. + */ + +static int +yaml_parser_fetch_flow_entry(yaml_parser_t *parser) +{ + yaml_mark_t start_mark, end_mark; + yaml_token_t token; + + /* Reset any potential simple keys on the current flow level. */ + + if (!yaml_parser_remove_simple_key(parser)) + return 0; + + /* Simple keys are allowed after ','. */ + + parser->simple_key_allowed = 1; + + /* Consume the token. */ + + start_mark = parser->mark; + SKIP(parser); + end_mark = parser->mark; + + /* Create the FLOW-ENTRY token and append it to the queue. */ + + TOKEN_INIT(token, YAML_FLOW_ENTRY_TOKEN, start_mark, end_mark); + + if (!ENQUEUE(parser, parser->tokens, token)) + return 0; + + return 1; +} + +/* + * Produce the BLOCK-ENTRY token. + */ + +static int +yaml_parser_fetch_block_entry(yaml_parser_t *parser) +{ + yaml_mark_t start_mark, end_mark; + yaml_token_t token; + + /* Check if the scanner is in the block context. */ + + if (!parser->flow_level) + { + /* Check if we are allowed to start a new entry. */ + + if (!parser->simple_key_allowed) { + return yaml_parser_set_scanner_error(parser, NULL, parser->mark, + "block sequence entries are not allowed in this context"); + } + + /* Add the BLOCK-SEQUENCE-START token if needed. */ + + if (!yaml_parser_roll_indent(parser, parser->mark.column, -1, + YAML_BLOCK_SEQUENCE_START_TOKEN, parser->mark)) + return 0; + } + else + { + /* + * It is an error for the '-' indicator to occur in the flow context, + * but we let the Parser detect and report about it because the Parser + * is able to point to the context. + */ + } + + /* Reset any potential simple keys on the current flow level. */ + + if (!yaml_parser_remove_simple_key(parser)) + return 0; + + /* Simple keys are allowed after '-'. */ + + parser->simple_key_allowed = 1; + + /* Consume the token. */ + + start_mark = parser->mark; + SKIP(parser); + end_mark = parser->mark; + + /* Create the BLOCK-ENTRY token and append it to the queue. */ + + TOKEN_INIT(token, YAML_BLOCK_ENTRY_TOKEN, start_mark, end_mark); + + if (!ENQUEUE(parser, parser->tokens, token)) + return 0; + + return 1; +} + +/* + * Produce the KEY token. + */ + +static int +yaml_parser_fetch_key(yaml_parser_t *parser) +{ + yaml_mark_t start_mark, end_mark; + yaml_token_t token; + + /* In the block context, additional checks are required. */ + + if (!parser->flow_level) + { + /* Check if we are allowed to start a new key (not necessary simple). */ + + if (!parser->simple_key_allowed) { + return yaml_parser_set_scanner_error(parser, NULL, parser->mark, + "mapping keys are not allowed in this context"); + } + + /* Add the BLOCK-MAPPING-START token if needed. */ + + if (!yaml_parser_roll_indent(parser, parser->mark.column, -1, + YAML_BLOCK_MAPPING_START_TOKEN, parser->mark)) + return 0; + } + + /* Reset any potential simple keys on the current flow level. */ + + if (!yaml_parser_remove_simple_key(parser)) + return 0; + + /* Simple keys are allowed after '?' in the block context. */ + + parser->simple_key_allowed = (!parser->flow_level); + + /* Consume the token. */ + + start_mark = parser->mark; + SKIP(parser); + end_mark = parser->mark; + + /* Create the KEY token and append it to the queue. */ + + TOKEN_INIT(token, YAML_KEY_TOKEN, start_mark, end_mark); + + if (!ENQUEUE(parser, parser->tokens, token)) + return 0; + + return 1; +} + +/* + * Produce the VALUE token. + */ + +static int +yaml_parser_fetch_value(yaml_parser_t *parser) +{ + yaml_mark_t start_mark, end_mark; + yaml_token_t token; + yaml_simple_key_t *simple_key = parser->simple_keys.top-1; + + /* Have we found a simple key? */ + + if (simple_key->possible) + { + + /* Create the KEY token and insert it into the queue. */ + + TOKEN_INIT(token, YAML_KEY_TOKEN, simple_key->mark, simple_key->mark); + + if (!QUEUE_INSERT(parser, parser->tokens, + simple_key->token_number - parser->tokens_parsed, token)) + return 0; + + /* In the block context, we may need to add the BLOCK-MAPPING-START token. */ + + if (!yaml_parser_roll_indent(parser, simple_key->mark.column, + simple_key->token_number, + YAML_BLOCK_MAPPING_START_TOKEN, simple_key->mark)) + return 0; + + /* Remove the simple key. */ + + simple_key->possible = 0; + + /* A simple key cannot follow another simple key. */ + + parser->simple_key_allowed = 0; + } + else + { + /* The ':' indicator follows a complex key. */ + + /* In the block context, extra checks are required. */ + + if (!parser->flow_level) + { + /* Check if we are allowed to start a complex value. */ + + if (!parser->simple_key_allowed) { + return yaml_parser_set_scanner_error(parser, NULL, parser->mark, + "mapping values are not allowed in this context"); + } + + /* Add the BLOCK-MAPPING-START token if needed. */ + + if (!yaml_parser_roll_indent(parser, parser->mark.column, -1, + YAML_BLOCK_MAPPING_START_TOKEN, parser->mark)) + return 0; + } + + /* Simple keys after ':' are allowed in the block context. */ + + parser->simple_key_allowed = (!parser->flow_level); + } + + /* Consume the token. */ + + start_mark = parser->mark; + SKIP(parser); + end_mark = parser->mark; + + /* Create the VALUE token and append it to the queue. */ + + TOKEN_INIT(token, YAML_VALUE_TOKEN, start_mark, end_mark); + + if (!ENQUEUE(parser, parser->tokens, token)) + return 0; + + return 1; +} + +/* + * Produce the ALIAS or ANCHOR token. + */ + +static int +yaml_parser_fetch_anchor(yaml_parser_t *parser, yaml_token_type_t type) +{ + yaml_token_t token; + + /* An anchor or an alias could be a simple key. */ + + if (!yaml_parser_save_simple_key(parser)) + return 0; + + /* A simple key cannot follow an anchor or an alias. */ + + parser->simple_key_allowed = 0; + + /* Create the ALIAS or ANCHOR token and append it to the queue. */ + + if (!yaml_parser_scan_anchor(parser, &token, type)) + return 0; + + if (!ENQUEUE(parser, parser->tokens, token)) { + yaml_token_delete(&token); + return 0; + } + return 1; +} + +/* + * Produce the TAG token. + */ + +static int +yaml_parser_fetch_tag(yaml_parser_t *parser) +{ + yaml_token_t token; + + /* A tag could be a simple key. */ + + if (!yaml_parser_save_simple_key(parser)) + return 0; + + /* A simple key cannot follow a tag. */ + + parser->simple_key_allowed = 0; + + /* Create the TAG token and append it to the queue. */ + + if (!yaml_parser_scan_tag(parser, &token)) + return 0; + + if (!ENQUEUE(parser, parser->tokens, token)) { + yaml_token_delete(&token); + return 0; + } + + return 1; +} + +/* + * Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. + */ + +static int +yaml_parser_fetch_block_scalar(yaml_parser_t *parser, int literal) +{ + yaml_token_t token; + + /* Remove any potential simple keys. */ + + if (!yaml_parser_remove_simple_key(parser)) + return 0; + + /* A simple key may follow a block scalar. */ + + parser->simple_key_allowed = 1; + + /* Create the SCALAR token and append it to the queue. */ + + if (!yaml_parser_scan_block_scalar(parser, &token, literal)) + return 0; + + if (!ENQUEUE(parser, parser->tokens, token)) { + yaml_token_delete(&token); + return 0; + } + + return 1; +} + +/* + * Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. + */ + +static int +yaml_parser_fetch_flow_scalar(yaml_parser_t *parser, int single) +{ + yaml_token_t token; + + /* A plain scalar could be a simple key. */ + + if (!yaml_parser_save_simple_key(parser)) + return 0; + + /* A simple key cannot follow a flow scalar. */ + + parser->simple_key_allowed = 0; + + /* Create the SCALAR token and append it to the queue. */ + + if (!yaml_parser_scan_flow_scalar(parser, &token, single)) + return 0; + + if (!ENQUEUE(parser, parser->tokens, token)) { + yaml_token_delete(&token); + return 0; + } + + return 1; +} + +/* + * Produce the SCALAR(...,plain) token. + */ + +static int +yaml_parser_fetch_plain_scalar(yaml_parser_t *parser) +{ + yaml_token_t token; + + /* A plain scalar could be a simple key. */ + + if (!yaml_parser_save_simple_key(parser)) + return 0; + + /* A simple key cannot follow a flow scalar. */ + + parser->simple_key_allowed = 0; + + /* Create the SCALAR token and append it to the queue. */ + + if (!yaml_parser_scan_plain_scalar(parser, &token)) + return 0; + + if (!ENQUEUE(parser, parser->tokens, token)) { + yaml_token_delete(&token); + return 0; + } + + return 1; +} + +/* + * Eat whitespaces and comments until the next token is found. + */ + +static int +yaml_parser_scan_to_next_token(yaml_parser_t *parser) +{ + /* Until the next token is not found. */ + + while (1) + { + /* Allow the BOM mark to start a line. */ + + if (!CACHE(parser, 1)) return 0; + + if (parser->mark.column == 0 && IS_BOM(parser->buffer)) + SKIP(parser); + + /* + * Eat whitespaces. + * + * Tabs are allowed: + * + * - in the flow context; + * - in the block context, but not at the beginning of the line or + * after '-', '?', or ':' (complex value). + */ + + if (!CACHE(parser, 1)) return 0; + + while (CHECK(parser->buffer,' ') || + ((parser->flow_level || !parser->simple_key_allowed) && + CHECK(parser->buffer, '\t'))) { + SKIP(parser); + if (!CACHE(parser, 1)) return 0; + } + + /* Eat a comment until a line break. */ + + if (CHECK(parser->buffer, '#')) { + while (!IS_BREAKZ(parser->buffer)) { + SKIP(parser); + if (!CACHE(parser, 1)) return 0; + } + } + + /* If it is a line break, eat it. */ + + if (IS_BREAK(parser->buffer)) + { + if (!CACHE(parser, 2)) return 0; + SKIP_LINE(parser); + + /* In the block context, a new line may start a simple key. */ + + if (!parser->flow_level) { + parser->simple_key_allowed = 1; + } + } + else + { + /* We have found a token. */ + + break; + } + } + + return 1; +} + +/* + * Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. + * + * Scope: + * %YAML 1.1 # a comment \n + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * %TAG !yaml! tag:yaml.org,2002: \n + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + */ + +int +yaml_parser_scan_directive(yaml_parser_t *parser, yaml_token_t *token) +{ + yaml_mark_t start_mark, end_mark; + yaml_char_t *name = NULL; + int major, minor; + yaml_char_t *handle = NULL, *prefix = NULL; + + /* Eat '%'. */ + + start_mark = parser->mark; + + SKIP(parser); + + /* Scan the directive name. */ + + if (!yaml_parser_scan_directive_name(parser, start_mark, &name)) + goto error; + + /* Is it a YAML directive? */ + + if (strcmp((char *)name, "YAML") == 0) + { + /* Scan the VERSION directive value. */ + + if (!yaml_parser_scan_version_directive_value(parser, start_mark, + &major, &minor)) + goto error; + + end_mark = parser->mark; + + /* Create a VERSION-DIRECTIVE token. */ + + VERSION_DIRECTIVE_TOKEN_INIT(*token, major, minor, + start_mark, end_mark); + } + + /* Is it a TAG directive? */ + + else if (strcmp((char *)name, "TAG") == 0) + { + /* Scan the TAG directive value. */ + + if (!yaml_parser_scan_tag_directive_value(parser, start_mark, + &handle, &prefix)) + goto error; + + end_mark = parser->mark; + + /* Create a TAG-DIRECTIVE token. */ + + TAG_DIRECTIVE_TOKEN_INIT(*token, handle, prefix, + start_mark, end_mark); + } + + /* Unknown directive. */ + + else + { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unknown directive name"); + goto error; + } + + /* Eat the rest of the line including any comments. */ + + if (!CACHE(parser, 1)) goto error; + + while (IS_BLANK(parser->buffer)) { + SKIP(parser); + if (!CACHE(parser, 1)) goto error; + } + + if (CHECK(parser->buffer, '#')) { + while (!IS_BREAKZ(parser->buffer)) { + SKIP(parser); + if (!CACHE(parser, 1)) goto error; + } + } + + /* Check if we are at the end of the line. */ + + if (!IS_BREAKZ(parser->buffer)) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "did not find expected comment or line break"); + goto error; + } + + /* Eat a line break. */ + + if (IS_BREAK(parser->buffer)) { + if (!CACHE(parser, 2)) goto error; + SKIP_LINE(parser); + } + + yaml_free(name); + + return 1; + +error: + yaml_free(prefix); + yaml_free(handle); + yaml_free(name); + return 0; +} + +/* + * Scan the directive name. + * + * Scope: + * %YAML 1.1 # a comment \n + * ^^^^ + * %TAG !yaml! tag:yaml.org,2002: \n + * ^^^ + */ + +static int +yaml_parser_scan_directive_name(yaml_parser_t *parser, + yaml_mark_t start_mark, yaml_char_t **name) +{ + yaml_string_t string = NULL_STRING; + + if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error; + + /* Consume the directive name. */ + + if (!CACHE(parser, 1)) goto error; + + while (IS_ALPHA(parser->buffer)) + { + if (!READ(parser, string)) goto error; + if (!CACHE(parser, 1)) goto error; + } + + /* Check if the name is empty. */ + + if (string.start == string.pointer) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "could not find expected directive name"); + goto error; + } + + /* Check for an blank character after the name. */ + + if (!IS_BLANKZ(parser->buffer)) { + yaml_parser_set_scanner_error(parser, "while scanning a directive", + start_mark, "found unexpected non-alphabetical character"); + goto error; + } + + *name = string.start; + + return 1; + +error: + STRING_DEL(parser, string); + return 0; +} + +/* + * Scan the value of VERSION-DIRECTIVE. + * + * Scope: + * %YAML 1.1 # a comment \n + * ^^^^^^ + */ + +static int +yaml_parser_scan_version_directive_value(yaml_parser_t *parser, + yaml_mark_t start_mark, int *major, int *minor) +{ + /* Eat whitespaces. */ + + if (!CACHE(parser, 1)) return 0; + + while (IS_BLANK(parser->buffer)) { + SKIP(parser); + if (!CACHE(parser, 1)) return 0; + } + + /* Consume the major version number. */ + + if (!yaml_parser_scan_version_directive_number(parser, start_mark, major)) + return 0; + + /* Eat '.'. */ + + if (!CHECK(parser->buffer, '.')) { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected digit or '.' character"); + } + + SKIP(parser); + + /* Consume the minor version number. */ + + if (!yaml_parser_scan_version_directive_number(parser, start_mark, minor)) + return 0; + + return 1; +} + +#define MAX_NUMBER_LENGTH 9 + +/* + * Scan the version number of VERSION-DIRECTIVE. + * + * Scope: + * %YAML 1.1 # a comment \n + * ^ + * %YAML 1.1 # a comment \n + * ^ + */ + +static int +yaml_parser_scan_version_directive_number(yaml_parser_t *parser, + yaml_mark_t start_mark, int *number) +{ + int value = 0; + size_t length = 0; + + /* Repeat while the next character is digit. */ + + if (!CACHE(parser, 1)) return 0; + + while (IS_DIGIT(parser->buffer)) + { + /* Check if the number is too long. */ + + if (++length > MAX_NUMBER_LENGTH) { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "found extremely long version number"); + } + + value = value*10 + AS_DIGIT(parser->buffer); + + SKIP(parser); + + if (!CACHE(parser, 1)) return 0; + } + + /* Check if the number was present. */ + + if (!length) { + return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", + start_mark, "did not find expected version number"); + } + + *number = value; + + return 1; +} + +/* + * Scan the value of a TAG-DIRECTIVE token. + * + * Scope: + * %TAG !yaml! tag:yaml.org,2002: \n + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + */ + +static int +yaml_parser_scan_tag_directive_value(yaml_parser_t *parser, + yaml_mark_t start_mark, yaml_char_t **handle, yaml_char_t **prefix) +{ + yaml_char_t *handle_value = NULL; + yaml_char_t *prefix_value = NULL; + + /* Eat whitespaces. */ + + if (!CACHE(parser, 1)) goto error; + + while (IS_BLANK(parser->buffer)) { + SKIP(parser); + if (!CACHE(parser, 1)) goto error; + } + + /* Scan a handle. */ + + if (!yaml_parser_scan_tag_handle(parser, 1, start_mark, &handle_value)) + goto error; + + /* Expect a whitespace. */ + + if (!CACHE(parser, 1)) goto error; + + if (!IS_BLANK(parser->buffer)) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace"); + goto error; + } + + /* Eat whitespaces. */ + + while (IS_BLANK(parser->buffer)) { + SKIP(parser); + if (!CACHE(parser, 1)) goto error; + } + + /* Scan a prefix. */ + + if (!yaml_parser_scan_tag_uri(parser, 1, 1, NULL, start_mark, &prefix_value)) + goto error; + + /* Expect a whitespace or line break. */ + + if (!CACHE(parser, 1)) goto error; + + if (!IS_BLANKZ(parser->buffer)) { + yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", + start_mark, "did not find expected whitespace or line break"); + goto error; + } + + *handle = handle_value; + *prefix = prefix_value; + + return 1; + +error: + yaml_free(handle_value); + yaml_free(prefix_value); + return 0; +} + +static int +yaml_parser_scan_anchor(yaml_parser_t *parser, yaml_token_t *token, + yaml_token_type_t type) +{ + int length = 0; + yaml_mark_t start_mark, end_mark; + yaml_string_t string = NULL_STRING; + + if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error; + + /* Eat the indicator character. */ + + start_mark = parser->mark; + + SKIP(parser); + + /* Consume the value. */ + + if (!CACHE(parser, 1)) goto error; + + while (IS_ALPHA(parser->buffer)) { + if (!READ(parser, string)) goto error; + if (!CACHE(parser, 1)) goto error; + length ++; + } + + end_mark = parser->mark; + + /* + * Check if length of the anchor is greater than 0 and it is followed by + * a whitespace character or one of the indicators: + * + * '?', ':', ',', ']', '}', '%', '@', '`'. + */ + + if (!length || !(IS_BLANKZ(parser->buffer) || CHECK(parser->buffer, '?') + || CHECK(parser->buffer, ':') || CHECK(parser->buffer, ',') + || CHECK(parser->buffer, ']') || CHECK(parser->buffer, '}') + || CHECK(parser->buffer, '%') || CHECK(parser->buffer, '@') + || CHECK(parser->buffer, '`'))) { + yaml_parser_set_scanner_error(parser, type == YAML_ANCHOR_TOKEN ? + "while scanning an anchor" : "while scanning an alias", start_mark, + "did not find expected alphabetic or numeric character"); + goto error; + } + + /* Create a token. */ + + if (type == YAML_ANCHOR_TOKEN) { + ANCHOR_TOKEN_INIT(*token, string.start, start_mark, end_mark); + } + else { + ALIAS_TOKEN_INIT(*token, string.start, start_mark, end_mark); + } + + return 1; + +error: + STRING_DEL(parser, string); + return 0; +} + +/* + * Scan a TAG token. + */ + +static int +yaml_parser_scan_tag(yaml_parser_t *parser, yaml_token_t *token) +{ + yaml_char_t *handle = NULL; + yaml_char_t *suffix = NULL; + yaml_mark_t start_mark, end_mark; + + start_mark = parser->mark; + + /* Check if the tag is in the canonical form. */ + + if (!CACHE(parser, 2)) goto error; + + if (CHECK_AT(parser->buffer, '<', 1)) + { + /* Set the handle to '' */ + + handle = YAML_MALLOC(1); + if (!handle) goto error; + handle[0] = '\0'; + + /* Eat '!<' */ + + SKIP(parser); + SKIP(parser); + + /* Consume the tag value. */ + + if (!yaml_parser_scan_tag_uri(parser, 1, 0, NULL, start_mark, &suffix)) + goto error; + + /* Check for '>' and eat it. */ + + if (!CHECK(parser->buffer, '>')) { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find the expected '>'"); + goto error; + } + + SKIP(parser); + } + else + { + /* The tag has either the '!suffix' or the '!handle!suffix' form. */ + + /* First, try to scan a handle. */ + + if (!yaml_parser_scan_tag_handle(parser, 0, start_mark, &handle)) + goto error; + + /* Check if it is, indeed, handle. */ + + if (handle[0] == '!' && handle[1] != '\0' && handle[strlen((char *)handle)-1] == '!') + { + /* Scan the suffix now. */ + + if (!yaml_parser_scan_tag_uri(parser, 0, 0, NULL, start_mark, &suffix)) + goto error; + } + else + { + /* It wasn't a handle after all. Scan the rest of the tag. */ + + if (!yaml_parser_scan_tag_uri(parser, 0, 0, handle, start_mark, &suffix)) + goto error; + + /* Set the handle to '!'. */ + + yaml_free(handle); + handle = YAML_MALLOC(2); + if (!handle) goto error; + handle[0] = '!'; + handle[1] = '\0'; + + /* + * A special case: the '!' tag. Set the handle to '' and the + * suffix to '!'. + */ + + if (suffix[0] == '\0') { + yaml_char_t *tmp = handle; + handle = suffix; + suffix = tmp; + } + } + } + + /* Check the character which ends the tag. */ + + if (!CACHE(parser, 1)) goto error; + + if (!IS_BLANKZ(parser->buffer)) { + if (!parser->flow_level || !CHECK(parser->buffer, ',') ) { + yaml_parser_set_scanner_error(parser, "while scanning a tag", + start_mark, "did not find expected whitespace or line break"); + goto error; + } + } + + end_mark = parser->mark; + + /* Create a token. */ + + TAG_TOKEN_INIT(*token, handle, suffix, start_mark, end_mark); + + return 1; + +error: + yaml_free(handle); + yaml_free(suffix); + return 0; +} + +/* + * Scan a tag handle. + */ + +static int +yaml_parser_scan_tag_handle(yaml_parser_t *parser, int directive, + yaml_mark_t start_mark, yaml_char_t **handle) +{ + yaml_string_t string = NULL_STRING; + + if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error; + + /* Check the initial '!' character. */ + + if (!CACHE(parser, 1)) goto error; + + if (!CHECK(parser->buffer, '!')) { + yaml_parser_set_scanner_error(parser, directive ? + "while scanning a tag directive" : "while scanning a tag", + start_mark, "did not find expected '!'"); + goto error; + } + + /* Copy the '!' character. */ + + if (!READ(parser, string)) goto error; + + /* Copy all subsequent alphabetical and numerical characters. */ + + if (!CACHE(parser, 1)) goto error; + + while (IS_ALPHA(parser->buffer)) + { + if (!READ(parser, string)) goto error; + if (!CACHE(parser, 1)) goto error; + } + + /* Check if the trailing character is '!' and copy it. */ + + if (CHECK(parser->buffer, '!')) + { + if (!READ(parser, string)) goto error; + } + else + { + /* + * It's either the '!' tag or not really a tag handle. If it's a %TAG + * directive, it's an error. If it's a tag token, it must be a part of + * URI. + */ + + if (directive && !(string.start[0] == '!' && string.start[1] == '\0')) { + yaml_parser_set_scanner_error(parser, "while parsing a tag directive", + start_mark, "did not find expected '!'"); + goto error; + } + } + + *handle = string.start; + + return 1; + +error: + STRING_DEL(parser, string); + return 0; +} + +/* + * Scan a tag. + */ + +static int +yaml_parser_scan_tag_uri(yaml_parser_t *parser, int uri_char, int directive, + yaml_char_t *head, yaml_mark_t start_mark, yaml_char_t **uri) +{ + size_t length = head ? strlen((char *)head) : 0; + yaml_string_t string = NULL_STRING; + + if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error; + + /* Resize the string to include the head. */ + + while ((size_t)(string.end - string.start) <= length) { + if (!yaml_string_extend(&string.start, &string.pointer, &string.end)) { + parser->error = YAML_MEMORY_ERROR; + goto error; + } + } + + /* + * Copy the head if needed. + * + * Note that we don't copy the leading '!' character. + */ + + if (length > 1) { + memcpy(string.start, head+1, length-1); + string.pointer += length-1; + } + + /* Scan the tag. */ + + if (!CACHE(parser, 1)) goto error; + + /* + * The set of characters that may appear in URI is as follows: + * + * '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', + * '=', '+', '$', '.', '!', '~', '*', '\'', '(', ')', '%'. + * + * If we are inside a verbatim tag <...> (parameter uri_char is true) + * then also the following flow indicators are allowed: + * ',', '[', ']' + */ + + while (IS_ALPHA(parser->buffer) || CHECK(parser->buffer, ';') + || CHECK(parser->buffer, '/') || CHECK(parser->buffer, '?') + || CHECK(parser->buffer, ':') || CHECK(parser->buffer, '@') + || CHECK(parser->buffer, '&') || CHECK(parser->buffer, '=') + || CHECK(parser->buffer, '+') || CHECK(parser->buffer, '$') + || CHECK(parser->buffer, '.') || CHECK(parser->buffer, '%') + || CHECK(parser->buffer, '!') || CHECK(parser->buffer, '~') + || CHECK(parser->buffer, '*') || CHECK(parser->buffer, '\'') + || CHECK(parser->buffer, '(') || CHECK(parser->buffer, ')') + || (uri_char && ( + CHECK(parser->buffer, ',') + || CHECK(parser->buffer, '[') || CHECK(parser->buffer, ']') + ) + )) + { + /* Check if it is a URI-escape sequence. */ + + if (CHECK(parser->buffer, '%')) { + if (!STRING_EXTEND(parser, string)) + goto error; + + if (!yaml_parser_scan_uri_escapes(parser, + directive, start_mark, &string)) goto error; + } + else { + if (!READ(parser, string)) goto error; + } + + length ++; + if (!CACHE(parser, 1)) goto error; + } + + /* Check if the tag is non-empty. */ + + if (!length) { + if (!STRING_EXTEND(parser, string)) + goto error; + + yaml_parser_set_scanner_error(parser, directive ? + "while parsing a %TAG directive" : "while parsing a tag", + start_mark, "did not find expected tag URI"); + goto error; + } + + *uri = string.start; + + return 1; + +error: + STRING_DEL(parser, string); + return 0; +} + +/* + * Decode an URI-escape sequence corresponding to a single UTF-8 character. + */ + +static int +yaml_parser_scan_uri_escapes(yaml_parser_t *parser, int directive, + yaml_mark_t start_mark, yaml_string_t *string) +{ + int width = 0; + + /* Decode the required number of characters. */ + + do { + + unsigned char octet = 0; + + /* Check for a URI-escaped octet. */ + + if (!CACHE(parser, 3)) return 0; + + if (!(CHECK(parser->buffer, '%') + && IS_HEX_AT(parser->buffer, 1) + && IS_HEX_AT(parser->buffer, 2))) { + return yaml_parser_set_scanner_error(parser, directive ? + "while parsing a %TAG directive" : "while parsing a tag", + start_mark, "did not find URI escaped octet"); + } + + /* Get the octet. */ + + octet = (AS_HEX_AT(parser->buffer, 1) << 4) + AS_HEX_AT(parser->buffer, 2); + + /* If it is the leading octet, determine the length of the UTF-8 sequence. */ + + if (!width) + { + width = (octet & 0x80) == 0x00 ? 1 : + (octet & 0xE0) == 0xC0 ? 2 : + (octet & 0xF0) == 0xE0 ? 3 : + (octet & 0xF8) == 0xF0 ? 4 : 0; + if (!width) { + return yaml_parser_set_scanner_error(parser, directive ? + "while parsing a %TAG directive" : "while parsing a tag", + start_mark, "found an incorrect leading UTF-8 octet"); + } + } + else + { + /* Check if the trailing octet is correct. */ + + if ((octet & 0xC0) != 0x80) { + return yaml_parser_set_scanner_error(parser, directive ? + "while parsing a %TAG directive" : "while parsing a tag", + start_mark, "found an incorrect trailing UTF-8 octet"); + } + } + + /* Copy the octet and move the pointers. */ + + *(string->pointer++) = octet; + SKIP(parser); + SKIP(parser); + SKIP(parser); + + } while (--width); + + return 1; +} + +/* + * Scan a block scalar. + */ + +static int +yaml_parser_scan_block_scalar(yaml_parser_t *parser, yaml_token_t *token, + int literal) +{ + yaml_mark_t start_mark; + yaml_mark_t end_mark; + yaml_string_t string = NULL_STRING; + yaml_string_t leading_break = NULL_STRING; + yaml_string_t trailing_breaks = NULL_STRING; + int chomping = 0; + int increment = 0; + int indent = 0; + int leading_blank = 0; + int trailing_blank = 0; + + if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error; + if (!STRING_INIT(parser, leading_break, INITIAL_STRING_SIZE)) goto error; + if (!STRING_INIT(parser, trailing_breaks, INITIAL_STRING_SIZE)) goto error; + + /* Eat the indicator '|' or '>'. */ + + start_mark = parser->mark; + + SKIP(parser); + + /* Scan the additional block scalar indicators. */ + + if (!CACHE(parser, 1)) goto error; + + /* Check for a chomping indicator. */ + + if (CHECK(parser->buffer, '+') || CHECK(parser->buffer, '-')) + { + /* Set the chomping method and eat the indicator. */ + + chomping = CHECK(parser->buffer, '+') ? +1 : -1; + + SKIP(parser); + + /* Check for an indentation indicator. */ + + if (!CACHE(parser, 1)) goto error; + + if (IS_DIGIT(parser->buffer)) + { + /* Check that the indentation is greater than 0. */ + + if (CHECK(parser->buffer, '0')) { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0"); + goto error; + } + + /* Get the indentation level and eat the indicator. */ + + increment = AS_DIGIT(parser->buffer); + + SKIP(parser); + } + } + + /* Do the same as above, but in the opposite order. */ + + else if (IS_DIGIT(parser->buffer)) + { + if (CHECK(parser->buffer, '0')) { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found an indentation indicator equal to 0"); + goto error; + } + + increment = AS_DIGIT(parser->buffer); + + SKIP(parser); + + if (!CACHE(parser, 1)) goto error; + + if (CHECK(parser->buffer, '+') || CHECK(parser->buffer, '-')) { + chomping = CHECK(parser->buffer, '+') ? +1 : -1; + + SKIP(parser); + } + } + + /* Eat whitespaces and comments to the end of the line. */ + + if (!CACHE(parser, 1)) goto error; + + while (IS_BLANK(parser->buffer)) { + SKIP(parser); + if (!CACHE(parser, 1)) goto error; + } + + if (CHECK(parser->buffer, '#')) { + while (!IS_BREAKZ(parser->buffer)) { + SKIP(parser); + if (!CACHE(parser, 1)) goto error; + } + } + + /* Check if we are at the end of the line. */ + + if (!IS_BREAKZ(parser->buffer)) { + yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "did not find expected comment or line break"); + goto error; + } + + /* Eat a line break. */ + + if (IS_BREAK(parser->buffer)) { + if (!CACHE(parser, 2)) goto error; + SKIP_LINE(parser); + } + + end_mark = parser->mark; + + /* Set the indentation level if it was specified. */ + + if (increment) { + indent = parser->indent >= 0 ? parser->indent+increment : increment; + } + + /* Scan the leading line breaks and determine the indentation level if needed. */ + + if (!yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, + start_mark, &end_mark)) goto error; + + /* Scan the block scalar content. */ + + if (!CACHE(parser, 1)) goto error; + + while ((int)parser->mark.column == indent && !(IS_Z(parser->buffer))) + { + /* + * We are at the beginning of a non-empty line. + */ + + /* Is it a trailing whitespace? */ + + trailing_blank = IS_BLANK(parser->buffer); + + /* Check if we need to fold the leading line break. */ + + if (!literal && (*leading_break.start == '\n') + && !leading_blank && !trailing_blank) + { + /* Do we need to join the lines by space? */ + + if (*trailing_breaks.start == '\0') { + if (!STRING_EXTEND(parser, string)) goto error; + *(string.pointer ++) = ' '; + } + + CLEAR(parser, leading_break); + } + else { + if (!JOIN(parser, string, leading_break)) goto error; + CLEAR(parser, leading_break); + } + + /* Append the remaining line breaks. */ + + if (!JOIN(parser, string, trailing_breaks)) goto error; + CLEAR(parser, trailing_breaks); + + /* Is it a leading whitespace? */ + + leading_blank = IS_BLANK(parser->buffer); + + /* Consume the current line. */ + + while (!IS_BREAKZ(parser->buffer)) { + if (!READ(parser, string)) goto error; + if (!CACHE(parser, 1)) goto error; + } + + /* Consume the line break. */ + + if (!CACHE(parser, 2)) goto error; + + if (!READ_LINE(parser, leading_break)) goto error; + + /* Eat the following indentation spaces and line breaks. */ + + if (!yaml_parser_scan_block_scalar_breaks(parser, + &indent, &trailing_breaks, start_mark, &end_mark)) goto error; + } + + /* Chomp the tail. */ + + if (chomping != -1) { + if (!JOIN(parser, string, leading_break)) goto error; + } + if (chomping == 1) { + if (!JOIN(parser, string, trailing_breaks)) goto error; + } + + /* Create a token. */ + + SCALAR_TOKEN_INIT(*token, string.start, string.pointer-string.start, + literal ? YAML_LITERAL_SCALAR_STYLE : YAML_FOLDED_SCALAR_STYLE, + start_mark, end_mark); + + STRING_DEL(parser, leading_break); + STRING_DEL(parser, trailing_breaks); + + return 1; + +error: + STRING_DEL(parser, string); + STRING_DEL(parser, leading_break); + STRING_DEL(parser, trailing_breaks); + + return 0; +} + +/* + * Scan indentation spaces and line breaks for a block scalar. Determine the + * indentation level if needed. + */ + +static int +yaml_parser_scan_block_scalar_breaks(yaml_parser_t *parser, + int *indent, yaml_string_t *breaks, + yaml_mark_t start_mark, yaml_mark_t *end_mark) +{ + int max_indent = 0; + + *end_mark = parser->mark; + + /* Eat the indentation spaces and line breaks. */ + + while (1) + { + /* Eat the indentation spaces. */ + + if (!CACHE(parser, 1)) return 0; + + while ((!*indent || (int)parser->mark.column < *indent) + && IS_SPACE(parser->buffer)) { + SKIP(parser); + if (!CACHE(parser, 1)) return 0; + } + + if ((int)parser->mark.column > max_indent) + max_indent = (int)parser->mark.column; + + /* Check for a tab character messing the indentation. */ + + if ((!*indent || (int)parser->mark.column < *indent) + && IS_TAB(parser->buffer)) { + return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", + start_mark, "found a tab character where an indentation space is expected"); + } + + /* Have we found a non-empty line? */ + + if (!IS_BREAK(parser->buffer)) break; + + /* Consume the line break. */ + + if (!CACHE(parser, 2)) return 0; + if (!READ_LINE(parser, *breaks)) return 0; + *end_mark = parser->mark; + } + + /* Determine the indentation level if needed. */ + + if (!*indent) { + *indent = max_indent; + if (*indent < parser->indent + 1) + *indent = parser->indent + 1; + if (*indent < 1) + *indent = 1; + } + + return 1; +} + +/* + * Scan a quoted scalar. + */ + +static int +yaml_parser_scan_flow_scalar(yaml_parser_t *parser, yaml_token_t *token, + int single) +{ + yaml_mark_t start_mark; + yaml_mark_t end_mark; + yaml_string_t string = NULL_STRING; + yaml_string_t leading_break = NULL_STRING; + yaml_string_t trailing_breaks = NULL_STRING; + yaml_string_t whitespaces = NULL_STRING; + int leading_blanks; + + if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error; + if (!STRING_INIT(parser, leading_break, INITIAL_STRING_SIZE)) goto error; + if (!STRING_INIT(parser, trailing_breaks, INITIAL_STRING_SIZE)) goto error; + if (!STRING_INIT(parser, whitespaces, INITIAL_STRING_SIZE)) goto error; + + /* Eat the left quote. */ + + start_mark = parser->mark; + + SKIP(parser); + + /* Consume the content of the quoted scalar. */ + + while (1) + { + /* Check that there are no document indicators at the beginning of the line. */ + + if (!CACHE(parser, 4)) goto error; + + if (parser->mark.column == 0 && + ((CHECK_AT(parser->buffer, '-', 0) && + CHECK_AT(parser->buffer, '-', 1) && + CHECK_AT(parser->buffer, '-', 2)) || + (CHECK_AT(parser->buffer, '.', 0) && + CHECK_AT(parser->buffer, '.', 1) && + CHECK_AT(parser->buffer, '.', 2))) && + IS_BLANKZ_AT(parser->buffer, 3)) + { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected document indicator"); + goto error; + } + + /* Check for EOF. */ + + if (IS_Z(parser->buffer)) { + yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", + start_mark, "found unexpected end of stream"); + goto error; + } + + /* Consume non-blank characters. */ + + if (!CACHE(parser, 2)) goto error; + + leading_blanks = 0; + + while (!IS_BLANKZ(parser->buffer)) + { + /* Check for an escaped single quote. */ + + if (single && CHECK_AT(parser->buffer, '\'', 0) + && CHECK_AT(parser->buffer, '\'', 1)) + { + if (!STRING_EXTEND(parser, string)) goto error; + *(string.pointer++) = '\''; + SKIP(parser); + SKIP(parser); + } + + /* Check for the right quote. */ + + else if (CHECK(parser->buffer, single ? '\'' : '"')) + { + break; + } + + /* Check for an escaped line break. */ + + else if (!single && CHECK(parser->buffer, '\\') + && IS_BREAK_AT(parser->buffer, 1)) + { + if (!CACHE(parser, 3)) goto error; + SKIP(parser); + SKIP_LINE(parser); + leading_blanks = 1; + break; + } + + /* Check for an escape sequence. */ + + else if (!single && CHECK(parser->buffer, '\\')) + { + size_t code_length = 0; + + if (!STRING_EXTEND(parser, string)) goto error; + + /* Check the escape character. */ + + switch (parser->buffer.pointer[1]) + { + case '0': + *(string.pointer++) = '\0'; + break; + + case 'a': + *(string.pointer++) = '\x07'; + break; + + case 'b': + *(string.pointer++) = '\x08'; + break; + + case 't': + case '\t': + *(string.pointer++) = '\x09'; + break; + + case 'n': + *(string.pointer++) = '\x0A'; + break; + + case 'v': + *(string.pointer++) = '\x0B'; + break; + + case 'f': + *(string.pointer++) = '\x0C'; + break; + + case 'r': + *(string.pointer++) = '\x0D'; + break; + + case 'e': + *(string.pointer++) = '\x1B'; + break; + + case ' ': + *(string.pointer++) = '\x20'; + break; + + case '"': + *(string.pointer++) = '"'; + break; + + case '/': + *(string.pointer++) = '/'; + break; + + case '\\': + *(string.pointer++) = '\\'; + break; + + case 'N': /* NEL (#x85) */ + *(string.pointer++) = '\xC2'; + *(string.pointer++) = '\x85'; + break; + + case '_': /* #xA0 */ + *(string.pointer++) = '\xC2'; + *(string.pointer++) = '\xA0'; + break; + + case 'L': /* LS (#x2028) */ + *(string.pointer++) = '\xE2'; + *(string.pointer++) = '\x80'; + *(string.pointer++) = '\xA8'; + break; + + case 'P': /* PS (#x2029) */ + *(string.pointer++) = '\xE2'; + *(string.pointer++) = '\x80'; + *(string.pointer++) = '\xA9'; + break; + + case 'x': + code_length = 2; + break; + + case 'u': + code_length = 4; + break; + + case 'U': + code_length = 8; + break; + + default: + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found unknown escape character"); + goto error; + } + + SKIP(parser); + SKIP(parser); + + /* Consume an arbitrary escape code. */ + + if (code_length) + { + unsigned int value = 0; + size_t k; + + /* Scan the character value. */ + + if (!CACHE(parser, code_length)) goto error; + + for (k = 0; k < code_length; k ++) { + if (!IS_HEX_AT(parser->buffer, k)) { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "did not find expected hexdecimal number"); + goto error; + } + value = (value << 4) + AS_HEX_AT(parser->buffer, k); + } + + /* Check the value and write the character. */ + + if ((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) { + yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", + start_mark, "found invalid Unicode character escape code"); + goto error; + } + + if (value <= 0x7F) { + *(string.pointer++) = value; + } + else if (value <= 0x7FF) { + *(string.pointer++) = 0xC0 + (value >> 6); + *(string.pointer++) = 0x80 + (value & 0x3F); + } + else if (value <= 0xFFFF) { + *(string.pointer++) = 0xE0 + (value >> 12); + *(string.pointer++) = 0x80 + ((value >> 6) & 0x3F); + *(string.pointer++) = 0x80 + (value & 0x3F); + } + else { + *(string.pointer++) = 0xF0 + (value >> 18); + *(string.pointer++) = 0x80 + ((value >> 12) & 0x3F); + *(string.pointer++) = 0x80 + ((value >> 6) & 0x3F); + *(string.pointer++) = 0x80 + (value & 0x3F); + } + + /* Advance the pointer. */ + + for (k = 0; k < code_length; k ++) { + SKIP(parser); + } + } + } + + else + { + /* It is a non-escaped non-blank character. */ + + if (!READ(parser, string)) goto error; + } + + if (!CACHE(parser, 2)) goto error; + } + + /* Check if we are at the end of the scalar. */ + + /* Fix for crash uninitialized value crash + * Credit for the bug and input is to OSS Fuzz + * Credit for the fix to Alex Gaynor + */ + if (!CACHE(parser, 1)) goto error; + if (CHECK(parser->buffer, single ? '\'' : '"')) + break; + + /* Consume blank characters. */ + + if (!CACHE(parser, 1)) goto error; + + while (IS_BLANK(parser->buffer) || IS_BREAK(parser->buffer)) + { + if (IS_BLANK(parser->buffer)) + { + /* Consume a space or a tab character. */ + + if (!leading_blanks) { + if (!READ(parser, whitespaces)) goto error; + } + else { + SKIP(parser); + } + } + else + { + if (!CACHE(parser, 2)) goto error; + + /* Check if it is a first line break. */ + + if (!leading_blanks) + { + CLEAR(parser, whitespaces); + if (!READ_LINE(parser, leading_break)) goto error; + leading_blanks = 1; + } + else + { + if (!READ_LINE(parser, trailing_breaks)) goto error; + } + } + if (!CACHE(parser, 1)) goto error; + } + + /* Join the whitespaces or fold line breaks. */ + + if (leading_blanks) + { + /* Do we need to fold line breaks? */ + + if (leading_break.start[0] == '\n') { + if (trailing_breaks.start[0] == '\0') { + if (!STRING_EXTEND(parser, string)) goto error; + *(string.pointer++) = ' '; + } + else { + if (!JOIN(parser, string, trailing_breaks)) goto error; + CLEAR(parser, trailing_breaks); + } + CLEAR(parser, leading_break); + } + else { + if (!JOIN(parser, string, leading_break)) goto error; + if (!JOIN(parser, string, trailing_breaks)) goto error; + CLEAR(parser, leading_break); + CLEAR(parser, trailing_breaks); + } + } + else + { + if (!JOIN(parser, string, whitespaces)) goto error; + CLEAR(parser, whitespaces); + } + } + + /* Eat the right quote. */ + + SKIP(parser); + + end_mark = parser->mark; + + /* Create a token. */ + + SCALAR_TOKEN_INIT(*token, string.start, string.pointer-string.start, + single ? YAML_SINGLE_QUOTED_SCALAR_STYLE : YAML_DOUBLE_QUOTED_SCALAR_STYLE, + start_mark, end_mark); + + STRING_DEL(parser, leading_break); + STRING_DEL(parser, trailing_breaks); + STRING_DEL(parser, whitespaces); + + return 1; + +error: + STRING_DEL(parser, string); + STRING_DEL(parser, leading_break); + STRING_DEL(parser, trailing_breaks); + STRING_DEL(parser, whitespaces); + + return 0; +} + +/* + * Scan a plain scalar. + */ + +static int +yaml_parser_scan_plain_scalar(yaml_parser_t *parser, yaml_token_t *token) +{ + yaml_mark_t start_mark; + yaml_mark_t end_mark; + yaml_string_t string = NULL_STRING; + yaml_string_t leading_break = NULL_STRING; + yaml_string_t trailing_breaks = NULL_STRING; + yaml_string_t whitespaces = NULL_STRING; + int leading_blanks = 0; + int indent = parser->indent+1; + + if (!STRING_INIT(parser, string, INITIAL_STRING_SIZE)) goto error; + if (!STRING_INIT(parser, leading_break, INITIAL_STRING_SIZE)) goto error; + if (!STRING_INIT(parser, trailing_breaks, INITIAL_STRING_SIZE)) goto error; + if (!STRING_INIT(parser, whitespaces, INITIAL_STRING_SIZE)) goto error; + + start_mark = end_mark = parser->mark; + + /* Consume the content of the plain scalar. */ + + while (1) + { + /* Check for a document indicator. */ + + if (!CACHE(parser, 4)) goto error; + + if (parser->mark.column == 0 && + ((CHECK_AT(parser->buffer, '-', 0) && + CHECK_AT(parser->buffer, '-', 1) && + CHECK_AT(parser->buffer, '-', 2)) || + (CHECK_AT(parser->buffer, '.', 0) && + CHECK_AT(parser->buffer, '.', 1) && + CHECK_AT(parser->buffer, '.', 2))) && + IS_BLANKZ_AT(parser->buffer, 3)) break; + + /* Check for a comment. */ + + if (CHECK(parser->buffer, '#')) + break; + + /* Consume non-blank characters. */ + + while (!IS_BLANKZ(parser->buffer)) + { + /* Check for "x:" + one of ',?[]{}' in the flow context. TODO: Fix the test "spec-08-13". + * This is not completely according to the spec + * See http://yaml.org/spec/1.1/#id907281 9.1.3. Plain + */ + + if (parser->flow_level + && CHECK(parser->buffer, ':') + && ( + CHECK_AT(parser->buffer, ',', 1) + || CHECK_AT(parser->buffer, '?', 1) + || CHECK_AT(parser->buffer, '[', 1) + || CHECK_AT(parser->buffer, ']', 1) + || CHECK_AT(parser->buffer, '{', 1) + || CHECK_AT(parser->buffer, '}', 1) + ) + ) { + yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", + start_mark, "found unexpected ':'"); + goto error; + } + + /* Check for indicators that may end a plain scalar. */ + + if ((CHECK(parser->buffer, ':') && IS_BLANKZ_AT(parser->buffer, 1)) + || (parser->flow_level && + (CHECK(parser->buffer, ',') + || CHECK(parser->buffer, '[') + || CHECK(parser->buffer, ']') || CHECK(parser->buffer, '{') + || CHECK(parser->buffer, '}')))) + break; + + /* Check if we need to join whitespaces and breaks. */ + + if (leading_blanks || whitespaces.start != whitespaces.pointer) + { + if (leading_blanks) + { + /* Do we need to fold line breaks? */ + + if (leading_break.start[0] == '\n') { + if (trailing_breaks.start[0] == '\0') { + if (!STRING_EXTEND(parser, string)) goto error; + *(string.pointer++) = ' '; + } + else { + if (!JOIN(parser, string, trailing_breaks)) goto error; + CLEAR(parser, trailing_breaks); + } + CLEAR(parser, leading_break); + } + else { + if (!JOIN(parser, string, leading_break)) goto error; + if (!JOIN(parser, string, trailing_breaks)) goto error; + CLEAR(parser, leading_break); + CLEAR(parser, trailing_breaks); + } + + leading_blanks = 0; + } + else + { + if (!JOIN(parser, string, whitespaces)) goto error; + CLEAR(parser, whitespaces); + } + } + + /* Copy the character. */ + + if (!READ(parser, string)) goto error; + + end_mark = parser->mark; + + if (!CACHE(parser, 2)) goto error; + } + + /* Is it the end? */ + + if (!(IS_BLANK(parser->buffer) || IS_BREAK(parser->buffer))) + break; + + /* Consume blank characters. */ + + if (!CACHE(parser, 1)) goto error; + + while (IS_BLANK(parser->buffer) || IS_BREAK(parser->buffer)) + { + if (IS_BLANK(parser->buffer)) + { + /* Check for tab characters that abuse indentation. */ + + if (leading_blanks && (int)parser->mark.column < indent + && IS_TAB(parser->buffer)) { + yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", + start_mark, "found a tab character that violates indentation"); + goto error; + } + + /* Consume a space or a tab character. */ + + if (!leading_blanks) { + if (!READ(parser, whitespaces)) goto error; + } + else { + SKIP(parser); + } + } + else + { + if (!CACHE(parser, 2)) goto error; + + /* Check if it is a first line break. */ + + if (!leading_blanks) + { + CLEAR(parser, whitespaces); + if (!READ_LINE(parser, leading_break)) goto error; + leading_blanks = 1; + } + else + { + if (!READ_LINE(parser, trailing_breaks)) goto error; + } + } + if (!CACHE(parser, 1)) goto error; + } + + /* Check indentation level. */ + + if (!parser->flow_level && (int)parser->mark.column < indent) + break; + } + + /* Create a token. */ + + SCALAR_TOKEN_INIT(*token, string.start, string.pointer-string.start, + YAML_PLAIN_SCALAR_STYLE, start_mark, end_mark); + + /* Note that we change the 'simple_key_allowed' flag. */ + + if (leading_blanks) { + parser->simple_key_allowed = 1; + } + + STRING_DEL(parser, leading_break); + STRING_DEL(parser, trailing_breaks); + STRING_DEL(parser, whitespaces); + + return 1; + +error: + STRING_DEL(parser, string); + STRING_DEL(parser, leading_break); + STRING_DEL(parser, trailing_breaks); + STRING_DEL(parser, whitespaces); + + return 0; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/writer.c b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/writer.c new file mode 100644 index 0000000..5d57f39 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/writer.c @@ -0,0 +1,141 @@ + +#include "yaml_private.h" + +/* + * Declarations. + */ + +static int +yaml_emitter_set_writer_error(yaml_emitter_t *emitter, const char *problem); + +YAML_DECLARE(int) +yaml_emitter_flush(yaml_emitter_t *emitter); + +/* + * Set the writer error and return 0. + */ + +static int +yaml_emitter_set_writer_error(yaml_emitter_t *emitter, const char *problem) +{ + emitter->error = YAML_WRITER_ERROR; + emitter->problem = problem; + + return 0; +} + +/* + * Flush the output buffer. + */ + +YAML_DECLARE(int) +yaml_emitter_flush(yaml_emitter_t *emitter) +{ + int low, high; + + assert(emitter); /* Non-NULL emitter object is expected. */ + assert(emitter->write_handler); /* Write handler must be set. */ + assert(emitter->encoding); /* Output encoding must be set. */ + + emitter->buffer.last = emitter->buffer.pointer; + emitter->buffer.pointer = emitter->buffer.start; + + /* Check if the buffer is empty. */ + + if (emitter->buffer.start == emitter->buffer.last) { + return 1; + } + + /* If the output encoding is UTF-8, we don't need to recode the buffer. */ + + if (emitter->encoding == YAML_UTF8_ENCODING) + { + if (emitter->write_handler(emitter->write_handler_data, + emitter->buffer.start, + emitter->buffer.last - emitter->buffer.start)) { + emitter->buffer.last = emitter->buffer.start; + emitter->buffer.pointer = emitter->buffer.start; + return 1; + } + else { + return yaml_emitter_set_writer_error(emitter, "write error"); + } + } + + /* Recode the buffer into the raw buffer. */ + + low = (emitter->encoding == YAML_UTF16LE_ENCODING ? 0 : 1); + high = (emitter->encoding == YAML_UTF16LE_ENCODING ? 1 : 0); + + while (emitter->buffer.pointer != emitter->buffer.last) + { + unsigned char octet; + unsigned int width; + unsigned int value; + size_t k; + + /* + * See the "reader.c" code for more details on UTF-8 encoding. Note + * that we assume that the buffer contains a valid UTF-8 sequence. + */ + + /* Read the next UTF-8 character. */ + + octet = emitter->buffer.pointer[0]; + + width = (octet & 0x80) == 0x00 ? 1 : + (octet & 0xE0) == 0xC0 ? 2 : + (octet & 0xF0) == 0xE0 ? 3 : + (octet & 0xF8) == 0xF0 ? 4 : 0; + + value = (octet & 0x80) == 0x00 ? octet & 0x7F : + (octet & 0xE0) == 0xC0 ? octet & 0x1F : + (octet & 0xF0) == 0xE0 ? octet & 0x0F : + (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; + + for (k = 1; k < width; k ++) { + octet = emitter->buffer.pointer[k]; + value = (value << 6) + (octet & 0x3F); + } + + emitter->buffer.pointer += width; + + /* Write the character. */ + + if (value < 0x10000) + { + emitter->raw_buffer.last[high] = value >> 8; + emitter->raw_buffer.last[low] = value & 0xFF; + + emitter->raw_buffer.last += 2; + } + else + { + /* Write the character using a surrogate pair (check "reader.c"). */ + + value -= 0x10000; + emitter->raw_buffer.last[high] = 0xD8 + (value >> 18); + emitter->raw_buffer.last[low] = (value >> 10) & 0xFF; + emitter->raw_buffer.last[high+2] = 0xDC + ((value >> 8) & 0xFF); + emitter->raw_buffer.last[low+2] = value & 0xFF; + + emitter->raw_buffer.last += 4; + } + } + + /* Write the raw buffer. */ + + if (emitter->write_handler(emitter->write_handler_data, + emitter->raw_buffer.start, + emitter->raw_buffer.last - emitter->raw_buffer.start)) { + emitter->buffer.last = emitter->buffer.start; + emitter->buffer.pointer = emitter->buffer.start; + emitter->raw_buffer.last = emitter->raw_buffer.start; + emitter->raw_buffer.pointer = emitter->raw_buffer.start; + return 1; + } + else { + return yaml_emitter_set_writer_error(emitter, "write error"); + } +} + diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/yaml.h b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/yaml.h new file mode 100644 index 0000000..f1b7bfd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/yaml.h @@ -0,0 +1,1985 @@ +/** + * @file yaml.h + * @brief Public interface for libyaml. + * + * Include the header file with the code: + * @code + * #include + * @endcode + */ + +#ifndef YAML_H +#define YAML_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +/** + * @defgroup export Export Definitions + * @{ + */ + +/** The public API declaration. */ + +#if defined(__MINGW32__) +# define YAML_DECLARE(type) type +#elif defined(_WIN32) +# if defined(YAML_DECLARE_STATIC) +# define YAML_DECLARE(type) type +# elif defined(YAML_DECLARE_EXPORT) +# define YAML_DECLARE(type) __declspec(dllexport) type +# else +# define YAML_DECLARE(type) __declspec(dllimport) type +# endif +#else +# define YAML_DECLARE(type) type +#endif + +/** @} */ + +/** + * @defgroup version Version Information + * @{ + */ + +/** + * Get the library version as a string. + * + * @returns The function returns the pointer to a static string of the form + * @c "X.Y.Z", where @c X is the major version number, @c Y is a minor version + * number, and @c Z is the patch version number. + */ + +YAML_DECLARE(const char *) +yaml_get_version_string(void); + +/** + * Get the library version numbers. + * + * @param[out] major Major version number. + * @param[out] minor Minor version number. + * @param[out] patch Patch version number. + */ + +YAML_DECLARE(void) +yaml_get_version(int *major, int *minor, int *patch); + +/** @} */ + +/** + * @defgroup basic Basic Types + * @{ + */ + +/** The character type (UTF-8 octet). */ +typedef unsigned char yaml_char_t; + +/** The version directive data. */ +typedef struct yaml_version_directive_s { + /** The major version number. */ + int major; + /** The minor version number. */ + int minor; +} yaml_version_directive_t; + +/** The tag directive data. */ +typedef struct yaml_tag_directive_s { + /** The tag handle. */ + yaml_char_t *handle; + /** The tag prefix. */ + yaml_char_t *prefix; +} yaml_tag_directive_t; + +/** The stream encoding. */ +typedef enum yaml_encoding_e { + /** Let the parser choose the encoding. */ + YAML_ANY_ENCODING, + /** The default UTF-8 encoding. */ + YAML_UTF8_ENCODING, + /** The UTF-16-LE encoding with BOM. */ + YAML_UTF16LE_ENCODING, + /** The UTF-16-BE encoding with BOM. */ + YAML_UTF16BE_ENCODING +} yaml_encoding_t; + +/** Line break types. */ + +typedef enum yaml_break_e { + /** Let the parser choose the break type. */ + YAML_ANY_BREAK, + /** Use CR for line breaks (Mac style). */ + YAML_CR_BREAK, + /** Use LN for line breaks (Unix style). */ + YAML_LN_BREAK, + /** Use CR LN for line breaks (DOS style). */ + YAML_CRLN_BREAK +} yaml_break_t; + +/** Many bad things could happen with the parser and emitter. */ +typedef enum yaml_error_type_e { + /** No error is produced. */ + YAML_NO_ERROR, + + /** Cannot allocate or reallocate a block of memory. */ + YAML_MEMORY_ERROR, + + /** Cannot read or decode the input stream. */ + YAML_READER_ERROR, + /** Cannot scan the input stream. */ + YAML_SCANNER_ERROR, + /** Cannot parse the input stream. */ + YAML_PARSER_ERROR, + /** Cannot compose a YAML document. */ + YAML_COMPOSER_ERROR, + + /** Cannot write to the output stream. */ + YAML_WRITER_ERROR, + /** Cannot emit a YAML stream. */ + YAML_EMITTER_ERROR +} yaml_error_type_t; + +/** The pointer position. */ +typedef struct yaml_mark_s { + /** The position index. */ + size_t index; + + /** The position line. */ + size_t line; + + /** The position column. */ + size_t column; +} yaml_mark_t; + +/** @} */ + +/** + * @defgroup styles Node Styles + * @{ + */ + +/** Scalar styles. */ +typedef enum yaml_scalar_style_e { + /** Let the emitter choose the style. */ + YAML_ANY_SCALAR_STYLE, + + /** The plain scalar style. */ + YAML_PLAIN_SCALAR_STYLE, + + /** The single-quoted scalar style. */ + YAML_SINGLE_QUOTED_SCALAR_STYLE, + /** The double-quoted scalar style. */ + YAML_DOUBLE_QUOTED_SCALAR_STYLE, + + /** The literal scalar style. */ + YAML_LITERAL_SCALAR_STYLE, + /** The folded scalar style. */ + YAML_FOLDED_SCALAR_STYLE +} yaml_scalar_style_t; + +/** Sequence styles. */ +typedef enum yaml_sequence_style_e { + /** Let the emitter choose the style. */ + YAML_ANY_SEQUENCE_STYLE, + + /** The block sequence style. */ + YAML_BLOCK_SEQUENCE_STYLE, + /** The flow sequence style. */ + YAML_FLOW_SEQUENCE_STYLE +} yaml_sequence_style_t; + +/** Mapping styles. */ +typedef enum yaml_mapping_style_e { + /** Let the emitter choose the style. */ + YAML_ANY_MAPPING_STYLE, + + /** The block mapping style. */ + YAML_BLOCK_MAPPING_STYLE, + /** The flow mapping style. */ + YAML_FLOW_MAPPING_STYLE +/* YAML_FLOW_SET_MAPPING_STYLE */ +} yaml_mapping_style_t; + +/** @} */ + +/** + * @defgroup tokens Tokens + * @{ + */ + +/** Token types. */ +typedef enum yaml_token_type_e { + /** An empty token. */ + YAML_NO_TOKEN, + + /** A STREAM-START token. */ + YAML_STREAM_START_TOKEN, + /** A STREAM-END token. */ + YAML_STREAM_END_TOKEN, + + /** A VERSION-DIRECTIVE token. */ + YAML_VERSION_DIRECTIVE_TOKEN, + /** A TAG-DIRECTIVE token. */ + YAML_TAG_DIRECTIVE_TOKEN, + /** A DOCUMENT-START token. */ + YAML_DOCUMENT_START_TOKEN, + /** A DOCUMENT-END token. */ + YAML_DOCUMENT_END_TOKEN, + + /** A BLOCK-SEQUENCE-START token. */ + YAML_BLOCK_SEQUENCE_START_TOKEN, + /** A BLOCK-MAPPING-START token. */ + YAML_BLOCK_MAPPING_START_TOKEN, + /** A BLOCK-END token. */ + YAML_BLOCK_END_TOKEN, + + /** A FLOW-SEQUENCE-START token. */ + YAML_FLOW_SEQUENCE_START_TOKEN, + /** A FLOW-SEQUENCE-END token. */ + YAML_FLOW_SEQUENCE_END_TOKEN, + /** A FLOW-MAPPING-START token. */ + YAML_FLOW_MAPPING_START_TOKEN, + /** A FLOW-MAPPING-END token. */ + YAML_FLOW_MAPPING_END_TOKEN, + + /** A BLOCK-ENTRY token. */ + YAML_BLOCK_ENTRY_TOKEN, + /** A FLOW-ENTRY token. */ + YAML_FLOW_ENTRY_TOKEN, + /** A KEY token. */ + YAML_KEY_TOKEN, + /** A VALUE token. */ + YAML_VALUE_TOKEN, + + /** An ALIAS token. */ + YAML_ALIAS_TOKEN, + /** An ANCHOR token. */ + YAML_ANCHOR_TOKEN, + /** A TAG token. */ + YAML_TAG_TOKEN, + /** A SCALAR token. */ + YAML_SCALAR_TOKEN +} yaml_token_type_t; + +/** The token structure. */ +typedef struct yaml_token_s { + + /** The token type. */ + yaml_token_type_t type; + + /** The token data. */ + union { + + /** The stream start (for @c YAML_STREAM_START_TOKEN). */ + struct { + /** The stream encoding. */ + yaml_encoding_t encoding; + } stream_start; + + /** The alias (for @c YAML_ALIAS_TOKEN). */ + struct { + /** The alias value. */ + yaml_char_t *value; + } alias; + + /** The anchor (for @c YAML_ANCHOR_TOKEN). */ + struct { + /** The anchor value. */ + yaml_char_t *value; + } anchor; + + /** The tag (for @c YAML_TAG_TOKEN). */ + struct { + /** The tag handle. */ + yaml_char_t *handle; + /** The tag suffix. */ + yaml_char_t *suffix; + } tag; + + /** The scalar value (for @c YAML_SCALAR_TOKEN). */ + struct { + /** The scalar value. */ + yaml_char_t *value; + /** The length of the scalar value. */ + size_t length; + /** The scalar style. */ + yaml_scalar_style_t style; + } scalar; + + /** The version directive (for @c YAML_VERSION_DIRECTIVE_TOKEN). */ + struct { + /** The major version number. */ + int major; + /** The minor version number. */ + int minor; + } version_directive; + + /** The tag directive (for @c YAML_TAG_DIRECTIVE_TOKEN). */ + struct { + /** The tag handle. */ + yaml_char_t *handle; + /** The tag prefix. */ + yaml_char_t *prefix; + } tag_directive; + + } data; + + /** The beginning of the token. */ + yaml_mark_t start_mark; + /** The end of the token. */ + yaml_mark_t end_mark; + +} yaml_token_t; + +/** + * Free any memory allocated for a token object. + * + * @param[in,out] token A token object. + */ + +YAML_DECLARE(void) +yaml_token_delete(yaml_token_t *token); + +/** @} */ + +/** + * @defgroup events Events + * @{ + */ + +/** Event types. */ +typedef enum yaml_event_type_e { + /** An empty event. */ + YAML_NO_EVENT, + + /** A STREAM-START event. */ + YAML_STREAM_START_EVENT, + /** A STREAM-END event. */ + YAML_STREAM_END_EVENT, + + /** A DOCUMENT-START event. */ + YAML_DOCUMENT_START_EVENT, + /** A DOCUMENT-END event. */ + YAML_DOCUMENT_END_EVENT, + + /** An ALIAS event. */ + YAML_ALIAS_EVENT, + /** A SCALAR event. */ + YAML_SCALAR_EVENT, + + /** A SEQUENCE-START event. */ + YAML_SEQUENCE_START_EVENT, + /** A SEQUENCE-END event. */ + YAML_SEQUENCE_END_EVENT, + + /** A MAPPING-START event. */ + YAML_MAPPING_START_EVENT, + /** A MAPPING-END event. */ + YAML_MAPPING_END_EVENT +} yaml_event_type_t; + +/** The event structure. */ +typedef struct yaml_event_s { + + /** The event type. */ + yaml_event_type_t type; + + /** The event data. */ + union { + + /** The stream parameters (for @c YAML_STREAM_START_EVENT). */ + struct { + /** The document encoding. */ + yaml_encoding_t encoding; + } stream_start; + + /** The document parameters (for @c YAML_DOCUMENT_START_EVENT). */ + struct { + /** The version directive. */ + yaml_version_directive_t *version_directive; + + /** The list of tag directives. */ + struct { + /** The beginning of the tag directives list. */ + yaml_tag_directive_t *start; + /** The end of the tag directives list. */ + yaml_tag_directive_t *end; + } tag_directives; + + /** Is the document indicator implicit? */ + int implicit; + } document_start; + + /** The document end parameters (for @c YAML_DOCUMENT_END_EVENT). */ + struct { + /** Is the document end indicator implicit? */ + int implicit; + } document_end; + + /** The alias parameters (for @c YAML_ALIAS_EVENT). */ + struct { + /** The anchor. */ + yaml_char_t *anchor; + } alias; + + /** The scalar parameters (for @c YAML_SCALAR_EVENT). */ + struct { + /** The anchor. */ + yaml_char_t *anchor; + /** The tag. */ + yaml_char_t *tag; + /** The scalar value. */ + yaml_char_t *value; + /** The length of the scalar value. */ + size_t length; + /** Is the tag optional for the plain style? */ + int plain_implicit; + /** Is the tag optional for any non-plain style? */ + int quoted_implicit; + /** The scalar style. */ + yaml_scalar_style_t style; + } scalar; + + /** The sequence parameters (for @c YAML_SEQUENCE_START_EVENT). */ + struct { + /** The anchor. */ + yaml_char_t *anchor; + /** The tag. */ + yaml_char_t *tag; + /** Is the tag optional? */ + int implicit; + /** The sequence style. */ + yaml_sequence_style_t style; + } sequence_start; + + /** The mapping parameters (for @c YAML_MAPPING_START_EVENT). */ + struct { + /** The anchor. */ + yaml_char_t *anchor; + /** The tag. */ + yaml_char_t *tag; + /** Is the tag optional? */ + int implicit; + /** The mapping style. */ + yaml_mapping_style_t style; + } mapping_start; + + } data; + + /** The beginning of the event. */ + yaml_mark_t start_mark; + /** The end of the event. */ + yaml_mark_t end_mark; + +} yaml_event_t; + +/** + * Create the STREAM-START event. + * + * @param[out] event An empty event object. + * @param[in] encoding The stream encoding. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_stream_start_event_initialize(yaml_event_t *event, + yaml_encoding_t encoding); + +/** + * Create the STREAM-END event. + * + * @param[out] event An empty event object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_stream_end_event_initialize(yaml_event_t *event); + +/** + * Create the DOCUMENT-START event. + * + * The @a implicit argument is considered as a stylistic parameter and may be + * ignored by the emitter. + * + * @param[out] event An empty event object. + * @param[in] version_directive The %YAML directive value or + * @c NULL. + * @param[in] tag_directives_start The beginning of the %TAG + * directives list. + * @param[in] tag_directives_end The end of the %TAG directives + * list. + * @param[in] implicit If the document start indicator is + * implicit. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_document_start_event_initialize(yaml_event_t *event, + yaml_version_directive_t *version_directive, + yaml_tag_directive_t *tag_directives_start, + yaml_tag_directive_t *tag_directives_end, + int implicit); + +/** + * Create the DOCUMENT-END event. + * + * The @a implicit argument is considered as a stylistic parameter and may be + * ignored by the emitter. + * + * @param[out] event An empty event object. + * @param[in] implicit If the document end indicator is implicit. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_document_end_event_initialize(yaml_event_t *event, int implicit); + +/** + * Create an ALIAS event. + * + * @param[out] event An empty event object. + * @param[in] anchor The anchor value. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_alias_event_initialize(yaml_event_t *event, const yaml_char_t *anchor); + +/** + * Create a SCALAR event. + * + * The @a style argument may be ignored by the emitter. + * + * Either the @a tag attribute or one of the @a plain_implicit and + * @a quoted_implicit flags must be set. + * + * @param[out] event An empty event object. + * @param[in] anchor The scalar anchor or @c NULL. + * @param[in] tag The scalar tag or @c NULL. + * @param[in] value The scalar value. + * @param[in] length The length of the scalar value. + * @param[in] plain_implicit If the tag may be omitted for the plain + * style. + * @param[in] quoted_implicit If the tag may be omitted for any + * non-plain style. + * @param[in] style The scalar style. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_scalar_event_initialize(yaml_event_t *event, + const yaml_char_t *anchor, const yaml_char_t *tag, + const yaml_char_t *value, int length, + int plain_implicit, int quoted_implicit, + yaml_scalar_style_t style); + +/** + * Create a SEQUENCE-START event. + * + * The @a style argument may be ignored by the emitter. + * + * Either the @a tag attribute or the @a implicit flag must be set. + * + * @param[out] event An empty event object. + * @param[in] anchor The sequence anchor or @c NULL. + * @param[in] tag The sequence tag or @c NULL. + * @param[in] implicit If the tag may be omitted. + * @param[in] style The sequence style. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_sequence_start_event_initialize(yaml_event_t *event, + const yaml_char_t *anchor, const yaml_char_t *tag, int implicit, + yaml_sequence_style_t style); + +/** + * Create a SEQUENCE-END event. + * + * @param[out] event An empty event object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_sequence_end_event_initialize(yaml_event_t *event); + +/** + * Create a MAPPING-START event. + * + * The @a style argument may be ignored by the emitter. + * + * Either the @a tag attribute or the @a implicit flag must be set. + * + * @param[out] event An empty event object. + * @param[in] anchor The mapping anchor or @c NULL. + * @param[in] tag The mapping tag or @c NULL. + * @param[in] implicit If the tag may be omitted. + * @param[in] style The mapping style. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_mapping_start_event_initialize(yaml_event_t *event, + const yaml_char_t *anchor, const yaml_char_t *tag, int implicit, + yaml_mapping_style_t style); + +/** + * Create a MAPPING-END event. + * + * @param[out] event An empty event object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_mapping_end_event_initialize(yaml_event_t *event); + +/** + * Free any memory allocated for an event object. + * + * @param[in,out] event An event object. + */ + +YAML_DECLARE(void) +yaml_event_delete(yaml_event_t *event); + +/** @} */ + +/** + * @defgroup nodes Nodes + * @{ + */ + +/** The tag @c !!null with the only possible value: @c null. */ +#define YAML_NULL_TAG "tag:yaml.org,2002:null" +/** The tag @c !!bool with the values: @c true and @c false. */ +#define YAML_BOOL_TAG "tag:yaml.org,2002:bool" +/** The tag @c !!str for string values. */ +#define YAML_STR_TAG "tag:yaml.org,2002:str" +/** The tag @c !!int for integer values. */ +#define YAML_INT_TAG "tag:yaml.org,2002:int" +/** The tag @c !!float for float values. */ +#define YAML_FLOAT_TAG "tag:yaml.org,2002:float" +/** The tag @c !!timestamp for date and time values. */ +#define YAML_TIMESTAMP_TAG "tag:yaml.org,2002:timestamp" + +/** The tag @c !!seq is used to denote sequences. */ +#define YAML_SEQ_TAG "tag:yaml.org,2002:seq" +/** The tag @c !!map is used to denote mapping. */ +#define YAML_MAP_TAG "tag:yaml.org,2002:map" + +/** The default scalar tag is @c !!str. */ +#define YAML_DEFAULT_SCALAR_TAG YAML_STR_TAG +/** The default sequence tag is @c !!seq. */ +#define YAML_DEFAULT_SEQUENCE_TAG YAML_SEQ_TAG +/** The default mapping tag is @c !!map. */ +#define YAML_DEFAULT_MAPPING_TAG YAML_MAP_TAG + +/** Node types. */ +typedef enum yaml_node_type_e { + /** An empty node. */ + YAML_NO_NODE, + + /** A scalar node. */ + YAML_SCALAR_NODE, + /** A sequence node. */ + YAML_SEQUENCE_NODE, + /** A mapping node. */ + YAML_MAPPING_NODE +} yaml_node_type_t; + +/** The forward definition of a document node structure. */ +typedef struct yaml_node_s yaml_node_t; + +/** An element of a sequence node. */ +typedef int yaml_node_item_t; + +/** An element of a mapping node. */ +typedef struct yaml_node_pair_s { + /** The key of the element. */ + int key; + /** The value of the element. */ + int value; +} yaml_node_pair_t; + +/** The node structure. */ +struct yaml_node_s { + + /** The node type. */ + yaml_node_type_t type; + + /** The node tag. */ + yaml_char_t *tag; + + /** The node data. */ + union { + + /** The scalar parameters (for @c YAML_SCALAR_NODE). */ + struct { + /** The scalar value. */ + yaml_char_t *value; + /** The length of the scalar value. */ + size_t length; + /** The scalar style. */ + yaml_scalar_style_t style; + } scalar; + + /** The sequence parameters (for @c YAML_SEQUENCE_NODE). */ + struct { + /** The stack of sequence items. */ + struct { + /** The beginning of the stack. */ + yaml_node_item_t *start; + /** The end of the stack. */ + yaml_node_item_t *end; + /** The top of the stack. */ + yaml_node_item_t *top; + } items; + /** The sequence style. */ + yaml_sequence_style_t style; + } sequence; + + /** The mapping parameters (for @c YAML_MAPPING_NODE). */ + struct { + /** The stack of mapping pairs (key, value). */ + struct { + /** The beginning of the stack. */ + yaml_node_pair_t *start; + /** The end of the stack. */ + yaml_node_pair_t *end; + /** The top of the stack. */ + yaml_node_pair_t *top; + } pairs; + /** The mapping style. */ + yaml_mapping_style_t style; + } mapping; + + } data; + + /** The beginning of the node. */ + yaml_mark_t start_mark; + /** The end of the node. */ + yaml_mark_t end_mark; + +}; + +/** The document structure. */ +typedef struct yaml_document_s { + + /** The document nodes. */ + struct { + /** The beginning of the stack. */ + yaml_node_t *start; + /** The end of the stack. */ + yaml_node_t *end; + /** The top of the stack. */ + yaml_node_t *top; + } nodes; + + /** The version directive. */ + yaml_version_directive_t *version_directive; + + /** The list of tag directives. */ + struct { + /** The beginning of the tag directives list. */ + yaml_tag_directive_t *start; + /** The end of the tag directives list. */ + yaml_tag_directive_t *end; + } tag_directives; + + /** Is the document start indicator implicit? */ + int start_implicit; + /** Is the document end indicator implicit? */ + int end_implicit; + + /** The beginning of the document. */ + yaml_mark_t start_mark; + /** The end of the document. */ + yaml_mark_t end_mark; + +} yaml_document_t; + +/** + * Create a YAML document. + * + * @param[out] document An empty document object. + * @param[in] version_directive The %YAML directive value or + * @c NULL. + * @param[in] tag_directives_start The beginning of the %TAG + * directives list. + * @param[in] tag_directives_end The end of the %TAG directives + * list. + * @param[in] start_implicit If the document start indicator is + * implicit. + * @param[in] end_implicit If the document end indicator is + * implicit. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_document_initialize(yaml_document_t *document, + yaml_version_directive_t *version_directive, + yaml_tag_directive_t *tag_directives_start, + yaml_tag_directive_t *tag_directives_end, + int start_implicit, int end_implicit); + +/** + * Delete a YAML document and all its nodes. + * + * @param[in,out] document A document object. + */ + +YAML_DECLARE(void) +yaml_document_delete(yaml_document_t *document); + +/** + * Get a node of a YAML document. + * + * The pointer returned by this function is valid until any of the functions + * modifying the documents are called. + * + * @param[in] document A document object. + * @param[in] index The node id. + * + * @returns the node objct or @c NULL if @c node_id is out of range. + */ + +YAML_DECLARE(yaml_node_t *) +yaml_document_get_node(yaml_document_t *document, int index); + +/** + * Get the root of a YAML document node. + * + * The root object is the first object added to the document. + * + * The pointer returned by this function is valid until any of the functions + * modifying the documents are called. + * + * An empty document produced by the parser signifies the end of a YAML + * stream. + * + * @param[in] document A document object. + * + * @returns the node object or @c NULL if the document is empty. + */ + +YAML_DECLARE(yaml_node_t *) +yaml_document_get_root_node(yaml_document_t *document); + +/** + * Create a SCALAR node and attach it to the document. + * + * The @a style argument may be ignored by the emitter. + * + * @param[in,out] document A document object. + * @param[in] tag The scalar tag. + * @param[in] value The scalar value. + * @param[in] length The length of the scalar value. + * @param[in] style The scalar style. + * + * @returns the node id or @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_document_add_scalar(yaml_document_t *document, + const yaml_char_t *tag, const yaml_char_t *value, int length, + yaml_scalar_style_t style); + +/** + * Create a SEQUENCE node and attach it to the document. + * + * The @a style argument may be ignored by the emitter. + * + * @param[in,out] document A document object. + * @param[in] tag The sequence tag. + * @param[in] style The sequence style. + * + * @returns the node id or @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_document_add_sequence(yaml_document_t *document, + const yaml_char_t *tag, yaml_sequence_style_t style); + +/** + * Create a MAPPING node and attach it to the document. + * + * The @a style argument may be ignored by the emitter. + * + * @param[in,out] document A document object. + * @param[in] tag The sequence tag. + * @param[in] style The sequence style. + * + * @returns the node id or @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_document_add_mapping(yaml_document_t *document, + const yaml_char_t *tag, yaml_mapping_style_t style); + +/** + * Add an item to a SEQUENCE node. + * + * @param[in,out] document A document object. + * @param[in] sequence The sequence node id. + * @param[in] item The item node id. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_document_append_sequence_item(yaml_document_t *document, + int sequence, int item); + +/** + * Add a pair of a key and a value to a MAPPING node. + * + * @param[in,out] document A document object. + * @param[in] mapping The mapping node id. + * @param[in] key The key node id. + * @param[in] value The value node id. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_document_append_mapping_pair(yaml_document_t *document, + int mapping, int key, int value); + +/** @} */ + +/** + * @defgroup parser Parser Definitions + * @{ + */ + +/** + * The prototype of a read handler. + * + * The read handler is called when the parser needs to read more bytes from the + * source. The handler should write not more than @a size bytes to the @a + * buffer. The number of written bytes should be set to the @a length variable. + * + * @param[in,out] data A pointer to an application data specified by + * yaml_parser_set_input(). + * @param[out] buffer The buffer to write the data from the source. + * @param[in] size The size of the buffer. + * @param[out] size_read The actual number of bytes read from the source. + * + * @returns On success, the handler should return @c 1. If the handler failed, + * the returned value should be @c 0. On EOF, the handler should set the + * @a size_read to @c 0 and return @c 1. + */ + +typedef int yaml_read_handler_t(void *data, unsigned char *buffer, size_t size, + size_t *size_read); + +/** + * This structure holds information about a potential simple key. + */ + +typedef struct yaml_simple_key_s { + /** Is a simple key possible? */ + int possible; + + /** Is a simple key required? */ + int required; + + /** The number of the token. */ + size_t token_number; + + /** The position mark. */ + yaml_mark_t mark; +} yaml_simple_key_t; + +/** + * The states of the parser. + */ +typedef enum yaml_parser_state_e { + /** Expect STREAM-START. */ + YAML_PARSE_STREAM_START_STATE, + /** Expect the beginning of an implicit document. */ + YAML_PARSE_IMPLICIT_DOCUMENT_START_STATE, + /** Expect DOCUMENT-START. */ + YAML_PARSE_DOCUMENT_START_STATE, + /** Expect the content of a document. */ + YAML_PARSE_DOCUMENT_CONTENT_STATE, + /** Expect DOCUMENT-END. */ + YAML_PARSE_DOCUMENT_END_STATE, + + /** Expect a block node. */ + YAML_PARSE_BLOCK_NODE_STATE, + /** Expect a block node or indentless sequence. */ + YAML_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE, + /** Expect a flow node. */ + YAML_PARSE_FLOW_NODE_STATE, + /** Expect the first entry of a block sequence. */ + YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE, + /** Expect an entry of a block sequence. */ + YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE, + + /** Expect an entry of an indentless sequence. */ + YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE, + /** Expect the first key of a block mapping. */ + YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE, + /** Expect a block mapping key. */ + YAML_PARSE_BLOCK_MAPPING_KEY_STATE, + /** Expect a block mapping value. */ + YAML_PARSE_BLOCK_MAPPING_VALUE_STATE, + /** Expect the first entry of a flow sequence. */ + YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE, + + /** Expect an entry of a flow sequence. */ + YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE, + /** Expect a key of an ordered mapping. */ + YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE, + /** Expect a value of an ordered mapping. */ + YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE, + /** Expect the and of an ordered mapping entry. */ + YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE, + /** Expect the first key of a flow mapping. */ + YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE, + /** Expect a key of a flow mapping. */ + + YAML_PARSE_FLOW_MAPPING_KEY_STATE, + /** Expect a value of a flow mapping. */ + YAML_PARSE_FLOW_MAPPING_VALUE_STATE, + /** Expect an empty value of a flow mapping. */ + YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE, + /** Expect nothing. */ + YAML_PARSE_END_STATE +} yaml_parser_state_t; + +/** + * This structure holds aliases data. + */ + +typedef struct yaml_alias_data_s { + /** The anchor. */ + yaml_char_t *anchor; + /** The node id. */ + int index; + /** The anchor mark. */ + yaml_mark_t mark; +} yaml_alias_data_t; + +/** + * The parser structure. + * + * All members are internal. Manage the structure using the @c yaml_parser_ + * family of functions. + */ + +typedef struct yaml_parser_s { + + /** + * @name Error handling + * @{ + */ + + /** Error type. */ + yaml_error_type_t error; + /** Error description. */ + const char *problem; + /** The byte about which the problem occurred. */ + size_t problem_offset; + /** The problematic value (@c -1 is none). */ + int problem_value; + /** The problem position. */ + yaml_mark_t problem_mark; + /** The error context. */ + const char *context; + /** The context position. */ + yaml_mark_t context_mark; + + /** + * @} + */ + + /** + * @name Reader stuff + * @{ + */ + + /** Read handler. */ + yaml_read_handler_t *read_handler; + + /** A pointer for passing to the read handler. */ + void *read_handler_data; + + /** Standard (string or file) input data. */ + union { + /** String input data. */ + struct { + /** The string start pointer. */ + const unsigned char *start; + /** The string end pointer. */ + const unsigned char *end; + /** The string current position. */ + const unsigned char *current; + } string; + + /** File input data. */ + FILE *file; + } input; + + /** EOF flag */ + int eof; + + /** The working buffer. */ + struct { + /** The beginning of the buffer. */ + yaml_char_t *start; + /** The end of the buffer. */ + yaml_char_t *end; + /** The current position of the buffer. */ + yaml_char_t *pointer; + /** The last filled position of the buffer. */ + yaml_char_t *last; + } buffer; + + /* The number of unread characters in the buffer. */ + size_t unread; + + /** The raw buffer. */ + struct { + /** The beginning of the buffer. */ + unsigned char *start; + /** The end of the buffer. */ + unsigned char *end; + /** The current position of the buffer. */ + unsigned char *pointer; + /** The last filled position of the buffer. */ + unsigned char *last; + } raw_buffer; + + /** The input encoding. */ + yaml_encoding_t encoding; + + /** The offset of the current position (in bytes). */ + size_t offset; + + /** The mark of the current position. */ + yaml_mark_t mark; + + /** + * @} + */ + + /** + * @name Scanner stuff + * @{ + */ + + /** Have we started to scan the input stream? */ + int stream_start_produced; + + /** Have we reached the end of the input stream? */ + int stream_end_produced; + + /** The number of unclosed '[' and '{' indicators. */ + int flow_level; + + /** The tokens queue. */ + struct { + /** The beginning of the tokens queue. */ + yaml_token_t *start; + /** The end of the tokens queue. */ + yaml_token_t *end; + /** The head of the tokens queue. */ + yaml_token_t *head; + /** The tail of the tokens queue. */ + yaml_token_t *tail; + } tokens; + + /** The number of tokens fetched from the queue. */ + size_t tokens_parsed; + + /** Does the tokens queue contain a token ready for dequeueing. */ + int token_available; + + /** The indentation levels stack. */ + struct { + /** The beginning of the stack. */ + int *start; + /** The end of the stack. */ + int *end; + /** The top of the stack. */ + int *top; + } indents; + + /** The current indentation level. */ + int indent; + + /** May a simple key occur at the current position? */ + int simple_key_allowed; + + /** The stack of simple keys. */ + struct { + /** The beginning of the stack. */ + yaml_simple_key_t *start; + /** The end of the stack. */ + yaml_simple_key_t *end; + /** The top of the stack. */ + yaml_simple_key_t *top; + } simple_keys; + + /** + * @} + */ + + /** + * @name Parser stuff + * @{ + */ + + /** The parser states stack. */ + struct { + /** The beginning of the stack. */ + yaml_parser_state_t *start; + /** The end of the stack. */ + yaml_parser_state_t *end; + /** The top of the stack. */ + yaml_parser_state_t *top; + } states; + + /** The current parser state. */ + yaml_parser_state_t state; + + /** The stack of marks. */ + struct { + /** The beginning of the stack. */ + yaml_mark_t *start; + /** The end of the stack. */ + yaml_mark_t *end; + /** The top of the stack. */ + yaml_mark_t *top; + } marks; + + /** The list of TAG directives. */ + struct { + /** The beginning of the list. */ + yaml_tag_directive_t *start; + /** The end of the list. */ + yaml_tag_directive_t *end; + /** The top of the list. */ + yaml_tag_directive_t *top; + } tag_directives; + + /** + * @} + */ + + /** + * @name Dumper stuff + * @{ + */ + + /** The alias data. */ + struct { + /** The beginning of the list. */ + yaml_alias_data_t *start; + /** The end of the list. */ + yaml_alias_data_t *end; + /** The top of the list. */ + yaml_alias_data_t *top; + } aliases; + + /** The currently parsed document. */ + yaml_document_t *document; + + /** + * @} + */ + +} yaml_parser_t; + +/** + * Initialize a parser. + * + * This function creates a new parser object. An application is responsible + * for destroying the object using the yaml_parser_delete() function. + * + * @param[out] parser An empty parser object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_parser_initialize(yaml_parser_t *parser); + +/** + * Destroy a parser. + * + * @param[in,out] parser A parser object. + */ + +YAML_DECLARE(void) +yaml_parser_delete(yaml_parser_t *parser); + +/** + * Set a string input. + * + * Note that the @a input pointer must be valid while the @a parser object + * exists. The application is responsible for destroying @a input after + * destroying the @a parser. + * + * @param[in,out] parser A parser object. + * @param[in] input A source data. + * @param[in] size The length of the source data in bytes. + */ + +YAML_DECLARE(void) +yaml_parser_set_input_string(yaml_parser_t *parser, + const unsigned char *input, size_t size); + +/** + * Set a file input. + * + * @a file should be a file object open for reading. The application is + * responsible for closing the @a file. + * + * @param[in,out] parser A parser object. + * @param[in] file An open file. + */ + +YAML_DECLARE(void) +yaml_parser_set_input_file(yaml_parser_t *parser, FILE *file); + +/** + * Set a generic input handler. + * + * @param[in,out] parser A parser object. + * @param[in] handler A read handler. + * @param[in] data Any application data for passing to the read + * handler. + */ + +YAML_DECLARE(void) +yaml_parser_set_input(yaml_parser_t *parser, + yaml_read_handler_t *handler, void *data); + +/** + * Set the source encoding. + * + * @param[in,out] parser A parser object. + * @param[in] encoding The source encoding. + */ + +YAML_DECLARE(void) +yaml_parser_set_encoding(yaml_parser_t *parser, yaml_encoding_t encoding); + +/** + * Scan the input stream and produce the next token. + * + * Call the function subsequently to produce a sequence of tokens corresponding + * to the input stream. The initial token has the type + * @c YAML_STREAM_START_TOKEN while the ending token has the type + * @c YAML_STREAM_END_TOKEN. + * + * An application is responsible for freeing any buffers associated with the + * produced token object using the @c yaml_token_delete function. + * + * An application must not alternate the calls of yaml_parser_scan() with the + * calls of yaml_parser_parse() or yaml_parser_load(). Doing this will break + * the parser. + * + * @param[in,out] parser A parser object. + * @param[out] token An empty token object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_parser_scan(yaml_parser_t *parser, yaml_token_t *token); + +/** + * Parse the input stream and produce the next parsing event. + * + * Call the function subsequently to produce a sequence of events corresponding + * to the input stream. The initial event has the type + * @c YAML_STREAM_START_EVENT while the ending event has the type + * @c YAML_STREAM_END_EVENT. + * + * An application is responsible for freeing any buffers associated with the + * produced event object using the yaml_event_delete() function. + * + * An application must not alternate the calls of yaml_parser_parse() with the + * calls of yaml_parser_scan() or yaml_parser_load(). Doing this will break the + * parser. + * + * @param[in,out] parser A parser object. + * @param[out] event An empty event object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_parser_parse(yaml_parser_t *parser, yaml_event_t *event); + +/** + * Parse the input stream and produce the next YAML document. + * + * Call this function subsequently to produce a sequence of documents + * constituting the input stream. + * + * If the produced document has no root node, it means that the document + * end has been reached. + * + * An application is responsible for freeing any data associated with the + * produced document object using the yaml_document_delete() function. + * + * An application must not alternate the calls of yaml_parser_load() with the + * calls of yaml_parser_scan() or yaml_parser_parse(). Doing this will break + * the parser. + * + * @param[in,out] parser A parser object. + * @param[out] document An empty document object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_parser_load(yaml_parser_t *parser, yaml_document_t *document); + +/** @} */ + +/** + * @defgroup emitter Emitter Definitions + * @{ + */ + +/** + * The prototype of a write handler. + * + * The write handler is called when the emitter needs to flush the accumulated + * characters to the output. The handler should write @a size bytes of the + * @a buffer to the output. + * + * @param[in,out] data A pointer to an application data specified by + * yaml_emitter_set_output(). + * @param[in] buffer The buffer with bytes to be written. + * @param[in] size The size of the buffer. + * + * @returns On success, the handler should return @c 1. If the handler failed, + * the returned value should be @c 0. + */ + +typedef int yaml_write_handler_t(void *data, unsigned char *buffer, size_t size); + +/** The emitter states. */ +typedef enum yaml_emitter_state_e { + /** Expect STREAM-START. */ + YAML_EMIT_STREAM_START_STATE, + /** Expect the first DOCUMENT-START or STREAM-END. */ + YAML_EMIT_FIRST_DOCUMENT_START_STATE, + /** Expect DOCUMENT-START or STREAM-END. */ + YAML_EMIT_DOCUMENT_START_STATE, + /** Expect the content of a document. */ + YAML_EMIT_DOCUMENT_CONTENT_STATE, + /** Expect DOCUMENT-END. */ + YAML_EMIT_DOCUMENT_END_STATE, + + /** Expect the first item of a flow sequence. */ + YAML_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE, + /** Expect an item of a flow sequence. */ + YAML_EMIT_FLOW_SEQUENCE_ITEM_STATE, + /** Expect the first key of a flow mapping. */ + YAML_EMIT_FLOW_MAPPING_FIRST_KEY_STATE, + /** Expect a key of a flow mapping. */ + YAML_EMIT_FLOW_MAPPING_KEY_STATE, + /** Expect a value for a simple key of a flow mapping. */ + YAML_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE, + + /** Expect a value of a flow mapping. */ + YAML_EMIT_FLOW_MAPPING_VALUE_STATE, + /** Expect the first item of a block sequence. */ + YAML_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE, + /** Expect an item of a block sequence. */ + YAML_EMIT_BLOCK_SEQUENCE_ITEM_STATE, + /** Expect the first key of a block mapping. */ + YAML_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE, + /** Expect the key of a block mapping. */ + YAML_EMIT_BLOCK_MAPPING_KEY_STATE, + + /** Expect a value for a simple key of a block mapping. */ + YAML_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE, + /** Expect a value of a block mapping. */ + YAML_EMIT_BLOCK_MAPPING_VALUE_STATE, + /** Expect nothing. */ + YAML_EMIT_END_STATE +} yaml_emitter_state_t; + + +/* This is needed for C++ */ + +typedef struct yaml_anchors_s { + /** The number of references. */ + int references; + /** The anchor id. */ + int anchor; + /** If the node has been emitted? */ + int serialized; +} yaml_anchors_t; + +/** + * The emitter structure. + * + * All members are internal. Manage the structure using the @c yaml_emitter_ + * family of functions. + */ + +typedef struct yaml_emitter_s { + + /** + * @name Error handling + * @{ + */ + + /** Error type. */ + yaml_error_type_t error; + /** Error description. */ + const char *problem; + + /** + * @} + */ + + /** + * @name Writer stuff + * @{ + */ + + /** Write handler. */ + yaml_write_handler_t *write_handler; + + /** A pointer for passing to the write handler. */ + void *write_handler_data; + + /** Standard (string or file) output data. */ + union { + /** String output data. */ + struct { + /** The buffer pointer. */ + unsigned char *buffer; + /** The buffer size. */ + size_t size; + /** The number of written bytes. */ + size_t *size_written; + } string; + + /** File output data. */ + FILE *file; + } output; + + /** The working buffer. */ + struct { + /** The beginning of the buffer. */ + yaml_char_t *start; + /** The end of the buffer. */ + yaml_char_t *end; + /** The current position of the buffer. */ + yaml_char_t *pointer; + /** The last filled position of the buffer. */ + yaml_char_t *last; + } buffer; + + /** The raw buffer. */ + struct { + /** The beginning of the buffer. */ + unsigned char *start; + /** The end of the buffer. */ + unsigned char *end; + /** The current position of the buffer. */ + unsigned char *pointer; + /** The last filled position of the buffer. */ + unsigned char *last; + } raw_buffer; + + /** The stream encoding. */ + yaml_encoding_t encoding; + + /** + * @} + */ + + /** + * @name Emitter stuff + * @{ + */ + + /** If the output is in the canonical style? */ + int canonical; + /** The number of indentation spaces. */ + int best_indent; + /** The preferred width of the output lines. */ + int best_width; + /** Allow unescaped non-ASCII characters? */ + int unicode; + /** The preferred line break. */ + yaml_break_t line_break; + + /** The stack of states. */ + struct { + /** The beginning of the stack. */ + yaml_emitter_state_t *start; + /** The end of the stack. */ + yaml_emitter_state_t *end; + /** The top of the stack. */ + yaml_emitter_state_t *top; + } states; + + /** The current emitter state. */ + yaml_emitter_state_t state; + + /** The event queue. */ + struct { + /** The beginning of the event queue. */ + yaml_event_t *start; + /** The end of the event queue. */ + yaml_event_t *end; + /** The head of the event queue. */ + yaml_event_t *head; + /** The tail of the event queue. */ + yaml_event_t *tail; + } events; + + /** The stack of indentation levels. */ + struct { + /** The beginning of the stack. */ + int *start; + /** The end of the stack. */ + int *end; + /** The top of the stack. */ + int *top; + } indents; + + /** The list of tag directives. */ + struct { + /** The beginning of the list. */ + yaml_tag_directive_t *start; + /** The end of the list. */ + yaml_tag_directive_t *end; + /** The top of the list. */ + yaml_tag_directive_t *top; + } tag_directives; + + /** The current indentation level. */ + int indent; + + /** The current flow level. */ + int flow_level; + + /** Is it the document root context? */ + int root_context; + /** Is it a sequence context? */ + int sequence_context; + /** Is it a mapping context? */ + int mapping_context; + /** Is it a simple mapping key context? */ + int simple_key_context; + + /** The current line. */ + int line; + /** The current column. */ + int column; + /** If the last character was a whitespace? */ + int whitespace; + /** If the last character was an indentation character (' ', '-', '?', ':')? */ + int indention; + /** If an explicit document end is required? */ + int open_ended; + + /** Anchor analysis. */ + struct { + /** The anchor value. */ + yaml_char_t *anchor; + /** The anchor length. */ + size_t anchor_length; + /** Is it an alias? */ + int alias; + } anchor_data; + + /** Tag analysis. */ + struct { + /** The tag handle. */ + yaml_char_t *handle; + /** The tag handle length. */ + size_t handle_length; + /** The tag suffix. */ + yaml_char_t *suffix; + /** The tag suffix length. */ + size_t suffix_length; + } tag_data; + + /** Scalar analysis. */ + struct { + /** The scalar value. */ + yaml_char_t *value; + /** The scalar length. */ + size_t length; + /** Does the scalar contain line breaks? */ + int multiline; + /** Can the scalar be expressed in the flow plain style? */ + int flow_plain_allowed; + /** Can the scalar be expressed in the block plain style? */ + int block_plain_allowed; + /** Can the scalar be expressed in the single quoted style? */ + int single_quoted_allowed; + /** Can the scalar be expressed in the literal or folded styles? */ + int block_allowed; + /** The output style. */ + yaml_scalar_style_t style; + } scalar_data; + + /** + * @} + */ + + /** + * @name Dumper stuff + * @{ + */ + + /** If the stream was already opened? */ + int opened; + /** If the stream was already closed? */ + int closed; + + /** The information associated with the document nodes. */ + yaml_anchors_t *anchors; + + /** The last assigned anchor id. */ + int last_anchor_id; + + /** The currently emitted document. */ + yaml_document_t *document; + + /** + * @} + */ + +} yaml_emitter_t; + +/** + * Initialize an emitter. + * + * This function creates a new emitter object. An application is responsible + * for destroying the object using the yaml_emitter_delete() function. + * + * @param[out] emitter An empty parser object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_emitter_initialize(yaml_emitter_t *emitter); + +/** + * Destroy an emitter. + * + * @param[in,out] emitter An emitter object. + */ + +YAML_DECLARE(void) +yaml_emitter_delete(yaml_emitter_t *emitter); + +/** + * Set a string output. + * + * The emitter will write the output characters to the @a output buffer of the + * size @a size. The emitter will set @a size_written to the number of written + * bytes. If the buffer is smaller than required, the emitter produces the + * YAML_WRITE_ERROR error. + * + * @param[in,out] emitter An emitter object. + * @param[in] output An output buffer. + * @param[in] size The buffer size. + * @param[in] size_written The pointer to save the number of written + * bytes. + */ + +YAML_DECLARE(void) +yaml_emitter_set_output_string(yaml_emitter_t *emitter, + unsigned char *output, size_t size, size_t *size_written); + +/** + * Set a file output. + * + * @a file should be a file object open for writing. The application is + * responsible for closing the @a file. + * + * @param[in,out] emitter An emitter object. + * @param[in] file An open file. + */ + +YAML_DECLARE(void) +yaml_emitter_set_output_file(yaml_emitter_t *emitter, FILE *file); + +/** + * Set a generic output handler. + * + * @param[in,out] emitter An emitter object. + * @param[in] handler A write handler. + * @param[in] data Any application data for passing to the write + * handler. + */ + +YAML_DECLARE(void) +yaml_emitter_set_output(yaml_emitter_t *emitter, + yaml_write_handler_t *handler, void *data); + +/** + * Set the output encoding. + * + * @param[in,out] emitter An emitter object. + * @param[in] encoding The output encoding. + */ + +YAML_DECLARE(void) +yaml_emitter_set_encoding(yaml_emitter_t *emitter, yaml_encoding_t encoding); + +/** + * Set if the output should be in the "canonical" format as in the YAML + * specification. + * + * @param[in,out] emitter An emitter object. + * @param[in] canonical If the output is canonical. + */ + +YAML_DECLARE(void) +yaml_emitter_set_canonical(yaml_emitter_t *emitter, int canonical); + +/** + * Set the indentation increment. + * + * @param[in,out] emitter An emitter object. + * @param[in] indent The indentation increment (1 < . < 10). + */ + +YAML_DECLARE(void) +yaml_emitter_set_indent(yaml_emitter_t *emitter, int indent); + +/** + * Set the preferred line width. @c -1 means unlimited. + * + * @param[in,out] emitter An emitter object. + * @param[in] width The preferred line width. + */ + +YAML_DECLARE(void) +yaml_emitter_set_width(yaml_emitter_t *emitter, int width); + +/** + * Set if unescaped non-ASCII characters are allowed. + * + * @param[in,out] emitter An emitter object. + * @param[in] unicode If unescaped Unicode characters are allowed. + */ + +YAML_DECLARE(void) +yaml_emitter_set_unicode(yaml_emitter_t *emitter, int unicode); + +/** + * Set the preferred line break. + * + * @param[in,out] emitter An emitter object. + * @param[in] line_break The preferred line break. + */ + +YAML_DECLARE(void) +yaml_emitter_set_break(yaml_emitter_t *emitter, yaml_break_t line_break); + +/** + * Emit an event. + * + * The event object may be generated using the yaml_parser_parse() function. + * The emitter takes the responsibility for the event object and destroys its + * content after it is emitted. The event object is destroyed even if the + * function fails. + * + * @param[in,out] emitter An emitter object. + * @param[in,out] event An event object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_emitter_emit(yaml_emitter_t *emitter, yaml_event_t *event); + +/** + * Start a YAML stream. + * + * This function should be used before yaml_emitter_dump() is called. + * + * @param[in,out] emitter An emitter object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_emitter_open(yaml_emitter_t *emitter); + +/** + * Finish a YAML stream. + * + * This function should be used after yaml_emitter_dump() is called. + * + * @param[in,out] emitter An emitter object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_emitter_close(yaml_emitter_t *emitter); + +/** + * Emit a YAML document. + * + * The document object may be generated using the yaml_parser_load() function + * or the yaml_document_initialize() function. The emitter takes the + * responsibility for the document object and destroys its content after + * it is emitted. The document object is destroyed even if the function fails. + * + * @param[in,out] emitter An emitter object. + * @param[in,out] document A document object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_emitter_dump(yaml_emitter_t *emitter, yaml_document_t *document); + +/** + * Flush the accumulated characters to the output. + * + * @param[in,out] emitter An emitter object. + * + * @returns @c 1 if the function succeeded, @c 0 on error. + */ + +YAML_DECLARE(int) +yaml_emitter_flush(yaml_emitter_t *emitter); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* #ifndef YAML_H */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/yaml_private.h b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/yaml_private.h new file mode 100644 index 0000000..266a6bd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/ext/psych/yaml/yaml_private.h @@ -0,0 +1,688 @@ +#ifdef RUBY_EXTCONF_H +#include RUBY_EXTCONF_H +#endif + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include + +#include +#include +#include + +/* + * Memory management. + */ + +YAML_DECLARE(void *) +yaml_malloc(size_t size); + +YAML_DECLARE(void *) +yaml_realloc(void *ptr, size_t size); + +YAML_DECLARE(void) +yaml_free(void *ptr); + +YAML_DECLARE(yaml_char_t *) +yaml_strdup(const yaml_char_t *); + +/* + * Reader: Ensure that the buffer contains at least `length` characters. + */ + +YAML_DECLARE(int) +yaml_parser_update_buffer(yaml_parser_t *parser, size_t length); + +/* + * Scanner: Ensure that the token stack contains at least one token ready. + */ + +YAML_DECLARE(int) +yaml_parser_fetch_more_tokens(yaml_parser_t *parser); + +/* + * The size of the input raw buffer. + */ + +#define INPUT_RAW_BUFFER_SIZE 16384 + +/* + * The size of the input buffer. + * + * It should be possible to decode the whole raw buffer. + */ + +#define INPUT_BUFFER_SIZE (INPUT_RAW_BUFFER_SIZE*3) + +/* + * The size of the output buffer. + */ + +#define OUTPUT_BUFFER_SIZE 16384 + +/* + * The size of the output raw buffer. + * + * It should be possible to encode the whole output buffer. + */ + +#define OUTPUT_RAW_BUFFER_SIZE (OUTPUT_BUFFER_SIZE*2+2) + +/* + * The maximum size of a YAML input file. + * This used to be PTRDIFF_MAX, but that's not entirely portable + * because stdint.h isn't available on all platforms. + * It is not entirely clear why this isn't the maximum value + * that can fit into the parser->offset field. + */ + +#define MAX_FILE_SIZE (~(size_t)0 / 2) + + +/* + * The size of other stacks and queues. + */ + +#define INITIAL_STACK_SIZE 16 +#define INITIAL_QUEUE_SIZE 16 +#define INITIAL_STRING_SIZE 16 + +/* + * Buffer management. + */ + +#define BUFFER_INIT(context,buffer,size) \ + (((buffer).start = (yaml_char_t *)yaml_malloc(size)) ? \ + ((buffer).last = (buffer).pointer = (buffer).start, \ + (buffer).end = (buffer).start+(size), \ + 1) : \ + ((context)->error = YAML_MEMORY_ERROR, \ + 0)) + +#define BUFFER_DEL(context,buffer) \ + (yaml_free((buffer).start), \ + (buffer).start = (buffer).pointer = (buffer).end = 0) + +/* + * String management. + */ + +typedef struct { + yaml_char_t *start; + yaml_char_t *end; + yaml_char_t *pointer; +} yaml_string_t; + +YAML_DECLARE(int) +yaml_string_extend(yaml_char_t **start, + yaml_char_t **pointer, yaml_char_t **end); + +YAML_DECLARE(int) +yaml_string_join( + yaml_char_t **a_start, yaml_char_t **a_pointer, yaml_char_t **a_end, + yaml_char_t **b_start, yaml_char_t **b_pointer, yaml_char_t **b_end); + +#define NULL_STRING { NULL, NULL, NULL } + +#define STRING(string,length) { (string), (string)+(length), (string) } + +#define STRING_ASSIGN(value,string,length) \ + ((value).start = (string), \ + (value).end = (string)+(length), \ + (value).pointer = (string)) + +#define STRING_INIT(context,string,size) \ + (((string).start = YAML_MALLOC(size)) ? \ + ((string).pointer = (string).start, \ + (string).end = (string).start+(size), \ + memset((string).start, 0, (size)), \ + 1) : \ + ((context)->error = YAML_MEMORY_ERROR, \ + 0)) + +#define STRING_DEL(context,string) \ + (yaml_free((string).start), \ + (string).start = (string).pointer = (string).end = 0) + +#define STRING_EXTEND(context,string) \ + ((((string).pointer+5 < (string).end) \ + || yaml_string_extend(&(string).start, \ + &(string).pointer, &(string).end)) ? \ + 1 : \ + ((context)->error = YAML_MEMORY_ERROR, \ + 0)) + +#define CLEAR(context,string) \ + ((string).pointer = (string).start, \ + memset((string).start, 0, (string).end-(string).start)) + +#define JOIN(context,string_a,string_b) \ + ((yaml_string_join(&(string_a).start, &(string_a).pointer, \ + &(string_a).end, &(string_b).start, \ + &(string_b).pointer, &(string_b).end)) ? \ + ((string_b).pointer = (string_b).start, \ + 1) : \ + ((context)->error = YAML_MEMORY_ERROR, \ + 0)) + +/* + * String check operations. + */ + +/* + * Check the octet at the specified position. + */ + +#define CHECK_AT(string,octet,offset) \ + ((string).pointer[offset] == (yaml_char_t)(octet)) + +/* + * Check the current octet in the buffer. + */ + +#define CHECK(string,octet) (CHECK_AT((string),(octet),0)) + +/* + * Check if the character at the specified position is an alphabetical + * character, a digit, '_', or '-'. + */ + +#define IS_ALPHA_AT(string,offset) \ + (((string).pointer[offset] >= (yaml_char_t) '0' && \ + (string).pointer[offset] <= (yaml_char_t) '9') || \ + ((string).pointer[offset] >= (yaml_char_t) 'A' && \ + (string).pointer[offset] <= (yaml_char_t) 'Z') || \ + ((string).pointer[offset] >= (yaml_char_t) 'a' && \ + (string).pointer[offset] <= (yaml_char_t) 'z') || \ + (string).pointer[offset] == '_' || \ + (string).pointer[offset] == '-') + +#define IS_ALPHA(string) IS_ALPHA_AT((string),0) + +/* + * Check if the character at the specified position is a digit. + */ + +#define IS_DIGIT_AT(string,offset) \ + (((string).pointer[offset] >= (yaml_char_t) '0' && \ + (string).pointer[offset] <= (yaml_char_t) '9')) + +#define IS_DIGIT(string) IS_DIGIT_AT((string),0) + +/* + * Get the value of a digit. + */ + +#define AS_DIGIT_AT(string,offset) \ + ((string).pointer[offset] - (yaml_char_t) '0') + +#define AS_DIGIT(string) AS_DIGIT_AT((string),0) + +/* + * Check if the character at the specified position is a hex-digit. + */ + +#define IS_HEX_AT(string,offset) \ + (((string).pointer[offset] >= (yaml_char_t) '0' && \ + (string).pointer[offset] <= (yaml_char_t) '9') || \ + ((string).pointer[offset] >= (yaml_char_t) 'A' && \ + (string).pointer[offset] <= (yaml_char_t) 'F') || \ + ((string).pointer[offset] >= (yaml_char_t) 'a' && \ + (string).pointer[offset] <= (yaml_char_t) 'f')) + +#define IS_HEX(string) IS_HEX_AT((string),0) + +/* + * Get the value of a hex-digit. + */ + +#define AS_HEX_AT(string,offset) \ + (((string).pointer[offset] >= (yaml_char_t) 'A' && \ + (string).pointer[offset] <= (yaml_char_t) 'F') ? \ + ((string).pointer[offset] - (yaml_char_t) 'A' + 10) : \ + ((string).pointer[offset] >= (yaml_char_t) 'a' && \ + (string).pointer[offset] <= (yaml_char_t) 'f') ? \ + ((string).pointer[offset] - (yaml_char_t) 'a' + 10) : \ + ((string).pointer[offset] - (yaml_char_t) '0')) + +#define AS_HEX(string) AS_HEX_AT((string),0) + +/* + * Check if the character is ASCII. + */ + +#define IS_ASCII_AT(string,offset) \ + ((string).pointer[offset] <= (yaml_char_t) '\x7F') + +#define IS_ASCII(string) IS_ASCII_AT((string),0) + +/* + * Check if the character can be printed unescaped. + */ + +#define IS_PRINTABLE_AT(string,offset) \ + (((string).pointer[offset] == 0x0A) /* . == #x0A */ \ + || ((string).pointer[offset] >= 0x20 /* #x20 <= . <= #x7E */ \ + && (string).pointer[offset] <= 0x7E) \ + || ((string).pointer[offset] == 0xC2 /* #0xA0 <= . <= #xD7FF */ \ + && (string).pointer[offset+1] >= 0xA0) \ + || ((string).pointer[offset] > 0xC2 \ + && (string).pointer[offset] < 0xED) \ + || ((string).pointer[offset] == 0xED \ + && (string).pointer[offset+1] < 0xA0) \ + || ((string).pointer[offset] == 0xEE) \ + || ((string).pointer[offset] == 0xEF /* #xE000 <= . <= #xFFFD */ \ + && !((string).pointer[offset+1] == 0xBB /* && . != #xFEFF */ \ + && (string).pointer[offset+2] == 0xBF) \ + && !((string).pointer[offset+1] == 0xBF \ + && ((string).pointer[offset+2] == 0xBE \ + || (string).pointer[offset+2] == 0xBF)))) + +#define IS_PRINTABLE(string) IS_PRINTABLE_AT((string),0) + +/* + * Check if the character at the specified position is NUL. + */ + +#define IS_Z_AT(string,offset) CHECK_AT((string),'\0',(offset)) + +#define IS_Z(string) IS_Z_AT((string),0) + +/* + * Check if the character at the specified position is BOM. + */ + +#define IS_BOM_AT(string,offset) \ + (CHECK_AT((string),'\xEF',(offset)) \ + && CHECK_AT((string),'\xBB',(offset)+1) \ + && CHECK_AT((string),'\xBF',(offset)+2)) /* BOM (#xFEFF) */ + +#define IS_BOM(string) IS_BOM_AT(string,0) + +/* + * Check if the character at the specified position is space. + */ + +#define IS_SPACE_AT(string,offset) CHECK_AT((string),' ',(offset)) + +#define IS_SPACE(string) IS_SPACE_AT((string),0) + +/* + * Check if the character at the specified position is tab. + */ + +#define IS_TAB_AT(string,offset) CHECK_AT((string),'\t',(offset)) + +#define IS_TAB(string) IS_TAB_AT((string),0) + +/* + * Check if the character at the specified position is blank (space or tab). + */ + +#define IS_BLANK_AT(string,offset) \ + (IS_SPACE_AT((string),(offset)) || IS_TAB_AT((string),(offset))) + +#define IS_BLANK(string) IS_BLANK_AT((string),0) + +/* + * Check if the character at the specified position is a line break. + */ + +#define IS_BREAK_AT(string,offset) \ + (CHECK_AT((string),'\r',(offset)) /* CR (#xD)*/ \ + || CHECK_AT((string),'\n',(offset)) /* LF (#xA) */ \ + || (CHECK_AT((string),'\xC2',(offset)) \ + && CHECK_AT((string),'\x85',(offset)+1)) /* NEL (#x85) */ \ + || (CHECK_AT((string),'\xE2',(offset)) \ + && CHECK_AT((string),'\x80',(offset)+1) \ + && CHECK_AT((string),'\xA8',(offset)+2)) /* LS (#x2028) */ \ + || (CHECK_AT((string),'\xE2',(offset)) \ + && CHECK_AT((string),'\x80',(offset)+1) \ + && CHECK_AT((string),'\xA9',(offset)+2))) /* PS (#x2029) */ + +#define IS_BREAK(string) IS_BREAK_AT((string),0) + +#define IS_CRLF_AT(string,offset) \ + (CHECK_AT((string),'\r',(offset)) && CHECK_AT((string),'\n',(offset)+1)) + +#define IS_CRLF(string) IS_CRLF_AT((string),0) + +/* + * Check if the character is a line break or NUL. + */ + +#define IS_BREAKZ_AT(string,offset) \ + (IS_BREAK_AT((string),(offset)) || IS_Z_AT((string),(offset))) + +#define IS_BREAKZ(string) IS_BREAKZ_AT((string),0) + +/* + * Check if the character is a line break, space, or NUL. + */ + +#define IS_SPACEZ_AT(string,offset) \ + (IS_SPACE_AT((string),(offset)) || IS_BREAKZ_AT((string),(offset))) + +#define IS_SPACEZ(string) IS_SPACEZ_AT((string),0) + +/* + * Check if the character is a line break, space, tab, or NUL. + */ + +#define IS_BLANKZ_AT(string,offset) \ + (IS_BLANK_AT((string),(offset)) || IS_BREAKZ_AT((string),(offset))) + +#define IS_BLANKZ(string) IS_BLANKZ_AT((string),0) + +/* + * Determine the width of the character. + */ + +#define WIDTH_AT(string,offset) \ + (((string).pointer[offset] & 0x80) == 0x00 ? 1 : \ + ((string).pointer[offset] & 0xE0) == 0xC0 ? 2 : \ + ((string).pointer[offset] & 0xF0) == 0xE0 ? 3 : \ + ((string).pointer[offset] & 0xF8) == 0xF0 ? 4 : 0) + +#define WIDTH(string) WIDTH_AT((string),0) + +/* + * Move the string pointer to the next character. + */ + +#define MOVE(string) ((string).pointer += WIDTH((string))) + +/* + * Copy a character and move the pointers of both strings. + */ + +#define COPY(string_a,string_b) \ + ((*(string_b).pointer & 0x80) == 0x00 ? \ + (*((string_a).pointer++) = *((string_b).pointer++)) : \ + (*(string_b).pointer & 0xE0) == 0xC0 ? \ + (*((string_a).pointer++) = *((string_b).pointer++), \ + *((string_a).pointer++) = *((string_b).pointer++)) : \ + (*(string_b).pointer & 0xF0) == 0xE0 ? \ + (*((string_a).pointer++) = *((string_b).pointer++), \ + *((string_a).pointer++) = *((string_b).pointer++), \ + *((string_a).pointer++) = *((string_b).pointer++)) : \ + (*(string_b).pointer & 0xF8) == 0xF0 ? \ + (*((string_a).pointer++) = *((string_b).pointer++), \ + *((string_a).pointer++) = *((string_b).pointer++), \ + *((string_a).pointer++) = *((string_b).pointer++), \ + *((string_a).pointer++) = *((string_b).pointer++)) : 0) + +/* + * Stack and queue management. + */ + +YAML_DECLARE(int) +yaml_stack_extend(void **start, void **top, void **end); + +YAML_DECLARE(int) +yaml_queue_extend(void **start, void **head, void **tail, void **end); + +#define STACK_INIT(context,stack,type) \ + (((stack).start = (type)yaml_malloc(INITIAL_STACK_SIZE*sizeof(*(stack).start))) ? \ + ((stack).top = (stack).start, \ + (stack).end = (stack).start+INITIAL_STACK_SIZE, \ + 1) : \ + ((context)->error = YAML_MEMORY_ERROR, \ + 0)) + +#define STACK_DEL(context,stack) \ + (yaml_free((stack).start), \ + (stack).start = (stack).top = (stack).end = 0) + +#define STACK_EMPTY(context,stack) \ + ((stack).start == (stack).top) + +#define STACK_LIMIT(context,stack,size) \ + ((stack).top - (stack).start < (size) ? \ + 1 : \ + ((context)->error = YAML_MEMORY_ERROR, \ + 0)) + +#define PUSH(context,stack,value) \ + (((stack).top != (stack).end \ + || yaml_stack_extend((void **)&(stack).start, \ + (void **)&(stack).top, (void **)&(stack).end)) ? \ + (*((stack).top++) = value, \ + 1) : \ + ((context)->error = YAML_MEMORY_ERROR, \ + 0)) + +#define POP(context,stack) \ + (*(--(stack).top)) + +#define QUEUE_INIT(context,queue,size,type) \ + (((queue).start = (type)yaml_malloc((size)*sizeof(*(queue).start))) ? \ + ((queue).head = (queue).tail = (queue).start, \ + (queue).end = (queue).start+(size), \ + 1) : \ + ((context)->error = YAML_MEMORY_ERROR, \ + 0)) + +#define QUEUE_DEL(context,queue) \ + (yaml_free((queue).start), \ + (queue).start = (queue).head = (queue).tail = (queue).end = 0) + +#define QUEUE_EMPTY(context,queue) \ + ((queue).head == (queue).tail) + +#define ENQUEUE(context,queue,value) \ + (((queue).tail != (queue).end \ + || yaml_queue_extend((void **)&(queue).start, (void **)&(queue).head, \ + (void **)&(queue).tail, (void **)&(queue).end)) ? \ + (*((queue).tail++) = value, \ + 1) : \ + ((context)->error = YAML_MEMORY_ERROR, \ + 0)) + +#define DEQUEUE(context,queue) \ + (*((queue).head++)) + +#define QUEUE_INSERT(context,queue,index,value) \ + (((queue).tail != (queue).end \ + || yaml_queue_extend((void **)&(queue).start, (void **)&(queue).head, \ + (void **)&(queue).tail, (void **)&(queue).end)) ? \ + (memmove((queue).head+(index)+1,(queue).head+(index), \ + ((queue).tail-(queue).head-(index))*sizeof(*(queue).start)), \ + *((queue).head+(index)) = value, \ + (queue).tail++, \ + 1) : \ + ((context)->error = YAML_MEMORY_ERROR, \ + 0)) + +/* + * Token initializers. + */ + +#define TOKEN_INIT(token,token_type,token_start_mark,token_end_mark) \ + (memset(&(token), 0, sizeof(yaml_token_t)), \ + (token).type = (token_type), \ + (token).start_mark = (token_start_mark), \ + (token).end_mark = (token_end_mark)) + +#define STREAM_START_TOKEN_INIT(token,token_encoding,start_mark,end_mark) \ + (TOKEN_INIT((token),YAML_STREAM_START_TOKEN,(start_mark),(end_mark)), \ + (token).data.stream_start.encoding = (token_encoding)) + +#define STREAM_END_TOKEN_INIT(token,start_mark,end_mark) \ + (TOKEN_INIT((token),YAML_STREAM_END_TOKEN,(start_mark),(end_mark))) + +#define ALIAS_TOKEN_INIT(token,token_value,start_mark,end_mark) \ + (TOKEN_INIT((token),YAML_ALIAS_TOKEN,(start_mark),(end_mark)), \ + (token).data.alias.value = (token_value)) + +#define ANCHOR_TOKEN_INIT(token,token_value,start_mark,end_mark) \ + (TOKEN_INIT((token),YAML_ANCHOR_TOKEN,(start_mark),(end_mark)), \ + (token).data.anchor.value = (token_value)) + +#define TAG_TOKEN_INIT(token,token_handle,token_suffix,start_mark,end_mark) \ + (TOKEN_INIT((token),YAML_TAG_TOKEN,(start_mark),(end_mark)), \ + (token).data.tag.handle = (token_handle), \ + (token).data.tag.suffix = (token_suffix)) + +#define SCALAR_TOKEN_INIT(token,token_value,token_length,token_style,start_mark,end_mark) \ + (TOKEN_INIT((token),YAML_SCALAR_TOKEN,(start_mark),(end_mark)), \ + (token).data.scalar.value = (token_value), \ + (token).data.scalar.length = (token_length), \ + (token).data.scalar.style = (token_style)) + +#define VERSION_DIRECTIVE_TOKEN_INIT(token,token_major,token_minor,start_mark,end_mark) \ + (TOKEN_INIT((token),YAML_VERSION_DIRECTIVE_TOKEN,(start_mark),(end_mark)), \ + (token).data.version_directive.major = (token_major), \ + (token).data.version_directive.minor = (token_minor)) + +#define TAG_DIRECTIVE_TOKEN_INIT(token,token_handle,token_prefix,start_mark,end_mark) \ + (TOKEN_INIT((token),YAML_TAG_DIRECTIVE_TOKEN,(start_mark),(end_mark)), \ + (token).data.tag_directive.handle = (token_handle), \ + (token).data.tag_directive.prefix = (token_prefix)) + +/* + * Event initializers. + */ + +#define EVENT_INIT(event,event_type,event_start_mark,event_end_mark) \ + (memset(&(event), 0, sizeof(yaml_event_t)), \ + (event).type = (event_type), \ + (event).start_mark = (event_start_mark), \ + (event).end_mark = (event_end_mark)) + +#define STREAM_START_EVENT_INIT(event,event_encoding,start_mark,end_mark) \ + (EVENT_INIT((event),YAML_STREAM_START_EVENT,(start_mark),(end_mark)), \ + (event).data.stream_start.encoding = (event_encoding)) + +#define STREAM_END_EVENT_INIT(event,start_mark,end_mark) \ + (EVENT_INIT((event),YAML_STREAM_END_EVENT,(start_mark),(end_mark))) + +#define DOCUMENT_START_EVENT_INIT(event,event_version_directive, \ + event_tag_directives_start,event_tag_directives_end,event_implicit,start_mark,end_mark) \ + (EVENT_INIT((event),YAML_DOCUMENT_START_EVENT,(start_mark),(end_mark)), \ + (event).data.document_start.version_directive = (event_version_directive), \ + (event).data.document_start.tag_directives.start = (event_tag_directives_start), \ + (event).data.document_start.tag_directives.end = (event_tag_directives_end), \ + (event).data.document_start.implicit = (event_implicit)) + +#define DOCUMENT_END_EVENT_INIT(event,event_implicit,start_mark,end_mark) \ + (EVENT_INIT((event),YAML_DOCUMENT_END_EVENT,(start_mark),(end_mark)), \ + (event).data.document_end.implicit = (event_implicit)) + +#define ALIAS_EVENT_INIT(event,event_anchor,start_mark,end_mark) \ + (EVENT_INIT((event),YAML_ALIAS_EVENT,(start_mark),(end_mark)), \ + (event).data.alias.anchor = (event_anchor)) + +#define SCALAR_EVENT_INIT(event,event_anchor,event_tag,event_value,event_length, \ + event_plain_implicit, event_quoted_implicit,event_style,start_mark,end_mark) \ + (EVENT_INIT((event),YAML_SCALAR_EVENT,(start_mark),(end_mark)), \ + (event).data.scalar.anchor = (event_anchor), \ + (event).data.scalar.tag = (event_tag), \ + (event).data.scalar.value = (event_value), \ + (event).data.scalar.length = (event_length), \ + (event).data.scalar.plain_implicit = (event_plain_implicit), \ + (event).data.scalar.quoted_implicit = (event_quoted_implicit), \ + (event).data.scalar.style = (event_style)) + +#define SEQUENCE_START_EVENT_INIT(event,event_anchor,event_tag, \ + event_implicit,event_style,start_mark,end_mark) \ + (EVENT_INIT((event),YAML_SEQUENCE_START_EVENT,(start_mark),(end_mark)), \ + (event).data.sequence_start.anchor = (event_anchor), \ + (event).data.sequence_start.tag = (event_tag), \ + (event).data.sequence_start.implicit = (event_implicit), \ + (event).data.sequence_start.style = (event_style)) + +#define SEQUENCE_END_EVENT_INIT(event,start_mark,end_mark) \ + (EVENT_INIT((event),YAML_SEQUENCE_END_EVENT,(start_mark),(end_mark))) + +#define MAPPING_START_EVENT_INIT(event,event_anchor,event_tag, \ + event_implicit,event_style,start_mark,end_mark) \ + (EVENT_INIT((event),YAML_MAPPING_START_EVENT,(start_mark),(end_mark)), \ + (event).data.mapping_start.anchor = (event_anchor), \ + (event).data.mapping_start.tag = (event_tag), \ + (event).data.mapping_start.implicit = (event_implicit), \ + (event).data.mapping_start.style = (event_style)) + +#define MAPPING_END_EVENT_INIT(event,start_mark,end_mark) \ + (EVENT_INIT((event),YAML_MAPPING_END_EVENT,(start_mark),(end_mark))) + +/* + * Document initializer. + */ + +#define DOCUMENT_INIT(document,document_nodes_start,document_nodes_end, \ + document_version_directive,document_tag_directives_start, \ + document_tag_directives_end,document_start_implicit, \ + document_end_implicit,document_start_mark,document_end_mark) \ + (memset(&(document), 0, sizeof(yaml_document_t)), \ + (document).nodes.start = (document_nodes_start), \ + (document).nodes.end = (document_nodes_end), \ + (document).nodes.top = (document_nodes_start), \ + (document).version_directive = (document_version_directive), \ + (document).tag_directives.start = (document_tag_directives_start), \ + (document).tag_directives.end = (document_tag_directives_end), \ + (document).start_implicit = (document_start_implicit), \ + (document).end_implicit = (document_end_implicit), \ + (document).start_mark = (document_start_mark), \ + (document).end_mark = (document_end_mark)) + +/* + * Node initializers. + */ + +#define NODE_INIT(node,node_type,node_tag,node_start_mark,node_end_mark) \ + (memset(&(node), 0, sizeof(yaml_node_t)), \ + (node).type = (node_type), \ + (node).tag = (node_tag), \ + (node).start_mark = (node_start_mark), \ + (node).end_mark = (node_end_mark)) + +#define SCALAR_NODE_INIT(node,node_tag,node_value,node_length, \ + node_style,start_mark,end_mark) \ + (NODE_INIT((node),YAML_SCALAR_NODE,(node_tag),(start_mark),(end_mark)), \ + (node).data.scalar.value = (node_value), \ + (node).data.scalar.length = (node_length), \ + (node).data.scalar.style = (node_style)) + +#define SEQUENCE_NODE_INIT(node,node_tag,node_items_start,node_items_end, \ + node_style,start_mark,end_mark) \ + (NODE_INIT((node),YAML_SEQUENCE_NODE,(node_tag),(start_mark),(end_mark)), \ + (node).data.sequence.items.start = (node_items_start), \ + (node).data.sequence.items.end = (node_items_end), \ + (node).data.sequence.items.top = (node_items_start), \ + (node).data.sequence.style = (node_style)) + +#define MAPPING_NODE_INIT(node,node_tag,node_pairs_start,node_pairs_end, \ + node_style,start_mark,end_mark) \ + (NODE_INIT((node),YAML_MAPPING_NODE,(node_tag),(start_mark),(end_mark)), \ + (node).data.mapping.pairs.start = (node_pairs_start), \ + (node).data.mapping.pairs.end = (node_pairs_end), \ + (node).data.mapping.pairs.top = (node_pairs_start), \ + (node).data.mapping.style = (node_style)) + +/* Strict C compiler warning helpers */ + +#if defined(__clang__) || defined(__GNUC__) +# define HASATTRIBUTE_UNUSED +#endif +#ifdef HASATTRIBUTE_UNUSED +# define __attribute__unused__ __attribute__((__unused__)) +#else +# define __attribute__unused__ +#endif + +/* Shim arguments are arguments that must be included in your function, + * but serve no purpose inside. Silence compiler warnings. */ +#define SHIM(a) /*@unused@*/ a __attribute__unused__ + +/* UNUSED_PARAM() marks a shim argument in the body to silence compiler warnings */ +#ifdef __clang__ +# define UNUSED_PARAM(a) (void)(a); +#else +# define UNUSED_PARAM(a) /*@-noeffect*/if (0) (void)(a)/*@=noeffect*/; +#endif + +#define YAML_MALLOC_STATIC(type) (type*)yaml_malloc(sizeof(type)) +#define YAML_MALLOC(size) (yaml_char_t *)yaml_malloc(size) diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych.rb new file mode 100644 index 0000000..3830787 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych.rb @@ -0,0 +1,741 @@ +# frozen_string_literal: true +require_relative 'psych/versions' +case RUBY_ENGINE +when 'jruby' + require_relative 'psych_jars' + if JRuby::Util.respond_to?(:load_ext) + JRuby::Util.load_ext('org.jruby.ext.psych.PsychLibrary') + else + require 'java'; require 'jruby' + org.jruby.ext.psych.PsychLibrary.new.load(JRuby.runtime, false) + end +else + require 'psych.so' +end +require_relative 'psych/nodes' +require_relative 'psych/streaming' +require_relative 'psych/visitors' +require_relative 'psych/handler' +require_relative 'psych/tree_builder' +require_relative 'psych/parser' +require_relative 'psych/omap' +require_relative 'psych/set' +require_relative 'psych/coder' +require_relative 'psych/core_ext' +require_relative 'psych/stream' +require_relative 'psych/json/tree_builder' +require_relative 'psych/json/stream' +require_relative 'psych/handlers/document_stream' +require_relative 'psych/class_loader' + +### +# = Overview +# +# Psych is a YAML parser and emitter. +# Psych leverages libyaml [Home page: https://pyyaml.org/wiki/LibYAML] +# or [git repo: https://github.com/yaml/libyaml] for its YAML parsing +# and emitting capabilities. In addition to wrapping libyaml, Psych also +# knows how to serialize and de-serialize most Ruby objects to and from +# the YAML format. +# +# = I NEED TO PARSE OR EMIT YAML RIGHT NOW! +# +# # Parse some YAML +# Psych.load("--- foo") # => "foo" +# +# # Emit some YAML +# Psych.dump("foo") # => "--- foo\n...\n" +# { :a => 'b'}.to_yaml # => "---\n:a: b\n" +# +# Got more time on your hands? Keep on reading! +# +# == YAML Parsing +# +# Psych provides a range of interfaces for parsing a YAML document ranging from +# low level to high level, depending on your parsing needs. At the lowest +# level, is an event based parser. Mid level is access to the raw YAML AST, +# and at the highest level is the ability to unmarshal YAML to Ruby objects. +# +# == YAML Emitting +# +# Psych provides a range of interfaces ranging from low to high level for +# producing YAML documents. Very similar to the YAML parsing interfaces, Psych +# provides at the lowest level, an event based system, mid-level is building +# a YAML AST, and the highest level is converting a Ruby object straight to +# a YAML document. +# +# == High-level API +# +# === Parsing +# +# The high level YAML parser provided by Psych simply takes YAML as input and +# returns a Ruby data structure. For information on using the high level parser +# see Psych.load +# +# ==== Reading from a string +# +# Psych.safe_load("--- a") # => 'a' +# Psych.safe_load("---\n - a\n - b") # => ['a', 'b'] +# # From a trusted string: +# Psych.load("--- !ruby/range\nbegin: 0\nend: 42\nexcl: false\n") # => 0..42 +# +# ==== Reading from a file +# +# Psych.safe_load_file("data.yml", permitted_classes: [Date]) +# Psych.load_file("trusted_database.yml") +# +# ==== Exception handling +# +# begin +# # The second argument changes only the exception contents +# Psych.parse("--- `", "file.txt") +# rescue Psych::SyntaxError => ex +# ex.file # => 'file.txt' +# ex.message # => "(file.txt): found character that cannot start any token" +# end +# +# === Emitting +# +# The high level emitter has the easiest interface. Psych simply takes a Ruby +# data structure and converts it to a YAML document. See Psych.dump for more +# information on dumping a Ruby data structure. +# +# ==== Writing to a string +# +# # Dump an array, get back a YAML string +# Psych.dump(['a', 'b']) # => "---\n- a\n- b\n" +# +# # Dump an array to an IO object +# Psych.dump(['a', 'b'], StringIO.new) # => # +# +# # Dump an array with indentation set +# Psych.dump(['a', ['b']], :indentation => 3) # => "---\n- a\n- - b\n" +# +# # Dump an array to an IO with indentation set +# Psych.dump(['a', ['b']], StringIO.new, :indentation => 3) +# +# ==== Writing to a file +# +# Currently there is no direct API for dumping Ruby structure to file: +# +# File.open('database.yml', 'w') do |file| +# file.write(Psych.dump(['a', 'b'])) +# end +# +# == Mid-level API +# +# === Parsing +# +# Psych provides access to an AST produced from parsing a YAML document. This +# tree is built using the Psych::Parser and Psych::TreeBuilder. The AST can +# be examined and manipulated freely. Please see Psych::parse_stream, +# Psych::Nodes, and Psych::Nodes::Node for more information on dealing with +# YAML syntax trees. +# +# ==== Reading from a string +# +# # Returns Psych::Nodes::Stream +# Psych.parse_stream("---\n - a\n - b") +# +# # Returns Psych::Nodes::Document +# Psych.parse("---\n - a\n - b") +# +# ==== Reading from a file +# +# # Returns Psych::Nodes::Stream +# Psych.parse_stream(File.read('database.yml')) +# +# # Returns Psych::Nodes::Document +# Psych.parse_file('database.yml') +# +# ==== Exception handling +# +# begin +# # The second argument changes only the exception contents +# Psych.parse("--- `", "file.txt") +# rescue Psych::SyntaxError => ex +# ex.file # => 'file.txt' +# ex.message # => "(file.txt): found character that cannot start any token" +# end +# +# === Emitting +# +# At the mid level is building an AST. This AST is exactly the same as the AST +# used when parsing a YAML document. Users can build an AST by hand and the +# AST knows how to emit itself as a YAML document. See Psych::Nodes, +# Psych::Nodes::Node, and Psych::TreeBuilder for more information on building +# a YAML AST. +# +# ==== Writing to a string +# +# # We need Psych::Nodes::Stream (not Psych::Nodes::Document) +# stream = Psych.parse_stream("---\n - a\n - b") +# +# stream.to_yaml # => "---\n- a\n- b\n" +# +# ==== Writing to a file +# +# # We need Psych::Nodes::Stream (not Psych::Nodes::Document) +# stream = Psych.parse_stream(File.read('database.yml')) +# +# File.open('database.yml', 'w') do |file| +# file.write(stream.to_yaml) +# end +# +# == Low-level API +# +# === Parsing +# +# The lowest level parser should be used when the YAML input is already known, +# and the developer does not want to pay the price of building an AST or +# automatic detection and conversion to Ruby objects. See Psych::Parser for +# more information on using the event based parser. +# +# ==== Reading to Psych::Nodes::Stream structure +# +# parser = Psych::Parser.new(TreeBuilder.new) # => # +# parser = Psych.parser # it's an alias for the above +# +# parser.parse("---\n - a\n - b") # => # +# parser.handler # => # +# parser.handler.root # => # +# +# ==== Receiving an events stream +# +# recorder = Psych::Handlers::Recorder.new +# parser = Psych::Parser.new(recorder) +# +# parser.parse("---\n - a\n - b") +# recorder.events # => [list of [event, args] lists] +# # event is one of: Psych::Handler::EVENTS +# # args are the arguments passed to the event +# +# === Emitting +# +# The lowest level emitter is an event based system. Events are sent to a +# Psych::Emitter object. That object knows how to convert the events to a YAML +# document. This interface should be used when document format is known in +# advance or speed is a concern. See Psych::Emitter for more information. +# +# ==== Writing to a Ruby structure +# +# Psych.parser.parse("--- a") # => # +# +# parser.handler.first # => # +# parser.handler.first.to_ruby # => ["a"] +# +# parser.handler.root.first # => # +# parser.handler.root.first.to_ruby # => "a" +# +# # You can instantiate an Emitter manually +# Psych::Visitors::ToRuby.new.accept(parser.handler.root.first) +# # => "a" + +module Psych + # The version of libyaml Psych is using + LIBYAML_VERSION = Psych.libyaml_version.join('.').freeze + + ### + # Load +yaml+ in to a Ruby data structure. If multiple documents are + # provided, the object contained in the first document will be returned. + # +filename+ will be used in the exception message if any exception + # is raised while parsing. If +yaml+ is empty, it returns + # the specified +fallback+ return value, which defaults to +false+. + # + # Raises a Psych::SyntaxError when a YAML syntax error is detected. + # + # Example: + # + # Psych.unsafe_load("--- a") # => 'a' + # Psych.unsafe_load("---\n - a\n - b") # => ['a', 'b'] + # + # begin + # Psych.unsafe_load("--- `", filename: "file.txt") + # rescue Psych::SyntaxError => ex + # ex.file # => 'file.txt' + # ex.message # => "(file.txt): found character that cannot start any token" + # end + # + # When the optional +symbolize_names+ keyword argument is set to a + # true value, returns symbols for keys in Hash objects (default: strings). + # + # Psych.unsafe_load("---\n foo: bar") # => {"foo"=>"bar"} + # Psych.unsafe_load("---\n foo: bar", symbolize_names: true) # => {:foo=>"bar"} + # + # Raises a TypeError when `yaml` parameter is NilClass + # + # NOTE: This method *should not* be used to parse untrusted documents, such as + # YAML documents that are supplied via user input. Instead, please use the + # load method or the safe_load method. + # + def self.unsafe_load yaml, filename: nil, fallback: false, symbolize_names: false, freeze: false + result = parse(yaml, filename: filename) + return fallback unless result + result.to_ruby(symbolize_names: symbolize_names, freeze: freeze) + end + class << self; alias :load :unsafe_load; end + + ### + # Safely load the yaml string in +yaml+. By default, only the following + # classes are allowed to be deserialized: + # + # * TrueClass + # * FalseClass + # * NilClass + # * Integer + # * Float + # * String + # * Array + # * Hash + # + # Recursive data structures are not allowed by default. Arbitrary classes + # can be allowed by adding those classes to the +permitted_classes+ keyword argument. They are + # additive. For example, to allow Date deserialization: + # + # Psych.safe_load(yaml, permitted_classes: [Date]) + # + # Now the Date class can be loaded in addition to the classes listed above. + # + # Aliases can be explicitly allowed by changing the +aliases+ keyword argument. + # For example: + # + # x = [] + # x << x + # yaml = Psych.dump x + # Psych.safe_load yaml # => raises an exception + # Psych.safe_load yaml, aliases: true # => loads the aliases + # + # A Psych::DisallowedClass exception will be raised if the yaml contains a + # class that isn't in the +permitted_classes+ list. + # + # A Psych::BadAlias exception will be raised if the yaml contains aliases + # but the +aliases+ keyword argument is set to false. + # + # +filename+ will be used in the exception message if any exception is raised + # while parsing. + # + # When the optional +symbolize_names+ keyword argument is set to a + # true value, returns symbols for keys in Hash objects (default: strings). + # + # Psych.safe_load("---\n foo: bar") # => {"foo"=>"bar"} + # Psych.safe_load("---\n foo: bar", symbolize_names: true) # => {:foo=>"bar"} + # + def self.safe_load yaml, permitted_classes: [], permitted_symbols: [], aliases: false, filename: nil, fallback: nil, symbolize_names: false, freeze: false + result = parse(yaml, filename: filename) + return fallback unless result + + class_loader = ClassLoader::Restricted.new(permitted_classes.map(&:to_s), + permitted_symbols.map(&:to_s)) + scanner = ScalarScanner.new class_loader + visitor = if aliases + Visitors::ToRuby.new scanner, class_loader, symbolize_names: symbolize_names, freeze: freeze + else + Visitors::NoAliasRuby.new scanner, class_loader, symbolize_names: symbolize_names, freeze: freeze + end + result = visitor.accept result + result + end + + ### + # Load +yaml+ in to a Ruby data structure. If multiple documents are + # provided, the object contained in the first document will be returned. + # +filename+ will be used in the exception message if any exception + # is raised while parsing. If +yaml+ is empty, it returns + # the specified +fallback+ return value, which defaults to +false+. + # + # Raises a Psych::SyntaxError when a YAML syntax error is detected. + # + # Example: + # + # Psych.load("--- a") # => 'a' + # Psych.load("---\n - a\n - b") # => ['a', 'b'] + # + # begin + # Psych.load("--- `", filename: "file.txt") + # rescue Psych::SyntaxError => ex + # ex.file # => 'file.txt' + # ex.message # => "(file.txt): found character that cannot start any token" + # end + # + # When the optional +symbolize_names+ keyword argument is set to a + # true value, returns symbols for keys in Hash objects (default: strings). + # + # Psych.load("---\n foo: bar") # => {"foo"=>"bar"} + # Psych.load("---\n foo: bar", symbolize_names: true) # => {:foo=>"bar"} + # + # Raises a TypeError when `yaml` parameter is NilClass. This method is + # similar to `safe_load` except that `Symbol` objects are allowed by default. + # + def self.load yaml, permitted_classes: [Symbol], permitted_symbols: [], aliases: false, filename: nil, fallback: nil, symbolize_names: false, freeze: false + safe_load yaml, permitted_classes: permitted_classes, + permitted_symbols: permitted_symbols, + aliases: aliases, + filename: filename, + fallback: fallback, + symbolize_names: symbolize_names, + freeze: freeze + end + + ### + # Parse a YAML string in +yaml+. Returns the Psych::Nodes::Document. + # +filename+ is used in the exception message if a Psych::SyntaxError is + # raised. + # + # Raises a Psych::SyntaxError when a YAML syntax error is detected. + # + # Example: + # + # Psych.parse("---\n - a\n - b") # => # + # + # begin + # Psych.parse("--- `", filename: "file.txt") + # rescue Psych::SyntaxError => ex + # ex.file # => 'file.txt' + # ex.message # => "(file.txt): found character that cannot start any token" + # end + # + # See Psych::Nodes for more information about YAML AST. + def self.parse yaml, filename: nil + parse_stream(yaml, filename: filename) do |node| + return node + end + + false + end + + ### + # Parse a file at +filename+. Returns the Psych::Nodes::Document. + # + # Raises a Psych::SyntaxError when a YAML syntax error is detected. + def self.parse_file filename, fallback: false + result = File.open filename, 'r:bom|utf-8' do |f| + parse f, filename: filename + end + result || fallback + end + + ### + # Returns a default parser + def self.parser + Psych::Parser.new(TreeBuilder.new) + end + + ### + # Parse a YAML string in +yaml+. Returns the Psych::Nodes::Stream. + # This method can handle multiple YAML documents contained in +yaml+. + # +filename+ is used in the exception message if a Psych::SyntaxError is + # raised. + # + # If a block is given, a Psych::Nodes::Document node will be yielded to the + # block as it's being parsed. + # + # Raises a Psych::SyntaxError when a YAML syntax error is detected. + # + # Example: + # + # Psych.parse_stream("---\n - a\n - b") # => # + # + # Psych.parse_stream("--- a\n--- b") do |node| + # node # => # + # end + # + # begin + # Psych.parse_stream("--- `", filename: "file.txt") + # rescue Psych::SyntaxError => ex + # ex.file # => 'file.txt' + # ex.message # => "(file.txt): found character that cannot start any token" + # end + # + # Raises a TypeError when NilClass is passed. + # + # See Psych::Nodes for more information about YAML AST. + def self.parse_stream yaml, filename: nil, &block + if block_given? + parser = Psych::Parser.new(Handlers::DocumentStream.new(&block)) + parser.parse yaml, filename + else + parser = self.parser + parser.parse yaml, filename + parser.handler.root + end + end + + ### + # call-seq: + # Psych.dump(o) -> string of yaml + # Psych.dump(o, options) -> string of yaml + # Psych.dump(o, io) -> io object passed in + # Psych.dump(o, io, options) -> io object passed in + # + # Dump Ruby object +o+ to a YAML string. Optional +options+ may be passed in + # to control the output format. If an IO object is passed in, the YAML will + # be dumped to that IO object. + # + # Currently supported options are: + # + # [:indentation] Number of space characters used to indent. + # Acceptable value should be in 0..9 range, + # otherwise option is ignored. + # + # Default: 2. + # [:line_width] Max character to wrap line at. + # + # Default: 0 (meaning "wrap at 81"). + # [:canonical] Write "canonical" YAML form (very verbose, yet + # strictly formal). + # + # Default: false. + # [:header] Write %YAML [version] at the beginning of document. + # + # Default: false. + # + # Example: + # + # # Dump an array, get back a YAML string + # Psych.dump(['a', 'b']) # => "---\n- a\n- b\n" + # + # # Dump an array to an IO object + # Psych.dump(['a', 'b'], StringIO.new) # => # + # + # # Dump an array with indentation set + # Psych.dump(['a', ['b']], indentation: 3) # => "---\n- a\n- - b\n" + # + # # Dump an array to an IO with indentation set + # Psych.dump(['a', ['b']], StringIO.new, indentation: 3) + def self.dump o, io = nil, options = {} + if Hash === io + options = io + io = nil + end + + visitor = Psych::Visitors::YAMLTree.create options + visitor << o + visitor.tree.yaml io, options + end + + ### + # call-seq: + # Psych.safe_dump(o) -> string of yaml + # Psych.safe_dump(o, options) -> string of yaml + # Psych.safe_dump(o, io) -> io object passed in + # Psych.safe_dump(o, io, options) -> io object passed in + # + # Safely dump Ruby object +o+ to a YAML string. Optional +options+ may be passed in + # to control the output format. If an IO object is passed in, the YAML will + # be dumped to that IO object. By default, only the following + # classes are allowed to be serialized: + # + # * TrueClass + # * FalseClass + # * NilClass + # * Integer + # * Float + # * String + # * Array + # * Hash + # + # Arbitrary classes can be allowed by adding those classes to the +permitted_classes+ + # keyword argument. They are additive. For example, to allow Date serialization: + # + # Psych.safe_dump(yaml, permitted_classes: [Date]) + # + # Now the Date class can be dumped in addition to the classes listed above. + # + # A Psych::DisallowedClass exception will be raised if the object contains a + # class that isn't in the +permitted_classes+ list. + # + # Currently supported options are: + # + # [:indentation] Number of space characters used to indent. + # Acceptable value should be in 0..9 range, + # otherwise option is ignored. + # + # Default: 2. + # [:line_width] Max character to wrap line at. + # + # Default: 0 (meaning "wrap at 81"). + # [:canonical] Write "canonical" YAML form (very verbose, yet + # strictly formal). + # + # Default: false. + # [:header] Write %YAML [version] at the beginning of document. + # + # Default: false. + # + # Example: + # + # # Dump an array, get back a YAML string + # Psych.safe_dump(['a', 'b']) # => "---\n- a\n- b\n" + # + # # Dump an array to an IO object + # Psych.safe_dump(['a', 'b'], StringIO.new) # => # + # + # # Dump an array with indentation set + # Psych.safe_dump(['a', ['b']], indentation: 3) # => "---\n- a\n- - b\n" + # + # # Dump an array to an IO with indentation set + # Psych.safe_dump(['a', ['b']], StringIO.new, indentation: 3) + def self.safe_dump o, io = nil, options = {} + if Hash === io + options = io + io = nil + end + + visitor = Psych::Visitors::RestrictedYAMLTree.create options + visitor << o + visitor.tree.yaml io, options + end + + ### + # Dump a list of objects as separate documents to a document stream. + # + # Example: + # + # Psych.dump_stream("foo\n ", {}) # => "--- ! \"foo\\n \"\n--- {}\n" + def self.dump_stream *objects + visitor = Psych::Visitors::YAMLTree.create({}) + objects.each do |o| + visitor << o + end + visitor.tree.yaml + end + + ### + # Dump Ruby +object+ to a JSON string. + def self.to_json object + visitor = Psych::Visitors::JSONTree.create + visitor << object + visitor.tree.yaml + end + + ### + # Load multiple documents given in +yaml+. Returns the parsed documents + # as a list. If a block is given, each document will be converted to Ruby + # and passed to the block during parsing + # + # Example: + # + # Psych.load_stream("--- foo\n...\n--- bar\n...") # => ['foo', 'bar'] + # + # list = [] + # Psych.load_stream("--- foo\n...\n--- bar\n...") do |ruby| + # list << ruby + # end + # list # => ['foo', 'bar'] + # + def self.load_stream yaml, filename: nil, fallback: [], **kwargs + result = if block_given? + parse_stream(yaml, filename: filename) do |node| + yield node.to_ruby(**kwargs) + end + else + parse_stream(yaml, filename: filename).children.map { |node| node.to_ruby(**kwargs) } + end + + return fallback if result.is_a?(Array) && result.empty? + result + end + + ### + # Load the document contained in +filename+. Returns the yaml contained in + # +filename+ as a Ruby object, or if the file is empty, it returns + # the specified +fallback+ return value, which defaults to +false+. + # + # NOTE: This method *should not* be used to parse untrusted documents, such as + # YAML documents that are supplied via user input. Instead, please use the + # safe_load_file method. + def self.unsafe_load_file filename, **kwargs + File.open(filename, 'r:bom|utf-8') { |f| + self.unsafe_load f, filename: filename, **kwargs + } + end + + ### + # Safely loads the document contained in +filename+. Returns the yaml contained in + # +filename+ as a Ruby object, or if the file is empty, it returns + # the specified +fallback+ return value, which defaults to +false+. + # See safe_load for options. + def self.safe_load_file filename, **kwargs + File.open(filename, 'r:bom|utf-8') { |f| + self.safe_load f, filename: filename, **kwargs + } + end + + ### + # Loads the document contained in +filename+. Returns the yaml contained in + # +filename+ as a Ruby object, or if the file is empty, it returns + # the specified +fallback+ return value, which defaults to +false+. + # See load for options. + def self.load_file filename, **kwargs + File.open(filename, 'r:bom|utf-8') { |f| + self.load f, filename: filename, **kwargs + } + end + + # :stopdoc: + def self.add_domain_type domain, type_tag, &block + key = ['tag', domain, type_tag].join ':' + domain_types[key] = [key, block] + domain_types["tag:#{type_tag}"] = [key, block] + end + + def self.add_builtin_type type_tag, &block + domain = 'yaml.org,2002' + key = ['tag', domain, type_tag].join ':' + domain_types[key] = [key, block] + end + + def self.remove_type type_tag + domain_types.delete type_tag + end + + def self.add_tag tag, klass + load_tags[tag] = klass.name + dump_tags[klass] = tag + end + + # Workaround for emulating `warn '...', uplevel: 1` in Ruby 2.4 or lower. + def self.warn_with_uplevel(message, uplevel: 1) + at = parse_caller(caller[uplevel]).join(':') + warn "#{at}: #{message}" + end + + def self.parse_caller(at) + if /^(.+?):(\d+)(?::in `.*')?/ =~ at + file = $1 + line = $2.to_i + [file, line] + end + end + private_class_method :warn_with_uplevel, :parse_caller + + class << self + if defined?(Ractor) + require 'forwardable' + extend Forwardable + + class Config + attr_accessor :load_tags, :dump_tags, :domain_types + def initialize + @load_tags = {} + @dump_tags = {} + @domain_types = {} + end + end + + def config + Ractor.current[:PsychConfig] ||= Config.new + end + + def_delegators :config, :load_tags, :dump_tags, :domain_types, :load_tags=, :dump_tags=, :domain_types= + else + attr_accessor :load_tags + attr_accessor :dump_tags + attr_accessor :domain_types + end + end + self.load_tags = {} + self.dump_tags = {} + self.domain_types = {} + # :startdoc: +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/class_loader.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/class_loader.rb new file mode 100644 index 0000000..c2e4ea4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/class_loader.rb @@ -0,0 +1,104 @@ +# frozen_string_literal: true +require_relative 'omap' +require_relative 'set' + +module Psych + class ClassLoader # :nodoc: + BIG_DECIMAL = 'BigDecimal' + COMPLEX = 'Complex' + DATE = 'Date' + DATE_TIME = 'DateTime' + EXCEPTION = 'Exception' + OBJECT = 'Object' + PSYCH_OMAP = 'Psych::Omap' + PSYCH_SET = 'Psych::Set' + RANGE = 'Range' + RATIONAL = 'Rational' + REGEXP = 'Regexp' + STRUCT = 'Struct' + SYMBOL = 'Symbol' + + def initialize + @cache = CACHE.dup + end + + def load klassname + return nil if !klassname || klassname.empty? + + find klassname + end + + def symbolize sym + symbol + sym.to_sym + end + + constants.each do |const| + konst = const_get const + class_eval <<~RUBY + def #{const.to_s.downcase} + load #{konst.inspect} + end + RUBY + end + + private + + def find klassname + @cache[klassname] ||= resolve(klassname) + end + + def resolve klassname + name = klassname + retried = false + + begin + path2class(name) + rescue ArgumentError, NameError => ex + unless retried + name = "Struct::#{name}" + retried = ex + retry + end + raise retried + end + end + + CACHE = Hash[constants.map { |const| + val = const_get const + begin + [val, ::Object.const_get(val)] + rescue + nil + end + }.compact].freeze + + class Restricted < ClassLoader + def initialize classes, symbols + @classes = classes + @symbols = symbols + super() + end + + def symbolize sym + return super if @symbols.empty? + + if @symbols.include? sym + super + else + raise DisallowedClass.new('load', 'Symbol') + end + end + + private + + def find klassname + if @classes.include? klassname + super + else + raise DisallowedClass.new('load', klassname) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/coder.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/coder.rb new file mode 100644 index 0000000..96a9c3f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/coder.rb @@ -0,0 +1,95 @@ +# frozen_string_literal: true +module Psych + ### + # If an object defines +encode_with+, then an instance of Psych::Coder will + # be passed to the method when the object is being serialized. The Coder + # automatically assumes a Psych::Nodes::Mapping is being emitted. Other + # objects like Sequence and Scalar may be emitted if +seq=+ or +scalar=+ are + # called, respectively. + class Coder + attr_accessor :tag, :style, :implicit, :object + attr_reader :type, :seq + + def initialize tag + @map = {} + @seq = [] + @implicit = false + @type = :map + @tag = tag + @style = Psych::Nodes::Mapping::BLOCK + @scalar = nil + @object = nil + end + + def scalar *args + if args.length > 0 + warn "#{caller[0]}: Coder#scalar(a,b,c) is deprecated" if $VERBOSE + @tag, @scalar, _ = args + @type = :scalar + end + @scalar + end + + # Emit a map. The coder will be yielded to the block. + def map tag = @tag, style = @style + @tag = tag + @style = style + yield self if block_given? + @map + end + + # Emit a scalar with +value+ and +tag+ + def represent_scalar tag, value + self.tag = tag + self.scalar = value + end + + # Emit a sequence with +list+ and +tag+ + def represent_seq tag, list + @tag = tag + self.seq = list + end + + # Emit a sequence with +map+ and +tag+ + def represent_map tag, map + @tag = tag + self.map = map + end + + # Emit an arbitrary object +obj+ and +tag+ + def represent_object tag, obj + @tag = tag + @type = :object + @object = obj + end + + # Emit a scalar with +value+ + def scalar= value + @type = :scalar + @scalar = value + end + + # Emit a map with +value+ + def map= map + @type = :map + @map = map + end + + def []= k, v + @type = :map + @map[k] = v + end + alias :add :[]= + + def [] k + @type = :map + @map[k] + end + + # Emit a sequence of +list+ + def seq= list + @type = :seq + @seq = list + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/core_ext.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/core_ext.rb new file mode 100644 index 0000000..0721a13 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/core_ext.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true +class Object + def self.yaml_tag url + Psych.add_tag(url, self) + end + + ### + # call-seq: to_yaml(options = {}) + # + # Convert an object to YAML. See Psych.dump for more information on the + # available +options+. + def to_yaml options = {} + Psych.dump self, options + end +end + +if defined?(::IRB) + require_relative 'y' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/exception.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/exception.rb new file mode 100644 index 0000000..f473b95 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/exception.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true +module Psych + class Exception < RuntimeError + end + + class BadAlias < Exception + end + + class DisallowedClass < Exception + def initialize action, klass_name + super "Tried to #{action} unspecified class: #{klass_name}" + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/handler.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/handler.rb new file mode 100644 index 0000000..ad7249f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/handler.rb @@ -0,0 +1,255 @@ +# frozen_string_literal: true +module Psych + ### + # Psych::Handler is an abstract base class that defines the events used + # when dealing with Psych::Parser. Clients who want to use Psych::Parser + # should implement a class that inherits from Psych::Handler and define + # events that they can handle. + # + # Psych::Handler defines all events that Psych::Parser can possibly send to + # event handlers. + # + # See Psych::Parser for more details + class Handler + ### + # Configuration options for dumping YAML. + class DumperOptions + attr_accessor :line_width, :indentation, :canonical + + def initialize + @line_width = 0 + @indentation = 2 + @canonical = false + end + end + + # Default dumping options + OPTIONS = DumperOptions.new + + # Events that a Handler should respond to. + EVENTS = [ :alias, + :empty, + :end_document, + :end_mapping, + :end_sequence, + :end_stream, + :scalar, + :start_document, + :start_mapping, + :start_sequence, + :start_stream ] + + ### + # Called with +encoding+ when the YAML stream starts. This method is + # called once per stream. A stream may contain multiple documents. + # + # See the constants in Psych::Parser for the possible values of +encoding+. + def start_stream encoding + end + + ### + # Called when the document starts with the declared +version+, + # +tag_directives+, if the document is +implicit+. + # + # +version+ will be an array of integers indicating the YAML version being + # dealt with, +tag_directives+ is a list of tuples indicating the prefix + # and suffix of each tag, and +implicit+ is a boolean indicating whether + # the document is started implicitly. + # + # === Example + # + # Given the following YAML: + # + # %YAML 1.1 + # %TAG ! tag:tenderlovemaking.com,2009: + # --- !squee + # + # The parameters for start_document must be this: + # + # version # => [1, 1] + # tag_directives # => [["!", "tag:tenderlovemaking.com,2009:"]] + # implicit # => false + def start_document version, tag_directives, implicit + end + + ### + # Called with the document ends. +implicit+ is a boolean value indicating + # whether or not the document has an implicit ending. + # + # === Example + # + # Given the following YAML: + # + # --- + # hello world + # + # +implicit+ will be true. Given this YAML: + # + # --- + # hello world + # ... + # + # +implicit+ will be false. + def end_document implicit + end + + ### + # Called when an alias is found to +anchor+. +anchor+ will be the name + # of the anchor found. + # + # === Example + # + # Here we have an example of an array that references itself in YAML: + # + # --- &ponies + # - first element + # - *ponies + # + # &ponies is the anchor, *ponies is the alias. In this case, alias is + # called with "ponies". + def alias anchor + end + + ### + # Called when a scalar +value+ is found. The scalar may have an + # +anchor+, a +tag+, be implicitly +plain+ or implicitly +quoted+ + # + # +value+ is the string value of the scalar + # +anchor+ is an associated anchor or nil + # +tag+ is an associated tag or nil + # +plain+ is a boolean value + # +quoted+ is a boolean value + # +style+ is an integer indicating the string style + # + # See the constants in Psych::Nodes::Scalar for the possible values of + # +style+ + # + # === Example + # + # Here is a YAML document that exercises most of the possible ways this + # method can be called: + # + # --- + # - !str "foo" + # - &anchor fun + # - many + # lines + # - | + # many + # newlines + # + # The above YAML document contains a list with four strings. Here are + # the parameters sent to this method in the same order: + # + # # value anchor tag plain quoted style + # ["foo", nil, "!str", false, false, 3 ] + # ["fun", "anchor", nil, true, false, 1 ] + # ["many lines", nil, nil, true, false, 1 ] + # ["many\nnewlines\n", nil, nil, false, true, 4 ] + # + def scalar value, anchor, tag, plain, quoted, style + end + + ### + # Called when a sequence is started. + # + # +anchor+ is the anchor associated with the sequence or nil. + # +tag+ is the tag associated with the sequence or nil. + # +implicit+ a boolean indicating whether or not the sequence was implicitly + # started. + # +style+ is an integer indicating the list style. + # + # See the constants in Psych::Nodes::Sequence for the possible values of + # +style+. + # + # === Example + # + # Here is a YAML document that exercises most of the possible ways this + # method can be called: + # + # --- + # - !!seq [ + # a + # ] + # - &pewpew + # - b + # + # The above YAML document consists of three lists, an outer list that + # contains two inner lists. Here is a matrix of the parameters sent + # to represent these lists: + # + # # anchor tag implicit style + # [nil, nil, true, 1 ] + # [nil, "tag:yaml.org,2002:seq", false, 2 ] + # ["pewpew", nil, true, 1 ] + + def start_sequence anchor, tag, implicit, style + end + + ### + # Called when a sequence ends. + def end_sequence + end + + ### + # Called when a map starts. + # + # +anchor+ is the anchor associated with the map or +nil+. + # +tag+ is the tag associated with the map or +nil+. + # +implicit+ is a boolean indicating whether or not the map was implicitly + # started. + # +style+ is an integer indicating the mapping style. + # + # See the constants in Psych::Nodes::Mapping for the possible values of + # +style+. + # + # === Example + # + # Here is a YAML document that exercises most of the possible ways this + # method can be called: + # + # --- + # k: !!map { hello: world } + # v: &pewpew + # hello: world + # + # The above YAML document consists of three maps, an outer map that contains + # two inner maps. Below is a matrix of the parameters sent in order to + # represent these three maps: + # + # # anchor tag implicit style + # [nil, nil, true, 1 ] + # [nil, "tag:yaml.org,2002:map", false, 2 ] + # ["pewpew", nil, true, 1 ] + + def start_mapping anchor, tag, implicit, style + end + + ### + # Called when a map ends + def end_mapping + end + + ### + # Called when an empty event happens. (Which, as far as I can tell, is + # never). + def empty + end + + ### + # Called when the YAML stream ends + def end_stream + end + + ### + # Called before each event with line/column information. + def event_location(start_line, start_column, end_line, end_column) + end + + ### + # Is this handler a streaming handler? + def streaming? + false + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/handlers/document_stream.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/handlers/document_stream.rb new file mode 100644 index 0000000..b77115d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/handlers/document_stream.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true +require_relative '../tree_builder' + +module Psych + module Handlers + class DocumentStream < Psych::TreeBuilder # :nodoc: + def initialize &block + super + @block = block + end + + def start_document version, tag_directives, implicit + n = Nodes::Document.new version, tag_directives, implicit + push n + end + + def end_document implicit_end = !streaming? + @last.implicit_end = implicit_end + @block.call pop + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/handlers/recorder.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/handlers/recorder.rb new file mode 100644 index 0000000..c98724c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/handlers/recorder.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true +require_relative '../handler' + +module Psych + module Handlers + ### + # This handler will capture an event and record the event. Recorder events + # are available vial Psych::Handlers::Recorder#events. + # + # For example: + # + # recorder = Psych::Handlers::Recorder.new + # parser = Psych::Parser.new recorder + # parser.parse '--- foo' + # + # recorder.events # => [list of events] + # + # # Replay the events + # + # emitter = Psych::Emitter.new $stdout + # recorder.events.each do |m, args| + # emitter.send m, *args + # end + + class Recorder < Psych::Handler + attr_reader :events + + def initialize + @events = [] + super + end + + EVENTS.each do |event| + define_method event do |*args| + @events << [event, args] + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/ruby_events.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/ruby_events.rb new file mode 100644 index 0000000..17b7ddc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/ruby_events.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true +module Psych + module JSON + module RubyEvents # :nodoc: + def visit_Time o + formatted = format_time o + @emitter.scalar formatted, nil, nil, false, true, Nodes::Scalar::DOUBLE_QUOTED + end + + def visit_DateTime o + visit_Time o.to_time + end + + def visit_String o + @emitter.scalar o.to_s, nil, nil, false, true, Nodes::Scalar::DOUBLE_QUOTED + end + alias :visit_Symbol :visit_String + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/stream.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/stream.rb new file mode 100644 index 0000000..24dd4b9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/stream.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true +require_relative 'ruby_events' +require_relative 'yaml_events' + +module Psych + module JSON + class Stream < Psych::Visitors::JSONTree + include Psych::JSON::RubyEvents + include Psych::Streaming + extend Psych::Streaming::ClassMethods + + class Emitter < Psych::Stream::Emitter # :nodoc: + include Psych::JSON::YAMLEvents + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/tree_builder.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/tree_builder.rb new file mode 100644 index 0000000..9a45f6b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/tree_builder.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true +require_relative 'yaml_events' + +module Psych + module JSON + ### + # Psych::JSON::TreeBuilder is an event based AST builder. Events are sent + # to an instance of Psych::JSON::TreeBuilder and a JSON AST is constructed. + class TreeBuilder < Psych::TreeBuilder + include Psych::JSON::YAMLEvents + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/yaml_events.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/yaml_events.rb new file mode 100644 index 0000000..eb973f5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/json/yaml_events.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true +module Psych + module JSON + module YAMLEvents # :nodoc: + def start_document version, tag_directives, implicit + super(version, tag_directives, !streaming?) + end + + def end_document implicit_end = !streaming? + super(implicit_end) + end + + def start_mapping anchor, tag, implicit, style + super(anchor, nil, true, Nodes::Mapping::FLOW) + end + + def start_sequence anchor, tag, implicit, style + super(anchor, nil, true, Nodes::Sequence::FLOW) + end + + def scalar value, anchor, tag, plain, quoted, style + if "tag:yaml.org,2002:null" == tag + super('null', nil, nil, true, false, Nodes::Scalar::PLAIN) + else + super + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes.rb new file mode 100644 index 0000000..2fa52e0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true +require_relative 'nodes/node' +require_relative 'nodes/stream' +require_relative 'nodes/document' +require_relative 'nodes/sequence' +require_relative 'nodes/scalar' +require_relative 'nodes/mapping' +require_relative 'nodes/alias' + +module Psych + ### + # = Overview + # + # When using Psych.load to deserialize a YAML document, the document is + # translated to an intermediary AST. That intermediary AST is then + # translated in to a Ruby object graph. + # + # In the opposite direction, when using Psych.dump, the Ruby object graph is + # translated to an intermediary AST which is then converted to a YAML + # document. + # + # Psych::Nodes contains all of the classes that make up the nodes of a YAML + # AST. You can manually build an AST and use one of the visitors (see + # Psych::Visitors) to convert that AST to either a YAML document or to a + # Ruby object graph. + # + # Here is an example of building an AST that represents a list with one + # scalar: + # + # # Create our nodes + # stream = Psych::Nodes::Stream.new + # doc = Psych::Nodes::Document.new + # seq = Psych::Nodes::Sequence.new + # scalar = Psych::Nodes::Scalar.new('foo') + # + # # Build up our tree + # stream.children << doc + # doc.children << seq + # seq.children << scalar + # + # The stream is the root of the tree. We can then convert the tree to YAML: + # + # stream.to_yaml => "---\n- foo\n" + # + # Or convert it to Ruby: + # + # stream.to_ruby => [["foo"]] + # + # == YAML AST Requirements + # + # A valid YAML AST *must* have one Psych::Nodes::Stream at the root. A + # Psych::Nodes::Stream node must have 1 or more Psych::Nodes::Document nodes + # as children. + # + # Psych::Nodes::Document nodes must have one and *only* one child. That child + # may be one of: + # + # * Psych::Nodes::Sequence + # * Psych::Nodes::Mapping + # * Psych::Nodes::Scalar + # + # Psych::Nodes::Sequence and Psych::Nodes::Mapping nodes may have many + # children, but Psych::Nodes::Mapping nodes should have an even number of + # children. + # + # All of these are valid children for Psych::Nodes::Sequence and + # Psych::Nodes::Mapping nodes: + # + # * Psych::Nodes::Sequence + # * Psych::Nodes::Mapping + # * Psych::Nodes::Scalar + # * Psych::Nodes::Alias + # + # Psych::Nodes::Scalar and Psych::Nodes::Alias are both terminal nodes and + # should not have any children. + module Nodes + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/alias.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/alias.rb new file mode 100644 index 0000000..6da655f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/alias.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true +module Psych + module Nodes + ### + # This class represents a {YAML Alias}[http://yaml.org/spec/1.1/#alias]. + # It points to an +anchor+. + # + # A Psych::Nodes::Alias is a terminal node and may have no children. + class Alias < Psych::Nodes::Node + # The anchor this alias links to + attr_accessor :anchor + + # Create a new Alias that points to an +anchor+ + def initialize anchor + @anchor = anchor + end + + def alias?; true; end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/document.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/document.rb new file mode 100644 index 0000000..f57410d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/document.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true +module Psych + module Nodes + ### + # This represents a YAML Document. This node must be a child of + # Psych::Nodes::Stream. A Psych::Nodes::Document must have one child, + # and that child may be one of the following: + # + # * Psych::Nodes::Sequence + # * Psych::Nodes::Mapping + # * Psych::Nodes::Scalar + class Document < Psych::Nodes::Node + # The version of the YAML document + attr_accessor :version + + # A list of tag directives for this document + attr_accessor :tag_directives + + # Was this document implicitly created? + attr_accessor :implicit + + # Is the end of the document implicit? + attr_accessor :implicit_end + + ### + # Create a new Psych::Nodes::Document object. + # + # +version+ is a list indicating the YAML version. + # +tags_directives+ is a list of tag directive declarations + # +implicit+ is a flag indicating whether the document will be implicitly + # started. + # + # == Example: + # This creates a YAML document object that represents a YAML 1.1 document + # with one tag directive, and has an implicit start: + # + # Psych::Nodes::Document.new( + # [1,1], + # [["!", "tag:tenderlovemaking.com,2009:"]], + # true + # ) + # + # == See Also + # See also Psych::Handler#start_document + def initialize version = [], tag_directives = [], implicit = false + super() + @version = version + @tag_directives = tag_directives + @implicit = implicit + @implicit_end = true + end + + ### + # Returns the root node. A Document may only have one root node: + # http://yaml.org/spec/1.1/#id898031 + def root + children.first + end + + def document?; true; end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/mapping.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/mapping.rb new file mode 100644 index 0000000..d49678c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/mapping.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true +module Psych + module Nodes + ### + # This class represents a {YAML Mapping}[http://yaml.org/spec/1.1/#mapping]. + # + # A Psych::Nodes::Mapping node may have 0 or more children, but must have + # an even number of children. Here are the valid children a + # Psych::Nodes::Mapping node may have: + # + # * Psych::Nodes::Sequence + # * Psych::Nodes::Mapping + # * Psych::Nodes::Scalar + # * Psych::Nodes::Alias + class Mapping < Psych::Nodes::Node + # Any Map Style + ANY = 0 + + # Block Map Style + BLOCK = 1 + + # Flow Map Style + FLOW = 2 + + # The optional anchor for this mapping + attr_accessor :anchor + + # The optional tag for this mapping + attr_accessor :tag + + # Is this an implicit mapping? + attr_accessor :implicit + + # The style of this mapping + attr_accessor :style + + ### + # Create a new Psych::Nodes::Mapping object. + # + # +anchor+ is the anchor associated with the map or +nil+. + # +tag+ is the tag associated with the map or +nil+. + # +implicit+ is a boolean indicating whether or not the map was implicitly + # started. + # +style+ is an integer indicating the mapping style. + # + # == See Also + # See also Psych::Handler#start_mapping + def initialize anchor = nil, tag = nil, implicit = true, style = BLOCK + super() + @anchor = anchor + @tag = tag + @implicit = implicit + @style = style + end + + def mapping?; true; end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/node.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/node.rb new file mode 100644 index 0000000..1f84162 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/node.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true +require 'stringio' +require_relative '../class_loader' +require_relative '../scalar_scanner' + +module Psych + module Nodes + ### + # The base class for any Node in a YAML parse tree. This class should + # never be instantiated. + class Node + include Enumerable + + # The children of this node + attr_reader :children + + # An associated tag + attr_reader :tag + + # The line number where this node start + attr_accessor :start_line + + # The column number where this node start + attr_accessor :start_column + + # The line number where this node ends + attr_accessor :end_line + + # The column number where this node ends + attr_accessor :end_column + + # Create a new Psych::Nodes::Node + def initialize + @children = [] + end + + ### + # Iterate over each node in the tree. Yields each node to +block+ depth + # first. + def each &block + return enum_for :each unless block_given? + Visitors::DepthFirst.new(block).accept self + end + + ### + # Convert this node to Ruby. + # + # See also Psych::Visitors::ToRuby + def to_ruby(symbolize_names: false, freeze: false) + Visitors::ToRuby.create(symbolize_names: symbolize_names, freeze: freeze).accept(self) + end + alias :transform :to_ruby + + ### + # Convert this node to YAML. + # + # See also Psych::Visitors::Emitter + def yaml io = nil, options = {} + real_io = io || StringIO.new(''.encode('utf-8')) + + Visitors::Emitter.new(real_io, options).accept self + return real_io.string unless io + io + end + alias :to_yaml :yaml + + def alias?; false; end + def document?; false; end + def mapping?; false; end + def scalar?; false; end + def sequence?; false; end + def stream?; false; end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/scalar.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/scalar.rb new file mode 100644 index 0000000..5550b61 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/scalar.rb @@ -0,0 +1,70 @@ +# frozen_string_literal: true +module Psych + module Nodes + ### + # This class represents a {YAML Scalar}[http://yaml.org/spec/1.1/#id858081]. + # + # This node type is a terminal node and should not have any children. + class Scalar < Psych::Nodes::Node + # Any style scalar, the emitter chooses + ANY = 0 + + # Plain scalar style + PLAIN = 1 + + # Single quoted style + SINGLE_QUOTED = 2 + + # Double quoted style + DOUBLE_QUOTED = 3 + + # Literal style + LITERAL = 4 + + # Folded style + FOLDED = 5 + + # The scalar value + attr_accessor :value + + # The anchor value (if there is one) + attr_accessor :anchor + + # The tag value (if there is one) + attr_accessor :tag + + # Is this a plain scalar? + attr_accessor :plain + + # Is this scalar quoted? + attr_accessor :quoted + + # The style of this scalar + attr_accessor :style + + ### + # Create a new Psych::Nodes::Scalar object. + # + # +value+ is the string value of the scalar + # +anchor+ is an associated anchor or nil + # +tag+ is an associated tag or nil + # +plain+ is a boolean value + # +quoted+ is a boolean value + # +style+ is an integer indicating the string style + # + # == See Also + # + # See also Psych::Handler#scalar + def initialize value, anchor = nil, tag = nil, plain = true, quoted = false, style = ANY + @value = value + @anchor = anchor + @tag = tag + @plain = plain + @quoted = quoted + @style = style + end + + def scalar?; true; end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/sequence.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/sequence.rb new file mode 100644 index 0000000..740f193 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/sequence.rb @@ -0,0 +1,84 @@ +# frozen_string_literal: true +module Psych + module Nodes + ### + # This class represents a + # {YAML sequence}[http://yaml.org/spec/1.1/#sequence/syntax]. + # + # A YAML sequence is basically a list, and looks like this: + # + # %YAML 1.1 + # --- + # - I am + # - a Sequence + # + # A YAML sequence may have an anchor like this: + # + # %YAML 1.1 + # --- + # &A [ + # "This sequence", + # "has an anchor" + # ] + # + # A YAML sequence may also have a tag like this: + # + # %YAML 1.1 + # --- + # !!seq [ + # "This sequence", + # "has a tag" + # ] + # + # This class represents a sequence in a YAML document. A + # Psych::Nodes::Sequence node may have 0 or more children. Valid children + # for this node are: + # + # * Psych::Nodes::Sequence + # * Psych::Nodes::Mapping + # * Psych::Nodes::Scalar + # * Psych::Nodes::Alias + class Sequence < Psych::Nodes::Node + # Any Styles, emitter chooses + ANY = 0 + + # Block style sequence + BLOCK = 1 + + # Flow style sequence + FLOW = 2 + + # The anchor for this sequence (if any) + attr_accessor :anchor + + # The tag name for this sequence (if any) + attr_accessor :tag + + # Is this sequence started implicitly? + attr_accessor :implicit + + # The sequence style used + attr_accessor :style + + ### + # Create a new object representing a YAML sequence. + # + # +anchor+ is the anchor associated with the sequence or nil. + # +tag+ is the tag associated with the sequence or nil. + # +implicit+ a boolean indicating whether or not the sequence was + # implicitly started. + # +style+ is an integer indicating the list style. + # + # See Psych::Handler#start_sequence + def initialize anchor = nil, tag = nil, implicit = true, style = BLOCK + super() + @anchor = anchor + @tag = tag + @implicit = implicit + @style = style + end + + def sequence?; true; end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/stream.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/stream.rb new file mode 100644 index 0000000..b525217 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/nodes/stream.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true +module Psych + module Nodes + ### + # Represents a YAML stream. This is the root node for any YAML parse + # tree. This node must have one or more child nodes. The only valid + # child node for a Psych::Nodes::Stream node is Psych::Nodes::Document. + class Stream < Psych::Nodes::Node + + # Encodings supported by Psych (and libyaml) + + # Any encoding + ANY = Psych::Parser::ANY + + # UTF-8 encoding + UTF8 = Psych::Parser::UTF8 + + # UTF-16LE encoding + UTF16LE = Psych::Parser::UTF16LE + + # UTF-16BE encoding + UTF16BE = Psych::Parser::UTF16BE + + # The encoding used for this stream + attr_accessor :encoding + + ### + # Create a new Psych::Nodes::Stream node with an +encoding+ that + # defaults to Psych::Nodes::Stream::UTF8. + # + # See also Psych::Handler#start_stream + def initialize encoding = UTF8 + super() + @encoding = encoding + end + + def stream?; true; end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/omap.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/omap.rb new file mode 100644 index 0000000..29cde0b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/omap.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +module Psych + class Omap < ::Hash + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/parser.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/parser.rb new file mode 100644 index 0000000..39bc828 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/parser.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true +module Psych + ### + # YAML event parser class. This class parses a YAML document and calls + # events on the handler that is passed to the constructor. The events can + # be used for things such as constructing a YAML AST or deserializing YAML + # documents. It can even be fed back to Psych::Emitter to emit the same + # document that was parsed. + # + # See Psych::Handler for documentation on the events that Psych::Parser emits. + # + # Here is an example that prints out ever scalar found in a YAML document: + # + # # Handler for detecting scalar values + # class ScalarHandler < Psych::Handler + # def scalar value, anchor, tag, plain, quoted, style + # puts value + # end + # end + # + # parser = Psych::Parser.new(ScalarHandler.new) + # parser.parse(yaml_document) + # + # Here is an example that feeds the parser back in to Psych::Emitter. The + # YAML document is read from STDIN and written back out to STDERR: + # + # parser = Psych::Parser.new(Psych::Emitter.new($stderr)) + # parser.parse($stdin) + # + # Psych uses Psych::Parser in combination with Psych::TreeBuilder to + # construct an AST of the parsed YAML document. + + class Parser + class Mark < Struct.new(:index, :line, :column) + end + + # The handler on which events will be called + attr_accessor :handler + + # Set the encoding for this parser to +encoding+ + attr_writer :external_encoding + + ### + # Creates a new Psych::Parser instance with +handler+. YAML events will + # be called on +handler+. See Psych::Parser for more details. + + def initialize handler = Handler.new + @handler = handler + @external_encoding = ANY + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/scalar_scanner.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/scalar_scanner.rb new file mode 100644 index 0000000..b66ff99 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/scalar_scanner.rb @@ -0,0 +1,135 @@ +# frozen_string_literal: true +require 'strscan' + +module Psych + ### + # Scan scalars for built in types + class ScalarScanner + # Taken from http://yaml.org/type/timestamp.html + TIME = /^-?\d{4}-\d{1,2}-\d{1,2}(?:[Tt]|\s+)\d{1,2}:\d\d:\d\d(?:\.\d*)?(?:\s*(?:Z|[-+]\d{1,2}:?(?:\d\d)?))?$/ + + # Taken from http://yaml.org/type/float.html + # Base 60, [-+]inf and NaN are handled separately + FLOAT = /^(?:[-+]?([0-9][0-9_,]*)?\.[0-9]*([eE][-+][0-9]+)?(?# base 10))$/x + + # Taken from http://yaml.org/type/int.html + INTEGER = /^(?:[-+]?0b[0-1_,]+ (?# base 2) + |[-+]?0[0-7_,]+ (?# base 8) + |[-+]?(?:0|[1-9](?:[0-9]|,[0-9]|_[0-9])*) (?# base 10) + |[-+]?0x[0-9a-fA-F_,]+ (?# base 16))$/x + + attr_reader :class_loader + + # Create a new scanner + def initialize class_loader + @symbol_cache = {} + @class_loader = class_loader + end + + # Tokenize +string+ returning the Ruby object + def tokenize string + return nil if string.empty? + return @symbol_cache[string] if @symbol_cache.key?(string) + + # Check for a String type, being careful not to get caught by hash keys, hex values, and + # special floats (e.g., -.inf). + if string.match?(%r{^[^\d.:-]?[[:alpha:]_\s!@#$%\^&*(){}<>|/\\~;=]+}) || string.match?(/\n/) + return string if string.length > 5 + + if string.match?(/^[^ytonf~]/i) + string + elsif string == '~' || string.match?(/^null$/i) + nil + elsif string.match?(/^(yes|true|on)$/i) + true + elsif string.match?(/^(no|false|off)$/i) + false + else + string + end + elsif string.match?(TIME) + begin + parse_time string + rescue ArgumentError + string + end + elsif string.match?(/^\d{4}-(?:1[012]|0\d|\d)-(?:[12]\d|3[01]|0\d|\d)$/) + require 'date' + begin + class_loader.date.strptime(string, '%Y-%m-%d') + rescue ArgumentError + string + end + elsif string.match?(/^\+?\.inf$/i) + Float::INFINITY + elsif string.match?(/^-\.inf$/i) + -Float::INFINITY + elsif string.match?(/^\.nan$/i) + Float::NAN + elsif string.match?(/^:./) + if string =~ /^:(["'])(.*)\1/ + @symbol_cache[string] = class_loader.symbolize($2.sub(/^:/, '')) + else + @symbol_cache[string] = class_loader.symbolize(string.sub(/^:/, '')) + end + elsif string.match?(/^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}$/) + i = 0 + string.split(':').each_with_index do |n,e| + i += (n.to_i * 60 ** (e - 2).abs) + end + i + elsif string.match?(/^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}\.[0-9_]*$/) + i = 0 + string.split(':').each_with_index do |n,e| + i += (n.to_f * 60 ** (e - 2).abs) + end + i + elsif string.match?(FLOAT) + if string.match?(/\A[-+]?\.\Z/) + string + else + Float(string.gsub(/[,_]|\.([Ee]|$)/, '\1')) + end + elsif string.match?(INTEGER) + parse_int string + else + string + end + end + + ### + # Parse and return an int from +string+ + def parse_int string + Integer(string.gsub(/[,_]/, '')) + end + + ### + # Parse and return a Time from +string+ + def parse_time string + klass = class_loader.load 'Time' + + date, time = *(string.split(/[ tT]/, 2)) + (yy, m, dd) = date.match(/^(-?\d{4})-(\d{1,2})-(\d{1,2})/).captures.map { |x| x.to_i } + md = time.match(/(\d+:\d+:\d+)(?:\.(\d*))?\s*(Z|[-+]\d+(:\d\d)?)?/) + + (hh, mm, ss) = md[1].split(':').map { |x| x.to_i } + us = (md[2] ? Rational("0.#{md[2]}") : 0) * 1000000 + + time = klass.utc(yy, m, dd, hh, mm, ss, us) + + return time if 'Z' == md[3] + return klass.at(time.to_i, us) unless md[3] + + tz = md[3].match(/^([+\-]?\d{1,2})\:?(\d{1,2})?$/)[1..-1].compact.map { |digit| Integer(digit, 10) } + offset = tz.first * 3600 + + if offset < 0 + offset -= ((tz[1] || 0) * 60) + else + offset += ((tz[1] || 0) * 60) + end + + klass.new(yy, m, dd, hh, mm, ss+us/(1_000_000r), offset) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/set.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/set.rb new file mode 100644 index 0000000..760d217 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/set.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true +module Psych + class Set < ::Hash + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/stream.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/stream.rb new file mode 100644 index 0000000..24e45af --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/stream.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true +module Psych + ### + # Psych::Stream is a streaming YAML emitter. It will not buffer your YAML, + # but send it straight to an IO. + # + # Here is an example use: + # + # stream = Psych::Stream.new($stdout) + # stream.start + # stream.push({:foo => 'bar'}) + # stream.finish + # + # YAML will be immediately emitted to $stdout with no buffering. + # + # Psych::Stream#start will take a block and ensure that Psych::Stream#finish + # is called, so you can do this form: + # + # stream = Psych::Stream.new($stdout) + # stream.start do |em| + # em.push(:foo => 'bar') + # end + # + class Stream < Psych::Visitors::YAMLTree + class Emitter < Psych::Emitter # :nodoc: + def end_document implicit_end = !streaming? + super + end + + def streaming? + true + end + end + + include Psych::Streaming + extend Psych::Streaming::ClassMethods + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/streaming.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/streaming.rb new file mode 100644 index 0000000..eb19792 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/streaming.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true +module Psych + module Streaming + module ClassMethods + ### + # Create a new streaming emitter. Emitter will print to +io+. See + # Psych::Stream for an example. + def new io + emitter = const_get(:Emitter).new(io) + class_loader = ClassLoader.new + ss = ScalarScanner.new class_loader + super(emitter, ss, {}) + end + end + + ### + # Start streaming using +encoding+ + def start encoding = Nodes::Stream::UTF8 + super.tap { yield self if block_given? } + ensure + finish if block_given? + end + + private + def register target, obj + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/syntax_error.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/syntax_error.rb new file mode 100644 index 0000000..a4c9c4a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/syntax_error.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true +require_relative 'exception' + +module Psych + class SyntaxError < Psych::Exception + attr_reader :file, :line, :column, :offset, :problem, :context + + def initialize file, line, col, offset, problem, context + err = [problem, context].compact.join ' ' + filename = file || '' + message = "(%s): %s at line %d column %d" % [filename, err, line, col] + + @file = file + @line = line + @column = col + @offset = offset + @problem = problem + @context = context + super(message) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/tree_builder.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/tree_builder.rb new file mode 100644 index 0000000..414ca02 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/tree_builder.rb @@ -0,0 +1,137 @@ +# frozen_string_literal: true +require_relative 'handler' + +module Psych + ### + # This class works in conjunction with Psych::Parser to build an in-memory + # parse tree that represents a YAML document. + # + # == Example + # + # parser = Psych::Parser.new Psych::TreeBuilder.new + # parser.parse('--- foo') + # tree = parser.handler.root + # + # See Psych::Handler for documentation on the event methods used in this + # class. + class TreeBuilder < Psych::Handler + # Returns the root node for the built tree + attr_reader :root + + # Create a new TreeBuilder instance + def initialize + @stack = [] + @last = nil + @root = nil + + @start_line = nil + @start_column = nil + @end_line = nil + @end_column = nil + end + + def event_location(start_line, start_column, end_line, end_column) + @start_line = start_line + @start_column = start_column + @end_line = end_line + @end_column = end_column + end + + %w{ + Sequence + Mapping + }.each do |node| + class_eval %{ + def start_#{node.downcase}(anchor, tag, implicit, style) + n = Nodes::#{node}.new(anchor, tag, implicit, style) + set_start_location(n) + @last.children << n + push n + end + + def end_#{node.downcase} + n = pop + set_end_location(n) + n + end + } + end + + ### + # Handles start_document events with +version+, +tag_directives+, + # and +implicit+ styling. + # + # See Psych::Handler#start_document + def start_document version, tag_directives, implicit + n = Nodes::Document.new version, tag_directives, implicit + set_start_location(n) + @last.children << n + push n + end + + ### + # Handles end_document events with +version+, +tag_directives+, + # and +implicit+ styling. + # + # See Psych::Handler#start_document + def end_document implicit_end = !streaming? + @last.implicit_end = implicit_end + n = pop + set_end_location(n) + n + end + + def start_stream encoding + @root = Nodes::Stream.new(encoding) + set_start_location(@root) + push @root + end + + def end_stream + n = pop + set_end_location(n) + n + end + + def scalar value, anchor, tag, plain, quoted, style + s = Nodes::Scalar.new(value,anchor,tag,plain,quoted,style) + set_location(s) + @last.children << s + s + end + + def alias anchor + a = Nodes::Alias.new(anchor) + set_location(a) + @last.children << a + a + end + + private + def push value + @stack.push value + @last = value + end + + def pop + x = @stack.pop + @last = @stack.last + x + end + + def set_location(node) + set_start_location(node) + set_end_location(node) + end + + def set_start_location(node) + node.start_line = @start_line + node.start_column = @start_column + end + + def set_end_location(node) + node.end_line = @end_line + node.end_column = @end_column + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/versions.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/versions.rb new file mode 100644 index 0000000..3cfd59e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/versions.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +module Psych + # The version of Psych you are using + VERSION = '4.0.3' + + if RUBY_ENGINE == 'jruby' + DEFAULT_SNAKEYAML_VERSION = '1.28'.freeze + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors.rb new file mode 100644 index 0000000..508290d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true +require_relative 'visitors/visitor' +require_relative 'visitors/to_ruby' +require_relative 'visitors/emitter' +require_relative 'visitors/yaml_tree' +require_relative 'visitors/json_tree' +require_relative 'visitors/depth_first' diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/depth_first.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/depth_first.rb new file mode 100644 index 0000000..b4ff9e4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/depth_first.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true +module Psych + module Visitors + class DepthFirst < Psych::Visitors::Visitor + def initialize block + @block = block + end + + private + + def nary o + o.children.each { |x| visit x } + @block.call o + end + alias :visit_Psych_Nodes_Stream :nary + alias :visit_Psych_Nodes_Document :nary + alias :visit_Psych_Nodes_Sequence :nary + alias :visit_Psych_Nodes_Mapping :nary + + def terminal o + @block.call o + end + alias :visit_Psych_Nodes_Scalar :terminal + alias :visit_Psych_Nodes_Alias :terminal + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/emitter.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/emitter.rb new file mode 100644 index 0000000..e3b92b7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/emitter.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true +module Psych + module Visitors + class Emitter < Psych::Visitors::Visitor + def initialize io, options = {} + opts = [:indentation, :canonical, :line_width].find_all { |opt| + options.key?(opt) + } + + if opts.empty? + @handler = Psych::Emitter.new io + else + du = Handler::DumperOptions.new + opts.each { |option| du.send :"#{option}=", options[option] } + @handler = Psych::Emitter.new io, du + end + end + + def visit_Psych_Nodes_Stream o + @handler.start_stream o.encoding + o.children.each { |c| accept c } + @handler.end_stream + end + + def visit_Psych_Nodes_Document o + @handler.start_document o.version, o.tag_directives, o.implicit + o.children.each { |c| accept c } + @handler.end_document o.implicit_end + end + + def visit_Psych_Nodes_Scalar o + @handler.scalar o.value, o.anchor, o.tag, o.plain, o.quoted, o.style + end + + def visit_Psych_Nodes_Sequence o + @handler.start_sequence o.anchor, o.tag, o.implicit, o.style + o.children.each { |c| accept c } + @handler.end_sequence + end + + def visit_Psych_Nodes_Mapping o + @handler.start_mapping o.anchor, o.tag, o.implicit, o.style + o.children.each { |c| accept c } + @handler.end_mapping + end + + def visit_Psych_Nodes_Alias o + @handler.alias o.anchor + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/json_tree.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/json_tree.rb new file mode 100644 index 0000000..979fc10 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/json_tree.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true +require_relative '../json/ruby_events' + +module Psych + module Visitors + class JSONTree < YAMLTree + include Psych::JSON::RubyEvents + + def self.create options = {} + emitter = Psych::JSON::TreeBuilder.new + class_loader = ClassLoader.new + ss = ScalarScanner.new class_loader + new(emitter, ss, options) + end + + def accept target + if target.respond_to?(:encode_with) + dump_coder target + else + send(@dispatch_cache[target.class], target) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/to_ruby.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/to_ruby.rb new file mode 100644 index 0000000..4c1f561 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/to_ruby.rb @@ -0,0 +1,434 @@ +# frozen_string_literal: true +require_relative '../scalar_scanner' +require_relative '../class_loader' +require_relative '../exception' + +unless defined?(Regexp::NOENCODING) + Regexp::NOENCODING = 32 +end + +module Psych + module Visitors + ### + # This class walks a YAML AST, converting each node to Ruby + class ToRuby < Psych::Visitors::Visitor + def self.create(symbolize_names: false, freeze: false) + class_loader = ClassLoader.new + scanner = ScalarScanner.new class_loader + new(scanner, class_loader, symbolize_names: symbolize_names, freeze: freeze) + end + + attr_reader :class_loader + + def initialize ss, class_loader, symbolize_names: false, freeze: false + super() + @st = {} + @ss = ss + @load_tags = Psych.load_tags + @domain_types = Psych.domain_types + @class_loader = class_loader + @symbolize_names = symbolize_names + @freeze = freeze + end + + def accept target + result = super + + unless @domain_types.empty? || !target.tag + key = target.tag.sub(/^[!\/]*/, '').sub(/(,\d+)\//, '\1:') + key = "tag:#{key}" unless key =~ /^(?:tag:|x-private)/ + + if @domain_types.key? key + value, block = @domain_types[key] + result = block.call value, result + end + end + + result = deduplicate(result).freeze if @freeze + result + end + + def deserialize o + if klass = resolve_class(@load_tags[o.tag]) + instance = klass.allocate + + if instance.respond_to?(:init_with) + coder = Psych::Coder.new(o.tag) + coder.scalar = o.value + instance.init_with coder + end + + return instance + end + + return o.value if o.quoted + return @ss.tokenize(o.value) unless o.tag + + case o.tag + when '!binary', 'tag:yaml.org,2002:binary' + o.value.unpack('m').first + when /^!(?:str|ruby\/string)(?::(.*))?$/, 'tag:yaml.org,2002:str' + klass = resolve_class($1) + if klass + klass.allocate.replace o.value + else + o.value + end + when '!ruby/object:BigDecimal' + require 'bigdecimal' unless defined? BigDecimal + class_loader.big_decimal._load o.value + when "!ruby/object:DateTime" + class_loader.date_time + require 'date' unless defined? DateTime + @ss.parse_time(o.value).to_datetime + when '!ruby/encoding' + ::Encoding.find o.value + when "!ruby/object:Complex" + class_loader.complex + Complex(o.value) + when "!ruby/object:Rational" + class_loader.rational + Rational(o.value) + when "!ruby/class", "!ruby/module" + resolve_class o.value + when "tag:yaml.org,2002:float", "!float" + Float(@ss.tokenize(o.value)) + when "!ruby/regexp" + klass = class_loader.regexp + o.value =~ /^\/(.*)\/([mixn]*)$/m + source = $1 + options = 0 + lang = nil + ($2 || '').split('').each do |option| + case option + when 'x' then options |= Regexp::EXTENDED + when 'i' then options |= Regexp::IGNORECASE + when 'm' then options |= Regexp::MULTILINE + when 'n' then options |= Regexp::NOENCODING + else lang = option + end + end + klass.new(*[source, options, lang].compact) + when "!ruby/range" + klass = class_loader.range + args = o.value.split(/([.]{2,3})/, 2).map { |s| + accept Nodes::Scalar.new(s) + } + args.push(args.delete_at(1) == '...') + klass.new(*args) + when /^!ruby\/sym(bol)?:?(.*)?$/ + class_loader.symbolize o.value + else + @ss.tokenize o.value + end + end + private :deserialize + + def visit_Psych_Nodes_Scalar o + register o, deserialize(o) + end + + def visit_Psych_Nodes_Sequence o + if klass = resolve_class(@load_tags[o.tag]) + instance = klass.allocate + + if instance.respond_to?(:init_with) + coder = Psych::Coder.new(o.tag) + coder.seq = o.children.map { |c| accept c } + instance.init_with coder + end + + return instance + end + + case o.tag + when nil + register_empty(o) + when '!omap', 'tag:yaml.org,2002:omap' + map = register(o, Psych::Omap.new) + o.children.each { |a| + map[accept(a.children.first)] = accept a.children.last + } + map + when /^!(?:seq|ruby\/array):(.*)$/ + klass = resolve_class($1) + list = register(o, klass.allocate) + o.children.each { |c| list.push accept c } + list + else + register_empty(o) + end + end + + def visit_Psych_Nodes_Mapping o + if @load_tags[o.tag] + return revive(resolve_class(@load_tags[o.tag]), o) + end + return revive_hash(register(o, {}), o) unless o.tag + + case o.tag + when /^!ruby\/struct:?(.*)?$/ + klass = resolve_class($1) if $1 + + if klass + s = register(o, klass.allocate) + + members = {} + struct_members = s.members.map { |x| class_loader.symbolize x } + o.children.each_slice(2) do |k,v| + member = accept(k) + value = accept(v) + if struct_members.include?(class_loader.symbolize(member)) + s.send("#{member}=", value) + else + members[member.to_s.sub(/^@/, '')] = value + end + end + init_with(s, members, o) + else + klass = class_loader.struct + members = o.children.map { |c| accept c } + h = Hash[*members] + s = klass.new(*h.map { |k,v| + class_loader.symbolize k + }).new(*h.map { |k,v| v }) + register(o, s) + s + end + + when /^!ruby\/object:?(.*)?$/ + name = $1 || 'Object' + + if name == 'Complex' + class_loader.complex + h = Hash[*o.children.map { |c| accept c }] + register o, Complex(h['real'], h['image']) + elsif name == 'Rational' + class_loader.rational + h = Hash[*o.children.map { |c| accept c }] + register o, Rational(h['numerator'], h['denominator']) + elsif name == 'Hash' + revive_hash(register(o, {}), o) + else + obj = revive((resolve_class(name) || class_loader.object), o) + obj + end + + when /^!(?:str|ruby\/string)(?::(.*))?$/, 'tag:yaml.org,2002:str' + klass = resolve_class($1) + members = {} + string = nil + + o.children.each_slice(2) do |k,v| + key = accept k + value = accept v + + if key == 'str' + if klass + string = klass.allocate.replace value + else + string = value + end + register(o, string) + else + members[key] = value + end + end + init_with(string, members.map { |k,v| [k.to_s.sub(/^@/, ''),v] }, o) + when /^!ruby\/array:(.*)$/ + klass = resolve_class($1) + list = register(o, klass.allocate) + + members = Hash[o.children.map { |c| accept c }.each_slice(2).to_a] + list.replace members['internal'] + + members['ivars'].each do |ivar, v| + list.instance_variable_set ivar, v + end + list + + when '!ruby/range' + klass = class_loader.range + h = Hash[*o.children.map { |c| accept c }] + register o, klass.new(h['begin'], h['end'], h['excl']) + + when /^!ruby\/exception:?(.*)?$/ + h = Hash[*o.children.map { |c| accept c }] + + e = build_exception((resolve_class($1) || class_loader.exception), + h.delete('message')) + + e.set_backtrace h.delete('backtrace') if h.key? 'backtrace' + init_with(e, h, o) + + when '!set', 'tag:yaml.org,2002:set' + set = class_loader.psych_set.new + @st[o.anchor] = set if o.anchor + o.children.each_slice(2) do |k,v| + set[accept(k)] = accept(v) + end + set + + when /^!ruby\/hash-with-ivars(?::(.*))?$/ + hash = $1 ? resolve_class($1).allocate : {} + register o, hash + o.children.each_slice(2) do |key, value| + case key.value + when 'elements' + revive_hash hash, value + when 'ivars' + value.children.each_slice(2) do |k,v| + hash.instance_variable_set accept(k), accept(v) + end + end + end + hash + + when /^!map:(.*)$/, /^!ruby\/hash:(.*)$/ + revive_hash register(o, resolve_class($1).allocate), o + + when '!omap', 'tag:yaml.org,2002:omap' + map = register(o, class_loader.psych_omap.new) + o.children.each_slice(2) do |l,r| + map[accept(l)] = accept r + end + map + + when /^!ruby\/marshalable:(.*)$/ + name = $1 + klass = resolve_class(name) + obj = register(o, klass.allocate) + + if obj.respond_to?(:init_with) + init_with(obj, revive_hash({}, o), o) + elsif obj.respond_to?(:marshal_load) + marshal_data = o.children.map(&method(:accept)) + obj.marshal_load(marshal_data) + obj + else + raise ArgumentError, "Cannot deserialize #{name}" + end + + else + revive_hash(register(o, {}), o) + end + end + + def visit_Psych_Nodes_Document o + accept o.root + end + + def visit_Psych_Nodes_Stream o + o.children.map { |c| accept c } + end + + def visit_Psych_Nodes_Alias o + @st.fetch(o.anchor) { raise BadAlias, "Unknown alias: #{o.anchor}" } + end + + private + + def register node, object + @st[node.anchor] = object if node.anchor + object + end + + def register_empty object + list = register(object, []) + object.children.each { |c| list.push accept c } + list + end + + def revive_hash hash, o, tagged= false + o.children.each_slice(2) { |k,v| + key = accept(k) + val = accept(v) + + if key == '<<' && k.tag != "tag:yaml.org,2002:str" + case v + when Nodes::Alias, Nodes::Mapping + begin + hash.merge! val + rescue TypeError + hash[key] = val + end + when Nodes::Sequence + begin + h = {} + val.reverse_each do |value| + h.merge! value + end + hash.merge! h + rescue TypeError + hash[key] = val + end + else + hash[key] = val + end + else + if !tagged && @symbolize_names && key.is_a?(String) + key = key.to_sym + elsif !@freeze + key = deduplicate(key) + end + + hash[key] = val + end + + } + hash + end + + if RUBY_VERSION < '2.7' + def deduplicate key + if key.is_a?(String) + # It is important to untaint the string, otherwise it won't + # be deduplicated into an fstring, but simply frozen. + -(key.untaint) + else + key + end + end + else + def deduplicate key + if key.is_a?(String) + -key + else + key + end + end + end + + def merge_key hash, key, val + end + + def revive klass, node + s = register(node, klass.allocate) + init_with(s, revive_hash({}, node, true), node) + end + + def init_with o, h, node + c = Psych::Coder.new(node.tag) + c.map = h + + if o.respond_to?(:init_with) + o.init_with c + else + h.each { |k,v| o.instance_variable_set(:"@#{k}", v) } + end + o + end + + # Convert +klassname+ to a Class + def resolve_class klassname + class_loader.load klassname + end + end + + class NoAliasRuby < ToRuby + def visit_Psych_Nodes_Alias o + raise BadAlias, "Unknown alias: #{o.anchor}" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/visitor.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/visitor.rb new file mode 100644 index 0000000..21052aa --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/visitor.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true +module Psych + module Visitors + class Visitor + def accept target + visit target + end + + private + + # @api private + def self.dispatch_cache + Hash.new do |hash, klass| + hash[klass] = :"visit_#{klass.name.gsub('::', '_')}" + end.compare_by_identity + end + + if defined?(Ractor) + def dispatch + @dispatch_cache ||= (Ractor.current[:Psych_Visitors_Visitor] ||= Visitor.dispatch_cache) + end + else + DISPATCH = dispatch_cache + def dispatch + DISPATCH + end + end + + def visit target + send dispatch[target.class], target + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/yaml_tree.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/yaml_tree.rb new file mode 100644 index 0000000..316a3a9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/visitors/yaml_tree.rb @@ -0,0 +1,587 @@ +# frozen_string_literal: true +require_relative '../tree_builder' +require_relative '../scalar_scanner' +require_relative '../class_loader' + +module Psych + module Visitors + ### + # YAMLTree builds a YAML ast given a Ruby object. For example: + # + # builder = Psych::Visitors::YAMLTree.new + # builder << { :foo => 'bar' } + # builder.tree # => # v } + @emitter.end_sequence + end + + def visit_Encoding o + tag = "!ruby/encoding" + @emitter.scalar o.name, nil, tag, false, false, Nodes::Scalar::ANY + end + + def visit_Object o + tag = Psych.dump_tags[o.class] + unless tag + klass = o.class == Object ? nil : o.class.name + tag = ['!ruby/object', klass].compact.join(':') + end + + map = @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK) + register(o, map) + + dump_ivars o + @emitter.end_mapping + end + + alias :visit_Delegator :visit_Object + + def visit_Struct o + tag = ['!ruby/struct', o.class.name].compact.join(':') + + register o, @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK) + o.members.each do |member| + @emitter.scalar member.to_s, nil, nil, true, false, Nodes::Scalar::ANY + accept o[member] + end + + dump_ivars o + + @emitter.end_mapping + end + + def visit_Exception o + dump_exception o, o.message.to_s + end + + def visit_NameError o + dump_exception o, o.message.to_s + end + + def visit_Regexp o + register o, @emitter.scalar(o.inspect, nil, '!ruby/regexp', false, false, Nodes::Scalar::ANY) + end + + def visit_DateTime o + formatted = if o.offset.zero? + o.strftime("%Y-%m-%d %H:%M:%S.%9N Z".freeze) + else + o.strftime("%Y-%m-%d %H:%M:%S.%9N %:z".freeze) + end + tag = '!ruby/object:DateTime' + register o, @emitter.scalar(formatted, nil, tag, false, false, Nodes::Scalar::ANY) + end + + def visit_Time o + formatted = format_time o + register o, @emitter.scalar(formatted, nil, nil, true, false, Nodes::Scalar::ANY) + end + + def visit_Rational o + register o, @emitter.start_mapping(nil, '!ruby/object:Rational', false, Nodes::Mapping::BLOCK) + + [ + 'denominator', o.denominator.to_s, + 'numerator', o.numerator.to_s + ].each do |m| + @emitter.scalar m, nil, nil, true, false, Nodes::Scalar::ANY + end + + @emitter.end_mapping + end + + def visit_Complex o + register o, @emitter.start_mapping(nil, '!ruby/object:Complex', false, Nodes::Mapping::BLOCK) + + ['real', o.real.to_s, 'image', o.imag.to_s].each do |m| + @emitter.scalar m, nil, nil, true, false, Nodes::Scalar::ANY + end + + @emitter.end_mapping + end + + def visit_Integer o + @emitter.scalar o.to_s, nil, nil, true, false, Nodes::Scalar::ANY + end + alias :visit_TrueClass :visit_Integer + alias :visit_FalseClass :visit_Integer + alias :visit_Date :visit_Integer + + def visit_Float o + if o.nan? + @emitter.scalar '.nan', nil, nil, true, false, Nodes::Scalar::ANY + elsif o.infinite? + @emitter.scalar((o.infinite? > 0 ? '.inf' : '-.inf'), + nil, nil, true, false, Nodes::Scalar::ANY) + else + @emitter.scalar o.to_s, nil, nil, true, false, Nodes::Scalar::ANY + end + end + + def visit_BigDecimal o + @emitter.scalar o._dump, nil, '!ruby/object:BigDecimal', false, false, Nodes::Scalar::ANY + end + + def visit_String o + plain = true + quote = true + style = Nodes::Scalar::PLAIN + tag = nil + + if binary?(o) + o = [o].pack('m0') + tag = '!binary' # FIXME: change to below when syck is removed + #tag = 'tag:yaml.org,2002:binary' + style = Nodes::Scalar::LITERAL + plain = false + quote = false + elsif o =~ /\n(?!\Z)/ # match \n except blank line at the end of string + style = Nodes::Scalar::LITERAL + elsif o == '<<' + style = Nodes::Scalar::SINGLE_QUOTED + tag = 'tag:yaml.org,2002:str' + plain = false + quote = false + elsif o == 'y' || o == 'n' + style = Nodes::Scalar::DOUBLE_QUOTED + elsif @line_width && o.length > @line_width + style = Nodes::Scalar::FOLDED + elsif o =~ /^[^[:word:]][^"]*$/ + style = Nodes::Scalar::DOUBLE_QUOTED + elsif not String === @ss.tokenize(o) or /\A0[0-7]*[89]/ =~ o + style = Nodes::Scalar::SINGLE_QUOTED + end + + is_primitive = o.class == ::String + ivars = is_primitive ? [] : o.instance_variables + + if ivars.empty? + unless is_primitive + tag = "!ruby/string:#{o.class}" + plain = false + quote = false + end + @emitter.scalar o, nil, tag, plain, quote, style + else + maptag = '!ruby/string'.dup + maptag << ":#{o.class}" unless o.class == ::String + + register o, @emitter.start_mapping(nil, maptag, false, Nodes::Mapping::BLOCK) + @emitter.scalar 'str', nil, nil, true, false, Nodes::Scalar::ANY + @emitter.scalar o, nil, tag, plain, quote, style + + dump_ivars o + + @emitter.end_mapping + end + end + + def visit_Module o + raise TypeError, "can't dump anonymous module: #{o}" unless o.name + register o, @emitter.scalar(o.name, nil, '!ruby/module', false, false, Nodes::Scalar::SINGLE_QUOTED) + end + + def visit_Class o + raise TypeError, "can't dump anonymous class: #{o}" unless o.name + register o, @emitter.scalar(o.name, nil, '!ruby/class', false, false, Nodes::Scalar::SINGLE_QUOTED) + end + + def visit_Range o + register o, @emitter.start_mapping(nil, '!ruby/range', false, Nodes::Mapping::BLOCK) + ['begin', o.begin, 'end', o.end, 'excl', o.exclude_end?].each do |m| + accept m + end + @emitter.end_mapping + end + + def visit_Hash o + if o.class == ::Hash + register(o, @emitter.start_mapping(nil, nil, true, Psych::Nodes::Mapping::BLOCK)) + o.each do |k,v| + accept k + accept v + end + @emitter.end_mapping + else + visit_hash_subclass o + end + end + + def visit_Psych_Set o + register(o, @emitter.start_mapping(nil, '!set', false, Psych::Nodes::Mapping::BLOCK)) + + o.each do |k,v| + accept k + accept v + end + + @emitter.end_mapping + end + + def visit_Array o + if o.class == ::Array + visit_Enumerator o + else + visit_array_subclass o + end + end + + def visit_Enumerator o + register o, @emitter.start_sequence(nil, nil, true, Nodes::Sequence::BLOCK) + o.each { |c| accept c } + @emitter.end_sequence + end + + def visit_NilClass o + @emitter.scalar('', nil, 'tag:yaml.org,2002:null', true, false, Nodes::Scalar::ANY) + end + + def visit_Symbol o + if o.empty? + @emitter.scalar "", nil, '!ruby/symbol', false, false, Nodes::Scalar::ANY + else + @emitter.scalar ":#{o}", nil, nil, true, false, Nodes::Scalar::ANY + end + end + + def visit_BasicObject o + tag = Psych.dump_tags[o.class] + tag ||= "!ruby/marshalable:#{o.class.name}" + + map = @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK) + register(o, map) + + o.marshal_dump.each(&method(:accept)) + + @emitter.end_mapping + end + + private + + def binary? string + string.encoding == Encoding::ASCII_8BIT && !string.ascii_only? + end + + def visit_array_subclass o + tag = "!ruby/array:#{o.class}" + ivars = o.instance_variables + if ivars.empty? + node = @emitter.start_sequence(nil, tag, false, Nodes::Sequence::BLOCK) + register o, node + o.each { |c| accept c } + @emitter.end_sequence + else + node = @emitter.start_mapping(nil, tag, false, Nodes::Sequence::BLOCK) + register o, node + + # Dump the internal list + accept 'internal' + @emitter.start_sequence(nil, nil, true, Nodes::Sequence::BLOCK) + o.each { |c| accept c } + @emitter.end_sequence + + # Dump the ivars + accept 'ivars' + @emitter.start_mapping(nil, nil, true, Nodes::Sequence::BLOCK) + ivars.each do |ivar| + accept ivar + accept o.instance_variable_get ivar + end + @emitter.end_mapping + + @emitter.end_mapping + end + end + + def visit_hash_subclass o + ivars = o.instance_variables + if ivars.any? + tag = "!ruby/hash-with-ivars:#{o.class}" + node = @emitter.start_mapping(nil, tag, false, Psych::Nodes::Mapping::BLOCK) + register(o, node) + + # Dump the ivars + accept 'ivars' + @emitter.start_mapping nil, nil, true, Nodes::Mapping::BLOCK + o.instance_variables.each do |ivar| + accept ivar + accept o.instance_variable_get ivar + end + @emitter.end_mapping + + # Dump the elements + accept 'elements' + @emitter.start_mapping nil, nil, true, Nodes::Mapping::BLOCK + o.each do |k,v| + accept k + accept v + end + @emitter.end_mapping + + @emitter.end_mapping + else + tag = "!ruby/hash:#{o.class}" + node = @emitter.start_mapping(nil, tag, false, Psych::Nodes::Mapping::BLOCK) + register(o, node) + o.each do |k,v| + accept k + accept v + end + @emitter.end_mapping + end + end + + def dump_list o + end + + def dump_exception o, msg + tag = ['!ruby/exception', o.class.name].join ':' + + @emitter.start_mapping nil, tag, false, Nodes::Mapping::BLOCK + + if msg + @emitter.scalar 'message', nil, nil, true, false, Nodes::Scalar::ANY + accept msg + end + + @emitter.scalar 'backtrace', nil, nil, true, false, Nodes::Scalar::ANY + accept o.backtrace + + dump_ivars o + + @emitter.end_mapping + end + + def format_time time + if time.utc? + time.strftime("%Y-%m-%d %H:%M:%S.%9N Z") + else + time.strftime("%Y-%m-%d %H:%M:%S.%9N %:z") + end + end + + def register target, yaml_obj + @st.register target, yaml_obj + yaml_obj + end + + def dump_coder o + @coders << o + tag = Psych.dump_tags[o.class] + unless tag + klass = o.class == Object ? nil : o.class.name + tag = ['!ruby/object', klass].compact.join(':') + end + + c = Psych::Coder.new(tag) + o.encode_with(c) + emit_coder c, o + end + + def emit_coder c, o + case c.type + when :scalar + @emitter.scalar c.scalar, nil, c.tag, c.tag.nil?, false, c.style + when :seq + @emitter.start_sequence nil, c.tag, c.tag.nil?, c.style + c.seq.each do |thing| + accept thing + end + @emitter.end_sequence + when :map + register o, @emitter.start_mapping(nil, c.tag, c.implicit, c.style) + c.map.each do |k,v| + accept k + accept v + end + @emitter.end_mapping + when :object + accept c.object + end + end + + def dump_ivars target + target.instance_variables.each do |iv| + @emitter.scalar("#{iv.to_s.sub(/^@/, '')}", nil, nil, true, false, Nodes::Scalar::ANY) + accept target.instance_variable_get(iv) + end + end + end + + class RestrictedYAMLTree < YAMLTree + DEFAULT_PERMITTED_CLASSES = { + TrueClass => true, + FalseClass => true, + NilClass => true, + Integer => true, + Float => true, + String => true, + Array => true, + Hash => true, + }.compare_by_identity.freeze + + def initialize emitter, ss, options + super + @permitted_classes = DEFAULT_PERMITTED_CLASSES.dup + Array(options[:permitted_classes]).each do |klass| + @permitted_classes[klass] = true + end + @permitted_symbols = {}.compare_by_identity + Array(options[:permitted_symbols]).each do |symbol| + @permitted_symbols[symbol] = true + end + @aliases = options.fetch(:aliases, false) + end + + def accept target + if !@aliases && @st.key?(target) + raise BadAlias, "Tried to dump an aliased object" + end + + unless @permitted_classes[target.class] + raise DisallowedClass.new('dump', target.class.name || target.class.inspect) + end + + super + end + + def visit_Symbol sym + unless @permitted_symbols[sym] + raise DisallowedClass.new('dump', "Symbol(#{sym.inspect})") + end + + super + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/y.rb b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/y.rb new file mode 100644 index 0000000..e857953 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/lib/psych/y.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true +module Kernel + ### + # An alias for Psych.dump_stream meant to be used with IRB. + def y *objects + puts Psych.dump_stream(*objects) + end + private :y +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/psych.gemspec b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/psych.gemspec new file mode 100644 index 0000000..65dd715 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/psych-4.0.3/psych.gemspec @@ -0,0 +1,69 @@ +# -*- encoding: utf-8 -*- +# frozen_string_literal: true + +version_module = Module.new do + version_rb = File.join(__dir__, "lib/psych/versions.rb") + module_eval(File.read(version_rb), version_rb) +end + +Gem::Specification.new do |s| + s.name = "psych" + s.version = version_module::Psych::VERSION + s.authors = ["Aaron Patterson", "SHIBATA Hiroshi", "Charles Oliver Nutter"] + s.email = ["aaron@tenderlovemaking.com", "hsbt@ruby-lang.org", "headius@headius.com"] + s.summary = "Psych is a YAML parser and emitter" + s.description = <<-DESCRIPTION +Psych is a YAML parser and emitter. Psych leverages libyaml[https://pyyaml.org/wiki/LibYAML] +for its YAML parsing and emitting capabilities. In addition to wrapping libyaml, +Psych also knows how to serialize and de-serialize most Ruby objects to and from the YAML format. +DESCRIPTION + s.homepage = "https://github.com/ruby/psych" + s.licenses = ["MIT"] + s.require_paths = ["lib"] + + # for ruby core repository. It was generated by `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } + s.files = [ + ".gitignore", "Gemfile", "LICENSE", "Mavenfile", "README.md", "Rakefile", "bin/console", + "bin/setup", "ext/psych/depend", "ext/psych/extconf.rb", "ext/psych/psych.c", "ext/psych/psych.h", + "ext/psych/psych_emitter.c", "ext/psych/psych_emitter.h", "ext/psych/psych_parser.c", "ext/psych/psych_parser.h", + "ext/psych/psych_to_ruby.c", "ext/psych/psych_to_ruby.h", "ext/psych/psych_yaml_tree.c", "ext/psych/psych_yaml_tree.h", + "ext/psych/yaml/LICENSE", "ext/psych/yaml/api.c", "ext/psych/yaml/config.h", "ext/psych/yaml/dumper.c", + "ext/psych/yaml/emitter.c", "ext/psych/yaml/loader.c", "ext/psych/yaml/parser.c", "ext/psych/yaml/reader.c", + "ext/psych/yaml/scanner.c", "ext/psych/yaml/writer.c", "ext/psych/yaml/yaml.h", "ext/psych/yaml/yaml_private.h", + "lib/psych.rb", "lib/psych/class_loader.rb", "lib/psych/coder.rb", "lib/psych/core_ext.rb", "lib/psych/exception.rb", + "lib/psych/handler.rb", "lib/psych/handlers/document_stream.rb", "lib/psych/handlers/recorder.rb", + "lib/psych/json/ruby_events.rb", "lib/psych/json/stream.rb", "lib/psych/json/tree_builder.rb", + "lib/psych/json/yaml_events.rb", "lib/psych/nodes.rb", "lib/psych/nodes/alias.rb", "lib/psych/nodes/document.rb", + "lib/psych/nodes/mapping.rb", "lib/psych/nodes/node.rb", "lib/psych/nodes/scalar.rb", "lib/psych/nodes/sequence.rb", + "lib/psych/nodes/stream.rb", "lib/psych/omap.rb", "lib/psych/parser.rb", "lib/psych/scalar_scanner.rb", + "lib/psych/set.rb", "lib/psych/stream.rb", "lib/psych/streaming.rb", "lib/psych/syntax_error.rb", + "lib/psych/tree_builder.rb", "lib/psych/versions.rb", "lib/psych/visitors.rb","lib/psych/visitors/depth_first.rb", + "lib/psych/visitors/emitter.rb", "lib/psych/visitors/json_tree.rb", "lib/psych/visitors/to_ruby.rb", + "lib/psych/visitors/visitor.rb", "lib/psych/visitors/yaml_tree.rb", "lib/psych/y.rb", "psych.gemspec" + ] + + s.rdoc_options = ["--main", "README.md"] + s.extra_rdoc_files = ["README.md"] + + s.required_ruby_version = Gem::Requirement.new(">= 2.4.0") + s.required_rubygems_version = Gem::Requirement.new(">= 0") + + if RUBY_ENGINE == 'jruby' + s.platform = 'java' + s.files.concat [ + "ext/java/org/jruby/ext/psych/PsychEmitter.java", + "ext/java/org/jruby/ext/psych/PsychLibrary.java", + "ext/java/org/jruby/ext/psych/PsychParser.java", + "ext/java/org/jruby/ext/psych/PsychToRuby.java", + "ext/java/org/jruby/ext/psych/PsychYamlTree.java", + "lib/psych_jars.rb", + "lib/psych.jar" + ] + s.requirements = "jar org.yaml:snakeyaml, #{version_module::Psych::DEFAULT_SNAKEYAML_VERSION}" + s.add_dependency 'jar-dependencies', '>= 0.1.7' + else + s.extensions = ["ext/psych/extconf.rb"] + s.add_dependency 'stringio' + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/CHANGELOG.md b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/CHANGELOG.md new file mode 100644 index 0000000..e74cca0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/CHANGELOG.md @@ -0,0 +1,694 @@ +# Changelog + +All notable changes to this project will be documented in this file. For info on how to format all future additions to this file please reference [Keep A Changelog](https://keepachangelog.com/en/1.0.0/). + +## [2.2.3] - 2020-02-11 + +- [CVE-2020-8184] Only decode cookie values + +## [2.2.2] - 2020-02-11 + +### Fixed + +- Fix incorrect `Rack::Request#host` value. ([#1591](https://github.com/rack/rack/pull/1591), [@ioquatix](https://github.com/ioquatix)) +- Revert `Rack::Handler::Thin` implementation. ([#1583](https://github.com/rack/rack/pull/1583), [@jeremyevans](https://github.com/jeremyevans)) +- Double assignment is still needed to prevent an "unused variable" warning. ([#1589](https://github.com/rack/rack/pull/1589), [@kamipo](https://github.com/kamipo)) +- Fix to handle same_site option for session pool. ([#1587](https://github.com/rack/rack/pull/1587), [@kamipo](https://github.com/kamipo)) + +## [2.2.1] - 2020-02-09 + +### Fixed + +- Rework `Rack::Request#ip` to handle empty `forwarded_for`. ([#1577](https://github.com/rack/rack/pull/1577), [@ioquatix](https://github.com/ioquatix)) + +## [2.2.0] - 2020-02-08 + +### SPEC Changes + +- `rack.session` request environment entry must respond to `to_hash` and return unfrozen Hash. ([@jeremyevans](https://github.com/jeremyevans)) +- Request environment cannot be frozen. ([@jeremyevans](https://github.com/jeremyevans)) +- CGI values in the request environment with non-ASCII characters must use ASCII-8BIT encoding. ([@jeremyevans](https://github.com/jeremyevans)) +- Improve SPEC/lint relating to SERVER_NAME, SERVER_PORT and HTTP_HOST. ([#1561](https://github.com/rack/rack/pull/1561), [@ioquatix](https://github.com/ioquatix)) + +### Added + +- `rackup` supports multiple `-r` options and will require all arguments. ([@jeremyevans](https://github.com/jeremyevans)) +- `Server` supports an array of paths to require for the `:require` option. ([@khotta](https://github.com/khotta)) +- `Files` supports multipart range requests. ([@fatkodima](https://github.com/fatkodima)) +- `Multipart::UploadedFile` supports an IO-like object instead of using the filesystem, using `:filename` and `:io` options. ([@jeremyevans](https://github.com/jeremyevans)) +- `Multipart::UploadedFile` supports keyword arguments `:path`, `:content_type`, and `:binary` in addition to positional arguments. ([@jeremyevans](https://github.com/jeremyevans)) +- `Static` supports a `:cascade` option for calling the app if there is no matching file. ([@jeremyevans](https://github.com/jeremyevans)) +- `Session::Abstract::SessionHash#dig`. ([@jeremyevans](https://github.com/jeremyevans)) +- `Response.[]` and `MockResponse.[]` for creating instances using status, headers, and body. ([@ioquatix](https://github.com/ioquatix)) +- Convenient cache and content type methods for `Rack::Response`. ([#1555](https://github.com/rack/rack/pull/1555), [@ioquatix](https://github.com/ioquatix)) + +### Changed + +- `Request#params` no longer rescues EOFError. ([@jeremyevans](https://github.com/jeremyevans)) +- `Directory` uses a streaming approach, significantly improving time to first byte for large directories. ([@jeremyevans](https://github.com/jeremyevans)) +- `Directory` no longer includes a Parent directory link in the root directory index. ([@jeremyevans](https://github.com/jeremyevans)) +- `QueryParser#parse_nested_query` uses original backtrace when reraising exception with new class. ([@jeremyevans](https://github.com/jeremyevans)) +- `ConditionalGet` follows RFC 7232 precedence if both If-None-Match and If-Modified-Since headers are provided. ([@jeremyevans](https://github.com/jeremyevans)) +- `.ru` files supports the `frozen-string-literal` magic comment. ([@eregon](https://github.com/eregon)) +- Rely on autoload to load constants instead of requiring internal files, make sure to require 'rack' and not just 'rack/...'. ([@jeremyevans](https://github.com/jeremyevans)) +- `Etag` will continue sending ETag even if the response should not be cached. ([@henm](https://github.com/henm)) +- `Request#host_with_port` no longer includes a colon for a missing or empty port. ([@AlexWayfer](https://github.com/AlexWayfer)) +- All handlers uses keywords arguments instead of an options hash argument. ([@ioquatix](https://github.com/ioquatix)) +- `Files` handling of range requests no longer return a body that supports `to_path`, to ensure range requests are handled correctly. ([@jeremyevans](https://github.com/jeremyevans)) +- `Multipart::Generator` only includes `Content-Length` for files with paths, and `Content-Disposition` `filename` if the `UploadedFile` instance has one. ([@jeremyevans](https://github.com/jeremyevans)) +- `Request#ssl?` is true for the `wss` scheme (secure websockets). ([@jeremyevans](https://github.com/jeremyevans)) +- `Rack::HeaderHash` is memoized by default. ([#1549](https://github.com/rack/rack/pull/1549), [@ioquatix](https://github.com/ioquatix)) +- `Rack::Directory` allow directory traversal inside root directory. ([#1417](https://github.com/rack/rack/pull/1417), [@ThomasSevestre](https://github.com/ThomasSevestre)) +- Sort encodings by server preference. ([#1184](https://github.com/rack/rack/pull/1184), [@ioquatix](https://github.com/ioquatix), [@wjordan](https://github.com/wjordan)) +- Rework host/hostname/authority implementation in `Rack::Request`. `#host` and `#host_with_port` have been changed to correctly return IPv6 addresses formatted with square brackets, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-3.2.2). ([#1561](https://github.com/rack/rack/pull/1561), [@ioquatix](https://github.com/ioquatix)) +- `Rack::Builder` parsing options on first `#\` line is deprecated. ([#1574](https://github.com/rack/rack/pull/1574), [@ioquatix](https://github.com/ioquatix)) + +### Removed + +- `Directory#path` as it was not used and always returned nil. ([@jeremyevans](https://github.com/jeremyevans)) +- `BodyProxy#each` as it was only needed to work around a bug in Ruby <1.9.3. ([@jeremyevans](https://github.com/jeremyevans)) +- `URLMap::INFINITY` and `URLMap::NEGATIVE_INFINITY`, in favor of `Float::INFINITY`. ([@ch1c0t](https://github.com/ch1c0t)) +- Deprecation of `Rack::File`. It will be deprecated again in rack 2.2 or 3.0. ([@rafaelfranca](https://github.com/rafaelfranca)) +- Support for Ruby 2.2 as it is well past EOL. ([@ioquatix](https://github.com/ioquatix)) +- Remove `Rack::Files#response_body` as the implementation was broken. ([#1153](https://github.com/rack/rack/pull/1153), [@ioquatix](https://github.com/ioquatix)) +- Remove `SERVER_ADDR` which was never part of the original SPEC. ([#1573](https://github.com/rack/rack/pull/1573), [@ioquatix](https://github.com/ioquatix)) + +### Fixed + +- `Directory` correctly handles root paths containing glob metacharacters. ([@jeremyevans](https://github.com/jeremyevans)) +- `Cascade` uses a new response object for each call if initialized with no apps. ([@jeremyevans](https://github.com/jeremyevans)) +- `BodyProxy` correctly delegates keyword arguments to the body object on Ruby 2.7+. ([@jeremyevans](https://github.com/jeremyevans)) +- `BodyProxy#method` correctly handles methods delegated to the body object. ([@jeremyevans](https://github.com/jeremyevans)) +- `Request#host` and `Request#host_with_port` handle IPv6 addresses correctly. ([@AlexWayfer](https://github.com/AlexWayfer)) +- `Lint` checks when response hijacking that `rack.hijack` is called with a valid object. ([@jeremyevans](https://github.com/jeremyevans)) +- `Response#write` correctly updates `Content-Length` if initialized with a body. ([@jeremyevans](https://github.com/jeremyevans)) +- `CommonLogger` includes `SCRIPT_NAME` when logging. ([@Erol](https://github.com/Erol)) +- `Utils.parse_nested_query` correctly handles empty queries, using an empty instance of the params class instead of a hash. ([@jeremyevans](https://github.com/jeremyevans)) +- `Directory` correctly escapes paths in links. ([@yous](https://github.com/yous)) +- `Request#delete_cookie` and related `Utils` methods handle `:domain` and `:path` options in same call. ([@jeremyevans](https://github.com/jeremyevans)) +- `Request#delete_cookie` and related `Utils` methods do an exact match on `:domain` and `:path` options. ([@jeremyevans](https://github.com/jeremyevans)) +- `Static` no longer adds headers when a gzipped file request has a 304 response. ([@chooh](https://github.com/chooh)) +- `ContentLength` sets `Content-Length` response header even for bodies not responding to `to_ary`. ([@jeremyevans](https://github.com/jeremyevans)) +- Thin handler supports options passed directly to `Thin::Controllers::Controller`. ([@jeremyevans](https://github.com/jeremyevans)) +- WEBrick handler no longer ignores `:BindAddress` option. ([@jeremyevans](https://github.com/jeremyevans)) +- `ShowExceptions` handles invalid POST data. ([@jeremyevans](https://github.com/jeremyevans)) +- Basic authentication requires a password, even if the password is empty. ([@jeremyevans](https://github.com/jeremyevans)) +- `Lint` checks response is array with 3 elements, per SPEC. ([@jeremyevans](https://github.com/jeremyevans)) +- Support for using `:SSLEnable` option when using WEBrick handler. (Gregor Melhorn) +- Close response body after buffering it when buffering. ([@ioquatix](https://github.com/ioquatix)) +- Only accept `;` as delimiter when parsing cookies. ([@mrageh](https://github.com/mrageh)) +- `Utils::HeaderHash#clear` clears the name mapping as well. ([@raxoft](https://github.com/raxoft)) +- Support for passing `nil` `Rack::Files.new`, which notably fixes Rails' current `ActiveStorage::FileServer` implementation. ([@ioquatix](https://github.com/ioquatix)) + +### Documentation + +- CHANGELOG updates. ([@aupajo](https://github.com/aupajo)) +- Added [CONTRIBUTING](CONTRIBUTING.md). ([@dblock](https://github.com/dblock)) + +## [2.1.2] - 2020-01-27 + +- Fix multipart parser for some files to prevent denial of service ([@aiomaster](https://github.com/aiomaster)) +- Fix `Rack::Builder#use` with keyword arguments ([@kamipo](https://github.com/kamipo)) +- Skip deflating in Rack::Deflater if Content-Length is 0 ([@jeremyevans](https://github.com/jeremyevans)) +- Remove `SessionHash#transform_keys`, no longer needed ([@pavel](https://github.com/pavel)) +- Add to_hash to wrap Hash and Session classes ([@oleh-demyanyuk](https://github.com/oleh-demyanyuk)) +- Handle case where session id key is requested but missing ([@jeremyevans](https://github.com/jeremyevans)) + +## [2.1.1] - 2020-01-12 + +- Remove `Rack::Chunked` from `Rack::Server` default middleware. ([#1475](https://github.com/rack/rack/pull/1475), [@ioquatix](https://github.com/ioquatix)) +- Restore support for code relying on `SessionId#to_s`. ([@jeremyevans](https://github.com/jeremyevans)) + +## [2.1.0] - 2020-01-10 + +### Added + +- Add support for `SameSite=None` cookie value. ([@hennikul](https://github.com/hennikul)) +- Add trailer headers. ([@eileencodes](https://github.com/eileencodes)) +- Add MIME Types for video streaming. ([@styd](https://github.com/styd)) +- Add MIME Type for WASM. ([@buildrtech](https://github.com/buildrtech)) +- Add `Early Hints(103)` to status codes. ([@egtra](https://github.com/egtra)) +- Add `Too Early(425)` to status codes. ([@y-yagi]((https://github.com/y-yagi))) +- Add `Bandwidth Limit Exceeded(509)` to status codes. ([@CJKinni](https://github.com/CJKinni)) +- Add method for custom `ip_filter`. ([@svcastaneda](https://github.com/svcastaneda)) +- Add boot-time profiling capabilities to `rackup`. ([@tenderlove](https://github.com/tenderlove)) +- Add multi mapping support for `X-Accel-Mappings` header. ([@yoshuki](https://github.com/yoshuki)) +- Add `sync: false` option to `Rack::Deflater`. (Eric Wong) +- Add `Builder#freeze_app` to freeze application and all middleware instances. ([@jeremyevans](https://github.com/jeremyevans)) +- Add API to extract cookies from `Rack::MockResponse`. ([@petercline](https://github.com/petercline)) + +### Changed + +- Don't propagate nil values from middleware. ([@ioquatix](https://github.com/ioquatix)) +- Lazily initialize the response body and only buffer it if required. ([@ioquatix](https://github.com/ioquatix)) +- Fix deflater zlib buffer errors on empty body part. ([@felixbuenemann](https://github.com/felixbuenemann)) +- Set `X-Accel-Redirect` to percent-encoded path. ([@diskkid](https://github.com/diskkid)) +- Remove unnecessary buffer growing when parsing multipart. ([@tainoe](https://github.com/tainoe)) +- Expand the root path in `Rack::Static` upon initialization. ([@rosenfeld](https://github.com/rosenfeld)) +- Make `ShowExceptions` work with binary data. ([@axyjo](https://github.com/axyjo)) +- Use buffer string when parsing multipart requests. ([@janko-m](https://github.com/janko-m)) +- Support optional UTF-8 Byte Order Mark (BOM) in config.ru. ([@mikegee](https://github.com/mikegee)) +- Handle `X-Forwarded-For` with optional port. ([@dpritchett](https://github.com/dpritchett)) +- Use `Time#httpdate` format for Expires, as proposed by RFC 7231. ([@nanaya](https://github.com/nanaya)) +- Make `Utils.status_code` raise an error when the status symbol is invalid instead of `500`. ([@adambutler](https://github.com/adambutler)) +- Rename `Request::SCHEME_WHITELIST` to `Request::ALLOWED_SCHEMES`. +- Make `Multipart::Parser.get_filename` accept files with `+` in their name. ([@lucaskanashiro](https://github.com/lucaskanashiro)) +- Add Falcon to the default handler fallbacks. ([@ioquatix](https://github.com/ioquatix)) +- Update codebase to avoid string mutations in preparation for `frozen_string_literals`. ([@pat](https://github.com/pat)) +- Change `MockRequest#env_for` to rely on the input optionally responding to `#size` instead of `#length`. ([@janko](https://github.com/janko)) +- Rename `Rack::File` -> `Rack::Files` and add deprecation notice. ([@postmodern](https://github.com/postmodern)). +- Prefer Base64 “strict encoding” for Base64 cookies. ([@ioquatix](https://github.com/ioquatix)) + +### Removed + +- Remove `to_ary` from Response ([@tenderlove](https://github.com/tenderlove)) +- Deprecate `Rack::Session::Memcache` in favor of `Rack::Session::Dalli` from dalli gem ([@fatkodima](https://github.com/fatkodima)) + +### Fixed + +- Eliminate warnings for Ruby 2.7. ([@osamtimizer](https://github.com/osamtimizer])) + +### Documentation + +- Update broken example in `Session::Abstract::ID` documentation. ([tonytonyjan](https://github.com/tonytonyjan)) +- Add Padrino to the list of frameworks implementing Rack. ([@wikimatze](https://github.com/wikimatze)) +- Remove Mongrel from the suggested server options in the help output. ([@tricknotes](https://github.com/tricknotes)) +- Replace `HISTORY.md` and `NEWS.md` with `CHANGELOG.md`. ([@twitnithegirl](https://github.com/twitnithegirl)) +- CHANGELOG updates. ([@drenmi](https://github.com/Drenmi), [@p8](https://github.com/p8)) + +## [2.0.8] - 2019-12-08 + +### Security + +- [[CVE-2019-16782](https://nvd.nist.gov/vuln/detail/CVE-2019-16782)] Prevent timing attacks targeted at session ID lookup. BREAKING CHANGE: Session ID is now a SessionId instance instead of a String. ([@tenderlove](https://github.com/tenderlove), [@rafaelfranca](https://github.com/rafaelfranca)) + +## [1.6.12] - 2019-12-08 + +### Security + +- [[CVE-2019-16782](https://nvd.nist.gov/vuln/detail/CVE-2019-16782)] Prevent timing attacks targeted at session ID lookup. BREAKING CHANGE: Session ID is now a SessionId instance instead of a String. ([@tenderlove](https://github.com/tenderlove), [@rafaelfranca](https://github.com/rafaelfranca)) + +## [2.0.7] - 2019-04-02 + +### Fixed + +- Remove calls to `#eof?` on Rack input in `Multipart::Parser`, as this breaks the specification. ([@matthewd](https://github.com/matthewd)) +- Preserve forwarded IP addresses for trusted proxy chains. ([@SamSaffron](https://github.com/SamSaffron)) + +## [2.0.6] - 2018-11-05 + +### Fixed + +- [[CVE-2018-16470](https://nvd.nist.gov/vuln/detail/CVE-2018-16470)] Reduce buffer size of `Multipart::Parser` to avoid pathological parsing. ([@tenderlove](https://github.com/tenderlove)) +- Fix a call to a non-existing method `#accepts_html` in the `ShowExceptions` middleware. ([@tomelm](https://github.com/tomelm)) +- [[CVE-2018-16471](https://nvd.nist.gov/vuln/detail/CVE-2018-16471)] Whitelist HTTP and HTTPS schemes in `Request#scheme` to prevent a possible XSS attack. ([@PatrickTulskie](https://github.com/PatrickTulskie)) + +## [2.0.5] - 2018-04-23 + +### Fixed + +- Record errors originating from invalid UTF8 in `MethodOverride` middleware instead of breaking. ([@mclark](https://github.com/mclark)) + +## [2.0.4] - 2018-01-31 + +### Changed + +- Ensure the `Lock` middleware passes the original `env` object. ([@lugray](https://github.com/lugray)) +- Improve performance of `Multipart::Parser` when uploading large files. ([@tompng](https://github.com/tompng)) +- Increase buffer size in `Multipart::Parser` for better performance. ([@jkowens](https://github.com/jkowens)) +- Reduce memory usage of `Multipart::Parser` when uploading large files. ([@tompng](https://github.com/tompng)) +- Replace ConcurrentRuby dependency with native `Queue`. ([@devmchakan](https://github.com/devmchakan)) + +### Fixed + +- Require the correct digest algorithm in the `ETag` middleware. ([@matthewd](https://github.com/matthewd)) + +### Documentation + +- Update homepage links to use SSL. ([@hugoabonizio](https://github.com/hugoabonizio)) + +## [2.0.3] - 2017-05-15 + +### Changed + +- Ensure `env` values are ASCII 8-bit encoded. ([@eileencodes](https://github.com/eileencodes)) + +### Fixed + +- Prevent exceptions when a class with mixins inherits from `Session::Abstract::ID`. ([@jnraine](https://github.com/jnraine)) + +## [2.0.2] - 2017-05-08 + +### Added + +- Allow `Session::Abstract::SessionHash#fetch` to accept a block with a default value. ([@yannvanhalewyn](https://github.com/yannvanhalewyn)) +- Add `Builder#freeze_app` to freeze application and all middleware. ([@jeremyevans](https://github.com/jeremyevans)) + +### Changed + +- Freeze default session options to avoid accidental mutation. ([@kirs](https://github.com/kirs)) +- Detect partial hijack without hash headers. ([@devmchakan](https://github.com/devmchakan)) +- Update tests to use MiniTest 6 matchers. ([@tonytonyjan](https://github.com/tonytonyjan)) +- Allow 205 Reset Content responses to set a Content-Length, as RFC 7231 proposes setting this to 0. ([@devmchakan](https://github.com/devmchakan)) + +### Fixed + +- Handle `NULL` bytes in multipart filenames. ([@casperisfine](https://github.com/casperisfine)) +- Remove warnings due to miscapitalized global. ([@ioquatix](https://github.com/ioquatix)) +- Prevent exceptions caused by a race condition on multi-threaded servers. ([@sophiedeziel](https://github.com/sophiedeziel)) +- Add RDoc as an explicit depencency for `doc` group. ([@tonytonyjan](https://github.com/tonytonyjan)) +- Record errors originating from `Multipart::Parser` in the `MethodOverride` middleware instead of letting them bubble up. ([@carlzulauf](https://github.com/carlzulauf)) +- Remove remaining use of removed `Utils#bytesize` method from the `File` middleware. ([@brauliomartinezlm](https://github.com/brauliomartinezlm)) + +### Removed + +- Remove `deflate` encoding support to reduce caching overhead. ([@devmchakan](https://github.com/devmchakan)) + +### Documentation + +- Update broken example in `Deflater` documentation. ([@mwpastore](https://github.com/mwpastore)) + +## [2.0.1] - 2016-06-30 + +### Changed + +- Remove JSON as an explicit dependency. ([@mperham](https://github.com/mperham)) + + +# History/News Archive +Items below this line are from the previously maintained HISTORY.md and NEWS.md files. + +## [2.0.0.rc1] 2016-05-06 +- Rack::Session::Abstract::ID is deprecated. Please change to use Rack::Session::Abstract::Persisted + +## [2.0.0.alpha] 2015-12-04 +- First-party "SameSite" cookies. Browsers omit SameSite cookies from third-party requests, closing the door on many CSRF attacks. +- Pass `same_site: true` (or `:strict`) to enable: response.set_cookie 'foo', value: 'bar', same_site: true or `same_site: :lax` to use Lax enforcement: response.set_cookie 'foo', value: 'bar', same_site: :lax +- Based on version 7 of the Same-site Cookies internet draft: + https://tools.ietf.org/html/draft-west-first-party-cookies-07 +- Thanks to Ben Toews (@mastahyeti) and Bob Long (@bobjflong) for updating to drafts 5 and 7. +- Add `Rack::Events` middleware for adding event based middleware: middleware that does not care about the response body, but only cares about doing work at particular points in the request / response lifecycle. +- Add `Rack::Request#authority` to calculate the authority under which the response is being made (this will be handy for h2 pushes). +- Add `Rack::Response::Helpers#cache_control` and `cache_control=`. Use this for setting cache control headers on your response objects. +- Add `Rack::Response::Helpers#etag` and `etag=`. Use this for setting etag values on the response. +- Introduce `Rack::Response::Helpers#add_header` to add a value to a multi-valued response header. Implemented in terms of other `Response#*_header` methods, so it's available to any response-like class that includes the `Helpers` module. +- Add `Rack::Request#add_header` to match. +- `Rack::Session::Abstract::ID` IS DEPRECATED. Please switch to `Rack::Session::Abstract::Persisted`. `Rack::Session::Abstract::Persisted` uses a request object rather than the `env` hash. +- Pull `ENV` access inside the request object in to a module. This will help with legacy Request objects that are ENV based but don't want to inherit from Rack::Request +- Move most methods on the `Rack::Request` to a module `Rack::Request::Helpers` and use public API to get values from the request object. This enables users to mix `Rack::Request::Helpers` in to their own objects so they can implement `(get|set|fetch|each)_header` as they see fit (for example a proxy object). +- Files and directories with + in the name are served correctly. Rather than unescaping paths like a form, we unescape with a URI parser using `Rack::Utils.unescape_path`. Fixes #265 +- Tempfiles are automatically closed in the case that there were too + many posted. +- Added methods for manipulating response headers that don't assume + they're stored as a Hash. Response-like classes may include the + Rack::Response::Helpers module if they define these methods: + - Rack::Response#has_header? + - Rack::Response#get_header + - Rack::Response#set_header + - Rack::Response#delete_header +- Introduce Util.get_byte_ranges that will parse the value of the HTTP_RANGE string passed to it without depending on the `env` hash. `byte_ranges` is deprecated in favor of this method. +- Change Session internals to use Request objects for looking up session information. This allows us to only allocate one request object when dealing with session objects (rather than doing it every time we need to manipulate cookies, etc). +- Add `Rack::Request#initialize_copy` so that the env is duped when the request gets duped. +- Added methods for manipulating request specific data. This includes + data set as CGI parameters, and just any arbitrary data the user wants + to associate with a particular request. New methods: + - Rack::Request#has_header? + - Rack::Request#get_header + - Rack::Request#fetch_header + - Rack::Request#each_header + - Rack::Request#set_header + - Rack::Request#delete_header +- lib/rack/utils.rb: add a method for constructing "delete" cookie + headers. This allows us to construct cookie headers without depending + on the side effects of mutating a hash. +- Prevent extremely deep parameters from being parsed. CVE-2015-3225 + +## [1.6.1] 2015-05-06 + - Fix CVE-2014-9490, denial of service attack in OkJson + - Use a monotonic time for Rack::Runtime, if available + - RACK_MULTIPART_LIMIT changed to RACK_MULTIPART_PART_LIMIT (RACK_MULTIPART_LIMIT is deprecated and will be removed in 1.7.0) + +## [1.5.3] 2015-05-06 + - Fix CVE-2014-9490, denial of service attack in OkJson + - Backport bug fixes to 1.5 series + +## [1.6.0] 2014-01-18 + - Response#unauthorized? helper + - Deflater now accepts an options hash to control compression on a per-request level + - Builder#warmup method for app preloading + - Request#accept_language method to extract HTTP_ACCEPT_LANGUAGE + - Add quiet mode of rack server, rackup --quiet + - Update HTTP Status Codes to RFC 7231 + - Less strict header name validation according to RFC 2616 + - SPEC updated to specify headers conform to RFC7230 specification + - Etag correctly marks etags as weak + - Request#port supports multiple x-http-forwarded-proto values + - Utils#multipart_part_limit configures the maximum number of parts a request can contain + - Default host to localhost when in development mode + - Various bugfixes and performance improvements + +## [1.5.2] 2013-02-07 + - Fix CVE-2013-0263, timing attack against Rack::Session::Cookie + - Fix CVE-2013-0262, symlink path traversal in Rack::File + - Add various methods to Session for enhanced Rails compatibility + - Request#trusted_proxy? now only matches whole strings + - Add JSON cookie coder, to be default in Rack 1.6+ due to security concerns + - URLMap host matching in environments that don't set the Host header fixed + - Fix a race condition that could result in overwritten pidfiles + - Various documentation additions + +## [1.4.5] 2013-02-07 + - Fix CVE-2013-0263, timing attack against Rack::Session::Cookie + - Fix CVE-2013-0262, symlink path traversal in Rack::File + +## [1.1.6, 1.2.8, 1.3.10] 2013-02-07 + - Fix CVE-2013-0263, timing attack against Rack::Session::Cookie + +## [1.5.1] 2013-01-28 + - Rack::Lint check_hijack now conforms to other parts of SPEC + - Added hash-like methods to Abstract::ID::SessionHash for compatibility + - Various documentation corrections + +## [1.5.0] 2013-01-21 + - Introduced hijack SPEC, for before-response and after-response hijacking + - SessionHash is no longer a Hash subclass + - Rack::File cache_control parameter is removed, in place of headers options + - Rack::Auth::AbstractRequest#scheme now yields strings, not symbols + - Rack::Utils cookie functions now format expires in RFC 2822 format + - Rack::File now has a default mime type + - rackup -b 'run Rack::Files.new(".")', option provides command line configs + - Rack::Deflater will no longer double encode bodies + - Rack::Mime#match? provides convenience for Accept header matching + - Rack::Utils#q_values provides splitting for Accept headers + - Rack::Utils#best_q_match provides a helper for Accept headers + - Rack::Handler.pick provides convenience for finding available servers + - Puma added to the list of default servers (preferred over Webrick) + - Various middleware now correctly close body when replacing it + - Rack::Request#params is no longer persistent with only GET params + - Rack::Request#update_param and #delete_param provide persistent operations + - Rack::Request#trusted_proxy? now returns true for local unix sockets + - Rack::Response no longer forces Content-Types + - Rack::Sendfile provides local mapping configuration options + - Rack::Utils#rfc2109 provides old netscape style time output + - Updated HTTP status codes + - Ruby 1.8.6 likely no longer passes tests, and is no longer fully supported + +## [1.4.4, 1.3.9, 1.2.7, 1.1.5] 2013-01-13 + - [SEC] Rack::Auth::AbstractRequest no longer symbolizes arbitrary strings + - Fixed erroneous test case in the 1.3.x series + +## [1.4.3] 2013-01-07 + - Security: Prevent unbounded reads in large multipart boundaries + +## [1.3.8] 2013-01-07 + - Security: Prevent unbounded reads in large multipart boundaries + +## [1.4.2] 2013-01-06 + - Add warnings when users do not provide a session secret + - Fix parsing performance for unquoted filenames + - Updated URI backports + - Fix URI backport version matching, and silence constant warnings + - Correct parameter parsing with empty values + - Correct rackup '-I' flag, to allow multiple uses + - Correct rackup pidfile handling + - Report rackup line numbers correctly + - Fix request loops caused by non-stale nonces with time limits + - Fix reloader on Windows + - Prevent infinite recursions from Response#to_ary + - Various middleware better conforms to the body close specification + - Updated language for the body close specification + - Additional notes regarding ECMA escape compatibility issues + - Fix the parsing of multiple ranges in range headers + - Prevent errors from empty parameter keys + - Added PATCH verb to Rack::Request + - Various documentation updates + - Fix session merge semantics (fixes rack-test) + - Rack::Static :index can now handle multiple directories + - All tests now utilize Rack::Lint (special thanks to Lars Gierth) + - Rack::File cache_control parameter is now deprecated, and removed by 1.5 + - Correct Rack::Directory script name escaping + - Rack::Static supports header rules for sophisticated configurations + - Multipart parsing now works without a Content-Length header + - New logos courtesy of Zachary Scott! + - Rack::BodyProxy now explicitly defines #each, useful for C extensions + - Cookies that are not URI escaped no longer cause exceptions + +## [1.3.7] 2013-01-06 + - Add warnings when users do not provide a session secret + - Fix parsing performance for unquoted filenames + - Updated URI backports + - Fix URI backport version matching, and silence constant warnings + - Correct parameter parsing with empty values + - Correct rackup '-I' flag, to allow multiple uses + - Correct rackup pidfile handling + - Report rackup line numbers correctly + - Fix request loops caused by non-stale nonces with time limits + - Fix reloader on Windows + - Prevent infinite recursions from Response#to_ary + - Various middleware better conforms to the body close specification + - Updated language for the body close specification + - Additional notes regarding ECMA escape compatibility issues + - Fix the parsing of multiple ranges in range headers + +## [1.2.6] 2013-01-06 + - Add warnings when users do not provide a session secret + - Fix parsing performance for unquoted filenames + +## [1.1.4] 2013-01-06 + - Add warnings when users do not provide a session secret + +## [1.4.1] 2012-01-22 + - Alter the keyspace limit calculations to reduce issues with nested params + - Add a workaround for multipart parsing where files contain unescaped "%" + - Added Rack::Response::Helpers#method_not_allowed? (code 405) + - Rack::File now returns 404 for illegal directory traversals + - Rack::File now returns 405 for illegal methods (non HEAD/GET) + - Rack::Cascade now catches 405 by default, as well as 404 + - Cookies missing '--' no longer cause an exception to be raised + - Various style changes and documentation spelling errors + - Rack::BodyProxy always ensures to execute its block + - Additional test coverage around cookies and secrets + - Rack::Session::Cookie can now be supplied either secret or old_secret + - Tests are no longer dependent on set order + - Rack::Static no longer defaults to serving index files + - Rack.release was fixed + +## [1.4.0] 2011-12-28 + - Ruby 1.8.6 support has officially been dropped. Not all tests pass. + - Raise sane error messages for broken config.ru + - Allow combining run and map in a config.ru + - Rack::ContentType will not set Content-Type for responses without a body + - Status code 205 does not send a response body + - Rack::Response::Helpers will not rely on instance variables + - Rack::Utils.build_query no longer outputs '=' for nil query values + - Various mime types added + - Rack::MockRequest now supports HEAD + - Rack::Directory now supports files that contain RFC3986 reserved chars + - Rack::File now only supports GET and HEAD requests + - Rack::Server#start now passes the block to Rack::Handler::#run + - Rack::Static now supports an index option + - Added the Teapot status code + - rackup now defaults to Thin instead of Mongrel (if installed) + - Support added for HTTP_X_FORWARDED_SCHEME + - Numerous bug fixes, including many fixes for new and alternate rubies + +## [1.1.3] 2011-12-28 + - Security fix. http://www.ocert.org/advisories/ocert-2011-003.html + Further information here: http://jruby.org/2011/12/27/jruby-1-6-5-1 + +## [1.3.5] 2011-10-17 + - Fix annoying warnings caused by the backport in 1.3.4 + +## [1.3.4] 2011-10-01 + - Backport security fix from 1.9.3, also fixes some roundtrip issues in URI + - Small documentation update + - Fix an issue where BodyProxy could cause an infinite recursion + - Add some supporting files for travis-ci + +## [1.2.4] 2011-09-16 + - Fix a bug with MRI regex engine to prevent XSS by malformed unicode + +## [1.3.3] 2011-09-16 + - Fix bug with broken query parameters in Rack::ShowExceptions + - Rack::Request#cookies no longer swallows exceptions on broken input + - Prevents XSS attacks enabled by bug in Ruby 1.8's regexp engine + - Rack::ConditionalGet handles broken If-Modified-Since helpers + +## [1.3.2] 2011-07-16 + - Fix for Rails and rack-test, Rack::Utils#escape calls to_s + +## [1.3.1] 2011-07-13 + - Fix 1.9.1 support + - Fix JRuby support + - Properly handle $KCODE in Rack::Utils.escape + - Make method_missing/respond_to behavior consistent for Rack::Lock, + Rack::Auth::Digest::Request and Rack::Multipart::UploadedFile + - Reenable passing rack.session to session middleware + - Rack::CommonLogger handles streaming responses correctly + - Rack::MockResponse calls close on the body object + - Fix a DOS vector from MRI stdlib backport + +## [1.2.3] 2011-05-22 + - Pulled in relevant bug fixes from 1.3 + - Fixed 1.8.6 support + +## [1.3.0] 2011-05-22 + - Various performance optimizations + - Various multipart fixes + - Various multipart refactors + - Infinite loop fix for multipart + - Test coverage for Rack::Server returns + - Allow files with '..', but not path components that are '..' + - rackup accepts handler-specific options on the command line + - Request#params no longer merges POST into GET (but returns the same) + - Use URI.encode_www_form_component instead. Use core methods for escaping. + - Allow multi-line comments in the config file + - Bug L#94 reported by Nikolai Lugovoi, query parameter unescaping. + - Rack::Response now deletes Content-Length when appropriate + - Rack::Deflater now supports streaming + - Improved Rack::Handler loading and searching + - Support for the PATCH verb + - env['rack.session.options'] now contains session options + - Cookies respect renew + - Session middleware uses SecureRandom.hex + +## [1.2.2, 1.1.2] 2011-03-13 + - Security fix in Rack::Auth::Digest::MD5: when authenticator + returned nil, permission was granted on empty password. + +## [1.2.1] 2010-06-15 + - Make CGI handler rewindable + - Rename spec/ to test/ to not conflict with SPEC on lesser + operating systems + +## [1.2.0] 2010-06-13 + - Removed Camping adapter: Camping 2.0 supports Rack as-is + - Removed parsing of quoted values + - Add Request.trace? and Request.options? + - Add mime-type for .webm and .htc + - Fix HTTP_X_FORWARDED_FOR + - Various multipart fixes + - Switch test suite to bacon + +## [1.1.0] 2010-01-03 + - Moved Auth::OpenID to rack-contrib. + - SPEC change that relaxes Lint slightly to allow subclasses of the + required types + - SPEC change to document rack.input binary mode in greator detail + - SPEC define optional rack.logger specification + - File servers support X-Cascade header + - Imported Config middleware + - Imported ETag middleware + - Imported Runtime middleware + - Imported Sendfile middleware + - New Logger and NullLogger middlewares + - Added mime type for .ogv and .manifest. + - Don't squeeze PATH_INFO slashes + - Use Content-Type to determine POST params parsing + - Update Rack::Utils::HTTP_STATUS_CODES hash + - Add status code lookup utility + - Response should call #to_i on the status + - Add Request#user_agent + - Request#host knows about forwarded host + - Return an empty string for Request#host if HTTP_HOST and + SERVER_NAME are both missing + - Allow MockRequest to accept hash params + - Optimizations to HeaderHash + - Refactored rackup into Rack::Server + - Added Utils.build_nested_query to complement Utils.parse_nested_query + - Added Utils::Multipart.build_multipart to complement + Utils::Multipart.parse_multipart + - Extracted set and delete cookie helpers into Utils so they can be + used outside Response + - Extract parse_query and parse_multipart in Request so subclasses + can change their behavior + - Enforce binary encoding in RewindableInput + - Set correct external_encoding for handlers that don't use RewindableInput + +## [1.0.1] 2009-10-18 + - Bump remainder of rack.versions. + - Support the pure Ruby FCGI implementation. + - Fix for form names containing "=": split first then unescape components + - Fixes the handling of the filename parameter with semicolons in names. + - Add anchor to nested params parsing regexp to prevent stack overflows + - Use more compatible gzip write api instead of "<<". + - Make sure that Reloader doesn't break when executed via ruby -e + - Make sure WEBrick respects the :Host option + - Many Ruby 1.9 fixes. + +## [1.0.0] 2009-04-25 + - SPEC change: Rack::VERSION has been pushed to [1,0]. + - SPEC change: header values must be Strings now, split on "\n". + - SPEC change: Content-Length can be missing, in this case chunked transfer + encoding is used. + - SPEC change: rack.input must be rewindable and support reading into + a buffer, wrap with Rack::RewindableInput if it isn't. + - SPEC change: rack.session is now specified. + - SPEC change: Bodies can now additionally respond to #to_path with + a filename to be served. + - NOTE: String bodies break in 1.9, use an Array consisting of a + single String instead. + - New middleware Rack::Lock. + - New middleware Rack::ContentType. + - Rack::Reloader has been rewritten. + - Major update to Rack::Auth::OpenID. + - Support for nested parameter parsing in Rack::Response. + - Support for redirects in Rack::Response. + - HttpOnly cookie support in Rack::Response. + - The Rakefile has been rewritten. + - Many bugfixes and small improvements. + +## [0.9.1] 2009-01-09 + - Fix directory traversal exploits in Rack::File and Rack::Directory. + +## [0.9] 2009-01-06 + - Rack is now managed by the Rack Core Team. + - Rack::Lint is stricter and follows the HTTP RFCs more closely. + - Added ConditionalGet middleware. + - Added ContentLength middleware. + - Added Deflater middleware. + - Added Head middleware. + - Added MethodOverride middleware. + - Rack::Mime now provides popular MIME-types and their extension. + - Mongrel Header now streams. + - Added Thin handler. + - Official support for swiftiplied Mongrel. + - Secure cookies. + - Made HeaderHash case-preserving. + - Many bugfixes and small improvements. + +## [0.4] 2008-08-21 + - New middleware, Rack::Deflater, by Christoffer Sawicki. + - OpenID authentication now needs ruby-openid 2. + - New Memcache sessions, by blink. + - Explicit EventedMongrel handler, by Joshua Peek + - Rack::Reloader is not loaded in rackup development mode. + - rackup can daemonize with -D. + - Many bugfixes, especially for pool sessions, URLMap, thread safety + and tempfile handling. + - Improved tests. + - Rack moved to Git. + +## [0.3] 2008-02-26 + - LiteSpeed handler, by Adrian Madrid. + - SCGI handler, by Jeremy Evans. + - Pool sessions, by blink. + - OpenID authentication, by blink. + - :Port and :File options for opening FastCGI sockets, by blink. + - Last-Modified HTTP header for Rack::File, by blink. + - Rack::Builder#use now accepts blocks, by Corey Jewett. + (See example/protectedlobster.ru) + - HTTP status 201 can contain a Content-Type and a body now. + - Many bugfixes, especially related to Cookie handling. + +## [0.2] 2007-05-16 + - HTTP Basic authentication. + - Cookie Sessions. + - Static file handler. + - Improved Rack::Request. + - Improved Rack::Response. + - Added Rack::ShowStatus, for better default error messages. + - Bug fixes in the Camping adapter. + - Removed Rails adapter, was too alpha. + +## [0.1] 2007-03-03 diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/CONTRIBUTING.md b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/CONTRIBUTING.md new file mode 100644 index 0000000..70a2746 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/CONTRIBUTING.md @@ -0,0 +1,136 @@ +Contributing to Rack +===================== + +Rack is work of [hundreds of contributors](https://github.com/rack/rack/graphs/contributors). You're encouraged to submit [pull requests](https://github.com/rack/rack/pulls), [propose features and discuss issues](https://github.com/rack/rack/issues). When in doubt, post to the [rack-devel](http://groups.google.com/group/rack-devel) mailing list. + +#### Fork the Project + +Fork the [project on Github](https://github.com/rack/rack) and check out your copy. + +``` +git clone https://github.com/contributor/rack.git +cd rack +git remote add upstream https://github.com/rack/rack.git +``` + +#### Create a Topic Branch + +Make sure your fork is up-to-date and create a topic branch for your feature or bug fix. + +``` +git checkout master +git pull upstream master +git checkout -b my-feature-branch +``` + +#### Bundle Install and Quick Test + +Ensure that you can build the project and run quick tests. + +``` +bundle install --without extra +bundle exec rake test +``` + +#### Running All Tests + +Install all dependencies. + +``` +bundle install +``` + +Run all tests. + +``` +rake test +``` + +The test suite has no dependencies outside of the core Ruby installation and bacon. + +Some tests will be skipped if a dependency is not found. + +To run the test suite completely, you need: + + * fcgi + * dalli + * thin + +To test Memcache sessions, you need memcached (will be run on port 11211) and dalli installed. + +#### Write Tests + +Try to write a test that reproduces the problem you're trying to fix or describes a feature that you want to build. + +We definitely appreciate pull requests that highlight or reproduce a problem, even without a fix. + +#### Write Code + +Implement your feature or bug fix. + +Make sure that `bundle exec rake fulltest` completes without errors. + +#### Write Documentation + +Document any external behavior in the [README](README.rdoc). + +#### Update Changelog + +Add a line to [CHANGELOG](CHANGELOG.md). + +#### Commit Changes + +Make sure git knows your name and email address: + +``` +git config --global user.name "Your Name" +git config --global user.email "contributor@example.com" +``` + +Writing good commit logs is important. A commit log should describe what changed and why. + +``` +git add ... +git commit +``` + +#### Push + +``` +git push origin my-feature-branch +``` + +#### Make a Pull Request + +Go to https://github.com/contributor/rack and select your feature branch. Click the 'Pull Request' button and fill out the form. Pull requests are usually reviewed within a few days. + +#### Rebase + +If you've been working on a change for a while, rebase with upstream/master. + +``` +git fetch upstream +git rebase upstream/master +git push origin my-feature-branch -f +``` + +#### Make Required Changes + +Amend your previous commit and force push the changes. + +``` +git commit --amend +git push origin my-feature-branch -f +``` + +#### Check on Your Pull Request + +Go back to your pull request after a few minutes and see whether it passed muster with Travis-CI. Everything should look green, otherwise fix issues and amend your commit as described above. + +#### Be Patient + +It's likely that your change will not be merged and that the nitpicky maintainers will ask you to do more, or fix seemingly benign problems. Hang on there! + +#### Thank You + +Please do know that we really appreciate and value your time and work. We love you, really. diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/MIT-LICENSE b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/MIT-LICENSE new file mode 100644 index 0000000..703d118 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/MIT-LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (C) 2007-2019 Leah Neukirchen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/README.rdoc b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/README.rdoc new file mode 100644 index 0000000..8533846 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/README.rdoc @@ -0,0 +1,306 @@ += \Rack, a modular Ruby webserver interface + +{rack powers web applications}[https://rack.github.io/] + +{CircleCI}[https://circleci.com/gh/rack/rack] +{Gem Version}[http://badge.fury.io/rb/rack] +{SemVer Stability}[https://dependabot.com/compatibility-score.html?dependency-name=rack&package-manager=bundler&version-scheme=semver] +{Inline docs}[http://inch-ci.org/github/rack/rack] + +\Rack provides a minimal, modular, and adaptable interface for developing +web applications in Ruby. By wrapping HTTP requests and responses in +the simplest way possible, it unifies and distills the API for web +servers, web frameworks, and software in between (the so-called +middleware) into a single method call. + +The exact details of this are described in the \Rack specification, +which all \Rack applications should conform to. + +== Supported web servers + +The included *handlers* connect all kinds of web servers to \Rack: + +* WEBrick[https://github.com/ruby/webrick] +* FCGI +* CGI +* SCGI +* LiteSpeed[https://www.litespeedtech.com/] +* Thin[https://rubygems.org/gems/thin] + +These web servers include \Rack handlers in their distributions: + +* Agoo[https://github.com/ohler55/agoo] +* Falcon[https://github.com/socketry/falcon] +* Iodine[https://github.com/boazsegev/iodine] +* {NGINX Unit}[https://unit.nginx.org/] +* {Phusion Passenger}[https://www.phusionpassenger.com/] (which is mod_rack for Apache and for nginx) +* Puma[https://puma.io/] +* Unicorn[https://yhbt.net/unicorn/] +* uWSGI[https://uwsgi-docs.readthedocs.io/en/latest/] + +Any valid \Rack app will run the same on all these handlers, without +changing anything. + +== Supported web frameworks + +These frameworks and many others support the \Rack API: + +* Camping[http://www.ruby-camping.com/] +* Coset[http://leahneukirchen.org/repos/coset/] +* Hanami[https://hanamirb.org/] +* Padrino[http://padrinorb.com/] +* Ramaze[http://ramaze.net/] +* Roda[https://github.com/jeremyevans/roda] +* {Ruby on Rails}[https://rubyonrails.org/] +* Rum[https://github.com/leahneukirchen/rum] +* Sinatra[http://sinatrarb.com/] +* Utopia[https://github.com/socketry/utopia] +* WABuR[https://github.com/ohler55/wabur] + +== Available middleware shipped with \Rack + +Between the server and the framework, \Rack can be customized to your +applications needs using middleware. \Rack itself ships with the following +middleware: + +* Rack::Chunked, for streaming responses using chunked encoding. +* Rack::CommonLogger, for creating Apache-style logfiles. +* Rack::ConditionalGet, for returning not modified responses when the response + has not changed. +* Rack::Config, for modifying the environment before processing the request. +* Rack::ContentLength, for setting Content-Length header based on body size. +* Rack::ContentType, for setting default Content-Type header for responses. +* Rack::Deflater, for compressing responses with gzip. +* Rack::ETag, for setting ETag header on string bodies. +* Rack::Events, for providing easy hooks when a request is received + and when the response is sent. +* Rack::Files, for serving static files. +* Rack::Head, for returning an empty body for HEAD requests. +* Rack::Lint, for checking conformance to the \Rack API. +* Rack::Lock, for serializing requests using a mutex. +* Rack::Logger, for setting a logger to handle logging errors. +* Rack::MethodOverride, for modifying the request method based on a submitted + parameter. +* Rack::Recursive, for including data from other paths in the application, + and for performing internal redirects. +* Rack::Reloader, for reloading files if they have been modified. +* Rack::Runtime, for including a response header with the time taken to + process the request. +* Rack::Sendfile, for working with web servers that can use optimized + file serving for file system paths. +* Rack::ShowException, for catching unhandled exceptions and + presenting them in a nice and helpful way with clickable backtrace. +* Rack::ShowStatus, for using nice error pages for empty client error + responses. +* Rack::Static, for more configurable serving of static files. +* Rack::TempfileReaper, for removing temporary files creating during a + request. + +All these components use the same interface, which is described in +detail in the \Rack specification. These optional components can be +used in any way you wish. + +== Convenience + +If you want to develop outside of existing frameworks, implement your +own ones, or develop middleware, \Rack provides many helpers to create +\Rack applications quickly and without doing the same web stuff all +over: + +* Rack::Request, which also provides query string parsing and + multipart handling. +* Rack::Response, for convenient generation of HTTP replies and + cookie handling. +* Rack::MockRequest and Rack::MockResponse for efficient and quick + testing of \Rack application without real HTTP round-trips. +* Rack::Cascade, for trying additional \Rack applications if an + application returns a not found or method not supported response. +* Rack::Directory, for serving files under a given directory, with + directory indexes. +* Rack::MediaType, for parsing Content-Type headers. +* Rack::Mime, for determining Content-Type based on file extension. +* Rack::RewindableInput, for making any IO object rewindable, using + a temporary file buffer. +* Rack::URLMap, to route to multiple applications inside the same process. + +== rack-contrib + +The plethora of useful middleware created the need for a project that +collects fresh \Rack middleware. rack-contrib includes a variety of +add-on components for \Rack and it is easy to contribute new modules. + +* https://github.com/rack/rack-contrib + +== rackup + +rackup is a useful tool for running \Rack applications, which uses the +Rack::Builder DSL to configure middleware and build up applications +easily. + +rackup automatically figures out the environment it is run in, and +runs your application as FastCGI, CGI, or WEBrick---all from the +same configuration. + +== Quick start + +Try the lobster! + +Either with the embedded WEBrick starter: + + ruby -Ilib lib/rack/lobster.rb + +Or with rackup: + + bin/rackup -Ilib example/lobster.ru + +By default, the lobster is found at http://localhost:9292. + +== Installing with RubyGems + +A Gem of \Rack is available at {rubygems.org}[https://rubygems.org/gems/rack]. You can install it with: + + gem install rack + +== Usage + +You should require the library: + + require 'rack' + +\Rack uses autoload to automatically load other files \Rack ships with on demand, +so you should not need require paths under +rack+. If you require paths under ++rack+ without requiring +rack+ itself, things may not work correctly. + +== Configuration + +Several parameters can be modified on Rack::Utils to configure \Rack behaviour. + +e.g: + + Rack::Utils.key_space_limit = 128 + +=== key_space_limit + +The default number of bytes to allow all parameters keys in a given parameter hash to take up. +Does not affect nested parameter hashes, so doesn't actually prevent an attacker from using +more than this many bytes for parameter keys. + +Defaults to 65536 characters. + +=== param_depth_limit + +The maximum amount of nesting allowed in parameters. +For example, if set to 3, this query string would be allowed: + + ?a[b][c]=d + +but this query string would not be allowed: + + ?a[b][c][d]=e + +Limiting the depth prevents a possible stack overflow when parsing parameters. + +Defaults to 100. + +=== multipart_part_limit + +The maximum number of parts a request can contain. +Accepting too many part can lead to the server running out of file handles. + +The default is 128, which means that a single request can't upload more than 128 files at once. + +Set to 0 for no limit. + +Can also be set via the +RACK_MULTIPART_PART_LIMIT+ environment variable. + +== Changelog + +See {CHANGELOG.md}[https://github.com/rack/rack/blob/master/CHANGELOG.md]. + +== Contributing + +See {CONTRIBUTING.md}[https://github.com/rack/rack/blob/master/CONTRIBUTING.md]. + +== Contact + +Please post bugs, suggestions and patches to +the bug tracker at {issues}[https://github.com/rack/rack/issues]. + +Please post security related bugs and suggestions to the core team at + or rack-core@googlegroups.com. This +list is not public. Due to wide usage of the library, it is strongly preferred +that we manage timing in order to provide viable patches at the time of +disclosure. Your assistance in this matter is greatly appreciated. + +Mailing list archives are available at +. + +Git repository (send Git patches to the mailing list): + +* https://github.com/rack/rack + +You are also welcome to join the #rack channel on irc.freenode.net. + +== Thanks + +The \Rack Core Team, consisting of + +* Aaron Patterson (tenderlove[https://github.com/tenderlove]) +* Samuel Williams (ioquatix[https://github.com/ioquatix]) +* Jeremy Evans (jeremyevans[https://github.com/jeremyevans]) +* Eileen Uchitelle (eileencodes[https://github.com/eileencodes]) +* Matthew Draper (matthewd[https://github.com/matthewd]) +* Rafael França (rafaelfranca[https://github.com/rafaelfranca]) + +and the \Rack Alumni + +* Ryan Tomayko (rtomayko[https://github.com/rtomayko]) +* Scytrin dai Kinthra (scytrin[https://github.com/scytrin]) +* Leah Neukirchen (leahneukirchen[https://github.com/leahneukirchen]) +* James Tucker (raggi[https://github.com/raggi]) +* Josh Peek (josh[https://github.com/josh]) +* José Valim (josevalim[https://github.com/josevalim]) +* Michael Fellinger (manveru[https://github.com/manveru]) +* Santiago Pastorino (spastorino[https://github.com/spastorino]) +* Konstantin Haase (rkh[https://github.com/rkh]) + +would like to thank: + +* Adrian Madrid, for the LiteSpeed handler. +* Christoffer Sawicki, for the first Rails adapter and Rack::Deflater. +* Tim Fletcher, for the HTTP authentication code. +* Luc Heinrich for the Cookie sessions, the static file handler and bugfixes. +* Armin Ronacher, for the logo and racktools. +* Alex Beregszaszi, Alexander Kahn, Anil Wadghule, Aredridel, Ben + Alpert, Dan Kubb, Daniel Roethlisberger, Matt Todd, Tom Robinson, + Phil Hagelberg, S. Brent Faulkner, Bosko Milekic, Daniel Rodríguez + Troitiño, Genki Takiuchi, Geoffrey Grosenbach, Julien Sanchez, Kamal + Fariz Mahyuddin, Masayoshi Takahashi, Patrick Aljordm, Mig, Kazuhiro + Nishiyama, Jon Bardin, Konstantin Haase, Larry Siden, Matias + Korhonen, Sam Ruby, Simon Chiang, Tim Connor, Timur Batyrshin, and + Zach Brock for bug fixing and other improvements. +* Eric Wong, Hongli Lai, Jeremy Kemper for their continuous support + and API improvements. +* Yehuda Katz and Carl Lerche for refactoring rackup. +* Brian Candler, for Rack::ContentType. +* Graham Batty, for improved handler loading. +* Stephen Bannasch, for bug reports and documentation. +* Gary Wright, for proposing a better Rack::Response interface. +* Jonathan Buch, for improvements regarding Rack::Response. +* Armin Röhrl, for tracking down bugs in the Cookie generator. +* Alexander Kellett for testing the Gem and reviewing the announcement. +* Marcus Rückert, for help with configuring and debugging lighttpd. +* The WSGI team for the well-done and documented work they've done and + \Rack builds up on. +* All bug reporters and patch contributors not mentioned above. + +== Links + +\Rack:: +Official \Rack repositories:: +\Rack Bug Tracking:: +rack-devel mailing list:: + +== License + +\Rack is released under the {MIT License}[https://opensource.org/licenses/MIT]. diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/Rakefile b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/Rakefile new file mode 100644 index 0000000..237c3f2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/Rakefile @@ -0,0 +1,130 @@ +# frozen_string_literal: true + +require "bundler/gem_tasks" +require "rake/testtask" + +desc "Run all the tests" +task default: :test + +desc "Install gem dependencies" +task :deps do + require 'rubygems' + spec = Gem::Specification.load('rack.gemspec') + spec.dependencies.each do |dep| + reqs = dep.requirements_list + reqs = (["-v"] * reqs.size).zip(reqs).flatten + # Use system over sh, because we want to ignore errors! + system Gem.ruby, "-S", "gem", "install", '--conservative', dep.name, *reqs + end +end + +desc "Make an archive as .tar.gz" +task dist: %w[chmod changelog spec rdoc] do + sh "git archive --format=tar --prefix=#{release}/ HEAD^{tree} >#{release}.tar" + sh "pax -waf #{release}.tar -s ':^:#{release}/:' SPEC.rdoc ChangeLog doc rack.gemspec" + sh "gzip -f -9 #{release}.tar" +end + +desc "Make an official release" +task :officialrelease do + puts "Official build for #{release}..." + sh "rm -rf stage" + sh "git clone --shared . stage" + sh "cd stage && rake officialrelease_really" + sh "mv stage/#{release}.tar.gz stage/#{release}.gem ." +end + +task officialrelease_really: %w[spec dist gem] do + sh "shasum #{release}.tar.gz #{release}.gem" +end + +def release + "rack-" + File.read('lib/rack/version.rb')[/RELEASE += +([\"\'])([\d][\w\.]+)\1/, 2] +end + +desc "Make binaries executable" +task :chmod do + Dir["bin/*"].each { |binary| File.chmod(0755, binary) } + Dir["test/cgi/test*"].each { |binary| File.chmod(0755, binary) } +end + +desc "Generate a ChangeLog" +task changelog: "ChangeLog" + +file '.git/index' +file "ChangeLog" => '.git/index' do + File.open("ChangeLog", "w") { |out| + log = `git log -z` + log.force_encoding(Encoding::BINARY) + log.split("\0").map { |chunk| + author = chunk[/Author: (.*)/, 1].strip + date = chunk[/Date: (.*)/, 1].strip + desc, detail = $'.strip.split("\n", 2) + detail ||= "" + detail = detail.gsub(/.*darcs-hash:.*/, '') + detail.rstrip! + out.puts "#{date} #{author}" + out.puts " * #{desc.strip}" + out.puts detail unless detail.empty? + out.puts + } + } +end + +desc "Generate Rack Specification" +task spec: "SPEC.rdoc" + +file 'lib/rack/lint.rb' +file "SPEC.rdoc" => 'lib/rack/lint.rb' do + File.open("SPEC.rdoc", "wb") { |file| + IO.foreach("lib/rack/lint.rb") { |line| + if line =~ /^\s*## ?(.*)/ + file.puts $1 + end + } + } +end + +Rake::TestTask.new("test:regular") do |t| + t.libs << "test" + t.test_files = FileList["test/**/*_test.rb", "test/**/spec_*.rb", "test/gemloader.rb"] + t.warning = false + t.verbose = true +end + +desc "Run tests with coverage" +task "test_cov" do + ENV['COVERAGE'] = '1' + Rake::Task['test:regular'].invoke +end + +desc "Run all the fast + platform agnostic tests" +task test: %w[spec test:regular] + +desc "Run all the tests we run on CI" +task ci: :test + +task gem: :spec do + sh "gem build rack.gemspec" +end + +task doc: :rdoc + +desc "Generate RDoc documentation" +task rdoc: %w[changelog spec] do + sh(*%w{rdoc --line-numbers --main README.rdoc + --title 'Rack\ Documentation' --charset utf-8 -U -o doc} + + %w{README.rdoc KNOWN-ISSUES SPEC.rdoc ChangeLog} + + `git ls-files lib/\*\*/\*.rb`.strip.split) + cp "contrib/rdoc.css", "doc/rdoc.css" +end + +task pushdoc: :rdoc do + sh "rsync -avz doc/ rack.rubyforge.org:/var/www/gforge-projects/rack/doc/" +end + +task pushsite: :pushdoc do + sh "cd site && git gc" + sh "rsync -avz site/ rack.rubyforge.org:/var/www/gforge-projects/rack/" + sh "cd site && git push" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/SPEC.rdoc b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/SPEC.rdoc new file mode 100644 index 0000000..6c6b95b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/SPEC.rdoc @@ -0,0 +1,292 @@ +This specification aims to formalize the Rack protocol. You +can (and should) use Rack::Lint to enforce it. + +When you develop middleware, be sure to add a Lint before and +after to catch all mistakes. += Rack applications +A Rack application is a Ruby object (not a class) that +responds to +call+. +It takes exactly one argument, the *environment* +and returns an Array of exactly three values: +The *status*, +the *headers*, +and the *body*. +== The Environment +The environment must be an unfrozen instance of Hash that includes +CGI-like headers. The application is free to modify the +environment. + +The environment is required to include these variables +(adopted from PEP333), except when they'd be empty, but see +below. +REQUEST_METHOD:: The HTTP request method, such as + "GET" or "POST". This cannot ever + be an empty string, and so is + always required. +SCRIPT_NAME:: The initial portion of the request + URL's "path" that corresponds to the + application object, so that the + application knows its virtual + "location". This may be an empty + string, if the application corresponds + to the "root" of the server. +PATH_INFO:: The remainder of the request URL's + "path", designating the virtual + "location" of the request's target + within the application. This may be an + empty string, if the request URL targets + the application root and does not have a + trailing slash. This value may be + percent-encoded when originating from + a URL. +QUERY_STRING:: The portion of the request URL that + follows the ?, if any. May be + empty, but is always required! +SERVER_NAME:: When combined with SCRIPT_NAME and + PATH_INFO, these variables can be + used to complete the URL. Note, however, + that HTTP_HOST, if present, + should be used in preference to + SERVER_NAME for reconstructing + the request URL. + SERVER_NAME can never be an empty + string, and so is always required. +SERVER_PORT:: An optional +Integer+ which is the port the + server is running on. Should be specified if + the server is running on a non-standard port. +HTTP_ Variables:: Variables corresponding to the + client-supplied HTTP request + headers (i.e., variables whose + names begin with HTTP_). The + presence or absence of these + variables should correspond with + the presence or absence of the + appropriate HTTP header in the + request. See + {RFC3875 section 4.1.18}[https://tools.ietf.org/html/rfc3875#section-4.1.18] + for specific behavior. +In addition to this, the Rack environment must include these +Rack-specific variables: +rack.version:: The Array representing this version of Rack + See Rack::VERSION, that corresponds to + the version of this SPEC. +rack.url_scheme:: +http+ or +https+, depending on the + request URL. +rack.input:: See below, the input stream. +rack.errors:: See below, the error stream. +rack.multithread:: true if the application object may be + simultaneously invoked by another thread + in the same process, false otherwise. +rack.multiprocess:: true if an equivalent application object + may be simultaneously invoked by another + process, false otherwise. +rack.run_once:: true if the server expects + (but does not guarantee!) that the + application will only be invoked this one + time during the life of its containing + process. Normally, this will only be true + for a server based on CGI + (or something similar). +rack.hijack?:: present and true if the server supports + connection hijacking. See below, hijacking. +rack.hijack:: an object responding to #call that must be + called at least once before using + rack.hijack_io. + It is recommended #call return rack.hijack_io + as well as setting it in env if necessary. +rack.hijack_io:: if rack.hijack? is true, and rack.hijack + has received #call, this will contain + an object resembling an IO. See hijacking. +Additional environment specifications have approved to +standardized middleware APIs. None of these are required to +be implemented by the server. +rack.session:: A hash like interface for storing + request session data. + The store must implement: + store(key, value) (aliased as []=); + fetch(key, default = nil) (aliased as []); + delete(key); + clear; + to_hash (returning unfrozen Hash instance); +rack.logger:: A common object interface for logging messages. + The object must implement: + info(message, &block) + debug(message, &block) + warn(message, &block) + error(message, &block) + fatal(message, &block) +rack.multipart.buffer_size:: An Integer hint to the multipart parser as to what chunk size to use for reads and writes. +rack.multipart.tempfile_factory:: An object responding to #call with two arguments, the filename and content_type given for the multipart form field, and returning an IO-like object that responds to #<< and optionally #rewind. This factory will be used to instantiate the tempfile for each multipart form file upload field, rather than the default class of Tempfile. +The server or the application can store their own data in the +environment, too. The keys must contain at least one dot, +and should be prefixed uniquely. The prefix rack. +is reserved for use with the Rack core distribution and other +accepted specifications and must not be used otherwise. + +The SERVER_PORT must be an Integer if set. +The SERVER_NAME must be a valid authority as defined by RFC7540. +The HTTP_HOST must be a valid authority as defined by RFC7540. +The environment must not contain the keys +HTTP_CONTENT_TYPE or HTTP_CONTENT_LENGTH +(use the versions without HTTP_). +The CGI keys (named without a period) must have String values. +If the string values for CGI keys contain non-ASCII characters, +they should use ASCII-8BIT encoding. +There are the following restrictions: +* rack.version must be an array of Integers. +* rack.url_scheme must either be +http+ or +https+. +* There must be a valid input stream in rack.input. +* There must be a valid error stream in rack.errors. +* There may be a valid hijack stream in rack.hijack_io +* The REQUEST_METHOD must be a valid token. +* The SCRIPT_NAME, if non-empty, must start with / +* The PATH_INFO, if non-empty, must start with / +* The CONTENT_LENGTH, if given, must consist of digits only. +* One of SCRIPT_NAME or PATH_INFO must be + set. PATH_INFO should be / if + SCRIPT_NAME is empty. + SCRIPT_NAME never should be /, but instead be empty. +=== The Input Stream + +The input stream is an IO-like object which contains the raw HTTP +POST data. +When applicable, its external encoding must be "ASCII-8BIT" and it +must be opened in binary mode, for Ruby 1.9 compatibility. +The input stream must respond to +gets+, +each+, +read+ and +rewind+. +* +gets+ must be called without arguments and return a string, + or +nil+ on EOF. +* +read+ behaves like IO#read. + Its signature is read([length, [buffer]]). + + If given, +length+ must be a non-negative Integer (>= 0) or +nil+, + and +buffer+ must be a String and may not be nil. + + If +length+ is given and not nil, then this method reads at most + +length+ bytes from the input stream. + + If +length+ is not given or nil, then this method reads + all data until EOF. + + When EOF is reached, this method returns nil if +length+ is given + and not nil, or "" if +length+ is not given or is nil. + + If +buffer+ is given, then the read data will be placed + into +buffer+ instead of a newly created String object. +* +each+ must be called without arguments and only yield Strings. +* +rewind+ must be called without arguments. It rewinds the input + stream back to the beginning. It must not raise Errno::ESPIPE: + that is, it may not be a pipe or a socket. Therefore, handler + developers must buffer the input data into some rewindable object + if the underlying input stream is not rewindable. +* +close+ must never be called on the input stream. +=== The Error Stream +The error stream must respond to +puts+, +write+ and +flush+. +* +puts+ must be called with a single argument that responds to +to_s+. +* +write+ must be called with a single argument that is a String. +* +flush+ must be called without arguments and must be called + in order to make the error appear for sure. +* +close+ must never be called on the error stream. +=== Hijacking +==== Request (before status) +If rack.hijack? is true then rack.hijack must respond to #call. +rack.hijack must return the io that will also be assigned (or is +already present, in rack.hijack_io. + +rack.hijack_io must respond to: +read, write, read_nonblock, write_nonblock, flush, close, +close_read, close_write, closed? + +The semantics of these IO methods must be a best effort match to +those of a normal ruby IO or Socket object, using standard +arguments and raising standard exceptions. Servers are encouraged +to simply pass on real IO objects, although it is recognized that +this approach is not directly compatible with SPDY and HTTP 2.0. + +IO provided in rack.hijack_io should preference the +IO::WaitReadable and IO::WaitWritable APIs wherever supported. + +There is a deliberate lack of full specification around +rack.hijack_io, as semantics will change from server to server. +Users are encouraged to utilize this API with a knowledge of their +server choice, and servers may extend the functionality of +hijack_io to provide additional features to users. The purpose of +rack.hijack is for Rack to "get out of the way", as such, Rack only +provides the minimum of specification and support. + +If rack.hijack? is false, then rack.hijack should not be set. + +If rack.hijack? is false, then rack.hijack_io should not be set. +==== Response (after headers) +It is also possible to hijack a response after the status and headers +have been sent. +In order to do this, an application may set the special header +rack.hijack to an object that responds to call +accepting an argument that conforms to the rack.hijack_io +protocol. + +After the headers have been sent, and this hijack callback has been +called, the application is now responsible for the remaining lifecycle +of the IO. The application is also responsible for maintaining HTTP +semantics. Of specific note, in almost all cases in the current SPEC, +applications will have wanted to specify the header Connection:close in +HTTP/1.1, and not Connection:keep-alive, as there is no protocol for +returning hijacked sockets to the web server. For that purpose, use the +body streaming API instead (progressively yielding strings via each). + +Servers must ignore the body part of the response tuple when +the rack.hijack response API is in use. + +The special response header rack.hijack must only be set +if the request env has rack.hijack? true. +==== Conventions +* Middleware should not use hijack unless it is handling the whole + response. +* Middleware may wrap the IO object for the response pattern. +* Middleware should not wrap the IO object for the request pattern. The + request pattern is intended to provide the hijacker with "raw tcp". +== The Response +=== The Status +This is an HTTP status. When parsed as integer (+to_i+), it must be +greater than or equal to 100. +=== The Headers +The header must respond to +each+, and yield values of key and value. +The header keys must be Strings. +Special headers starting "rack." are for communicating with the +server, and must not be sent back to the client. +The header must not contain a +Status+ key. +The header must conform to RFC7230 token specification, i.e. cannot +contain non-printable ASCII, DQUOTE or "(),/:;<=>?@[\]{}". +The values of the header must be Strings, +consisting of lines (for multiple header values, e.g. multiple +Set-Cookie values) separated by "\\n". +The lines must not contain characters below 037. +=== The Content-Type +There must not be a Content-Type, when the +Status+ is 1xx, +204 or 304. +=== The Content-Length +There must not be a Content-Length header when the ++Status+ is 1xx, 204 or 304. +=== The Body +The Body must respond to +each+ +and must only yield String values. + +The Body itself should not be an instance of String, as this will +break in Ruby 1.9. + +If the Body responds to +close+, it will be called after iteration. If +the body is replaced by a middleware after action, the original body +must be closed first, if it responds to close. + +If the Body responds to +to_path+, it must return a String +identifying the location of a file whose contents are identical +to that produced by calling +each+; this may be used by the +server as an alternative, possibly more efficient way to +transport the response. + +The Body commonly is an Array of Strings, the application +instance itself, or a File-like object. +== Thanks +Some parts of this specification are adopted from PEP333: Python +Web Server Gateway Interface +v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank +everyone involved in that effort. diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/bin/rackup b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/bin/rackup new file mode 100755 index 0000000..58988a0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/bin/rackup @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "rack" +Rack::Server.start diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rack.png b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rack.png new file mode 100644 index 0000000..0920c4f Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rack.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rack.svg b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rack.svg new file mode 100644 index 0000000..0d3f961 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rack.svg @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rack_logo.svg b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rack_logo.svg new file mode 100644 index 0000000..8287c9d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rack_logo.svg @@ -0,0 +1,164 @@ + + + + + + + + + + + + + + diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rdoc.css b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rdoc.css new file mode 100644 index 0000000..f1e342f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/contrib/rdoc.css @@ -0,0 +1,412 @@ +/* Forked from the Darkfish templates rdoc.css file, much hacked, probably + * imperfect */ + +html { max-width: 960px; margin: 0 auto; } +body { + font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif; +} +body.file-popup { + font-size: 90%; + margin-left: 0; +} + +h1 { + color: #4183C4; +} + +:link, +:visited { + color: #4183C4; + text-decoration: none; +} +:link:hover, +:visited:hover { + border-bottom: 1px dotted #4183C4; +} + +pre, pre.description { + font: 12px Monaco,"Courier New","DejaVu Sans Mono","Bitstream Vera Sans Mono",monospace; + padding: 1em; + overflow: auto; + line-height: 1.4; +} + +/* @group Generic Classes */ + +.initially-hidden { + display: none; +} + +#search-field { + width: 98%; +} + +.missing-docs { + font-size: 120%; + background: white url(images/wrench_orange.png) no-repeat 4px center; + color: #ccc; + line-height: 2em; + border: 1px solid #d00; + opacity: 1; + text-indent: 24px; + letter-spacing: 3px; + font-weight: bold; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; +} + +.target-section { + border: 2px solid #dcce90; + border-left-width: 8px; + background: #fff3c2; +} + +/* @end */ + +/* @group Index Page, Standalone file pages */ +.indexpage ul { + line-height: 160%; + list-style: none; +} +.indexpage ul :link, +.indexpage ul :visited { + font-size: 16px; +} + +.indexpage li { + padding-left: 20px; +} + +.indexpage ul > li { + background: url(images/bullet_black.png) no-repeat left 4px; +} +.indexpage li.method { + background: url(images/plugin.png) no-repeat left 4px; +} +.indexpage li.module { + background: url(images/package.png) no-repeat left 4px; +} +.indexpage li.class { + background: url(images/ruby.png) no-repeat left 4px; +} +.indexpage li.file { + background: url(images/page_white_text.png) no-repeat left 4px; +} +.indexpage li li { + background: url(images/tag_blue.png) no-repeat left 4px; +} +.indexpage li .toc-toggle { + width: 16px; + height: 16px; + background: url(images/add.png) no-repeat; +} + +.indexpage li .toc-toggle.open { + background: url(images/delete.png) no-repeat; +} + +/* @end */ + +/* @group Top-Level Structure */ + +.project-section, #file-metadata, #class-metadata { + display: block; + background: #f5f5f5; + margin-bottom: 1em; + padding: 0.5em; +} +.project-section h3, #file-metadata h3, #class-metadata h3 { + margin: 0; +} + +#metadata { + float: left; + width: 280px; +} + +#documentation { + margin: 2em 1em 2em 300px; +} + +#validator-badges { + clear: both; + margin: 1em 1em 2em; + font-size: smaller; +} + +/* @end */ + +/* @group Metadata Section */ + +#metadata ul, +#metadata dl, +#metadata p { + padding: 0px; + list-style: none; +} + +dl.svninfo { + color: #666; + margin: 0; +} +dl.svninfo dt { + font-weight: bold; +} + +ul.link-list li { + white-space: nowrap; +} +ul.link-list .type { + font-size: 8px; + text-transform: uppercase; + color: white; + background: #969696; +} + +/* @end */ + +/* @group Documentation Section */ + +.note-list { + margin: 8px 0; +} + +.label-list { + margin: 8px 1.5em; + border: 1px solid #ccc; +} +.description .label-list { + font-size: 14px; +} + +.note-list dt { + font-weight: bold; +} +.note-list dd { +} + +.label-list dt { + font-weight: bold; + background: #ddd; +} +.label-list dd { +} +.label-list dd + dt, +.note-list dd + dt { + margin-top: 0.7em; +} + +#documentation .section { + font-size: 90%; +} + +#documentation h2.section-header { + color: #333; + font-size: 175%; +} + +.documentation-section-title { + position: relative; +} +.documentation-section-title .section-click-top { + position: absolute; + top: 6px; + right: 12px; + font-size: 10px; + visibility: hidden; +} + +.documentation-section-title:hover .section-click-top { + visibility: visible; +} + +#documentation h3.section-header { + color: #333; + font-size: 150%; +} + +#constants-list > dl, +#attributes-list > dl { + margin: 1em 0 2em; + border: 0; +} +#constants-list > dl dt, +#attributes-list > dl dt { + font-weight: bold; + font-family: Monaco, "Andale Mono"; + background: inherit; +} +#constants-list > dl dt a, +#attributes-list > dl dt a { + color: inherit; +} +#constants-list > dl dd, +#attributes-list > dl dd { + margin: 0 0 1em 0; + color: #666; +} + +.documentation-section h2 { + position: relative; +} + +.documentation-section h2 a { + position: absolute; + top: 8px; + right: 10px; + font-size: 12px; + color: #9b9877; + visibility: hidden; +} + +.documentation-section h2:hover a { + visibility: visible; +} + +/* @group Method Details */ + +#documentation .method-source-code { + display: none; +} + +#documentation .method-detail { + margin: 0.2em 0.2em; + padding: 0.5em; +} +#documentation .method-detail:hover { + background-color: #f5f5f5; +} +#documentation .method-heading { + cursor: pointer; + position: relative; + font-size: 125%; + line-height: 125%; + font-weight: bold; + color: #333; + background: url(images/brick.png) no-repeat left bottom; + padding-left: 20px; +} +#documentation .method-heading :link, +#documentation .method-heading :visited { + color: inherit; +} +#documentation .method-click-advice { + position: absolute; + right: 5px; + font-size: 10px; + color: #aaa; + visibility: hidden; + background: url(images/zoom.png) no-repeat right 5px; + padding-right: 20px; + overflow: show; +} +#documentation .method-heading:hover .method-click-advice { + visibility: visible; +} + +#documentation .method-alias .method-heading { + color: #666; + background: url(images/brick_link.png) no-repeat left bottom; +} + +#documentation .method-description, +#documentation .aliases { + margin: 0 20px; + color: #666; +} + +#documentation .method-description p, +#documentation .aliases p { + line-height: 1.2em; +} + +#documentation .aliases { + font-style: italic; + cursor: default; +} +#documentation .method-description p { + margin-bottom: 0.5em; +} +#documentation .method-description ul { + margin-left: 1.5em; +} + +#documentation .attribute-method-heading { + background: url(images/tag_green.png) no-repeat left bottom; +} +#documentation #attribute-method-details .method-detail:hover { + background-color: transparent; + cursor: default; +} +#documentation .attribute-access-type { + font-size: 60%; + text-transform: uppercase; + vertical-align: super; +} + +.method-section .method-source-code { + background: white; +} + +/* @group Source Code */ + +.ruby-constant .ruby-keyword .ruby-ivar .ruby-operator .ruby-identifier +.ruby-node .ruby-comment .ruby-regexp .ruby-value { + background: transparent; +} + +/* Thanks GitHub!!! */ +.ruby-constant { color: #458; font-weight: bold; } +.ruby-keyword { color: black; font-weight: bold; } +.ruby-ivar { color: teal; } +.ruby-operator { color: #000; } +.ruby-identifier { color: black; } +.ruby-node { color: red; } +.ruby-comment { color: #998; font-weight: bold; } +.ruby-regexp { color: #009926; } +.ruby-value { color: #099; } +.ruby-string { color: red; } + +/* @group search results */ + +#search-section .section-header { + margin: 0; + padding: 0; +} + +#search-results { + width: 100%; + list-style: none; + margin: 0; + padding: 0; +} + +#search-results h1 { + font-size: 1em; + font-weight: normal; + text-shadow: none; +} + +#search-results .current { + background: #eee; +} + +#search-results li { + list-style: none; + line-height: 1em; + padding: 0.5em; + border-bottom: 1px solid black; +} + +#search-results .search-namespace { + font-weight: bold; +} + +#search-results li em { + background: yellow; + font-style: normal; +} + +#search-results pre { + margin: 0.5em; +} diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/example/lobster.ru b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/example/lobster.ru new file mode 100644 index 0000000..901e18a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/example/lobster.ru @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +require 'rack/lobster' + +use Rack::ShowExceptions +run Rack::Lobster.new diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/example/protectedlobster.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/example/protectedlobster.rb new file mode 100644 index 0000000..fe4f0b0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/example/protectedlobster.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require 'rack' +require 'rack/lobster' + +lobster = Rack::Lobster.new + +protected_lobster = Rack::Auth::Basic.new(lobster) do |username, password| + Rack::Utils.secure_compare('secret', password) +end + +protected_lobster.realm = 'Lobster 2.0' + +pretty_protected_lobster = Rack::ShowStatus.new(Rack::ShowExceptions.new(protected_lobster)) + +Rack::Server.start app: pretty_protected_lobster, Port: 9292 diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/example/protectedlobster.ru b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/example/protectedlobster.ru new file mode 100644 index 0000000..0eb243c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/example/protectedlobster.ru @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require 'rack/lobster' + +use Rack::ShowExceptions +use Rack::Auth::Basic, "Lobster 2.0" do |username, password| + Rack::Utils.secure_compare('secret', password) +end + +run Rack::Lobster.new diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack.rb new file mode 100644 index 0000000..e4494e5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack.rb @@ -0,0 +1,141 @@ +# frozen_string_literal: true + +# Copyright (C) 2007-2019 Leah Neukirchen +# +# Rack is freely distributable under the terms of an MIT-style license. +# See MIT-LICENSE or https://opensource.org/licenses/MIT. + +# The Rack main module, serving as a namespace for all core Rack +# modules and classes. +# +# All modules meant for use in your application are autoloaded here, +# so it should be enough just to require 'rack' in your code. + +require_relative 'rack/version' + +module Rack + HTTP_HOST = 'HTTP_HOST' + HTTP_PORT = 'HTTP_PORT' + HTTP_VERSION = 'HTTP_VERSION' + HTTPS = 'HTTPS' + PATH_INFO = 'PATH_INFO' + REQUEST_METHOD = 'REQUEST_METHOD' + REQUEST_PATH = 'REQUEST_PATH' + SCRIPT_NAME = 'SCRIPT_NAME' + QUERY_STRING = 'QUERY_STRING' + SERVER_PROTOCOL = 'SERVER_PROTOCOL' + SERVER_NAME = 'SERVER_NAME' + SERVER_PORT = 'SERVER_PORT' + CACHE_CONTROL = 'Cache-Control' + EXPIRES = 'Expires' + CONTENT_LENGTH = 'Content-Length' + CONTENT_TYPE = 'Content-Type' + SET_COOKIE = 'Set-Cookie' + TRANSFER_ENCODING = 'Transfer-Encoding' + HTTP_COOKIE = 'HTTP_COOKIE' + ETAG = 'ETag' + + # HTTP method verbs + GET = 'GET' + POST = 'POST' + PUT = 'PUT' + PATCH = 'PATCH' + DELETE = 'DELETE' + HEAD = 'HEAD' + OPTIONS = 'OPTIONS' + LINK = 'LINK' + UNLINK = 'UNLINK' + TRACE = 'TRACE' + + # Rack environment variables + RACK_VERSION = 'rack.version' + RACK_TEMPFILES = 'rack.tempfiles' + RACK_ERRORS = 'rack.errors' + RACK_LOGGER = 'rack.logger' + RACK_INPUT = 'rack.input' + RACK_SESSION = 'rack.session' + RACK_SESSION_OPTIONS = 'rack.session.options' + RACK_SHOWSTATUS_DETAIL = 'rack.showstatus.detail' + RACK_MULTITHREAD = 'rack.multithread' + RACK_MULTIPROCESS = 'rack.multiprocess' + RACK_RUNONCE = 'rack.run_once' + RACK_URL_SCHEME = 'rack.url_scheme' + RACK_HIJACK = 'rack.hijack' + RACK_IS_HIJACK = 'rack.hijack?' + RACK_HIJACK_IO = 'rack.hijack_io' + RACK_RECURSIVE_INCLUDE = 'rack.recursive.include' + RACK_MULTIPART_BUFFER_SIZE = 'rack.multipart.buffer_size' + RACK_MULTIPART_TEMPFILE_FACTORY = 'rack.multipart.tempfile_factory' + RACK_REQUEST_FORM_INPUT = 'rack.request.form_input' + RACK_REQUEST_FORM_HASH = 'rack.request.form_hash' + RACK_REQUEST_FORM_VARS = 'rack.request.form_vars' + RACK_REQUEST_COOKIE_HASH = 'rack.request.cookie_hash' + RACK_REQUEST_COOKIE_STRING = 'rack.request.cookie_string' + RACK_REQUEST_QUERY_HASH = 'rack.request.query_hash' + RACK_REQUEST_QUERY_STRING = 'rack.request.query_string' + RACK_METHODOVERRIDE_ORIGINAL_METHOD = 'rack.methodoverride.original_method' + RACK_SESSION_UNPACKED_COOKIE_DATA = 'rack.session.unpacked_cookie_data' + + autoload :Builder, "rack/builder" + autoload :BodyProxy, "rack/body_proxy" + autoload :Cascade, "rack/cascade" + autoload :Chunked, "rack/chunked" + autoload :CommonLogger, "rack/common_logger" + autoload :ConditionalGet, "rack/conditional_get" + autoload :Config, "rack/config" + autoload :ContentLength, "rack/content_length" + autoload :ContentType, "rack/content_type" + autoload :ETag, "rack/etag" + autoload :Events, "rack/events" + autoload :File, "rack/file" + autoload :Files, "rack/files" + autoload :Deflater, "rack/deflater" + autoload :Directory, "rack/directory" + autoload :ForwardRequest, "rack/recursive" + autoload :Handler, "rack/handler" + autoload :Head, "rack/head" + autoload :Lint, "rack/lint" + autoload :Lock, "rack/lock" + autoload :Logger, "rack/logger" + autoload :MediaType, "rack/media_type" + autoload :MethodOverride, "rack/method_override" + autoload :Mime, "rack/mime" + autoload :NullLogger, "rack/null_logger" + autoload :Recursive, "rack/recursive" + autoload :Reloader, "rack/reloader" + autoload :RewindableInput, "rack/rewindable_input" + autoload :Runtime, "rack/runtime" + autoload :Sendfile, "rack/sendfile" + autoload :Server, "rack/server" + autoload :ShowExceptions, "rack/show_exceptions" + autoload :ShowStatus, "rack/show_status" + autoload :Static, "rack/static" + autoload :TempfileReaper, "rack/tempfile_reaper" + autoload :URLMap, "rack/urlmap" + autoload :Utils, "rack/utils" + autoload :Multipart, "rack/multipart" + + autoload :MockRequest, "rack/mock" + autoload :MockResponse, "rack/mock" + + autoload :Request, "rack/request" + autoload :Response, "rack/response" + + module Auth + autoload :Basic, "rack/auth/basic" + autoload :AbstractRequest, "rack/auth/abstract/request" + autoload :AbstractHandler, "rack/auth/abstract/handler" + module Digest + autoload :MD5, "rack/auth/digest/md5" + autoload :Nonce, "rack/auth/digest/nonce" + autoload :Params, "rack/auth/digest/params" + autoload :Request, "rack/auth/digest/request" + end + end + + module Session + autoload :Cookie, "rack/session/cookie" + autoload :Pool, "rack/session/pool" + autoload :Memcache, "rack/session/memcache" + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/abstract/handler.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/abstract/handler.rb new file mode 100644 index 0000000..3ed8709 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/abstract/handler.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +module Rack + module Auth + # Rack::Auth::AbstractHandler implements common authentication functionality. + # + # +realm+ should be set for all handlers. + + class AbstractHandler + + attr_accessor :realm + + def initialize(app, realm = nil, &authenticator) + @app, @realm, @authenticator = app, realm, authenticator + end + + + private + + def unauthorized(www_authenticate = challenge) + return [ 401, + { CONTENT_TYPE => 'text/plain', + CONTENT_LENGTH => '0', + 'WWW-Authenticate' => www_authenticate.to_s }, + [] + ] + end + + def bad_request + return [ 400, + { CONTENT_TYPE => 'text/plain', + CONTENT_LENGTH => '0' }, + [] + ] + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/abstract/request.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/abstract/request.rb new file mode 100644 index 0000000..34042c4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/abstract/request.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +module Rack + module Auth + class AbstractRequest + + def initialize(env) + @env = env + end + + def request + @request ||= Request.new(@env) + end + + def provided? + !authorization_key.nil? && valid? + end + + def valid? + !@env[authorization_key].nil? + end + + def parts + @parts ||= @env[authorization_key].split(' ', 2) + end + + def scheme + @scheme ||= parts.first && parts.first.downcase + end + + def params + @params ||= parts.last + end + + + private + + AUTHORIZATION_KEYS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION'] + + def authorization_key + @authorization_key ||= AUTHORIZATION_KEYS.detect { |key| @env.has_key?(key) } + end + + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/basic.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/basic.rb new file mode 100644 index 0000000..d5b4ea1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/basic.rb @@ -0,0 +1,61 @@ +# frozen_string_literal: true + +require_relative 'abstract/handler' +require_relative 'abstract/request' +require 'base64' + +module Rack + module Auth + # Rack::Auth::Basic implements HTTP Basic Authentication, as per RFC 2617. + # + # Initialize with the Rack application that you want protecting, + # and a block that checks if a username and password pair are valid. + # + # See also: example/protectedlobster.rb + + class Basic < AbstractHandler + + def call(env) + auth = Basic::Request.new(env) + + return unauthorized unless auth.provided? + + return bad_request unless auth.basic? + + if valid?(auth) + env['REMOTE_USER'] = auth.username + + return @app.call(env) + end + + unauthorized + end + + + private + + def challenge + 'Basic realm="%s"' % realm + end + + def valid?(auth) + @authenticator.call(*auth.credentials) + end + + class Request < Auth::AbstractRequest + def basic? + "basic" == scheme && credentials.length == 2 + end + + def credentials + @credentials ||= Base64.decode64(params).split(':', 2) + end + + def username + credentials.first + end + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/md5.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/md5.rb new file mode 100644 index 0000000..04b103e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/md5.rb @@ -0,0 +1,131 @@ +# frozen_string_literal: true + +require_relative '../abstract/handler' +require_relative 'request' +require_relative 'params' +require_relative 'nonce' +require 'digest/md5' + +module Rack + module Auth + module Digest + # Rack::Auth::Digest::MD5 implements the MD5 algorithm version of + # HTTP Digest Authentication, as per RFC 2617. + # + # Initialize with the [Rack] application that you want protecting, + # and a block that looks up a plaintext password for a given username. + # + # +opaque+ needs to be set to a constant base64/hexadecimal string. + # + class MD5 < AbstractHandler + + attr_accessor :opaque + + attr_writer :passwords_hashed + + def initialize(app, realm = nil, opaque = nil, &authenticator) + @passwords_hashed = nil + if opaque.nil? and realm.respond_to? :values_at + realm, opaque, @passwords_hashed = realm.values_at :realm, :opaque, :passwords_hashed + end + super(app, realm, &authenticator) + @opaque = opaque + end + + def passwords_hashed? + !!@passwords_hashed + end + + def call(env) + auth = Request.new(env) + + unless auth.provided? + return unauthorized + end + + if !auth.digest? || !auth.correct_uri? || !valid_qop?(auth) + return bad_request + end + + if valid?(auth) + if auth.nonce.stale? + return unauthorized(challenge(stale: true)) + else + env['REMOTE_USER'] = auth.username + + return @app.call(env) + end + end + + unauthorized + end + + + private + + QOP = 'auth' + + def params(hash = {}) + Params.new do |params| + params['realm'] = realm + params['nonce'] = Nonce.new.to_s + params['opaque'] = H(opaque) + params['qop'] = QOP + + hash.each { |k, v| params[k] = v } + end + end + + def challenge(hash = {}) + "Digest #{params(hash)}" + end + + def valid?(auth) + valid_opaque?(auth) && valid_nonce?(auth) && valid_digest?(auth) + end + + def valid_qop?(auth) + QOP == auth.qop + end + + def valid_opaque?(auth) + H(opaque) == auth.opaque + end + + def valid_nonce?(auth) + auth.nonce.valid? + end + + def valid_digest?(auth) + pw = @authenticator.call(auth.username) + pw && Rack::Utils.secure_compare(digest(auth, pw), auth.response) + end + + def md5(data) + ::Digest::MD5.hexdigest(data) + end + + alias :H :md5 + + def KD(secret, data) + H "#{secret}:#{data}" + end + + def A1(auth, password) + "#{auth.username}:#{auth.realm}:#{password}" + end + + def A2(auth) + "#{auth.method}:#{auth.uri}" + end + + def digest(auth, password) + password_hash = passwords_hashed? ? password : H(A1(auth, password)) + + KD password_hash, "#{auth.nonce}:#{auth.nc}:#{auth.cnonce}:#{QOP}:#{H A2(auth)}" + end + + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/nonce.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/nonce.rb new file mode 100644 index 0000000..3216d97 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/nonce.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +require 'digest/md5' +require 'base64' + +module Rack + module Auth + module Digest + # Rack::Auth::Digest::Nonce is the default nonce generator for the + # Rack::Auth::Digest::MD5 authentication handler. + # + # +private_key+ needs to set to a constant string. + # + # +time_limit+ can be optionally set to an integer (number of seconds), + # to limit the validity of the generated nonces. + + class Nonce + + class << self + attr_accessor :private_key, :time_limit + end + + def self.parse(string) + new(*Base64.decode64(string).split(' ', 2)) + end + + def initialize(timestamp = Time.now, given_digest = nil) + @timestamp, @given_digest = timestamp.to_i, given_digest + end + + def to_s + Base64.encode64("#{@timestamp} #{digest}").strip + end + + def digest + ::Digest::MD5.hexdigest("#{@timestamp}:#{self.class.private_key}") + end + + def valid? + digest == @given_digest + end + + def stale? + !self.class.time_limit.nil? && (Time.now.to_i - @timestamp) > self.class.time_limit + end + + def fresh? + !stale? + end + + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/params.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/params.rb new file mode 100644 index 0000000..f611b3c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/params.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +module Rack + module Auth + module Digest + class Params < Hash + + def self.parse(str) + Params[*split_header_value(str).map do |param| + k, v = param.split('=', 2) + [k, dequote(v)] + end.flatten] + end + + def self.dequote(str) # From WEBrick::HTTPUtils + ret = (/\A"(.*)"\Z/ =~ str) ? $1 : str.dup + ret.gsub!(/\\(.)/, "\\1") + ret + end + + def self.split_header_value(str) + str.scan(/\w+\=(?:"[^\"]+"|[^,]+)/n) + end + + def initialize + super() + + yield self if block_given? + end + + def [](k) + super k.to_s + end + + def []=(k, v) + super k.to_s, v.to_s + end + + UNQUOTED = ['nc', 'stale'] + + def to_s + map do |k, v| + "#{k}=#{(UNQUOTED.include?(k) ? v.to_s : quote(v))}" + end.join(', ') + end + + def quote(str) # From WEBrick::HTTPUtils + '"' + str.gsub(/[\\\"]/o, "\\\1") + '"' + end + + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/request.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/request.rb new file mode 100644 index 0000000..7b89b76 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/auth/digest/request.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +require_relative '../abstract/request' +require_relative 'params' +require_relative 'nonce' + +module Rack + module Auth + module Digest + class Request < Auth::AbstractRequest + def method + @env[RACK_METHODOVERRIDE_ORIGINAL_METHOD] || @env[REQUEST_METHOD] + end + + def digest? + "digest" == scheme + end + + def correct_uri? + request.fullpath == uri + end + + def nonce + @nonce ||= Nonce.parse(params['nonce']) + end + + def params + @params ||= Params.parse(parts.last) + end + + def respond_to?(sym, *) + super or params.has_key? sym.to_s + end + + def method_missing(sym, *args) + return super unless params.has_key?(key = sym.to_s) + return params[key] if args.size == 0 + raise ArgumentError, "wrong number of arguments (#{args.size} for 0)" + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/body_proxy.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/body_proxy.rb new file mode 100644 index 0000000..cfc0796 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/body_proxy.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +module Rack + # Proxy for response bodies allowing calling a block when + # the response body is closed (after the response has been fully + # sent to the client). + class BodyProxy + # Set the response body to wrap, and the block to call when the + # response has been fully sent. + def initialize(body, &block) + @body = body + @block = block + @closed = false + end + + # Return whether the wrapped body responds to the method. + def respond_to_missing?(method_name, include_all = false) + super or @body.respond_to?(method_name, include_all) + end + + # If not already closed, close the wrapped body and + # then call the block the proxy was initialized with. + def close + return if @closed + @closed = true + begin + @body.close if @body.respond_to? :close + ensure + @block.call + end + end + + # Whether the proxy is closed. The proxy starts as not closed, + # and becomes closed on the first call to close. + def closed? + @closed + end + + # Delegate missing methods to the wrapped body. + def method_missing(method_name, *args, &block) + @body.__send__(method_name, *args, &block) + end + ruby2_keywords(:method_missing) if respond_to?(:ruby2_keywords, true) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/builder.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/builder.rb new file mode 100644 index 0000000..816ecf6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/builder.rb @@ -0,0 +1,257 @@ +# frozen_string_literal: true + +module Rack + # Rack::Builder implements a small DSL to iteratively construct Rack + # applications. + # + # Example: + # + # require 'rack/lobster' + # app = Rack::Builder.new do + # use Rack::CommonLogger + # use Rack::ShowExceptions + # map "/lobster" do + # use Rack::Lint + # run Rack::Lobster.new + # end + # end + # + # run app + # + # Or + # + # app = Rack::Builder.app do + # use Rack::CommonLogger + # run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] } + # end + # + # run app + # + # +use+ adds middleware to the stack, +run+ dispatches to an application. + # You can use +map+ to construct a Rack::URLMap in a convenient way. + + class Builder + + # https://stackoverflow.com/questions/2223882/whats-the-difference-between-utf-8-and-utf-8-without-bom + UTF_8_BOM = '\xef\xbb\xbf' + + # Parse the given config file to get a Rack application. + # + # If the config file ends in +.ru+, it is treated as a + # rackup file and the contents will be treated as if + # specified inside a Rack::Builder block, using the given + # options. + # + # If the config file does not end in +.ru+, it is + # required and Rack will use the basename of the file + # to guess which constant will be the Rack application to run. + # The options given will be ignored in this case. + # + # Examples: + # + # Rack::Builder.parse_file('config.ru') + # # Rack application built using Rack::Builder.new + # + # Rack::Builder.parse_file('app.rb') + # # requires app.rb, which can be anywhere in Ruby's + # # load path. After requiring, assumes App constant + # # contains Rack application + # + # Rack::Builder.parse_file('./my_app.rb') + # # requires ./my_app.rb, which should be in the + # # process's current directory. After requiring, + # # assumes MyApp constant contains Rack application + def self.parse_file(config, opts = Server::Options.new) + if config.end_with?('.ru') + return self.load_file(config, opts) + else + require config + app = Object.const_get(::File.basename(config, '.rb').split('_').map(&:capitalize).join('')) + return app, {} + end + end + + # Load the given file as a rackup file, treating the + # contents as if specified inside a Rack::Builder block. + # + # Treats the first comment at the beginning of a line + # that starts with a backslash as options similar to + # options passed on a rackup command line. + # + # Ignores content in the file after +__END__+, so that + # use of +__END__+ will not result in a syntax error. + # + # Example config.ru file: + # + # $ cat config.ru + # + # #\ -p 9393 + # + # use Rack::ContentLength + # require './app.rb' + # run App + def self.load_file(path, opts = Server::Options.new) + options = {} + + cfgfile = ::File.read(path) + cfgfile.slice!(/\A#{UTF_8_BOM}/) if cfgfile.encoding == Encoding::UTF_8 + + if cfgfile[/^#\\(.*)/] && opts + warn "Parsing options from the first comment line is deprecated!" + options = opts.parse! $1.split(/\s+/) + end + + cfgfile.sub!(/^__END__\n.*\Z/m, '') + app = new_from_string cfgfile, path + + return app, options + end + + # Evaluate the given +builder_script+ string in the context of + # a Rack::Builder block, returning a Rack application. + def self.new_from_string(builder_script, file = "(rackup)") + # We want to build a variant of TOPLEVEL_BINDING with self as a Rack::Builder instance. + # We cannot use instance_eval(String) as that would resolve constants differently. + binding, builder = TOPLEVEL_BINDING.eval('Rack::Builder.new.instance_eval { [binding, self] }') + eval builder_script, binding, file + builder.to_app + end + + # Initialize a new Rack::Builder instance. +default_app+ specifies the + # default application if +run+ is not called later. If a block + # is given, it is evaluted in the context of the instance. + def initialize(default_app = nil, &block) + @use, @map, @run, @warmup, @freeze_app = [], nil, default_app, nil, false + instance_eval(&block) if block_given? + end + + # Create a new Rack::Builder instance and return the Rack application + # generated from it. + def self.app(default_app = nil, &block) + self.new(default_app, &block).to_app + end + + # Specifies middleware to use in a stack. + # + # class Middleware + # def initialize(app) + # @app = app + # end + # + # def call(env) + # env["rack.some_header"] = "setting an example" + # @app.call(env) + # end + # end + # + # use Middleware + # run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] } + # + # All requests through to this application will first be processed by the middleware class. + # The +call+ method in this example sets an additional environment key which then can be + # referenced in the application if required. + def use(middleware, *args, &block) + if @map + mapping, @map = @map, nil + @use << proc { |app| generate_map(app, mapping) } + end + @use << proc { |app| middleware.new(app, *args, &block) } + end + ruby2_keywords(:use) if respond_to?(:ruby2_keywords, true) + + # Takes an argument that is an object that responds to #call and returns a Rack response. + # The simplest form of this is a lambda object: + # + # run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] } + # + # However this could also be a class: + # + # class Heartbeat + # def self.call(env) + # [200, { "Content-Type" => "text/plain" }, ["OK"]] + # end + # end + # + # run Heartbeat + def run(app) + @run = app + end + + # Takes a lambda or block that is used to warm-up the application. This block is called + # before the Rack application is returned by to_app. + # + # warmup do |app| + # client = Rack::MockRequest.new(app) + # client.get('/') + # end + # + # use SomeMiddleware + # run MyApp + def warmup(prc = nil, &block) + @warmup = prc || block + end + + # Creates a route within the application. Routes under the mapped path will be sent to + # the Rack application specified by run inside the block. Other requests will be sent to the + # default application specified by run outside the block. + # + # Rack::Builder.app do + # map '/heartbeat' do + # run Heartbeat + # end + # run App + # end + # + # The +use+ method can also be used inside the block to specify middleware to run under a specific path: + # + # Rack::Builder.app do + # map '/heartbeat' do + # use Middleware + # run Heartbeat + # end + # run App + # end + # + # This example includes a piece of middleware which will run before +/heartbeat+ requests hit +Heartbeat+. + # + # Note that providing a +path+ of +/+ will ignore any default application given in a +run+ statement + # outside the block. + def map(path, &block) + @map ||= {} + @map[path] = block + end + + # Freeze the app (set using run) and all middleware instances when building the application + # in to_app. + def freeze_app + @freeze_app = true + end + + # Return the Rack application generated by this instance. + def to_app + app = @map ? generate_map(@run, @map) : @run + fail "missing run or map statement" unless app + app.freeze if @freeze_app + app = @use.reverse.inject(app) { |a, e| e[a].tap { |x| x.freeze if @freeze_app } } + @warmup.call(app) if @warmup + app + end + + # Call the Rack application generated by this builder instance. Note that + # this rebuilds the Rack application and runs the warmup code (if any) + # every time it is called, so it should not be used if performance is important. + def call(env) + to_app.call(env) + end + + private + + # Generate a URLMap instance by generating new Rack applications for each + # map block in this instance. + def generate_map(default_app, mapping) + mapped = default_app ? { '/' => default_app } : {} + mapping.each { |r, b| mapped[r] = self.class.new(default_app, &b).to_app } + URLMap.new(mapped) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/cascade.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/cascade.rb new file mode 100644 index 0000000..d71274c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/cascade.rb @@ -0,0 +1,68 @@ +# frozen_string_literal: true + +module Rack + # Rack::Cascade tries a request on several apps, and returns the + # first response that is not 404 or 405 (or in a list of configured + # status codes). If all applications tried return one of the configured + # status codes, return the last response. + + class Cascade + # deprecated, no longer used + NotFound = [404, { CONTENT_TYPE => "text/plain" }, []] + + # An array of applications to try in order. + attr_reader :apps + + # Set the apps to send requests to, and what statuses result in + # cascading. Arguments: + # + # apps: An enumerable of rack applications. + # cascade_for: The statuses to use cascading for. If a response is received + # from an app, the next app is tried. + def initialize(apps, cascade_for = [404, 405]) + @apps = [] + apps.each { |app| add app } + + @cascade_for = {} + [*cascade_for].each { |status| @cascade_for[status] = true } + end + + # Call each app in order. If the responses uses a status that requires + # cascading, try the next app. If all responses require cascading, + # return the response from the last app. + def call(env) + return [404, { CONTENT_TYPE => "text/plain" }, []] if @apps.empty? + result = nil + last_body = nil + + @apps.each do |app| + # The SPEC says that the body must be closed after it has been iterated + # by the server, or if it is replaced by a middleware action. Cascade + # replaces the body each time a cascade happens. It is assumed that nil + # does not respond to close, otherwise the previous application body + # will be closed. The final application body will not be closed, as it + # will be passed to the server as a result. + last_body.close if last_body.respond_to? :close + + result = app.call(env) + return result unless @cascade_for.include?(result[0].to_i) + last_body = result[2] + end + + result + end + + # Append an app to the list of apps to cascade. This app will + # be tried last. + def add(app) + @apps << app + end + + # Whether the given app is one of the apps to cascade to. + def include?(app) + @apps.include?(app) + end + + alias_method :<<, :add + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/chunked.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/chunked.rb new file mode 100644 index 0000000..84c6600 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/chunked.rb @@ -0,0 +1,117 @@ +# frozen_string_literal: true + +module Rack + + # Middleware that applies chunked transfer encoding to response bodies + # when the response does not include a Content-Length header. + # + # This supports the Trailer response header to allow the use of trailing + # headers in the chunked encoding. However, using this requires you manually + # specify a response body that supports a +trailers+ method. Example: + # + # [200, { 'Trailer' => 'Expires'}, ["Hello", "World"]] + # # error raised + # + # body = ["Hello", "World"] + # def body.trailers + # { 'Expires' => Time.now.to_s } + # end + # [200, { 'Trailer' => 'Expires'}, body] + # # No exception raised + class Chunked + include Rack::Utils + + # A body wrapper that emits chunked responses. + class Body + TERM = "\r\n" + TAIL = "0#{TERM}" + + # Store the response body to be chunked. + def initialize(body) + @body = body + end + + # For each element yielded by the response body, yield + # the element in chunked encoding. + def each(&block) + term = TERM + @body.each do |chunk| + size = chunk.bytesize + next if size == 0 + + yield [size.to_s(16), term, chunk.b, term].join + end + yield TAIL + yield_trailers(&block) + yield term + end + + # Close the response body if the response body supports it. + def close + @body.close if @body.respond_to?(:close) + end + + private + + # Do nothing as this class does not support trailer headers. + def yield_trailers + end + end + + # A body wrapper that emits chunked responses and also supports + # sending Trailer headers. Note that the response body provided to + # initialize must have a +trailers+ method that returns a hash + # of trailer headers, and the rack response itself should have a + # Trailer header listing the headers that the +trailers+ method + # will return. + class TrailerBody < Body + private + + # Yield strings for each trailer header. + def yield_trailers + @body.trailers.each_pair do |k, v| + yield "#{k}: #{v}\r\n" + end + end + end + + def initialize(app) + @app = app + end + + # Whether the HTTP version supports chunked encoding (HTTP 1.1 does). + def chunkable_version?(ver) + case ver + # pre-HTTP/1.0 (informally "HTTP/0.9") HTTP requests did not have + # a version (nor response headers) + when 'HTTP/1.0', nil, 'HTTP/0.9' + false + else + true + end + end + + # If the rack app returns a response that should have a body, + # but does not have Content-Length or Transfer-Encoding headers, + # modify the response to use chunked Transfer-Encoding. + def call(env) + status, headers, body = @app.call(env) + headers = HeaderHash[headers] + + if chunkable_version?(env[SERVER_PROTOCOL]) && + !STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) && + !headers[CONTENT_LENGTH] && + !headers[TRANSFER_ENCODING] + + headers[TRANSFER_ENCODING] = 'chunked' + if headers['Trailer'] + body = TrailerBody.new(body) + else + body = Body.new(body) + end + end + + [status, headers, body] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/common_logger.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/common_logger.rb new file mode 100644 index 0000000..3810b26 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/common_logger.rb @@ -0,0 +1,80 @@ +# frozen_string_literal: true + +module Rack + # Rack::CommonLogger forwards every request to the given +app+, and + # logs a line in the + # {Apache common log format}[http://httpd.apache.org/docs/1.3/logs.html#common] + # to the configured logger. + class CommonLogger + # Common Log Format: http://httpd.apache.org/docs/1.3/logs.html#common + # + # lilith.local - - [07/Aug/2006 23:58:02 -0400] "GET / HTTP/1.1" 500 - + # + # %{%s - %s [%s] "%s %s%s %s" %d %s\n} % + # + # The actual format is slightly different than the above due to the + # separation of SCRIPT_NAME and PATH_INFO, and because the elapsed + # time in seconds is included at the end. + FORMAT = %{%s - %s [%s] "%s %s%s%s %s" %d %s %0.4f\n} + + # +logger+ can be any object that supports the +write+ or +<<+ methods, + # which includes the standard library Logger. These methods are called + # with a single string argument, the log message. + # If +logger+ is nil, CommonLogger will fall back env['rack.errors']. + def initialize(app, logger = nil) + @app = app + @logger = logger + end + + # Log all requests in common_log format after a response has been + # returned. Note that if the app raises an exception, the request + # will not be logged, so if exception handling middleware are used, + # they should be loaded after this middleware. Additionally, because + # the logging happens after the request body has been fully sent, any + # exceptions raised during the sending of the response body will + # cause the request not to be logged. + def call(env) + began_at = Utils.clock_time + status, headers, body = @app.call(env) + headers = Utils::HeaderHash[headers] + body = BodyProxy.new(body) { log(env, status, headers, began_at) } + [status, headers, body] + end + + private + + # Log the request to the configured logger. + def log(env, status, header, began_at) + length = extract_content_length(header) + + msg = FORMAT % [ + env['HTTP_X_FORWARDED_FOR'] || env["REMOTE_ADDR"] || "-", + env["REMOTE_USER"] || "-", + Time.now.strftime("%d/%b/%Y:%H:%M:%S %z"), + env[REQUEST_METHOD], + env[SCRIPT_NAME], + env[PATH_INFO], + env[QUERY_STRING].empty? ? "" : "?#{env[QUERY_STRING]}", + env[SERVER_PROTOCOL], + status.to_s[0..3], + length, + Utils.clock_time - began_at ] + + logger = @logger || env[RACK_ERRORS] + # Standard library logger doesn't support write but it supports << which actually + # calls to write on the log device without formatting + if logger.respond_to?(:write) + logger.write(msg) + else + logger << msg + end + end + + # Attempt to determine the content length for the response to + # include it in the logged data. + def extract_content_length(headers) + value = headers[CONTENT_LENGTH] + !value || value.to_s == '0' ? '-' : value + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/conditional_get.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/conditional_get.rb new file mode 100644 index 0000000..7b7808a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/conditional_get.rb @@ -0,0 +1,83 @@ +# frozen_string_literal: true + +module Rack + + # Middleware that enables conditional GET using If-None-Match and + # If-Modified-Since. The application should set either or both of the + # Last-Modified or Etag response headers according to RFC 2616. When + # either of the conditions is met, the response body is set to be zero + # length and the response status is set to 304 Not Modified. + # + # Applications that defer response body generation until the body's each + # message is received will avoid response body generation completely when + # a conditional GET matches. + # + # Adapted from Michael Klishin's Merb implementation: + # https://github.com/wycats/merb/blob/master/merb-core/lib/merb-core/rack/middleware/conditional_get.rb + class ConditionalGet + def initialize(app) + @app = app + end + + # Return empty 304 response if the response has not been + # modified since the last request. + def call(env) + case env[REQUEST_METHOD] + when "GET", "HEAD" + status, headers, body = @app.call(env) + headers = Utils::HeaderHash[headers] + if status == 200 && fresh?(env, headers) + status = 304 + headers.delete(CONTENT_TYPE) + headers.delete(CONTENT_LENGTH) + original_body = body + body = Rack::BodyProxy.new([]) do + original_body.close if original_body.respond_to?(:close) + end + end + [status, headers, body] + else + @app.call(env) + end + end + + private + + # Return whether the response has not been modified since the + # last request. + def fresh?(env, headers) + # If-None-Match has priority over If-Modified-Since per RFC 7232 + if none_match = env['HTTP_IF_NONE_MATCH'] + etag_matches?(none_match, headers) + elsif (modified_since = env['HTTP_IF_MODIFIED_SINCE']) && (modified_since = to_rfc2822(modified_since)) + modified_since?(modified_since, headers) + end + end + + # Whether the ETag response header matches the If-None-Match request header. + # If so, the request has not been modified. + def etag_matches?(none_match, headers) + headers['ETag'] == none_match + end + + # Whether the Last-Modified response header matches the If-Modified-Since + # request header. If so, the request has not been modified. + def modified_since?(modified_since, headers) + last_modified = to_rfc2822(headers['Last-Modified']) and + modified_since >= last_modified + end + + # Return a Time object for the given string (which should be in RFC2822 + # format), or nil if the string cannot be parsed. + def to_rfc2822(since) + # shortest possible valid date is the obsolete: 1 Nov 97 09:55 A + # anything shorter is invalid, this avoids exceptions for common cases + # most common being the empty string + if since && since.length >= 16 + # NOTE: there is no trivial way to write this in a non exception way + # _rfc2822 returns a hash but is not that usable + Time.rfc2822(since) rescue nil + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/config.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/config.rb new file mode 100644 index 0000000..41f6f7d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/config.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +module Rack + # Rack::Config modifies the environment using the block given during + # initialization. + # + # Example: + # use Rack::Config do |env| + # env['my-key'] = 'some-value' + # end + class Config + def initialize(app, &block) + @app = app + @block = block + end + + def call(env) + @block.call(env) + @app.call(env) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/content_length.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/content_length.rb new file mode 100644 index 0000000..9e2b5fc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/content_length.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +module Rack + + # Sets the Content-Length header on responses that do not specify + # a Content-Length or Transfer-Encoding header. Note that this + # does not fix responses that have an invalid Content-Length + # header specified. + class ContentLength + include Rack::Utils + + def initialize(app) + @app = app + end + + def call(env) + status, headers, body = @app.call(env) + headers = HeaderHash[headers] + + if !STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) && + !headers[CONTENT_LENGTH] && + !headers[TRANSFER_ENCODING] + + obody = body + body, length = [], 0 + obody.each { |part| body << part; length += part.bytesize } + + body = BodyProxy.new(body) do + obody.close if obody.respond_to?(:close) + end + + headers[CONTENT_LENGTH] = length.to_s + end + + [status, headers, body] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/content_type.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/content_type.rb new file mode 100644 index 0000000..503f707 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/content_type.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +module Rack + + # Sets the Content-Type header on responses which don't have one. + # + # Builder Usage: + # use Rack::ContentType, "text/plain" + # + # When no content type argument is provided, "text/html" is the + # default. + class ContentType + include Rack::Utils + + def initialize(app, content_type = "text/html") + @app, @content_type = app, content_type + end + + def call(env) + status, headers, body = @app.call(env) + headers = Utils::HeaderHash[headers] + + unless STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) + headers[CONTENT_TYPE] ||= @content_type + end + + [status, headers, body] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/core_ext/regexp.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/core_ext/regexp.rb new file mode 100644 index 0000000..a32fcdf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/core_ext/regexp.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +# Regexp has `match?` since Ruby 2.4 +# so to support Ruby < 2.4 we need to define this method + +module Rack + module RegexpExtensions + refine Regexp do + def match?(string, pos = 0) + !!match(string, pos) + end + end unless //.respond_to?(:match?) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/deflater.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/deflater.rb new file mode 100644 index 0000000..e177fab --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/deflater.rb @@ -0,0 +1,144 @@ +# frozen_string_literal: true + +require "zlib" +require "time" # for Time.httpdate + +module Rack + # This middleware enables content encoding of http responses, + # usually for purposes of compression. + # + # Currently supported encodings: + # + # * gzip + # * identity (no transformation) + # + # This middleware automatically detects when encoding is supported + # and allowed. For example no encoding is made when a cache + # directive of 'no-transform' is present, when the response status + # code is one that doesn't allow an entity body, or when the body + # is empty. + # + # Note that despite the name, Deflater does not support the +deflate+ + # encoding. + class Deflater + (require_relative 'core_ext/regexp'; using ::Rack::RegexpExtensions) if RUBY_VERSION < '2.4' + + # Creates Rack::Deflater middleware. Options: + # + # :if :: a lambda enabling / disabling deflation based on returned boolean value + # (e.g use Rack::Deflater, :if => lambda { |*, body| sum=0; body.each { |i| sum += i.length }; sum > 512 }). + # However, be aware that calling `body.each` inside the block will break cases where `body.each` is not idempotent, + # such as when it is an +IO+ instance. + # :include :: a list of content types that should be compressed. By default, all content types are compressed. + # :sync :: determines if the stream is going to be flushed after every chunk. Flushing after every chunk reduces + # latency for time-sensitive streaming applications, but hurts compression and throughput. + # Defaults to +true+. + def initialize(app, options = {}) + @app = app + @condition = options[:if] + @compressible_types = options[:include] + @sync = options.fetch(:sync, true) + end + + def call(env) + status, headers, body = @app.call(env) + headers = Utils::HeaderHash[headers] + + unless should_deflate?(env, status, headers, body) + return [status, headers, body] + end + + request = Request.new(env) + + encoding = Utils.select_best_encoding(%w(gzip identity), + request.accept_encoding) + + # Set the Vary HTTP header. + vary = headers["Vary"].to_s.split(",").map(&:strip) + unless vary.include?("*") || vary.include?("Accept-Encoding") + headers["Vary"] = vary.push("Accept-Encoding").join(",") + end + + case encoding + when "gzip" + headers['Content-Encoding'] = "gzip" + headers.delete(CONTENT_LENGTH) + mtime = headers["Last-Modified"] + mtime = Time.httpdate(mtime).to_i if mtime + [status, headers, GzipStream.new(body, mtime, @sync)] + when "identity" + [status, headers, body] + when nil + message = "An acceptable encoding for the requested resource #{request.fullpath} could not be found." + bp = Rack::BodyProxy.new([message]) { body.close if body.respond_to?(:close) } + [406, { CONTENT_TYPE => "text/plain", CONTENT_LENGTH => message.length.to_s }, bp] + end + end + + # Body class used for gzip encoded responses. + class GzipStream + # Initialize the gzip stream. Arguments: + # body :: Response body to compress with gzip + # mtime :: The modification time of the body, used to set the + # modification time in the gzip header. + # sync :: Whether to flush each gzip chunk as soon as it is ready. + def initialize(body, mtime, sync) + @body = body + @mtime = mtime + @sync = sync + end + + # Yield gzip compressed strings to the given block. + def each(&block) + @writer = block + gzip = ::Zlib::GzipWriter.new(self) + gzip.mtime = @mtime if @mtime + @body.each { |part| + # Skip empty strings, as they would result in no output, + # and flushing empty parts would raise Zlib::BufError. + next if part.empty? + + gzip.write(part) + gzip.flush if @sync + } + ensure + gzip.close + end + + # Call the block passed to #each with the the gzipped data. + def write(data) + @writer.call(data) + end + + # Close the original body if possible. + def close + @body.close if @body.respond_to?(:close) + end + end + + private + + # Whether the body should be compressed. + def should_deflate?(env, status, headers, body) + # Skip compressing empty entity body responses and responses with + # no-transform set. + if Utils::STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) || + /\bno-transform\b/.match?(headers['Cache-Control'].to_s) || + headers['Content-Encoding']&.!~(/\bidentity\b/) + return false + end + + # Skip if @compressible_types are given and does not include request's content type + return false if @compressible_types && !(headers.has_key?('Content-Type') && @compressible_types.include?(headers['Content-Type'][/[^;]*/])) + + # Skip if @condition lambda is given and evaluates to false + return false if @condition && !@condition.call(env, status, headers, body) + + # No point in compressing empty body, also handles usage with + # Rack::Sendfile. + return false if headers[CONTENT_LENGTH] == '0' + + true + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/directory.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/directory.rb new file mode 100644 index 0000000..be72be0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/directory.rb @@ -0,0 +1,199 @@ +# frozen_string_literal: true + +require 'time' + +module Rack + # Rack::Directory serves entries below the +root+ given, according to the + # path info of the Rack request. If a directory is found, the file's contents + # will be presented in an html based index. If a file is found, the env will + # be passed to the specified +app+. + # + # If +app+ is not specified, a Rack::Files of the same +root+ will be used. + + class Directory + DIR_FILE = "%s%s%s%s\n" + DIR_PAGE_HEADER = <<-PAGE + + %s + + + +

%s

+
+ + + + + + + + PAGE + DIR_PAGE_FOOTER = <<-PAGE +
NameSizeTypeLast Modified
+
+ + PAGE + + # Body class for directory entries, showing an index page with links + # to each file. + class DirectoryBody < Struct.new(:root, :path, :files) + # Yield strings for each part of the directory entry + def each + show_path = Utils.escape_html(path.sub(/^#{root}/, '')) + yield(DIR_PAGE_HEADER % [ show_path, show_path ]) + + unless path.chomp('/') == root + yield(DIR_FILE % DIR_FILE_escape(files.call('..'))) + end + + Dir.foreach(path) do |basename| + next if basename.start_with?('.') + next unless f = files.call(basename) + yield(DIR_FILE % DIR_FILE_escape(f)) + end + + yield(DIR_PAGE_FOOTER) + end + + private + + # Escape each element in the array of html strings. + def DIR_FILE_escape(htmls) + htmls.map { |e| Utils.escape_html(e) } + end + end + + # The root of the directory hierarchy. Only requests for files and + # directories inside of the root directory are supported. + attr_reader :root + + # Set the root directory and application for serving files. + def initialize(root, app = nil) + @root = ::File.expand_path(root) + @app = app || Files.new(@root) + @head = Head.new(method(:get)) + end + + def call(env) + # strip body if this is a HEAD call + @head.call env + end + + # Internals of request handling. Similar to call but does + # not remove body for HEAD requests. + def get(env) + script_name = env[SCRIPT_NAME] + path_info = Utils.unescape_path(env[PATH_INFO]) + + if client_error_response = check_bad_request(path_info) || check_forbidden(path_info) + client_error_response + else + path = ::File.join(@root, path_info) + list_path(env, path, path_info, script_name) + end + end + + # Rack response to use for requests with invalid paths, or nil if path is valid. + def check_bad_request(path_info) + return if Utils.valid_path?(path_info) + + body = "Bad Request\n" + [400, { CONTENT_TYPE => "text/plain", + CONTENT_LENGTH => body.bytesize.to_s, + "X-Cascade" => "pass" }, [body]] + end + + # Rack response to use for requests with paths outside the root, or nil if path is inside the root. + def check_forbidden(path_info) + return unless path_info.include? ".." + return if ::File.expand_path(::File.join(@root, path_info)).start_with?(@root) + + body = "Forbidden\n" + [403, { CONTENT_TYPE => "text/plain", + CONTENT_LENGTH => body.bytesize.to_s, + "X-Cascade" => "pass" }, [body]] + end + + # Rack response to use for directories under the root. + def list_directory(path_info, path, script_name) + url_head = (script_name.split('/') + path_info.split('/')).map do |part| + Utils.escape_path part + end + + # Globbing not safe as path could contain glob metacharacters + body = DirectoryBody.new(@root, path, ->(basename) do + stat = stat(::File.join(path, basename)) + next unless stat + + url = ::File.join(*url_head + [Utils.escape_path(basename)]) + mtime = stat.mtime.httpdate + if stat.directory? + type = 'directory' + size = '-' + url << '/' + if basename == '..' + basename = 'Parent Directory' + else + basename << '/' + end + else + type = Mime.mime_type(::File.extname(basename)) + size = filesize_format(stat.size) + end + + [ url, basename, size, type, mtime ] + end) + + [ 200, { CONTENT_TYPE => 'text/html; charset=utf-8' }, body ] + end + + # File::Stat for the given path, but return nil for missing/bad entries. + def stat(path) + ::File.stat(path) + rescue Errno::ENOENT, Errno::ELOOP + return nil + end + + # Rack response to use for files and directories under the root. + # Unreadable and non-file, non-directory entries will get a 404 response. + def list_path(env, path, path_info, script_name) + if (stat = stat(path)) && stat.readable? + return @app.call(env) if stat.file? + return list_directory(path_info, path, script_name) if stat.directory? + end + + entity_not_found(path_info) + end + + # Rack response to use for unreadable and non-file, non-directory entries. + def entity_not_found(path_info) + body = "Entity not found: #{path_info}\n" + [404, { CONTENT_TYPE => "text/plain", + CONTENT_LENGTH => body.bytesize.to_s, + "X-Cascade" => "pass" }, [body]] + end + + # Stolen from Ramaze + FILESIZE_FORMAT = [ + ['%.1fT', 1 << 40], + ['%.1fG', 1 << 30], + ['%.1fM', 1 << 20], + ['%.1fK', 1 << 10], + ] + + # Provide human readable file sizes + def filesize_format(int) + FILESIZE_FORMAT.each do |format, size| + return format % (int.to_f / size) if int >= size + end + + "#{int}B" + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/etag.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/etag.rb new file mode 100644 index 0000000..aceb449 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/etag.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true + +require_relative '../rack' +require 'digest/sha2' + +module Rack + # Automatically sets the ETag header on all String bodies. + # + # The ETag header is skipped if ETag or Last-Modified headers are sent or if + # a sendfile body (body.responds_to :to_path) is given (since such cases + # should be handled by apache/nginx). + # + # On initialization, you can pass two parameters: a Cache-Control directive + # used when Etag is absent and a directive when it is present. The first + # defaults to nil, while the second defaults to "max-age=0, private, must-revalidate" + class ETag + ETAG_STRING = Rack::ETAG + DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate" + + def initialize(app, no_cache_control = nil, cache_control = DEFAULT_CACHE_CONTROL) + @app = app + @cache_control = cache_control + @no_cache_control = no_cache_control + end + + def call(env) + status, headers, body = @app.call(env) + + if etag_status?(status) && etag_body?(body) && !skip_caching?(headers) + original_body = body + digest, new_body = digest_body(body) + body = Rack::BodyProxy.new(new_body) do + original_body.close if original_body.respond_to?(:close) + end + headers[ETAG_STRING] = %(W/"#{digest}") if digest + end + + unless headers[CACHE_CONTROL] + if digest + headers[CACHE_CONTROL] = @cache_control if @cache_control + else + headers[CACHE_CONTROL] = @no_cache_control if @no_cache_control + end + end + + [status, headers, body] + end + + private + + def etag_status?(status) + status == 200 || status == 201 + end + + def etag_body?(body) + !body.respond_to?(:to_path) + end + + def skip_caching?(headers) + headers.key?(ETAG_STRING) || headers.key?('Last-Modified') + end + + def digest_body(body) + parts = [] + digest = nil + + body.each do |part| + parts << part + (digest ||= Digest::SHA256.new) << part unless part.empty? + end + + [digest && digest.hexdigest.byteslice(0, 32), parts] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/events.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/events.rb new file mode 100644 index 0000000..65055fd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/events.rb @@ -0,0 +1,153 @@ +# frozen_string_literal: true + +module Rack + ### This middleware provides hooks to certain places in the request / + # response lifecycle. This is so that middleware that don't need to filter + # the response data can safely leave it alone and not have to send messages + # down the traditional "rack stack". + # + # The events are: + # + # * on_start(request, response) + # + # This event is sent at the start of the request, before the next + # middleware in the chain is called. This method is called with a request + # object, and a response object. Right now, the response object is always + # nil, but in the future it may actually be a real response object. + # + # * on_commit(request, response) + # + # The response has been committed. The application has returned, but the + # response has not been sent to the webserver yet. This method is always + # called with a request object and the response object. The response + # object is constructed from the rack triple that the application returned. + # Changes may still be made to the response object at this point. + # + # * on_send(request, response) + # + # The webserver has started iterating over the response body and presumably + # has started sending data over the wire. This method is always called with + # a request object and the response object. The response object is + # constructed from the rack triple that the application returned. Changes + # SHOULD NOT be made to the response object as the webserver has already + # started sending data. Any mutations will likely result in an exception. + # + # * on_finish(request, response) + # + # The webserver has closed the response, and all data has been written to + # the response socket. The request and response object should both be + # read-only at this point. The body MAY NOT be available on the response + # object as it may have been flushed to the socket. + # + # * on_error(request, response, error) + # + # An exception has occurred in the application or an `on_commit` event. + # This method will get the request, the response (if available) and the + # exception that was raised. + # + # ## Order + # + # `on_start` is called on the handlers in the order that they were passed to + # the constructor. `on_commit`, on_send`, `on_finish`, and `on_error` are + # called in the reverse order. `on_finish` handlers are called inside an + # `ensure` block, so they are guaranteed to be called even if something + # raises an exception. If something raises an exception in a `on_finish` + # method, then nothing is guaranteed. + + class Events + module Abstract + def on_start(req, res) + end + + def on_commit(req, res) + end + + def on_send(req, res) + end + + def on_finish(req, res) + end + + def on_error(req, res, e) + end + end + + class EventedBodyProxy < Rack::BodyProxy # :nodoc: + attr_reader :request, :response + + def initialize(body, request, response, handlers, &block) + super(body, &block) + @request = request + @response = response + @handlers = handlers + end + + def each + @handlers.reverse_each { |handler| handler.on_send request, response } + super + end + end + + class BufferedResponse < Rack::Response::Raw # :nodoc: + attr_reader :body + + def initialize(status, headers, body) + super(status, headers) + @body = body + end + + def to_a; [status, headers, body]; end + end + + def initialize(app, handlers) + @app = app + @handlers = handlers + end + + def call(env) + request = make_request env + on_start request, nil + + begin + status, headers, body = @app.call request.env + response = make_response status, headers, body + on_commit request, response + rescue StandardError => e + on_error request, response, e + on_finish request, response + raise + end + + body = EventedBodyProxy.new(body, request, response, @handlers) do + on_finish request, response + end + [response.status, response.headers, body] + end + + private + + def on_error(request, response, e) + @handlers.reverse_each { |handler| handler.on_error request, response, e } + end + + def on_commit(request, response) + @handlers.reverse_each { |handler| handler.on_commit request, response } + end + + def on_start(request, response) + @handlers.each { |handler| handler.on_start request, nil } + end + + def on_finish(request, response) + @handlers.reverse_each { |handler| handler.on_finish request, response } + end + + def make_request(env) + Rack::Request.new env + end + + def make_response(status, headers, body) + BufferedResponse.new status, headers, body + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/file.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/file.rb new file mode 100644 index 0000000..fdcf9b3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/file.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +require_relative 'files' + +module Rack + File = Files +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/files.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/files.rb new file mode 100644 index 0000000..e745eb3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/files.rb @@ -0,0 +1,218 @@ +# frozen_string_literal: true + +require 'time' + +module Rack + # Rack::Files serves files below the +root+ directory given, according to the + # path info of the Rack request. + # e.g. when Rack::Files.new("/etc") is used, you can access 'passwd' file + # as http://localhost:9292/passwd + # + # Handlers can detect if bodies are a Rack::Files, and use mechanisms + # like sendfile on the +path+. + + class Files + ALLOWED_VERBS = %w[GET HEAD OPTIONS] + ALLOW_HEADER = ALLOWED_VERBS.join(', ') + MULTIPART_BOUNDARY = 'AaB03x' + + # @todo remove in 3.0 + def self.method_added(name) + if name == :response_body + raise "#{self.class}\#response_body is no longer supported." + end + super + end + + attr_reader :root + + def initialize(root, headers = {}, default_mime = 'text/plain') + @root = (::File.expand_path(root) if root) + @headers = headers + @default_mime = default_mime + @head = Rack::Head.new(lambda { |env| get env }) + end + + def call(env) + # HEAD requests drop the response body, including 4xx error messages. + @head.call env + end + + def get(env) + request = Rack::Request.new env + unless ALLOWED_VERBS.include? request.request_method + return fail(405, "Method Not Allowed", { 'Allow' => ALLOW_HEADER }) + end + + path_info = Utils.unescape_path request.path_info + return fail(400, "Bad Request") unless Utils.valid_path?(path_info) + + clean_path_info = Utils.clean_path_info(path_info) + path = ::File.join(@root, clean_path_info) + + available = begin + ::File.file?(path) && ::File.readable?(path) + rescue SystemCallError + # Not sure in what conditions this exception can occur, but this + # is a safe way to handle such an error. + # :nocov: + false + # :nocov: + end + + if available + serving(request, path) + else + fail(404, "File not found: #{path_info}") + end + end + + def serving(request, path) + if request.options? + return [200, { 'Allow' => ALLOW_HEADER, CONTENT_LENGTH => '0' }, []] + end + last_modified = ::File.mtime(path).httpdate + return [304, {}, []] if request.get_header('HTTP_IF_MODIFIED_SINCE') == last_modified + + headers = { "Last-Modified" => last_modified } + mime_type = mime_type path, @default_mime + headers[CONTENT_TYPE] = mime_type if mime_type + + # Set custom headers + headers.merge!(@headers) if @headers + + status = 200 + size = filesize path + + ranges = Rack::Utils.get_byte_ranges(request.get_header('HTTP_RANGE'), size) + if ranges.nil? + # No ranges: + ranges = [0..size - 1] + elsif ranges.empty? + # Unsatisfiable. Return error, and file size: + response = fail(416, "Byte range unsatisfiable") + response[1]["Content-Range"] = "bytes */#{size}" + return response + elsif ranges.size >= 1 + # Partial content + partial_content = true + + if ranges.size == 1 + range = ranges[0] + headers["Content-Range"] = "bytes #{range.begin}-#{range.end}/#{size}" + else + headers[CONTENT_TYPE] = "multipart/byteranges; boundary=#{MULTIPART_BOUNDARY}" + end + + status = 206 + body = BaseIterator.new(path, ranges, mime_type: mime_type, size: size) + size = body.bytesize + end + + headers[CONTENT_LENGTH] = size.to_s + + if request.head? + body = [] + elsif !partial_content + body = Iterator.new(path, ranges, mime_type: mime_type, size: size) + end + + [status, headers, body] + end + + class BaseIterator + attr_reader :path, :ranges, :options + + def initialize(path, ranges, options) + @path = path + @ranges = ranges + @options = options + end + + def each + ::File.open(path, "rb") do |file| + ranges.each do |range| + yield multipart_heading(range) if multipart? + + each_range_part(file, range) do |part| + yield part + end + end + + yield "\r\n--#{MULTIPART_BOUNDARY}--\r\n" if multipart? + end + end + + def bytesize + size = ranges.inject(0) do |sum, range| + sum += multipart_heading(range).bytesize if multipart? + sum += range.size + end + size += "\r\n--#{MULTIPART_BOUNDARY}--\r\n".bytesize if multipart? + size + end + + def close; end + + private + + def multipart? + ranges.size > 1 + end + + def multipart_heading(range) +<<-EOF +\r +--#{MULTIPART_BOUNDARY}\r +Content-Type: #{options[:mime_type]}\r +Content-Range: bytes #{range.begin}-#{range.end}/#{options[:size]}\r +\r +EOF + end + + def each_range_part(file, range) + file.seek(range.begin) + remaining_len = range.end - range.begin + 1 + while remaining_len > 0 + part = file.read([8192, remaining_len].min) + break unless part + remaining_len -= part.length + + yield part + end + end + end + + class Iterator < BaseIterator + alias :to_path :path + end + + private + + def fail(status, body, headers = {}) + body += "\n" + + [ + status, + { + CONTENT_TYPE => "text/plain", + CONTENT_LENGTH => body.size.to_s, + "X-Cascade" => "pass" + }.merge!(headers), + [body] + ] + end + + # The MIME type for the contents of the file located at @path + def mime_type(path, default_mime) + Mime.mime_type(::File.extname(path), default_mime) + end + + def filesize(path) + # We check via File::size? whether this file provides size info + # via stat (e.g. /proc files often don't), otherwise we have to + # figure it out by reading the whole file into memory. + ::File.size?(path) || ::File.read(path).bytesize + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler.rb new file mode 100644 index 0000000..df17b23 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler.rb @@ -0,0 +1,104 @@ +# frozen_string_literal: true + +module Rack + # *Handlers* connect web servers with Rack. + # + # Rack includes Handlers for Thin, WEBrick, FastCGI, CGI, SCGI + # and LiteSpeed. + # + # Handlers usually are activated by calling MyHandler.run(myapp). + # A second optional hash can be passed to include server-specific + # configuration. + module Handler + def self.get(server) + return unless server + server = server.to_s + + unless @handlers.include? server + load_error = try_require('rack/handler', server) + end + + if klass = @handlers[server] + const_get(klass) + else + const_get(server, false) + end + + rescue NameError => name_error + raise load_error || name_error + end + + # Select first available Rack handler given an `Array` of server names. + # Raises `LoadError` if no handler was found. + # + # > pick ['thin', 'webrick'] + # => Rack::Handler::WEBrick + def self.pick(server_names) + server_names = Array(server_names) + server_names.each do |server_name| + begin + return get(server_name.to_s) + rescue LoadError, NameError + end + end + + raise LoadError, "Couldn't find handler for: #{server_names.join(', ')}." + end + + SERVER_NAMES = %w(puma thin falcon webrick).freeze + private_constant :SERVER_NAMES + + def self.default + # Guess. + if ENV.include?("PHP_FCGI_CHILDREN") + Rack::Handler::FastCGI + elsif ENV.include?(REQUEST_METHOD) + Rack::Handler::CGI + elsif ENV.include?("RACK_HANDLER") + self.get(ENV["RACK_HANDLER"]) + else + pick SERVER_NAMES + end + end + + # Transforms server-name constants to their canonical form as filenames, + # then tries to require them but silences the LoadError if not found + # + # Naming convention: + # + # Foo # => 'foo' + # FooBar # => 'foo_bar.rb' + # FooBAR # => 'foobar.rb' + # FOObar # => 'foobar.rb' + # FOOBAR # => 'foobar.rb' + # FooBarBaz # => 'foo_bar_baz.rb' + def self.try_require(prefix, const_name) + file = const_name.gsub(/^[A-Z]+/) { |pre| pre.downcase }. + gsub(/[A-Z]+[^A-Z]/, '_\&').downcase + + require(::File.join(prefix, file)) + nil + rescue LoadError => error + error + end + + def self.register(server, klass) + @handlers ||= {} + @handlers[server.to_s] = klass.to_s + end + + autoload :CGI, "rack/handler/cgi" + autoload :FastCGI, "rack/handler/fastcgi" + autoload :WEBrick, "rack/handler/webrick" + autoload :LSWS, "rack/handler/lsws" + autoload :SCGI, "rack/handler/scgi" + autoload :Thin, "rack/handler/thin" + + register 'cgi', 'Rack::Handler::CGI' + register 'fastcgi', 'Rack::Handler::FastCGI' + register 'webrick', 'Rack::Handler::WEBrick' + register 'lsws', 'Rack::Handler::LSWS' + register 'scgi', 'Rack::Handler::SCGI' + register 'thin', 'Rack::Handler::Thin' + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/cgi.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/cgi.rb new file mode 100644 index 0000000..1c11ab3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/cgi.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +module Rack + module Handler + class CGI + def self.run(app, **options) + $stdin.binmode + serve app + end + + def self.serve(app) + env = ENV.to_hash + env.delete "HTTP_CONTENT_LENGTH" + + env[SCRIPT_NAME] = "" if env[SCRIPT_NAME] == "/" + + env.update( + RACK_VERSION => Rack::VERSION, + RACK_INPUT => Rack::RewindableInput.new($stdin), + RACK_ERRORS => $stderr, + RACK_MULTITHREAD => false, + RACK_MULTIPROCESS => true, + RACK_RUNONCE => true, + RACK_URL_SCHEME => ["yes", "on", "1"].include?(ENV[HTTPS]) ? "https" : "http" + ) + + env[QUERY_STRING] ||= "" + env[HTTP_VERSION] ||= env[SERVER_PROTOCOL] + env[REQUEST_PATH] ||= "/" + + status, headers, body = app.call(env) + begin + send_headers status, headers + send_body body + ensure + body.close if body.respond_to? :close + end + end + + def self.send_headers(status, headers) + $stdout.print "Status: #{status}\r\n" + headers.each { |k, vs| + vs.split("\n").each { |v| + $stdout.print "#{k}: #{v}\r\n" + } + } + $stdout.print "\r\n" + $stdout.flush + end + + def self.send_body(body) + body.each { |part| + $stdout.print part + $stdout.flush + } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/fastcgi.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/fastcgi.rb new file mode 100644 index 0000000..1df123e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/fastcgi.rb @@ -0,0 +1,100 @@ +# frozen_string_literal: true + +require 'fcgi' +require 'socket' + +if defined? FCGI::Stream + class FCGI::Stream + alias _rack_read_without_buffer read + + def read(n, buffer = nil) + buf = _rack_read_without_buffer n + buffer.replace(buf.to_s) if buffer + buf + end + end +end + +module Rack + module Handler + class FastCGI + def self.run(app, **options) + if options[:File] + STDIN.reopen(UNIXServer.new(options[:File])) + elsif options[:Port] + STDIN.reopen(TCPServer.new(options[:Host], options[:Port])) + end + FCGI.each { |request| + serve request, app + } + end + + def self.valid_options + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : '0.0.0.0' + + { + "Host=HOST" => "Hostname to listen on (default: #{default_host})", + "Port=PORT" => "Port to listen on (default: 8080)", + "File=PATH" => "Creates a Domain socket at PATH instead of a TCP socket. Ignores Host and Port if set.", + } + end + + def self.serve(request, app) + env = request.env + env.delete "HTTP_CONTENT_LENGTH" + + env[SCRIPT_NAME] = "" if env[SCRIPT_NAME] == "/" + + rack_input = RewindableInput.new(request.in) + + env.update( + RACK_VERSION => Rack::VERSION, + RACK_INPUT => rack_input, + RACK_ERRORS => request.err, + RACK_MULTITHREAD => false, + RACK_MULTIPROCESS => true, + RACK_RUNONCE => false, + RACK_URL_SCHEME => ["yes", "on", "1"].include?(env[HTTPS]) ? "https" : "http" + ) + + env[QUERY_STRING] ||= "" + env[HTTP_VERSION] ||= env[SERVER_PROTOCOL] + env[REQUEST_PATH] ||= "/" + env.delete "CONTENT_TYPE" if env["CONTENT_TYPE"] == "" + env.delete "CONTENT_LENGTH" if env["CONTENT_LENGTH"] == "" + + begin + status, headers, body = app.call(env) + begin + send_headers request.out, status, headers + send_body request.out, body + ensure + body.close if body.respond_to? :close + end + ensure + rack_input.close + request.finish + end + end + + def self.send_headers(out, status, headers) + out.print "Status: #{status}\r\n" + headers.each { |k, vs| + vs.split("\n").each { |v| + out.print "#{k}: #{v}\r\n" + } + } + out.print "\r\n" + out.flush + end + + def self.send_body(out, body) + body.each { |part| + out.print part + out.flush + } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/lsws.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/lsws.rb new file mode 100644 index 0000000..f12090b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/lsws.rb @@ -0,0 +1,61 @@ +# frozen_string_literal: true + +require 'lsapi' + +module Rack + module Handler + class LSWS + def self.run(app, **options) + while LSAPI.accept != nil + serve app + end + end + def self.serve(app) + env = ENV.to_hash + env.delete "HTTP_CONTENT_LENGTH" + env[SCRIPT_NAME] = "" if env[SCRIPT_NAME] == "/" + + rack_input = RewindableInput.new($stdin.read.to_s) + + env.update( + RACK_VERSION => Rack::VERSION, + RACK_INPUT => rack_input, + RACK_ERRORS => $stderr, + RACK_MULTITHREAD => false, + RACK_MULTIPROCESS => true, + RACK_RUNONCE => false, + RACK_URL_SCHEME => ["yes", "on", "1"].include?(ENV[HTTPS]) ? "https" : "http" + ) + + env[QUERY_STRING] ||= "" + env[HTTP_VERSION] ||= env[SERVER_PROTOCOL] + env[REQUEST_PATH] ||= "/" + status, headers, body = app.call(env) + begin + send_headers status, headers + send_body body + ensure + body.close if body.respond_to? :close + end + ensure + rack_input.close + end + def self.send_headers(status, headers) + print "Status: #{status}\r\n" + headers.each { |k, vs| + vs.split("\n").each { |v| + print "#{k}: #{v}\r\n" + } + } + print "\r\n" + STDOUT.flush + end + def self.send_body(body) + body.each { |part| + print part + STDOUT.flush + } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/scgi.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/scgi.rb new file mode 100644 index 0000000..e3b8d3c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/scgi.rb @@ -0,0 +1,71 @@ +# frozen_string_literal: true + +require 'scgi' +require 'stringio' + +module Rack + module Handler + class SCGI < ::SCGI::Processor + attr_accessor :app + + def self.run(app, **options) + options[:Socket] = UNIXServer.new(options[:File]) if options[:File] + new(options.merge(app: app, + host: options[:Host], + port: options[:Port], + socket: options[:Socket])).listen + end + + def self.valid_options + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : '0.0.0.0' + + { + "Host=HOST" => "Hostname to listen on (default: #{default_host})", + "Port=PORT" => "Port to listen on (default: 8080)", + } + end + + def initialize(settings = {}) + @app = settings[:app] + super(settings) + end + + def process_request(request, input_body, socket) + env = Hash[request] + env.delete "HTTP_CONTENT_TYPE" + env.delete "HTTP_CONTENT_LENGTH" + env[REQUEST_PATH], env[QUERY_STRING] = env["REQUEST_URI"].split('?', 2) + env[HTTP_VERSION] ||= env[SERVER_PROTOCOL] + env[PATH_INFO] = env[REQUEST_PATH] + env[QUERY_STRING] ||= "" + env[SCRIPT_NAME] = "" + + rack_input = StringIO.new(input_body) + rack_input.set_encoding(Encoding::BINARY) + + env.update( + RACK_VERSION => Rack::VERSION, + RACK_INPUT => rack_input, + RACK_ERRORS => $stderr, + RACK_MULTITHREAD => true, + RACK_MULTIPROCESS => true, + RACK_RUNONCE => false, + RACK_URL_SCHEME => ["yes", "on", "1"].include?(env[HTTPS]) ? "https" : "http" + ) + + status, headers, body = app.call(env) + begin + socket.write("Status: #{status}\r\n") + headers.each do |k, vs| + vs.split("\n").each { |v| socket.write("#{k}: #{v}\r\n")} + end + socket.write("\r\n") + body.each {|s| socket.write(s)} + ensure + body.close if body.respond_to? :close + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/thin.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/thin.rb new file mode 100644 index 0000000..393a6e9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/thin.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +require "thin" +require "thin/server" +require "thin/logging" +require "thin/backends/tcp_server" + +module Rack + module Handler + class Thin + def self.run(app, **options) + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : '0.0.0.0' + + host = options.delete(:Host) || default_host + port = options.delete(:Port) || 8080 + args = [host, port, app, options] + # Thin versions below 0.8.0 do not support additional options + args.pop if ::Thin::VERSION::MAJOR < 1 && ::Thin::VERSION::MINOR < 8 + server = ::Thin::Server.new(*args) + yield server if block_given? + server.start + end + + def self.valid_options + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : '0.0.0.0' + + { + "Host=HOST" => "Hostname to listen on (default: #{default_host})", + "Port=PORT" => "Port to listen on (default: 8080)", + } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/webrick.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/webrick.rb new file mode 100644 index 0000000..d2f3897 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/handler/webrick.rb @@ -0,0 +1,129 @@ +# frozen_string_literal: true + +require 'webrick' +require 'stringio' + +# This monkey patch allows for applications to perform their own chunking +# through WEBrick::HTTPResponse if rack is set to true. +class WEBrick::HTTPResponse + attr_accessor :rack + + alias _rack_setup_header setup_header + def setup_header + app_chunking = rack && @header['transfer-encoding'] == 'chunked' + + @chunked = app_chunking if app_chunking + + _rack_setup_header + + @chunked = false if app_chunking + end +end + +module Rack + module Handler + class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet + def self.run(app, **options) + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : nil + + if !options[:BindAddress] || options[:Host] + options[:BindAddress] = options.delete(:Host) || default_host + end + options[:Port] ||= 8080 + if options[:SSLEnable] + require 'webrick/https' + end + + @server = ::WEBrick::HTTPServer.new(options) + @server.mount "/", Rack::Handler::WEBrick, app + yield @server if block_given? + @server.start + end + + def self.valid_options + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : '0.0.0.0' + + { + "Host=HOST" => "Hostname to listen on (default: #{default_host})", + "Port=PORT" => "Port to listen on (default: 8080)", + } + end + + def self.shutdown + if @server + @server.shutdown + @server = nil + end + end + + def initialize(server, app) + super server + @app = app + end + + def service(req, res) + res.rack = true + env = req.meta_vars + env.delete_if { |k, v| v.nil? } + + rack_input = StringIO.new(req.body.to_s) + rack_input.set_encoding(Encoding::BINARY) + + env.update( + RACK_VERSION => Rack::VERSION, + RACK_INPUT => rack_input, + RACK_ERRORS => $stderr, + RACK_MULTITHREAD => true, + RACK_MULTIPROCESS => false, + RACK_RUNONCE => false, + RACK_URL_SCHEME => ["yes", "on", "1"].include?(env[HTTPS]) ? "https" : "http", + RACK_IS_HIJACK => true, + RACK_HIJACK => lambda { raise NotImplementedError, "only partial hijack is supported."}, + RACK_HIJACK_IO => nil + ) + + env[HTTP_VERSION] ||= env[SERVER_PROTOCOL] + env[QUERY_STRING] ||= "" + unless env[PATH_INFO] == "" + path, n = req.request_uri.path, env[SCRIPT_NAME].length + env[PATH_INFO] = path[n, path.length - n] + end + env[REQUEST_PATH] ||= [env[SCRIPT_NAME], env[PATH_INFO]].join + + status, headers, body = @app.call(env) + begin + res.status = status.to_i + io_lambda = nil + headers.each { |k, vs| + if k == RACK_HIJACK + io_lambda = vs + elsif k.downcase == "set-cookie" + res.cookies.concat vs.split("\n") + else + # Since WEBrick won't accept repeated headers, + # merge the values per RFC 1945 section 4.2. + res[k] = vs.split("\n").join(", ") + end + } + + if io_lambda + rd, wr = IO.pipe + res.body = rd + res.chunked = true + io_lambda.call wr + elsif body.respond_to?(:to_path) + res.body = ::File.open(body.to_path, 'rb') + else + body.each { |part| + res.body << part + } + end + ensure + body.close if body.respond_to? :close + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/head.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/head.rb new file mode 100644 index 0000000..8025a27 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/head.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +module Rack + # Rack::Head returns an empty body for all HEAD requests. It leaves + # all other requests unchanged. + class Head + def initialize(app) + @app = app + end + + def call(env) + status, headers, body = @app.call(env) + + if env[REQUEST_METHOD] == HEAD + [ + status, headers, Rack::BodyProxy.new([]) do + body.close if body.respond_to? :close + end + ] + else + [status, headers, body] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/lint.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/lint.rb new file mode 100644 index 0000000..16b5fee --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/lint.rb @@ -0,0 +1,806 @@ +# frozen_string_literal: true + +require 'forwardable' + +module Rack + # Rack::Lint validates your application and the requests and + # responses according to the Rack spec. + + class Lint + def initialize(app) + @app = app + @content_length = nil + end + + # :stopdoc: + + class LintError < RuntimeError; end + module Assertion + def assert(message) + unless yield + raise LintError, message + end + end + end + include Assertion + + ## This specification aims to formalize the Rack protocol. You + ## can (and should) use Rack::Lint to enforce it. + ## + ## When you develop middleware, be sure to add a Lint before and + ## after to catch all mistakes. + + ## = Rack applications + + ## A Rack application is a Ruby object (not a class) that + ## responds to +call+. + def call(env = nil) + dup._call(env) + end + + def _call(env) + ## It takes exactly one argument, the *environment* + assert("No env given") { env } + check_env env + + env[RACK_INPUT] = InputWrapper.new(env[RACK_INPUT]) + env[RACK_ERRORS] = ErrorWrapper.new(env[RACK_ERRORS]) + + ## and returns an Array of exactly three values: + ary = @app.call(env) + assert("response #{ary.inspect} is not an Array , but #{ary.class}") { + ary.kind_of? Array + } + assert("response array #{ary.inspect} has #{ary.size} elements instead of 3") { + ary.size == 3 + } + + status, headers, @body = ary + ## The *status*, + check_status status + ## the *headers*, + check_headers headers + + hijack_proc = check_hijack_response headers, env + if hijack_proc && headers.is_a?(Hash) + headers[RACK_HIJACK] = hijack_proc + end + + ## and the *body*. + check_content_type status, headers + check_content_length status, headers + @head_request = env[REQUEST_METHOD] == HEAD + [status, headers, self] + end + + ## == The Environment + def check_env(env) + ## The environment must be an unfrozen instance of Hash that includes + ## CGI-like headers. The application is free to modify the + ## environment. + assert("env #{env.inspect} is not a Hash, but #{env.class}") { + env.kind_of? Hash + } + assert("env should not be frozen, but is") { + !env.frozen? + } + + ## + ## The environment is required to include these variables + ## (adopted from PEP333), except when they'd be empty, but see + ## below. + + ## REQUEST_METHOD:: The HTTP request method, such as + ## "GET" or "POST". This cannot ever + ## be an empty string, and so is + ## always required. + + ## SCRIPT_NAME:: The initial portion of the request + ## URL's "path" that corresponds to the + ## application object, so that the + ## application knows its virtual + ## "location". This may be an empty + ## string, if the application corresponds + ## to the "root" of the server. + + ## PATH_INFO:: The remainder of the request URL's + ## "path", designating the virtual + ## "location" of the request's target + ## within the application. This may be an + ## empty string, if the request URL targets + ## the application root and does not have a + ## trailing slash. This value may be + ## percent-encoded when originating from + ## a URL. + + ## QUERY_STRING:: The portion of the request URL that + ## follows the ?, if any. May be + ## empty, but is always required! + + ## SERVER_NAME:: When combined with SCRIPT_NAME and + ## PATH_INFO, these variables can be + ## used to complete the URL. Note, however, + ## that HTTP_HOST, if present, + ## should be used in preference to + ## SERVER_NAME for reconstructing + ## the request URL. + ## SERVER_NAME can never be an empty + ## string, and so is always required. + + ## SERVER_PORT:: An optional +Integer+ which is the port the + ## server is running on. Should be specified if + ## the server is running on a non-standard port. + + ## HTTP_ Variables:: Variables corresponding to the + ## client-supplied HTTP request + ## headers (i.e., variables whose + ## names begin with HTTP_). The + ## presence or absence of these + ## variables should correspond with + ## the presence or absence of the + ## appropriate HTTP header in the + ## request. See + ## {RFC3875 section 4.1.18}[https://tools.ietf.org/html/rfc3875#section-4.1.18] + ## for specific behavior. + + ## In addition to this, the Rack environment must include these + ## Rack-specific variables: + + ## rack.version:: The Array representing this version of Rack + ## See Rack::VERSION, that corresponds to + ## the version of this SPEC. + + ## rack.url_scheme:: +http+ or +https+, depending on the + ## request URL. + + ## rack.input:: See below, the input stream. + + ## rack.errors:: See below, the error stream. + + ## rack.multithread:: true if the application object may be + ## simultaneously invoked by another thread + ## in the same process, false otherwise. + + ## rack.multiprocess:: true if an equivalent application object + ## may be simultaneously invoked by another + ## process, false otherwise. + + ## rack.run_once:: true if the server expects + ## (but does not guarantee!) that the + ## application will only be invoked this one + ## time during the life of its containing + ## process. Normally, this will only be true + ## for a server based on CGI + ## (or something similar). + + ## rack.hijack?:: present and true if the server supports + ## connection hijacking. See below, hijacking. + + ## rack.hijack:: an object responding to #call that must be + ## called at least once before using + ## rack.hijack_io. + ## It is recommended #call return rack.hijack_io + ## as well as setting it in env if necessary. + + ## rack.hijack_io:: if rack.hijack? is true, and rack.hijack + ## has received #call, this will contain + ## an object resembling an IO. See hijacking. + + ## Additional environment specifications have approved to + ## standardized middleware APIs. None of these are required to + ## be implemented by the server. + + ## rack.session:: A hash like interface for storing + ## request session data. + ## The store must implement: + if session = env[RACK_SESSION] + ## store(key, value) (aliased as []=); + assert("session #{session.inspect} must respond to store and []=") { + session.respond_to?(:store) && session.respond_to?(:[]=) + } + + ## fetch(key, default = nil) (aliased as []); + assert("session #{session.inspect} must respond to fetch and []") { + session.respond_to?(:fetch) && session.respond_to?(:[]) + } + + ## delete(key); + assert("session #{session.inspect} must respond to delete") { + session.respond_to?(:delete) + } + + ## clear; + assert("session #{session.inspect} must respond to clear") { + session.respond_to?(:clear) + } + + ## to_hash (returning unfrozen Hash instance); + assert("session #{session.inspect} must respond to to_hash and return unfrozen Hash instance") { + session.respond_to?(:to_hash) && session.to_hash.kind_of?(Hash) && !session.to_hash.frozen? + } + end + + ## rack.logger:: A common object interface for logging messages. + ## The object must implement: + if logger = env[RACK_LOGGER] + ## info(message, &block) + assert("logger #{logger.inspect} must respond to info") { + logger.respond_to?(:info) + } + + ## debug(message, &block) + assert("logger #{logger.inspect} must respond to debug") { + logger.respond_to?(:debug) + } + + ## warn(message, &block) + assert("logger #{logger.inspect} must respond to warn") { + logger.respond_to?(:warn) + } + + ## error(message, &block) + assert("logger #{logger.inspect} must respond to error") { + logger.respond_to?(:error) + } + + ## fatal(message, &block) + assert("logger #{logger.inspect} must respond to fatal") { + logger.respond_to?(:fatal) + } + end + + ## rack.multipart.buffer_size:: An Integer hint to the multipart parser as to what chunk size to use for reads and writes. + if bufsize = env[RACK_MULTIPART_BUFFER_SIZE] + assert("rack.multipart.buffer_size must be an Integer > 0 if specified") { + bufsize.is_a?(Integer) && bufsize > 0 + } + end + + ## rack.multipart.tempfile_factory:: An object responding to #call with two arguments, the filename and content_type given for the multipart form field, and returning an IO-like object that responds to #<< and optionally #rewind. This factory will be used to instantiate the tempfile for each multipart form file upload field, rather than the default class of Tempfile. + if tempfile_factory = env[RACK_MULTIPART_TEMPFILE_FACTORY] + assert("rack.multipart.tempfile_factory must respond to #call") { tempfile_factory.respond_to?(:call) } + env[RACK_MULTIPART_TEMPFILE_FACTORY] = lambda do |filename, content_type| + io = tempfile_factory.call(filename, content_type) + assert("rack.multipart.tempfile_factory return value must respond to #<<") { io.respond_to?(:<<) } + io + end + end + + ## The server or the application can store their own data in the + ## environment, too. The keys must contain at least one dot, + ## and should be prefixed uniquely. The prefix rack. + ## is reserved for use with the Rack core distribution and other + ## accepted specifications and must not be used otherwise. + ## + + %w[REQUEST_METHOD SERVER_NAME QUERY_STRING + rack.version rack.input rack.errors + rack.multithread rack.multiprocess rack.run_once].each { |header| + assert("env missing required key #{header}") { env.include? header } + } + + ## The SERVER_PORT must be an Integer if set. + assert("env[SERVER_PORT] is not an Integer") do + server_port = env["SERVER_PORT"] + server_port.nil? || (Integer(server_port) rescue false) + end + + ## The SERVER_NAME must be a valid authority as defined by RFC7540. + assert("#{env[SERVER_NAME]} must be a valid authority") do + URI.parse("http://#{env[SERVER_NAME]}/") rescue false + end + + ## The HTTP_HOST must be a valid authority as defined by RFC7540. + assert("#{env[HTTP_HOST]} must be a valid authority") do + URI.parse("http://#{env[HTTP_HOST]}/") rescue false + end + + ## The environment must not contain the keys + ## HTTP_CONTENT_TYPE or HTTP_CONTENT_LENGTH + ## (use the versions without HTTP_). + %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header| + assert("env contains #{header}, must use #{header[5, -1]}") { + not env.include? header + } + } + + ## The CGI keys (named without a period) must have String values. + ## If the string values for CGI keys contain non-ASCII characters, + ## they should use ASCII-8BIT encoding. + env.each { |key, value| + next if key.include? "." # Skip extensions + assert("env variable #{key} has non-string value #{value.inspect}") { + value.kind_of? String + } + next if value.encoding == Encoding::ASCII_8BIT + assert("env variable #{key} has value containing non-ASCII characters and has non-ASCII-8BIT encoding #{value.inspect} encoding: #{value.encoding}") { + value.b !~ /[\x80-\xff]/n + } + } + + ## There are the following restrictions: + + ## * rack.version must be an array of Integers. + assert("rack.version must be an Array, was #{env[RACK_VERSION].class}") { + env[RACK_VERSION].kind_of? Array + } + ## * rack.url_scheme must either be +http+ or +https+. + assert("rack.url_scheme unknown: #{env[RACK_URL_SCHEME].inspect}") { + %w[http https].include?(env[RACK_URL_SCHEME]) + } + + ## * There must be a valid input stream in rack.input. + check_input env[RACK_INPUT] + ## * There must be a valid error stream in rack.errors. + check_error env[RACK_ERRORS] + ## * There may be a valid hijack stream in rack.hijack_io + check_hijack env + + ## * The REQUEST_METHOD must be a valid token. + assert("REQUEST_METHOD unknown: #{env[REQUEST_METHOD]}") { + env[REQUEST_METHOD] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/ + } + + ## * The SCRIPT_NAME, if non-empty, must start with / + assert("SCRIPT_NAME must start with /") { + !env.include?(SCRIPT_NAME) || + env[SCRIPT_NAME] == "" || + env[SCRIPT_NAME] =~ /\A\// + } + ## * The PATH_INFO, if non-empty, must start with / + assert("PATH_INFO must start with /") { + !env.include?(PATH_INFO) || + env[PATH_INFO] == "" || + env[PATH_INFO] =~ /\A\// + } + ## * The CONTENT_LENGTH, if given, must consist of digits only. + assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") { + !env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/ + } + + ## * One of SCRIPT_NAME or PATH_INFO must be + ## set. PATH_INFO should be / if + ## SCRIPT_NAME is empty. + assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") { + env[SCRIPT_NAME] || env[PATH_INFO] + } + ## SCRIPT_NAME never should be /, but instead be empty. + assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") { + env[SCRIPT_NAME] != "/" + } + end + + ## === The Input Stream + ## + ## The input stream is an IO-like object which contains the raw HTTP + ## POST data. + def check_input(input) + ## When applicable, its external encoding must be "ASCII-8BIT" and it + ## must be opened in binary mode, for Ruby 1.9 compatibility. + assert("rack.input #{input} does not have ASCII-8BIT as its external encoding") { + input.external_encoding == Encoding::ASCII_8BIT + } if input.respond_to?(:external_encoding) + assert("rack.input #{input} is not opened in binary mode") { + input.binmode? + } if input.respond_to?(:binmode?) + + ## The input stream must respond to +gets+, +each+, +read+ and +rewind+. + [:gets, :each, :read, :rewind].each { |method| + assert("rack.input #{input} does not respond to ##{method}") { + input.respond_to? method + } + } + end + + class InputWrapper + include Assertion + + def initialize(input) + @input = input + end + + ## * +gets+ must be called without arguments and return a string, + ## or +nil+ on EOF. + def gets(*args) + assert("rack.input#gets called with arguments") { args.size == 0 } + v = @input.gets + assert("rack.input#gets didn't return a String") { + v.nil? or v.kind_of? String + } + v + end + + ## * +read+ behaves like IO#read. + ## Its signature is read([length, [buffer]]). + ## + ## If given, +length+ must be a non-negative Integer (>= 0) or +nil+, + ## and +buffer+ must be a String and may not be nil. + ## + ## If +length+ is given and not nil, then this method reads at most + ## +length+ bytes from the input stream. + ## + ## If +length+ is not given or nil, then this method reads + ## all data until EOF. + ## + ## When EOF is reached, this method returns nil if +length+ is given + ## and not nil, or "" if +length+ is not given or is nil. + ## + ## If +buffer+ is given, then the read data will be placed + ## into +buffer+ instead of a newly created String object. + def read(*args) + assert("rack.input#read called with too many arguments") { + args.size <= 2 + } + if args.size >= 1 + assert("rack.input#read called with non-integer and non-nil length") { + args.first.kind_of?(Integer) || args.first.nil? + } + assert("rack.input#read called with a negative length") { + args.first.nil? || args.first >= 0 + } + end + if args.size >= 2 + assert("rack.input#read called with non-String buffer") { + args[1].kind_of?(String) + } + end + + v = @input.read(*args) + + assert("rack.input#read didn't return nil or a String") { + v.nil? or v.kind_of? String + } + if args[0].nil? + assert("rack.input#read(nil) returned nil on EOF") { + !v.nil? + } + end + + v + end + + ## * +each+ must be called without arguments and only yield Strings. + def each(*args) + assert("rack.input#each called with arguments") { args.size == 0 } + @input.each { |line| + assert("rack.input#each didn't yield a String") { + line.kind_of? String + } + yield line + } + end + + ## * +rewind+ must be called without arguments. It rewinds the input + ## stream back to the beginning. It must not raise Errno::ESPIPE: + ## that is, it may not be a pipe or a socket. Therefore, handler + ## developers must buffer the input data into some rewindable object + ## if the underlying input stream is not rewindable. + def rewind(*args) + assert("rack.input#rewind called with arguments") { args.size == 0 } + assert("rack.input#rewind raised Errno::ESPIPE") { + begin + @input.rewind + true + rescue Errno::ESPIPE + false + end + } + end + + ## * +close+ must never be called on the input stream. + def close(*args) + assert("rack.input#close must not be called") { false } + end + end + + ## === The Error Stream + def check_error(error) + ## The error stream must respond to +puts+, +write+ and +flush+. + [:puts, :write, :flush].each { |method| + assert("rack.error #{error} does not respond to ##{method}") { + error.respond_to? method + } + } + end + + class ErrorWrapper + include Assertion + + def initialize(error) + @error = error + end + + ## * +puts+ must be called with a single argument that responds to +to_s+. + def puts(str) + @error.puts str + end + + ## * +write+ must be called with a single argument that is a String. + def write(str) + assert("rack.errors#write not called with a String") { str.kind_of? String } + @error.write str + end + + ## * +flush+ must be called without arguments and must be called + ## in order to make the error appear for sure. + def flush + @error.flush + end + + ## * +close+ must never be called on the error stream. + def close(*args) + assert("rack.errors#close must not be called") { false } + end + end + + class HijackWrapper + include Assertion + extend Forwardable + + REQUIRED_METHODS = [ + :read, :write, :read_nonblock, :write_nonblock, :flush, :close, + :close_read, :close_write, :closed? + ] + + def_delegators :@io, *REQUIRED_METHODS + + def initialize(io) + @io = io + REQUIRED_METHODS.each do |meth| + assert("rack.hijack_io must respond to #{meth}") { io.respond_to? meth } + end + end + end + + ## === Hijacking + # + # AUTHORS: n.b. The trailing whitespace between paragraphs is important and + # should not be removed. The whitespace creates paragraphs in the RDoc + # output. + # + ## ==== Request (before status) + def check_hijack(env) + if env[RACK_IS_HIJACK] + ## If rack.hijack? is true then rack.hijack must respond to #call. + original_hijack = env[RACK_HIJACK] + assert("rack.hijack must respond to call") { original_hijack.respond_to?(:call) } + env[RACK_HIJACK] = proc do + ## rack.hijack must return the io that will also be assigned (or is + ## already present, in rack.hijack_io. + io = original_hijack.call + HijackWrapper.new(io) + ## + ## rack.hijack_io must respond to: + ## read, write, read_nonblock, write_nonblock, flush, close, + ## close_read, close_write, closed? + ## + ## The semantics of these IO methods must be a best effort match to + ## those of a normal ruby IO or Socket object, using standard + ## arguments and raising standard exceptions. Servers are encouraged + ## to simply pass on real IO objects, although it is recognized that + ## this approach is not directly compatible with SPDY and HTTP 2.0. + ## + ## IO provided in rack.hijack_io should preference the + ## IO::WaitReadable and IO::WaitWritable APIs wherever supported. + ## + ## There is a deliberate lack of full specification around + ## rack.hijack_io, as semantics will change from server to server. + ## Users are encouraged to utilize this API with a knowledge of their + ## server choice, and servers may extend the functionality of + ## hijack_io to provide additional features to users. The purpose of + ## rack.hijack is for Rack to "get out of the way", as such, Rack only + ## provides the minimum of specification and support. + env[RACK_HIJACK_IO] = HijackWrapper.new(env[RACK_HIJACK_IO]) + io + end + else + ## + ## If rack.hijack? is false, then rack.hijack should not be set. + assert("rack.hijack? is false, but rack.hijack is present") { env[RACK_HIJACK].nil? } + ## + ## If rack.hijack? is false, then rack.hijack_io should not be set. + assert("rack.hijack? is false, but rack.hijack_io is present") { env[RACK_HIJACK_IO].nil? } + end + end + + ## ==== Response (after headers) + ## It is also possible to hijack a response after the status and headers + ## have been sent. + def check_hijack_response(headers, env) + + # this check uses headers like a hash, but the spec only requires + # headers respond to #each + headers = Rack::Utils::HeaderHash[headers] + + ## In order to do this, an application may set the special header + ## rack.hijack to an object that responds to call + ## accepting an argument that conforms to the rack.hijack_io + ## protocol. + ## + ## After the headers have been sent, and this hijack callback has been + ## called, the application is now responsible for the remaining lifecycle + ## of the IO. The application is also responsible for maintaining HTTP + ## semantics. Of specific note, in almost all cases in the current SPEC, + ## applications will have wanted to specify the header Connection:close in + ## HTTP/1.1, and not Connection:keep-alive, as there is no protocol for + ## returning hijacked sockets to the web server. For that purpose, use the + ## body streaming API instead (progressively yielding strings via each). + ## + ## Servers must ignore the body part of the response tuple when + ## the rack.hijack response API is in use. + + if env[RACK_IS_HIJACK] && headers[RACK_HIJACK] + assert('rack.hijack header must respond to #call') { + headers[RACK_HIJACK].respond_to? :call + } + original_hijack = headers[RACK_HIJACK] + proc do |io| + original_hijack.call HijackWrapper.new(io) + end + else + ## + ## The special response header rack.hijack must only be set + ## if the request env has rack.hijack? true. + assert('rack.hijack header must not be present if server does not support hijacking') { + headers[RACK_HIJACK].nil? + } + + nil + end + end + ## ==== Conventions + ## * Middleware should not use hijack unless it is handling the whole + ## response. + ## * Middleware may wrap the IO object for the response pattern. + ## * Middleware should not wrap the IO object for the request pattern. The + ## request pattern is intended to provide the hijacker with "raw tcp". + + ## == The Response + + ## === The Status + def check_status(status) + ## This is an HTTP status. When parsed as integer (+to_i+), it must be + ## greater than or equal to 100. + assert("Status must be >=100 seen as integer") { status.to_i >= 100 } + end + + ## === The Headers + def check_headers(header) + ## The header must respond to +each+, and yield values of key and value. + assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") { + header.respond_to? :each + } + + header.each { |key, value| + ## The header keys must be Strings. + assert("header key must be a string, was #{key.class}") { + key.kind_of? String + } + + ## Special headers starting "rack." are for communicating with the + ## server, and must not be sent back to the client. + next if key =~ /^rack\..+$/ + + ## The header must not contain a +Status+ key. + assert("header must not contain Status") { key.downcase != "status" } + ## The header must conform to RFC7230 token specification, i.e. cannot + ## contain non-printable ASCII, DQUOTE or "(),/:;<=>?@[\]{}". + assert("invalid header name: #{key}") { key !~ /[\(\),\/:;<=>\?@\[\\\]{}[:cntrl:]]/ } + + ## The values of the header must be Strings, + assert("a header value must be a String, but the value of " + + "'#{key}' is a #{value.class}") { value.kind_of? String } + ## consisting of lines (for multiple header values, e.g. multiple + ## Set-Cookie values) separated by "\\n". + value.split("\n").each { |item| + ## The lines must not contain characters below 037. + assert("invalid header value #{key}: #{item.inspect}") { + item !~ /[\000-\037]/ + } + } + } + end + + ## === The Content-Type + def check_content_type(status, headers) + headers.each { |key, value| + ## There must not be a Content-Type, when the +Status+ is 1xx, + ## 204 or 304. + if key.downcase == "content-type" + assert("Content-Type header found in #{status} response, not allowed") { + not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key? status.to_i + } + return + end + } + end + + ## === The Content-Length + def check_content_length(status, headers) + headers.each { |key, value| + if key.downcase == 'content-length' + ## There must not be a Content-Length header when the + ## +Status+ is 1xx, 204 or 304. + assert("Content-Length header found in #{status} response, not allowed") { + not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key? status.to_i + } + @content_length = value + end + } + end + + def verify_content_length(bytes) + if @head_request + assert("Response body was given for HEAD request, but should be empty") { + bytes == 0 + } + elsif @content_length + assert("Content-Length header was #{@content_length}, but should be #{bytes}") { + @content_length == bytes.to_s + } + end + end + + ## === The Body + def each + @closed = false + bytes = 0 + + ## The Body must respond to +each+ + assert("Response body must respond to each") do + @body.respond_to?(:each) + end + + @body.each { |part| + ## and must only yield String values. + assert("Body yielded non-string value #{part.inspect}") { + part.kind_of? String + } + bytes += part.bytesize + yield part + } + verify_content_length(bytes) + + ## + ## The Body itself should not be an instance of String, as this will + ## break in Ruby 1.9. + ## + ## If the Body responds to +close+, it will be called after iteration. If + ## the body is replaced by a middleware after action, the original body + ## must be closed first, if it responds to close. + # XXX howto: assert("Body has not been closed") { @closed } + + + ## + ## If the Body responds to +to_path+, it must return a String + ## identifying the location of a file whose contents are identical + ## to that produced by calling +each+; this may be used by the + ## server as an alternative, possibly more efficient way to + ## transport the response. + + if @body.respond_to?(:to_path) + assert("The file identified by body.to_path does not exist") { + ::File.exist? @body.to_path + } + end + + ## + ## The Body commonly is an Array of Strings, the application + ## instance itself, or a File-like object. + end + + def close + @closed = true + @body.close if @body.respond_to?(:close) + end + + # :startdoc: + + end +end + +## == Thanks +## Some parts of this specification are adopted from PEP333: Python +## Web Server Gateway Interface +## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank +## everyone involved in that effort. diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/lobster.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/lobster.rb new file mode 100644 index 0000000..b86a625 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/lobster.rb @@ -0,0 +1,70 @@ +# frozen_string_literal: true + +require 'zlib' + +module Rack + # Paste has a Pony, Rack has a Lobster! + class Lobster + LobsterString = Zlib::Inflate.inflate("eJx9kEEOwyAMBO99xd7MAcytUhPlJyj2 + P6jy9i4k9EQyGAnBarEXeCBqSkntNXsi/ZCvC48zGQoZKikGrFMZvgS5ZHd+aGWVuWwhVF0 + t1drVmiR42HcWNz5w3QanT+2gIvTVCiE1lm1Y0eU4JGmIIbaKwextKn8rvW+p5PIwFl8ZWJ + I8jyiTlhTcYXkekJAzTyYN6E08A+dk8voBkAVTJQ==".delete("\n ").unpack("m*")[0]) + + LambdaLobster = lambda { |env| + if env[QUERY_STRING].include?("flip") + lobster = LobsterString.split("\n"). + map { |line| line.ljust(42).reverse }. + join("\n") + href = "?" + else + lobster = LobsterString + href = "?flip" + end + + content = ["Lobstericious!", + "
", lobster, "
", + "flip!"] + length = content.inject(0) { |a, e| a + e.size }.to_s + [200, { CONTENT_TYPE => "text/html", CONTENT_LENGTH => length }, content] + } + + def call(env) + req = Request.new(env) + if req.GET["flip"] == "left" + lobster = LobsterString.split("\n").map do |line| + line.ljust(42).reverse. + gsub('\\', 'TEMP'). + gsub('/', '\\'). + gsub('TEMP', '/'). + gsub('{', '}'). + gsub('(', ')') + end.join("\n") + href = "?flip=right" + elsif req.GET["flip"] == "crash" + raise "Lobster crashed" + else + lobster = LobsterString + href = "?flip=left" + end + + res = Response.new + res.write "Lobstericious!" + res.write "
"
+      res.write lobster
+      res.write "
" + res.write "

flip!

" + res.write "

crash!

" + res.finish + end + + end +end + +if $0 == __FILE__ + # :nocov: + require_relative '../rack' + Rack::Server.start( + app: Rack::ShowExceptions.new(Rack::Lint.new(Rack::Lobster.new)), Port: 9292 + ) + # :nocov: +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/lock.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/lock.rb new file mode 100644 index 0000000..4bae3a9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/lock.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require 'thread' + +module Rack + # Rack::Lock locks every request inside a mutex, so that every request + # will effectively be executed synchronously. + class Lock + def initialize(app, mutex = Mutex.new) + @app, @mutex = app, mutex + end + + def call(env) + @mutex.lock + @env = env + @old_rack_multithread = env[RACK_MULTITHREAD] + begin + response = @app.call(env.merge!(RACK_MULTITHREAD => false)) + returned = response << BodyProxy.new(response.pop) { unlock } + ensure + unlock unless returned + end + end + + private + + def unlock + @mutex.unlock + @env[RACK_MULTITHREAD] = @old_rack_multithread + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/logger.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/logger.rb new file mode 100644 index 0000000..6c4bede --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/logger.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +require 'logger' + +module Rack + # Sets up rack.logger to write to rack.errors stream + class Logger + def initialize(app, level = ::Logger::INFO) + @app, @level = app, level + end + + def call(env) + logger = ::Logger.new(env[RACK_ERRORS]) + logger.level = @level + + env[RACK_LOGGER] = logger + @app.call(env) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/media_type.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/media_type.rb new file mode 100644 index 0000000..41937c9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/media_type.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +module Rack + # Rack::MediaType parse media type and parameters out of content_type string + + class MediaType + SPLIT_PATTERN = %r{\s*[;,]\s*} + + class << self + # The media type (type/subtype) portion of the CONTENT_TYPE header + # without any media type parameters. e.g., when CONTENT_TYPE is + # "text/plain;charset=utf-8", the media-type is "text/plain". + # + # For more information on the use of media types in HTTP, see: + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7 + def type(content_type) + return nil unless content_type + content_type.split(SPLIT_PATTERN, 2).first.tap &:downcase! + end + + # The media type parameters provided in CONTENT_TYPE as a Hash, or + # an empty Hash if no CONTENT_TYPE or media-type parameters were + # provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8", + # this method responds with the following Hash: + # { 'charset' => 'utf-8' } + def params(content_type) + return {} if content_type.nil? + + content_type.split(SPLIT_PATTERN)[1..-1].each_with_object({}) do |s, hsh| + k, v = s.split('=', 2) + + hsh[k.tap(&:downcase!)] = strip_doublequotes(v) + end + end + + private + + def strip_doublequotes(str) + (str.start_with?('"') && str.end_with?('"')) ? str[1..-2] : str + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/method_override.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/method_override.rb new file mode 100644 index 0000000..453901f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/method_override.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true + +module Rack + class MethodOverride + HTTP_METHODS = %w[GET HEAD PUT POST DELETE OPTIONS PATCH LINK UNLINK] + + METHOD_OVERRIDE_PARAM_KEY = "_method" + HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE" + ALLOWED_METHODS = %w[POST] + + def initialize(app) + @app = app + end + + def call(env) + if allowed_methods.include?(env[REQUEST_METHOD]) + method = method_override(env) + if HTTP_METHODS.include?(method) + env[RACK_METHODOVERRIDE_ORIGINAL_METHOD] = env[REQUEST_METHOD] + env[REQUEST_METHOD] = method + end + end + + @app.call(env) + end + + def method_override(env) + req = Request.new(env) + method = method_override_param(req) || + env[HTTP_METHOD_OVERRIDE_HEADER] + begin + method.to_s.upcase + rescue ArgumentError + env[RACK_ERRORS].puts "Invalid string for method" + end + end + + private + + def allowed_methods + ALLOWED_METHODS + end + + def method_override_param(req) + req.POST[METHOD_OVERRIDE_PARAM_KEY] + rescue Utils::InvalidParameterError, Utils::ParameterTypeError + req.get_header(RACK_ERRORS).puts "Invalid or incomplete POST params" + rescue EOFError + req.get_header(RACK_ERRORS).puts "Bad request content body" + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/mime.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/mime.rb new file mode 100644 index 0000000..f6c02c1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/mime.rb @@ -0,0 +1,685 @@ +# frozen_string_literal: true + +module Rack + module Mime + # Returns String with mime type if found, otherwise use +fallback+. + # +ext+ should be filename extension in the '.ext' format that + # File.extname(file) returns. + # +fallback+ may be any object + # + # Also see the documentation for MIME_TYPES + # + # Usage: + # Rack::Mime.mime_type('.foo') + # + # This is a shortcut for: + # Rack::Mime::MIME_TYPES.fetch('.foo', 'application/octet-stream') + + def mime_type(ext, fallback = 'application/octet-stream') + MIME_TYPES.fetch(ext.to_s.downcase, fallback) + end + module_function :mime_type + + # Returns true if the given value is a mime match for the given mime match + # specification, false otherwise. + # + # Rack::Mime.match?('text/html', 'text/*') => true + # Rack::Mime.match?('text/plain', '*') => true + # Rack::Mime.match?('text/html', 'application/json') => false + + def match?(value, matcher) + v1, v2 = value.split('/', 2) + m1, m2 = matcher.split('/', 2) + + (m1 == '*' || v1 == m1) && (m2.nil? || m2 == '*' || m2 == v2) + end + module_function :match? + + # List of most common mime-types, selected various sources + # according to their usefulness in a webserving scope for Ruby + # users. + # + # To amend this list with your local mime.types list you can use: + # + # require 'webrick/httputils' + # list = WEBrick::HTTPUtils.load_mime_types('/etc/mime.types') + # Rack::Mime::MIME_TYPES.merge!(list) + # + # N.B. On Ubuntu the mime.types file does not include the leading period, so + # users may need to modify the data before merging into the hash. + + MIME_TYPES = { + ".123" => "application/vnd.lotus-1-2-3", + ".3dml" => "text/vnd.in3d.3dml", + ".3g2" => "video/3gpp2", + ".3gp" => "video/3gpp", + ".a" => "application/octet-stream", + ".acc" => "application/vnd.americandynamics.acc", + ".ace" => "application/x-ace-compressed", + ".acu" => "application/vnd.acucobol", + ".aep" => "application/vnd.audiograph", + ".afp" => "application/vnd.ibm.modcap", + ".ai" => "application/postscript", + ".aif" => "audio/x-aiff", + ".aiff" => "audio/x-aiff", + ".ami" => "application/vnd.amiga.ami", + ".appcache" => "text/cache-manifest", + ".apr" => "application/vnd.lotus-approach", + ".asc" => "application/pgp-signature", + ".asf" => "video/x-ms-asf", + ".asm" => "text/x-asm", + ".aso" => "application/vnd.accpac.simply.aso", + ".asx" => "video/x-ms-asf", + ".atc" => "application/vnd.acucorp", + ".atom" => "application/atom+xml", + ".atomcat" => "application/atomcat+xml", + ".atomsvc" => "application/atomsvc+xml", + ".atx" => "application/vnd.antix.game-component", + ".au" => "audio/basic", + ".avi" => "video/x-msvideo", + ".bat" => "application/x-msdownload", + ".bcpio" => "application/x-bcpio", + ".bdm" => "application/vnd.syncml.dm+wbxml", + ".bh2" => "application/vnd.fujitsu.oasysprs", + ".bin" => "application/octet-stream", + ".bmi" => "application/vnd.bmi", + ".bmp" => "image/bmp", + ".box" => "application/vnd.previewsystems.box", + ".btif" => "image/prs.btif", + ".bz" => "application/x-bzip", + ".bz2" => "application/x-bzip2", + ".c" => "text/x-c", + ".c4g" => "application/vnd.clonk.c4group", + ".cab" => "application/vnd.ms-cab-compressed", + ".cc" => "text/x-c", + ".ccxml" => "application/ccxml+xml", + ".cdbcmsg" => "application/vnd.contact.cmsg", + ".cdkey" => "application/vnd.mediastation.cdkey", + ".cdx" => "chemical/x-cdx", + ".cdxml" => "application/vnd.chemdraw+xml", + ".cdy" => "application/vnd.cinderella", + ".cer" => "application/pkix-cert", + ".cgm" => "image/cgm", + ".chat" => "application/x-chat", + ".chm" => "application/vnd.ms-htmlhelp", + ".chrt" => "application/vnd.kde.kchart", + ".cif" => "chemical/x-cif", + ".cii" => "application/vnd.anser-web-certificate-issue-initiation", + ".cil" => "application/vnd.ms-artgalry", + ".cla" => "application/vnd.claymore", + ".class" => "application/octet-stream", + ".clkk" => "application/vnd.crick.clicker.keyboard", + ".clkp" => "application/vnd.crick.clicker.palette", + ".clkt" => "application/vnd.crick.clicker.template", + ".clkw" => "application/vnd.crick.clicker.wordbank", + ".clkx" => "application/vnd.crick.clicker", + ".clp" => "application/x-msclip", + ".cmc" => "application/vnd.cosmocaller", + ".cmdf" => "chemical/x-cmdf", + ".cml" => "chemical/x-cml", + ".cmp" => "application/vnd.yellowriver-custom-menu", + ".cmx" => "image/x-cmx", + ".com" => "application/x-msdownload", + ".conf" => "text/plain", + ".cpio" => "application/x-cpio", + ".cpp" => "text/x-c", + ".cpt" => "application/mac-compactpro", + ".crd" => "application/x-mscardfile", + ".crl" => "application/pkix-crl", + ".crt" => "application/x-x509-ca-cert", + ".csh" => "application/x-csh", + ".csml" => "chemical/x-csml", + ".csp" => "application/vnd.commonspace", + ".css" => "text/css", + ".csv" => "text/csv", + ".curl" => "application/vnd.curl", + ".cww" => "application/prs.cww", + ".cxx" => "text/x-c", + ".daf" => "application/vnd.mobius.daf", + ".davmount" => "application/davmount+xml", + ".dcr" => "application/x-director", + ".dd2" => "application/vnd.oma.dd2+xml", + ".ddd" => "application/vnd.fujixerox.ddd", + ".deb" => "application/x-debian-package", + ".der" => "application/x-x509-ca-cert", + ".dfac" => "application/vnd.dreamfactory", + ".diff" => "text/x-diff", + ".dis" => "application/vnd.mobius.dis", + ".djv" => "image/vnd.djvu", + ".djvu" => "image/vnd.djvu", + ".dll" => "application/x-msdownload", + ".dmg" => "application/octet-stream", + ".dna" => "application/vnd.dna", + ".doc" => "application/msword", + ".docm" => "application/vnd.ms-word.document.macroEnabled.12", + ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".dot" => "application/msword", + ".dotm" => "application/vnd.ms-word.template.macroEnabled.12", + ".dotx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.template", + ".dp" => "application/vnd.osgi.dp", + ".dpg" => "application/vnd.dpgraph", + ".dsc" => "text/prs.lines.tag", + ".dtd" => "application/xml-dtd", + ".dts" => "audio/vnd.dts", + ".dtshd" => "audio/vnd.dts.hd", + ".dv" => "video/x-dv", + ".dvi" => "application/x-dvi", + ".dwf" => "model/vnd.dwf", + ".dwg" => "image/vnd.dwg", + ".dxf" => "image/vnd.dxf", + ".dxp" => "application/vnd.spotfire.dxp", + ".ear" => "application/java-archive", + ".ecelp4800" => "audio/vnd.nuera.ecelp4800", + ".ecelp7470" => "audio/vnd.nuera.ecelp7470", + ".ecelp9600" => "audio/vnd.nuera.ecelp9600", + ".ecma" => "application/ecmascript", + ".edm" => "application/vnd.novadigm.edm", + ".edx" => "application/vnd.novadigm.edx", + ".efif" => "application/vnd.picsel", + ".ei6" => "application/vnd.pg.osasli", + ".eml" => "message/rfc822", + ".eol" => "audio/vnd.digital-winds", + ".eot" => "application/vnd.ms-fontobject", + ".eps" => "application/postscript", + ".es3" => "application/vnd.eszigno3+xml", + ".esf" => "application/vnd.epson.esf", + ".etx" => "text/x-setext", + ".exe" => "application/x-msdownload", + ".ext" => "application/vnd.novadigm.ext", + ".ez" => "application/andrew-inset", + ".ez2" => "application/vnd.ezpix-album", + ".ez3" => "application/vnd.ezpix-package", + ".f" => "text/x-fortran", + ".f77" => "text/x-fortran", + ".f90" => "text/x-fortran", + ".fbs" => "image/vnd.fastbidsheet", + ".fdf" => "application/vnd.fdf", + ".fe_launch" => "application/vnd.denovo.fcselayout-link", + ".fg5" => "application/vnd.fujitsu.oasysgp", + ".fli" => "video/x-fli", + ".flo" => "application/vnd.micrografx.flo", + ".flv" => "video/x-flv", + ".flw" => "application/vnd.kde.kivio", + ".flx" => "text/vnd.fmi.flexstor", + ".fly" => "text/vnd.fly", + ".fm" => "application/vnd.framemaker", + ".fnc" => "application/vnd.frogans.fnc", + ".for" => "text/x-fortran", + ".fpx" => "image/vnd.fpx", + ".fsc" => "application/vnd.fsc.weblaunch", + ".fst" => "image/vnd.fst", + ".ftc" => "application/vnd.fluxtime.clip", + ".fti" => "application/vnd.anser-web-funds-transfer-initiation", + ".fvt" => "video/vnd.fvt", + ".fzs" => "application/vnd.fuzzysheet", + ".g3" => "image/g3fax", + ".gac" => "application/vnd.groove-account", + ".gdl" => "model/vnd.gdl", + ".gem" => "application/octet-stream", + ".gemspec" => "text/x-script.ruby", + ".ghf" => "application/vnd.groove-help", + ".gif" => "image/gif", + ".gim" => "application/vnd.groove-identity-message", + ".gmx" => "application/vnd.gmx", + ".gph" => "application/vnd.flographit", + ".gqf" => "application/vnd.grafeq", + ".gram" => "application/srgs", + ".grv" => "application/vnd.groove-injector", + ".grxml" => "application/srgs+xml", + ".gtar" => "application/x-gtar", + ".gtm" => "application/vnd.groove-tool-message", + ".gtw" => "model/vnd.gtw", + ".gv" => "text/vnd.graphviz", + ".gz" => "application/x-gzip", + ".h" => "text/x-c", + ".h261" => "video/h261", + ".h263" => "video/h263", + ".h264" => "video/h264", + ".hbci" => "application/vnd.hbci", + ".hdf" => "application/x-hdf", + ".hh" => "text/x-c", + ".hlp" => "application/winhlp", + ".hpgl" => "application/vnd.hp-hpgl", + ".hpid" => "application/vnd.hp-hpid", + ".hps" => "application/vnd.hp-hps", + ".hqx" => "application/mac-binhex40", + ".htc" => "text/x-component", + ".htke" => "application/vnd.kenameaapp", + ".htm" => "text/html", + ".html" => "text/html", + ".hvd" => "application/vnd.yamaha.hv-dic", + ".hvp" => "application/vnd.yamaha.hv-voice", + ".hvs" => "application/vnd.yamaha.hv-script", + ".icc" => "application/vnd.iccprofile", + ".ice" => "x-conference/x-cooltalk", + ".ico" => "image/vnd.microsoft.icon", + ".ics" => "text/calendar", + ".ief" => "image/ief", + ".ifb" => "text/calendar", + ".ifm" => "application/vnd.shana.informed.formdata", + ".igl" => "application/vnd.igloader", + ".igs" => "model/iges", + ".igx" => "application/vnd.micrografx.igx", + ".iif" => "application/vnd.shana.informed.interchange", + ".imp" => "application/vnd.accpac.simply.imp", + ".ims" => "application/vnd.ms-ims", + ".ipk" => "application/vnd.shana.informed.package", + ".irm" => "application/vnd.ibm.rights-management", + ".irp" => "application/vnd.irepository.package+xml", + ".iso" => "application/octet-stream", + ".itp" => "application/vnd.shana.informed.formtemplate", + ".ivp" => "application/vnd.immervision-ivp", + ".ivu" => "application/vnd.immervision-ivu", + ".jad" => "text/vnd.sun.j2me.app-descriptor", + ".jam" => "application/vnd.jam", + ".jar" => "application/java-archive", + ".java" => "text/x-java-source", + ".jisp" => "application/vnd.jisp", + ".jlt" => "application/vnd.hp-jlyt", + ".jnlp" => "application/x-java-jnlp-file", + ".joda" => "application/vnd.joost.joda-archive", + ".jp2" => "image/jp2", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".jpgv" => "video/jpeg", + ".jpm" => "video/jpm", + ".js" => "application/javascript", + ".json" => "application/json", + ".karbon" => "application/vnd.kde.karbon", + ".kfo" => "application/vnd.kde.kformula", + ".kia" => "application/vnd.kidspiration", + ".kml" => "application/vnd.google-earth.kml+xml", + ".kmz" => "application/vnd.google-earth.kmz", + ".kne" => "application/vnd.kinar", + ".kon" => "application/vnd.kde.kontour", + ".kpr" => "application/vnd.kde.kpresenter", + ".ksp" => "application/vnd.kde.kspread", + ".ktz" => "application/vnd.kahootz", + ".kwd" => "application/vnd.kde.kword", + ".latex" => "application/x-latex", + ".lbd" => "application/vnd.llamagraphics.life-balance.desktop", + ".lbe" => "application/vnd.llamagraphics.life-balance.exchange+xml", + ".les" => "application/vnd.hhe.lesson-player", + ".link66" => "application/vnd.route66.link66+xml", + ".log" => "text/plain", + ".lostxml" => "application/lost+xml", + ".lrm" => "application/vnd.ms-lrm", + ".ltf" => "application/vnd.frogans.ltf", + ".lvp" => "audio/vnd.lucent.voice", + ".lwp" => "application/vnd.lotus-wordpro", + ".m3u" => "audio/x-mpegurl", + ".m3u8" => "application/x-mpegurl", + ".m4a" => "audio/mp4a-latm", + ".m4v" => "video/mp4", + ".ma" => "application/mathematica", + ".mag" => "application/vnd.ecowin.chart", + ".man" => "text/troff", + ".manifest" => "text/cache-manifest", + ".mathml" => "application/mathml+xml", + ".mbk" => "application/vnd.mobius.mbk", + ".mbox" => "application/mbox", + ".mc1" => "application/vnd.medcalcdata", + ".mcd" => "application/vnd.mcd", + ".mdb" => "application/x-msaccess", + ".mdi" => "image/vnd.ms-modi", + ".mdoc" => "text/troff", + ".me" => "text/troff", + ".mfm" => "application/vnd.mfmp", + ".mgz" => "application/vnd.proteus.magazine", + ".mid" => "audio/midi", + ".midi" => "audio/midi", + ".mif" => "application/vnd.mif", + ".mime" => "message/rfc822", + ".mj2" => "video/mj2", + ".mlp" => "application/vnd.dolby.mlp", + ".mmd" => "application/vnd.chipnuts.karaoke-mmd", + ".mmf" => "application/vnd.smaf", + ".mml" => "application/mathml+xml", + ".mmr" => "image/vnd.fujixerox.edmics-mmr", + ".mng" => "video/x-mng", + ".mny" => "application/x-msmoney", + ".mov" => "video/quicktime", + ".movie" => "video/x-sgi-movie", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mp4a" => "audio/mp4", + ".mp4s" => "application/mp4", + ".mp4v" => "video/mp4", + ".mpc" => "application/vnd.mophun.certificate", + ".mpd" => "application/dash+xml", + ".mpeg" => "video/mpeg", + ".mpg" => "video/mpeg", + ".mpga" => "audio/mpeg", + ".mpkg" => "application/vnd.apple.installer+xml", + ".mpm" => "application/vnd.blueice.multipass", + ".mpn" => "application/vnd.mophun.application", + ".mpp" => "application/vnd.ms-project", + ".mpy" => "application/vnd.ibm.minipay", + ".mqy" => "application/vnd.mobius.mqy", + ".mrc" => "application/marc", + ".ms" => "text/troff", + ".mscml" => "application/mediaservercontrol+xml", + ".mseq" => "application/vnd.mseq", + ".msf" => "application/vnd.epson.msf", + ".msh" => "model/mesh", + ".msi" => "application/x-msdownload", + ".msl" => "application/vnd.mobius.msl", + ".msty" => "application/vnd.muvee.style", + ".mts" => "model/vnd.mts", + ".mus" => "application/vnd.musician", + ".mvb" => "application/x-msmediaview", + ".mwf" => "application/vnd.mfer", + ".mxf" => "application/mxf", + ".mxl" => "application/vnd.recordare.musicxml", + ".mxml" => "application/xv+xml", + ".mxs" => "application/vnd.triscape.mxs", + ".mxu" => "video/vnd.mpegurl", + ".n" => "application/vnd.nokia.n-gage.symbian.install", + ".nc" => "application/x-netcdf", + ".ngdat" => "application/vnd.nokia.n-gage.data", + ".nlu" => "application/vnd.neurolanguage.nlu", + ".nml" => "application/vnd.enliven", + ".nnd" => "application/vnd.noblenet-directory", + ".nns" => "application/vnd.noblenet-sealer", + ".nnw" => "application/vnd.noblenet-web", + ".npx" => "image/vnd.net-fpx", + ".nsf" => "application/vnd.lotus-notes", + ".oa2" => "application/vnd.fujitsu.oasys2", + ".oa3" => "application/vnd.fujitsu.oasys3", + ".oas" => "application/vnd.fujitsu.oasys", + ".obd" => "application/x-msbinder", + ".oda" => "application/oda", + ".odc" => "application/vnd.oasis.opendocument.chart", + ".odf" => "application/vnd.oasis.opendocument.formula", + ".odg" => "application/vnd.oasis.opendocument.graphics", + ".odi" => "application/vnd.oasis.opendocument.image", + ".odp" => "application/vnd.oasis.opendocument.presentation", + ".ods" => "application/vnd.oasis.opendocument.spreadsheet", + ".odt" => "application/vnd.oasis.opendocument.text", + ".oga" => "audio/ogg", + ".ogg" => "application/ogg", + ".ogv" => "video/ogg", + ".ogx" => "application/ogg", + ".org" => "application/vnd.lotus-organizer", + ".otc" => "application/vnd.oasis.opendocument.chart-template", + ".otf" => "application/vnd.oasis.opendocument.formula-template", + ".otg" => "application/vnd.oasis.opendocument.graphics-template", + ".oth" => "application/vnd.oasis.opendocument.text-web", + ".oti" => "application/vnd.oasis.opendocument.image-template", + ".otm" => "application/vnd.oasis.opendocument.text-master", + ".ots" => "application/vnd.oasis.opendocument.spreadsheet-template", + ".ott" => "application/vnd.oasis.opendocument.text-template", + ".oxt" => "application/vnd.openofficeorg.extension", + ".p" => "text/x-pascal", + ".p10" => "application/pkcs10", + ".p12" => "application/x-pkcs12", + ".p7b" => "application/x-pkcs7-certificates", + ".p7m" => "application/pkcs7-mime", + ".p7r" => "application/x-pkcs7-certreqresp", + ".p7s" => "application/pkcs7-signature", + ".pas" => "text/x-pascal", + ".pbd" => "application/vnd.powerbuilder6", + ".pbm" => "image/x-portable-bitmap", + ".pcl" => "application/vnd.hp-pcl", + ".pclxl" => "application/vnd.hp-pclxl", + ".pcx" => "image/x-pcx", + ".pdb" => "chemical/x-pdb", + ".pdf" => "application/pdf", + ".pem" => "application/x-x509-ca-cert", + ".pfr" => "application/font-tdpfr", + ".pgm" => "image/x-portable-graymap", + ".pgn" => "application/x-chess-pgn", + ".pgp" => "application/pgp-encrypted", + ".pic" => "image/x-pict", + ".pict" => "image/pict", + ".pkg" => "application/octet-stream", + ".pki" => "application/pkixcmp", + ".pkipath" => "application/pkix-pkipath", + ".pl" => "text/x-script.perl", + ".plb" => "application/vnd.3gpp.pic-bw-large", + ".plc" => "application/vnd.mobius.plc", + ".plf" => "application/vnd.pocketlearn", + ".pls" => "application/pls+xml", + ".pm" => "text/x-script.perl-module", + ".pml" => "application/vnd.ctc-posml", + ".png" => "image/png", + ".pnm" => "image/x-portable-anymap", + ".pntg" => "image/x-macpaint", + ".portpkg" => "application/vnd.macports.portpkg", + ".pot" => "application/vnd.ms-powerpoint", + ".potm" => "application/vnd.ms-powerpoint.template.macroEnabled.12", + ".potx" => "application/vnd.openxmlformats-officedocument.presentationml.template", + ".ppa" => "application/vnd.ms-powerpoint", + ".ppam" => "application/vnd.ms-powerpoint.addin.macroEnabled.12", + ".ppd" => "application/vnd.cups-ppd", + ".ppm" => "image/x-portable-pixmap", + ".pps" => "application/vnd.ms-powerpoint", + ".ppsm" => "application/vnd.ms-powerpoint.slideshow.macroEnabled.12", + ".ppsx" => "application/vnd.openxmlformats-officedocument.presentationml.slideshow", + ".ppt" => "application/vnd.ms-powerpoint", + ".pptm" => "application/vnd.ms-powerpoint.presentation.macroEnabled.12", + ".pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation", + ".prc" => "application/vnd.palm", + ".pre" => "application/vnd.lotus-freelance", + ".prf" => "application/pics-rules", + ".ps" => "application/postscript", + ".psb" => "application/vnd.3gpp.pic-bw-small", + ".psd" => "image/vnd.adobe.photoshop", + ".ptid" => "application/vnd.pvi.ptid1", + ".pub" => "application/x-mspublisher", + ".pvb" => "application/vnd.3gpp.pic-bw-var", + ".pwn" => "application/vnd.3m.post-it-notes", + ".py" => "text/x-script.python", + ".pya" => "audio/vnd.ms-playready.media.pya", + ".pyv" => "video/vnd.ms-playready.media.pyv", + ".qam" => "application/vnd.epson.quickanime", + ".qbo" => "application/vnd.intu.qbo", + ".qfx" => "application/vnd.intu.qfx", + ".qps" => "application/vnd.publishare-delta-tree", + ".qt" => "video/quicktime", + ".qtif" => "image/x-quicktime", + ".qxd" => "application/vnd.quark.quarkxpress", + ".ra" => "audio/x-pn-realaudio", + ".rake" => "text/x-script.ruby", + ".ram" => "audio/x-pn-realaudio", + ".rar" => "application/x-rar-compressed", + ".ras" => "image/x-cmu-raster", + ".rb" => "text/x-script.ruby", + ".rcprofile" => "application/vnd.ipunplugged.rcprofile", + ".rdf" => "application/rdf+xml", + ".rdz" => "application/vnd.data-vision.rdz", + ".rep" => "application/vnd.businessobjects", + ".rgb" => "image/x-rgb", + ".rif" => "application/reginfo+xml", + ".rl" => "application/resource-lists+xml", + ".rlc" => "image/vnd.fujixerox.edmics-rlc", + ".rld" => "application/resource-lists-diff+xml", + ".rm" => "application/vnd.rn-realmedia", + ".rmp" => "audio/x-pn-realaudio-plugin", + ".rms" => "application/vnd.jcp.javame.midlet-rms", + ".rnc" => "application/relax-ng-compact-syntax", + ".roff" => "text/troff", + ".rpm" => "application/x-redhat-package-manager", + ".rpss" => "application/vnd.nokia.radio-presets", + ".rpst" => "application/vnd.nokia.radio-preset", + ".rq" => "application/sparql-query", + ".rs" => "application/rls-services+xml", + ".rsd" => "application/rsd+xml", + ".rss" => "application/rss+xml", + ".rtf" => "application/rtf", + ".rtx" => "text/richtext", + ".ru" => "text/x-script.ruby", + ".s" => "text/x-asm", + ".saf" => "application/vnd.yamaha.smaf-audio", + ".sbml" => "application/sbml+xml", + ".sc" => "application/vnd.ibm.secure-container", + ".scd" => "application/x-msschedule", + ".scm" => "application/vnd.lotus-screencam", + ".scq" => "application/scvp-cv-request", + ".scs" => "application/scvp-cv-response", + ".sdkm" => "application/vnd.solent.sdkm+xml", + ".sdp" => "application/sdp", + ".see" => "application/vnd.seemail", + ".sema" => "application/vnd.sema", + ".semd" => "application/vnd.semd", + ".semf" => "application/vnd.semf", + ".setpay" => "application/set-payment-initiation", + ".setreg" => "application/set-registration-initiation", + ".sfd" => "application/vnd.hydrostatix.sof-data", + ".sfs" => "application/vnd.spotfire.sfs", + ".sgm" => "text/sgml", + ".sgml" => "text/sgml", + ".sh" => "application/x-sh", + ".shar" => "application/x-shar", + ".shf" => "application/shf+xml", + ".sig" => "application/pgp-signature", + ".sit" => "application/x-stuffit", + ".sitx" => "application/x-stuffitx", + ".skp" => "application/vnd.koan", + ".slt" => "application/vnd.epson.salt", + ".smi" => "application/smil+xml", + ".snd" => "audio/basic", + ".so" => "application/octet-stream", + ".spf" => "application/vnd.yamaha.smaf-phrase", + ".spl" => "application/x-futuresplash", + ".spot" => "text/vnd.in3d.spot", + ".spp" => "application/scvp-vp-response", + ".spq" => "application/scvp-vp-request", + ".src" => "application/x-wais-source", + ".srt" => "text/srt", + ".srx" => "application/sparql-results+xml", + ".sse" => "application/vnd.kodak-descriptor", + ".ssf" => "application/vnd.epson.ssf", + ".ssml" => "application/ssml+xml", + ".stf" => "application/vnd.wt.stf", + ".stk" => "application/hyperstudio", + ".str" => "application/vnd.pg.format", + ".sus" => "application/vnd.sus-calendar", + ".sv4cpio" => "application/x-sv4cpio", + ".sv4crc" => "application/x-sv4crc", + ".svd" => "application/vnd.svd", + ".svg" => "image/svg+xml", + ".svgz" => "image/svg+xml", + ".swf" => "application/x-shockwave-flash", + ".swi" => "application/vnd.arastra.swi", + ".t" => "text/troff", + ".tao" => "application/vnd.tao.intent-module-archive", + ".tar" => "application/x-tar", + ".tbz" => "application/x-bzip-compressed-tar", + ".tcap" => "application/vnd.3gpp2.tcap", + ".tcl" => "application/x-tcl", + ".tex" => "application/x-tex", + ".texi" => "application/x-texinfo", + ".texinfo" => "application/x-texinfo", + ".text" => "text/plain", + ".tif" => "image/tiff", + ".tiff" => "image/tiff", + ".tmo" => "application/vnd.tmobile-livetv", + ".torrent" => "application/x-bittorrent", + ".tpl" => "application/vnd.groove-tool-template", + ".tpt" => "application/vnd.trid.tpt", + ".tr" => "text/troff", + ".tra" => "application/vnd.trueapp", + ".trm" => "application/x-msterminal", + ".ts" => "video/mp2t", + ".tsv" => "text/tab-separated-values", + ".ttf" => "application/octet-stream", + ".twd" => "application/vnd.simtech-mindmapper", + ".txd" => "application/vnd.genomatix.tuxedo", + ".txf" => "application/vnd.mobius.txf", + ".txt" => "text/plain", + ".ufd" => "application/vnd.ufdl", + ".umj" => "application/vnd.umajin", + ".unityweb" => "application/vnd.unity", + ".uoml" => "application/vnd.uoml+xml", + ".uri" => "text/uri-list", + ".ustar" => "application/x-ustar", + ".utz" => "application/vnd.uiq.theme", + ".uu" => "text/x-uuencode", + ".vcd" => "application/x-cdlink", + ".vcf" => "text/x-vcard", + ".vcg" => "application/vnd.groove-vcard", + ".vcs" => "text/x-vcalendar", + ".vcx" => "application/vnd.vcx", + ".vis" => "application/vnd.visionary", + ".viv" => "video/vnd.vivo", + ".vrml" => "model/vrml", + ".vsd" => "application/vnd.visio", + ".vsf" => "application/vnd.vsf", + ".vtt" => "text/vtt", + ".vtu" => "model/vnd.vtu", + ".vxml" => "application/voicexml+xml", + ".war" => "application/java-archive", + ".wasm" => "application/wasm", + ".wav" => "audio/x-wav", + ".wax" => "audio/x-ms-wax", + ".wbmp" => "image/vnd.wap.wbmp", + ".wbs" => "application/vnd.criticaltools.wbs+xml", + ".wbxml" => "application/vnd.wap.wbxml", + ".webm" => "video/webm", + ".wm" => "video/x-ms-wm", + ".wma" => "audio/x-ms-wma", + ".wmd" => "application/x-ms-wmd", + ".wmf" => "application/x-msmetafile", + ".wml" => "text/vnd.wap.wml", + ".wmlc" => "application/vnd.wap.wmlc", + ".wmls" => "text/vnd.wap.wmlscript", + ".wmlsc" => "application/vnd.wap.wmlscriptc", + ".wmv" => "video/x-ms-wmv", + ".wmx" => "video/x-ms-wmx", + ".wmz" => "application/x-ms-wmz", + ".woff" => "application/font-woff", + ".woff2" => "application/font-woff2", + ".wpd" => "application/vnd.wordperfect", + ".wpl" => "application/vnd.ms-wpl", + ".wps" => "application/vnd.ms-works", + ".wqd" => "application/vnd.wqd", + ".wri" => "application/x-mswrite", + ".wrl" => "model/vrml", + ".wsdl" => "application/wsdl+xml", + ".wspolicy" => "application/wspolicy+xml", + ".wtb" => "application/vnd.webturbo", + ".wvx" => "video/x-ms-wvx", + ".x3d" => "application/vnd.hzn-3d-crossword", + ".xar" => "application/vnd.xara", + ".xbd" => "application/vnd.fujixerox.docuworks.binder", + ".xbm" => "image/x-xbitmap", + ".xdm" => "application/vnd.syncml.dm+xml", + ".xdp" => "application/vnd.adobe.xdp+xml", + ".xdw" => "application/vnd.fujixerox.docuworks", + ".xenc" => "application/xenc+xml", + ".xer" => "application/patch-ops-error+xml", + ".xfdf" => "application/vnd.adobe.xfdf", + ".xfdl" => "application/vnd.xfdl", + ".xhtml" => "application/xhtml+xml", + ".xif" => "image/vnd.xiff", + ".xla" => "application/vnd.ms-excel", + ".xlam" => "application/vnd.ms-excel.addin.macroEnabled.12", + ".xls" => "application/vnd.ms-excel", + ".xlsb" => "application/vnd.ms-excel.sheet.binary.macroEnabled.12", + ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".xlsm" => "application/vnd.ms-excel.sheet.macroEnabled.12", + ".xlt" => "application/vnd.ms-excel", + ".xltx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.template", + ".xml" => "application/xml", + ".xo" => "application/vnd.olpc-sugar", + ".xop" => "application/xop+xml", + ".xpm" => "image/x-xpixmap", + ".xpr" => "application/vnd.is-xpr", + ".xps" => "application/vnd.ms-xpsdocument", + ".xpw" => "application/vnd.intercon.formnet", + ".xsl" => "application/xml", + ".xslt" => "application/xslt+xml", + ".xsm" => "application/vnd.syncml+xml", + ".xspf" => "application/xspf+xml", + ".xul" => "application/vnd.mozilla.xul+xml", + ".xwd" => "image/x-xwindowdump", + ".xyz" => "chemical/x-xyz", + ".yaml" => "text/yaml", + ".yml" => "text/yaml", + ".zaz" => "application/vnd.zzazz.deck+xml", + ".zip" => "application/zip", + ".zmm" => "application/vnd.handheld-entertainment+xml", + } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/mock.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/mock.rb new file mode 100644 index 0000000..5b2512c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/mock.rb @@ -0,0 +1,273 @@ +# frozen_string_literal: true + +require 'uri' +require 'stringio' +require_relative '../rack' +require 'cgi/cookie' + +module Rack + # Rack::MockRequest helps testing your Rack application without + # actually using HTTP. + # + # After performing a request on a URL with get/post/put/patch/delete, it + # returns a MockResponse with useful helper methods for effective + # testing. + # + # You can pass a hash with additional configuration to the + # get/post/put/patch/delete. + # :input:: A String or IO-like to be used as rack.input. + # :fatal:: Raise a FatalWarning if the app writes to rack.errors. + # :lint:: If true, wrap the application in a Rack::Lint. + + class MockRequest + class FatalWarning < RuntimeError + end + + class FatalWarner + def puts(warning) + raise FatalWarning, warning + end + + def write(warning) + raise FatalWarning, warning + end + + def flush + end + + def string + "" + end + end + + DEFAULT_ENV = { + RACK_VERSION => Rack::VERSION, + RACK_INPUT => StringIO.new, + RACK_ERRORS => StringIO.new, + RACK_MULTITHREAD => true, + RACK_MULTIPROCESS => true, + RACK_RUNONCE => false, + }.freeze + + def initialize(app) + @app = app + end + + # Make a GET request and return a MockResponse. See #request. + def get(uri, opts = {}) request(GET, uri, opts) end + # Make a POST request and return a MockResponse. See #request. + def post(uri, opts = {}) request(POST, uri, opts) end + # Make a PUT request and return a MockResponse. See #request. + def put(uri, opts = {}) request(PUT, uri, opts) end + # Make a PATCH request and return a MockResponse. See #request. + def patch(uri, opts = {}) request(PATCH, uri, opts) end + # Make a DELETE request and return a MockResponse. See #request. + def delete(uri, opts = {}) request(DELETE, uri, opts) end + # Make a HEAD request and return a MockResponse. See #request. + def head(uri, opts = {}) request(HEAD, uri, opts) end + # Make an OPTIONS request and return a MockResponse. See #request. + def options(uri, opts = {}) request(OPTIONS, uri, opts) end + + # Make a request using the given request method for the given + # uri to the rack application and return a MockResponse. + # Options given are passed to MockRequest.env_for. + def request(method = GET, uri = "", opts = {}) + env = self.class.env_for(uri, opts.merge(method: method)) + + if opts[:lint] + app = Rack::Lint.new(@app) + else + app = @app + end + + errors = env[RACK_ERRORS] + status, headers, body = app.call(env) + MockResponse.new(status, headers, body, errors) + ensure + body.close if body.respond_to?(:close) + end + + # For historical reasons, we're pinning to RFC 2396. + # URI::Parser = URI::RFC2396_Parser + def self.parse_uri_rfc2396(uri) + @parser ||= URI::Parser.new + @parser.parse(uri) + end + + # Return the Rack environment used for a request to +uri+. + # All options that are strings are added to the returned environment. + # Options: + # :fatal :: Whether to raise an exception if request outputs to rack.errors + # :input :: The rack.input to set + # :method :: The HTTP request method to use + # :params :: The params to use + # :script_name :: The SCRIPT_NAME to set + def self.env_for(uri = "", opts = {}) + uri = parse_uri_rfc2396(uri) + uri.path = "/#{uri.path}" unless uri.path[0] == ?/ + + env = DEFAULT_ENV.dup + + env[REQUEST_METHOD] = (opts[:method] ? opts[:method].to_s.upcase : GET).b + env[SERVER_NAME] = (uri.host || "example.org").b + env[SERVER_PORT] = (uri.port ? uri.port.to_s : "80").b + env[QUERY_STRING] = (uri.query.to_s).b + env[PATH_INFO] = ((!uri.path || uri.path.empty?) ? "/" : uri.path).b + env[RACK_URL_SCHEME] = (uri.scheme || "http").b + env[HTTPS] = (env[RACK_URL_SCHEME] == "https" ? "on" : "off").b + + env[SCRIPT_NAME] = opts[:script_name] || "" + + if opts[:fatal] + env[RACK_ERRORS] = FatalWarner.new + else + env[RACK_ERRORS] = StringIO.new + end + + if params = opts[:params] + if env[REQUEST_METHOD] == GET + params = Utils.parse_nested_query(params) if params.is_a?(String) + params.update(Utils.parse_nested_query(env[QUERY_STRING])) + env[QUERY_STRING] = Utils.build_nested_query(params) + elsif !opts.has_key?(:input) + opts["CONTENT_TYPE"] = "application/x-www-form-urlencoded" + if params.is_a?(Hash) + if data = Rack::Multipart.build_multipart(params) + opts[:input] = data + opts["CONTENT_LENGTH"] ||= data.length.to_s + opts["CONTENT_TYPE"] = "multipart/form-data; boundary=#{Rack::Multipart::MULTIPART_BOUNDARY}" + else + opts[:input] = Utils.build_nested_query(params) + end + else + opts[:input] = params + end + end + end + + empty_str = String.new + opts[:input] ||= empty_str + if String === opts[:input] + rack_input = StringIO.new(opts[:input]) + else + rack_input = opts[:input] + end + + rack_input.set_encoding(Encoding::BINARY) + env[RACK_INPUT] = rack_input + + env["CONTENT_LENGTH"] ||= env[RACK_INPUT].size.to_s if env[RACK_INPUT].respond_to?(:size) + + opts.each { |field, value| + env[field] = value if String === field + } + + env + end + end + + # Rack::MockResponse provides useful helpers for testing your apps. + # Usually, you don't create the MockResponse on your own, but use + # MockRequest. + + class MockResponse < Rack::Response + class << self + alias [] new + end + + # Headers + attr_reader :original_headers, :cookies + + # Errors + attr_accessor :errors + + def initialize(status, headers, body, errors = StringIO.new("")) + @original_headers = headers + @errors = errors.string if errors.respond_to?(:string) + @cookies = parse_cookies_from_header + + super(body, status, headers) + + buffered_body! + end + + def =~(other) + body =~ other + end + + def match(other) + body.match other + end + + def body + # FIXME: apparently users of MockResponse expect the return value of + # MockResponse#body to be a string. However, the real response object + # returns the body as a list. + # + # See spec_showstatus.rb: + # + # should "not replace existing messages" do + # ... + # res.body.should == "foo!" + # end + buffer = String.new + + super.each do |chunk| + buffer << chunk + end + + return buffer + end + + def empty? + [201, 204, 304].include? status + end + + def cookie(name) + cookies.fetch(name, nil) + end + + private + + def parse_cookies_from_header + cookies = Hash.new + if original_headers.has_key? 'Set-Cookie' + set_cookie_header = original_headers.fetch('Set-Cookie') + set_cookie_header.split("\n").each do |cookie| + cookie_name, cookie_filling = cookie.split('=', 2) + cookie_attributes = identify_cookie_attributes cookie_filling + parsed_cookie = CGI::Cookie.new( + 'name' => cookie_name.strip, + 'value' => cookie_attributes.fetch('value'), + 'path' => cookie_attributes.fetch('path', nil), + 'domain' => cookie_attributes.fetch('domain', nil), + 'expires' => cookie_attributes.fetch('expires', nil), + 'secure' => cookie_attributes.fetch('secure', false) + ) + cookies.store(cookie_name, parsed_cookie) + end + end + cookies + end + + def identify_cookie_attributes(cookie_filling) + cookie_bits = cookie_filling.split(';') + cookie_attributes = Hash.new + cookie_attributes.store('value', cookie_bits[0].strip) + cookie_bits.each do |bit| + if bit.include? '=' + cookie_attribute, attribute_value = bit.split('=') + cookie_attributes.store(cookie_attribute.strip, attribute_value.strip) + if cookie_attribute.include? 'max-age' + cookie_attributes.store('expires', Time.now + attribute_value.strip.to_i) + end + end + if bit.include? 'secure' + cookie_attributes.store('secure', true) + end + end + cookie_attributes + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart.rb new file mode 100644 index 0000000..45f43bb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +require_relative 'multipart/parser' + +module Rack + # A multipart form data parser, adapted from IOWA. + # + # Usually, Rack::Request#POST takes care of calling this. + module Multipart + autoload :UploadedFile, 'rack/multipart/uploaded_file' + autoload :Generator, 'rack/multipart/generator' + + EOL = "\r\n" + MULTIPART_BOUNDARY = "AaB03x" + MULTIPART = %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|ni + TOKEN = /[^\s()<>,;:\\"\/\[\]?=]+/ + CONDISP = /Content-Disposition:\s*#{TOKEN}\s*/i + VALUE = /"(?:\\"|[^"])*"|#{TOKEN}/ + BROKEN_QUOTED = /^#{CONDISP}.*;\s*filename="(.*?)"(?:\s*$|\s*;\s*#{TOKEN}=)/i + BROKEN_UNQUOTED = /^#{CONDISP}.*;\s*filename=(#{TOKEN})/i + MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{EOL}/ni + MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*;\s*name=(#{VALUE})/ni + MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{EOL}]*)/ni + # Updated definitions from RFC 2231 + ATTRIBUTE_CHAR = %r{[^ \t\v\n\r)(><@,;:\\"/\[\]?='*%]} + ATTRIBUTE = /#{ATTRIBUTE_CHAR}+/ + SECTION = /\*[0-9]+/ + REGULAR_PARAMETER_NAME = /#{ATTRIBUTE}#{SECTION}?/ + REGULAR_PARAMETER = /(#{REGULAR_PARAMETER_NAME})=(#{VALUE})/ + EXTENDED_OTHER_NAME = /#{ATTRIBUTE}\*[1-9][0-9]*\*/ + EXTENDED_OTHER_VALUE = /%[0-9a-fA-F]{2}|#{ATTRIBUTE_CHAR}/ + EXTENDED_OTHER_PARAMETER = /(#{EXTENDED_OTHER_NAME})=(#{EXTENDED_OTHER_VALUE}*)/ + EXTENDED_INITIAL_NAME = /#{ATTRIBUTE}(?:\*0)?\*/ + EXTENDED_INITIAL_VALUE = /[a-zA-Z0-9\-]*'[a-zA-Z0-9\-]*'#{EXTENDED_OTHER_VALUE}*/ + EXTENDED_INITIAL_PARAMETER = /(#{EXTENDED_INITIAL_NAME})=(#{EXTENDED_INITIAL_VALUE})/ + EXTENDED_PARAMETER = /#{EXTENDED_INITIAL_PARAMETER}|#{EXTENDED_OTHER_PARAMETER}/ + DISPPARM = /;\s*(?:#{REGULAR_PARAMETER}|#{EXTENDED_PARAMETER})\s*/ + RFC2183 = /^#{CONDISP}(#{DISPPARM})+$/i + + class << self + def parse_multipart(env, params = Rack::Utils.default_query_parser) + extract_multipart Rack::Request.new(env), params + end + + def extract_multipart(req, params = Rack::Utils.default_query_parser) + io = req.get_header(RACK_INPUT) + io.rewind + content_length = req.content_length + content_length = content_length.to_i if content_length + + tempfile = req.get_header(RACK_MULTIPART_TEMPFILE_FACTORY) || Parser::TEMPFILE_FACTORY + bufsize = req.get_header(RACK_MULTIPART_BUFFER_SIZE) || Parser::BUFSIZE + + info = Parser.parse io, content_length, req.get_header('CONTENT_TYPE'), tempfile, bufsize, params + req.set_header(RACK_TEMPFILES, info.tmp_files) + info.params + end + + def build_multipart(params, first = true) + Generator.new(params, first).dump + end + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart/generator.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart/generator.rb new file mode 100644 index 0000000..f798a98 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart/generator.rb @@ -0,0 +1,97 @@ +# frozen_string_literal: true + +module Rack + module Multipart + class Generator + def initialize(params, first = true) + @params, @first = params, first + + if @first && !@params.is_a?(Hash) + raise ArgumentError, "value must be a Hash" + end + end + + def dump + return nil if @first && !multipart? + return flattened_params unless @first + + flattened_params.map do |name, file| + if file.respond_to?(:original_filename) + if file.path + ::File.open(file.path, 'rb') do |f| + f.set_encoding(Encoding::BINARY) + content_for_tempfile(f, file, name) + end + else + content_for_tempfile(file, file, name) + end + else + content_for_other(file, name) + end + end.join << "--#{MULTIPART_BOUNDARY}--\r" + end + + private + def multipart? + query = lambda { |value| + case value + when Array + value.any?(&query) + when Hash + value.values.any?(&query) + when Rack::Multipart::UploadedFile + true + end + } + + @params.values.any?(&query) + end + + def flattened_params + @flattened_params ||= begin + h = Hash.new + @params.each do |key, value| + k = @first ? key.to_s : "[#{key}]" + + case value + when Array + value.map { |v| + Multipart.build_multipart(v, false).each { |subkey, subvalue| + h["#{k}[]#{subkey}"] = subvalue + } + } + when Hash + Multipart.build_multipart(value, false).each { |subkey, subvalue| + h[k + subkey] = subvalue + } + else + h[k] = value + end + end + h + end + end + + def content_for_tempfile(io, file, name) + length = ::File.stat(file.path).size if file.path + filename = "; filename=\"#{Utils.escape(file.original_filename)}\"" if file.original_filename +<<-EOF +--#{MULTIPART_BOUNDARY}\r +Content-Disposition: form-data; name="#{name}"#{filename}\r +Content-Type: #{file.content_type}\r +#{"Content-Length: #{length}\r\n" if length}\r +#{io.read}\r +EOF + end + + def content_for_other(file, name) +<<-EOF +--#{MULTIPART_BOUNDARY}\r +Content-Disposition: form-data; name="#{name}"\r +\r +#{file}\r +EOF + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart/parser.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart/parser.rb new file mode 100644 index 0000000..2eb3838 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart/parser.rb @@ -0,0 +1,364 @@ +# frozen_string_literal: true + +require 'strscan' + +module Rack + module Multipart + class MultipartPartLimitError < Errno::EMFILE; end + + class Parser + (require_relative '../core_ext/regexp'; using ::Rack::RegexpExtensions) if RUBY_VERSION < '2.4' + + BUFSIZE = 1_048_576 + TEXT_PLAIN = "text/plain" + TEMPFILE_FACTORY = lambda { |filename, content_type| + Tempfile.new(["RackMultipart", ::File.extname(filename.gsub("\0", '%00'))]) + } + + BOUNDARY_REGEX = /\A([^\n]*(?:\n|\Z))/ + + class BoundedIO # :nodoc: + def initialize(io, content_length) + @io = io + @content_length = content_length + @cursor = 0 + end + + def read(size, outbuf = nil) + return if @cursor >= @content_length + + left = @content_length - @cursor + + str = if left < size + @io.read left, outbuf + else + @io.read size, outbuf + end + + if str + @cursor += str.bytesize + else + # Raise an error for mismatching Content-Length and actual contents + raise EOFError, "bad content body" + end + + str + end + + def rewind + @io.rewind + end + end + + MultipartInfo = Struct.new :params, :tmp_files + EMPTY = MultipartInfo.new(nil, []) + + def self.parse_boundary(content_type) + return unless content_type + data = content_type.match(MULTIPART) + return unless data + data[1] + end + + def self.parse(io, content_length, content_type, tmpfile, bufsize, qp) + return EMPTY if 0 == content_length + + boundary = parse_boundary content_type + return EMPTY unless boundary + + io = BoundedIO.new(io, content_length) if content_length + outbuf = String.new + + parser = new(boundary, tmpfile, bufsize, qp) + parser.on_read io.read(bufsize, outbuf) + + loop do + break if parser.state == :DONE + parser.on_read io.read(bufsize, outbuf) + end + + io.rewind + parser.result + end + + class Collector + class MimePart < Struct.new(:body, :head, :filename, :content_type, :name) + def get_data + data = body + if filename == "" + # filename is blank which means no file has been selected + return + elsif filename + body.rewind if body.respond_to?(:rewind) + + # Take the basename of the upload's original filename. + # This handles the full Windows paths given by Internet Explorer + # (and perhaps other broken user agents) without affecting + # those which give the lone filename. + fn = filename.split(/[\/\\]/).last + + data = { filename: fn, type: content_type, + name: name, tempfile: body, head: head } + end + + yield data + end + end + + class BufferPart < MimePart + def file?; false; end + def close; end + end + + class TempfilePart < MimePart + def file?; true; end + def close; body.close; end + end + + include Enumerable + + def initialize(tempfile) + @tempfile = tempfile + @mime_parts = [] + @open_files = 0 + end + + def each + @mime_parts.each { |part| yield part } + end + + def on_mime_head(mime_index, head, filename, content_type, name) + if filename + body = @tempfile.call(filename, content_type) + body.binmode if body.respond_to?(:binmode) + klass = TempfilePart + @open_files += 1 + else + body = String.new + klass = BufferPart + end + + @mime_parts[mime_index] = klass.new(body, head, filename, content_type, name) + + check_open_files + end + + def on_mime_body(mime_index, content) + @mime_parts[mime_index].body << content + end + + def on_mime_finish(mime_index) + end + + private + + def check_open_files + if Utils.multipart_part_limit > 0 + if @open_files >= Utils.multipart_part_limit + @mime_parts.each(&:close) + raise MultipartPartLimitError, 'Maximum file multiparts in content reached' + end + end + end + end + + attr_reader :state + + def initialize(boundary, tempfile, bufsize, query_parser) + @query_parser = query_parser + @params = query_parser.make_params + @boundary = "--#{boundary}" + @bufsize = bufsize + + @full_boundary = @boundary + @end_boundary = @boundary + '--' + @state = :FAST_FORWARD + @mime_index = 0 + @collector = Collector.new tempfile + + @sbuf = StringScanner.new("".dup) + @body_regex = /(?:#{EOL})?#{Regexp.quote(@boundary)}(?:#{EOL}|--)/m + @rx_max_size = EOL.size + @boundary.bytesize + [EOL.size, '--'.size].max + @head_regex = /(.*?#{EOL})#{EOL}/m + end + + def on_read(content) + handle_empty_content!(content) + @sbuf.concat content + run_parser + end + + def result + @collector.each do |part| + part.get_data do |data| + tag_multipart_encoding(part.filename, part.content_type, part.name, data) + @query_parser.normalize_params(@params, part.name, data, @query_parser.param_depth_limit) + end + end + MultipartInfo.new @params.to_params_hash, @collector.find_all(&:file?).map(&:body) + end + + private + + def run_parser + loop do + case @state + when :FAST_FORWARD + break if handle_fast_forward == :want_read + when :CONSUME_TOKEN + break if handle_consume_token == :want_read + when :MIME_HEAD + break if handle_mime_head == :want_read + when :MIME_BODY + break if handle_mime_body == :want_read + when :DONE + break + end + end + end + + def handle_fast_forward + if consume_boundary + @state = :MIME_HEAD + else + raise EOFError, "bad content body" if @sbuf.rest_size >= @bufsize + :want_read + end + end + + def handle_consume_token + tok = consume_boundary + # break if we're at the end of a buffer, but not if it is the end of a field + @state = if tok == :END_BOUNDARY || (@sbuf.eos? && tok != :BOUNDARY) + :DONE + else + :MIME_HEAD + end + end + + def handle_mime_head + if @sbuf.scan_until(@head_regex) + head = @sbuf[1] + content_type = head[MULTIPART_CONTENT_TYPE, 1] + if name = head[MULTIPART_CONTENT_DISPOSITION, 1] + name = Rack::Auth::Digest::Params::dequote(name) + else + name = head[MULTIPART_CONTENT_ID, 1] + end + + filename = get_filename(head) + + if name.nil? || name.empty? + name = filename || "#{content_type || TEXT_PLAIN}[]".dup + end + + @collector.on_mime_head @mime_index, head, filename, content_type, name + @state = :MIME_BODY + else + :want_read + end + end + + def handle_mime_body + if (body_with_boundary = @sbuf.check_until(@body_regex)) # check but do not advance the pointer yet + body = body_with_boundary.sub(/#{@body_regex}\z/m, '') # remove the boundary from the string + @collector.on_mime_body @mime_index, body + @sbuf.pos += body.length + 2 # skip \r\n after the content + @state = :CONSUME_TOKEN + @mime_index += 1 + else + # Save what we have so far + if @rx_max_size < @sbuf.rest_size + delta = @sbuf.rest_size - @rx_max_size + @collector.on_mime_body @mime_index, @sbuf.peek(delta) + @sbuf.pos += delta + @sbuf.string = @sbuf.rest + end + :want_read + end + end + + def full_boundary; @full_boundary; end + + def consume_boundary + while read_buffer = @sbuf.scan_until(BOUNDARY_REGEX) + case read_buffer.strip + when full_boundary then return :BOUNDARY + when @end_boundary then return :END_BOUNDARY + end + return if @sbuf.eos? + end + end + + def get_filename(head) + filename = nil + case head + when RFC2183 + params = Hash[*head.scan(DISPPARM).flat_map(&:compact)] + + if filename = params['filename'] + filename = $1 if filename =~ /^"(.*)"$/ + elsif filename = params['filename*'] + encoding, _, filename = filename.split("'", 3) + end + when BROKEN_QUOTED, BROKEN_UNQUOTED + filename = $1 + end + + return unless filename + + if filename.scan(/%.?.?/).all? { |s| /%[0-9a-fA-F]{2}/.match?(s) } + filename = Utils.unescape_path(filename) + end + + filename.scrub! + + if filename !~ /\\[^\\"]/ + filename = filename.gsub(/\\(.)/, '\1') + end + + if encoding + filename.force_encoding ::Encoding.find(encoding) + end + + filename + end + + CHARSET = "charset" + + def tag_multipart_encoding(filename, content_type, name, body) + name = name.to_s + encoding = Encoding::UTF_8 + + name.force_encoding(encoding) + + return if filename + + if content_type + list = content_type.split(';') + type_subtype = list.first + type_subtype.strip! + if TEXT_PLAIN == type_subtype + rest = list.drop 1 + rest.each do |param| + k, v = param.split('=', 2) + k.strip! + v.strip! + v = v[1..-2] if v.start_with?('"') && v.end_with?('"') + encoding = Encoding.find v if k == CHARSET + end + end + end + + name.force_encoding(encoding) + body.force_encoding(encoding) + end + + def handle_empty_content!(content) + if content.nil? || content.empty? + raise EOFError + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart/uploaded_file.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart/uploaded_file.rb new file mode 100644 index 0000000..9eaf691 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/multipart/uploaded_file.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +module Rack + module Multipart + class UploadedFile + # The filename, *not* including the path, of the "uploaded" file + attr_reader :original_filename + + # The content type of the "uploaded" file + attr_accessor :content_type + + def initialize(filepath = nil, ct = "text/plain", bin = false, + path: filepath, content_type: ct, binary: bin, filename: nil, io: nil) + if io + @tempfile = io + @original_filename = filename + else + raise "#{path} file does not exist" unless ::File.exist?(path) + @original_filename = filename || ::File.basename(path) + @tempfile = Tempfile.new([@original_filename, ::File.extname(path)], encoding: Encoding::BINARY) + @tempfile.binmode if binary + FileUtils.copy_file(path, @tempfile.path) + end + @content_type = content_type + end + + def path + @tempfile.path if @tempfile.respond_to?(:path) + end + alias_method :local_path, :path + + def respond_to?(*args) + super or @tempfile.respond_to?(*args) + end + + def method_missing(method_name, *args, &block) #:nodoc: + @tempfile.__send__(method_name, *args, &block) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/null_logger.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/null_logger.rb new file mode 100644 index 0000000..3eff73d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/null_logger.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +module Rack + class NullLogger + def initialize(app) + @app = app + end + + def call(env) + env[RACK_LOGGER] = self + @app.call(env) + end + + def info(progname = nil, &block); end + def debug(progname = nil, &block); end + def warn(progname = nil, &block); end + def error(progname = nil, &block); end + def fatal(progname = nil, &block); end + def unknown(progname = nil, &block); end + def info? ; end + def debug? ; end + def warn? ; end + def error? ; end + def fatal? ; end + def level ; end + def progname ; end + def datetime_format ; end + def formatter ; end + def sev_threshold ; end + def level=(level); end + def progname=(progname); end + def datetime_format=(datetime_format); end + def formatter=(formatter); end + def sev_threshold=(sev_threshold); end + def close ; end + def add(severity, message = nil, progname = nil, &block); end + def <<(msg); end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/query_parser.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/query_parser.rb new file mode 100644 index 0000000..dbbb18e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/query_parser.rb @@ -0,0 +1,217 @@ +# frozen_string_literal: true + +module Rack + class QueryParser + (require_relative 'core_ext/regexp'; using ::Rack::RegexpExtensions) if RUBY_VERSION < '2.4' + + DEFAULT_SEP = /[&;] */n + COMMON_SEP = { ";" => /[;] */n, ";," => /[;,] */n, "&" => /[&] */n } + + # ParameterTypeError is the error that is raised when incoming structural + # parameters (parsed by parse_nested_query) contain conflicting types. + class ParameterTypeError < TypeError; end + + # InvalidParameterError is the error that is raised when incoming structural + # parameters (parsed by parse_nested_query) contain invalid format or byte + # sequence. + class InvalidParameterError < ArgumentError; end + + def self.make_default(key_space_limit, param_depth_limit) + new Params, key_space_limit, param_depth_limit + end + + attr_reader :key_space_limit, :param_depth_limit + + def initialize(params_class, key_space_limit, param_depth_limit) + @params_class = params_class + @key_space_limit = key_space_limit + @param_depth_limit = param_depth_limit + end + + # Stolen from Mongrel, with some small modifications: + # Parses a query string by breaking it up at the '&' + # and ';' characters. You can also use this to parse + # cookies by changing the characters used in the second + # parameter (which defaults to '&;'). + def parse_query(qs, d = nil, &unescaper) + unescaper ||= method(:unescape) + + params = make_params + + (qs || '').split(d ? (COMMON_SEP[d] || /[#{d}] */n) : DEFAULT_SEP).each do |p| + next if p.empty? + k, v = p.split('=', 2).map!(&unescaper) + + if cur = params[k] + if cur.class == Array + params[k] << v + else + params[k] = [cur, v] + end + else + params[k] = v + end + end + + return params.to_h + end + + # parse_nested_query expands a query string into structural types. Supported + # types are Arrays, Hashes and basic value types. It is possible to supply + # query strings with parameters of conflicting types, in this case a + # ParameterTypeError is raised. Users are encouraged to return a 400 in this + # case. + def parse_nested_query(qs, d = nil) + params = make_params + + unless qs.nil? || qs.empty? + (qs || '').split(d ? (COMMON_SEP[d] || /[#{d}] */n) : DEFAULT_SEP).each do |p| + k, v = p.split('=', 2).map! { |s| unescape(s) } + + normalize_params(params, k, v, param_depth_limit) + end + end + + return params.to_h + rescue ArgumentError => e + raise InvalidParameterError, e.message, e.backtrace + end + + # normalize_params recursively expands parameters into structural types. If + # the structural types represented by two different parameter names are in + # conflict, a ParameterTypeError is raised. + def normalize_params(params, name, v, depth) + raise RangeError if depth <= 0 + + name =~ %r(\A[\[\]]*([^\[\]]+)\]*) + k = $1 || '' + after = $' || '' + + if k.empty? + if !v.nil? && name == "[]" + return Array(v) + else + return + end + end + + if after == '' + params[k] = v + elsif after == "[" + params[name] = v + elsif after == "[]" + params[k] ||= [] + raise ParameterTypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array) + params[k] << v + elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$) + child_key = $1 + params[k] ||= [] + raise ParameterTypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array) + if params_hash_type?(params[k].last) && !params_hash_has_key?(params[k].last, child_key) + normalize_params(params[k].last, child_key, v, depth - 1) + else + params[k] << normalize_params(make_params, child_key, v, depth - 1) + end + else + params[k] ||= make_params + raise ParameterTypeError, "expected Hash (got #{params[k].class.name}) for param `#{k}'" unless params_hash_type?(params[k]) + params[k] = normalize_params(params[k], after, v, depth - 1) + end + + params + end + + def make_params + @params_class.new @key_space_limit + end + + def new_space_limit(key_space_limit) + self.class.new @params_class, key_space_limit, param_depth_limit + end + + def new_depth_limit(param_depth_limit) + self.class.new @params_class, key_space_limit, param_depth_limit + end + + private + + def params_hash_type?(obj) + obj.kind_of?(@params_class) + end + + def params_hash_has_key?(hash, key) + return false if /\[\]/.match?(key) + + key.split(/[\[\]]+/).inject(hash) do |h, part| + next h if part == '' + return false unless params_hash_type?(h) && h.key?(part) + h[part] + end + + true + end + + def unescape(s) + Utils.unescape(s) + end + + class Params + def initialize(limit) + @limit = limit + @size = 0 + @params = {} + end + + def [](key) + @params[key] + end + + def []=(key, value) + @size += key.size if key && !@params.key?(key) + raise RangeError, 'exceeded available parameter key space' if @size > @limit + @params[key] = value + end + + def key?(key) + @params.key?(key) + end + + # Recursively unwraps nested `Params` objects and constructs an object + # of the same shape, but using the objects' internal representations + # (Ruby hashes) in place of the objects. The result is a hash consisting + # purely of Ruby primitives. + # + # Mutation warning! + # + # 1. This method mutates the internal representation of the `Params` + # objects in order to save object allocations. + # + # 2. The value you get back is a reference to the internal hash + # representation, not a copy. + # + # 3. Because the `Params` object's internal representation is mutable + # through the `#[]=` method, it is not thread safe. The result of + # getting the hash representation while another thread is adding a + # key to it is non-deterministic. + # + def to_h + @params.each do |key, value| + case value + when self + # Handle circular references gracefully. + @params[key] = @params + when Params + @params[key] = value.to_h + when Array + value.map! { |v| v.kind_of?(Params) ? v.to_h : v } + else + # Ignore anything that is not a `Params` object or + # a collection that can contain one. + end + end + @params + end + alias_method :to_params_hash, :to_h + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/recursive.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/recursive.rb new file mode 100644 index 0000000..6971cbf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/recursive.rb @@ -0,0 +1,64 @@ +# frozen_string_literal: true + +require 'uri' + +module Rack + # Rack::ForwardRequest gets caught by Rack::Recursive and redirects + # the current request to the app at +url+. + # + # raise ForwardRequest.new("/not-found") + # + + class ForwardRequest < Exception + attr_reader :url, :env + + def initialize(url, env = {}) + @url = URI(url) + @env = env + + @env[PATH_INFO] = @url.path + @env[QUERY_STRING] = @url.query if @url.query + @env[HTTP_HOST] = @url.host if @url.host + @env[HTTP_PORT] = @url.port if @url.port + @env[RACK_URL_SCHEME] = @url.scheme if @url.scheme + + super "forwarding to #{url}" + end + end + + # Rack::Recursive allows applications called down the chain to + # include data from other applications (by using + # rack['rack.recursive.include'][...] or raise a + # ForwardRequest to redirect internally. + + class Recursive + def initialize(app) + @app = app + end + + def call(env) + dup._call(env) + end + + def _call(env) + @script_name = env[SCRIPT_NAME] + @app.call(env.merge(RACK_RECURSIVE_INCLUDE => method(:include))) + rescue ForwardRequest => req + call(env.merge(req.env)) + end + + def include(env, path) + unless path.index(@script_name) == 0 && (path[@script_name.size] == ?/ || + path[@script_name.size].nil?) + raise ArgumentError, "can only include below #{@script_name}, not #{path}" + end + + env = env.merge(PATH_INFO => path, + SCRIPT_NAME => @script_name, + REQUEST_METHOD => GET, + "CONTENT_LENGTH" => "0", "CONTENT_TYPE" => "", + RACK_INPUT => StringIO.new("")) + @app.call(env) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/reloader.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/reloader.rb new file mode 100644 index 0000000..2f17f50 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/reloader.rb @@ -0,0 +1,114 @@ +# frozen_string_literal: true + +# Copyright (C) 2009-2018 Michael Fellinger +# Rack::Reloader is subject to the terms of an MIT-style license. +# See MIT-LICENSE or https://opensource.org/licenses/MIT. + +require 'pathname' + +module Rack + + # High performant source reloader + # + # This class acts as Rack middleware. + # + # What makes it especially suited for use in a production environment is that + # any file will only be checked once and there will only be made one system + # call stat(2). + # + # Please note that this will not reload files in the background, it does so + # only when actively called. + # + # It is performing a check/reload cycle at the start of every request, but + # also respects a cool down time, during which nothing will be done. + class Reloader + (require_relative 'core_ext/regexp'; using ::Rack::RegexpExtensions) if RUBY_VERSION < '2.4' + + def initialize(app, cooldown = 10, backend = Stat) + @app = app + @cooldown = cooldown + @last = (Time.now - cooldown) + @cache = {} + @mtimes = {} + @reload_mutex = Mutex.new + + extend backend + end + + def call(env) + if @cooldown and Time.now > @last + @cooldown + if Thread.list.size > 1 + @reload_mutex.synchronize{ reload! } + else + reload! + end + + @last = Time.now + end + + @app.call(env) + end + + def reload!(stderr = $stderr) + rotation do |file, mtime| + previous_mtime = @mtimes[file] ||= mtime + safe_load(file, mtime, stderr) if mtime > previous_mtime + end + end + + # A safe Kernel::load, issuing the hooks depending on the results + def safe_load(file, mtime, stderr = $stderr) + load(file) + stderr.puts "#{self.class}: reloaded `#{file}'" + file + rescue LoadError, SyntaxError => ex + stderr.puts ex + ensure + @mtimes[file] = mtime + end + + module Stat + def rotation + files = [$0, *$LOADED_FEATURES].uniq + paths = ['./', *$LOAD_PATH].uniq + + files.map{|file| + next if /\.(so|bundle)$/.match?(file) # cannot reload compiled files + + found, stat = figure_path(file, paths) + next unless found && stat && mtime = stat.mtime + + @cache[file] = found + + yield(found, mtime) + }.compact + end + + # Takes a relative or absolute +file+ name, a couple possible +paths+ that + # the +file+ might reside in. Returns the full path and File::Stat for the + # path. + def figure_path(file, paths) + found = @cache[file] + found = file if !found and Pathname.new(file).absolute? + found, stat = safe_stat(found) + return found, stat if found + + paths.find do |possible_path| + path = ::File.join(possible_path, file) + found, stat = safe_stat(path) + return ::File.expand_path(found), stat if found + end + + return false, false + end + + def safe_stat(file) + return unless file + stat = ::File.stat(file) + return file, stat if stat.file? + rescue Errno::ENOENT, Errno::ENOTDIR, Errno::ESRCH + @cache.delete(file) and false + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/request.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/request.rb new file mode 100644 index 0000000..750a0dc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/request.rb @@ -0,0 +1,659 @@ +# frozen_string_literal: true + +module Rack + # Rack::Request provides a convenient interface to a Rack + # environment. It is stateless, the environment +env+ passed to the + # constructor will be directly modified. + # + # req = Rack::Request.new(env) + # req.post? + # req.params["data"] + + class Request + (require_relative 'core_ext/regexp'; using ::Rack::RegexpExtensions) if RUBY_VERSION < '2.4' + + class << self + attr_accessor :ip_filter + end + + self.ip_filter = lambda { |ip| /\A127\.0\.0\.1\Z|\A(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.|\A::1\Z|\Afd[0-9a-f]{2}:.+|\Alocalhost\Z|\Aunix\Z|\Aunix:/i.match?(ip) } + ALLOWED_SCHEMES = %w(https http).freeze + SCHEME_WHITELIST = ALLOWED_SCHEMES + if Object.respond_to?(:deprecate_constant) + deprecate_constant :SCHEME_WHITELIST + end + + def initialize(env) + @params = nil + super(env) + end + + def params + @params ||= super + end + + def update_param(k, v) + super + @params = nil + end + + def delete_param(k) + v = super + @params = nil + v + end + + module Env + # The environment of the request. + attr_reader :env + + def initialize(env) + @env = env + super() + end + + # Predicate method to test to see if `name` has been set as request + # specific data + def has_header?(name) + @env.key? name + end + + # Get a request specific value for `name`. + def get_header(name) + @env[name] + end + + # If a block is given, it yields to the block if the value hasn't been set + # on the request. + def fetch_header(name, &block) + @env.fetch(name, &block) + end + + # Loops through each key / value pair in the request specific data. + def each_header(&block) + @env.each(&block) + end + + # Set a request specific value for `name` to `v` + def set_header(name, v) + @env[name] = v + end + + # Add a header that may have multiple values. + # + # Example: + # request.add_header 'Accept', 'image/png' + # request.add_header 'Accept', '*/*' + # + # assert_equal 'image/png,*/*', request.get_header('Accept') + # + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 + def add_header(key, v) + if v.nil? + get_header key + elsif has_header? key + set_header key, "#{get_header key},#{v}" + else + set_header key, v + end + end + + # Delete a request specific value for `name`. + def delete_header(name) + @env.delete name + end + + def initialize_copy(other) + @env = other.env.dup + end + end + + module Helpers + # The set of form-data media-types. Requests that do not indicate + # one of the media types present in this list will not be eligible + # for form-data / param parsing. + FORM_DATA_MEDIA_TYPES = [ + 'application/x-www-form-urlencoded', + 'multipart/form-data' + ] + + # The set of media-types. Requests that do not indicate + # one of the media types present in this list will not be eligible + # for param parsing like soap attachments or generic multiparts + PARSEABLE_DATA_MEDIA_TYPES = [ + 'multipart/related', + 'multipart/mixed' + ] + + # Default ports depending on scheme. Used to decide whether or not + # to include the port in a generated URI. + DEFAULT_PORTS = { 'http' => 80, 'https' => 443, 'coffee' => 80 } + + # The address of the client which connected to the proxy. + HTTP_X_FORWARDED_FOR = 'HTTP_X_FORWARDED_FOR' + + # The contents of the host/:authority header sent to the proxy. + HTTP_X_FORWARDED_HOST = 'HTTP_X_FORWARDED_HOST' + + # The value of the scheme sent to the proxy. + HTTP_X_FORWARDED_SCHEME = 'HTTP_X_FORWARDED_SCHEME' + + # The protocol used to connect to the proxy. + HTTP_X_FORWARDED_PROTO = 'HTTP_X_FORWARDED_PROTO' + + # The port used to connect to the proxy. + HTTP_X_FORWARDED_PORT = 'HTTP_X_FORWARDED_PORT' + + # Another way for specifing https scheme was used. + HTTP_X_FORWARDED_SSL = 'HTTP_X_FORWARDED_SSL' + + def body; get_header(RACK_INPUT) end + def script_name; get_header(SCRIPT_NAME).to_s end + def script_name=(s); set_header(SCRIPT_NAME, s.to_s) end + + def path_info; get_header(PATH_INFO).to_s end + def path_info=(s); set_header(PATH_INFO, s.to_s) end + + def request_method; get_header(REQUEST_METHOD) end + def query_string; get_header(QUERY_STRING).to_s end + def content_length; get_header('CONTENT_LENGTH') end + def logger; get_header(RACK_LOGGER) end + def user_agent; get_header('HTTP_USER_AGENT') end + def multithread?; get_header(RACK_MULTITHREAD) end + + # the referer of the client + def referer; get_header('HTTP_REFERER') end + alias referrer referer + + def session + fetch_header(RACK_SESSION) do |k| + set_header RACK_SESSION, default_session + end + end + + def session_options + fetch_header(RACK_SESSION_OPTIONS) do |k| + set_header RACK_SESSION_OPTIONS, {} + end + end + + # Checks the HTTP request method (or verb) to see if it was of type DELETE + def delete?; request_method == DELETE end + + # Checks the HTTP request method (or verb) to see if it was of type GET + def get?; request_method == GET end + + # Checks the HTTP request method (or verb) to see if it was of type HEAD + def head?; request_method == HEAD end + + # Checks the HTTP request method (or verb) to see if it was of type OPTIONS + def options?; request_method == OPTIONS end + + # Checks the HTTP request method (or verb) to see if it was of type LINK + def link?; request_method == LINK end + + # Checks the HTTP request method (or verb) to see if it was of type PATCH + def patch?; request_method == PATCH end + + # Checks the HTTP request method (or verb) to see if it was of type POST + def post?; request_method == POST end + + # Checks the HTTP request method (or verb) to see if it was of type PUT + def put?; request_method == PUT end + + # Checks the HTTP request method (or verb) to see if it was of type TRACE + def trace?; request_method == TRACE end + + # Checks the HTTP request method (or verb) to see if it was of type UNLINK + def unlink?; request_method == UNLINK end + + def scheme + if get_header(HTTPS) == 'on' + 'https' + elsif get_header(HTTP_X_FORWARDED_SSL) == 'on' + 'https' + elsif forwarded_scheme + forwarded_scheme + else + get_header(RACK_URL_SCHEME) + end + end + + # The authority of the incoming request as defined by RFC3976. + # https://tools.ietf.org/html/rfc3986#section-3.2 + # + # In HTTP/1, this is the `host` header. + # In HTTP/2, this is the `:authority` pseudo-header. + def authority + forwarded_authority || host_authority || server_authority + end + + # The authority as defined by the `SERVER_NAME` and `SERVER_PORT` + # variables. + def server_authority + host = self.server_name + port = self.server_port + + if host + if port + "#{host}:#{port}" + else + host + end + end + end + + def server_name + get_header(SERVER_NAME) + end + + def server_port + if port = get_header(SERVER_PORT) + Integer(port) + end + end + + def cookies + hash = fetch_header(RACK_REQUEST_COOKIE_HASH) do |key| + set_header(key, {}) + end + + string = get_header(HTTP_COOKIE) + + unless string == get_header(RACK_REQUEST_COOKIE_STRING) + hash.replace Utils.parse_cookies_header(string) + set_header(RACK_REQUEST_COOKIE_STRING, string) + end + + hash + end + + def content_type + content_type = get_header('CONTENT_TYPE') + content_type.nil? || content_type.empty? ? nil : content_type + end + + def xhr? + get_header("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest" + end + + # The `HTTP_HOST` header. + def host_authority + get_header(HTTP_HOST) + end + + def host_with_port(authority = self.authority) + host, _, port = split_authority(authority) + + if port == DEFAULT_PORTS[self.scheme] + host + else + authority + end + end + + # Returns a formatted host, suitable for being used in a URI. + def host + split_authority(self.authority)[0] + end + + # Returns an address suitable for being to resolve to an address. + # In the case of a domain name or IPv4 address, the result is the same + # as +host+. In the case of IPv6 or future address formats, the square + # brackets are removed. + def hostname + split_authority(self.authority)[1] + end + + def port + if authority = self.authority + _, _, port = split_authority(self.authority) + + if port + return port + end + end + + if forwarded_port = self.forwarded_port + return forwarded_port.first + end + + if scheme = self.scheme + if port = DEFAULT_PORTS[self.scheme] + return port + end + end + + self.server_port + end + + def forwarded_for + if value = get_header(HTTP_X_FORWARDED_FOR) + split_header(value).map do |authority| + split_authority(wrap_ipv6(authority))[1] + end + end + end + + def forwarded_port + if value = get_header(HTTP_X_FORWARDED_PORT) + split_header(value).map(&:to_i) + end + end + + def forwarded_authority + if value = get_header(HTTP_X_FORWARDED_HOST) + wrap_ipv6(split_header(value).first) + end + end + + def ssl? + scheme == 'https' || scheme == 'wss' + end + + def ip + remote_addresses = split_header(get_header('REMOTE_ADDR')) + external_addresses = reject_trusted_ip_addresses(remote_addresses) + + unless external_addresses.empty? + return external_addresses.first + end + + if forwarded_for = self.forwarded_for + unless forwarded_for.empty? + # The forwarded for addresses are ordered: client, proxy1, proxy2. + # So we reject all the trusted addresses (proxy*) and return the + # last client. Or if we trust everyone, we just return the first + # address. + return reject_trusted_ip_addresses(forwarded_for).last || forwarded_for.first + end + end + + # If all the addresses are trusted, and we aren't forwarded, just return + # the first remote address, which represents the source of the request. + remote_addresses.first + end + + # The media type (type/subtype) portion of the CONTENT_TYPE header + # without any media type parameters. e.g., when CONTENT_TYPE is + # "text/plain;charset=utf-8", the media-type is "text/plain". + # + # For more information on the use of media types in HTTP, see: + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7 + def media_type + MediaType.type(content_type) + end + + # The media type parameters provided in CONTENT_TYPE as a Hash, or + # an empty Hash if no CONTENT_TYPE or media-type parameters were + # provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8", + # this method responds with the following Hash: + # { 'charset' => 'utf-8' } + def media_type_params + MediaType.params(content_type) + end + + # The character set of the request body if a "charset" media type + # parameter was given, or nil if no "charset" was specified. Note + # that, per RFC2616, text/* media types that specify no explicit + # charset are to be considered ISO-8859-1. + def content_charset + media_type_params['charset'] + end + + # Determine whether the request body contains form-data by checking + # the request Content-Type for one of the media-types: + # "application/x-www-form-urlencoded" or "multipart/form-data". The + # list of form-data media types can be modified through the + # +FORM_DATA_MEDIA_TYPES+ array. + # + # A request body is also assumed to contain form-data when no + # Content-Type header is provided and the request_method is POST. + def form_data? + type = media_type + meth = get_header(RACK_METHODOVERRIDE_ORIGINAL_METHOD) || get_header(REQUEST_METHOD) + + (meth == POST && type.nil?) || FORM_DATA_MEDIA_TYPES.include?(type) + end + + # Determine whether the request body contains data by checking + # the request media_type against registered parse-data media-types + def parseable_data? + PARSEABLE_DATA_MEDIA_TYPES.include?(media_type) + end + + # Returns the data received in the query string. + def GET + if get_header(RACK_REQUEST_QUERY_STRING) == query_string + get_header(RACK_REQUEST_QUERY_HASH) + else + query_hash = parse_query(query_string, '&;') + set_header(RACK_REQUEST_QUERY_STRING, query_string) + set_header(RACK_REQUEST_QUERY_HASH, query_hash) + end + end + + # Returns the data received in the request body. + # + # This method support both application/x-www-form-urlencoded and + # multipart/form-data. + def POST + if get_header(RACK_INPUT).nil? + raise "Missing rack.input" + elsif get_header(RACK_REQUEST_FORM_INPUT) == get_header(RACK_INPUT) + get_header(RACK_REQUEST_FORM_HASH) + elsif form_data? || parseable_data? + unless set_header(RACK_REQUEST_FORM_HASH, parse_multipart) + form_vars = get_header(RACK_INPUT).read + + # Fix for Safari Ajax postings that always append \0 + # form_vars.sub!(/\0\z/, '') # performance replacement: + form_vars.slice!(-1) if form_vars.end_with?("\0") + + set_header RACK_REQUEST_FORM_VARS, form_vars + set_header RACK_REQUEST_FORM_HASH, parse_query(form_vars, '&') + + get_header(RACK_INPUT).rewind + end + set_header RACK_REQUEST_FORM_INPUT, get_header(RACK_INPUT) + get_header RACK_REQUEST_FORM_HASH + else + {} + end + end + + # The union of GET and POST data. + # + # Note that modifications will not be persisted in the env. Use update_param or delete_param if you want to destructively modify params. + def params + self.GET.merge(self.POST) + end + + # Destructively update a parameter, whether it's in GET and/or POST. Returns nil. + # + # The parameter is updated wherever it was previous defined, so GET, POST, or both. If it wasn't previously defined, it's inserted into GET. + # + # env['rack.input'] is not touched. + def update_param(k, v) + found = false + if self.GET.has_key?(k) + found = true + self.GET[k] = v + end + if self.POST.has_key?(k) + found = true + self.POST[k] = v + end + unless found + self.GET[k] = v + end + end + + # Destructively delete a parameter, whether it's in GET or POST. Returns the value of the deleted parameter. + # + # If the parameter is in both GET and POST, the POST value takes precedence since that's how #params works. + # + # env['rack.input'] is not touched. + def delete_param(k) + post_value, get_value = self.POST.delete(k), self.GET.delete(k) + post_value || get_value + end + + def base_url + "#{scheme}://#{host_with_port}" + end + + # Tries to return a remake of the original request URL as a string. + def url + base_url + fullpath + end + + def path + script_name + path_info + end + + def fullpath + query_string.empty? ? path : "#{path}?#{query_string}" + end + + def accept_encoding + parse_http_accept_header(get_header("HTTP_ACCEPT_ENCODING")) + end + + def accept_language + parse_http_accept_header(get_header("HTTP_ACCEPT_LANGUAGE")) + end + + def trusted_proxy?(ip) + Rack::Request.ip_filter.call(ip) + end + + # shortcut for request.params[key] + def [](key) + if $VERBOSE + warn("Request#[] is deprecated and will be removed in a future version of Rack. Please use request.params[] instead") + end + + params[key.to_s] + end + + # shortcut for request.params[key] = value + # + # Note that modifications will not be persisted in the env. Use update_param or delete_param if you want to destructively modify params. + def []=(key, value) + if $VERBOSE + warn("Request#[]= is deprecated and will be removed in a future version of Rack. Please use request.params[]= instead") + end + + params[key.to_s] = value + end + + # like Hash#values_at + def values_at(*keys) + keys.map { |key| params[key] } + end + + private + + def default_session; {}; end + + # Assist with compatibility when processing `X-Forwarded-For`. + def wrap_ipv6(host) + # Even thought IPv6 addresses should be wrapped in square brackets, + # sometimes this is not done in various legacy/underspecified headers. + # So we try to fix this situation for compatibility reasons. + + # Try to detect IPv6 addresses which aren't escaped yet: + if !host.start_with?('[') && host.count(':') > 1 + "[#{host}]" + else + host + end + end + + def parse_http_accept_header(header) + header.to_s.split(/\s*,\s*/).map do |part| + attribute, parameters = part.split(/\s*;\s*/, 2) + quality = 1.0 + if parameters and /\Aq=([\d.]+)/ =~ parameters + quality = $1.to_f + end + [attribute, quality] + end + end + + def query_parser + Utils.default_query_parser + end + + def parse_query(qs, d = '&') + query_parser.parse_nested_query(qs, d) + end + + def parse_multipart + Rack::Multipart.extract_multipart(self, query_parser) + end + + def split_header(value) + value ? value.strip.split(/[,\s]+/) : [] + end + + AUTHORITY = /^ + # The host: + (? + # An IPv6 address: + (\[(?.*)\]) + | + # An IPv4 address: + (?[\d\.]+) + | + # A hostname: + (?[a-zA-Z0-9\.\-]+) + ) + # The optional port: + (:(?\d+))? + $/x + + private_constant :AUTHORITY + + def split_authority(authority) + if match = AUTHORITY.match(authority) + if address = match[:ip6] + return match[:host], address, match[:port]&.to_i + else + return match[:host], match[:host], match[:port]&.to_i + end + end + + # Give up! + return authority, authority, nil + end + + def reject_trusted_ip_addresses(ip_addresses) + ip_addresses.reject { |ip| trusted_proxy?(ip) } + end + + def forwarded_scheme + allowed_scheme(get_header(HTTP_X_FORWARDED_SCHEME)) || + allowed_scheme(extract_proto_header(get_header(HTTP_X_FORWARDED_PROTO))) + end + + def allowed_scheme(header) + header if ALLOWED_SCHEMES.include?(header) + end + + def extract_proto_header(header) + if header + if (comma_index = header.index(',')) + header[0, comma_index] + else + header + end + end + end + end + + include Env + include Helpers + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/response.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/response.rb new file mode 100644 index 0000000..fd6d2f5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/response.rb @@ -0,0 +1,318 @@ +# frozen_string_literal: true + +require 'time' + +module Rack + # Rack::Response provides a convenient interface to create a Rack + # response. + # + # It allows setting of headers and cookies, and provides useful + # defaults (an OK response with empty headers and body). + # + # You can use Response#write to iteratively generate your response, + # but note that this is buffered by Rack::Response until you call + # +finish+. +finish+ however can take a block inside which calls to + # +write+ are synchronous with the Rack response. + # + # Your application's +call+ should end returning Response#finish. + class Response + def self.[](status, headers, body) + self.new(body, status, headers) + end + + CHUNKED = 'chunked' + STATUS_WITH_NO_ENTITY_BODY = Utils::STATUS_WITH_NO_ENTITY_BODY + + attr_accessor :length, :status, :body + attr_reader :headers + + # @deprecated Use {#headers} instead. + alias header headers + + # Initialize the response object with the specified body, status + # and headers. + # + # @param body [nil, #each, #to_str] the response body. + # @param status [Integer] the integer status as defined by the + # HTTP protocol RFCs. + # @param headers [#each] a list of key-value header pairs which + # conform to the HTTP protocol RFCs. + # + # Providing a body which responds to #to_str is legacy behaviour. + def initialize(body = nil, status = 200, headers = {}) + @status = status.to_i + @headers = Utils::HeaderHash[headers] + + @writer = self.method(:append) + + @block = nil + + # Keep track of whether we have expanded the user supplied body. + if body.nil? + @body = [] + @buffered = true + @length = 0 + elsif body.respond_to?(:to_str) + @body = [body] + @buffered = true + @length = body.to_str.bytesize + else + @body = body + @buffered = false + @length = 0 + end + + yield self if block_given? + end + + def redirect(target, status = 302) + self.status = status + self.location = target + end + + def chunked? + CHUNKED == get_header(TRANSFER_ENCODING) + end + + # Generate a response array consistent with the requirements of the SPEC. + # @return [Array] a 3-tuple suitable of `[status, headers, body]` + # which is suitable to be returned from the middleware `#call(env)` method. + def finish(&block) + if STATUS_WITH_NO_ENTITY_BODY[status.to_i] + delete_header CONTENT_TYPE + delete_header CONTENT_LENGTH + close + return [@status, @headers, []] + else + if block_given? + @block = block + return [@status, @headers, self] + else + return [@status, @headers, @body] + end + end + end + + alias to_a finish # For *response + + def each(&callback) + @body.each(&callback) + @buffered = true + + if @block + @writer = callback + @block.call(self) + end + end + + # Append to body and update Content-Length. + # + # NOTE: Do not mix #write and direct #body access! + # + def write(chunk) + buffered_body! + + @writer.call(chunk.to_s) + end + + def close + @body.close if @body.respond_to?(:close) + end + + def empty? + @block == nil && @body.empty? + end + + def has_header?(key); headers.key? key; end + def get_header(key); headers[key]; end + def set_header(key, v); headers[key] = v; end + def delete_header(key); headers.delete key; end + + alias :[] :get_header + alias :[]= :set_header + + module Helpers + def invalid?; status < 100 || status >= 600; end + + def informational?; status >= 100 && status < 200; end + def successful?; status >= 200 && status < 300; end + def redirection?; status >= 300 && status < 400; end + def client_error?; status >= 400 && status < 500; end + def server_error?; status >= 500 && status < 600; end + + def ok?; status == 200; end + def created?; status == 201; end + def accepted?; status == 202; end + def no_content?; status == 204; end + def moved_permanently?; status == 301; end + def bad_request?; status == 400; end + def unauthorized?; status == 401; end + def forbidden?; status == 403; end + def not_found?; status == 404; end + def method_not_allowed?; status == 405; end + def precondition_failed?; status == 412; end + def unprocessable?; status == 422; end + + def redirect?; [301, 302, 303, 307, 308].include? status; end + + def include?(header) + has_header? header + end + + # Add a header that may have multiple values. + # + # Example: + # response.add_header 'Vary', 'Accept-Encoding' + # response.add_header 'Vary', 'Cookie' + # + # assert_equal 'Accept-Encoding,Cookie', response.get_header('Vary') + # + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 + def add_header(key, v) + if v.nil? + get_header key + elsif has_header? key + set_header key, "#{get_header key},#{v}" + else + set_header key, v + end + end + + # Get the content type of the response. + def content_type + get_header CONTENT_TYPE + end + + # Set the content type of the response. + def content_type=(content_type) + set_header CONTENT_TYPE, content_type + end + + def media_type + MediaType.type(content_type) + end + + def media_type_params + MediaType.params(content_type) + end + + def content_length + cl = get_header CONTENT_LENGTH + cl ? cl.to_i : cl + end + + def location + get_header "Location" + end + + def location=(location) + set_header "Location", location + end + + def set_cookie(key, value) + cookie_header = get_header SET_COOKIE + set_header SET_COOKIE, ::Rack::Utils.add_cookie_to_header(cookie_header, key, value) + end + + def delete_cookie(key, value = {}) + set_header SET_COOKIE, ::Rack::Utils.add_remove_cookie_to_header(get_header(SET_COOKIE), key, value) + end + + def set_cookie_header + get_header SET_COOKIE + end + + def set_cookie_header=(v) + set_header SET_COOKIE, v + end + + def cache_control + get_header CACHE_CONTROL + end + + def cache_control=(v) + set_header CACHE_CONTROL, v + end + + # Specifies that the content shouldn't be cached. Overrides `cache!` if already called. + def do_not_cache! + set_header CACHE_CONTROL, "no-cache, must-revalidate" + set_header EXPIRES, Time.now.httpdate + end + + # Specify that the content should be cached. + # @param duration [Integer] The number of seconds until the cache expires. + # @option directive [String] The cache control directive, one of "public", "private", "no-cache" or "no-store". + def cache!(duration = 3600, directive: "public") + unless headers[CACHE_CONTROL] =~ /no-cache/ + set_header CACHE_CONTROL, "#{directive}, max-age=#{duration}" + set_header EXPIRES, (Time.now + duration).httpdate + end + end + + def etag + get_header ETAG + end + + def etag=(v) + set_header ETAG, v + end + + protected + + def buffered_body! + return if @buffered + + if @body.is_a?(Array) + # The user supplied body was an array: + @body = @body.compact + @body.each do |part| + @length += part.to_s.bytesize + end + else + # Turn the user supplied body into a buffered array: + body = @body + @body = Array.new + + body.each do |part| + @writer.call(part.to_s) + end + + body.close if body.respond_to?(:close) + end + + @buffered = true + end + + def append(chunk) + @body << chunk + + unless chunked? + @length += chunk.bytesize + set_header(CONTENT_LENGTH, @length.to_s) + end + + return chunk + end + end + + include Helpers + + class Raw + include Helpers + + attr_reader :headers + attr_accessor :status + + def initialize(status, headers) + @status = status + @headers = headers + end + + def has_header?(key); headers.key? key; end + def get_header(key); headers[key]; end + def set_header(key, v); headers[key] = v; end + def delete_header(key); headers.delete key; end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/rewindable_input.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/rewindable_input.rb new file mode 100644 index 0000000..91b9d1e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/rewindable_input.rb @@ -0,0 +1,94 @@ +# -*- encoding: binary -*- +# frozen_string_literal: true + +require 'tempfile' + +module Rack + # Class which can make any IO object rewindable, including non-rewindable ones. It does + # this by buffering the data into a tempfile, which is rewindable. + # + # rack.input is required to be rewindable, so if your input stream IO is non-rewindable + # by nature (e.g. a pipe or a socket) then you can wrap it in an object of this class + # to easily make it rewindable. + # + # Don't forget to call #close when you're done. This frees up temporary resources that + # RewindableInput uses, though it does *not* close the original IO object. + class RewindableInput + def initialize(io) + @io = io + @rewindable_io = nil + @unlinked = false + end + + def gets + make_rewindable unless @rewindable_io + @rewindable_io.gets + end + + def read(*args) + make_rewindable unless @rewindable_io + @rewindable_io.read(*args) + end + + def each(&block) + make_rewindable unless @rewindable_io + @rewindable_io.each(&block) + end + + def rewind + make_rewindable unless @rewindable_io + @rewindable_io.rewind + end + + # Closes this RewindableInput object without closing the originally + # wrapped IO object. Cleans up any temporary resources that this RewindableInput + # has created. + # + # This method may be called multiple times. It does nothing on subsequent calls. + def close + if @rewindable_io + if @unlinked + @rewindable_io.close + else + @rewindable_io.close! + end + @rewindable_io = nil + end + end + + private + + def make_rewindable + # Buffer all data into a tempfile. Since this tempfile is private to this + # RewindableInput object, we chmod it so that nobody else can read or write + # it. On POSIX filesystems we also unlink the file so that it doesn't + # even have a file entry on the filesystem anymore, though we can still + # access it because we have the file handle open. + @rewindable_io = Tempfile.new('RackRewindableInput') + @rewindable_io.chmod(0000) + @rewindable_io.set_encoding(Encoding::BINARY) if @rewindable_io.respond_to?(:set_encoding) + @rewindable_io.binmode + if filesystem_has_posix_semantics? + raise 'Unlink failed. IO closed.' if @rewindable_io.closed? + @unlinked = true + end + + buffer = "".dup + while @io.read(1024 * 4, buffer) + entire_buffer_written_out = false + while !entire_buffer_written_out + written = @rewindable_io.write(buffer) + entire_buffer_written_out = written == buffer.bytesize + if !entire_buffer_written_out + buffer.slice!(0 .. written - 1) + end + end + end + @rewindable_io.rewind + end + + def filesystem_has_posix_semantics? + RUBY_PLATFORM !~ /(mswin|mingw|cygwin|java)/ + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/runtime.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/runtime.rb new file mode 100644 index 0000000..d9b2d8e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/runtime.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +module Rack + # Sets an "X-Runtime" response header, indicating the response + # time of the request, in seconds + # + # You can put it right before the application to see the processing + # time, or before all the other middlewares to include time for them, + # too. + class Runtime + FORMAT_STRING = "%0.6f" # :nodoc: + HEADER_NAME = "X-Runtime" # :nodoc: + + def initialize(app, name = nil) + @app = app + @header_name = HEADER_NAME + @header_name += "-#{name}" if name + end + + def call(env) + start_time = Utils.clock_time + status, headers, body = @app.call(env) + headers = Utils::HeaderHash[headers] + + request_time = Utils.clock_time - start_time + + unless headers.key?(@header_name) + headers[@header_name] = FORMAT_STRING % request_time + end + + [status, headers, body] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/sendfile.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/sendfile.rb new file mode 100644 index 0000000..3d5e786 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/sendfile.rb @@ -0,0 +1,162 @@ +# frozen_string_literal: true + +module Rack + + # = Sendfile + # + # The Sendfile middleware intercepts responses whose body is being + # served from a file and replaces it with a server specific X-Sendfile + # header. The web server is then responsible for writing the file contents + # to the client. This can dramatically reduce the amount of work required + # by the Ruby backend and takes advantage of the web server's optimized file + # delivery code. + # + # In order to take advantage of this middleware, the response body must + # respond to +to_path+ and the request must include an X-Sendfile-Type + # header. Rack::Files and other components implement +to_path+ so there's + # rarely anything you need to do in your application. The X-Sendfile-Type + # header is typically set in your web servers configuration. The following + # sections attempt to document + # + # === Nginx + # + # Nginx supports the X-Accel-Redirect header. This is similar to X-Sendfile + # but requires parts of the filesystem to be mapped into a private URL + # hierarchy. + # + # The following example shows the Nginx configuration required to create + # a private "/files/" area, enable X-Accel-Redirect, and pass the special + # X-Sendfile-Type and X-Accel-Mapping headers to the backend: + # + # location ~ /files/(.*) { + # internal; + # alias /var/www/$1; + # } + # + # location / { + # proxy_redirect off; + # + # proxy_set_header Host $host; + # proxy_set_header X-Real-IP $remote_addr; + # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + # + # proxy_set_header X-Sendfile-Type X-Accel-Redirect; + # proxy_set_header X-Accel-Mapping /var/www/=/files/; + # + # proxy_pass http://127.0.0.1:8080/; + # } + # + # Note that the X-Sendfile-Type header must be set exactly as shown above. + # The X-Accel-Mapping header should specify the location on the file system, + # followed by an equals sign (=), followed name of the private URL pattern + # that it maps to. The middleware performs a simple substitution on the + # resulting path. + # + # See Also: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile + # + # === lighttpd + # + # Lighttpd has supported some variation of the X-Sendfile header for some + # time, although only recent version support X-Sendfile in a reverse proxy + # configuration. + # + # $HTTP["host"] == "example.com" { + # proxy-core.protocol = "http" + # proxy-core.balancer = "round-robin" + # proxy-core.backends = ( + # "127.0.0.1:8000", + # "127.0.0.1:8001", + # ... + # ) + # + # proxy-core.allow-x-sendfile = "enable" + # proxy-core.rewrite-request = ( + # "X-Sendfile-Type" => (".*" => "X-Sendfile") + # ) + # } + # + # See Also: http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModProxyCore + # + # === Apache + # + # X-Sendfile is supported under Apache 2.x using a separate module: + # + # https://tn123.org/mod_xsendfile/ + # + # Once the module is compiled and installed, you can enable it using + # XSendFile config directive: + # + # RequestHeader Set X-Sendfile-Type X-Sendfile + # ProxyPassReverse / http://localhost:8001/ + # XSendFile on + # + # === Mapping parameter + # + # The third parameter allows for an overriding extension of the + # X-Accel-Mapping header. Mappings should be provided in tuples of internal to + # external. The internal values may contain regular expression syntax, they + # will be matched with case indifference. + + class Sendfile + def initialize(app, variation = nil, mappings = []) + @app = app + @variation = variation + @mappings = mappings.map do |internal, external| + [/^#{internal}/i, external] + end + end + + def call(env) + status, headers, body = @app.call(env) + if body.respond_to?(:to_path) + case type = variation(env) + when 'X-Accel-Redirect' + path = ::File.expand_path(body.to_path) + if url = map_accel_path(env, path) + headers[CONTENT_LENGTH] = '0' + # '?' must be percent-encoded because it is not query string but a part of path + headers[type] = ::Rack::Utils.escape_path(url).gsub('?', '%3F') + obody = body + body = Rack::BodyProxy.new([]) do + obody.close if obody.respond_to?(:close) + end + else + env[RACK_ERRORS].puts "X-Accel-Mapping header missing" + end + when 'X-Sendfile', 'X-Lighttpd-Send-File' + path = ::File.expand_path(body.to_path) + headers[CONTENT_LENGTH] = '0' + headers[type] = path + obody = body + body = Rack::BodyProxy.new([]) do + obody.close if obody.respond_to?(:close) + end + when '', nil + else + env[RACK_ERRORS].puts "Unknown x-sendfile variation: '#{type}'.\n" + end + end + [status, headers, body] + end + + private + def variation(env) + @variation || + env['sendfile.type'] || + env['HTTP_X_SENDFILE_TYPE'] + end + + def map_accel_path(env, path) + if mapping = @mappings.find { |internal, _| internal =~ path } + path.sub(*mapping) + elsif mapping = env['HTTP_X_ACCEL_MAPPING'] + mapping.split(',').map(&:strip).each do |m| + internal, external = m.split('=', 2).map(&:strip) + new_path = path.sub(/^#{internal}/i, external) + return new_path unless path == new_path + end + path + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/server.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/server.rb new file mode 100644 index 0000000..c1f2f5c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/server.rb @@ -0,0 +1,466 @@ +# frozen_string_literal: true + +require 'optparse' +require 'fileutils' + +module Rack + + class Server + (require_relative 'core_ext/regexp'; using ::Rack::RegexpExtensions) if RUBY_VERSION < '2.4' + + class Options + def parse!(args) + options = {} + opt_parser = OptionParser.new("", 24, ' ') do |opts| + opts.banner = "Usage: rackup [ruby options] [rack options] [rackup config]" + + opts.separator "" + opts.separator "Ruby options:" + + lineno = 1 + opts.on("-e", "--eval LINE", "evaluate a LINE of code") { |line| + eval line, TOPLEVEL_BINDING, "-e", lineno + lineno += 1 + } + + opts.on("-d", "--debug", "set debugging flags (set $DEBUG to true)") { + options[:debug] = true + } + opts.on("-w", "--warn", "turn warnings on for your script") { + options[:warn] = true + } + opts.on("-q", "--quiet", "turn off logging") { + options[:quiet] = true + } + + opts.on("-I", "--include PATH", + "specify $LOAD_PATH (may be used more than once)") { |path| + (options[:include] ||= []).concat(path.split(":")) + } + + opts.on("-r", "--require LIBRARY", + "require the library, before executing your script") { |library| + (options[:require] ||= []) << library + } + + opts.separator "" + opts.separator "Rack options:" + opts.on("-b", "--builder BUILDER_LINE", "evaluate a BUILDER_LINE of code as a builder script") { |line| + options[:builder] = line + } + + opts.on("-s", "--server SERVER", "serve using SERVER (thin/puma/webrick)") { |s| + options[:server] = s + } + + opts.on("-o", "--host HOST", "listen on HOST (default: localhost)") { |host| + options[:Host] = host + } + + opts.on("-p", "--port PORT", "use PORT (default: 9292)") { |port| + options[:Port] = port + } + + opts.on("-O", "--option NAME[=VALUE]", "pass VALUE to the server as option NAME. If no VALUE, sets it to true. Run '#{$0} -s SERVER -h' to get a list of options for SERVER") { |name| + name, value = name.split('=', 2) + value = true if value.nil? + options[name.to_sym] = value + } + + opts.on("-E", "--env ENVIRONMENT", "use ENVIRONMENT for defaults (default: development)") { |e| + options[:environment] = e + } + + opts.on("-D", "--daemonize", "run daemonized in the background") { |d| + options[:daemonize] = d ? true : false + } + + opts.on("-P", "--pid FILE", "file to store PID") { |f| + options[:pid] = ::File.expand_path(f) + } + + opts.separator "" + opts.separator "Profiling options:" + + opts.on("--heap HEAPFILE", "Build the application, then dump the heap to HEAPFILE") do |e| + options[:heapfile] = e + end + + opts.on("--profile PROFILE", "Dump CPU or Memory profile to PROFILE (defaults to a tempfile)") do |e| + options[:profile_file] = e + end + + opts.on("--profile-mode MODE", "Profile mode (cpu|wall|object)") do |e| + { cpu: true, wall: true, object: true }.fetch(e.to_sym) do + raise OptionParser::InvalidOption, "unknown profile mode: #{e}" + end + options[:profile_mode] = e.to_sym + end + + opts.separator "" + opts.separator "Common options:" + + opts.on_tail("-h", "-?", "--help", "Show this message") do + puts opts + puts handler_opts(options) + + exit + end + + opts.on_tail("--version", "Show version") do + puts "Rack #{Rack.version} (Release: #{Rack.release})" + exit + end + end + + begin + opt_parser.parse! args + rescue OptionParser::InvalidOption => e + warn e.message + abort opt_parser.to_s + end + + options[:config] = args.last if args.last && !args.last.empty? + options + end + + def handler_opts(options) + begin + info = [] + server = Rack::Handler.get(options[:server]) || Rack::Handler.default + if server && server.respond_to?(:valid_options) + info << "" + info << "Server-specific options for #{server.name}:" + + has_options = false + server.valid_options.each do |name, description| + next if /^(Host|Port)[^a-zA-Z]/.match?(name.to_s) # ignore handler's host and port options, we do our own. + info << " -O %-21s %s" % [name, description] + has_options = true + end + return "" if !has_options + end + info.join("\n") + rescue NameError, LoadError + return "Warning: Could not find handler specified (#{options[:server] || 'default'}) to determine handler-specific options" + end + end + end + + # Start a new rack server (like running rackup). This will parse ARGV and + # provide standard ARGV rackup options, defaulting to load 'config.ru'. + # + # Providing an options hash will prevent ARGV parsing and will not include + # any default options. + # + # This method can be used to very easily launch a CGI application, for + # example: + # + # Rack::Server.start( + # :app => lambda do |e| + # [200, {'Content-Type' => 'text/html'}, ['hello world']] + # end, + # :server => 'cgi' + # ) + # + # Further options available here are documented on Rack::Server#initialize + def self.start(options = nil) + new(options).start + end + + attr_writer :options + + # Options may include: + # * :app + # a rack application to run (overrides :config and :builder) + # * :builder + # a string to evaluate a Rack::Builder from + # * :config + # a rackup configuration file path to load (.ru) + # * :environment + # this selects the middleware that will be wrapped around + # your application. Default options available are: + # - development: CommonLogger, ShowExceptions, and Lint + # - deployment: CommonLogger + # - none: no extra middleware + # note: when the server is a cgi server, CommonLogger is not included. + # * :server + # choose a specific Rack::Handler, e.g. cgi, fcgi, webrick + # * :daemonize + # if true, the server will daemonize itself (fork, detach, etc) + # * :pid + # path to write a pid file after daemonize + # * :Host + # the host address to bind to (used by supporting Rack::Handler) + # * :Port + # the port to bind to (used by supporting Rack::Handler) + # * :AccessLog + # webrick access log options (or supporting Rack::Handler) + # * :debug + # turn on debug output ($DEBUG = true) + # * :warn + # turn on warnings ($-w = true) + # * :include + # add given paths to $LOAD_PATH + # * :require + # require the given libraries + # + # Additional options for profiling app initialization include: + # * :heapfile + # location for ObjectSpace.dump_all to write the output to + # * :profile_file + # location for CPU/Memory (StackProf) profile output (defaults to a tempfile) + # * :profile_mode + # StackProf profile mode (cpu|wall|object) + def initialize(options = nil) + @ignore_options = [] + + if options + @use_default_options = false + @options = options + @app = options[:app] if options[:app] + else + argv = defined?(SPEC_ARGV) ? SPEC_ARGV : ARGV + @use_default_options = true + @options = parse_options(argv) + end + end + + def options + merged_options = @use_default_options ? default_options.merge(@options) : @options + merged_options.reject { |k, v| @ignore_options.include?(k) } + end + + def default_options + environment = ENV['RACK_ENV'] || 'development' + default_host = environment == 'development' ? 'localhost' : '0.0.0.0' + + { + environment: environment, + pid: nil, + Port: 9292, + Host: default_host, + AccessLog: [], + config: "config.ru" + } + end + + def app + @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config + end + + class << self + def logging_middleware + lambda { |server| + /CGI/.match?(server.server.name) || server.options[:quiet] ? nil : [Rack::CommonLogger, $stderr] + } + end + + def default_middleware_by_environment + m = Hash.new {|h, k| h[k] = []} + m["deployment"] = [ + [Rack::ContentLength], + logging_middleware, + [Rack::TempfileReaper] + ] + m["development"] = [ + [Rack::ContentLength], + logging_middleware, + [Rack::ShowExceptions], + [Rack::Lint], + [Rack::TempfileReaper] + ] + + m + end + + def middleware + default_middleware_by_environment + end + end + + def middleware + self.class.middleware + end + + def start(&block) + if options[:warn] + $-w = true + end + + if includes = options[:include] + $LOAD_PATH.unshift(*includes) + end + + Array(options[:require]).each do |library| + require library + end + + if options[:debug] + $DEBUG = true + require 'pp' + p options[:server] + pp wrapped_app + pp app + end + + check_pid! if options[:pid] + + # Touch the wrapped app, so that the config.ru is loaded before + # daemonization (i.e. before chdir, etc). + handle_profiling(options[:heapfile], options[:profile_mode], options[:profile_file]) do + wrapped_app + end + + daemonize_app if options[:daemonize] + + write_pid if options[:pid] + + trap(:INT) do + if server.respond_to?(:shutdown) + server.shutdown + else + exit + end + end + + server.run(wrapped_app, **options, &block) + end + + def server + @_server ||= Rack::Handler.get(options[:server]) + + unless @_server + @_server = Rack::Handler.default + + # We already speak FastCGI + @ignore_options = [:File, :Port] if @_server.to_s == 'Rack::Handler::FastCGI' + end + + @_server + end + + private + def build_app_and_options_from_config + if !::File.exist? options[:config] + abort "configuration #{options[:config]} not found" + end + + app, options = Rack::Builder.parse_file(self.options[:config], opt_parser) + @options.merge!(options) { |key, old, new| old } + app + end + + def handle_profiling(heapfile, profile_mode, filename) + if heapfile + require "objspace" + ObjectSpace.trace_object_allocations_start + yield + GC.start + ::File.open(heapfile, "w") { |f| ObjectSpace.dump_all(output: f) } + exit + end + + if profile_mode + require "stackprof" + require "tempfile" + + make_profile_name(filename) do |filename| + ::File.open(filename, "w") do |f| + StackProf.run(mode: profile_mode, out: f) do + yield + end + puts "Profile written to: #{filename}" + end + end + exit + end + + yield + end + + def make_profile_name(filename) + if filename + yield filename + else + ::Dir::Tmpname.create("profile.dump") do |tmpname, _, _| + yield tmpname + end + end + end + + def build_app_from_string + Rack::Builder.new_from_string(self.options[:builder]) + end + + def parse_options(args) + # Don't evaluate CGI ISINDEX parameters. + # http://www.meb.uni-bonn.de/docs/cgi/cl.html + args.clear if ENV.include?(REQUEST_METHOD) + + @options = opt_parser.parse!(args) + @options[:config] = ::File.expand_path(options[:config]) + ENV["RACK_ENV"] = options[:environment] + @options + end + + def opt_parser + Options.new + end + + def build_app(app) + middleware[options[:environment]].reverse_each do |middleware| + middleware = middleware.call(self) if middleware.respond_to?(:call) + next unless middleware + klass, *args = middleware + app = klass.new(app, *args) + end + app + end + + def wrapped_app + @wrapped_app ||= build_app app + end + + def daemonize_app + # Cannot be covered as it forks + # :nocov: + Process.daemon + # :nocov: + end + + def write_pid + ::File.open(options[:pid], ::File::CREAT | ::File::EXCL | ::File::WRONLY ){ |f| f.write("#{Process.pid}") } + at_exit { ::FileUtils.rm_f(options[:pid]) } + rescue Errno::EEXIST + check_pid! + retry + end + + def check_pid! + case pidfile_process_status + when :running, :not_owned + $stderr.puts "A server is already running. Check #{options[:pid]}." + exit(1) + when :dead + ::File.delete(options[:pid]) + end + end + + def pidfile_process_status + return :exited unless ::File.exist?(options[:pid]) + + pid = ::File.read(options[:pid]).to_i + return :dead if pid == 0 + + Process.kill(0, pid) + :running + rescue Errno::ESRCH + :dead + rescue Errno::EPERM + :not_owned + end + + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/abstract/id.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/abstract/id.rb new file mode 100644 index 0000000..638bd3b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/abstract/id.rb @@ -0,0 +1,523 @@ +# frozen_string_literal: true + +# AUTHOR: blink ; blink#ruby-lang@irc.freenode.net +# bugrep: Andreas Zehnder + +require_relative '../../../rack' +require 'time' +require 'securerandom' +require 'digest/sha2' + +module Rack + + module Session + + class SessionId + ID_VERSION = 2 + + attr_reader :public_id + + def initialize(public_id) + @public_id = public_id + end + + def private_id + "#{ID_VERSION}::#{hash_sid(public_id)}" + end + + alias :cookie_value :public_id + alias :to_s :public_id + + def empty?; false; end + def inspect; public_id.inspect; end + + private + + def hash_sid(sid) + Digest::SHA256.hexdigest(sid) + end + end + + module Abstract + # SessionHash is responsible to lazily load the session from store. + + class SessionHash + include Enumerable + attr_writer :id + + Unspecified = Object.new + + def self.find(req) + req.get_header RACK_SESSION + end + + def self.set(req, session) + req.set_header RACK_SESSION, session + end + + def self.set_options(req, options) + req.set_header RACK_SESSION_OPTIONS, options.dup + end + + def initialize(store, req) + @store = store + @req = req + @loaded = false + end + + def id + return @id if @loaded or instance_variable_defined?(:@id) + @id = @store.send(:extract_session_id, @req) + end + + def options + @req.session_options + end + + def each(&block) + load_for_read! + @data.each(&block) + end + + def [](key) + load_for_read! + @data[key.to_s] + end + + def dig(key, *keys) + load_for_read! + @data.dig(key.to_s, *keys) + end + + def fetch(key, default = Unspecified, &block) + load_for_read! + if default == Unspecified + @data.fetch(key.to_s, &block) + else + @data.fetch(key.to_s, default, &block) + end + end + + def has_key?(key) + load_for_read! + @data.has_key?(key.to_s) + end + alias :key? :has_key? + alias :include? :has_key? + + def []=(key, value) + load_for_write! + @data[key.to_s] = value + end + alias :store :[]= + + def clear + load_for_write! + @data.clear + end + + def destroy + clear + @id = @store.send(:delete_session, @req, id, options) + end + + def to_hash + load_for_read! + @data.dup + end + + def update(hash) + load_for_write! + @data.update(stringify_keys(hash)) + end + alias :merge! :update + + def replace(hash) + load_for_write! + @data.replace(stringify_keys(hash)) + end + + def delete(key) + load_for_write! + @data.delete(key.to_s) + end + + def inspect + if loaded? + @data.inspect + else + "#<#{self.class}:0x#{self.object_id.to_s(16)} not yet loaded>" + end + end + + def exists? + return @exists if instance_variable_defined?(:@exists) + @data = {} + @exists = @store.send(:session_exists?, @req) + end + + def loaded? + @loaded + end + + def empty? + load_for_read! + @data.empty? + end + + def keys + load_for_read! + @data.keys + end + + def values + load_for_read! + @data.values + end + + private + + def load_for_read! + load! if !loaded? && exists? + end + + def load_for_write! + load! unless loaded? + end + + def load! + @id, session = @store.send(:load_session, @req) + @data = stringify_keys(session) + @loaded = true + end + + def stringify_keys(other) + # Use transform_keys after dropping Ruby 2.4 support + hash = {} + other.to_hash.each do |key, value| + hash[key.to_s] = value + end + hash + end + end + + # ID sets up a basic framework for implementing an id based sessioning + # service. Cookies sent to the client for maintaining sessions will only + # contain an id reference. Only #find_session, #write_session and + # #delete_session are required to be overwritten. + # + # All parameters are optional. + # * :key determines the name of the cookie, by default it is + # 'rack.session' + # * :path, :domain, :expire_after, :secure, and :httponly set the related + # cookie options as by Rack::Response#set_cookie + # * :skip will not a set a cookie in the response nor update the session state + # * :defer will not set a cookie in the response but still update the session + # state if it is used with a backend + # * :renew (implementation dependent) will prompt the generation of a new + # session id, and migration of data to be referenced at the new id. If + # :defer is set, it will be overridden and the cookie will be set. + # * :sidbits sets the number of bits in length that a generated session + # id will be. + # + # These options can be set on a per request basis, at the location of + # env['rack.session.options']. Additionally the id of the + # session can be found within the options hash at the key :id. It is + # highly not recommended to change its value. + # + # Is Rack::Utils::Context compatible. + # + # Not included by default; you must require 'rack/session/abstract/id' + # to use. + + class Persisted + DEFAULT_OPTIONS = { + key: RACK_SESSION, + path: '/', + domain: nil, + expire_after: nil, + secure: false, + httponly: true, + defer: false, + renew: false, + sidbits: 128, + cookie_only: true, + secure_random: ::SecureRandom + }.freeze + + attr_reader :key, :default_options, :sid_secure + + def initialize(app, options = {}) + @app = app + @default_options = self.class::DEFAULT_OPTIONS.merge(options) + @key = @default_options.delete(:key) + @cookie_only = @default_options.delete(:cookie_only) + @same_site = @default_options.delete(:same_site) + initialize_sid + end + + def call(env) + context(env) + end + + def context(env, app = @app) + req = make_request env + prepare_session(req) + status, headers, body = app.call(req.env) + res = Rack::Response::Raw.new status, headers + commit_session(req, res) + [status, headers, body] + end + + private + + def make_request(env) + Rack::Request.new env + end + + def initialize_sid + @sidbits = @default_options[:sidbits] + @sid_secure = @default_options[:secure_random] + @sid_length = @sidbits / 4 + end + + # Generate a new session id using Ruby #rand. The size of the + # session id is controlled by the :sidbits option. + # Monkey patch this to use custom methods for session id generation. + + def generate_sid(secure = @sid_secure) + if secure + secure.hex(@sid_length) + else + "%0#{@sid_length}x" % Kernel.rand(2**@sidbits - 1) + end + rescue NotImplementedError + generate_sid(false) + end + + # Sets the lazy session at 'rack.session' and places options and session + # metadata into 'rack.session.options'. + + def prepare_session(req) + session_was = req.get_header RACK_SESSION + session = session_class.new(self, req) + req.set_header RACK_SESSION, session + req.set_header RACK_SESSION_OPTIONS, @default_options.dup + session.merge! session_was if session_was + end + + # Extracts the session id from provided cookies and passes it and the + # environment to #find_session. + + def load_session(req) + sid = current_session_id(req) + sid, session = find_session(req, sid) + [sid, session || {}] + end + + # Extract session id from request object. + + def extract_session_id(request) + sid = request.cookies[@key] + sid ||= request.params[@key] unless @cookie_only + sid + end + + # Returns the current session id from the SessionHash. + + def current_session_id(req) + req.get_header(RACK_SESSION).id + end + + # Check if the session exists or not. + + def session_exists?(req) + value = current_session_id(req) + value && !value.empty? + end + + # Session should be committed if it was loaded, any of specific options like :renew, :drop + # or :expire_after was given and the security permissions match. Skips if skip is given. + + def commit_session?(req, session, options) + if options[:skip] + false + else + has_session = loaded_session?(session) || forced_session_update?(session, options) + has_session && security_matches?(req, options) + end + end + + def loaded_session?(session) + !session.is_a?(session_class) || session.loaded? + end + + def forced_session_update?(session, options) + force_options?(options) && session && !session.empty? + end + + def force_options?(options) + options.values_at(:max_age, :renew, :drop, :defer, :expire_after).any? + end + + def security_matches?(request, options) + return true unless options[:secure] + request.ssl? + end + + # Acquires the session from the environment and the session id from + # the session options and passes them to #write_session. If successful + # and the :defer option is not true, a cookie will be added to the + # response with the session's id. + + def commit_session(req, res) + session = req.get_header RACK_SESSION + options = session.options + + if options[:drop] || options[:renew] + session_id = delete_session(req, session.id || generate_sid, options) + return unless session_id + end + + return unless commit_session?(req, session, options) + + session.send(:load!) unless loaded_session?(session) + session_id ||= session.id + session_data = session.to_hash.delete_if { |k, v| v.nil? } + + if not data = write_session(req, session_id, session_data, options) + req.get_header(RACK_ERRORS).puts("Warning! #{self.class.name} failed to save session. Content dropped.") + elsif options[:defer] and not options[:renew] + req.get_header(RACK_ERRORS).puts("Deferring cookie for #{session_id}") if $VERBOSE + else + cookie = Hash.new + cookie[:value] = cookie_value(data) + cookie[:expires] = Time.now + options[:expire_after] if options[:expire_after] + cookie[:expires] = Time.now + options[:max_age] if options[:max_age] + + if @same_site.respond_to? :call + cookie[:same_site] = @same_site.call(req, res) + else + cookie[:same_site] = @same_site + end + set_cookie(req, res, cookie.merge!(options)) + end + end + public :commit_session + + def cookie_value(data) + data + end + + # Sets the cookie back to the client with session id. We skip the cookie + # setting if the value didn't change (sid is the same) or expires was given. + + def set_cookie(request, res, cookie) + if request.cookies[@key] != cookie[:value] || cookie[:expires] + res.set_cookie_header = + Utils.add_cookie_to_header(res.set_cookie_header, @key, cookie) + end + end + + # Allow subclasses to prepare_session for different Session classes + + def session_class + SessionHash + end + + # All thread safety and session retrieval procedures should occur here. + # Should return [session_id, session]. + # If nil is provided as the session id, generation of a new valid id + # should occur within. + + def find_session(env, sid) + raise '#find_session not implemented.' + end + + # All thread safety and session storage procedures should occur here. + # Must return the session id if the session was saved successfully, or + # false if the session could not be saved. + + def write_session(req, sid, session, options) + raise '#write_session not implemented.' + end + + # All thread safety and session destroy procedures should occur here. + # Should return a new session id or nil if options[:drop] + + def delete_session(req, sid, options) + raise '#delete_session not implemented' + end + end + + class PersistedSecure < Persisted + class SecureSessionHash < SessionHash + def [](key) + if key == "session_id" + load_for_read! + id.public_id if id + else + super + end + end + end + + def generate_sid(*) + public_id = super + + SessionId.new(public_id) + end + + def extract_session_id(*) + public_id = super + public_id && SessionId.new(public_id) + end + + private + + def session_class + SecureSessionHash + end + + def cookie_value(data) + data.cookie_value + end + end + + class ID < Persisted + def self.inherited(klass) + k = klass.ancestors.find { |kl| kl.respond_to?(:superclass) && kl.superclass == ID } + unless k.instance_variable_defined?(:"@_rack_warned") + warn "#{klass} is inheriting from #{ID}. Inheriting from #{ID} is deprecated, please inherit from #{Persisted} instead" if $VERBOSE + k.instance_variable_set(:"@_rack_warned", true) + end + super + end + + # All thread safety and session retrieval procedures should occur here. + # Should return [session_id, session]. + # If nil is provided as the session id, generation of a new valid id + # should occur within. + + def find_session(req, sid) + get_session req.env, sid + end + + # All thread safety and session storage procedures should occur here. + # Must return the session id if the session was saved successfully, or + # false if the session could not be saved. + + def write_session(req, sid, session, options) + set_session req.env, sid, session, options + end + + # All thread safety and session destroy procedures should occur here. + # Should return a new session id or nil if options[:drop] + + def delete_session(req, sid, options) + destroy_session req.env, sid, options + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/cookie.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/cookie.rb new file mode 100644 index 0000000..bb54139 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/cookie.rb @@ -0,0 +1,203 @@ +# frozen_string_literal: true + +require 'openssl' +require 'zlib' +require_relative 'abstract/id' +require 'json' +require 'base64' + +module Rack + + module Session + + # Rack::Session::Cookie provides simple cookie based session management. + # By default, the session is a Ruby Hash stored as base64 encoded marshalled + # data set to :key (default: rack.session). The object that encodes the + # session data is configurable and must respond to +encode+ and +decode+. + # Both methods must take a string and return a string. + # + # When the secret key is set, cookie data is checked for data integrity. + # The old secret key is also accepted and allows graceful secret rotation. + # + # Example: + # + # use Rack::Session::Cookie, :key => 'rack.session', + # :domain => 'foo.com', + # :path => '/', + # :expire_after => 2592000, + # :secret => 'change_me', + # :old_secret => 'also_change_me' + # + # All parameters are optional. + # + # Example of a cookie with no encoding: + # + # Rack::Session::Cookie.new(application, { + # :coder => Rack::Session::Cookie::Identity.new + # }) + # + # Example of a cookie with custom encoding: + # + # Rack::Session::Cookie.new(application, { + # :coder => Class.new { + # def encode(str); str.reverse; end + # def decode(str); str.reverse; end + # }.new + # }) + # + + class Cookie < Abstract::PersistedSecure + # Encode session cookies as Base64 + class Base64 + def encode(str) + ::Base64.strict_encode64(str) + end + + def decode(str) + ::Base64.decode64(str) + end + + # Encode session cookies as Marshaled Base64 data + class Marshal < Base64 + def encode(str) + super(::Marshal.dump(str)) + end + + def decode(str) + return unless str + ::Marshal.load(super(str)) rescue nil + end + end + + # N.B. Unlike other encoding methods, the contained objects must be a + # valid JSON composite type, either a Hash or an Array. + class JSON < Base64 + def encode(obj) + super(::JSON.dump(obj)) + end + + def decode(str) + return unless str + ::JSON.parse(super(str)) rescue nil + end + end + + class ZipJSON < Base64 + def encode(obj) + super(Zlib::Deflate.deflate(::JSON.dump(obj))) + end + + def decode(str) + return unless str + ::JSON.parse(Zlib::Inflate.inflate(super(str))) + rescue + nil + end + end + end + + # Use no encoding for session cookies + class Identity + def encode(str); str; end + def decode(str); str; end + end + + attr_reader :coder + + def initialize(app, options = {}) + @secrets = options.values_at(:secret, :old_secret).compact + @hmac = options.fetch(:hmac, OpenSSL::Digest::SHA1) + + warn <<-MSG unless secure?(options) + SECURITY WARNING: No secret option provided to Rack::Session::Cookie. + This poses a security threat. It is strongly recommended that you + provide a secret to prevent exploits that may be possible from crafted + cookies. This will not be supported in future versions of Rack, and + future versions will even invalidate your existing user cookies. + + Called from: #{caller[0]}. + MSG + @coder = options[:coder] ||= Base64::Marshal.new + super(app, options.merge!(cookie_only: true)) + end + + private + + def find_session(req, sid) + data = unpacked_cookie_data(req) + data = persistent_session_id!(data) + [data["session_id"], data] + end + + def extract_session_id(request) + unpacked_cookie_data(request)["session_id"] + end + + def unpacked_cookie_data(request) + request.fetch_header(RACK_SESSION_UNPACKED_COOKIE_DATA) do |k| + session_data = request.cookies[@key] + + if @secrets.size > 0 && session_data + session_data, _, digest = session_data.rpartition('--') + session_data = nil unless digest_match?(session_data, digest) + end + + request.set_header(k, coder.decode(session_data) || {}) + end + end + + def persistent_session_id!(data, sid = nil) + data ||= {} + data["session_id"] ||= sid || generate_sid + data + end + + class SessionId < DelegateClass(Session::SessionId) + attr_reader :cookie_value + + def initialize(session_id, cookie_value) + super(session_id) + @cookie_value = cookie_value + end + end + + def write_session(req, session_id, session, options) + session = session.merge("session_id" => session_id) + session_data = coder.encode(session) + + if @secrets.first + session_data << "--#{generate_hmac(session_data, @secrets.first)}" + end + + if session_data.size > (4096 - @key.size) + req.get_header(RACK_ERRORS).puts("Warning! Rack::Session::Cookie data size exceeds 4K.") + nil + else + SessionId.new(session_id, session_data) + end + end + + def delete_session(req, session_id, options) + # Nothing to do here, data is in the client + generate_sid unless options[:drop] + end + + def digest_match?(data, digest) + return unless data && digest + @secrets.any? do |secret| + Rack::Utils.secure_compare(digest, generate_hmac(data, secret)) + end + end + + def generate_hmac(data, secret) + OpenSSL::HMAC.hexdigest(@hmac.new, secret, data) + end + + def secure?(options) + @secrets.size >= 1 || + (options[:coder] && options[:let_coder_handle_secure_encoding]) + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/memcache.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/memcache.rb new file mode 100644 index 0000000..6a60117 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/memcache.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require 'rack/session/dalli' + +module Rack + module Session + warn "Rack::Session::Memcache is deprecated, please use Rack::Session::Dalli from 'dalli' gem instead." + Memcache = Dalli + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/pool.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/pool.rb new file mode 100644 index 0000000..4885605 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/session/pool.rb @@ -0,0 +1,85 @@ +# frozen_string_literal: true + +# AUTHOR: blink ; blink#ruby-lang@irc.freenode.net +# THANKS: +# apeiros, for session id generation, expiry setup, and threadiness +# sergio, threadiness and bugreps + +require_relative 'abstract/id' +require 'thread' + +module Rack + module Session + # Rack::Session::Pool provides simple cookie based session management. + # Session data is stored in a hash held by @pool. + # In the context of a multithreaded environment, sessions being + # committed to the pool is done in a merging manner. + # + # The :drop option is available in rack.session.options if you wish to + # explicitly remove the session from the session cache. + # + # Example: + # myapp = MyRackApp.new + # sessioned = Rack::Session::Pool.new(myapp, + # :domain => 'foo.com', + # :expire_after => 2592000 + # ) + # Rack::Handler::WEBrick.run sessioned + + class Pool < Abstract::PersistedSecure + attr_reader :mutex, :pool + DEFAULT_OPTIONS = Abstract::ID::DEFAULT_OPTIONS.merge drop: false + + def initialize(app, options = {}) + super + @pool = Hash.new + @mutex = Mutex.new + end + + def generate_sid + loop do + sid = super + break sid unless @pool.key? sid.private_id + end + end + + def find_session(req, sid) + with_lock(req) do + unless sid and session = get_session_with_fallback(sid) + sid, session = generate_sid, {} + @pool.store sid.private_id, session + end + [sid, session] + end + end + + def write_session(req, session_id, new_session, options) + with_lock(req) do + @pool.store session_id.private_id, new_session + session_id + end + end + + def delete_session(req, session_id, options) + with_lock(req) do + @pool.delete(session_id.public_id) + @pool.delete(session_id.private_id) + generate_sid unless options[:drop] + end + end + + def with_lock(req) + @mutex.lock if req.multithread? + yield + ensure + @mutex.unlock if @mutex.locked? + end + + private + + def get_session_with_fallback(sid) + @pool[sid.private_id] || @pool[sid.public_id] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/show_exceptions.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/show_exceptions.rb new file mode 100644 index 0000000..07e6038 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/show_exceptions.rb @@ -0,0 +1,390 @@ +# frozen_string_literal: true + +require 'ostruct' +require 'erb' + +module Rack + # Rack::ShowExceptions catches all exceptions raised from the app it + # wraps. It shows a useful backtrace with the sourcefile and + # clickable context, the whole Rack environment and the request + # data. + # + # Be careful when you use this on public-facing sites as it could + # reveal information helpful to attackers. + + class ShowExceptions + CONTEXT = 7 + + def initialize(app) + @app = app + end + + def call(env) + @app.call(env) + rescue StandardError, LoadError, SyntaxError => e + exception_string = dump_exception(e) + + env[RACK_ERRORS].puts(exception_string) + env[RACK_ERRORS].flush + + if accepts_html?(env) + content_type = "text/html" + body = pretty(env, e) + else + content_type = "text/plain" + body = exception_string + end + + [ + 500, + { + CONTENT_TYPE => content_type, + CONTENT_LENGTH => body.bytesize.to_s, + }, + [body], + ] + end + + def prefers_plaintext?(env) + !accepts_html?(env) + end + + def accepts_html?(env) + Rack::Utils.best_q_match(env["HTTP_ACCEPT"], %w[text/html]) + end + private :accepts_html? + + def dump_exception(exception) + string = "#{exception.class}: #{exception.message}\n".dup + string << exception.backtrace.map { |l| "\t#{l}" }.join("\n") + string + end + + def pretty(env, exception) + req = Rack::Request.new(env) + + # This double assignment is to prevent an "unused variable" warning. + # Yes, it is dumb, but I don't like Ruby yelling at me. + path = path = (req.script_name + req.path_info).squeeze("/") + + # This double assignment is to prevent an "unused variable" warning. + # Yes, it is dumb, but I don't like Ruby yelling at me. + frames = frames = exception.backtrace.map { |line| + frame = OpenStruct.new + if line =~ /(.*?):(\d+)(:in `(.*)')?/ + frame.filename = $1 + frame.lineno = $2.to_i + frame.function = $4 + + begin + lineno = frame.lineno - 1 + lines = ::File.readlines(frame.filename) + frame.pre_context_lineno = [lineno - CONTEXT, 0].max + frame.pre_context = lines[frame.pre_context_lineno...lineno] + frame.context_line = lines[lineno].chomp + frame.post_context_lineno = [lineno + CONTEXT, lines.size].min + frame.post_context = lines[lineno + 1..frame.post_context_lineno] + rescue + end + + frame + else + nil + end + }.compact + + template.result(binding) + end + + def template + TEMPLATE + end + + def h(obj) # :nodoc: + case obj + when String + Utils.escape_html(obj) + else + Utils.escape_html(obj.inspect) + end + end + + # :stopdoc: + + # adapted from Django + # Copyright (c) Django Software Foundation and individual contributors. + # Used under the modified BSD license: + # http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5 + TEMPLATE = ERB.new(<<-'HTML'.gsub(/^ /, '')) + + + + + + <%=h exception.class %> at <%=h path %> + + + + + +
+

<%=h exception.class %> at <%=h path %>

+

<%=h exception.message %>

+ + + + + + +
Ruby + <% if first = frames.first %> + <%=h first.filename %>: in <%=h first.function %>, line <%=h frames.first.lineno %> + <% else %> + unknown location + <% end %> +
Web<%=h req.request_method %> <%=h(req.host + path)%>
+ +

Jump to:

+ +
+ +
+

Traceback (innermost first)

+
    + <% frames.each { |frame| %> +
  • + <%=h frame.filename %>: in <%=h frame.function %> + + <% if frame.context_line %> +
    + <% if frame.pre_context %> +
      + <% frame.pre_context.each { |line| %> +
    1. <%=h line %>
    2. + <% } %> +
    + <% end %> + +
      +
    1. <%=h frame.context_line %>...
    + + <% if frame.post_context %> +
      + <% frame.post_context.each { |line| %> +
    1. <%=h line %>
    2. + <% } %> +
    + <% end %> +
    + <% end %> +
  • + <% } %> +
+
+ +
+

Request information

+ +

GET

+ <% if req.GET and not req.GET.empty? %> + + + + + + + + + <% req.GET.sort_by { |k, v| k.to_s }.each { |key, val| %> + + + + + <% } %> + +
VariableValue
<%=h key %>
<%=h val.inspect %>
+ <% else %> +

No GET data.

+ <% end %> + +

POST

+ <% if ((req.POST and not req.POST.empty?) rescue (no_post_data = "Invalid POST data"; nil)) %> + + + + + + + + + <% req.POST.sort_by { |k, v| k.to_s }.each { |key, val| %> + + + + + <% } %> + +
VariableValue
<%=h key %>
<%=h val.inspect %>
+ <% else %> +

<%= no_post_data || "No POST data" %>.

+ <% end %> + + + + <% unless req.cookies.empty? %> + + + + + + + + + <% req.cookies.each { |key, val| %> + + + + + <% } %> + +
VariableValue
<%=h key %>
<%=h val.inspect %>
+ <% else %> +

No cookie data.

+ <% end %> + +

Rack ENV

+ + + + + + + + + <% env.sort_by { |k, v| k.to_s }.each { |key, val| %> + + + + + <% } %> + +
VariableValue
<%=h key %>
<%=h val.inspect %>
+ +
+ +
+

+ You're seeing this error because you use Rack::ShowExceptions. +

+
+ + + + HTML + + # :startdoc: + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/show_status.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/show_status.rb new file mode 100644 index 0000000..a99bdaf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/show_status.rb @@ -0,0 +1,113 @@ +# frozen_string_literal: true + +require 'erb' + +module Rack + # Rack::ShowStatus catches all empty responses and replaces them + # with a site explaining the error. + # + # Additional details can be put into rack.showstatus.detail + # and will be shown as HTML. If such details exist, the error page + # is always rendered, even if the reply was not empty. + + class ShowStatus + def initialize(app) + @app = app + @template = ERB.new(TEMPLATE) + end + + def call(env) + status, headers, body = @app.call(env) + headers = Utils::HeaderHash[headers] + empty = headers[CONTENT_LENGTH].to_i <= 0 + + # client or server error, or explicit message + if (status.to_i >= 400 && empty) || env[RACK_SHOWSTATUS_DETAIL] + # This double assignment is to prevent an "unused variable" warning. + # Yes, it is dumb, but I don't like Ruby yelling at me. + req = req = Rack::Request.new(env) + + message = Rack::Utils::HTTP_STATUS_CODES[status.to_i] || status.to_s + + # This double assignment is to prevent an "unused variable" warning. + # Yes, it is dumb, but I don't like Ruby yelling at me. + detail = detail = env[RACK_SHOWSTATUS_DETAIL] || message + + body = @template.result(binding) + size = body.bytesize + [status, headers.merge(CONTENT_TYPE => "text/html", CONTENT_LENGTH => size.to_s), [body]] + else + [status, headers, body] + end + end + + def h(obj) # :nodoc: + case obj + when String + Utils.escape_html(obj) + else + Utils.escape_html(obj.inspect) + end + end + + # :stopdoc: + +# adapted from Django +# Copyright (c) Django Software Foundation and individual contributors. +# Used under the modified BSD license: +# http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5 +TEMPLATE = <<'HTML' + + + + + <%=h message %> at <%=h req.script_name + req.path_info %> + + + + +
+

<%=h message %> (<%= status.to_i %>)

+ + + + + + + + + +
Request Method:<%=h req.request_method %>
Request URL:<%=h req.url %>
+
+
+

<%=h detail %>

+
+ +
+

+ You're seeing this error because you use Rack::ShowStatus. +

+
+ + +HTML + + # :startdoc: + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/static.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/static.rb new file mode 100644 index 0000000..8cb58b2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/static.rb @@ -0,0 +1,187 @@ +# frozen_string_literal: true + +module Rack + + # The Rack::Static middleware intercepts requests for static files + # (javascript files, images, stylesheets, etc) based on the url prefixes or + # route mappings passed in the options, and serves them using a Rack::Files + # object. This allows a Rack stack to serve both static and dynamic content. + # + # Examples: + # + # Serve all requests beginning with /media from the "media" folder located + # in the current directory (ie media/*): + # + # use Rack::Static, :urls => ["/media"] + # + # Same as previous, but instead of returning 404 for missing files under + # /media, call the next middleware: + # + # use Rack::Static, :urls => ["/media"], :cascade => true + # + # Serve all requests beginning with /css or /images from the folder "public" + # in the current directory (ie public/css/* and public/images/*): + # + # use Rack::Static, :urls => ["/css", "/images"], :root => "public" + # + # Serve all requests to / with "index.html" from the folder "public" in the + # current directory (ie public/index.html): + # + # use Rack::Static, :urls => {"/" => 'index.html'}, :root => 'public' + # + # Serve all requests normally from the folder "public" in the current + # directory but uses index.html as default route for "/" + # + # use Rack::Static, :urls => [""], :root => 'public', :index => + # 'index.html' + # + # Set custom HTTP Headers for based on rules: + # + # use Rack::Static, :root => 'public', + # :header_rules => [ + # [rule, {header_field => content, header_field => content}], + # [rule, {header_field => content}] + # ] + # + # Rules for selecting files: + # + # 1) All files + # Provide the :all symbol + # :all => Matches every file + # + # 2) Folders + # Provide the folder path as a string + # '/folder' or '/folder/subfolder' => Matches files in a certain folder + # + # 3) File Extensions + # Provide the file extensions as an array + # ['css', 'js'] or %w(css js) => Matches files ending in .css or .js + # + # 4) Regular Expressions / Regexp + # Provide a regular expression + # %r{\.(?:css|js)\z} => Matches files ending in .css or .js + # /\.(?:eot|ttf|otf|woff2|woff|svg)\z/ => Matches files ending in + # the most common web font formats (.eot, .ttf, .otf, .woff2, .woff, .svg) + # Note: This Regexp is available as a shortcut, using the :fonts rule + # + # 5) Font Shortcut + # Provide the :fonts symbol + # :fonts => Uses the Regexp rule stated right above to match all common web font endings + # + # Rule Ordering: + # Rules are applied in the order that they are provided. + # List rather general rules above special ones. + # + # Complete example use case including HTTP header rules: + # + # use Rack::Static, :root => 'public', + # :header_rules => [ + # # Cache all static files in public caches (e.g. Rack::Cache) + # # as well as in the browser + # [:all, {'Cache-Control' => 'public, max-age=31536000'}], + # + # # Provide web fonts with cross-origin access-control-headers + # # Firefox requires this when serving assets using a Content Delivery Network + # [:fonts, {'Access-Control-Allow-Origin' => '*'}] + # ] + # + class Static + (require_relative 'core_ext/regexp'; using ::Rack::RegexpExtensions) if RUBY_VERSION < '2.4' + + def initialize(app, options = {}) + @app = app + @urls = options[:urls] || ["/favicon.ico"] + @index = options[:index] + @gzip = options[:gzip] + @cascade = options[:cascade] + root = options[:root] || Dir.pwd + + # HTTP Headers + @header_rules = options[:header_rules] || [] + # Allow for legacy :cache_control option while prioritizing global header_rules setting + @header_rules.unshift([:all, { CACHE_CONTROL => options[:cache_control] }]) if options[:cache_control] + + @file_server = Rack::Files.new(root) + end + + def add_index_root?(path) + @index && route_file(path) && path.end_with?('/') + end + + def overwrite_file_path(path) + @urls.kind_of?(Hash) && @urls.key?(path) || add_index_root?(path) + end + + def route_file(path) + @urls.kind_of?(Array) && @urls.any? { |url| path.index(url) == 0 } + end + + def can_serve(path) + route_file(path) || overwrite_file_path(path) + end + + def call(env) + path = env[PATH_INFO] + + if can_serve(path) + if overwrite_file_path(path) + env[PATH_INFO] = (add_index_root?(path) ? path + @index : @urls[path]) + elsif @gzip && env['HTTP_ACCEPT_ENCODING'] && /\bgzip\b/.match?(env['HTTP_ACCEPT_ENCODING']) + path = env[PATH_INFO] + env[PATH_INFO] += '.gz' + response = @file_server.call(env) + env[PATH_INFO] = path + + if response[0] == 404 + response = nil + elsif response[0] == 304 + # Do nothing, leave headers as is + else + if mime_type = Mime.mime_type(::File.extname(path), 'text/plain') + response[1][CONTENT_TYPE] = mime_type + end + response[1]['Content-Encoding'] = 'gzip' + end + end + + path = env[PATH_INFO] + response ||= @file_server.call(env) + + if @cascade && response[0] == 404 + return @app.call(env) + end + + headers = response[1] + applicable_rules(path).each do |rule, new_headers| + new_headers.each { |field, content| headers[field] = content } + end + + response + else + @app.call(env) + end + end + + # Convert HTTP header rules to HTTP headers + def applicable_rules(path) + @header_rules.find_all do |rule, new_headers| + case rule + when :all + true + when :fonts + /\.(?:ttf|otf|eot|woff2|woff|svg)\z/.match?(path) + when String + path = ::Rack::Utils.unescape(path) + path.start_with?(rule) || path.start_with?('/' + rule) + when Array + /\.(#{rule.join('|')})\z/.match?(path) + when Regexp + rule.match?(path) + else + false + end + end + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/tempfile_reaper.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/tempfile_reaper.rb new file mode 100644 index 0000000..9b04fef --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/tempfile_reaper.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +module Rack + + # Middleware tracks and cleans Tempfiles created throughout a request (i.e. Rack::Multipart) + # Ideas/strategy based on posts by Eric Wong and Charles Oliver Nutter + # https://groups.google.com/forum/#!searchin/rack-devel/temp/rack-devel/brK8eh-MByw/sw61oJJCGRMJ + class TempfileReaper + def initialize(app) + @app = app + end + + def call(env) + env[RACK_TEMPFILES] ||= [] + status, headers, body = @app.call(env) + body_proxy = BodyProxy.new(body) do + env[RACK_TEMPFILES].each(&:close!) unless env[RACK_TEMPFILES].nil? + end + [status, headers, body_proxy] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/urlmap.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/urlmap.rb new file mode 100644 index 0000000..31a642c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/urlmap.rb @@ -0,0 +1,97 @@ +# frozen_string_literal: true + +require 'set' + +module Rack + # Rack::URLMap takes a hash mapping urls or paths to apps, and + # dispatches accordingly. Support for HTTP/1.1 host names exists if + # the URLs start with http:// or https://. + # + # URLMap modifies the SCRIPT_NAME and PATH_INFO such that the part + # relevant for dispatch is in the SCRIPT_NAME, and the rest in the + # PATH_INFO. This should be taken care of when you need to + # reconstruct the URL in order to create links. + # + # URLMap dispatches in such a way that the longest paths are tried + # first, since they are most specific. + + class URLMap + def initialize(map = {}) + remap(map) + end + + def remap(map) + @known_hosts = Set[] + @mapping = map.map { |location, app| + if location =~ %r{\Ahttps?://(.*?)(/.*)} + host, location = $1, $2 + @known_hosts << host + else + host = nil + end + + unless location[0] == ?/ + raise ArgumentError, "paths need to start with /" + end + + location = location.chomp('/') + match = Regexp.new("^#{Regexp.quote(location).gsub('/', '/+')}(.*)", nil, 'n') + + [host, location, match, app] + }.sort_by do |(host, location, _, _)| + [host ? -host.size : Float::INFINITY, -location.size] + end + end + + def call(env) + path = env[PATH_INFO] + script_name = env[SCRIPT_NAME] + http_host = env[HTTP_HOST] + server_name = env[SERVER_NAME] + server_port = env[SERVER_PORT] + + is_same_server = casecmp?(http_host, server_name) || + casecmp?(http_host, "#{server_name}:#{server_port}") + + is_host_known = @known_hosts.include? http_host + + @mapping.each do |host, location, match, app| + unless casecmp?(http_host, host) \ + || casecmp?(server_name, host) \ + || (!host && is_same_server) \ + || (!host && !is_host_known) # If we don't have a matching host, default to the first without a specified host + next + end + + next unless m = match.match(path.to_s) + + rest = m[1] + next unless !rest || rest.empty? || rest[0] == ?/ + + env[SCRIPT_NAME] = (script_name + location) + env[PATH_INFO] = rest + + return app.call(env) + end + + [404, { CONTENT_TYPE => "text/plain", "X-Cascade" => "pass" }, ["Not Found: #{path}"]] + + ensure + env[PATH_INFO] = path + env[SCRIPT_NAME] = script_name + end + + private + def casecmp?(v1, v2) + # if both nil, or they're the same string + return true if v1 == v2 + + # if either are nil... (but they're not the same) + return false if v1.nil? + return false if v2.nil? + + # otherwise check they're not case-insensitive the same + v1.casecmp(v2).zero? + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/utils.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/utils.rb new file mode 100644 index 0000000..d3b3b1d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/utils.rb @@ -0,0 +1,613 @@ +# -*- encoding: binary -*- +# frozen_string_literal: true + +require 'uri' +require 'fileutils' +require 'set' +require 'tempfile' +require 'time' + +require_relative 'query_parser' + +module Rack + # Rack::Utils contains a grab-bag of useful methods for writing web + # applications adopted from all kinds of Ruby libraries. + + module Utils + (require_relative 'core_ext/regexp'; using ::Rack::RegexpExtensions) if RUBY_VERSION < '2.4' + + ParameterTypeError = QueryParser::ParameterTypeError + InvalidParameterError = QueryParser::InvalidParameterError + DEFAULT_SEP = QueryParser::DEFAULT_SEP + COMMON_SEP = QueryParser::COMMON_SEP + KeySpaceConstrainedParams = QueryParser::Params + + class << self + attr_accessor :default_query_parser + end + # The default number of bytes to allow parameter keys to take up. + # This helps prevent a rogue client from flooding a Request. + self.default_query_parser = QueryParser.make_default(65536, 100) + + module_function + + # URI escapes. (CGI style space to +) + def escape(s) + URI.encode_www_form_component(s) + end + + # Like URI escaping, but with %20 instead of +. Strictly speaking this is + # true URI escaping. + def escape_path(s) + ::URI::DEFAULT_PARSER.escape s + end + + # Unescapes the **path** component of a URI. See Rack::Utils.unescape for + # unescaping query parameters or form components. + def unescape_path(s) + ::URI::DEFAULT_PARSER.unescape s + end + + # Unescapes a URI escaped string with +encoding+. +encoding+ will be the + # target encoding of the string returned, and it defaults to UTF-8 + def unescape(s, encoding = Encoding::UTF_8) + URI.decode_www_form_component(s, encoding) + end + + class << self + attr_accessor :multipart_part_limit + end + + # The maximum number of parts a request can contain. Accepting too many part + # can lead to the server running out of file handles. + # Set to `0` for no limit. + self.multipart_part_limit = (ENV['RACK_MULTIPART_PART_LIMIT'] || 128).to_i + + def self.param_depth_limit + default_query_parser.param_depth_limit + end + + def self.param_depth_limit=(v) + self.default_query_parser = self.default_query_parser.new_depth_limit(v) + end + + def self.key_space_limit + default_query_parser.key_space_limit + end + + def self.key_space_limit=(v) + self.default_query_parser = self.default_query_parser.new_space_limit(v) + end + + if defined?(Process::CLOCK_MONOTONIC) + def clock_time + Process.clock_gettime(Process::CLOCK_MONOTONIC) + end + else + # :nocov: + def clock_time + Time.now.to_f + end + # :nocov: + end + + def parse_query(qs, d = nil, &unescaper) + Rack::Utils.default_query_parser.parse_query(qs, d, &unescaper) + end + + def parse_nested_query(qs, d = nil) + Rack::Utils.default_query_parser.parse_nested_query(qs, d) + end + + def build_query(params) + params.map { |k, v| + if v.class == Array + build_query(v.map { |x| [k, x] }) + else + v.nil? ? escape(k) : "#{escape(k)}=#{escape(v)}" + end + }.join("&") + end + + def build_nested_query(value, prefix = nil) + case value + when Array + value.map { |v| + build_nested_query(v, "#{prefix}[]") + }.join("&") + when Hash + value.map { |k, v| + build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k)) + }.delete_if(&:empty?).join('&') + when nil + prefix + else + raise ArgumentError, "value must be a Hash" if prefix.nil? + "#{prefix}=#{escape(value)}" + end + end + + def q_values(q_value_header) + q_value_header.to_s.split(/\s*,\s*/).map do |part| + value, parameters = part.split(/\s*;\s*/, 2) + quality = 1.0 + if parameters && (md = /\Aq=([\d.]+)/.match(parameters)) + quality = md[1].to_f + end + [value, quality] + end + end + + # Return best accept value to use, based on the algorithm + # in RFC 2616 Section 14. If there are multiple best + # matches (same specificity and quality), the value returned + # is arbitrary. + def best_q_match(q_value_header, available_mimes) + values = q_values(q_value_header) + + matches = values.map do |req_mime, quality| + match = available_mimes.find { |am| Rack::Mime.match?(am, req_mime) } + next unless match + [match, quality] + end.compact.sort_by do |match, quality| + (match.split('/', 2).count('*') * -10) + quality + end.last + matches && matches.first + end + + ESCAPE_HTML = { + "&" => "&", + "<" => "<", + ">" => ">", + "'" => "'", + '"' => """, + "/" => "/" + } + + ESCAPE_HTML_PATTERN = Regexp.union(*ESCAPE_HTML.keys) + + # Escape ampersands, brackets and quotes to their HTML/XML entities. + def escape_html(string) + string.to_s.gsub(ESCAPE_HTML_PATTERN){|c| ESCAPE_HTML[c] } + end + + def select_best_encoding(available_encodings, accept_encoding) + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html + + expanded_accept_encoding = [] + + accept_encoding.each do |m, q| + preference = available_encodings.index(m) || available_encodings.size + + if m == "*" + (available_encodings - accept_encoding.map(&:first)).each do |m2| + expanded_accept_encoding << [m2, q, preference] + end + else + expanded_accept_encoding << [m, q, preference] + end + end + + encoding_candidates = expanded_accept_encoding + .sort_by { |_, q, p| [-q, p] } + .map!(&:first) + + unless encoding_candidates.include?("identity") + encoding_candidates.push("identity") + end + + expanded_accept_encoding.each do |m, q| + encoding_candidates.delete(m) if q == 0.0 + end + + (encoding_candidates & available_encodings)[0] + end + + def parse_cookies(env) + parse_cookies_header env[HTTP_COOKIE] + end + + def parse_cookies_header(header) + # According to RFC 6265: + # The syntax for cookie headers only supports semicolons + # User Agent -> Server == + # Cookie: SID=31d4d96e407aad42; lang=en-US + return {} unless header + header.split(/[;] */n).each_with_object({}) do |cookie, cookies| + next if cookie.empty? + key, value = cookie.split('=', 2) + cookies[key] = (unescape(value) rescue value) unless cookies.key?(key) + end + end + + def add_cookie_to_header(header, key, value) + case value + when Hash + domain = "; domain=#{value[:domain]}" if value[:domain] + path = "; path=#{value[:path]}" if value[:path] + max_age = "; max-age=#{value[:max_age]}" if value[:max_age] + expires = "; expires=#{value[:expires].httpdate}" if value[:expires] + secure = "; secure" if value[:secure] + httponly = "; HttpOnly" if (value.key?(:httponly) ? value[:httponly] : value[:http_only]) + same_site = + case value[:same_site] + when false, nil + nil + when :none, 'None', :None + '; SameSite=None' + when :lax, 'Lax', :Lax + '; SameSite=Lax' + when true, :strict, 'Strict', :Strict + '; SameSite=Strict' + else + raise ArgumentError, "Invalid SameSite value: #{value[:same_site].inspect}" + end + value = value[:value] + end + value = [value] unless Array === value + + cookie = "#{escape(key)}=#{value.map { |v| escape v }.join('&')}#{domain}" \ + "#{path}#{max_age}#{expires}#{secure}#{httponly}#{same_site}" + + case header + when nil, '' + cookie + when String + [header, cookie].join("\n") + when Array + (header + [cookie]).join("\n") + else + raise ArgumentError, "Unrecognized cookie header value. Expected String, Array, or nil, got #{header.inspect}" + end + end + + def set_cookie_header!(header, key, value) + header[SET_COOKIE] = add_cookie_to_header(header[SET_COOKIE], key, value) + nil + end + + def make_delete_cookie_header(header, key, value) + case header + when nil, '' + cookies = [] + when String + cookies = header.split("\n") + when Array + cookies = header + end + + key = escape(key) + domain = value[:domain] + path = value[:path] + regexp = if domain + if path + /\A#{key}=.*(?:domain=#{domain}(?:;|$).*path=#{path}(?:;|$)|path=#{path}(?:;|$).*domain=#{domain}(?:;|$))/ + else + /\A#{key}=.*domain=#{domain}(?:;|$)/ + end + elsif path + /\A#{key}=.*path=#{path}(?:;|$)/ + else + /\A#{key}=/ + end + + cookies.reject! { |cookie| regexp.match? cookie } + + cookies.join("\n") + end + + def delete_cookie_header!(header, key, value = {}) + header[SET_COOKIE] = add_remove_cookie_to_header(header[SET_COOKIE], key, value) + nil + end + + # Adds a cookie that will *remove* a cookie from the client. Hence the + # strange method name. + def add_remove_cookie_to_header(header, key, value = {}) + new_header = make_delete_cookie_header(header, key, value) + + add_cookie_to_header(new_header, key, + { value: '', path: nil, domain: nil, + max_age: '0', + expires: Time.at(0) }.merge(value)) + + end + + def rfc2822(time) + time.rfc2822 + end + + # Modified version of stdlib time.rb Time#rfc2822 to use '%d-%b-%Y' instead + # of '% %b %Y'. + # It assumes that the time is in GMT to comply to the RFC 2109. + # + # NOTE: I'm not sure the RFC says it requires GMT, but is ambiguous enough + # that I'm certain someone implemented only that option. + # Do not use %a and %b from Time.strptime, it would use localized names for + # weekday and month. + # + def rfc2109(time) + wday = Time::RFC2822_DAY_NAME[time.wday] + mon = Time::RFC2822_MONTH_NAME[time.mon - 1] + time.strftime("#{wday}, %d-#{mon}-%Y %H:%M:%S GMT") + end + + # Parses the "Range:" header, if present, into an array of Range objects. + # Returns nil if the header is missing or syntactically invalid. + # Returns an empty array if none of the ranges are satisfiable. + def byte_ranges(env, size) + warn "`byte_ranges` is deprecated, please use `get_byte_ranges`" if $VERBOSE + get_byte_ranges env['HTTP_RANGE'], size + end + + def get_byte_ranges(http_range, size) + # See + return nil unless http_range && http_range =~ /bytes=([^;]+)/ + ranges = [] + $1.split(/,\s*/).each do |range_spec| + return nil unless range_spec =~ /(\d*)-(\d*)/ + r0, r1 = $1, $2 + if r0.empty? + return nil if r1.empty? + # suffix-byte-range-spec, represents trailing suffix of file + r0 = size - r1.to_i + r0 = 0 if r0 < 0 + r1 = size - 1 + else + r0 = r0.to_i + if r1.empty? + r1 = size - 1 + else + r1 = r1.to_i + return nil if r1 < r0 # backwards range is syntactically invalid + r1 = size - 1 if r1 >= size + end + end + ranges << (r0..r1) if r0 <= r1 + end + ranges + end + + # Constant time string comparison. + # + # NOTE: the values compared should be of fixed length, such as strings + # that have already been processed by HMAC. This should not be used + # on variable length plaintext strings because it could leak length info + # via timing attacks. + def secure_compare(a, b) + return false unless a.bytesize == b.bytesize + + l = a.unpack("C*") + + r, i = 0, -1 + b.each_byte { |v| r |= v ^ l[i += 1] } + r == 0 + end + + # Context allows the use of a compatible middleware at different points + # in a request handling stack. A compatible middleware must define + # #context which should take the arguments env and app. The first of which + # would be the request environment. The second of which would be the rack + # application that the request would be forwarded to. + class Context + attr_reader :for, :app + + def initialize(app_f, app_r) + raise 'running context does not respond to #context' unless app_f.respond_to? :context + @for, @app = app_f, app_r + end + + def call(env) + @for.context(env, @app) + end + + def recontext(app) + self.class.new(@for, app) + end + + def context(env, app = @app) + recontext(app).call(env) + end + end + + # A case-insensitive Hash that preserves the original case of a + # header when set. + # + # @api private + class HeaderHash < Hash # :nodoc: + def self.[](headers) + if headers.is_a?(HeaderHash) && !headers.frozen? + return headers + else + return self.new(headers) + end + end + + def initialize(hash = {}) + super() + @names = {} + hash.each { |k, v| self[k] = v } + end + + # on dup/clone, we need to duplicate @names hash + def initialize_copy(other) + super + @names = other.names.dup + end + + # on clear, we need to clear @names hash + def clear + super + @names.clear + end + + def each + super do |k, v| + yield(k, v.respond_to?(:to_ary) ? v.to_ary.join("\n") : v) + end + end + + def to_hash + hash = {} + each { |k, v| hash[k] = v } + hash + end + + def [](k) + super(k) || super(@names[k.downcase]) + end + + def []=(k, v) + canonical = k.downcase.freeze + delete k if @names[canonical] && @names[canonical] != k # .delete is expensive, don't invoke it unless necessary + @names[canonical] = k + super k, v + end + + def delete(k) + canonical = k.downcase + result = super @names.delete(canonical) + result + end + + def include?(k) + super || @names.include?(k.downcase) + end + + alias_method :has_key?, :include? + alias_method :member?, :include? + alias_method :key?, :include? + + def merge!(other) + other.each { |k, v| self[k] = v } + self + end + + def merge(other) + hash = dup + hash.merge! other + end + + def replace(other) + clear + other.each { |k, v| self[k] = v } + self + end + + protected + def names + @names + end + end + + # Every standard HTTP code mapped to the appropriate message. + # Generated with: + # curl -s https://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv | \ + # ruby -ne 'm = /^(\d{3}),(?!Unassigned|\(Unused\))([^,]+)/.match($_) and \ + # puts "#{m[1]} => \x27#{m[2].strip}\x27,"' + HTTP_STATUS_CODES = { + 100 => 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 103 => 'Early Hints', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-Status', + 208 => 'Already Reported', + 226 => 'IM Used', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => '(Unused)', + 307 => 'Temporary Redirect', + 308 => 'Permanent Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Payload Too Large', + 414 => 'URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Range Not Satisfiable', + 417 => 'Expectation Failed', + 421 => 'Misdirected Request', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 425 => 'Too Early', + 426 => 'Upgrade Required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 451 => 'Unavailable for Legal Reasons', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 509 => 'Bandwidth Limit Exceeded', + 510 => 'Not Extended', + 511 => 'Network Authentication Required' + } + + # Responses with HTTP status codes that should not have an entity body + STATUS_WITH_NO_ENTITY_BODY = Hash[((100..199).to_a << 204 << 304).product([true])] + + SYMBOL_TO_STATUS_CODE = Hash[*HTTP_STATUS_CODES.map { |code, message| + [message.downcase.gsub(/\s|-|'/, '_').to_sym, code] + }.flatten] + + def status_code(status) + if status.is_a?(Symbol) + SYMBOL_TO_STATUS_CODE.fetch(status) { raise ArgumentError, "Unrecognized status code #{status.inspect}" } + else + status.to_i + end + end + + PATH_SEPS = Regexp.union(*[::File::SEPARATOR, ::File::ALT_SEPARATOR].compact) + + def clean_path_info(path_info) + parts = path_info.split PATH_SEPS + + clean = [] + + parts.each do |part| + next if part.empty? || part == '.' + part == '..' ? clean.pop : clean << part + end + + clean_path = clean.join(::File::SEPARATOR) + clean_path.prepend("/") if parts.empty? || parts.first.empty? + clean_path + end + + NULL_BYTE = "\0" + + def valid_path?(path) + path.valid_encoding? && !path.include?(NULL_BYTE) + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/version.rb b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/version.rb new file mode 100644 index 0000000..aad9c59 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/lib/rack/version.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +# Copyright (C) 2007-2019 Leah Neukirchen +# +# Rack is freely distributable under the terms of an MIT-style license. +# See MIT-LICENSE or https://opensource.org/licenses/MIT. + +# The Rack main module, serving as a namespace for all core Rack +# modules and classes. +# +# All modules meant for use in your application are autoloaded here, +# so it should be enough just to require 'rack' in your code. + +module Rack + # The Rack protocol version number implemented. + VERSION = [1, 3] + + # Return the Rack protocol version as a dotted string. + def self.version + VERSION.join(".") + end + + RELEASE = "2.2.3" + + # Return the Rack release as a dotted string. + def self.release + RELEASE + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/rack.gemspec b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/rack.gemspec new file mode 100644 index 0000000..246ed7c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-2.2.3/rack.gemspec @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +require_relative 'lib/rack/version' + +Gem::Specification.new do |s| + s.name = "rack" + s.version = Rack::RELEASE + s.platform = Gem::Platform::RUBY + s.summary = "A modular Ruby webserver interface." + s.license = "MIT" + + s.description = <<~EOF + Rack provides a minimal, modular and adaptable interface for developing + web applications in Ruby. By wrapping HTTP requests and responses in + the simplest way possible, it unifies and distills the API for web + servers, web frameworks, and software in between (the so-called + middleware) into a single method call. + EOF + + s.files = Dir['{bin/*,contrib/*,example/*,lib/**/*}'] + + %w(MIT-LICENSE rack.gemspec Rakefile README.rdoc SPEC.rdoc) + + s.bindir = 'bin' + s.executables << 'rackup' + s.require_path = 'lib' + s.extra_rdoc_files = ['README.rdoc', 'CHANGELOG.md', 'CONTRIBUTING.md'] + + s.author = 'Leah Neukirchen' + s.email = 'leah@vuxu.org' + + s.homepage = 'https://github.com/rack/rack' + + s.required_ruby_version = '>= 2.3.0' + + s.metadata = { + "bug_tracker_uri" => "https://github.com/rack/rack/issues", + "changelog_uri" => "https://github.com/rack/rack/blob/master/CHANGELOG.md", + "documentation_uri" => "https://rubydoc.info/github/rack/rack", + "source_code_uri" => "https://github.com/rack/rack" + } + + s.add_development_dependency 'minitest', "~> 5.0" + s.add_development_dependency 'minitest-sprint' + s.add_development_dependency 'minitest-global_expectations' + s.add_development_dependency 'rake' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/Gemfile b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/Gemfile new file mode 100644 index 0000000..66d7b03 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/Gemfile @@ -0,0 +1,13 @@ +source "https://rubygems.org" +# encoding: utf-8 + +gem 'rake' + +rack_version = ENV['rack'].to_s +rack_version = nil if rack_version.empty? or rack_version == 'stable' +rack_version = {:github => 'rack/rack'} if rack_version == 'master' +gem 'rack', rack_version + +gem 'sinatra', path: '..' + +gemspec diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/License b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/License new file mode 100644 index 0000000..29cdd92 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/License @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) 2011-2017 Konstantin Haase +Copyright (c) 2015-2017 Zachary Scott + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/README.md b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/README.md new file mode 100644 index 0000000..82fbf98 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/README.md @@ -0,0 +1,118 @@ +# Rack::Protection + +This gem protects against typical web attacks. +Should work for all Rack apps, including Rails. + +# Usage + +Use all protections you probably want to use: + +``` ruby +# config.ru +require 'rack/protection' +use Rack::Protection +run MyApp +``` + +Skip a single protection middleware: + +``` ruby +# config.ru +require 'rack/protection' +use Rack::Protection, :except => :path_traversal +run MyApp +``` + +Use a single protection middleware: + +``` ruby +# config.ru +require 'rack/protection' +use Rack::Protection::AuthenticityToken +run MyApp +``` + +# Prevented Attacks + +## Cross Site Request Forgery + +Prevented by: + +* [`Rack::Protection::AuthenticityToken`][authenticity-token] (not included by `use Rack::Protection`) +* [`Rack::Protection::FormToken`][form-token] (not included by `use Rack::Protection`) +* [`Rack::Protection::JsonCsrf`][json-csrf] +* [`Rack::Protection::RemoteReferrer`][remote-referrer] (not included by `use Rack::Protection`) +* [`Rack::Protection::RemoteToken`][remote-token] +* [`Rack::Protection::HttpOrigin`][http-origin] + +## Cross Site Scripting + +Prevented by: + +* [`Rack::Protection::EscapedParams`][escaped-params] (not included by `use Rack::Protection`) +* [`Rack::Protection::XSSHeader`][xss-header] (Internet Explorer and Chrome only) +* [`Rack::Protection::ContentSecurityPolicy`][content-security-policy] + +## Clickjacking + +Prevented by: + +* [`Rack::Protection::FrameOptions`][frame-options] + +## Directory Traversal + +Prevented by: + +* [`Rack::Protection::PathTraversal`][path-traversal] + +## Session Hijacking + +Prevented by: + +* [`Rack::Protection::SessionHijacking`][session-hijacking] + +## Cookie Tossing + +Prevented by: +* [`Rack::Protection::CookieTossing`][cookie-tossing] (not included by `use Rack::Protection`) + +## IP Spoofing + +Prevented by: + +* [`Rack::Protection::IPSpoofing`][ip-spoofing] + +## Helps to protect against protocol downgrade attacks and cookie hijacking + +Prevented by: + +* [`Rack::Protection::StrictTransport`][strict-transport] (not included by `use Rack::Protection`) + +# Installation + + gem install rack-protection + +# Instrumentation + +Instrumentation is enabled by passing in an instrumenter as an option. +``` +use Rack::Protection, instrumenter: ActiveSupport::Notifications +``` + +The instrumenter is passed a namespace (String) and environment (Hash). The namespace is 'rack.protection' and the attack type can be obtained from the environment key 'rack.protection.attack'. + +[authenticity-token]: http://www.sinatrarb.com/protection/authenticity_token +[content-security-policy]: http://www.sinatrarb.com/protection/content_security_policy +[cookie-tossing]: http://www.sinatrarb.com/protection/cookie_tossing +[escaped-params]: http://www.sinatrarb.com/protection/escaped_params +[form-token]: http://www.sinatrarb.com/protection/form_token +[frame-options]: http://www.sinatrarb.com/protection/frame_options +[http-origin]: http://www.sinatrarb.com/protection/http_origin +[ip-spoofing]: http://www.sinatrarb.com/protection/ip_spoofing +[json-csrf]: http://www.sinatrarb.com/protection/json_csrf +[path-traversal]: http://www.sinatrarb.com/protection/path_traversal +[remote-referrer]: http://www.sinatrarb.com/protection/remote_referrer +[remote-token]: http://www.sinatrarb.com/protection/remote_token +[session-hijacking]: http://www.sinatrarb.com/protection/session_hijacking +[strict-transport]: http://www.sinatrarb.com/protection/strict_transport +[xss-header]: http://www.sinatrarb.com/protection/xss_header diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/Rakefile b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/Rakefile new file mode 100644 index 0000000..5bab169 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/Rakefile @@ -0,0 +1,72 @@ +# encoding: utf-8 +$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) + +begin + require 'bundler' + Bundler::GemHelper.install_tasks +rescue LoadError => e + $stderr.puts e +end + +desc "run specs" +task(:spec) { ruby '-S rspec spec' } + +namespace :doc do + task :readmes do + Dir.glob 'lib/rack/protection/*.rb' do |file| + excluded_files = %w[lib/rack/protection/base.rb lib/rack/protection/version.rb] + next if excluded_files.include?(file) + doc = File.read(file)[/^ module Protection(\n)+( #[^\n]*\n)*/m].scan(/^ *#(?!#) ?(.*)\n/).join("\n") + file = "doc/#{file[4..-4].tr("/_", "-")}.rdoc" + Dir.mkdir "doc" unless File.directory? "doc" + puts "writing #{file}" + File.open(file, "w") { |f| f << doc } + end + end + + task :index do + doc = File.read("README.md") + file = "doc/rack-protection-readme.md" + Dir.mkdir "doc" unless File.directory? "doc" + puts "writing #{file}" + File.open(file, "w") { |f| f << doc } + end + + task :all => [:readmes, :index] +end + +desc "generate documentation" +task :doc => 'doc:all' + +desc "generate gemspec" +task 'rack-protection.gemspec' do + require 'rack/protection/version' + content = File.binread 'rack-protection.gemspec' + + # fetch data + fields = { + :authors => `git shortlog -sn`.force_encoding('utf-8').scan(/[^\d\s].*/), + :email => ["mail@zzak.io", "konstantin.haase@gmail.com"], + :files => %w(License README.md Rakefile Gemfile rack-protection.gemspec) + Dir['lib/**/*'] + } + + # insert data + fields.each do |field, values| + updated = " s.#{field} = [" + updated << values.map { |v| "\n %p" % v }.join(',') + updated << "\n ]" + content.sub!(/ s\.#{field} = \[\n( .*\n)* \]/, updated) + end + + # set version + content.sub! /(s\.version.*=\s+).*/, "\\1\"#{Rack::Protection::VERSION}\"" + + # escape unicode + content.gsub!(/./) { |c| c.bytesize > 1 ? "\\u{#{c.codepoints.first.to_s(16)}}" : c } + + File.open('rack-protection.gemspec', 'w') { |f| f << content } +end + +task :gemspec => 'rack-protection.gemspec' +task :default => :spec +task :test => :spec diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack-protection.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack-protection.rb new file mode 100644 index 0000000..1633086 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack-protection.rb @@ -0,0 +1 @@ +require "rack/protection" diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection.rb new file mode 100644 index 0000000..be2c03f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection.rb @@ -0,0 +1,57 @@ +require 'rack/protection/version' +require 'rack' + +module Rack + module Protection + autoload :AuthenticityToken, 'rack/protection/authenticity_token' + autoload :Base, 'rack/protection/base' + autoload :CookieTossing, 'rack/protection/cookie_tossing' + autoload :ContentSecurityPolicy, 'rack/protection/content_security_policy' + autoload :EscapedParams, 'rack/protection/escaped_params' + autoload :FormToken, 'rack/protection/form_token' + autoload :FrameOptions, 'rack/protection/frame_options' + autoload :HttpOrigin, 'rack/protection/http_origin' + autoload :IPSpoofing, 'rack/protection/ip_spoofing' + autoload :JsonCsrf, 'rack/protection/json_csrf' + autoload :PathTraversal, 'rack/protection/path_traversal' + autoload :ReferrerPolicy, 'rack/protection/referrer_policy' + autoload :RemoteReferrer, 'rack/protection/remote_referrer' + autoload :RemoteToken, 'rack/protection/remote_token' + autoload :SessionHijacking, 'rack/protection/session_hijacking' + autoload :StrictTransport, 'rack/protection/strict_transport' + autoload :XSSHeader, 'rack/protection/xss_header' + + def self.new(app, options = {}) + # does not include: RemoteReferrer, AuthenticityToken and FormToken + except = Array options[:except] + use_these = Array options[:use] + + if options.fetch(:without_session, false) + except += [:session_hijacking, :remote_token] + end + + Rack::Builder.new do + # Off by default, unless added + use ::Rack::Protection::AuthenticityToken, options if use_these.include? :authenticity_token + use ::Rack::Protection::ContentSecurityPolicy, options if use_these.include? :content_security_policy + use ::Rack::Protection::CookieTossing, options if use_these.include? :cookie_tossing + use ::Rack::Protection::EscapedParams, options if use_these.include? :escaped_params + use ::Rack::Protection::FormToken, options if use_these.include? :form_token + use ::Rack::Protection::ReferrerPolicy, options if use_these.include? :referrer_policy + use ::Rack::Protection::RemoteReferrer, options if use_these.include? :remote_referrer + use ::Rack::Protection::StrictTransport, options if use_these.include? :strict_transport + + # On by default, unless skipped + use ::Rack::Protection::FrameOptions, options unless except.include? :frame_options + use ::Rack::Protection::HttpOrigin, options unless except.include? :http_origin + use ::Rack::Protection::IPSpoofing, options unless except.include? :ip_spoofing + use ::Rack::Protection::JsonCsrf, options unless except.include? :json_csrf + use ::Rack::Protection::PathTraversal, options unless except.include? :path_traversal + use ::Rack::Protection::RemoteToken, options unless except.include? :remote_token + use ::Rack::Protection::SessionHijacking, options unless except.include? :session_hijacking + use ::Rack::Protection::XSSHeader, options unless except.include? :xss_header + run app + end.to_app + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/authenticity_token.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/authenticity_token.rb new file mode 100644 index 0000000..d7445e2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/authenticity_token.rb @@ -0,0 +1,251 @@ +require 'rack/protection' +require 'securerandom' +require 'openssl' +require 'base64' + +module Rack + module Protection + ## + # Prevented attack:: CSRF + # Supported browsers:: all + # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery + # + # This middleware only accepts requests other than GET, + # HEAD, OPTIONS, TRACE if their given access + # token matches the token included in the session. + # + # It checks the X-CSRF-Token header and the POST form + # data. + # + # Compatible with the {rack-csrf}[https://rubygems.org/gems/rack_csrf] gem. + # + # == Options + # + # [:authenticity_param] the name of the param that should contain + # the token on a request. Default value: + # "authenticity_token" + # + # [:key] the name of the param that should contain + # the token in the session. Default value: + # :csrf + # + # [:allow_if] a proc for custom allow/deny logic. Default value: + # nil + # + # == Example: Forms application + # + # To show what the AuthenticityToken does, this section includes a sample + # program which shows two forms. One with, and one without a CSRF token + # The one without CSRF token field will get a 403 Forbidden response. + # + # Install the gem, then run the program: + # + # gem install 'rack-protection' + # ruby server.rb + # + # Here is server.rb: + # + # require 'rack/protection' + # + # app = Rack::Builder.app do + # use Rack::Session::Cookie, secret: 'secret' + # use Rack::Protection::AuthenticityToken + # + # run -> (env) do + # [200, {}, [ + # <<~EOS + # + # + # + # + # rack-protection minimal example + # + # + #

Without Authenticity Token

+ #

This takes you to Forbidden

+ #
+ # + # + #
+ # + #

With Authenticity Token

+ #

This successfully takes you to back to this form.

+ #
+ # + # + # + #
+ # + # + # EOS + # ]] + # end + # end + # + # Rack::Handler::WEBrick.run app + # + # == Example: Customize which POST parameter holds the token + # + # To customize the authenticity parameter for form data, use the + # :authenticity_param option: + # use Rack::Protection::AuthenticityToken, authenticity_param: 'your_token_param_name' + class AuthenticityToken < Base + TOKEN_LENGTH = 32 + + default_options :authenticity_param => 'authenticity_token', + :key => :csrf, + :allow_if => nil + + def self.token(session, path: nil, method: :post) + self.new(nil).mask_authenticity_token(session, path: path, method: method) + end + + def self.random_token + SecureRandom.urlsafe_base64(TOKEN_LENGTH, padding: false) + end + + def accepts?(env) + session = session(env) + set_token(session) + + safe?(env) || + valid_token?(env, env['HTTP_X_CSRF_TOKEN']) || + valid_token?(env, Request.new(env).params[options[:authenticity_param]]) || + ( options[:allow_if] && options[:allow_if].call(env) ) + rescue + false + end + + def mask_authenticity_token(session, path: nil, method: :post) + set_token(session) + + token = if path && method + per_form_token(session, path, method) + else + global_token(session) + end + + mask_token(token) + end + + GLOBAL_TOKEN_IDENTIFIER = '!real_csrf_token' + private_constant :GLOBAL_TOKEN_IDENTIFIER + + private + + def set_token(session) + session[options[:key]] ||= self.class.random_token + end + + # Checks the client's masked token to see if it matches the + # session token. + def valid_token?(env, token) + return false if token.nil? || token.empty? + + session = session(env) + + begin + token = decode_token(token) + rescue ArgumentError # encoded_masked_token is invalid Base64 + return false + end + + # See if it's actually a masked token or not. We should be able + # to handle any unmasked tokens that we've issued without error. + + if unmasked_token?(token) + compare_with_real_token(token, session) + elsif masked_token?(token) + token = unmask_token(token) + + compare_with_global_token(token, session) || + compare_with_real_token(token, session) || + compare_with_per_form_token(token, session, Request.new(env)) + else + false # Token is malformed + end + end + + # Creates a masked version of the authenticity token that varies + # on each request. The masking is used to mitigate SSL attacks + # like BREACH. + def mask_token(token) + one_time_pad = SecureRandom.random_bytes(token.length) + encrypted_token = xor_byte_strings(one_time_pad, token) + masked_token = one_time_pad + encrypted_token + encode_token(masked_token) + end + + # Essentially the inverse of +mask_token+. + def unmask_token(masked_token) + # Split the token into the one-time pad and the encrypted + # value and decrypt it + token_length = masked_token.length / 2 + one_time_pad = masked_token[0...token_length] + encrypted_token = masked_token[token_length..-1] + xor_byte_strings(one_time_pad, encrypted_token) + end + + def unmasked_token?(token) + token.length == TOKEN_LENGTH + end + + def masked_token?(token) + token.length == TOKEN_LENGTH * 2 + end + + def compare_with_real_token(token, session) + secure_compare(token, real_token(session)) + end + + def compare_with_global_token(token, session) + secure_compare(token, global_token(session)) + end + + def compare_with_per_form_token(token, session, request) + secure_compare(token, + per_form_token(session, request.path.chomp('/'), request.request_method) + ) + end + + def real_token(session) + decode_token(session[options[:key]]) + end + + def global_token(session) + token_hmac(session, GLOBAL_TOKEN_IDENTIFIER) + end + + def per_form_token(session, path, method) + token_hmac(session, "#{path}##{method.downcase}") + end + + def encode_token(token) + Base64.urlsafe_encode64(token) + end + + def decode_token(token) + Base64.urlsafe_decode64(token) + end + + def token_hmac(session, identifier) + OpenSSL::HMAC.digest( + OpenSSL::Digest::SHA256.new, + real_token(session), + identifier + ) + end + + def xor_byte_strings(s1, s2) + s2 = s2.dup + size = s1.bytesize + i = 0 + while i < size + s2.setbyte(i, s1.getbyte(i) ^ s2.getbyte(i)) + i += 1 + end + s2 + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/base.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/base.rb new file mode 100644 index 0000000..83e7240 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/base.rb @@ -0,0 +1,126 @@ +require 'rack/protection' +require 'rack/utils' +require 'digest' +require 'logger' +require 'uri' + +module Rack + module Protection + class Base + DEFAULT_OPTIONS = { + :reaction => :default_reaction, :logging => true, + :message => 'Forbidden', :encryptor => Digest::SHA1, + :session_key => 'rack.session', :status => 403, + :allow_empty_referrer => true, + :report_key => "protection.failed", + :html_types => %w[text/html application/xhtml text/xml application/xml] + } + + attr_reader :app, :options + + def self.default_options(options) + define_method(:default_options) { super().merge(options) } + end + + def self.default_reaction(reaction) + alias_method(:default_reaction, reaction) + end + + def default_options + DEFAULT_OPTIONS + end + + def initialize(app, options = {}) + @app, @options = app, default_options.merge(options) + end + + def safe?(env) + %w[GET HEAD OPTIONS TRACE].include? env['REQUEST_METHOD'] + end + + def accepts?(env) + raise NotImplementedError, "#{self.class} implementation pending" + end + + def call(env) + unless accepts? env + instrument env + result = react env + end + result or app.call(env) + end + + def react(env) + result = send(options[:reaction], env) + result if Array === result and result.size == 3 + end + + def warn(env, message) + return unless options[:logging] + l = options[:logger] || env['rack.logger'] || ::Logger.new(env['rack.errors']) + l.warn(message) + end + + def instrument(env) + return unless i = options[:instrumenter] + env['rack.protection.attack'] = self.class.name.split('::').last.downcase + i.instrument('rack.protection', env) + end + + def deny(env) + warn env, "attack prevented by #{self.class}" + [options[:status], {'Content-Type' => 'text/plain'}, [options[:message]]] + end + + def report(env) + warn env, "attack reported by #{self.class}" + env[options[:report_key]] = true + end + + def session?(env) + env.include? options[:session_key] + end + + def session(env) + return env[options[:session_key]] if session? env + fail "you need to set up a session middleware *before* #{self.class}" + end + + def drop_session(env) + session(env).clear if session? env + end + + def referrer(env) + ref = env['HTTP_REFERER'].to_s + return if !options[:allow_empty_referrer] and ref.empty? + URI.parse(ref).host || Request.new(env).host + rescue URI::InvalidURIError + end + + def origin(env) + env['HTTP_ORIGIN'] || env['HTTP_X_ORIGIN'] + end + + def random_string(secure = defined? SecureRandom) + secure ? SecureRandom.hex(16) : "%032x" % rand(2**128-1) + rescue NotImplementedError + random_string false + end + + def encrypt(value) + options[:encryptor].hexdigest value.to_s + end + + def secure_compare(a, b) + Rack::Utils.secure_compare(a.to_s, b.to_s) + end + + alias default_reaction deny + + def html?(headers) + return false unless header = headers.detect { |k,v| k.downcase == 'content-type' } + options[:html_types].include? header.last[/^\w+\/\w+/] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/content_security_policy.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/content_security_policy.rb new file mode 100644 index 0000000..91eea92 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/content_security_policy.rb @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: XSS and others + # Supported browsers:: Firefox 23+, Safari 7+, Chrome 25+, Opera 15+ + # + # Description:: Content Security Policy, a mechanism web applications + # can use to mitigate a broad class of content injection + # vulnerabilities, such as cross-site scripting (XSS). + # Content Security Policy is a declarative policy that lets + # the authors (or server administrators) of a web application + # inform the client about the sources from which the + # application expects to load resources. + # + # More info:: W3C CSP Level 1 : https://www.w3.org/TR/CSP1/ (deprecated) + # W3C CSP Level 2 : https://www.w3.org/TR/CSP2/ (current) + # W3C CSP Level 3 : https://www.w3.org/TR/CSP3/ (draft) + # https://developer.mozilla.org/en-US/docs/Web/Security/CSP + # http://caniuse.com/#search=ContentSecurityPolicy + # http://content-security-policy.com/ + # https://securityheaders.io + # https://scotthelme.co.uk/csp-cheat-sheet/ + # http://www.html5rocks.com/en/tutorials/security/content-security-policy/ + # + # Sets the 'Content-Security-Policy[-Report-Only]' header. + # + # Options: ContentSecurityPolicy configuration is a complex topic with + # several levels of support that has evolved over time. + # See the W3C documentation and the links in the more info + # section for CSP usage examples and best practices. The + # CSP3 directives in the 'NO_ARG_DIRECTIVES' constant need to be + # presented in the options hash with a boolean 'true' in order + # to be used in a policy. + # + class ContentSecurityPolicy < Base + default_options default_src: "'self'", report_only: false + + DIRECTIVES = %i(base_uri child_src connect_src default_src + font_src form_action frame_ancestors frame_src + img_src manifest_src media_src object_src + plugin_types referrer reflected_xss report_to + report_uri require_sri_for sandbox script_src + style_src worker_src webrtc_src navigate_to + prefetch_src).freeze + + NO_ARG_DIRECTIVES = %i(block_all_mixed_content disown_opener + upgrade_insecure_requests).freeze + + def csp_policy + directives = [] + + DIRECTIVES.each do |d| + if options.key?(d) + directives << "#{d.to_s.sub(/_/, '-')} #{options[d]}" + end + end + + # Set these key values to boolean 'true' to include in policy + NO_ARG_DIRECTIVES.each do |d| + if options.key?(d) && options[d].is_a?(TrueClass) + directives << d.to_s.tr('_', '-') + end + end + + directives.compact.sort.join('; ') + end + + def call(env) + status, headers, body = @app.call(env) + header = options[:report_only] ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy' + headers[header] ||= csp_policy if html? headers + [status, headers, body] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/cookie_tossing.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/cookie_tossing.rb new file mode 100644 index 0000000..10614d5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/cookie_tossing.rb @@ -0,0 +1,75 @@ +require 'rack/protection' +require 'pathname' + +module Rack + module Protection + ## + # Prevented attack:: Cookie Tossing + # Supported browsers:: all + # More infos:: https://github.com/blog/1466-yummy-cookies-across-domains + # + # Does not accept HTTP requests if the HTTP_COOKIE header contains more than one + # session cookie. This does not protect against a cookie overflow attack. + # + # Options: + # + # session_key:: The name of the session cookie (default: 'rack.session') + class CookieTossing < Base + default_reaction :deny + + def call(env) + status, headers, body = super + response = Rack::Response.new(body, status, headers) + request = Rack::Request.new(env) + remove_bad_cookies(request, response) + response.finish + end + + def accepts?(env) + cookie_header = env['HTTP_COOKIE'] + cookies = Rack::Utils.parse_query(cookie_header, ';,') { |s| s } + cookies.each do |k, v| + if k == session_key && Array(v).size > 1 + bad_cookies << k + elsif k != session_key && Rack::Utils.unescape(k) == session_key + bad_cookies << k + end + end + bad_cookies.empty? + end + + def remove_bad_cookies(request, response) + return if bad_cookies.empty? + paths = cookie_paths(request.path) + bad_cookies.each do |name| + paths.each { |path| response.set_cookie name, empty_cookie(request.host, path) } + end + end + + def redirect(env) + request = Request.new(env) + warn env, "attack prevented by #{self.class}" + [302, {'Content-Type' => 'text/html', 'Location' => request.path}, []] + end + + def bad_cookies + @bad_cookies ||= [] + end + + def cookie_paths(path) + path = '/' if path.to_s.empty? + paths = [] + Pathname.new(path).descend { |p| paths << p.to_s } + paths + end + + def empty_cookie(host, path) + {:value => '', :domain => host, :path => path, :expires => Time.at(0)} + end + + def session_key + @session_key ||= options[:session_key] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/escaped_params.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/escaped_params.rb new file mode 100644 index 0000000..6706d10 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/escaped_params.rb @@ -0,0 +1,89 @@ +require 'rack/protection' +require 'rack/utils' +require 'tempfile' + +begin + require 'escape_utils' +rescue LoadError +end + +module Rack + module Protection + ## + # Prevented attack:: XSS + # Supported browsers:: all + # More infos:: http://en.wikipedia.org/wiki/Cross-site_scripting + # + # Automatically escapes Rack::Request#params so they can be embedded in HTML + # or JavaScript without any further issues. Calls +html_safe+ on the escaped + # strings if defined, to avoid double-escaping in Rails. + # + # Options: + # escape:: What escaping modes to use, should be Symbol or Array of Symbols. + # Available: :html (default), :javascript, :url + class EscapedParams < Base + extend Rack::Utils + + class << self + alias escape_url escape + public :escape_html + end + + default_options :escape => :html, + :escaper => defined?(EscapeUtils) ? EscapeUtils : self + + def initialize(*) + super + + modes = Array options[:escape] + @escaper = options[:escaper] + @html = modes.include? :html + @javascript = modes.include? :javascript + @url = modes.include? :url + + if @javascript and not @escaper.respond_to? :escape_javascript + fail("Use EscapeUtils for JavaScript escaping.") + end + end + + def call(env) + request = Request.new(env) + get_was = handle(request.GET) + post_was = handle(request.POST) rescue nil + app.call env + ensure + request.GET.replace get_was if get_was + request.POST.replace post_was if post_was + end + + def handle(hash) + was = hash.dup + hash.replace escape(hash) + was + end + + def escape(object) + case object + when Hash then escape_hash(object) + when Array then object.map { |o| escape(o) } + when String then escape_string(object) + when Tempfile then object + else nil + end + end + + def escape_hash(hash) + hash = hash.dup + hash.each { |k,v| hash[k] = escape(v) } + hash + end + + def escape_string(str) + str = @escaper.escape_url(str) if @url + str = @escaper.escape_html(str) if @html + str = @escaper.escape_javascript(str) if @javascript + str + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/form_token.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/form_token.rb new file mode 100644 index 0000000..994740f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/form_token.rb @@ -0,0 +1,23 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: CSRF + # Supported browsers:: all + # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery + # + # Only accepts submitted forms if a given access token matches the token + # included in the session. Does not expect such a token from Ajax request. + # + # This middleware is not used when using the Rack::Protection collection, + # since it might be a security issue, depending on your application + # + # Compatible with rack-csrf. + class FormToken < AuthenticityToken + def accepts?(env) + env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" or super + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/frame_options.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/frame_options.rb new file mode 100644 index 0000000..bce75c4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/frame_options.rb @@ -0,0 +1,37 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: Clickjacking + # Supported browsers:: Internet Explorer 8, Firefox 3.6.9, Opera 10.50, + # Safari 4.0, Chrome 4.1.249.1042 and later + # More infos:: https://developer.mozilla.org/en/The_X-FRAME-OPTIONS_response_header + # + # Sets X-Frame-Options header to tell the browser avoid embedding the page + # in a frame. + # + # Options: + # + # frame_options:: Defines who should be allowed to embed the page in a + # frame. Use :deny to forbid any embedding, :sameorigin + # to allow embedding from the same origin (default). + class FrameOptions < Base + default_options :frame_options => :sameorigin + + def frame_options + @frame_options ||= begin + frame_options = options[:frame_options] + frame_options = options[:frame_options].to_s.upcase unless frame_options.respond_to? :to_str + frame_options.to_str + end + end + + def call(env) + status, headers, body = @app.call(env) + headers['X-Frame-Options'] ||= frame_options if html? headers + [status, headers, body] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/http_origin.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/http_origin.rb new file mode 100644 index 0000000..034b7ac --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/http_origin.rb @@ -0,0 +1,47 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: CSRF + # Supported browsers:: Google Chrome 2, Safari 4 and later + # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery + # http://tools.ietf.org/html/draft-abarth-origin + # + # Does not accept unsafe HTTP requests when value of Origin HTTP request header + # does not match default or permitted URIs. + # + # If you want to permit a specific domain, you can pass in as the `:permitted_origins` option: + # + # use Rack::Protection, permitted_origins: ["http://localhost:3000", "http://127.0.01:3000"] + # + # The `:allow_if` option can also be set to a proc to use custom allow/deny logic. + class HttpOrigin < Base + DEFAULT_PORTS = { 'http' => 80, 'https' => 443, 'coffee' => 80 } + default_reaction :deny + default_options :allow_if => nil + + def base_url(env) + request = Rack::Request.new(env) + port = ":#{request.port}" unless request.port == DEFAULT_PORTS[request.scheme] + "#{request.scheme}://#{request.host}#{port}" + end + + def accepts?(env) + return true if safe? env + return true unless origin = env['HTTP_ORIGIN'] + return true if base_url(env) == origin + return true if options[:allow_if] && options[:allow_if].call(env) + + if options.key? :origin_whitelist + warn env, "Rack::Protection origin_whitelist option is deprecated and will be removed, " \ + "use permitted_origins instead.\n" + end + + permitted_origins = options[:permitted_origins] || options[:origin_whitelist] + Array(permitted_origins).include? origin + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/ip_spoofing.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/ip_spoofing.rb new file mode 100644 index 0000000..3e404ad --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/ip_spoofing.rb @@ -0,0 +1,23 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: IP spoofing + # Supported browsers:: all + # More infos:: http://blog.c22.cc/2011/04/22/surveymonkey-ip-spoofing/ + # + # Detect (some) IP spoofing attacks. + class IPSpoofing < Base + default_reaction :deny + + def accepts?(env) + return true unless env.include? 'HTTP_X_FORWARDED_FOR' + ips = env['HTTP_X_FORWARDED_FOR'].split(/\s*,\s*/) + return false if env.include? 'HTTP_CLIENT_IP' and not ips.include? env['HTTP_CLIENT_IP'] + return false if env.include? 'HTTP_X_REAL_IP' and not ips.include? env['HTTP_X_REAL_IP'] + true + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/json_csrf.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/json_csrf.rb new file mode 100644 index 0000000..5ec826b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/json_csrf.rb @@ -0,0 +1,57 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: CSRF + # Supported browsers:: all + # More infos:: http://flask.pocoo.org/docs/0.10/security/#json-security + # http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx + # + # JSON GET APIs are vulnerable to being embedded as JavaScript when the + # Array prototype has been patched to track data. Checks the referrer + # even on GET requests if the content type is JSON. + # + # If request includes Origin HTTP header, defers to HttpOrigin to determine + # if the request is safe. Please refer to the documentation for more info. + # + # The `:allow_if` option can be set to a proc to use custom allow/deny logic. + class JsonCsrf < Base + default_options :allow_if => nil + + alias react deny + + def call(env) + request = Request.new(env) + status, headers, body = app.call(env) + + if has_vector?(request, headers) + warn env, "attack prevented by #{self.class}" + + react_and_close(env, body) or [status, headers, body] + else + [status, headers, body] + end + end + + def has_vector?(request, headers) + return false if request.xhr? + return false if options[:allow_if] && options[:allow_if].call(request.env) + return false unless headers['Content-Type'].to_s.split(';', 2).first =~ /^\s*application\/json\s*$/ + origin(request.env).nil? and referrer(request.env) != request.host + end + + def react_and_close(env, body) + reaction = react(env) + + close_body(body) if reaction + + reaction + end + + def close_body(body) + body.close if body.respond_to?(:close) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/path_traversal.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/path_traversal.rb new file mode 100644 index 0000000..4e8c94c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/path_traversal.rb @@ -0,0 +1,42 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: Directory traversal + # Supported browsers:: all + # More infos:: http://en.wikipedia.org/wiki/Directory_traversal + # + # Unescapes '/' and '.', expands +path_info+. + # Thus GET /foo/%2e%2e%2fbar becomes GET /bar. + class PathTraversal < Base + def call(env) + path_was = env["PATH_INFO"] + env["PATH_INFO"] = cleanup path_was if path_was && !path_was.empty? + app.call env + ensure + env["PATH_INFO"] = path_was + end + + def cleanup(path) + encoding = path.encoding + dot = '.'.encode(encoding) + slash = '/'.encode(encoding) + backslash = '\\'.encode(encoding) + + parts = [] + unescaped = path.gsub(/%2e/i, dot).gsub(/%2f/i, slash).gsub(/%5c/i, backslash) + unescaped = unescaped.gsub(backslash, slash) + + unescaped.split(slash).each do |part| + next if part.empty? or part == dot + part == '..' ? parts.pop : parts << part + end + + cleaned = slash + parts.join(slash) + cleaned << slash if parts.any? and unescaped =~ %r{/\.{0,2}$} + cleaned + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/referrer_policy.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/referrer_policy.rb new file mode 100644 index 0000000..f977d72 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/referrer_policy.rb @@ -0,0 +1,25 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: Secret leakage, third party tracking + # Supported browsers:: mixed support + # More infos:: https://www.w3.org/TR/referrer-policy/ + # https://caniuse.com/#search=referrer-policy + # + # Sets Referrer-Policy header to tell the browser to limit the Referer header. + # + # Options: + # referrer_policy:: The policy to use (default: 'strict-origin-when-cross-origin') + class ReferrerPolicy < Base + default_options :referrer_policy => 'strict-origin-when-cross-origin' + + def call(env) + status, headers, body = @app.call(env) + headers['Referrer-Policy'] ||= options[:referrer_policy] + [status, headers, body] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/remote_referrer.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/remote_referrer.rb new file mode 100644 index 0000000..5375ebc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/remote_referrer.rb @@ -0,0 +1,20 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: CSRF + # Supported browsers:: all + # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery + # + # Does not accept unsafe HTTP requests if the Referer [sic] header is set to + # a different host. + class RemoteReferrer < Base + default_reaction :deny + + def accepts?(env) + safe?(env) or referrer(env) == Request.new(env).host + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/remote_token.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/remote_token.rb new file mode 100644 index 0000000..f3922c8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/remote_token.rb @@ -0,0 +1,22 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: CSRF + # Supported browsers:: all + # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery + # + # Only accepts unsafe HTTP requests if a given access token matches the token + # included in the session *or* the request comes from the same origin. + # + # Compatible with rack-csrf. + class RemoteToken < AuthenticityToken + default_reaction :deny + + def accepts?(env) + super or referrer(env) == Request.new(env).host + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/session_hijacking.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/session_hijacking.rb new file mode 100644 index 0000000..a7dd54b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/session_hijacking.rb @@ -0,0 +1,36 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: Session Hijacking + # Supported browsers:: all + # More infos:: http://en.wikipedia.org/wiki/Session_hijacking + # + # Tracks request properties like the user agent in the session and empties + # the session if those properties change. This essentially prevents attacks + # from Firesheep. Since all headers taken into consideration can be + # spoofed, too, this will not prevent determined hijacking attempts. + class SessionHijacking < Base + default_reaction :drop_session + default_options :tracking_key => :tracking, :encrypt_tracking => true, + :track => %w[HTTP_USER_AGENT] + + def accepts?(env) + session = session env + key = options[:tracking_key] + if session.include? key + session[key].all? { |k,v| v == encrypt(env[k]) } + else + session[key] = {} + options[:track].each { |k| session[key][k] = encrypt(env[k]) } + end + end + + def encrypt(value) + value = value.to_s.downcase + options[:encrypt_tracking] ? super(value) : value + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/strict_transport.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/strict_transport.rb new file mode 100644 index 0000000..b4283ba --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/strict_transport.rb @@ -0,0 +1,39 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: Protects against against protocol downgrade attacks and cookie hijacking. + # Supported browsers:: all + # More infos:: https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security + # + # browser will prevent any communications from being sent over HTTP + # to the specified domain and will instead send all communications over HTTPS. + # It also prevents HTTPS click through prompts on browsers. + # + # Options: + # + # max_age:: How long future requests to the domain should go over HTTPS; specified in seconds + # include_subdomains:: If all present and future subdomains will be HTTPS + # preload:: Allow this domain to be included in browsers HSTS preload list. See https://hstspreload.appspot.com/ + + class StrictTransport < Base + default_options :max_age => 31_536_000, :include_subdomains => false, :preload => false + + def strict_transport + @strict_transport ||= begin + strict_transport = 'max-age=' + options[:max_age].to_s + strict_transport += '; includeSubDomains' if options[:include_subdomains] + strict_transport += '; preload' if options[:preload] + strict_transport.to_str + end + end + + def call(env) + status, headers, body = @app.call(env) + headers['Strict-Transport-Security'] ||= strict_transport + [status, headers, body] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/version.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/version.rb new file mode 100644 index 0000000..b7df5d1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/version.rb @@ -0,0 +1,5 @@ +module Rack + module Protection + VERSION = '2.2.0' + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/xss_header.rb b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/xss_header.rb new file mode 100644 index 0000000..eb6f92f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/lib/rack/protection/xss_header.rb @@ -0,0 +1,25 @@ +require 'rack/protection' + +module Rack + module Protection + ## + # Prevented attack:: Non-permanent XSS + # Supported browsers:: Internet Explorer 8+ and Chrome + # More infos:: http://blogs.msdn.com/b/ie/archive/2008/07/01/ie8-security-part-iv-the-xss-filter.aspx + # + # Sets X-XSS-Protection header to tell the browser to block attacks. + # + # Options: + # xss_mode:: How the browser should prevent the attack (default: :block) + class XSSHeader < Base + default_options :xss_mode => :block, :nosniff => true + + def call(env) + status, headers, body = @app.call(env) + headers['X-XSS-Protection'] ||= "1; mode=#{options[:xss_mode]}" if html? headers + headers['X-Content-Type-Options'] ||= 'nosniff' if options[:nosniff] + [status, headers, body] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/rack-protection.gemspec b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/rack-protection.gemspec new file mode 100644 index 0000000..817649d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rack-protection-2.2.0/rack-protection.gemspec @@ -0,0 +1,40 @@ +version = File.read(File.expand_path("../../VERSION", __FILE__)).strip + +Gem::Specification.new do |s| + # general infos + s.name = "rack-protection" + s.version = version + s.description = "Protect against typical web attacks, works with all Rack apps, including Rails." + s.homepage = "http://sinatrarb.com/protection/" + s.summary = s.description + s.license = 'MIT' + s.authors = ["https://github.com/sinatra/sinatra/graphs/contributors"] + s.email = "sinatrarb@googlegroups.com" + s.files = Dir["lib/**/*.rb"] + [ + "License", + "README.md", + "Rakefile", + "Gemfile", + "rack-protection.gemspec" + ] + + if s.respond_to?(:metadata) + s.metadata = { + 'source_code_uri' => 'https://github.com/sinatra/sinatra/tree/master/rack-protection', + 'homepage_uri' => 'http://sinatrarb.com/protection/', + 'documentation_uri' => 'https://www.rubydoc.info/gems/rack-protection' + } + else + raise <<-EOF +RubyGems 2.0 or newer is required to protect against public gem pushes. You can update your rubygems version by running: + gem install rubygems-update + update_rubygems: + gem update --system +EOF + end + + # dependencies + s.add_dependency "rack" + s.add_development_dependency "rack-test" + s.add_development_dependency "rspec", "~> 3.6" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/CONTRIBUTING.rdoc b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/CONTRIBUTING.rdoc new file mode 100644 index 0000000..b5c551c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/CONTRIBUTING.rdoc @@ -0,0 +1,220 @@ += Developer Introduction + +So you want to write a generator, fix a bug, or otherwise work with RDoc. This +document provides an overview of how RDoc works from parsing options to +generating output. Most of the documentation can be found in the specific +classes for each feature. + +== Bugs + +If you think you found a bug, file a ticket on the {issues +tracker}[https://github.com/ruby/rdoc/issues] on github. + +If your bug involves an error RDoc produced please include a sample file that +illustrates the problem or link to the repository or gem that is associated +with the bug. + +Please include steps to reproduce the issue. Here are some examples of good +issues: + +* https://github.com/ruby/rdoc/issues/55 +* https://github.com/ruby/rdoc/issues/61 + +== Developer Quick Start + +RDoc uses bundler for development. To get ready to work on RDoc run: + + $ gem install bundler + [...] + $ bundle install + [...] + $ rake + [...] + +This will install all the necessary dependencies for development with rake, +generate documentation and run the tests for the first time. + +If the tests don't pass on the first run check the {Travis CI page for +RDoc}[https://travis-ci.org/ruby/rdoc] to see if there are any known failures +(there shouldn't be). + +You can now use `rake` and `autotest` to run the tests. + +Note: the `rake` command must be used first before running any tests, because +its used to generate various parsers implemented in RDoc. Also `rake clean` is +helpful to delete these generated files. + +== Glossary + +Here are definitions for some common terms in the RDoc documentation. The +list also briefly describes how the components of RDoc interact. + +parser:: + Parses files and creates a documentation tree from the contents. + +documentation tree:: + The documentation tree represents files, classes, modules, methods, + constants, includes, comments and other ruby syntax features as a tree. + RDoc walks this tree with a generator to create documentation. + +generator:: + Walks the documentation tree and generates output. + + RDoc ships with two generators, the Darkfish generator creates HTML and the + RI generator creates an RI data store. + +markup parser:: + Parses comments from a file into a generic markup tree. + + The markup parsers allow RDoc to handle RDoc, TomDoc, rd and Markdown format + documentation with common formatters. + +markup tree:: + Each parsed comment has a markup tree that represents common markup items + such as headings, paragraphs, lists or verbatim text sections for example + code or output. + + A generator uses a formatters to walks the tree to create output. Some + generators use multiple formatters on a markup tree to produce the output. + +formatter:: + Converts a parsed markup tree into some form other form of markup. + + Formatters can either produce a one-to-one conversion, such as ToHtml, or + extract part of the parsed result, such as ToHtmlSnippet which outputs the + first 100 characters as HTML. + +== Plugins + +When 'rdoc/rdoc' is loaded RDoc looks for 'rdoc/discover' files in your +installed gems. This can be used to load parsers, alternate generators, or +additional preprocessor directives. An rdoc plugin layout should look +something like this: + + lib/rdoc/discover.rb + lib/my/rdoc/plugin.rb + # etc. + +In your rdoc/discover.rb file you will want to wrap the loading of your plugin +in an RDoc version check like this: + + begin + gem 'rdoc', '~> 3' + require 'my/rdoc/plugin' + rescue Gem::LoadError + end + +=== Plugin Types + +In RDoc you can change the following behaviors: + +* Add a parser for a new file format +* Add a new output generator +* Add a new markup directive +* Add a new type of documentation markup +* Add a new type of formatter + +All of these are described below + +== Option Parsing + +Option parsing is handled by RDoc::Options. When you're writing a generator +you can provide the user with extra options by providing a class method ++setup_options+. The option parser will call this after your generator is +loaded. See RDoc::Generator for details. + +== File Parsing + +After options are parsed, RDoc parses files from the files and directories in +ARGV. RDoc compares the filename against what each parser claims it can parse +via RDoc::Parser#parse_files_matching. For example, RDoc::Parser::C can parse +C files, C headers, C++ files, C++ headers and yacc grammars. + +Once a matching parser class is found it is instantiated and +scan+ is called. +The parser needs to extract documentation from the file and add it to the RDoc +document tree. Usually this involves starting at the root and adding a class +or a module (RDoc::TopLevel#add_class and RDoc::TopLevel#add_module) and +proceeding to add classes, modules and methods to each nested item. + +When the parsers are finished the document tree is cleaned up to remove +dangling references to aliases and includes that were not found (and may exist +in a separate library) through RDoc::ClassModule#complete. + +To write your own parser for a new file format see RDoc::Parser. + +=== Documentation Tree + +The parsers build a documentation tree that is composed of RDoc::CodeObject and +its subclasses. There are various methods to walk the tree to extract +information, see RDoc::Context and its subclasses. + +Within a class or module, attributes, methods and constants are divided into +sections. The section represents a functional grouping of parts of the class. +TomDoc uses the sections "Public", "Internal" and "Deprecated". The sections +can be enumerated using RDoc::Context#each_section. + +== Output Generation + +An RDoc generator turns the documentation tree into some other kind of output. +RDoc comes with an HTML generator (RDoc::Generator::Darkfish) and an RI +database generator (RDoc::Generator::RI). The output a generator creates does +not have to be human-readable. + +To create your own generator see RDoc::Generator. + +=== Comments + +In RDoc 3.10 and newer the comment on an RDoc::CodeObject is now an +RDoc::Comment object instead of a String. This is to support various +documentation markup formats like rdoc, TomDoc and rd. The comments are +normalized to remove comment markers and remove indentation then parsed lazily +via RDoc::Comment#document to create a generic markup tree that can be +processed by a formatter. + +To add your own markup format see RDoc::Markup@Other+directives + +==== Formatters + +To transform a comment into some form of output an RDoc::Markup::Formatter +subclass is used like RDoc::Markup::ToHtml. A formatter is a visitor that +walks a parsed comment tree (an RDoc::Markup::Document) of any format. To help +write a formatter RDoc::Markup::FormatterTestCase exists for generic parsers, +and RDoc::Markup::TextFormatterTestCase which contains extra test cases for +text-type output (like +ri+ output). + +RDoc ships with formatters that will turn a comment into HTML, rdoc-markup-like +text, ANSI or terminal backspace highlighted text, HTML, cross-referenced HTML, +an HTML snippet free of most markup, an HTML label for use in id attributes, a +table-of-contents page, and text with only code blocks. + +The output of the formatter does not need to be text or text-like. +RDoc::Markup::ToLabel creates an HTML-safe label for use in an HTML id +attribute. A formatter could count the number of words and the average word +length for a comment, for example. + +==== Directives + +For comments in markup you can add new directives (:nodoc: is a directive). +Directives may replace text or store it off for later use. + +See RDoc::Markup::PreProcess::register for details. + +=== JSONIndex + +RDoc contains a special generator, RDoc::Generator::JSONIndex, which creates a +JSON-based search index and includes a search engine for use with HTML output. +This generator can be used to add searching to any HTML output and is designed +to be called from inside an HTML generator. + +== Markup + +Additional documentation markup formats can be added to RDoc. A markup +parsing class must respond to \::parse and accept a String argument containing +the markup format. An RDoc::Document containing documentation items +(RDoc::Markup::Heading, RDoc::Markup::Paragraph, RDoc::Markup::Verbatim, etc.) +must be returned. + +To register the parser with rdoc, add the markup type's name and class to the +RDoc::Text::MARKUP_FORMAT hash like: + + RDoc::Text::MARKUP_FORMAT['rdoc'] = RDoc::Markup diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/CVE-2013-0256.rdoc b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/CVE-2013-0256.rdoc new file mode 100644 index 0000000..b285b6a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/CVE-2013-0256.rdoc @@ -0,0 +1,49 @@ += RDoc 2.3.0 through 3.12 XSS Exploit + +RDoc documentation generated by rdoc 2.3.0 through rdoc 3.12 and prereleases up +to rdoc 4.0.0.preview2.1 are vulnerable to an XSS exploit. This exploit may +lead to cookie disclosure to third parties. + +The exploit exists in darkfish.js which is copied from the RDoc install +location to the generated documentation. + +RDoc is a static documentation generation tool. Patching the library itself +is insufficient to correct this exploit. Those hosting rdoc documentation will +need to apply the following patch. If applied while ignoring whitespace, this +patch will correct all affected versions: + + diff --git darkfish.js darkfish.js + index 4be722f..f26fd45 100644 + --- darkfish.js + +++ darkfish.js + @@ -109,13 +109,15 @@ function hookSearch() { + function highlightTarget( anchor ) { + console.debug( "Highlighting target '%s'.", anchor ); + + - $("a[name=" + anchor + "]").each( function() { + - if ( !$(this).parent().parent().hasClass('target-section') ) { + - console.debug( "Wrapping the target-section" ); + - $('div.method-detail').unwrap( 'div.target-section' ); + - $(this).parent().wrap( '
' ); + - } else { + - console.debug( "Already wrapped." ); + + $("a[name]").each( function() { + + if ( $(this).attr("name") == anchor ) { + + if ( !$(this).parent().parent().hasClass('target-section') ) { + + console.debug( "Wrapping the target-section" ); + + $('div.method-detail').unwrap( 'div.target-section' ); + + $(this).parent().wrap( '
' ); + + } else { + + console.debug( "Already wrapped." ); + + } + } + }); + }; + +RDoc 3.9.5, 3.12.1 and RDoc 4.0.0.rc.2 and newer are not vulnerable to this +exploit. + +This exploit was discovered by Evgeny Ermakov . + +This vulnerability has been assigned the CVE identifier CVE-2013-0256. + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/ExampleMarkdown.md b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/ExampleMarkdown.md new file mode 100644 index 0000000..2a883c5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/ExampleMarkdown.md @@ -0,0 +1,37 @@ +This document contains example output to show RDoc styling. This file was +created from a Markdown file. + +For the following styles, see ExampleRDoc.rdoc for style examples: + +* Headings +* Paragraphs +* Code blocks (verbatim sections) +* Definition lists +* Ordered lists +* Unordered lists + +These items all use the same styles as RDoc format files. + +## Footnotes + +Footnotes are rendered at the bottom of the documentation section[^1]. For +pages this will be at the bottom of the page. For method documentation this +will be at the end of the current method. + +[^1]: Here is the footnote content. As you can see it is at the bottom of the +page. + +## Blockquotes + +Here is how a blockquote looks. + +> We finished our first sensor sweep of the neutral zone. Now, how the hell do +> we defeat an enemy that knows us better than we know ourselves? and attack +> the Romulans. +> +> > Sorry, Data. I guess it's better to be lucky than good. The unexpected is +> > our normal routine. Could someone survive inside a transporter buffer for +> > 75 years? + +This text is from [Riker Ipsum](http://rikeripsum.com) + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/ExampleRDoc.rdoc b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/ExampleRDoc.rdoc new file mode 100644 index 0000000..79c2432 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/ExampleRDoc.rdoc @@ -0,0 +1,208 @@ +This document contains example output to show RDoc styling. This file was +created from a RDoc Markup file. + +== Headings + +You should not use headings beyond level 3, it is a sign of poor organization +of your code or documentation. It also becomes difficult for the user to +figure out what you are attempting to explain to them as they have to track +the multiple layers of nesting. + += Heading level 1 + +Above is a level one heading. + +These paragraphs are filler that exist so you can see how the heading +interacts with paragraphs before and after the heading. As you can see each +different heading has a different amount of margin above and below. + +This should be sufficient to give you a proper picture of how it will appear in +your documentation. + +== Heading level 2 + +Above is a level two heading. + +These paragraphs are filler that exist so you can see how the heading +interacts with paragraphs before and after the heading. As you can see each +different heading has a different amount of margin above and below. + +This should be sufficient to give you a proper picture of how it will appear in +your documentation. + +=== Heading level 3 + +Above is a level three heading. + +These paragraphs are filler that exist so you can see how the heading +interacts with paragraphs before and after the heading. As you can see each +different heading has a different amount of margin above and below. + +This should be sufficient to give you a proper picture of how it will appear in +your documentation. + +==== Heading level 4 + +Above is a level four heading. + +These paragraphs are filler that exist so you can see how the heading +interacts with paragraphs before and after the heading. As you can see each +different heading has a different amount of margin above and below. + +This should be sufficient to give you a proper picture of how it will appear in +your documentation. + +===== Heading level 5 + +Above is a level five heading. + +These paragraphs are filler that exist so you can see how the heading +interacts with paragraphs before and after the heading. As you can see each +different heading has a different amount of margin above and below. + +This should be sufficient to give you a proper picture of how it will appear in +your documentation. + +====== Heading level 6 + +Above is a level six heading. + +These paragraphs are filler that exist so you can see how the heading +interacts with paragraphs before and after the heading. As you can see each +different heading has a different amount of margin above and below. + +This should be sufficient to give you a proper picture of how it will appear in +your documentation. + +== Paragraphs + +This is how a paragraph looks. Since it is difficult to generate good content +for paragraphs I have chosen to use {Riker Ipsum}[http://rikeripsum.com] for +nonsense filler content. In the previous sentence you can see how a link is +formatted. + +Here is an example of *bold* and _emphasis_ styling. Try not to combine the +two or use them too often. Here is an example of inline verbatim +text. That should be enough of a taste of inline markup in paragraphs. +The Riker Ipsum filler follows: + +Shields up! Rrrrred alert! Well, I'll say this for him - he's sure of himself. +and attack the Romulans. Worf, It's better than music. It's jazz. This should +be interesting. When has justice ever been as simple as a rule book? Flair is +what marks the difference between artistry and mere competence. + +Sorry, Data. I think you've let your personal feelings cloud your judgement. We +finished our first sensor sweep of the neutral zone. Yes, absolutely, I do +indeed concur, wholeheartedly! Mr. Worf, you do remember how to fire phasers? A +lot of things can change in twelve years, Admiral. Your shields were failing, +sir. + +== Verbatim sections + +A verbatim section typically contains source code or example output. This is +how verbatim blocks of code looks: + + def local responder + responder.ping do |value| + return value + end + end + + def ping uri + @uri = uri + @remote = DRb::DRbObject.new_with_uri @uri + + @remote.ping do |value| + return value + end + end + +This is a paragraph following the verbatim block so you can see how leading and trailing paragraphs interact with it. + +== Unordered lists + +Here is an unordered list. As you can see it uses non-numeral markers for each list item: + +* This is the top-most item in the list. +* This is a second item in the list. + + Unlike the first item, this item has more than one paragraph so you can see + how they interact. +* This is a third item in the list. Like the item before it, this item has a + second paragraph. + + Here is the second paragraph in the list item. +* A final list item. + +== Ordered lists + +Here is an ordered list. As you can see it uses numeral markers for each list +item: + +1. This is the first item in the list. +1. This is the second item in the list. + + Unlike the first item, this item has more than one paragraph so you can see + how they interact. +1. This is the third item in the list. Like the item before it, this item has + a second paragraph. + + Here is the second paragraph in the third list item. +1. The fourth and final list item. + +== Definition lists + +=== "Note" list + +The "note" syntax can be used to create a definition list: + + note:: + description + +Here is such a definition list: + +cat:: + A cat is a small mammal that is commonly kept as a pet. + +dog:: + A dog is a mammal that is also kept as a pet. A dog may range in size from + smaller than a cat to larger than a human. + + Typically dogs are easier to train to respond to commands than cats. + +rabbit:: + Rabbits are also mammals, but are infrequently kept as pets. Most rabbits + are wild. + +=== "Label" list + +The "label" syntax can be used to create a definition list: + + [label] + description + +Here is such a definition list: + +[cat] + A cat is a small mammal that is commonly kept as a pet. + +[dog] + A dog is a mammal that is also kept as a pet. A dog may range in size from + smaller than a cat to larger than a human. + + Typically dogs are easier to train to respond to commands than cats. + +[rabbit] + Rabbits are also mammals, but are infrequently kept as pets. Most rabbits + are wild. + +== Rule + +A rule is a horizontal divider between two paragraphs. Following this +paragraph is a rule. + +--- + +In historic versions of RDoc you could control the height of the rule in HTML +output. This is no longer true as HTML 5 does not support this. + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/Gemfile b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/Gemfile new file mode 100644 index 0000000..b7bd49a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/Gemfile @@ -0,0 +1,12 @@ +source 'https://rubygems.org' + +gemspec + +group :development do + gem 'rake' + gem 'racc', '> 1.4.10' + gem 'kpeg', github: 'evanphx/kpeg' + gem 'test-unit' + gem 'rubocop' + gem 'gettext' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/History.rdoc b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/History.rdoc new file mode 100644 index 0000000..d20211f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/History.rdoc @@ -0,0 +1,1666 @@ +=== 5.1.0 / 2017-02-24 + +* Bug fixes + * Fix an issue that rdoc fails when running on Windows with RUBYOPT=-U. + PR #430 by Toshihiko Ichida + +* Minor enhancements + * Parse ruby 2.1 def. PR #436 by Akira Matsuda. + * Suppress warnings in eval. PR #440 by Nobuyoshi Nakada. + +=== 5.0.0 / 2016-11-05 + +* Major enhancements + * Cleanup deprecated code targeted Ruby 1.8 + +* Bug fixes + * Ensure badge data is included in result of JsonIndex template. + * Ensure items in the nil section are displayed in HTML output. Issue #399 + by Daniel Svensson. + * Parse rb_intern_const correctly in C. PR #381 by Sho Hashimoto. + * Fix broken assets caused by #335 when serving ri. PR #360 by Alex Wood. + * Don't try to parse svg files. Issue #350 by Sigurd Svela. + +* Minor enhancements + * Improve class name expansion/resolution in ri. PR #400 by NARUSE, Yui + * Improve performance of document generation. PR #397 by Yusuke Endoh. + +=== 4.3.0 / 2016-11-04 + +* Minor enhancements + * Removed json dependency for Ruby 2.4.0 + * End to support Ruby 1.8.x + +=== 4.2.2 / 2016-02-09 + +* Bug fixes + * Include lib/rdoc/generator/pot/* in built gem + + +=== 4.2.1 / 2015-12-22 + +* Bug fixes + * Fixed infinite loop with CR #339 by @nobu + * Allow rdoc run with --disable-gems #340 by @luizluca + * Don't store full path in GZipped js files #341 by @voxik + * Fix relative path names for drive letters #367 by @nobu + * Fix for valid syntax `class C end` parsing #368 by @nobu + + +=== 4.2.0 / 2014-12-06 + +* Major enhancements + * RDoc can now produce translation files for use with gettext. See + RDoc::Generator::POT for a workflow for creating translations of your + documentation. Pull request #254 by Kouhei Sutou. + +* Minor enhancements + * RDoc now allows any single-word macro before a C method implementation. + Issue #722 by Hanmac. + * Now :all is a synonym for :private for RDoc::Options#visibility= to match + the --all command line option. Pull request #276 by Zachary Scott. + * Running rake for the first time now installs racc. Pull request #285 by + Kouhei Sutou. + * Added -h flag to also display help. Issue #300 by Ryan Davis + * search_index.js is now loaded asynchronously for improved performance. + * Allow +X::Y+ as typewriter text. Issue #319, pull request #322 by Jeremy + Evans. + * Added RDoc::RI::Task for building ri data easily through rake. Pull + request #332 by Zachary Scott. + * A gzipped search index is generated for servers configured to use + precompressed files. Pull request #334 by Zachary Scott. + * CSS files now live under /css relative to the document root. Pull request + #335 by Zachary Scott. + * Improved detection of valid ruby in verbatim sections. Pull request #333 + by Jeremy Evans. + +* Bug fixes + * Fixed HTML labels for cross-browser compatibility. This breaks existing + links but enables cross-browser compatibility. Pull request #330 by Jens + Will. + * RDoc handles ASCII-incompatible encodings now. An encoding hint may need + to be added to the file for RDoc to produce correct output, though. + Issue #288 by Manuel Meurer. + * Fixed height recalculation issues when headings are hovered. Issue #289 + by Dietmar H. Büto. + * RDoc now ignores its own output directories. Pull Request #306 by + Hsing-Hui Hsu, bug #305 by Ryan Davis. + * Fixed RDoc::Task no longer uselessly builds documentation when generating + non-HTML output. Bug #307 by Christina Thompson, pull request #308 by + Hsing-Hui Hsu + * Added pointer to font copyright and license information to LEGAL.rdoc. + Issue #290 by Christian Hofstaedtler. + * Fixed RDoc::Context#<=> for ruby trunk. Issue #284 by Hanmac, pull + request #287 by Aaron Patterson + * Tests no longer create directories inside test/. Pull request #286 by + Kouhei Sutou. + * Fixed documentation example in RDoc::Markup. Pull request #292 by Gregory + Brown. + * Applied typo fix to RDoc::Markup. Pull request #297 by @montanalow + * Fixed pretty_print for RDoc::MethodAttr with an alias. Pull request #324 + by Hsing-Hui Hsu. + * Fixed lexing of %w"". Issue #315 by Thierry Lambert, pull request #323 by + Jeremy Evans. + * RDoc::TokenStream now removes nil tokens. Pull request #318 by Calle + Erlandsson. + * Fixed footer links to rubyforge and darkfish. Pull request #328 by + @blackwinter + * Fixed page-top link. Pull request #329 by @blackwinter + * Minitest gem activation failures are now ignored during test startup. + Issue #313 by Vít Ondruch. + * Fixed error when generating documentation from singleton classes. Issue + #311 by Vít Ondruch. + * Splat and keyword params can now be detected for documentation + completeness. Issue #321 Tom Kadwill. + * Standalone anchors in markdown documents are no longer escaped. Issue + #312 by Scott Thompson. + * Fixed RegExp matching stack overflow on Ruby 1.8.7. Issue #327 by sshao. + +=== 4.1.2 / 2014-09-05 + +* Bug fixes + * Updated vendored jQuery to 1.6.4. Bug ruby/ruby#711 by @neuralme + +=== 4.1.1 / 2014-01-09 + +* Bug fixes + * Fixed reporting of undocumented method parameters when including when + yield and &block are present. Pull request #281 by Victor Bilyk. + * Fixed merging of rd-style and hash-style comments at the top of a file. + Bug #266 by Zachary Scott. + * Fixed Document-attr in the C parser. Bug #271 by Hanmac. + * Removed duplicated condition in superclass fixup. Pull request #282 by + Benoit Daloze. + +=== 4.1.0 / 2013-12-26 + +* Notable changes + * Improved accessibility of HTML output. Accessibility review was provided + by: + + Techvision – http://www.techvision.net.in + + The accessibility consultants in Pune, India + + * The look of RDoc has been updated. + +* Minor enhancements + * RDoc can now link to [], []=, << and >> methods. Pull request #202 by + Jeremy Evans, Bug # 191 by by Zachary Scott. + * Added RDoc::Options#output_decoration which controls header labels for + HTML output. Pull Request #199 by Zachary Scott. + * Added --template-stylesheets options to RDoc to allow specification of + alternate stylesheets. Pull request #205 by Zachary Scott. + * Improved performance of the Markdown and RD parsers. Pull request #217 by + Ryan Davis. + * rdoc -v now prints the version instead of enabling verbose + mode. Pull request #201 by Lee Jarvis. + * Running rake newb now automatically installs development + dependencies if the parser files haven't been built. Pull request #235 by + Kouhei Sutou. + * Moved old DEVELOPERS file to CONTRIBUTING to match github conventions. + * TomDoc output now has a "Returns" heading. Issue #234 by Brian Henderson + * Metaprogrammed methods can now use the :args: directive in addition to the + :call-seq: directive. Issue #236 by Mike Moore. + * Sections can be linked to using "@" like labels. If a section and a label + have the same name the section will be preferred. Issue #233 by Brian + Henderson. + * Files that come with a template are hard-linked to save space. Issue #186 + by Vít Ondruch. + +* Bug fixes + * Applied typo fixes by @dvsuresh from ruby/ruby@2c5dcdf + * Restored behavior of --no-pager alias -T. Pull request #223 by ruafozy. + * Fixed extra whitespace output in the rdoc coverage report. Bug #210 by + Ryan Davis. + * RDoc no longer documents its timestamp file when run on an empty + directory. Bug #212 by Rainer Keller + * HTML escape method names in the table of contents. Bug #219 by Akinori + MUSHA. + * Character literals ?h now create a new token type to prevent + loss of the "?" in output. Bug #220 by Vipul A M. + * When looking up a method that does not exist, ri escapes the regular + expression for fallback searches. Bug #227 by Aaron Patterson. + * The ri generator now writes the class method data after +module_function+. + Bug #222 by Zachary Scott, Ruby bug #8225 by David Unric. + * ri now handles missing ri data files. Bug #222 by Zachary Scott, Ruby bug + #8225 by David Unric. + * Added TomDoc to the supported markup formats section of rdoc --help. + Bug #214 by Ryan Davis. + * Fixed documented? check for classes which indicated incorrect 100% + coverage. Bug #211 by Ryan Davis. + * An :enddoc: at the top level stops all further parsing. Bug #213 by Ryan + Davis. + * Improved handling of multiline call-seq. Bug #207 by Erik Hollensbe. + * Fixed text that is missing whitespace for TomDoc. Bug #248 by Noel Cower. + * The RDoc methods now store the method they are aliased to. Bug #206 by + Jeremy Stephens. + * Fixed parsing of multiple methods on the same line. Bug #221 by derula. + * Fixed missing support for images in markdown. Bug #241, pull request #242 + by Zachary Scott. + * The markdown image fix also added support for images via an rdoc-image: + scheme. See RDoc::Markup@Links for details. Issue #93 by Tim Pease. + * Ignore empty call-seq for methods. Improved deduplication of C methods + sharing the same C function. This allows the method heading to show + up correctly for String#== and #===. Bug #244 by Neurogami. + * RDoc no longer adds "http://" to urls without a scheme. Bug #208 by + Zachary Scott. + * Improved the error message in the RDoc server when ri data is missing. + Bug #243, Pull Request #249 by Tadas Tamošauskas. + * Support ruby 2.0 hash syntax for keywords. Bug #256 by diogocsc. + * Prevent \\ from escaping the tag in RDoc markup. (\ still + escapes the tag.) Bug #251 by Pablo Bianciotto. + * Fixed lexing of escaped characters in strings which could cause + duplication of the final characters in source code view. Bug #252 by Mike + Stok. + * Disallow invalid tab widths for -w option. Bug reported by Charles + Hixson. + * rb_file_const() now adds constants to File::Constants when used outside + file.c. Fixes missing File::Constants::FNM_* constants in ruby. + * Fixed handling of :markup: when the file parser is unknown. Issue #262 by + Brian Henderson, pull request #269 by Rein Henrichs. + * Regexp options are no longer stripped in HTML output. Bug #259 by Zachary + Scott, Pull request #265 by Rein Henrichs + +=== 4.0.1 / 2013-03-27 + +* Bug fixes + * RDoc::Options parser should rescue from OptionParser::ParseError. + * Updated example of RDoc::Options to include reopening RDoc::Options. + Pointed out by Michael Granger + * Moved RubyGems documentation installed message into RDoc hook. For + RubyGems bug #469 by Jeff Sandberg + * An Error is now raised when a heredoc is not terminated. Fixes exceptions + when processing comment blocks. Reported by darix + * rdoc --quiet --no-ignore-invalid now exits for invalid options. Pull + request #192 by Jeremy Evans + * RDoc::Parser::C no longer ignores a (METHOD) cast in rb_define_method. + Pull request #184 by Carlos Agarie + * RDoc::Servlet no longer ignores extra directories from -d. Pull request + #173 by Thomas Leitner + * Fixed `rdoc --ri-site`. Bug #193 by Michal Papis. + * RDoc no longer attempts to parse binary files. Bug #189 by postmodern, + Bug #190 by Christoffer Lervåg, Bug #195 by Aaron Patterson + * `rdoc --pipe` output now contains for markdown compliance. + * RDoc no longer leaves emacs-style modelines in .txt, .md or .rd files. + Bug #178 by Zachary Scott + * RDoc no longer puts raw markup in HTML output for markdown input. Bug + #204 by Erik Hollensbe + * Code objects with nodoc are no longer included in the ri store. Bug #177 + by Thomas Leitner. + * Text#snippet now creates a RDoc::Markup::ToHtmlSnippet correctly. + * The C parser now de-duplicates call-seq if the same C function is used for + multiple method names. Bug #203 by Pete Higgins + +=== 4.0.0 / 2013-02-24 + +RDoc 4.0 includes several new features and several breaking changes. The +changes should not affect users of `rdoc` or `ri`. + +Notable feature additions are markdown support and an WEBrick servlet that can +serve HTML from an ri store. (This means that RubyGems 2.0+ no longer needs +to build HTML documentation when installing gems.) + +Changes since RDoc 3.12.1: + +* Breaking changes + * The default output encoding for RDoc is now UTF-8. Previously RDoc used + the default external encoding which was determined from your locale. + Issue #106 by Justin Baker. + * RDoc::RI::Store is now RDoc::Store so ri data generated by RDoc 4 cannot + be read by earlier versions of RDoc. RDoc::RI::Store exists as an alias + of RDoc::Store so ri data from older versions can still be read. + RDoc::RI::Store will be removed in RDoc 5. + + Tests that create RDoc::CodeObjects on the fly without wiring them into + the documentation tree (did not use add_class, add_method, etc.) must be + updated to use these methods. The documentation tree automatically + attaches them to the store instance which allows lookups to work + correctly. Additionally, a new method RDoc::Store#add_file must be used + instead of RDoc::TopLevel.new. The latter will not be attached to the + documentation tree. + * RDoc generators must accept an RDoc::Store and an RDoc::Options in + initialize. RDoc no longer passes an Array of RDoc::TopLevel objects to + #generate. Use RDoc::Store#all_files instead. + * Some markup formatters (RDoc::Markup::To*) now accept an RDoc::Options + instance as the first argument. Notably, the base class Formatter and + ToHtml*. (This is not universal due to the difficult at accessing the + user's options instance deep inside RDoc. A future major release may + remedy this.) + * Added new markup nodes and specials that RDoc::Markup::Formatter + subclasses must handle. If you're using RDoc::Markup::FormatterTestCase + the new methods you need to add should be readily apparent. + * Removed RDoc::RI::Paths::SYSDIR and ::SITEDIR. These were hidden + constants so no breakage is expected. Use RDoc::RI::Paths::system_dir + and ::site_dir instead. + * RDoc::RI::Store#modules has been renamed to RDoc::Store#module_names + to avoid confusion with RDoc::Store#all_modules imported from + RDoc::TopLevel. + * RDoc::RDocError has been removed. It was deprecated throughout RDoc 3. + * ri -f html is no longer supported. + * Comment definitions in C comments are now only discovered from the first + line. A colon on a subsequent line won't trigger definition extraction. + Issue #103, see also + http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/42942 + * Fixed :stopdoc: for class A::B where A has not been seen. Issue #95 by + Ryan Davis + * RDoc::ClassModule#each_ancestor no longer yields itself if there is + circular ancestry + +* Major enhancements + * ri can now show pages (README, etc.) + + ri rdoc:README + + Will show the README for the latest version of RDoc. You can specify + exact gem versions such as "rdoc-4.0:README" or view pages from the + standard library documentation with "ruby:README". + + RDoc 3 did not save pages in ri data so you will need to regenerate + documentation from your gems to use this feature. + * Added Markdown as a supported format. The markdown format can be set on a + per-file or per-comment basis with the +:markdown:+ directive like the rd + and tomdoc formats and on a per-project basis with + rdoc --markup markdown --write-options + * Removed global state from RDoc. RDoc::Store holds the documentation tree + and connects the driver to the parsers and generator. This also allows + documentation parsing and generation for multiple instances, but the rdoc + command-line tool does not support this. + + Due to this change RDoc::RDoc.current and RDoc::RDoc.reset no longer + exist. + +* Minor enhancements + * Added --page-dir option to give pretty names for a FAQ, guides, or other + documentation you write that is not stored in the project root. For + example, with the following layout: + + README.txt + guides/syntax.txt + guides/conversion.txt + + Running `rdoc --page-dir guides` will make the files in "guides" appear to + be at the top level of the project. This means they will appear to exist + at the top level in HTML output and you can access them with + `ri your_gem:syntax` and `ri your_gem:conversion`. + * Added --root for building documentation from outside the source dir. + * Added current heading and page-top links to HTML headings. + * Added a ChangeLog parser. It automatically parses files that begin + with 'ChangeLog' + * Added a table of contents to the sidebar. + * RDoc markup format merges adjacent labels in a label or note list into a + single definition list item for output. + * RDoc now tracks use of extend. Pull request #118 by Michael Granger. + * RDoc now tracks methods that use super. Pull request #116 by Erik + Hollensbe. + * Added methods ::system_dir, ::site_dir, ::home_dir and ::gem_dir to fetch + the components of RDoc::RI::Paths.path individually. + * Added support for rb_file_const. + * RDoc now processes files in sorted order. Issue #71 by Vít Ondruch + * RDoc now warns with --verbose when methods are duplicated. Issue #71 by + Vít Ondruch + * ri will display documentation for all methods in a class if -a is given. + Issue #57 by casper + * The RDoc coverage report will report line information for attributes, + constants and methods missing documentation. Issue #121 by Zachary Scott + * RDoc now reports a warning for files that are unreadable due to + permissions problems. + * RDoc controls documentation generation for RubyGems 2.0+ + +* Bug fixes + * Fixed parsing of multibyte files with incomplete characters at byte 1024. + Ruby bug #6393 by nobu, patch by Nobuyoshi Nakada and Yui NARUSE. + * Fixed rdoc -E. Ruby Bug #6392 and (modified) patch by Nobuyoshi Nakada + * Added link handling to Markdown output. Bug #160 by burningTyger. + * Fixed HEREDOC output for the limited case of a heredoc followed by a line + end. When a HEREDOC is not followed by a line end RDoc is not currently + smart enough to restore the source correctly. Bug #162 by Zachary Scott. + * Fixed parsing of executables with shebang and encoding comments. Bug #161 + by Marcus Stollsteimer + * RDoc now ignores methods defined on constants instead of creating a fake + module. Bug #163 by Zachary Scott. + * Fixed ChangeLog parsing for FFI gem. Bug #165 by Zachary Scott. + * RDoc now links \#=== methods. Bug #164 by Zachary Scott. + * Allow [] following argument names for TomDoc. Bug #167 by Ellis Berner. + * Fixed the RDoc servlet for home and site directories. Bug #170 by Thomas + Leitner. + * Fixed references to methods in the RDoc servlet. Bug #171 by Thomas + Leitner. + * Fixed debug message when generating the darkfish root page. Pull Request + #174 by Thomas Leitner. + * Fixed deletion of attribute ri data when a class was loaded then saved. + Issue #171 by Thomas Leitner. + * Fully qualified names for constants declared from the top level are now + attached to their class or module properly. + * Fixed table of contents display in HTML output for classes and modules. + * Incremental ri builds of C files now work. C variable names from previous + runs are now saved between runs. + * A word that is directly followed by a multi-word tidy link label no longer + disappears. (Like text{link}[http://example]) + * Fixed legacy template support. Pull Request #107 by Justin Baker. + * An HTML class in a verbatim section no longer triggers ruby parsing. + Issue #92 by Vijay Dev + * Improved documentation for setting the default documentation format for + your ruby project. Issue #94 by Henrik Hodne + * Fixed handling of LANG in the RDoc::Options tests. Issue #99 by Vít + Ondruch + * RDoc no longer quits when given an entry that is not a file or directory. + Issue #101 by Charles Nutter + * Fixed bug in syntax-highlighting that would corrupt regular expressions. + Ruby Bug #6488 by Benny Lyne Amorsen. + * "class Object" no longer appears in the coverage report if all its methods + are documented. This suppresses a false positive for libraries that add + toplevel methods. Pull Request #128 by Zachary Scott. + * Fixed test_gen_url test name in TestRDocMarkupToHtml. Pull Request #130 + by Zachary Scott. + * Comment-defined methods ahead of define_method are now discovered. Issue + #133 by eclectic923 + * Fixed detection of define_method documentation. Issue #138 by Marvin + Gülker. + * Fixed lexing of character syntax (?z). Reported by Xavier + Noria. + * Add license to gem spec. Issue #144 by pivotalcommon + * Fixed comment selection for classes. Pull request #146 by pioz + * Fixed parsing of def self.&() end. Issue #148 by Michael + Lucy + * Generated RD parser files are now included in the gem. Issue #145 by + Marvin Gülker + * Class and module aliases now create new classes to avoid duplicate names + in the class list. Issue #143 by Richard Schneeman, Rails Issue #2839 + * RDoc::Markup::Parser now correctly matches indentation of lists when + multibyte characters are used in the list labels. Issue #140 by + burningTyger + * Fixed mangling of email addresses that look like labels. Issue #129 by + Tobias Koch + * Classes and modules in a C file may now be created in any order. Issue + #124 by Su Zhang + * A metaprogrammed method supports the :args: directive. Issue #100 + * A metaprogrammed method supports the :yields: directive. + * RDoc will now look for directives up to the end of the line. For example, + class B < A; end # :nodoc: + will now hide documentation of B. Issue #125 by Zachary Scott + * Fixed tokenization of % when it is not followed by a $-string type + * Fixed display of __END__ in documentation examples in HTML output + * Fixed tokenization of reserved words used as new-style hash keys + * RDoc now handles class << $gvar by ignoring the body + * Fixed parsing of class A:: B. + * Worked around bug in RDoc::RubyLex where tokens won't be reinterpreted + after unget_tk. + * Fixed class << ::Foo writing documentation to /Foo.html + * Fixed class ::A referencing itself from inside its own namespace. + +Changes since RDoc 4.0.0.rc.2: + +* Bug fix + * Templates now use the correct encoding when generating pages. Issue #183 + by Vít Ondruch + +=== 4.0.0.rc.2 / 2013-02-05 + +* Minor enhancements + * Added current heading and page-top links to HTML headings. + +* Bug fixes + * Fixed an XSS exploit in darkfish.js. This could lead to cookie disclosure + to third parties. See CVE-2013-0256[rdoc-ref:CVE-2013-0256.rdoc] for full + details including a patch you can apply to generated RDoc documentation. + * Fixed parsing of multibyte files with incomplete characters at byte 1024. + Ruby bug #6393 by nobu, patch by Nobuyoshi Nakada and Yui NARUSE. + * Fixed rdoc -E. Ruby Bug #6392 and (modified) patch by Nobuyoshi Nakada + * Added link handling to Markdown output. Bug #160 by burningTyger. + * Fixed HEREDOC output for the limited case of a heredoc followed by a line + end. When a HEREDOC is not followed by a line end RDoc is not currently + smart enough to restore the source correctly. Bug #162 by Zachary Scott. + * Fixed parsing of executables with shebang and encoding comments. Bug #161 + by Marcus Stollsteimer + * RDoc now ignores methods defined on constants instead of creating a fake + module. Bug #163 by Zachary Scott. + * Fixed ChangeLog parsing for FFI gem. Bug #165 by Zachary Scott. + * RDoc now links \#=== methods. Bug #164 by Zachary Scott. + * Allow [] following argument names for TomDoc. Bug #167 by Ellis Berner. + * Fixed the RDoc servlet for home and site directories. Bug #170 by Thomas + Leitner. + * Fixed references to methods in the RDoc servlet. Bug #171 by Thomas + Leitner. + * Fixed debug message when generating the darkfish root page. Pull Request + #174 by Thomas Leitner. + * Fixed deletion of attribute ri data when a class was loaded then saved. + Issue #171 by Thomas Leitner. + +=== 4.0.0.preview2.1 / 2012-12-14 + +* Minor enhancements + * Added --page-dir option to give pretty names for a FAQ, guides, or other + documentation you write that is not stored in the project root. For + example, with the following layout: + + README.txt + guides/syntax.txt + guides/conversion.txt + + Running `rdoc --page-dir guides` will make the files in "guides" appear to + be at the top level of the project. This means they will appear to exist + at the top level in HTML output and you can access them with + `ri your_gem:syntax` and `ri your_gem:conversion`. + +* Bug fixes + * Fully qualified names for constants declared from the top level are now + attached to their class or module properly. + * Fixed table of contents display in HTML output for classes and modules. + * Incremental ri builds of C files now work. C variable names from previous + runs are now saved between runs. + +=== 4.0.0.preview2 / 2012-12-01 + +* Breaking changes + * The default output encoding for RDoc is now UTF-8. Previously RDoc used + the default external encoding which was determined from your locale. + Issue #106 by Justin Baker. + * RDoc::RI::Store is now RDoc::Store so ri data generated by RDoc 4 cannot + be read by earlier versions of RDoc. RDoc::RI::Store exists as an alias + of RDoc::Store so ri data from older versions can still be read. + RDoc::RI::Store will be removed in RDoc 5. + + Tests that create RDoc::CodeObjects on the fly without wiring them into + the documentation tree (did not use add_class, add_method, etc.) must be + updated to use these methods. The documentation tree automatically + attaches them to the store instance which allows lookups to work + correctly. Additionally, a new method RDoc::Store#add_file must be used + instead of RDoc::TopLevel.new. The latter will not be attached to the + documentation tree. + * RDoc generators must accept an RDoc::Store and an RDoc::Options in + initialize. RDoc no longer passes an Array of RDoc::TopLevel objects to + #generate. Use RDoc::Store#all_files instead. + * Some markup formatters (RDoc::Markup::To*) now accept an RDoc::Options + instance as the first argument. Notably, the base class Formatter and + ToHtml*. (This is not universal due to the difficult at accessing the + user's options instance deep inside RDoc. A future major release may + remedy this.) + * Added new markup nodes and specials that RDoc::Markup::Formatter + subclasses must handle. If you're using RDoc::Markup::FormatterTestCase + the new methods you need to add should be readily apparent. + * Removed RDoc::RI::Paths::SYSDIR and ::SITEDIR. These were hidden + constants so no breakage is expected. Use RDoc::RI::Paths::system_dir + and ::site_dir instead. + * RDoc::RI::Store#modules has been renamed to RDoc::Store#module_names + to avoid confusion with RDoc::Store#all_modules imported from + RDoc::TopLevel. + * RDoc::RDocError has been removed. It was deprecated throughout RDoc 3. + * ri -f html is no longer supported. + * Comment definitions in C comments are now only discovered from the first + line. A colon on a subsequent line won't trigger definition extraction. + Issue #103, see also + http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/42942 + * Fixed :stopdoc: for class A::B where A has not been seen. Issue #95 by + Ryan Davis + * RDoc::ClassModule#each_ancestor no longer yields itself if there is + circular ancestry + +* Major enhancements + * ri can now show pages (README, etc.) + + ri rdoc:README + + Will show the README for the latest version of RDoc. You can specify + exact gem versions such as "rdoc-4.0:README" or view pages from the + standard library documentation with "ruby:README". + + RDoc 3 did not save pages in ri data so you will need to regenerate + documentation from your gems to use this feature. + * Added Markdown as a supported format. The markdown format can be set on a + per-file or per-comment basis with the +:markdown:+ directive like the rd + and tomdoc formats and on a per-project basis with + rdoc --markup markdown --write-options + * Removed global state from RDoc. RDoc::Store holds the documentation tree + and connects the driver to the parsers and generator. This also allows + documentation parsing and generation for multiple instances, but the rdoc + command-line tool does not support this. + + Due to this change RDoc::RDoc.current and RDoc::RDoc.reset no longer + exist. + +* Minor enhancements + * Added --root for building documentation from outside the source dir. + * Added a ChangeLog parser. It automatically parses files that begin + with 'ChangeLog' + * Added a table of contents to the sidebar. + * RDoc markup format merges adjacent labels in a label or note list into a + single definition list item for output. + * RDoc now tracks use of extend. Pull request #118 by Michael Granger. + * RDoc now tracks methods that use super. Pull request #116 by Erik + Hollensbe. + * Added methods ::system_dir, ::site_dir, ::home_dir and ::gem_dir to fetch + the components of RDoc::RI::Paths.path individually. + * Added support for rb_file_const. + * RDoc now processes files in sorted order. Issue #71 by Vít Ondruch + * RDoc now warns with --verbose when methods are duplicated. Issue #71 by + Vít Ondruch + * ri will display documentation for all methods in a class if -a is given. + Issue #57 by casper + * The RDoc coverage report will report line information for attributes, + constants and methods missing documentation. Issue #121 by Zachary Scott + * RDoc now reports a warning for files that are unreadable due to + permissions problems. + * RDoc controls documentation generation for RubyGems 2.0+ + +* Bug fixes + * A word that is directly followed by a multi-word tidy link label no longer + disappears. (Like text{link}[http://example]) + * Fixed legacy template support. Pull Request #107 by Justin Baker. + * An HTML class in a verbatim section no longer triggers ruby parsing. + Issue #92 by Vijay Dev + * Improved documentation for setting the default documentation format for + your ruby project. Issue #94 by Henrik Hodne + * Fixed handling of LANG in the RDoc::Options tests. Issue #99 by Vít + Ondruch + * RDoc no longer quits when given an entry that is not a file or directory. + Issue #101 by Charles Nutter + * Fixed bug in syntax-highlighting that would corrupt regular expressions. + Ruby Bug #6488 by Benny Lyne Amorsen. + * "class Object" no longer appears in the coverage report if all its methods + are documented. This suppresses a false positive for libraries that add + toplevel methods. Pull Request #128 by Zachary Scott. + * Fixed test_gen_url test name in TestRDocMarkupToHtml. Pull Request #130 + by Zachary Scott. + * Comment-defined methods ahead of define_method are now discovered. Issue + #133 by eclectic923 + * Fixed detection of define_method documentation. Issue #138 by Marvin + Gülker. + * Fixed lexing of character syntax (?z). Reported by Xavier + Noria. + * Add license to gem spec. Issue #144 by pivotalcommon + * Fixed comment selection for classes. Pull request #146 by pioz + * Fixed parsing of def self.&() end. Issue #148 by Michael + Lucy + * Generated RD parser files are now included in the gem. Issue #145 by + Marvin Gülker + * Class and module aliases now create new classes to avoid duplicate names + in the class list. Issue #143 by Richard Schneeman, Rails Issue #2839 + * RDoc::Markup::Parser now correctly matches indentation of lists when + multibyte characters are used in the list labels. Issue #140 by + burningTyger + * Fixed mangling of email addresses that look like labels. Issue #129 by + Tobias Koch + * Classes and modules in a C file may now be created in any order. Issue + #124 by Su Zhang + * A metaprogrammed method supports the :args: directive. Issue #100 + * A metaprogrammed method supports the :yields: directive. + * RDoc will now look for directives up to the end of the line. For example, + class B < A; end # :nodoc: + will now hide documentation of B. Issue #125 by Zachary Scott + * Fixed tokenization of % when it is not followed by a $-string type + * Fixed display of __END__ in documentation examples in HTML output + * Fixed tokenization of reserved words used as new-style hash keys + * RDoc now handles class << $gvar by ignoring the body + * Fixed parsing of class A:: B. + * Worked around bug in RDoc::RubyLex where tokens won't be reinterpreted + after unget_tk. + * Fixed class << ::Foo writing documentation to /Foo.html + * Fixed class ::A referencing itself from inside its own namespace. + +=== 3.12.2 / 2013-02-24 + +* Bug fixes + * Fixed bug in syntax-highlighting that would corrupt regular expressions. + Ruby Bug #6488 by Benny Lyne Amorsen. + * Fixed lexing of character syntax (?x). Reported by Xavier + Noria. + * Fixed tokenization of % when it is not followed by a $-string type + * Fixed display of __END__ in documentation examples in HTML output + * Fixed tokenization of reserved words used as new-style hash keys + * Fixed HEREDOC output for the limited case of a heredoc followed by a line + end. When a HEREDOC is not followed by a line end RDoc is not currently + smart enough to restore the source correctly. Bug #162 by Zachary Scott. + +=== 3.12.1 / 2013-02-05 + +* Bug fixes + * Fixed an XSS exploit in darkfish.js. This could lead to cookie disclosure + to third parties. See CVE-2013-0256[rdoc-ref:CVE-2013-0256.rdoc] for full + details including a patch you can apply to generated RDoc documentation. + * Ensured that rd parser files are generated before checking the manifest. + +=== 3.12 / 2011-12-15 + +* Minor enhancements + * Added DEVELOPERS document which contains an overview of how RDoc works and + how to add new features to RDoc. + * Improved title for HTML output to include --title in the + title element. + * rdoc --pipe now understands --markup. + * RDoc now supports IRC-scheme hyperlinks. Issue #83 by trans. + +* Bug fixes + * Fixed title on HTML output for pages. + * Fixed parsing of non-indented HEREDOC. + * Fixed parsing of %w[] and other % literals. Issue #84 by + Erik Hollensbe + * Fixed arrow replacement in HTML output munging the spaceship operator. + Issue #85 by eclectic923. + * Verbatim sections with ERB that match the ruby code whitelist are no + longer syntax-highlighted. Issue #86 by eclectic923 + * Line endings on windows are normalized immediately after reading with + binmode. Issue #87 by Usa Nakamura + * RDoc better understands directives for comments. Comment directives can + now be found anywhere in multi-line comments. Issue #90 by Ryan Davis + * Tidy links to methods show the label again. Issue #88 by Simon Chiang + * RDoc::Parser::C can now find comments directly above + +rb_define_class_under+. Issue #89 by Enrico + * In rdoc, backspace and ansi formatters, labels and notes without bodies + are now shown. + * In rdoc, backspace and ansi formatters, whitespace between label or note + and the colon is now stripped. + +=== 3.11 / 2011-10-17 + +* Bug fixes + * Avoid parsing TAGS files included in gems. Issue #81 by Santiago + Pastorino. + +=== 3.10 / 2011-10-08 + +* Major enhancements + * RDoc HTML output has been improved: + * The search from Володя Колесников's (Vladimir Kolesnikov) SDoc has been + integrated. + + The search index generation is a reusable component through + RDoc::Generator::JsonIndex + * The table of contents is now a separate page and now shows links to + headings and sections inside a page or class. + * Class pages no longer show the namespace and no longer have file info + pages. + * HTML output is HTML 5. + * Static files can be copied into RDoc using --copy-files + * RDoc supports additional documentation formats: + * TomDoc 1.0.0-rc1 + * RD format + + The default markup can be set via the --markup option. + + The format of documentation in a particular file can be specified by the + +:markup:+ directive. If the +:markup:+ directive is in the first comment + it is used as the default for the entire file. For other comments it + overrides the default markup format. + + The markup format can be set for rake tasks using RDoc::Task#markup + * RDoc can save and load an options file. + + To create an options file that defaults to using TomDoc markup run: + + rdoc --markup tomdoc --write-options + + This will create a .rdoc_options file. Check it in to your VCS and + package it with your gem. RDoc will automatically load this file and + combine it with the user's options. + + Some options are not saved. See RDoc::Options@Saved+Options for full + details. + +* Minor enhancements + * RDoc autoloads everything. You only need to require 'rdoc' now. + * HTML headings now have ids matching their titles. + + = Hello! + + Is rendered as + +

Hello!

+ + * Labels for classes or methods can be linked-to by adding an @ + following the class or method reference. For example, + RDoc::Markup@Links + + See RDoc::Markup@Links for further details. + * For HTML output RDoc uses +SomeClass.method_name+ and + +SomeClass#method_name+ for remote methods and attributes and + +::method_name+ and +#method_name+ for local methods. + * RDoc makes an effort to syntax-highlight ruby code in verbatim sections. + See RDoc::Markup@Paragraphs+and+Verbatim + * Added RDoc::TopLevel#text? and RDoc::Parser::Text to indicate a + parsed file contains no ruby constructs. + * Added rdoc-label link scheme which allows bidirectional links. + See RDoc::Markup for details. + * Image paths at HTTPS URLs will now be turned into ++ tags. Pull + Request #60 by James Mead + * Added RDoc::Comment which encapsulates comment-handling functionality. + * Added RDoc::Markup::PreProcess::post_process to allow arbitrary comment + munging. + * RDoc::RDoc::current is set for the entire RDoc run. + * Split rdoc/markup/inline into individual files for its component classes. + * Moved token stream HTML markup out of RDoc::AnyMethod#markup_code into + RDoc::TokenStream::to_html + * "Top" link in section headers is no longer inside the heading element. + * RDoc avoids printing some warnings unless run with `rdoc --verbose`. For + Rails issue #1646. + * Finishing a paragraph with two or more spaces will result in a line break. + This feature is experimental and may be modified or removed. + +* Bug fixes + * Markup defined by RDoc::Markup#add_special inside a is no + longer converted. + * Performance of RDoc::RubyLex has been improved. Ruby Bug #5202 by Ryan + Melton. + * Add US-ASCII magic comments to work with ruby -Ku. Issue #63 by + Travis D. Warlick, Jr. + * Clicking a link in the method description now works. Issue #61 by Alan + Hogan. + * Fixed RDoc::Markup::Parser for CRLF line endings. Issue #67 by Marvin + Gülker. + * Fixed lexing of percent strings like %r{#}. Issue #68 by eclectic923. + * The C parser now understands classes defined with + +rb_struct_define_without_accessor+ (like Range). Pull Request #73 by Dan + Bernier + * Fixed lexing of a b <<-HEREDOC. Issue #75 by John Mair. + * Added LEGAL.rdoc with references to licenses in other files. Issue #78 by + Dmitry Jemerov. + * Block parameters are displayed in Darkfish output again. Issue #76 by + Andrea Singh. + * The method parameter coverage report no longer includes parameter default + values. Issue #77 by Jake Goulding. + * The module for an include is not looked up until parsed all the files are + parsed. Unless your project includes nonexistent modules this avoids + worst-case behavior (O(n!)) of RDoc::Include#module. + +=== 3.9.5 / 2013-02-05 + +* Bug fixes + * Fixed an XSS exploit in darkfish.js. This could lead to cookie disclosure + to third parties. See CVE-2013-0256.rdoc for full details including a + patch you can apply to generated RDoc documentation. + +=== 3.9.4 / 2011-08-26 + +* Bug fixes + * Applied typo and grammar fixes from Luke Gruber. Ruby bug #5203 + +=== 3.9.3 / 2011-08-23 + +* Bug fixes + * Add US-ASCII magic comments to work with ruby -Ku. Issue #63 by + Travis D. Warlick, Jr. + * Image paths at HTTPS URLs are now turned into ++ tags. Pull + Request #60 by James Mead + * Markup defined by RDoc::Markup#add_special inside a is no + longer converted. + +=== 3.9.2 / 2011-08-11 + +* Bug fix + * Loosened TIDYLINK regexp to allow any content in the link section like: + {foo}[rdoc-ref:SomeClass] + * In HTML output headings are capped at
again + +=== 3.9.1 / 2011-07-31 + +* Bug fixes + * Fix RDoc::Markup parser for a header followed by a non-text token. Issue + #56 by Adam Tait + * Fix RDoc::Markup::ToHtmlCrossref#gen_url for non-rdoc-ref links. + * Fix bug report URL when rdoc crashes. + +=== 3.9 / 2011-07-30 + +* Minor enhancements + * RDoc::Parser::C now supports :doc: and :nodoc: for class comments + * Added the rdoc-ref: link scheme which links to a named reference. + rdoc-ref: can resolve references to classes, modules, methods, + files, etc. This can be used to create cross-generator named links unlike + the link: scheme which is dependent upon the exact file name. + Issue #53 by Simon Chiang + * Pulled RDoc::CrossReference out of RDoc::Markup::ToHtmlCrossref. + Cross-references can now be created easily for non-HTML formatters. +* Bug fixes + * `ri []` and other special methods now work properly. Issue #52 by + ddebernardy. + * `ri` now has space between class comments from multiple files. + * :stopdoc: no longer creates Object references. Issue #55 by Simon Chiang + * :nodoc: works on class aliases now. Issue #51 by Steven G. Harms + * Remove tokenizer restriction on header lengths for verbatim sections. + Issue #49 by trans + +=== 3.8 / 2011-06-29 + +* Minor enhancements + * RDoc::Parser::C can now discover methods on ENV and ARGF. + * RDoc::Parser::C now knows about rb_cSocket and rb_mDL. +* Bug fixes + * Updating Object in an ri data store with new data now removes methods, + includes, constants and aliases. + +=== 3.7 / 2011-06-27 + +* Minor enhancements + * New directive :category: which allows methods to be grouped into sections + more cleanly. See RDoc::Markup for details. + * Document-class for RDoc::Parser::C now supports Foo::CONST as well as + CONST. + * ri method output is now a comma-separated list when displayed + interactively. Pull Request #39 by Benoit Daloze. + * RDoc::ClassModule#merge now prefers the argument's information over the + receiver's (it now behaves like Hash#merge! instead of a backwards + Hash#merge!). + * RDoc::Markup#convert now accepts an RDoc::Markup::Document instance + * RDoc now owns the code for generating RDoc and ri data when gems install + * Added RDoc::RDoc::reset + * Added RDoc::CodeObject#file_name +* Bug fixes + * ri no longer crashes when attempting to complete a plain [. + * ri data now tracks which file information came from so it can process + removals and changes to: + * Classes and Modules + * Methods + * Attributes + * Includes + * Constants + You will need to rebuild your ri data for it to update properly. Issue + #21 by Sven Riedel + * Signal and SignalException no longer clobber each other + * RDoc::Parser::C no longer creates classes when processing aliases. + * RDoc::Text#strip_stars handles Document-method for methods with =, ! and ? + now. + * RDoc::Parser::C now allows .cpp files to be used with the "in" comment on + rb_define_method. Bug #35 by Hanmac. + * RDoc::Parser::Ruby no longer eats content when =begin/=end documentation + blocks are followed by a documentable item. Issue #41 by mfn. + * RDoc::Markup::Formatter and subclasses now allow an optional +markup+ + parameter for adding custom markup. The example in + RDoc::Markup::Formatter will now work. Issue #38 by tsilen. + * RDoc::Parser::C can now distinguish between class methods and instance + methods in Document-method. Issue #36 by Vincent Batts. + * RDoc now encodes file names in the output encoding. Issue #33 by Perry + Smith. + * ri data generation for method aliases no longer duplicates the class in + #full_name + +=== 3.6.1 / 2011-05-15 + +* Bug fixes + * Fix infinite loop created when re-encountering BasicObject. + * RDoc::Context#each_ancestor is now provided for duck-typing. + * rb_path2class() can now be used to discover the parent class in + rb_define_class_under. + +=== 3.6 / 2011-05-13 + +* Major Enhancements + * Interactive ri is now the default when no names are given. +* Minor Enhancements + * RDoc::RDoc#generate was added to allow multiple generators to be used with + a set of parsed file info. + * RDoc::Options#finish can be called multiple times now. + * `ri -i` only shows one level of namespace when completing class names. + * Added `ri --list` for explicit listing. `ri -l F G` will list all classes + or modules starting with F or G +* Bug fixes + * Remove windows-specific test for test_check_files, it is too hard to do. + Ruby commit r30811 by Usaku Nakamura. + * Remove unnecessary (and wrong) platform-dependent hacks. Ruby commit + r30829 by Usaku Nakamura. + * Completing via Array#[ in `ri -i` no longer crashes. Ruby Bug #3167 + * Completing IO::o in `ri -i` now returns results. Ruby Bug #3167 + * RDoc::Parser::C ignores prototypes better. Pull Request #34 by Pete + Higgins. + * private_class_method and public_class_method are now parsed correctly for + inherited methods. Issue #16 by gitsucks. + * The doc directive now forces documentation even when the method is marked + private or protected. + +=== 3.5.3 / 2010-02-06 + +* Bug fixes + * When including a file perform a lossy force-transcoding to the output + encoding instead of crashing to preserve as much content as possible. + Ruby Bug #4376 by Yui NARUSE. + * Work around inconsistent encoding result from String#sub!, String#gsub!. + Related to Ruby Bug #4376. + * Work around inconsistent encoding result from String#[]=. Related to Ruby + Bug #4376. + * When Darkfish fails the file being generated is now reported. + +=== 3.5.2 / 2010-02-04 + +* Deprecations + * RDoc::Context::Section#sequence is now deprecated. Use + RDoc::Context::Section#aref instead. + +* Bug fixes + * Fixed syntax highlighting CSS class generation. Reported by Daniel + Bretoi. + * Fixed ri for methods with aliases. Pull Request #15 by Sven Riedel. + * Added windows-specific test for test_check_files. + * Darkfish now supports sections. Template and generator author see + RDoc::Context#each_section to add section support. RubyForge Bug #26883 + by Jeff Hodges. + * Fixed post-install message for Ruby 1.9.2 users. + * Set required ruby version to >= 1.8.7. + +=== 3.5.1 / 2010-01-30 + +* Bug fixes + * Fixed some typos. Pull request #13 by R.T. Lechow. + * Ensure an RDoc::Stats is created in #parse_files. Fixes documentation for + railties which has no files. Reported by Aaron Patterson + +=== 3.5 / 2010-01-29 + +* Minor enhancements + * RDoc::Parser::C looks for rb_scan_args and fills in RDoc::AnyMethod#params + appropriately. This may provide useful information if the author did not + provide a call-seq. + * RDoc::Parser::C now records the function name for methods implemented in + C. + * RDoc now records file and byte offset information for methods. +* Bug fixes + * Locations of module aliases are now recorded. + * RDoc::Parser::C finds method bodies better now. + * Fixed further locations where output encoding was not preserved. Bug #11 + by Vít Ondruch, RubyForge bug #28791 by Dzmitry Prakapenka. + * Fixed display of numeric lists on the index page and file pages. Bug #12 + by tobijk. + * Skip TestRDocOptions#test_check_files on windows until a windows-specific + test can be created. RubyForge bug #28821 by Usaku Nakamura. + * Fixed line-height of headings in method and alias descriptions. RubyForge + Bug #2770 by Adam Avilla + * Relaxed RDoc::Parser::Ruby#remove_private_comments to consume more dashes + as older versions once did. Bug #7 by Claus Folke Brobak. + +=== 3.4 / 2010-01-06 + +* Minor enhancements + * RDoc::RDoc#document may now be called with an RDoc::Options instance. +* Bug fixes + * Added skips to Encoding tests running on 1.8. + * Fixed warnings + +=== 3.3 / 2010-01-03 + +* Minor enhancements + * The coverage report can now report undocumented method parameters + including methods defined in C. + + rdoc -C gives a standard report, rdoc -C1 includes + method parameters. Method parameters are considered documented if they're + marked-up with +, or . + * The C parser now uses *args instead of ... if no + call-seq was provided to give names to the arguments. +* Bug fixes + * The C parser now records the file location of aliases, attributes, + constants and methods allowing -C to work on C files. + * Darkfish now handles dots in call-seq allowing ary.insert(index, + obj...) to display correctly. Patch #6 by KUBO Takehiro. + * Improved processing of meta-programmed methods when followed by unparseable + syntax. RubyForge patch #28653 by Aidan Cully. + * rdoc now touches the flag file when it create the output directory. + Prevents the "isn't an RDoc directory" error if rdoc crashes. + * RDoc now properly converts to the expected output encoding. RubyForge bug + #28791 by Dzmitry Prakapenka. + * Restored parsing of block comments. RubyForge bug #28668 by Stefano Crocco. + * Metaprogrammed methods defined with blocks no longer confuse the ruby + parser. RubyForge bug #28370 by Erik Hollensbe. + * ri no longer displays all methods in the inheritance chain. + +=== 3.2 / 2010-12-29 + +* Minor enhancements + * RDoc generator authors may now suppress updating the output dir (creating + a created.rid file) by setting RDoc::Options#update_output_dir to false. + * RDoc::Task has been refactored to ease creating subclasses. +* Bug fixes + * RDoc's gitignore now ignores .DS_Store files. Pull Request #3 by Shane + Becker. + +=== 3.1 / 2010-12-28 + +RDoc has moved to github. Releases after 3.1 reference github unless +otherwise noted. + +* Minor enhancements + * RDoc::Task now features a #generator option to choose an alternate + generator. Pull Request #2 by Erik Hollensbe. + * Enhanced test for RDoc::Parser::binary? RubyForge patch #28538 by Eito + Katagiri. + * Generator list in --help is no longer static. Generator description comes + from the generator's DESCRIPTION constant. + * Documentation summary is now displayed with dynamic width. +* Bug fixes + * Strip encoding comment from input to avoid overriding file comment. + RubyForge Bug #22113 by James Gray. + * Restore call-seq parsing behavior when the call-seq is the only comment. + RubyForge Bug #26290 by Sylvain Joyeux. + * Coverage report no longer crashes for constant aliases. Pull Request #1 + by Andy Lindeman. + * RDoc no longer loses ghost methods when followed by certain tokens. + RubyForge bug #27793 by Aaron Patterson. + * RDoc no longer crashes in ri if HOME is not set. Ruby Bug #4202 by + Shyouhei Urabe. + * ri no longer crashes with HTML format output. RubyForge bug #28675 by + 7rans. + * RDoc::Markup::ToHtml#gen_url now initializes #from_path to ''. + Additionally, #from_path is now settable. RubyForge bug #27838 by Claus + Folke Brobak. + * Comments in the C parser are now normalized before being combined. + RubyForge patch #28646 by Sven Herzberg. + * RDoc::Parser::C no longer requires a comment and finds more method bodies. + RubyForge patch #28643 by Sven Herzberg. + * Darkfish now has a "Class/Module Index" instead of a "Class Index". + RubyForge patch #28364 by James Tucker. + * RDoc::Parser::Ruby now parses negative numbers correctly. RubyForge patch + #28544 by Eito Katagiri. + +=== 3.0.1 / 2010-12-19 + +* Bug fix + * RDoc no longer has a Perl parser. + +=== 3.0 / 2010-12-19 + +Special thanks to Thierry Lambert for massive improvements to RDoc. + +* Major enhancements + * Ruby 1.8.6 is no longer supported by RDoc. + * RDoc now converts input files to a single encoding specified by + --encoding. See RDoc::RDoc and RDoc::Options#encoding. + --encoding is now preferred over --charset + * RDoc now supports a --coverage-report flag (also -C and + --dcov) that outputs a report on items lacking documentation. + * Templates (rdoc -T) are now checked for existence in + RDoc::Options. Generator authors can now use RDoc::Options#template_dir + which is the full path to the template directory. + * Added support for class aliases. Patch by Thierry Lambert. + * Improved merging of classes and modules across multiple files including + more accurate documentation statistics. Patch by Thierry Lambert. + * Improved handling of method aliases. Patch by Thierry Lambert. + * Improved handling of visibility of RDoc code objects. Patch by Thierry + Lambert. + * RDoc::Attr#type is now RDoc::Attr#definition. Patch by Thierry Lambert. + * Removed TimeConstantMethods + * RDoc now calls ::new instead of ::for on generators. +* Minor enhancements + * Added rdoc arguments --dry-run, --all, + --visibility, --force-output, --hyperlink-all. + Patch by Thierry Lambert. + * RDoc::Markup::FormatterTestCase has been expanded. Patch by Thierry + Lambert. + * RDoc::Markup::TextFormatterTestCase has been extracted from RDoc tests. + Patch by Thierry Lambert. + * Various RDoc::Parser::Ruby enhancements. Patch by Thierry Lambert. + * Various RDoc::Markup::Parser enhancements. Patch by Thierry Lambert. + * RDoc::Parser::binary? is more robust now that it uses Encoding. + * Deprecated rdoc arguments are now explicitly mentioned in rdoc command + output. Patch by Thierry Lambert. + * Constant values are formatted more accurately. Patch by Thierry Lambert. + * Enhanced call-seq parsing in RDoc::Parser::C. Patch by Thierry Lambert. + * RDoc no longer uses kw, cmt, re or str classes for embedded source code + snippets. Patch by Thierry Lambert. + * RDoc directives may now be escaped with a leading '\\'. Patch by Thierry + Lambert. + * RDoc note lists (label::) now generate a table with class + "rdoc-list". Patch by Thierry Lambert. + * RDoc markup documentation has been moved to RDoc::Markup including notes + on how to document source code. + * An RDoc::Require is now always listed at the file level. Patch by Thierry + Lambert. + * RDoc::CodeObjects now know which file they were defined in. + * RDoc::Options calls ::setup_options on the generator class specified by + --format. See RDoc::Options::setup_generator. + * rdoc gives an error when multiple formats are given. + * Files with erb inside will no longer trip RDoc::Parser::binary? + * Last --title wins. Patch by Thierry Lambert. + * Better block params handling. Patch by Thierry Lambert. + * Moved rdoc/tokenstream.rb to rdoc/token_stream.rb. + * Moved rdoc/markup/preprocess.rb to rdoc/markup/pre_process.rb. + * Removed "':' not followed by operator or identifier" warning for new Hash + syntax. + * rb_attr() is now supported for attributes. + * RDoc::Parser::C now supports yields, doc, and args directives like + RDoc::Parser::Ruby. + * Moved RDoc::Parser::PerlPOD to the rdoc-perl_pod gem. +* Bug fixes + * RDoc::Generator tests no longer require any installed RDoc on Ruby 1.9 + * Load existing cache before generating ri. Ruby r27749 by NAKAMURA Usaku. + * RDoc now handles BOM. Ruby r28062 by Nobuyoshi Nakada. + * Use proper XML encoding for darkfish classpage. Ruby r28083 by NARUSE, + Yui. + * Fix ri output when special characters are inside html tags. Patch by Tomo + Kazahaya, Ruby Bug #3512. + * Don't bother checking if the pager exists, it's already done. Ruby r28842 + by NAKAMURA Usaku. + * RDoc::Parser::Ruby now ignores non-constant-named singleton classes. Ruby + r29140 by Nobuyoshi Nakada. Ruby Bug #3759. + * RDoc::Parser::Ruby call args no longer include assignment. Ruby r29141 by + Nobuyoshi Nakada. Ruby Bug #3759 + * Handle $HOME being unset in ri. Ruby r29272 by Nobuyoshi Nakada. + * uniq ancestors and modules too. Ruby r29312 by Nobuyoshi Nakada. + * RDoc now knows about Encoding by default. Ruby r29356 by Nobuyoshi + Nakada. + * ri now defaults to the backspace formatter when piped. Use RI environment + variable or options to override. Ruby r28455 by Yusuke Endoh. + * __send__ and friends no longer get their underscores removed. Patch by + Thierry Lambert. + * The C parser now makes new public when promoting initialize. + * Fix crash in #markup_code for TkUnknownChar. + * Fix crash in RDoc::Parser::C when aliasing methods with Regexp special + characters. + * Fix crash when various operators are used as a name as in + alias * compose. + * Fix warning with some dynamic use of attr_* + * Methods added to true, false and nil are now documented. + * Remove warning for methods defined on globals. + +=== 2.5.11 / 2010-08-20 + +* Minor Enhancements + * Alias comments are now discovered by the C parser. Reported by Jeremy + Evans. + * Removed --all option which is unused in RDoc. Use the nodoc or + stopdoc/startdoc directives to suppress documentation instead. + +=== 2.5.10 / 2010-08-17 + +* Minor Enhancements + * Support rb_singleton_class(). Reported by Jeremy Evans. + * Support rb_define_private_method() on rb_singleton_class(). Reported by + Jeremy Evans. + +* Bug Fixes + * Treat non-ASCII RDoc files as text. Bug #28391 by Kouhei Sutou. + * Fix potential test failures due to ivar collision. Bug #28390 by Kouhei + Sutou. + * Added duck-typed #aref for RDoc::Attr to RDoc::AnyMethod. Bug #28375 by + Erik Hollensbe + * Fixed method references in HTML output when show_hash is false. + * Fixed comments with '.' in call-seq in C sources. Reported by Jeremy + Evans. + * RDoc now understands singleton aliases. Reported by Jeremy Evans. + +=== 2.5.9 / 2010-07-06 + +* Bug Fixes + * Look up pager correctly. + * Fixed handling of bullets in verbatim sections. Partial patch by + Juha-Jarmo Heinonen. + +=== 2.5.8 / 2010-04-27 + +*NOTE*: + +RDoc 2.5 did not save method parameters, so you should upgrade your rdoc-data +gem to a version >= 2.5.3. + +To have ri data for core and stdlib you'll need to: + + gem install rdoc-data + +then run: + + rdoc-data --install + +To have ri data for you gems you'll also need to run: + + gem rdoc --all --overwrite + +If you don't want to rebuild the rdoc for `gem server`, add --no-rdoc. + +* Bug Fixes + * ri no longer complains about nonexistent pagers. + * Fixed failing test + +=== 2.5.7 / 2010-04-22 + +* Minor Enhancements + * Unrecognized RDoc directives can now be registered by a plugin for + handling. See RDoc::Markup::PreProcess. + * Added RDoc::Markup::Raw to allow other markup engines to dump raw content + into RDoc. +* Bug Fixes + * rdoc -p no longer means --pipe if files are also given. + * RDoc now knows about BasicObject by default. Ruby Bug #1318 by Ambrus Zsbán + +=== 2.5.6 / 2010-04-22 + +* Minor Enhancements + * Unrecognized RDoc directives are added as metadata to the object they get + attached to. + + ## + # :my_new_directive: my cool value + + Results in a 'my_new_directive' metadata key with value 'my cool value' on + the RDoc::CodeObject it is for +* Bug Fixes + * RDoc no longer prints out "invalid options:" when there were no invalid + options. + * Fixed link size on Darkfish file pages + +=== 2.5.5 / 2010-04-19 + +* 1 Minor Enhancement + * Use #binread in RDoc::Markup::PreProcess. Patch from ruby trunk. +* 3 Bug Fixes + * Fixed indentation of method-description lists in Darkfish. Bug #28081 by + Theresa Dwinnell. + * Fixed loading RDoc::AnyMethod aliases to no longer infinitely loop. Bug + #28107 by Sven Riedel + * Fixed handling of ignored invalid options to continue after the invalid + option. + +=== 2.5.4 / 2010-04-18 + +* 2 Minor Enhancements + * Methods will now be cross-referenced when preceded with ::. Ruby Bug + #3169 by Marc-Andre Lafortune. + * Methods now have human readable fragment identifiers for HTML output. + (#method-i-gsub vs #M000005). Ruby Bug #3023 by Marc-Andre Lafortune. +* 1 Bug Fixes + * RDoc::Parser::Ruby now handles while begin a; b end # .... + Ruby Bug #3160 by Yusuke Endoh. + +=== 2.5.3 / 2010-04-10 + +* 1 Minor Enhancement + * RDoc::Parser::Simple and the include directive remove coding: comment from + first line +* 2 Bug Fixes + * Fixed loading of created.rid when regenerating documentation. Ruby bug + #3121 by Yusuke Endoh. + * Compare times as Integers as created.rid doesn't store fractional times. + +=== 2.5.2 / 2010-04-09 + +* 1 Minor Enhancement + * Imported various changes by Nobu from ruby trunk. +* 2 Bug Fixes + * RDoc parses files without extensions as text files again. + * RDoc::Parser::Ruby parses %{ strings correctly again. + +=== 2.5.1 / 2010-04-06 + +* 1 Minor Enhancement + * RDoc::Parser::C now supports the include directive for classes and + modules. +* 6 Bug Fixes + * RDoc::AnyMethod params now get saved in ri data. + * ri now displays method arguments correctly. + * RDoc::Markup::Parser allows no space between = and header text like rdoc + 2.4 and earlier. + * RDoc::Parser::C's "in" directive now looks in the current directory. + * RDoc::Task's rerdoc task no longer deletes the doc directory twice. + * rdoc --force-update now works correctly. Patch by Nobu Nokada + +=== 2.5 / 2010-03-31 + +* 9 Major Enhancements + * Darkfish now has a "Home" button + * ri no longer displays the value of a constant. There's no easy way to + make them presentable. Use irb or ruby -e instead. Ruby Bug #549. + * New ri data format now uses Marshal and pre-builds caches + * No support for old ri data format, too hard to maintain + * To upgrade your core ri documentation, install the rdoc-data gem and run + rdoc-data + * RDoc now displays how well you've documented your library + * New recursive-descent parser for RDoc::Markup. See RDoc::Markup::Parser + * Updated ruby_lex and ruby_token + * Removed threading support, RDoc is not thread-safe + * Removed many unsupported options to rdoc + * Future versions of RDoc will not support Ruby 1.8.6. Bugs filed for + 1.8.6-only issues will be (largely) rejected. + +* 17 Minor Enhancements + * Source Parsing + * RDoc now supports module aliasing via constant assignment. + * RDoc now tracks superclasses correctly. Fixes File < IO for core docs. + * RDoc now ignores methods inside methods. + * RDoc now ignores Marshal and other binray files. + * Removed "Skipping require of dynamic string" warning. + * C parser now handles Document-method better. Bug #27329. + * API enhancements for writing parsers like the Ruby parser, see + RDoc::Parser::RubyTools + * ri + * Uses pager over less and more for Debian. Ruby Bug #1171. + * ri will use the RI_PAGER environment variable to find a pager. + * ri data generator now supports SIGINFO (^T) + * When rdoc is in debug mode, ^C now prints a backtrace + * RDoc::Markup::AttributeManager no longer uses global state. + * RDoc::RDoc no longer passes around options. Patch #27167. + * Darkfish won't generate a file if its template is missing. Patch #25857. + * Improved some wording for the RDoc main page. Patch #27264, #27268. + * Removed diagram generation support (to return in the future). + * Removed external support for RDoc::Task. + +* 12 Bug Fixes + * The :attr: directives now use the name given to create an attribute. See + RDoc::Parser::Ruby#parse_meta_attr. + * Fix crossrefs on paths with '-'. Ruby Bug #883. + * Fix ruby parser for alias with = in the name. Bug #27522. + * Images are no longer executable. Bug #27156. + * --op is no longer overridden by --ri. Bug #27054. + * :method: now works when at the end of a class. Bug #26910. + * Preserve ellipsis from call-seq in Darkfish. Patch #26974. + * Emacs-style coding: is handled properly. Patch #27388. + * RDoc::RubyLex now parses UTF-8 identifiers. Bug #26946, #26947. + * Fixed namespace lookup rules. Bug #26161. + * Worked around bug in Selenium where they hide a .jar in a .txt file. + Filed Selenium bug #27789. + * Alias comments are no longer hidden. Reported by Adam Avilla. + +=== 2.4.3 / 2009-04-01 + +* 2 Bug Fixes + * Corrected patch for file links + * Corrected display of file popup + +=== 2.4.2 / 2009-03-25 + +* 2 Minor Enhancements + * Added --pipe for turning RDoc on stdin into HTML + * Added rdoc/task.rb containing a replacement for rake/rdoctask.rb. Use + RDoc::Task now instead of Rake::RDocTask. + +* 10 Bug Fixes + * Writing the ri cache file to the proper directory. Bug #24459 by Lars + Christensen. + * Possible fix for Dir::[] and Pathname interaction on 1.9. Bug #24650 by + tiburon. + * Fixed scanning constants for if/end, etc. pairs. Bug #24609 by Ryan + Davis. + * Fixed private methods in the C parser. Bug #24599 by Aaron Patterson. + * Fixed display of markup on RDoc main page. Bug #24168 by rhubarb. + * Fixed display of \\ character in documentation proceeding words. + Bug #22112 by James Gray. See RDoc for details. + * Fixed parsing and display of arg params for some corner cases. Bug #21113 + by Csiszár Attila. + * Fixed links in Files box. Patch #24403 by Eric Wong. + * Toplevel methods now appear in Object. Bug #22677 by Ryan Davis. + * Added back --promiscuous which didn't do anything you cared about. Why + did you enable it? Nobody looked at that page! Oh, it warns, too. + +=== 2.4.1 / 2009-02-26 + +* 1 Minor Enhancements + * Added :attr:, :attr_reader:, :attr_writer:, :attr_accessor: directives. + Replaces --accessor. See RDoc::Parser::Ruby for details. + +* 3 Bug Fixes + * Don't complain when exiting normally. Bug by Matt Neuburg. + * Restore --inline-source that warns + * Fixed links to files in Darkfish output + +=== 2.4.0 / 2009-02-24 + +* 9 Minor Enhancements + * `ri -f html` is now XHTML-happy + * Clarified RDoc::Markup link syntax. Bug #23517 by Eric Armstrong. + * Number of threads to parse with is now configurable + * Darkfish can now use alternate templates from $LOAD_PATH via -T + * Removed F95 parser in favor of the rdoc-f95 gem + * Moved HTML and XML generators to unmaintained + * No gem will be provided as it's too difficult to make them work + * Removed options --one-file, --style=, --inline-source, --promiscuous, + --op-name + * Removed support for --accessor, use regular documentation or + the method directive instead. See RDoc::Parser::Ruby + * Removed --ri-system as it is unused by Ruby's makefiles + * Added method list to index.html + +* 6 Bug Fixes + * A class marked nodoc no longer appears in the index. Bug #23751 by + Clifford Heath. + * Fix 1.9 compatibility issues. Bug #23815 by paddor. + * Darkfish now respects --charset + * RDoc no longer attempts to be lazy when building HTML. This is a + workaround. Bug #23893 by Stefano Crocco. + * RDoc doesn't crash with def (blah).foo() end + * RDoc doesn't crash with #define functions + +=== 2.3.0 / 2009-01-28 + +* 3 Major Enhancements + * Michael Granger's Darkfish generator is now the default for HTML output + * Various rdoc generation speedups by Hongli Lai. Patches #22555, #22556, + #22557, #22562, #22565. + * rdoc/discover.rb files are loaded automatically from installed gems + +* 8 Minor Enhancements + * Added a space after the commas in ri class method lists. RubyForge + enhancement #22182. + * Improved ri --interactive + * Generators can now override generated file locations + * Moved unmaintained CHM generator to it's own package + * Moved unmaintained extra HTML templates to their own package + * Removed experimental texinfo generator + * Converted to minitest + * Known classes and modules list outputs once per line now for grep + +* 11 Bug Fixes + * Fix missing superclass in ri output + * Fix an RDoc crash when told to parse an empty file + * Ignore nonexistent files instead of crashing + * .txt and .rdoc files are always considered text. Patch #22897 by Aaron + Patterson. + * When merging ri data with a nonexistent directory, RDoc no longer crashes + * Fix visibility of methods in XML output. Issue by Yehuda Katz. + * Fixed relative link generation + * Fix crash, RDoc now ignores comments above local variable assignments in + modules + * RDoc now only accepts adjacent comments for rb_define_module and + rb_define_class + * C file RDoc is no longer included in token stream + * Scan all gem paths to match gem name for ri output + +=== 2.2.1 / 2008-09-24 +This version provides some minor fixes and enhancements to 2.2.0 intended +to polish RDoc for Ruby 1.9.1. + +* 3 Minor Enhancements + * Support for parsing RDoc from SWIG. Ruby patch #10742 by Gonzalo + Garramuno, #13993 by Steven Jenkins. + * Simple support for Perl POD documentation. Patch by Hugh Sasse. + * Changed the default character set of RDoc's output from iso-8859-1 to + utf-8. + +* 9 Bug Fixes + * Explicitly set the html template's text color, so that the generated + documentation will display correctly on browsers with custom text and + background color settings (patch by Luther Thompson). + * Ensure that RDoc correctly will associate an alias and a method, even + if it encounters the alias first because the alias lives in a different + file. + * Fix the parsing of multiline constants (patch by Chris Alfeld and + Joel VanderWerf) + * Make --exclude usuable. Ruby patch #11671 by Trans. + * Detect inline C functions. Ruby Bug #11993 by Florian Frank. + * Fix an issue in which RDoc might not document a class' + superclass correctly if the class was defined in multiple files and + depending on the order in which RDoc processed the files. This should + ensure that the child class -> parent class relationship is correct in + ri documentation, allowing ri to lookup inherited methods (i.e., File.read). + * Stop ri from crashing when it looks for a completely bogus method (i.e., + File#reada). Now, ri exits with a helpful error message. + * Fixed missing display of constant values in ri. + * Fixed display of constants in ri's html output. + +=== 2.2.0 / 2008-09-19 +This version includes some significant enhancements to ri. See RI.txt for +documentation about ri. + +* 5 Major Enhancements + * More extensive unit tests (special thanks to Chris Lowis for contributing + a test). + * Made ri twice as fast for the most common use case of displaying + information for a class or a fully-qualified method + (i.e., ri Array#flatten, after ri has created a cache the first time that + it runs). + * Made ri many times faster when searching for an unqualified method (i.e., + ri read, again after the first such search has populated ri's cache) + * Changed ri to do regular expression searches for unqualified methods; + now, a regular expression for a method can be passed to ri on the + command-line. + * Added an interactive mode to ri (patch by Daniel Choi). Now, when ri + is given a -i argument, it will allow the user to disambiguate + unqualified methods if more than one is present and also will allow a + user to get information for a class' method. + +* 8 Minor Enhancements + * RDoc now adds the package title to the web pages that it generates + for files and classes/modules, which helps them appear better in + search engine results. + * RDoc now automatically generates cross-reference links for classes and + methods specified relative to the global namespace (i.e., ::A::B::C#method). + * All built-in templates now output valid, strict XHTML. + * The documentation is slightly better organized (the markup details were + merged into the RDoc module's documentation). + * Improved rdoc's HTML generation speed by about 20% (on Windows, the + boost seems larger). + * Provided an ri command-line option to control its caching behavior. + * Improved RDoc's documentation. Added RI.txt to document ri. + * Allow HTML templates distributed as gems to be loaded with the -T option, + just like the standard templates in rdoc/generator/html (so an HTML + template lib/new_template.rb in a gem can be used with rdoc -T new_template) + +* 25 Bug fixes: + * Fixed prototype detection in C parser. Can process ruby 1.8 C files + again. + * Fixed the main page for frameless template. Patch by Marcin Raczkowski. + * Fixed the main page for frame templates. Now, if no main page is + specified, RDoc will default to the README. + * Fixed missing stylesheet in generated chm. Patch by Gordon Thiesfeld. + * Fixed the parsing of module names starting with '::'. Patch by + Giuseppe Bilotta. + * Fixed a case where RDoc first would encounter Foo::Bar and then would + encounter class Foo. Previously, RDoc erroneously would have considered + that both a Foo class and a Foo module existed. + * Fix a class where RDoc would not generate correct cross-reference links + to a class contained within a module of the same name (i.e. RDoc::RDoc) + * Prevented RDoc from trying to parse binary files, which would produce + garbage output. + * RDoc now correctly converts ' characters to apostrophes, opening single + quotes, and closing single quotes in most cases (smart single quotes). + * RDoc now correctly converts " characters to opening double quotes and + and closing double quotes in most cases (smart double quotes). + * (c) correctly is converted into the copyright symbol. + * '&' characters in text now correctly are translated to HTML character codes. + * Fixed missing stylesheet in generated chm. Patch by Gordon Thiesfeld. + * Fixed broken method links in the built-in templates. + * RDoc properly links to files and classes in the one page HTML template. + * The kilmer and hefss templates properly syntax highlight when inlining + source code. + * The kilmer and hefss template class pages properly display methods again. + * Fixed broken class, file, and method links in the frameless template. + * Fixed the clipping of source code in the html and frameless templates when + the source code cannot fit into the window; a scrollbar now will allow + all of the source code to be viewed. + * Fixed the missing constant descriptions in the html and frameless + templates. + * Fixed the ri command-line options that customize the directories to be + searched for documentation. + * Fixed the XML generator. Patch by Anthony Durity. + * Stopped the XML template from generating invalid XML due to malformed + embedded ruby. + * Adding missing information about a class' constants to the XML template. + * Fixed the horizontal rule markup (---) so that it correctly adds a + horizontal rule rather than suppressing all text that follows. + +=== 2.1.0 / 2008-07-20 + +* 3 Major Enhancements: + * RDoc now knows about meta-programmed methods, see RDoc::Parser::Ruby + * Reorganized parsers under RDoc::Parser base class + * ri now walks the ancestors of a class looking for a method e.g. ri + File#read displays documentation for IO#read (may require regeneration of + ri data) +* 5 Minor Enhancements: + * Allow links to files + * Default options now taken from RDOCOPT environment variable + * Class method documentation can be found at toplevel now (def X.foo) + * Allow HTML templates distributed as gems to be loaded with the -T option, + just like the standard templates in rdoc/generator/html (so an HTML + template lib/new_template.rb in a gem can be used with rdoc -T new_template) + * `rdoc -v` prints out files, classes, modules and methods as it goes +* 11 Bug Fixes: + * `ri Foo.bar` now looks for class methods also + * Sections work in the default template again + * Doesn't warn about :foo:: list item being an unrecognized directive + * RDoc no longer converts characters inside tt tags + * Fixed "uninitialized constant RDoc::Markup::ToHtml::HTML" + * Fixed generation of relative links + * Fixed various diagram generation issues + * Fixed templates broken by switch to erb + * Fixed issue with style comments + * Lowercase words are no longer rdoc'd as methods without leading #, as + described in the documentation + * RDoc now correctly sets superclasses if they were originally unknown + +=== 2.0.0 / 2008-04-10 + +* 3 Major Enhancements: + * Renamespaced everything RDoc under the RDoc module. + * New `ri` implementation. + * Reads from a cache in ~/.ri/ for enhanced speed. + * RubyGems aware, only searches latest gem versions. + * Now up to over 100 tests and 200 assertions. +* 4 Minor Enhancements: + * Switched to an ERb-based TemplatePage, see RDoc::TemplatePage. + * Class/module ri now displays attribute and constant comments. + * Cross-references can be disabled with a leading \. + * Relaxed parsing for some RDoc inline markup. diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/LEGAL.rdoc b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/LEGAL.rdoc new file mode 100644 index 0000000..431e698 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/LEGAL.rdoc @@ -0,0 +1,50 @@ +# coding: UTF-8 + += Legal Notice Information + +The files in this distribution are covered by the Ruby license (see LICENSE) except the features mentioned below: + +Darkfish:: + Darkfish was written by Michael Granger and is included under the MIT + license. Darkfish contains images from the Silk Icons set by Mark James. + + See lib/rdoc/generator/darkfish.rb for license information. + + * lib/rdoc/generator/darkfish.rb + * lib/rdoc/generator/template/darkfish/* + * lib/rdoc/generator/template/darkfish/images + +SDoc:: + Portions of SDoc by (Володя Колесников) Vladimir Kolesnikov are included + under the MIT license as RDoc::Generator::JsonIndex. See + lib/rdoc/generator/json_index.rb for license information. + + * lib/rdoc/generator/json_index.rb + * lib/rdoc/generator/template/json_index/* + * The +#search_index+ methods on RDoc::CodeObject subclasses were derived + from sdoc. + * RDoc::ClassModule#document_self_or_methods comes from SDoc. + +peg-markdown:: + RDoc's Markdown support is derived from peg-markdown by John MacFarlane. It + is used under the MIT license. See RDoc::Markdown for license details. + +MarkdownTest:: + test/test_rdoc_markdown_test.rb uses MarkdownTest 1.0.3's source files which + are included as test/MarkdownTest_1.0.3/*.text which are Copyright (c) + 2004-2005 John Gruber http://daringfireball.net and is included under the + same terms as Perl itself. + + See http://dev.perl.org/licenses/ for the terms of the Perl license. + +Fonts:: + Source Code Pro is (c) 2010, 2012 Adobe Systems Incorporated. + + Lato is (c) 2010 Łukasz Dziedzic. + + Both fonts are used under the SIL Open Font License, Version 1.1. The + license is available at http://scripts.sil.org/OFL + + See lib/rdoc/generator/template/darkfish/fonts.css for complete copyright + and license information, including a copy of the OFL. + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/LICENSE.rdoc b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/LICENSE.rdoc new file mode 100644 index 0000000..683585a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/LICENSE.rdoc @@ -0,0 +1,57 @@ +RDoc is copyrighted free software. + +You can redistribute it and/or modify it under either the terms of the GPL +version 2 (see the file GPL), or the conditions below: + +1. You may make and give away verbatim copies of the source form of the + software without restriction, provided that you duplicate all of the + original copyright notices and associated disclaimers. + +2. You may modify your copy of the software in any way, provided that + you do at least ONE of the following: + + a. place your modifications in the Public Domain or otherwise + make them Freely Available, such as by posting said + modifications to Usenet or an equivalent medium, or by allowing + the author to include your modifications in the software. + + b. use the modified software only within your corporation or + organization. + + c. give non-standard binaries non-standard names, with + instructions on where to get the original software distribution. + + d. make other distribution arrangements with the author. + +3. You may distribute the software in object code or binary form, + provided that you do at least ONE of the following: + + a. distribute the binaries and library files of the software, + together with instructions (in the manual page or equivalent) + on where to get the original distribution. + + b. accompany the distribution with the machine-readable source of + the software. + + c. give non-standard binaries non-standard names, with + instructions on where to get the original software distribution. + + d. make other distribution arrangements with the author. + +4. You may modify and include the part of the software into any other + software (possibly commercial). But some files in the distribution + are not written by the author, so that they are not under these terms. + + For the list of those files and their copying conditions, see the + file LEGAL. + +5. The scripts and library files supplied as input to or produced as + output from the software do not automatically fall under the + copyright of the software, but belong to whomever generated them, + and may be sold commercially, and may be aggregated with this + software. + +6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE. diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/README.rdoc b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/README.rdoc new file mode 100644 index 0000000..59349dc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/README.rdoc @@ -0,0 +1,129 @@ += \RDoc - Ruby Documentation System + +home :: https://github.com/ruby/rdoc +rdoc :: https://ruby.github.io/rdoc +bugs :: https://github.com/ruby/rdoc/issues +code quality :: {Code Climate}[https://codeclimate.com/github/ruby/rdoc] + +== Description + +RDoc produces HTML and command-line documentation for Ruby projects. RDoc +includes the +rdoc+ and +ri+ tools for generating and displaying documentation +from the command-line. + +== Generating Documentation + +Once installed, you can create documentation using the +rdoc+ command + + $ rdoc [options] [names...] + +For an up-to-date option summary, type + + $ rdoc --help + +A typical use might be to generate documentation for a package of Ruby +source (such as RDoc itself). + + $ rdoc + +This command generates documentation for all the Ruby and C source +files in and below the current directory. These will be stored in a +documentation tree starting in the subdirectory +doc+. + +You can make this slightly more useful for your readers by having the +index page contain the documentation for the primary file. In our +case, we could type + + % rdoc --main README.rdoc + +You'll find information on the various formatting tricks you can use +in comment blocks in the documentation this generates. + +RDoc uses file extensions to determine how to process each file. File names +ending +.rb+ and +.rbw+ are assumed to be Ruby source. Files +ending +.c+ are parsed as C files. All other files are assumed to +contain just Markup-style markup (with or without leading '#' comment +markers). If directory names are passed to RDoc, they are scanned +recursively for C and Ruby source files only. + +To generate documentation using +rake+ see RDoc::Task[https://ruby.github.io/rdoc/RDocTask.html]. + +To generate documentation programmatically: + + gem 'rdoc' + require 'rdoc/rdoc' + + options = RDoc::Options.new + # see RDoc::Options + + rdoc = RDoc::RDoc.new + rdoc.document options + # see RDoc::RDoc + +== Writing Documentation + +To write documentation for RDoc place a comment above the class, module, +method, constant, or attribute you want documented: + + ## + # This class represents an arbitrary shape by a series of points. + + class Shape + + ## + # Creates a new shape described by a +polyline+. + # + # If the +polyline+ does not end at the same point it started at the + # first pointed is copied and placed at the end of the line. + # + # An ArgumentError is raised if the line crosses itself, but shapes may + # be concave. + + def initialize polyline + # ... + end + + end + +The default comment markup format is the RDoc::Markup format. +TomDoc[rdoc-ref:RDoc::TomDoc], Markdown[rdoc-ref:RDoc::Markdown] and +RD[rdoc-ref:RDoc::RD] format comments are also supported. You can set the +default comment format for your entire project by creating a +.rdoc_options file. See RDoc::Options@Saved+Options for instructions +on creating one. You can also set the comment format for a single file +through the +:markup:+ directive, but this is only recommended if you wish to +switch markup formats. See RDoc::Markup@Other+directives. + +Comments can contain directives that tell RDoc information that it cannot +otherwise discover through parsing. See RDoc::Markup@Directives to control +what is or is not documented, to define method arguments or to break up +methods in a class by topic. See RDoc::Parser::Ruby for directives used to +teach RDoc about metaprogrammed methods. + +See RDoc::Parser::C for documenting C extensions with RDoc. + +To determine how well your project is documented run rdoc -C lib to +get a documentation coverage report. rdoc -C1 lib includes parameter +names in the documentation coverage report. + +== Bugs + +See CONTRIBUTING@Bugs for information on filing a bug report. It's OK to file +a bug report for anything you're having a problem with. If you can't figure +out how to make RDoc produce the output you like that is probably a +documentation bug. + +== License + +RDoc is Copyright (c) 2001-2003 Dave Thomas, The Pragmatic Programmers. +Portions (c) 2007-2011 Eric Hodel. Portions copyright others, see individual +files and LEGAL.rdoc for details. + +RDoc is free software, and may be redistributed under the terms specified in +LICENSE.rdoc. + +== Warranty + +This software is provided "as is" and without any express or implied +warranties, including, without limitation, the implied warranties of +merchantability and fitness for a particular purpose. diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/RI.rdoc b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/RI.rdoc new file mode 100644 index 0000000..f007b51 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/RI.rdoc @@ -0,0 +1,57 @@ += RI + ++ri+ is a tool that allows Ruby documentation to be viewed on the command-line. + +You can use +ri+ to look up information from either the command line or +interactively. When you run +ri+ without any arguments it will launch in +interactive mode. In interactive mode you can tab-complete class and method +names. + +== Usage + +To see information for a class, do: + ri ClassName + +For example, for the Array class, do: + ri Array + +To see information on a method on a class, do: + ri ClassName.method + +This will show both instance and class methods. For example, the IO +class defines both IO::read and IO#read: + ri IO.read + +To see information for an instance method, do: + ri ClassName#method_name + +For example, for Array's +join+ method, do: + ri Array#join + +To see information for a class method, do: + ri ClassName::method_name + +For example, for Module's +private+ method, do: + ri Module::private + +To read documentation for all +read+ methods, do: + ri read + +== Options + ++ri+ supports a variety of options, all of which can be viewed via +--help+. +Of particular interest, are: + +[-f] + Outputs ri data using the selected formatter. You can see the available + formatters in ri --help +[-T] + Send output to stdout, rather than to a pager. + +All options also can be specified through the +RI+ environment variable. +Command-line options always override those specified in the +RI+ environment +variable. + +The +RI_PAGER+ environment variable allows you to choose a particular pager or +particular options for your pager. + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/Rakefile b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/Rakefile new file mode 100644 index 0000000..278972e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/Rakefile @@ -0,0 +1,107 @@ +$:.unshift File.expand_path 'lib' +require 'rdoc/task' +require 'bundler/gem_tasks' +require 'rake/testtask' + +task :docs => :generate +task :test => [:normal_test, :rubygems_test] + +PARSER_FILES = %w[ + lib/rdoc/rd/block_parser.ry + lib/rdoc/rd/inline_parser.ry + lib/rdoc/markdown.kpeg + lib/rdoc/markdown/literals.kpeg +] + +$rdoc_rakefile = true + +task :default => :test + +RDoc::Task.new do |doc| + doc.main = 'README.rdoc' + doc.title = "rdoc #{RDoc::VERSION} Documentation" + doc.rdoc_dir = 'html' + doc.rdoc_files = FileList.new %w[lib/**/*.rb *.rdoc] - PARSER_FILES +end + +task ghpages: :rdoc do + `git checkout gh-pages` + require "fileutils" + FileUtils.rm_rf "/tmp/html" + FileUtils.mv "html", "/tmp" + FileUtils.rm_rf "*" + FileUtils.cp_r Dir.glob("/tmp/html/*"), "." +end + +Rake::TestTask.new(:normal_test) do |t| + t.libs << "test/rdoc" + t.verbose = true + t.deps = :generate + t.test_files = FileList["test/**/test_*.rb"].exclude("test/rdoc/test_rdoc_rubygems_hook.rb") +end + +Rake::TestTask.new(:rubygems_test) do |t| + t.libs << "test/rdoc" + t.verbose = true + t.deps = :generate + t.pattern = "test/rdoc/test_rdoc_rubygems_hook.rb" +end + +path = "pkg/#{Bundler::GemHelper.gemspec.full_name}" + +package_parser_files = PARSER_FILES.map do |parser_file| + name = File.basename(parser_file, File.extname(parser_file)) + _path = File.dirname(parser_file) + package_parser_file = "#{path}/#{name}.rb" + parsed_file = "#{_path}/#{name}.rb" + + file package_parser_file => parsed_file # ensure copy runs before racc + + package_parser_file +end + +parsed_files = PARSER_FILES.map do |parser_file| + ext = File.extname(parser_file) + parsed_file = "#{parser_file.chomp(ext)}.rb" + + file parsed_file => parser_file do |t| + puts "Generating #{parsed_file}..." + case ext + when '.ry' # need racc + racc = Gem.bin_path 'racc', 'racc' + rb_file = parser_file.gsub(/\.ry\z/, ".rb") + ruby "#{racc} -l -o #{rb_file} #{parser_file}" + open(rb_file, 'r+') do |f| + newtext = "# frozen_string_literal: true\n#{f.read}" + f.rewind + f.write newtext + end + when '.kpeg' # need kpeg + kpeg = Gem.bin_path 'kpeg', 'kpeg' + rb_file = parser_file.gsub(/\.kpeg\z/, ".rb") + ruby "#{kpeg} -fsv -o #{rb_file} #{parser_file}" + end + end + + parsed_file +end + +task "#{path}.gem" => package_parser_files +desc "Generate all files used racc and kpeg" +task :generate => parsed_files + +task :clean do + parsed_files.each do |path| + File.delete(path) if File.exist?(path) + end +end + +begin + require 'rubocop/rake_task' +rescue LoadError +else + RuboCop::RakeTask.new(:rubocop) do |t| + t.options = [*parsed_files] + end + task :build => [:generate, "rubocop:auto_correct"] +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/TODO.rdoc b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/TODO.rdoc new file mode 100644 index 0000000..431f6f6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/TODO.rdoc @@ -0,0 +1,59 @@ +This file contains some things that might happen in RDoc, or might not. +Forward Looking Statements applies. + +=== RDoc::VERSION.succ + +Blockers: + +* Update LICENSE to match ruby's switch +* The alias keyword should not be bidirectional +* Fix RDoc::Parser#use_markup to handle the filename (see TODO) +* Restore backwards compatibility due to paragraph text joining from existing + ri files +* Fix consumption of , after link like: RDoc[rdoc-ref:RDoc], <- comma here +* Remove support for links like Matrix[*rows] + +Nice to have: + +* Parse only changed files (like in ruby) +* Page of Glory (or Shame) in HTML output showing documentation coverage + statistics. +* Link to the parent-class implementation of methods that use super +* Add direct accessor to RDoc::Options to RDoc::Task +* Remove "Public" in HTML output if there are only public methods +* Method markup support for rd documentation (per rd syntax) +* Improve SIGINFO handling +* Global variable support +* Provide the code_object to directive handlers + +=== 4 + +API changes to RDoc + +* RDoc::TopLevel#add_method should automatically create the appropriate method + class rather than requiring one be passed in. +* Remove #comment= from Context subclasses in favor of #add_comment +* Add versions to RDoc::Markup syntax tree marshal format +* Comments can no longer be Strings + +=== Crazy Ideas + +* Auto-normalize heading levels to look OK. It's weird to see an

in + the middle of a method section. +* RDoc::CodeObject + * Move into own namespace + * Rename TopLevel to File + * Rename Context to Container + * Rename NormalClass to Class + +=== Accessibility + +Page title in right hand side + +Table of contents in left hand side as sub-list under main heading + +For class list, never method list, method summary at top + +table-of-contents-navigation div => nav + role="navigation" + +type "mod", focus is still on "mod" diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/bin/console b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/bin/console new file mode 100755 index 0000000..c5ee285 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/bin/console @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby + +require "bundler/setup" +require "rdoc" + +require "irb" +IRB.start diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/bin/setup b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/bin/setup new file mode 100755 index 0000000..cf4ad25 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/bin/setup @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/exe/rdoc b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/exe/rdoc new file mode 100755 index 0000000..aaa2329 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/exe/rdoc @@ -0,0 +1,44 @@ +#!/usr/bin/env ruby +# +# RDoc: Documentation tool for source code +# (see lib/rdoc/rdoc.rb for more information) +# +# Copyright (c) 2003 Dave Thomas +# Released under the same terms as Ruby + +begin + gem 'rdoc' +rescue NameError => e # --disable-gems + raise unless e.name == :gem +rescue Gem::LoadError +end + +require 'rdoc/rdoc' + +begin + r = RDoc::RDoc.new + r.document ARGV +rescue Errno::ENOSPC + $stderr.puts 'Ran out of space creating documentation' + $stderr.puts + $stderr.puts 'Please free up some space and try again' +rescue SystemExit + raise +rescue Exception => e + if $DEBUG_RDOC then + $stderr.puts e.message + $stderr.puts "#{e.backtrace.join "\n\t"}" + $stderr.puts + elsif Interrupt === e then + $stderr.puts + $stderr.puts 'Interrupted' + else + $stderr.puts "uh-oh! RDoc had a problem:" + $stderr.puts e.message + $stderr.puts + $stderr.puts "run with --debug for full backtrace" + end + + exit 1 +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/exe/ri b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/exe/ri new file mode 100755 index 0000000..7fbed0c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/exe/ri @@ -0,0 +1,12 @@ +#!/usr/bin/env ruby + +begin + gem 'rdoc' +rescue NameError => e # --disable-gems + raise unless e.name == :gem +rescue Gem::LoadError +end + +require 'rdoc/ri/driver' + +RDoc::RI::Driver.run ARGV diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc.rb new file mode 100644 index 0000000..2d3f8c1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc.rb @@ -0,0 +1,201 @@ +# frozen_string_literal: true +$DEBUG_RDOC = nil + +# :main: README.rdoc + +## +# RDoc produces documentation for Ruby source files by parsing the source and +# extracting the definition for classes, modules, methods, includes and +# requires. It associates these with optional documentation contained in an +# immediately preceding comment block then renders the result using an output +# formatter. +# +# For a simple introduction to writing or generating documentation using RDoc +# see the README. +# +# == Roadmap +# +# If you think you found a bug in RDoc see CONTRIBUTING@Bugs +# +# If you want to use RDoc to create documentation for your Ruby source files, +# see RDoc::Markup and refer to rdoc --help for command line usage. +# +# If you want to set the default markup format see +# RDoc::Markup@Supported+Formats +# +# If you want to store rdoc configuration in your gem (such as the default +# markup format) see RDoc::Options@Saved+Options +# +# If you want to write documentation for Ruby files see RDoc::Parser::Ruby +# +# If you want to write documentation for extensions written in C see +# RDoc::Parser::C +# +# If you want to generate documentation using rake see RDoc::Task. +# +# If you want to drive RDoc programmatically, see RDoc::RDoc. +# +# If you want to use the library to format text blocks into HTML or other +# formats, look at RDoc::Markup. +# +# If you want to make an RDoc plugin such as a generator or directive handler +# see RDoc::RDoc. +# +# If you want to write your own output generator see RDoc::Generator. +# +# If you want an overview of how RDoc works see CONTRIBUTING +# +# == Credits +# +# RDoc is currently being maintained by Eric Hodel . +# +# Dave Thomas is the original author of RDoc. +# +# * The Ruby parser in rdoc/parse.rb is based heavily on the outstanding +# work of Keiju ISHITSUKA of Nippon Rational Inc, who produced the Ruby +# parser for irb and the rtags package. + +module RDoc + + ## + # Exception thrown by any rdoc error. + + class Error < RuntimeError; end + + require 'rdoc/version' + + ## + # Method visibilities + + VISIBILITIES = [:public, :protected, :private] + + ## + # Name of the dotfile that contains the description of files to be processed + # in the current directory + + DOT_DOC_FILENAME = ".document" + + ## + # General RDoc modifiers + + GENERAL_MODIFIERS = %w[nodoc].freeze + + ## + # RDoc modifiers for classes + + CLASS_MODIFIERS = GENERAL_MODIFIERS + + ## + # RDoc modifiers for attributes + + ATTR_MODIFIERS = GENERAL_MODIFIERS + + ## + # RDoc modifiers for constants + + CONSTANT_MODIFIERS = GENERAL_MODIFIERS + + ## + # RDoc modifiers for methods + + METHOD_MODIFIERS = GENERAL_MODIFIERS + + %w[arg args yield yields notnew not-new not_new doc] + + ## + # Loads the best available YAML library. + + def self.load_yaml + begin + gem 'psych' + rescue NameError => e # --disable-gems + raise unless e.name == :gem + rescue Gem::LoadError + end + + begin + require 'psych' + rescue ::LoadError + ensure + require 'yaml' + end + end + + def self.home + rdoc_dir = begin + File.expand_path('~/.rdoc') + rescue ArgumentError + end + + if File.directory?(rdoc_dir) + rdoc_dir + else + begin + # XDG + xdg_data_home = ENV["XDG_DATA_HOME"] || File.join(File.expand_path("~"), '.local', 'share') + unless File.exist?(xdg_data_home) + FileUtils.mkdir_p xdg_data_home + end + File.join xdg_data_home, "rdoc" + rescue Errno::EACCES + end + end + end + + autoload :RDoc, 'rdoc/rdoc' + + autoload :CrossReference, 'rdoc/cross_reference' + autoload :ERBIO, 'rdoc/erbio' + autoload :ERBPartial, 'rdoc/erb_partial' + autoload :Encoding, 'rdoc/encoding' + autoload :Generator, 'rdoc/generator' + autoload :Options, 'rdoc/options' + autoload :Parser, 'rdoc/parser' + autoload :Servlet, 'rdoc/servlet' + autoload :RI, 'rdoc/ri' + autoload :Stats, 'rdoc/stats' + autoload :Store, 'rdoc/store' + autoload :Task, 'rdoc/task' + autoload :Text, 'rdoc/text' + + autoload :Markdown, 'rdoc/markdown' + autoload :Markup, 'rdoc/markup' + autoload :RD, 'rdoc/rd' + autoload :TomDoc, 'rdoc/tom_doc' + + autoload :KNOWN_CLASSES, 'rdoc/known_classes' + + autoload :TokenStream, 'rdoc/token_stream' + + autoload :Comment, 'rdoc/comment' + + require 'rdoc/i18n' + + # code objects + # + # We represent the various high-level code constructs that appear in Ruby + # programs: classes, modules, methods, and so on. + autoload :CodeObject, 'rdoc/code_object' + + autoload :Context, 'rdoc/context' + autoload :TopLevel, 'rdoc/top_level' + + autoload :AnonClass, 'rdoc/anon_class' + autoload :ClassModule, 'rdoc/class_module' + autoload :NormalClass, 'rdoc/normal_class' + autoload :NormalModule, 'rdoc/normal_module' + autoload :SingleClass, 'rdoc/single_class' + + autoload :Alias, 'rdoc/alias' + autoload :AnyMethod, 'rdoc/any_method' + autoload :MethodAttr, 'rdoc/method_attr' + autoload :GhostMethod, 'rdoc/ghost_method' + autoload :MetaMethod, 'rdoc/meta_method' + autoload :Attr, 'rdoc/attr' + + autoload :Constant, 'rdoc/constant' + autoload :Mixin, 'rdoc/mixin' + autoload :Include, 'rdoc/include' + autoload :Extend, 'rdoc/extend' + autoload :Require, 'rdoc/require' + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/alias.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/alias.rb new file mode 100644 index 0000000..858e053 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/alias.rb @@ -0,0 +1,112 @@ +# frozen_string_literal: true +## +# Represent an alias, which is an old_name/new_name pair associated with a +# particular context +#-- +# TODO implement Alias as a proxy to a method/attribute, inheriting from +# MethodAttr + +class RDoc::Alias < RDoc::CodeObject + + ## + # Aliased method's name + + attr_reader :new_name + + alias name new_name + + ## + # Aliasee method's name + + attr_reader :old_name + + ## + # Is this an alias declared in a singleton context? + + attr_accessor :singleton + + ## + # Source file token stream + + attr_reader :text + + ## + # Creates a new Alias with a token stream of +text+ that aliases +old_name+ + # to +new_name+, has +comment+ and is a +singleton+ context. + + def initialize(text, old_name, new_name, comment, singleton = false) + super() + + @text = text + @singleton = singleton + @old_name = old_name + @new_name = new_name + self.comment = comment + end + + ## + # Order by #singleton then #new_name + + def <=>(other) + [@singleton ? 0 : 1, new_name] <=> [other.singleton ? 0 : 1, other.new_name] + end + + ## + # HTML fragment reference for this alias + + def aref + type = singleton ? 'c' : 'i' + "#alias-#{type}-#{html_name}" + end + + ## + # Full old name including namespace + + def full_old_name + @full_name || "#{parent.name}#{pretty_old_name}" + end + + ## + # HTML id-friendly version of +#new_name+. + + def html_name + CGI.escape(@new_name.gsub('-', '-2D')).gsub('%','-').sub(/^-/, '') + end + + def inspect # :nodoc: + parent_name = parent ? parent.name : '(unknown)' + "#<%s:0x%x %s.alias_method %s, %s>" % [ + self.class, object_id, + parent_name, @old_name, @new_name, + ] + end + + ## + # '::' for the alias of a singleton method/attribute, '#' for instance-level. + + def name_prefix + singleton ? '::' : '#' + end + + ## + # Old name with prefix '::' or '#'. + + def pretty_old_name + "#{singleton ? '::' : '#'}#{@old_name}" + end + + ## + # New name with prefix '::' or '#'. + + def pretty_new_name + "#{singleton ? '::' : '#'}#{@new_name}" + end + + alias pretty_name pretty_new_name + + def to_s # :nodoc: + "alias: #{self.new_name} -> #{self.pretty_old_name} in: #{parent}" + end + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/anon_class.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/anon_class.rb new file mode 100644 index 0000000..d02a38c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/anon_class.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true +## +# An anonymous class like: +# +# c = Class.new do end +# +# AnonClass is currently not used. + +class RDoc::AnonClass < RDoc::ClassModule +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/any_method.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/any_method.rb new file mode 100644 index 0000000..0b7dd71 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/any_method.rb @@ -0,0 +1,364 @@ +# frozen_string_literal: true +## +# AnyMethod is the base class for objects representing methods + +class RDoc::AnyMethod < RDoc::MethodAttr + + ## + # 2:: + # RDoc 4 + # Added calls_super + # Added parent name and class + # Added section title + # 3:: + # RDoc 4.1 + # Added is_alias_for + + MARSHAL_VERSION = 3 # :nodoc: + + ## + # Don't rename \#initialize to \::new + + attr_accessor :dont_rename_initialize + + ## + # The C function that implements this method (if it was defined in a C file) + + attr_accessor :c_function + + # The section title of the method (if defined in a C file via +:category:+) + attr_accessor :section_title + + # Parameters for this method + + attr_accessor :params + + ## + # If true this method uses +super+ to call a superclass version + + attr_accessor :calls_super + + include RDoc::TokenStream + + ## + # Creates a new AnyMethod with a token stream +text+ and +name+ + + def initialize text, name + super + + @c_function = nil + @dont_rename_initialize = false + @token_stream = nil + @calls_super = false + @superclass_method = nil + end + + ## + # Adds +an_alias+ as an alias for this method in +context+. + + def add_alias an_alias, context = nil + method = self.class.new an_alias.text, an_alias.new_name + + method.record_location an_alias.file + method.singleton = self.singleton + method.params = self.params + method.visibility = self.visibility + method.comment = an_alias.comment + method.is_alias_for = self + @aliases << method + context.add_method method if context + method + end + + ## + # Prefix for +aref+ is 'method'. + + def aref_prefix + 'method' + end + + ## + # The call_seq or the param_seq with method name, if there is no call_seq. + # + # Use this for displaying a method's argument lists. + + def arglists + if @call_seq then + @call_seq + elsif @params then + "#{name}#{param_seq}" + end + end + + ## + # Different ways to call this method + + def call_seq + unless call_seq = _call_seq + call_seq = is_alias_for._call_seq if is_alias_for + end + + return unless call_seq + + deduplicate_call_seq(call_seq) + end + + ## + # Sets the different ways you can call this method. If an empty +call_seq+ + # is given nil is assumed. + # + # See also #param_seq + + def call_seq= call_seq + return if call_seq.empty? + + @call_seq = call_seq + end + + ## + # Loads is_alias_for from the internal name. Returns nil if the alias + # cannot be found. + + def is_alias_for # :nodoc: + case @is_alias_for + when RDoc::MethodAttr then + @is_alias_for + when Array then + return nil unless @store + + klass_name, singleton, method_name = @is_alias_for + + return nil unless klass = @store.find_class_or_module(klass_name) + + @is_alias_for = klass.find_method method_name, singleton + end + end + + ## + # Dumps this AnyMethod for use by ri. See also #marshal_load + + def marshal_dump + aliases = @aliases.map do |a| + [a.name, parse(a.comment)] + end + + is_alias_for = [ + @is_alias_for.parent.full_name, + @is_alias_for.singleton, + @is_alias_for.name + ] if @is_alias_for + + [ MARSHAL_VERSION, + @name, + full_name, + @singleton, + @visibility, + parse(@comment), + @call_seq, + @block_params, + aliases, + @params, + @file.relative_name, + @calls_super, + @parent.name, + @parent.class, + @section.title, + is_alias_for, + ] + end + + ## + # Loads this AnyMethod from +array+. For a loaded AnyMethod the following + # methods will return cached values: + # + # * #full_name + # * #parent_name + + def marshal_load array + initialize_visibility + + @dont_rename_initialize = nil + @token_stream = nil + @aliases = [] + @parent = nil + @parent_name = nil + @parent_class = nil + @section = nil + @file = nil + + version = array[0] + @name = array[1] + @full_name = array[2] + @singleton = array[3] + @visibility = array[4] + @comment = array[5] + @call_seq = array[6] + @block_params = array[7] + # 8 handled below + @params = array[9] + # 10 handled below + @calls_super = array[11] + @parent_name = array[12] + @parent_title = array[13] + @section_title = array[14] + @is_alias_for = array[15] + + array[8].each do |new_name, comment| + add_alias RDoc::Alias.new(nil, @name, new_name, comment, @singleton) + end + + @parent_name ||= if @full_name =~ /#/ then + $` + else + name = @full_name.split('::') + name.pop + name.join '::' + end + + @file = RDoc::TopLevel.new array[10] if version > 0 + end + + ## + # Method name + # + # If the method has no assigned name, it extracts it from #call_seq. + + def name + return @name if @name + + @name = + @call_seq[/^.*?\.(\w+)/, 1] || + @call_seq[/^.*?(\w+)/, 1] || + @call_seq if @call_seq + end + + ## + # A list of this method's method and yield parameters. +call-seq+ params + # are preferred over parsed method and block params. + + def param_list + if @call_seq then + params = @call_seq.split("\n").last + params = params.sub(/.*?\((.*)\)/, '\1') + params = params.sub(/(\{|do)\s*\|([^|]*)\|.*/, ',\2') + elsif @params then + params = @params.sub(/\((.*)\)/, '\1') + + params << ",#{@block_params}" if @block_params + elsif @block_params then + params = @block_params + else + return [] + end + + if @block_params then + # If this method has explicit block parameters, remove any explicit + # &block + params = params.sub(/,?\s*&\w+/, '') + else + params = params.sub(/\&(\w+)/, '\1') + end + + params = params.gsub(/\s+/, '').split(',').reject(&:empty?) + + params.map { |param| param.sub(/=.*/, '') } + end + + ## + # Pretty parameter list for this method. If the method's parameters were + # given by +call-seq+ it is preferred over the parsed values. + + def param_seq + if @call_seq then + params = @call_seq.split("\n").last + params = params.sub(/[^( ]+/, '') + params = params.sub(/(\|[^|]+\|)\s*\.\.\.\s*(end|\})/, '\1 \2') + elsif @params then + params = @params.gsub(/\s*\#.*/, '') + params = params.tr_s("\n ", " ") + params = "(#{params})" unless params[0] == ?( + else + params = '' + end + + if @block_params then + # If this method has explicit block parameters, remove any explicit + # &block + params = params.sub(/,?\s*&\w+/, '') + + block = @block_params.tr_s("\n ", " ") + if block[0] == ?( + block = block.sub(/^\(/, '').sub(/\)/, '') + end + params << " { |#{block}| ... }" + end + + params + end + + ## + # Sets the store for this method and its referenced code objects. + + def store= store + super + + @file = @store.add_file @file.full_name if @file + end + + ## + # For methods that +super+, find the superclass method that would be called. + + def superclass_method + return unless @calls_super + return @superclass_method if @superclass_method + + parent.each_ancestor do |ancestor| + if method = ancestor.method_list.find { |m| m.name == @name } then + @superclass_method = method + break + end + end + + @superclass_method + end + + protected + + ## + # call_seq without deduplication and alias lookup. + + def _call_seq + @call_seq if defined?(@call_seq) && @call_seq + end + + private + + ## + # call_seq with alias examples information removed, if this + # method is an alias method. + + def deduplicate_call_seq(call_seq) + return call_seq unless is_alias_for || !aliases.empty? + + method_name = self.name + method_name = method_name[0, 1] if method_name =~ /\A\[/ + + entries = call_seq.split "\n" + + ignore = aliases.map(&:name) + if is_alias_for + ignore << is_alias_for.name + ignore.concat is_alias_for.aliases.map(&:name) + end + ignore.map! { |n| n =~ /\A\[/ ? n[0, 1] : n} + ignore.delete(method_name) + ignore = Regexp.union(ignore) + + matching = entries.reject do |entry| + entry =~ /^\w*\.?#{ignore}/ or + entry =~ /\s#{ignore}\s/ + end + + matching.empty? ? nil : matching.join("\n") + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/attr.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/attr.rb new file mode 100644 index 0000000..f780b3b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/attr.rb @@ -0,0 +1,176 @@ +# frozen_string_literal: true +## +# An attribute created by \#attr, \#attr_reader, \#attr_writer or +# \#attr_accessor + +class RDoc::Attr < RDoc::MethodAttr + + ## + # 3:: + # RDoc 4 + # Added parent name and class + # Added section title + + MARSHAL_VERSION = 3 # :nodoc: + + ## + # Is the attribute readable ('R'), writable ('W') or both ('RW')? + + attr_accessor :rw + + ## + # Creates a new Attr with body +text+, +name+, read/write status +rw+ and + # +comment+. +singleton+ marks this as a class attribute. + + def initialize(text, name, rw, comment, singleton = false) + super text, name + + @rw = rw + @singleton = singleton + self.comment = comment + end + + ## + # Attributes are equal when their names, singleton and rw are identical + + def == other + self.class == other.class and + self.name == other.name and + self.rw == other.rw and + self.singleton == other.singleton + end + + ## + # Add +an_alias+ as an attribute in +context+. + + def add_alias(an_alias, context) + new_attr = self.class.new(self.text, an_alias.new_name, self.rw, + self.comment, self.singleton) + + new_attr.record_location an_alias.file + new_attr.visibility = self.visibility + new_attr.is_alias_for = self + @aliases << new_attr + context.add_attribute new_attr + new_attr + end + + ## + # The #aref prefix for attributes + + def aref_prefix + 'attribute' + end + + ## + # Attributes never call super. See RDoc::AnyMethod#calls_super + # + # An RDoc::Attr can show up in the method list in some situations (see + # Gem::ConfigFile) + + def calls_super # :nodoc: + false + end + + ## + # Returns attr_reader, attr_writer or attr_accessor as appropriate. + + def definition + case @rw + when 'RW' then 'attr_accessor' + when 'R' then 'attr_reader' + when 'W' then 'attr_writer' + end + end + + def inspect # :nodoc: + alias_for = @is_alias_for ? " (alias for #{@is_alias_for.name})" : nil + visibility = self.visibility + visibility = "forced #{visibility}" if force_documentation + "#<%s:0x%x %s %s (%s)%s>" % [ + self.class, object_id, + full_name, + rw, + visibility, + alias_for, + ] + end + + ## + # Dumps this Attr for use by ri. See also #marshal_load + + def marshal_dump + [ MARSHAL_VERSION, + @name, + full_name, + @rw, + @visibility, + parse(@comment), + singleton, + @file.relative_name, + @parent.full_name, + @parent.class, + @section.title + ] + end + + ## + # Loads this Attr from +array+. For a loaded Attr the following + # methods will return cached values: + # + # * #full_name + # * #parent_name + + def marshal_load array + initialize_visibility + + @aliases = [] + @parent = nil + @parent_name = nil + @parent_class = nil + @section = nil + @file = nil + + version = array[0] + @name = array[1] + @full_name = array[2] + @rw = array[3] + @visibility = array[4] + @comment = array[5] + @singleton = array[6] || false # MARSHAL_VERSION == 0 + # 7 handled below + @parent_name = array[8] + @parent_class = array[9] + @section_title = array[10] + + @file = RDoc::TopLevel.new array[7] if version > 1 + + @parent_name ||= @full_name.split('#', 2).first + end + + def pretty_print q # :nodoc: + q.group 2, "[#{self.class.name} #{full_name} #{rw} #{visibility}", "]" do + unless comment.empty? then + q.breakable + q.text "comment:" + q.breakable + q.pp @comment + end + end + end + + def to_s # :nodoc: + "#{definition} #{name} in: #{parent}" + end + + ## + # Attributes do not have token streams. + # + # An RDoc::Attr can show up in the method list in some situations (see + # Gem::ConfigFile) + + def token_stream # :nodoc: + end + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/class_module.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/class_module.rb new file mode 100644 index 0000000..7609080 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/class_module.rb @@ -0,0 +1,802 @@ +# frozen_string_literal: true +## +# ClassModule is the base class for objects representing either a class or a +# module. + +class RDoc::ClassModule < RDoc::Context + + ## + # 1:: + # RDoc 3.7 + # * Added visibility, singleton and file to attributes + # * Added file to constants + # * Added file to includes + # * Added file to methods + # 2:: + # RDoc 3.13 + # * Added extends + # 3:: + # RDoc 4.0 + # * Added sections + # * Added in_files + # * Added parent name + # * Complete Constant dump + + MARSHAL_VERSION = 3 # :nodoc: + + ## + # Constants that are aliases for this class or module + + attr_accessor :constant_aliases + + ## + # Comment and the location it came from. Use #add_comment to add comments + + attr_accessor :comment_location + + attr_accessor :diagram # :nodoc: + + ## + # Class or module this constant is an alias for + + attr_accessor :is_alias_for + + ## + # Return a RDoc::ClassModule of class +class_type+ that is a copy + # of module +module+. Used to promote modules to classes. + #-- + # TODO move to RDoc::NormalClass (I think) + + def self.from_module class_type, mod + klass = class_type.new mod.name + + mod.comment_location.each do |comment, location| + klass.add_comment comment, location + end + + klass.parent = mod.parent + klass.section = mod.section + klass.viewer = mod.viewer + + klass.attributes.concat mod.attributes + klass.method_list.concat mod.method_list + klass.aliases.concat mod.aliases + klass.external_aliases.concat mod.external_aliases + klass.constants.concat mod.constants + klass.includes.concat mod.includes + klass.extends.concat mod.extends + + klass.methods_hash.update mod.methods_hash + klass.constants_hash.update mod.constants_hash + + klass.current_section = mod.current_section + klass.in_files.concat mod.in_files + klass.sections.concat mod.sections + klass.unmatched_alias_lists = mod.unmatched_alias_lists + klass.current_section = mod.current_section + klass.visibility = mod.visibility + + klass.classes_hash.update mod.classes_hash + klass.modules_hash.update mod.modules_hash + klass.metadata.update mod.metadata + + klass.document_self = mod.received_nodoc ? nil : mod.document_self + klass.document_children = mod.document_children + klass.force_documentation = mod.force_documentation + klass.done_documenting = mod.done_documenting + + # update the parent of all children + + (klass.attributes + + klass.method_list + + klass.aliases + + klass.external_aliases + + klass.constants + + klass.includes + + klass.extends + + klass.classes + + klass.modules).each do |obj| + obj.parent = klass + obj.full_name = nil + end + + klass + end + + ## + # Creates a new ClassModule with +name+ with optional +superclass+ + # + # This is a constructor for subclasses, and must never be called directly. + + def initialize(name, superclass = nil) + @constant_aliases = [] + @diagram = nil + @is_alias_for = nil + @name = name + @superclass = superclass + @comment_location = [] # [[comment, location]] + + super() + end + + ## + # Adds +comment+ to this ClassModule's list of comments at +location+. This + # method is preferred over #comment= since it allows ri data to be updated + # across multiple runs. + + def add_comment comment, location + return unless document_self + + original = comment + + comment = case comment + when RDoc::Comment then + comment.normalize + else + normalize_comment comment + end + + if location.parser == RDoc::Parser::C + @comment_location.delete_if { |(_, l)| l == location } + end + + @comment_location << [comment, location] + + self.comment = original + end + + def add_things my_things, other_things # :nodoc: + other_things.each do |group, things| + my_things[group].each { |thing| yield false, thing } if + my_things.include? group + + things.each do |thing| + yield true, thing + end + end + end + + ## + # Ancestors list for this ClassModule: the list of included modules + # (classes will add their superclass if any). + # + # Returns the included classes or modules, not the includes + # themselves. The returned values are either String or + # RDoc::NormalModule instances (see RDoc::Include#module). + # + # The values are returned in reverse order of their inclusion, + # which is the order suitable for searching methods/attributes + # in the ancestors. The superclass, if any, comes last. + + def ancestors + includes.map { |i| i.module }.reverse + end + + def aref_prefix # :nodoc: + raise NotImplementedError, "missing aref_prefix for #{self.class}" + end + + ## + # HTML fragment reference for this module or class. See + # RDoc::NormalClass#aref and RDoc::NormalModule#aref + + def aref + "#{aref_prefix}-#{full_name}" + end + + ## + # Ancestors of this class or module only + + alias direct_ancestors ancestors + + ## + # Clears the comment. Used by the Ruby parser. + + def clear_comment + @comment = '' + end + + ## + # This method is deprecated, use #add_comment instead. + # + # Appends +comment+ to the current comment, but separated by a rule. Works + # more like +=. + + def comment= comment # :nodoc: + comment = case comment + when RDoc::Comment then + comment.normalize + else + normalize_comment comment + end + + comment = "#{@comment.to_s}\n---\n#{comment.to_s}" unless @comment.empty? + + super comment + end + + ## + # Prepares this ClassModule for use by a generator. + # + # See RDoc::Store#complete + + def complete min_visibility + update_aliases + remove_nodoc_children + update_includes + remove_invisible min_visibility + end + + ## + # Does this ClassModule or any of its methods have document_self set? + + def document_self_or_methods + document_self || method_list.any?{ |m| m.document_self } + end + + ## + # Does this class or module have a comment with content or is + # #received_nodoc true? + + def documented? + return true if @received_nodoc + return false if @comment_location.empty? + @comment_location.any? { |comment, _| not comment.empty? } + end + + ## + # Iterates the ancestors of this class or module for which an + # RDoc::ClassModule exists. + + def each_ancestor # :yields: module + return enum_for __method__ unless block_given? + + ancestors.each do |mod| + next if String === mod + next if self == mod + yield mod + end + end + + ## + # Looks for a symbol in the #ancestors. See Context#find_local_symbol. + + def find_ancestor_local_symbol symbol + each_ancestor do |m| + res = m.find_local_symbol(symbol) + return res if res + end + + nil + end + + ## + # Finds a class or module with +name+ in this namespace or its descendants + + def find_class_named name + return self if full_name == name + return self if @name == name + + @classes.values.find do |klass| + next if klass == self + klass.find_class_named name + end + end + + ## + # Return the fully qualified name of this class or module + + def full_name + @full_name ||= if RDoc::ClassModule === parent then + "#{parent.full_name}::#{@name}" + else + @name + end + end + + ## + # TODO: filter included items by #display? + + def marshal_dump # :nodoc: + attrs = attributes.sort.map do |attr| + next unless attr.display? + [ attr.name, attr.rw, + attr.visibility, attr.singleton, attr.file_name, + ] + end.compact + + method_types = methods_by_type.map do |type, visibilities| + visibilities = visibilities.map do |visibility, methods| + method_names = methods.map do |method| + next unless method.display? + [method.name, method.file_name] + end.compact + + [visibility, method_names.uniq] + end + + [type, visibilities] + end + + [ MARSHAL_VERSION, + @name, + full_name, + @superclass, + parse(@comment_location), + attrs, + constants.select { |constant| constant.display? }, + includes.map do |incl| + next unless incl.display? + [incl.name, parse(incl.comment), incl.file_name] + end.compact, + method_types, + extends.map do |ext| + next unless ext.display? + [ext.name, parse(ext.comment), ext.file_name] + end.compact, + @sections.values, + @in_files.map do |tl| + tl.relative_name + end, + parent.full_name, + parent.class, + ] + end + + def marshal_load array # :nodoc: + initialize_visibility + initialize_methods_etc + @current_section = nil + @document_self = true + @done_documenting = false + @parent = nil + @temporary_section = nil + @visibility = nil + @classes = {} + @modules = {} + + @name = array[1] + @full_name = array[2] + @superclass = array[3] + @comment = array[4] + + @comment_location = if RDoc::Markup::Document === @comment.parts.first then + @comment + else + RDoc::Markup::Document.new @comment + end + + array[5].each do |name, rw, visibility, singleton, file| + singleton ||= false + visibility ||= :public + + attr = RDoc::Attr.new nil, name, rw, nil, singleton + + add_attribute attr + attr.visibility = visibility + attr.record_location RDoc::TopLevel.new file + end + + array[6].each do |constant, comment, file| + case constant + when RDoc::Constant then + add_constant constant + else + constant = add_constant RDoc::Constant.new(constant, nil, comment) + constant.record_location RDoc::TopLevel.new file + end + end + + array[7].each do |name, comment, file| + incl = add_include RDoc::Include.new(name, comment) + incl.record_location RDoc::TopLevel.new file + end + + array[8].each do |type, visibilities| + visibilities.each do |visibility, methods| + @visibility = visibility + + methods.each do |name, file| + method = RDoc::AnyMethod.new nil, name + method.singleton = true if type == 'class' + method.record_location RDoc::TopLevel.new file + add_method method + end + end + end + + array[9].each do |name, comment, file| + ext = add_extend RDoc::Extend.new(name, comment) + ext.record_location RDoc::TopLevel.new file + end if array[9] # Support Marshal version 1 + + sections = (array[10] || []).map do |section| + [section.title, section] + end + + @sections = Hash[*sections.flatten] + @current_section = add_section nil + + @in_files = [] + + (array[11] || []).each do |filename| + record_location RDoc::TopLevel.new filename + end + + @parent_name = array[12] + @parent_class = array[13] + end + + ## + # Merges +class_module+ into this ClassModule. + # + # The data in +class_module+ is preferred over the receiver. + + def merge class_module + @parent = class_module.parent + @parent_name = class_module.parent_name + + other_document = parse class_module.comment_location + + if other_document then + document = parse @comment_location + + document = document.merge other_document + + @comment = @comment_location = document + end + + cm = class_module + other_files = cm.in_files + + merge_collections attributes, cm.attributes, other_files do |add, attr| + if add then + add_attribute attr + else + @attributes.delete attr + @methods_hash.delete attr.pretty_name + end + end + + merge_collections constants, cm.constants, other_files do |add, const| + if add then + add_constant const + else + @constants.delete const + @constants_hash.delete const.name + end + end + + merge_collections includes, cm.includes, other_files do |add, incl| + if add then + add_include incl + else + @includes.delete incl + end + end + + @includes.uniq! # clean up + + merge_collections extends, cm.extends, other_files do |add, ext| + if add then + add_extend ext + else + @extends.delete ext + end + end + + @extends.uniq! # clean up + + merge_collections method_list, cm.method_list, other_files do |add, meth| + if add then + add_method meth + else + @method_list.delete meth + @methods_hash.delete meth.pretty_name + end + end + + merge_sections cm + + self + end + + ## + # Merges collection +mine+ with +other+ preferring other. +other_files+ is + # used to help determine which items should be deleted. + # + # Yields whether the item should be added or removed (true or false) and the + # item to be added or removed. + # + # merge_collections things, other.things, other.in_files do |add, thing| + # if add then + # # add the thing + # else + # # remove the thing + # end + # end + + def merge_collections mine, other, other_files, &block # :nodoc: + my_things = mine. group_by { |thing| thing.file } + other_things = other.group_by { |thing| thing.file } + + remove_things my_things, other_files, &block + add_things my_things, other_things, &block + end + + ## + # Merges the comments in this ClassModule with the comments in the other + # ClassModule +cm+. + + def merge_sections cm # :nodoc: + my_sections = sections.group_by { |section| section.title } + other_sections = cm.sections.group_by { |section| section.title } + + other_files = cm.in_files + + remove_things my_sections, other_files do |_, section| + @sections.delete section.title + end + + other_sections.each do |group, sections| + if my_sections.include? group + my_sections[group].each do |my_section| + other_section = cm.sections_hash[group] + + my_comments = my_section.comments + other_comments = other_section.comments + + other_files = other_section.in_files + + merge_collections my_comments, other_comments, other_files do |add, comment| + if add then + my_section.add_comment comment + else + my_section.remove_comment comment + end + end + end + else + sections.each do |section| + add_section group, section.comments + end + end + end + end + + ## + # Does this object represent a module? + + def module? + false + end + + ## + # Allows overriding the initial name. + # + # Used for modules and classes that are constant aliases. + + def name= new_name + @name = new_name + end + + ## + # Parses +comment_location+ into an RDoc::Markup::Document composed of + # multiple RDoc::Markup::Documents with their file set. + + def parse comment_location + case comment_location + when String then + super + when Array then + docs = comment_location.map do |comment, location| + doc = super comment + doc.file = location + doc + end + + RDoc::Markup::Document.new(*docs) + when RDoc::Comment then + doc = super comment_location.text, comment_location.format + doc.file = comment_location.location + doc + when RDoc::Markup::Document then + return comment_location + else + raise ArgumentError, "unknown comment class #{comment_location.class}" + end + end + + ## + # Path to this class or module for use with HTML generator output. + + def path + http_url @store.rdoc.generator.class_dir + end + + ## + # Name to use to generate the url: + # modules and classes that are aliases for another + # module or class return the name of the latter. + + def name_for_path + is_alias_for ? is_alias_for.full_name : full_name + end + + ## + # Returns the classes and modules that are not constants + # aliasing another class or module. For use by formatters + # only (caches its result). + + def non_aliases + @non_aliases ||= classes_and_modules.reject { |cm| cm.is_alias_for } + end + + ## + # Updates the child modules or classes of class/module +parent+ by + # deleting the ones that have been removed from the documentation. + # + # +parent_hash+ is either parent.modules_hash or + # parent.classes_hash and +all_hash+ is ::all_modules_hash or + # ::all_classes_hash. + + def remove_nodoc_children + prefix = self.full_name + '::' + + modules_hash.each_key do |name| + full_name = prefix + name + modules_hash.delete name unless @store.modules_hash[full_name] + end + + classes_hash.each_key do |name| + full_name = prefix + name + classes_hash.delete name unless @store.classes_hash[full_name] + end + end + + def remove_things my_things, other_files # :nodoc: + my_things.delete_if do |file, things| + next false unless other_files.include? file + + things.each do |thing| + yield false, thing + end + + true + end + end + + ## + # Search record used by RDoc::Generator::JsonIndex + + def search_record + [ + name, + full_name, + full_name, + '', + path, + '', + snippet(@comment_location), + ] + end + + ## + # Sets the store for this class or module and its contained code objects. + + def store= store + super + + @attributes .each do |attr| attr.store = store end + @constants .each do |const| const.store = store end + @includes .each do |incl| incl.store = store end + @extends .each do |ext| ext.store = store end + @method_list.each do |meth| meth.store = store end + end + + ## + # Get the superclass of this class. Attempts to retrieve the superclass + # object, returns the name if it is not known. + + def superclass + @store.find_class_named(@superclass) || @superclass + end + + ## + # Set the superclass of this class to +superclass+ + + def superclass=(superclass) + raise NoMethodError, "#{full_name} is a module" if module? + @superclass = superclass + end + + def to_s # :nodoc: + if is_alias_for then + "#{self.class.name} #{self.full_name} -> #{is_alias_for}" + else + super + end + end + + ## + # 'module' or 'class' + + def type + module? ? 'module' : 'class' + end + + ## + # Updates the child modules & classes by replacing the ones that are + # aliases through a constant. + # + # The aliased module/class is replaced in the children and in + # RDoc::Store#modules_hash or RDoc::Store#classes_hash + # by a copy that has RDoc::ClassModule#is_alias_for set to + # the aliased module/class, and this copy is added to #aliases + # of the aliased module/class. + # + # Formatters can use the #non_aliases method to retrieve children that + # are not aliases, for instance to list the namespace content, since + # the aliased modules are included in the constants of the class/module, + # that are listed separately. + + def update_aliases + constants.each do |const| + next unless cm = const.is_alias_for + cm_alias = cm.dup + cm_alias.name = const.name + + # Don't move top-level aliases under Object, they look ugly there + unless RDoc::TopLevel === cm_alias.parent then + cm_alias.parent = self + cm_alias.full_name = nil # force update for new parent + end + + cm_alias.aliases.clear + cm_alias.is_alias_for = cm + + if cm.module? then + @store.modules_hash[cm_alias.full_name] = cm_alias + modules_hash[const.name] = cm_alias + else + @store.classes_hash[cm_alias.full_name] = cm_alias + classes_hash[const.name] = cm_alias + end + + cm.aliases << cm_alias + end + end + + ## + # Deletes from #includes those whose module has been removed from the + # documentation. + #-- + # FIXME: includes are not reliably removed, see _possible_bug test case + + def update_includes + includes.reject! do |include| + mod = include.module + !(String === mod) && @store.modules_hash[mod.full_name].nil? + end + + includes.uniq! + end + + ## + # Deletes from #extends those whose module has been removed from the + # documentation. + #-- + # FIXME: like update_includes, extends are not reliably removed + + def update_extends + extends.reject! do |ext| + mod = ext.module + + !(String === mod) && @store.modules_hash[mod.full_name].nil? + end + + extends.uniq! + end + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/code_object.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/code_object.rb new file mode 100644 index 0000000..aeb4b47 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/code_object.rb @@ -0,0 +1,421 @@ +# frozen_string_literal: true +## +# Base class for the RDoc code tree. +# +# We contain the common stuff for contexts (which are containers) and other +# elements (methods, attributes and so on) +# +# Here's the tree of the CodeObject subclasses: +# +# * RDoc::Context +# * RDoc::TopLevel +# * RDoc::ClassModule +# * RDoc::AnonClass (never used so far) +# * RDoc::NormalClass +# * RDoc::NormalModule +# * RDoc::SingleClass +# * RDoc::MethodAttr +# * RDoc::Attr +# * RDoc::AnyMethod +# * RDoc::GhostMethod +# * RDoc::MetaMethod +# * RDoc::Alias +# * RDoc::Constant +# * RDoc::Mixin +# * RDoc::Require +# * RDoc::Include + +class RDoc::CodeObject + + include RDoc::Text + + ## + # Our comment + + attr_reader :comment + + ## + # Do we document our children? + + attr_reader :document_children + + ## + # Do we document ourselves? + + attr_reader :document_self + + ## + # Are we done documenting (ie, did we come across a :enddoc:)? + + attr_reader :done_documenting + + ## + # Which file this code object was defined in + + attr_reader :file + + ## + # Force documentation of this CodeObject + + attr_reader :force_documentation + + ## + # Line in #file where this CodeObject was defined + + attr_accessor :line + + ## + # Hash of arbitrary metadata for this CodeObject + + attr_reader :metadata + + ## + # Sets the parent CodeObject + + attr_writer :parent + + ## + # Did we ever receive a +:nodoc:+ directive? + + attr_reader :received_nodoc + + ## + # Set the section this CodeObject is in + + attr_writer :section + + ## + # The RDoc::Store for this object. + + attr_reader :store + + ## + # We are the model of the code, but we know that at some point we will be + # worked on by viewers. By implementing the Viewable protocol, viewers can + # associated themselves with these objects. + + attr_accessor :viewer + + ## + # Creates a new CodeObject that will document itself and its children + + def initialize + @metadata = {} + @comment = '' + @parent = nil + @parent_name = nil # for loading + @parent_class = nil # for loading + @section = nil + @section_title = nil # for loading + @file = nil + @full_name = nil + @store = nil + @track_visibility = true + + initialize_visibility + end + + ## + # Initializes state for visibility of this CodeObject and its children. + + def initialize_visibility # :nodoc: + @document_children = true + @document_self = true + @done_documenting = false + @force_documentation = false + @received_nodoc = false + @ignored = false + @suppressed = false + @track_visibility = true + end + + ## + # Replaces our comment with +comment+, unless it is empty. + + def comment=(comment) + @comment = case comment + when NilClass then '' + when RDoc::Markup::Document then comment + when RDoc::Comment then comment.normalize + else + if comment and not comment.empty? then + normalize_comment comment + else + # HACK correct fix is to have #initialize create @comment + # with the correct encoding + if String === @comment and @comment.empty? then + @comment = RDoc::Encoding.change_encoding @comment, comment.encoding + end + @comment + end + end + end + + ## + # Should this CodeObject be displayed in output? + # + # A code object should be displayed if: + # + # * The item didn't have a nodoc or wasn't in a container that had nodoc + # * The item wasn't ignored + # * The item has documentation and was not suppressed + + def display? + @document_self and not @ignored and + (documented? or not @suppressed) + end + + ## + # Enables or disables documentation of this CodeObject's children unless it + # has been turned off by :enddoc: + + def document_children=(document_children) + return unless @track_visibility + + @document_children = document_children unless @done_documenting + end + + ## + # Enables or disables documentation of this CodeObject unless it has been + # turned off by :enddoc:. If the argument is +nil+ it means the + # documentation is turned off by +:nodoc:+. + + def document_self=(document_self) + return unless @track_visibility + return if @done_documenting + + @document_self = document_self + @received_nodoc = true if document_self.nil? + end + + ## + # Does this object have a comment with content or is #received_nodoc true? + + def documented? + @received_nodoc or !@comment.empty? + end + + ## + # Turns documentation on/off, and turns on/off #document_self + # and #document_children. + # + # Once documentation has been turned off (by +:enddoc:+), + # the object will refuse to turn #document_self or + # #document_children on, so +:doc:+ and +:start_doc:+ directives + # will have no effect in the current file. + + def done_documenting=(value) + return unless @track_visibility + @done_documenting = value + @document_self = !value + @document_children = @document_self + end + + ## + # Yields each parent of this CodeObject. See also + # RDoc::ClassModule#each_ancestor + + def each_parent + code_object = self + + while code_object = code_object.parent do + yield code_object + end + + self + end + + ## + # File name where this CodeObject was found. + # + # See also RDoc::Context#in_files + + def file_name + return unless @file + + @file.absolute_name + end + + ## + # Force the documentation of this object unless documentation + # has been turned off by :enddoc: + #-- + # HACK untested, was assigning to an ivar + + def force_documentation=(value) + @force_documentation = value unless @done_documenting + end + + ## + # Sets the full_name overriding any computed full name. + # + # Set to +nil+ to clear RDoc's cached value + + def full_name= full_name + @full_name = full_name + end + + ## + # Use this to ignore a CodeObject and all its children until found again + # (#record_location is called). An ignored item will not be displayed in + # documentation. + # + # See github issue #55 + # + # The ignored status is temporary in order to allow implementation details + # to be hidden. At the end of processing a file RDoc allows all classes + # and modules to add new documentation to previously created classes. + # + # If a class was ignored (via stopdoc) then reopened later with additional + # documentation it should be displayed. If a class was ignored and never + # reopened it should not be displayed. The ignore flag allows this to + # occur. + + def ignore + return unless @track_visibility + + @ignored = true + + stop_doc + end + + ## + # Has this class been ignored? + # + # See also #ignore + + def ignored? + @ignored + end + + ## + # The options instance from the store this CodeObject is attached to, or a + # default options instance if the CodeObject is not attached. + # + # This is used by Text#snippet + + def options + if @store and @store.rdoc then + @store.rdoc.options + else + RDoc::Options.new + end + end + + ## + # Our parent CodeObject. The parent may be missing for classes loaded from + # legacy RI data stores. + + def parent + return @parent if @parent + return nil unless @parent_name + + if @parent_class == RDoc::TopLevel then + @parent = @store.add_file @parent_name + else + @parent = @store.find_class_or_module @parent_name + + return @parent if @parent + + begin + @parent = @store.load_class @parent_name + rescue RDoc::Store::MissingFileError + nil + end + end + end + + ## + # File name of our parent + + def parent_file_name + @parent ? @parent.base_name : '(unknown)' + end + + ## + # Name of our parent + + def parent_name + @parent ? @parent.full_name : '(unknown)' + end + + ## + # Records the RDoc::TopLevel (file) where this code object was defined + + def record_location top_level + @ignored = false + @suppressed = false + @file = top_level + end + + ## + # The section this CodeObject is in. Sections allow grouping of constants, + # attributes and methods inside a class or module. + + def section + return @section if @section + + @section = parent.add_section @section_title if parent + end + + ## + # Enable capture of documentation unless documentation has been + # turned off by :enddoc: + + def start_doc + return if @done_documenting + + @document_self = true + @document_children = true + @ignored = false + @suppressed = false + end + + ## + # Disable capture of documentation + + def stop_doc + return unless @track_visibility + + @document_self = false + @document_children = false + end + + ## + # Sets the +store+ that contains this CodeObject + + def store= store + @store = store + + return unless @track_visibility + + if :nodoc == options.visibility then + initialize_visibility + @track_visibility = false + end + end + + ## + # Use this to suppress a CodeObject and all its children until the next file + # it is seen in or documentation is discovered. A suppressed item with + # documentation will be displayed while an ignored item with documentation + # may not be displayed. + + def suppress + return unless @track_visibility + + @suppressed = true + + stop_doc + end + + ## + # Has this class been suppressed? + # + # See also #suppress + + def suppressed? + @suppressed + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/code_objects.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/code_objects.rb new file mode 100644 index 0000000..434a25a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/code_objects.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true +# This file was used to load all the RDoc::CodeObject subclasses at once. Now +# autoload handles this. + +require 'rdoc' + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/comment.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/comment.rb new file mode 100644 index 0000000..9e90999 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/comment.rb @@ -0,0 +1,250 @@ +# frozen_string_literal: true +## +# A comment holds the text comment for a RDoc::CodeObject and provides a +# unified way of cleaning it up and parsing it into an RDoc::Markup::Document. +# +# Each comment may have a different markup format set by #format=. By default +# 'rdoc' is used. The :markup: directive tells RDoc which format to use. +# +# See RDoc::Markup@Other+directives for instructions on adding an alternate +# format. + +class RDoc::Comment + + include RDoc::Text + + ## + # The format of this comment. Defaults to RDoc::Markup + + attr_reader :format + + ## + # The RDoc::TopLevel this comment was found in + + attr_accessor :location + + ## + # Line where this Comment was written + + attr_accessor :line + + ## + # For duck-typing when merging classes at load time + + alias file location # :nodoc: + + ## + # The text for this comment + + attr_reader :text + + ## + # Alias for text + + alias to_s text + + ## + # Overrides the content returned by #parse. Use when there is no #text + # source for this comment + + attr_writer :document + + ## + # Creates a new comment with +text+ that is found in the RDoc::TopLevel + # +location+. + + def initialize text = nil, location = nil, language = nil + @location = location + @text = text.nil? ? nil : text.dup + @language = language + + @document = nil + @format = 'rdoc' + @normalized = false + end + + ## + #-- + # TODO deep copy @document + + def initialize_copy copy # :nodoc: + @text = copy.text.dup + end + + def == other # :nodoc: + self.class === other and + other.text == @text and other.location == @location + end + + ## + # Look for a 'call-seq' in the comment to override the normal parameter + # handling. The :call-seq: is indented from the baseline. All lines of the + # same indentation level and prefix are consumed. + # + # For example, all of the following will be used as the :call-seq: + # + # # :call-seq: + # # ARGF.readlines(sep=$/) -> array + # # ARGF.readlines(limit) -> array + # # ARGF.readlines(sep, limit) -> array + # # + # # ARGF.to_a(sep=$/) -> array + # # ARGF.to_a(limit) -> array + # # ARGF.to_a(sep, limit) -> array + + def extract_call_seq method + # we must handle situations like the above followed by an unindented first + # comment. The difficulty is to make sure not to match lines starting + # with ARGF at the same indent, but that are after the first description + # paragraph. + if @text =~ /^\s*:?call-seq:(.*?(?:\S).*?)^\s*$/m then + all_start, all_stop = $~.offset(0) + seq_start, seq_stop = $~.offset(1) + + # we get the following lines that start with the leading word at the + # same indent, even if they have blank lines before + if $1 =~ /(^\s*\n)+^(\s*\w+)/m then + leading = $2 # ' * ARGF' in the example above + re = %r% + \A( + (^\s*\n)+ + (^#{Regexp.escape leading}.*?\n)+ + )+ + ^\s*$ + %xm + + if @text[seq_stop..-1] =~ re then + all_stop = seq_stop + $~.offset(0).last + seq_stop = seq_stop + $~.offset(1).last + end + end + + seq = @text[seq_start..seq_stop] + seq.gsub!(/^\s*(\S|\n)/m, '\1') + @text.slice! all_start...all_stop + + method.call_seq = seq.chomp + + else + regexp = /^\s*:?call-seq:(.*?)(^\s*$|\z)/m + if regexp =~ @text then + @text = @text.sub(regexp, '') + seq = $1 + seq.gsub!(/^\s*/, '') + method.call_seq = seq + end + end + + method + end + + ## + # A comment is empty if its text String is empty. + + def empty? + @text.empty? + end + + ## + # HACK dubious + + def encode! encoding + # TODO: Remove this condition after Ruby 2.2 EOL + if RUBY_VERSION < '2.3.0' + @text = @text.force_encoding encoding + else + @text = String.new @text, encoding: encoding + end + self + end + + ## + # Sets the format of this comment and resets any parsed document + + def format= format + @format = format + @document = nil + end + + def inspect # :nodoc: + location = @location ? @location.relative_name : '(unknown)' + + "#<%s:%x %s %p>" % [self.class, object_id, location, @text] + end + + ## + # Normalizes the text. See RDoc::Text#normalize_comment for details + + def normalize + return self unless @text + return self if @normalized # TODO eliminate duplicate normalization + + @text = normalize_comment @text + + @normalized = true + + self + end + + ## + # Was this text normalized? + + def normalized? # :nodoc: + @normalized + end + + ## + # Parses the comment into an RDoc::Markup::Document. The parsed document is + # cached until the text is changed. + + def parse + return @document if @document + + @document = super @text, @format + @document.file = @location + @document + end + + ## + # Removes private sections from this comment. Private sections are flush to + # the comment marker and start with -- and end with ++. + # For C-style comments, a private marker may not start at the opening of the + # comment. + # + # /* + # *-- + # * private + # *++ + # * public + # */ + + def remove_private + # Workaround for gsub encoding for Ruby 1.9.2 and earlier + empty = '' + empty = RDoc::Encoding.change_encoding empty, @text.encoding + + @text = @text.gsub(%r%^\s*([#*]?)--.*?^\s*(\1)\+\+\n?%m, empty) + @text = @text.sub(%r%^\s*[#*]?--.*%m, '') + end + + ## + # Replaces this comment's text with +text+ and resets the parsed document. + # + # An error is raised if the comment contains a document but no text. + + def text= text + raise RDoc::Error, 'replacing document-only comment is not allowed' if + @text.nil? and @document + + @document = nil + @text = text.nil? ? nil : text.dup + end + + ## + # Returns true if this comment is in TomDoc format. + + def tomdoc? + @format == 'tomdoc' + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/constant.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/constant.rb new file mode 100644 index 0000000..0c3d750 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/constant.rb @@ -0,0 +1,187 @@ +# frozen_string_literal: true +## +# A constant + +class RDoc::Constant < RDoc::CodeObject + + MARSHAL_VERSION = 0 # :nodoc: + + ## + # Sets the module or class this is constant is an alias for. + + attr_writer :is_alias_for + + ## + # The constant's name + + attr_accessor :name + + ## + # The constant's value + + attr_accessor :value + + ## + # The constant's visibility + + attr_accessor :visibility + + ## + # Creates a new constant with +name+, +value+ and +comment+ + + def initialize(name, value, comment) + super() + + @name = name + @value = value + + @is_alias_for = nil + @visibility = :public + + self.comment = comment + end + + ## + # Constants are ordered by name + + def <=> other + return unless self.class === other + + [parent_name, name] <=> [other.parent_name, other.name] + end + + ## + # Constants are equal when their #parent and #name is the same + + def == other + self.class == other.class and + @parent == other.parent and + @name == other.name + end + + ## + # A constant is documented if it has a comment, or is an alias + # for a documented class or module. + + def documented? + return true if super + return false unless @is_alias_for + case @is_alias_for + when String then + found = @store.find_class_or_module @is_alias_for + return false unless found + @is_alias_for = found + end + @is_alias_for.documented? + end + + ## + # Full constant name including namespace + + def full_name + @full_name ||= "#{parent_name}::#{@name}" + end + + ## + # The module or class this constant is an alias for + + def is_alias_for + case @is_alias_for + when String then + found = @store.find_class_or_module @is_alias_for + @is_alias_for = found if found + @is_alias_for + else + @is_alias_for + end + end + + def inspect # :nodoc: + "#<%s:0x%x %s::%s>" % [ + self.class, object_id, + parent_name, @name, + ] + end + + ## + # Dumps this Constant for use by ri. See also #marshal_load + + def marshal_dump + alias_name = case found = is_alias_for + when RDoc::CodeObject then found.full_name + else found + end + + [ MARSHAL_VERSION, + @name, + full_name, + @visibility, + alias_name, + parse(@comment), + @file.relative_name, + parent.name, + parent.class, + section.title, + ] + end + + ## + # Loads this Constant from +array+. For a loaded Constant the following + # methods will return cached values: + # + # * #full_name + # * #parent_name + + def marshal_load array + initialize array[1], nil, array[5] + + @full_name = array[2] + @visibility = array[3] || :public + @is_alias_for = array[4] + # 5 handled above + # 6 handled below + @parent_name = array[7] + @parent_class = array[8] + @section_title = array[9] + + @file = RDoc::TopLevel.new array[6] + end + + ## + # Path to this constant for use with HTML generator output. + + def path + "#{@parent.path}##{@name}" + end + + def pretty_print q # :nodoc: + q.group 2, "[#{self.class.name} #{full_name}", "]" do + unless comment.empty? then + q.breakable + q.text "comment:" + q.breakable + q.pp @comment + end + end + end + + ## + # Sets the store for this class or module and its contained code objects. + + def store= store + super + + @file = @store.add_file @file.full_name if @file + end + + def to_s # :nodoc: + parent_name = parent ? parent.full_name : '(unknown)' + if is_alias_for + "constant #{parent_name}::#@name -> #{is_alias_for}" + else + "constant #{parent_name}::#@name" + end + end + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/context.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/context.rb new file mode 100644 index 0000000..b3caa53 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/context.rb @@ -0,0 +1,1266 @@ +# frozen_string_literal: true +require 'cgi' + +## +# A Context is something that can hold modules, classes, methods, attributes, +# aliases, requires, and includes. Classes, modules, and files are all +# Contexts. + +class RDoc::Context < RDoc::CodeObject + + include Comparable + + ## + # Types of methods + + TYPES = %w[class instance] + + ## + # If a context has these titles it will be sorted in this order. + + TOMDOC_TITLES = [nil, 'Public', 'Internal', 'Deprecated'] # :nodoc: + TOMDOC_TITLES_SORT = TOMDOC_TITLES.sort_by { |title| title.to_s } # :nodoc: + + ## + # Class/module aliases + + attr_reader :aliases + + ## + # All attr* methods + + attr_reader :attributes + + ## + # Block params to be used in the next MethodAttr parsed under this context + + attr_accessor :block_params + + ## + # Constants defined + + attr_reader :constants + + ## + # Sets the current documentation section of documentation + + attr_writer :current_section + + ## + # Files this context is found in + + attr_reader :in_files + + ## + # Modules this context includes + + attr_reader :includes + + ## + # Modules this context is extended with + + attr_reader :extends + + ## + # Methods defined in this context + + attr_reader :method_list + + ## + # Name of this class excluding namespace. See also full_name + + attr_reader :name + + ## + # Files this context requires + + attr_reader :requires + + ## + # Use this section for the next method, attribute or constant added. + + attr_accessor :temporary_section + + ## + # Hash old_name => [aliases], for aliases + # that haven't (yet) been resolved to a method/attribute. + # (Not to be confused with the aliases of the context.) + + attr_accessor :unmatched_alias_lists + + ## + # Aliases that could not be resolved. + + attr_reader :external_aliases + + ## + # Current visibility of this context + + attr_accessor :visibility + + ## + # Current visibility of this line + + attr_writer :current_line_visibility + + ## + # Hash of registered methods. Attributes are also registered here, + # twice if they are RW. + + attr_reader :methods_hash + + ## + # Params to be used in the next MethodAttr parsed under this context + + attr_accessor :params + + ## + # Hash of registered constants. + + attr_reader :constants_hash + + ## + # Creates an unnamed empty context with public current visibility + + def initialize + super + + @in_files = [] + + @name ||= "unknown" + @parent = nil + @visibility = :public + + @current_section = Section.new self, nil, nil + @sections = { nil => @current_section } + @temporary_section = nil + + @classes = {} + @modules = {} + + initialize_methods_etc + end + + ## + # Sets the defaults for methods and so-forth + + def initialize_methods_etc + @method_list = [] + @attributes = [] + @aliases = [] + @requires = [] + @includes = [] + @extends = [] + @constants = [] + @external_aliases = [] + @current_line_visibility = nil + + # This Hash maps a method name to a list of unmatched aliases (aliases of + # a method not yet encountered). + @unmatched_alias_lists = {} + + @methods_hash = {} + @constants_hash = {} + + @params = nil + + @store ||= nil + end + + ## + # Contexts are sorted by full_name + + def <=>(other) + return nil unless RDoc::CodeObject === other + + full_name <=> other.full_name + end + + ## + # Adds an item of type +klass+ with the given +name+ and +comment+ to the + # context. + # + # Currently only RDoc::Extend and RDoc::Include are supported. + + def add klass, name, comment + if RDoc::Extend == klass then + ext = RDoc::Extend.new name, comment + add_extend ext + elsif RDoc::Include == klass then + incl = RDoc::Include.new name, comment + add_include incl + else + raise NotImplementedError, "adding a #{klass} is not implemented" + end + end + + ## + # Adds +an_alias+ that is automatically resolved + + def add_alias an_alias + return an_alias unless @document_self + + method_attr = find_method(an_alias.old_name, an_alias.singleton) || + find_attribute(an_alias.old_name, an_alias.singleton) + + if method_attr then + method_attr.add_alias an_alias, self + else + add_to @external_aliases, an_alias + unmatched_alias_list = + @unmatched_alias_lists[an_alias.pretty_old_name] ||= [] + unmatched_alias_list.push an_alias + end + + an_alias + end + + ## + # Adds +attribute+ if not already there. If it is (as method(s) or attribute), + # updates the comment if it was empty. + # + # The attribute is registered only if it defines a new method. + # For instance, attr_reader :foo will not be registered + # if method +foo+ exists, but attr_accessor :foo will be registered + # if method +foo+ exists, but foo= does not. + + def add_attribute attribute + return attribute unless @document_self + + # mainly to check for redefinition of an attribute as a method + # TODO find a policy for 'attr_reader :foo' + 'def foo=()' + register = false + + key = nil + + if attribute.rw.index 'R' then + key = attribute.pretty_name + known = @methods_hash[key] + + if known then + known.comment = attribute.comment if known.comment.empty? + elsif registered = @methods_hash[attribute.pretty_name + '='] and + RDoc::Attr === registered then + registered.rw = 'RW' + else + @methods_hash[key] = attribute + register = true + end + end + + if attribute.rw.index 'W' then + key = attribute.pretty_name + '=' + known = @methods_hash[key] + + if known then + known.comment = attribute.comment if known.comment.empty? + elsif registered = @methods_hash[attribute.pretty_name] and + RDoc::Attr === registered then + registered.rw = 'RW' + else + @methods_hash[key] = attribute + register = true + end + end + + if register then + attribute.visibility = @visibility + add_to @attributes, attribute + resolve_aliases attribute + end + + attribute + end + + ## + # Adds a class named +given_name+ with +superclass+. + # + # Both +given_name+ and +superclass+ may contain '::', and are + # interpreted relative to the +self+ context. This allows handling correctly + # examples like these: + # class RDoc::Gauntlet < Gauntlet + # module Mod + # class Object # implies < ::Object + # class SubObject < Object # this is _not_ ::Object + # + # Given class Container::Item RDoc assumes +Container+ is a module + # unless it later sees class Container. +add_class+ automatically + # upgrades +given_name+ to a class in this case. + + def add_class class_type, given_name, superclass = '::Object' + # superclass +nil+ is passed by the C parser in the following cases: + # - registering Object in 1.8 (correct) + # - registering BasicObject in 1.9 (correct) + # - registering RubyVM in 1.9 in iseq.c (incorrect: < Object in vm.c) + # + # If we later find a superclass for a registered class with a nil + # superclass, we must honor it. + + # find the name & enclosing context + if given_name =~ /^:+(\w+)$/ then + full_name = $1 + enclosing = top_level + name = full_name.split(/:+/).last + else + full_name = child_name given_name + + if full_name =~ /^(.+)::(\w+)$/ then + name = $2 + ename = $1 + enclosing = @store.classes_hash[ename] || @store.modules_hash[ename] + # HACK: crashes in actionpack/lib/action_view/helpers/form_helper.rb (metaprogramming) + unless enclosing then + # try the given name at top level (will work for the above example) + enclosing = @store.classes_hash[given_name] || + @store.modules_hash[given_name] + return enclosing if enclosing + # not found: create the parent(s) + names = ename.split('::') + enclosing = self + names.each do |n| + enclosing = enclosing.classes_hash[n] || + enclosing.modules_hash[n] || + enclosing.add_module(RDoc::NormalModule, n) + end + end + else + name = full_name + enclosing = self + end + end + + # fix up superclass + if full_name == 'BasicObject' then + superclass = nil + elsif full_name == 'Object' then + superclass = '::BasicObject' + end + + # find the superclass full name + if superclass then + if superclass =~ /^:+/ then + superclass = $' #' + else + if superclass =~ /^(\w+):+(.+)$/ then + suffix = $2 + mod = find_module_named($1) + superclass = mod.full_name + '::' + suffix if mod + else + mod = find_module_named(superclass) + superclass = mod.full_name if mod + end + end + + # did we believe it was a module? + mod = @store.modules_hash.delete superclass + + upgrade_to_class mod, RDoc::NormalClass, mod.parent if mod + + # e.g., Object < Object + superclass = nil if superclass == full_name + end + + klass = @store.classes_hash[full_name] + + if klass then + # if TopLevel, it may not be registered in the classes: + enclosing.classes_hash[name] = klass + + # update the superclass if needed + if superclass then + existing = klass.superclass + existing = existing.full_name unless existing.is_a?(String) if existing + if existing.nil? || + (existing == 'Object' && superclass != 'Object') then + klass.superclass = superclass + end + end + else + # this is a new class + mod = @store.modules_hash.delete full_name + + if mod then + klass = upgrade_to_class mod, RDoc::NormalClass, enclosing + + klass.superclass = superclass unless superclass.nil? + else + klass = class_type.new name, superclass + + enclosing.add_class_or_module(klass, enclosing.classes_hash, + @store.classes_hash) + end + end + + klass.parent = self + + klass + end + + ## + # Adds the class or module +mod+ to the modules or + # classes Hash +self_hash+, and to +all_hash+ (either + # TopLevel::modules_hash or TopLevel::classes_hash), + # unless #done_documenting is +true+. Sets the #parent of +mod+ + # to +self+, and its #section to #current_section. Returns +mod+. + + def add_class_or_module mod, self_hash, all_hash + mod.section = current_section # TODO declaring context? something is + # wrong here... + mod.parent = self + mod.full_name = nil + mod.store = @store + + unless @done_documenting then + self_hash[mod.name] = mod + # this must be done AFTER adding mod to its parent, so that the full + # name is correct: + all_hash[mod.full_name] = mod + if @store.unmatched_constant_alias[mod.full_name] then + to, file = @store.unmatched_constant_alias[mod.full_name] + add_module_alias mod, mod.name, to, file + end + end + + mod + end + + ## + # Adds +constant+ if not already there. If it is, updates the comment, + # value and/or is_alias_for of the known constant if they were empty/nil. + + def add_constant constant + return constant unless @document_self + + # HACK: avoid duplicate 'PI' & 'E' in math.c (1.8.7 source code) + # (this is a #ifdef: should be handled by the C parser) + known = @constants_hash[constant.name] + + if known then + known.comment = constant.comment if known.comment.empty? + + known.value = constant.value if + known.value.nil? or known.value.strip.empty? + + known.is_alias_for ||= constant.is_alias_for + else + @constants_hash[constant.name] = constant + add_to @constants, constant + end + + constant + end + + ## + # Adds included module +include+ which should be an RDoc::Include + + def add_include include + add_to @includes, include + + include + end + + ## + # Adds extension module +ext+ which should be an RDoc::Extend + + def add_extend ext + add_to @extends, ext + + ext + end + + ## + # Adds +method+ if not already there. If it is (as method or attribute), + # updates the comment if it was empty. + + def add_method method + return method unless @document_self + + # HACK: avoid duplicate 'new' in io.c & struct.c (1.8.7 source code) + key = method.pretty_name + known = @methods_hash[key] + + if known then + if @store then # otherwise we are loading + known.comment = method.comment if known.comment.empty? + previously = ", previously in #{known.file}" unless + method.file == known.file + @store.rdoc.options.warn \ + "Duplicate method #{known.full_name} in #{method.file}#{previously}" + end + else + @methods_hash[key] = method + if @current_line_visibility + method.visibility, @current_line_visibility = @current_line_visibility, nil + else + method.visibility = @visibility + end + add_to @method_list, method + resolve_aliases method + end + + method + end + + ## + # Adds a module named +name+. If RDoc already knows +name+ is a class then + # that class is returned instead. See also #add_class. + + def add_module(class_type, name) + mod = @classes[name] || @modules[name] + return mod if mod + + full_name = child_name name + mod = @store.modules_hash[full_name] || class_type.new(name) + + add_class_or_module mod, @modules, @store.modules_hash + end + + ## + # Adds a module by +RDoc::NormalModule+ instance. See also #add_module. + + def add_module_by_normal_module(mod) + add_class_or_module mod, @modules, @store.modules_hash + end + + ## + # Adds an alias from +from+ (a class or module) to +name+ which was defined + # in +file+. + + def add_module_alias from, from_name, to, file + return from if @done_documenting + + to_full_name = child_name to.name + + # if we already know this name, don't register an alias: + # see the metaprogramming in lib/active_support/basic_object.rb, + # where we already know BasicObject is a class when we find + # BasicObject = BlankSlate + return from if @store.find_class_or_module to_full_name + + unless from + @store.unmatched_constant_alias[child_name(from_name)] = [to, file] + return to + end + + new_to = from.dup + new_to.name = to.name + new_to.full_name = nil + + if new_to.module? then + @store.modules_hash[to_full_name] = new_to + @modules[to.name] = new_to + else + @store.classes_hash[to_full_name] = new_to + @classes[to.name] = new_to + end + + # Registers a constant for this alias. The constant value and comment + # will be updated later, when the Ruby parser adds the constant + const = RDoc::Constant.new to.name, nil, new_to.comment + const.record_location file + const.is_alias_for = from + add_constant const + + new_to + end + + ## + # Adds +require+ to this context's top level + + def add_require(require) + return require unless @document_self + + if RDoc::TopLevel === self then + add_to @requires, require + else + parent.add_require require + end + end + + ## + # Returns a section with +title+, creating it if it doesn't already exist. + # +comment+ will be appended to the section's comment. + # + # A section with a +title+ of +nil+ will return the default section. + # + # See also RDoc::Context::Section + + def add_section title, comment = nil + if section = @sections[title] then + section.add_comment comment if comment + else + section = Section.new self, title, comment + @sections[title] = section + end + + section + end + + ## + # Adds +thing+ to the collection +array+ + + def add_to array, thing + array << thing if @document_self + + thing.parent = self + thing.store = @store if @store + thing.section = current_section + end + + ## + # Is there any content? + # + # This means any of: comment, aliases, methods, attributes, external + # aliases, require, constant. + # + # Includes and extends are also checked unless includes == false. + + def any_content(includes = true) + @any_content ||= !( + @comment.empty? && + @method_list.empty? && + @attributes.empty? && + @aliases.empty? && + @external_aliases.empty? && + @requires.empty? && + @constants.empty? + ) + @any_content || (includes && !(@includes + @extends).empty? ) + end + + ## + # Creates the full name for a child with +name+ + + def child_name name + if name =~ /^:+/ + $' #' + elsif RDoc::TopLevel === self then + name + else + "#{self.full_name}::#{name}" + end + end + + ## + # Class attributes + + def class_attributes + @class_attributes ||= attributes.select { |a| a.singleton } + end + + ## + # Class methods + + def class_method_list + @class_method_list ||= method_list.select { |a| a.singleton } + end + + ## + # Array of classes in this context + + def classes + @classes.values + end + + ## + # All classes and modules in this namespace + + def classes_and_modules + classes + modules + end + + ## + # Hash of classes keyed by class name + + def classes_hash + @classes + end + + ## + # The current documentation section that new items will be added to. If + # temporary_section is available it will be used. + + def current_section + if section = @temporary_section then + @temporary_section = nil + else + section = @current_section + end + + section + end + + ## + # Is part of this thing was defined in +file+? + + def defined_in?(file) + @in_files.include?(file) + end + + def display(method_attr) # :nodoc: + if method_attr.is_a? RDoc::Attr + "#{method_attr.definition} #{method_attr.pretty_name}" + else + "method #{method_attr.pretty_name}" + end + end + + ## + # Iterator for ancestors for duck-typing. Does nothing. See + # RDoc::ClassModule#each_ancestor. + # + # This method exists to make it easy to work with Context subclasses that + # aren't part of RDoc. + + def each_ancestor # :nodoc: + end + + ## + # Iterator for attributes + + def each_attribute # :yields: attribute + @attributes.each { |a| yield a } + end + + ## + # Iterator for classes and modules + + def each_classmodule(&block) # :yields: module + classes_and_modules.sort.each(&block) + end + + ## + # Iterator for constants + + def each_constant # :yields: constant + @constants.each {|c| yield c} + end + + ## + # Iterator for included modules + + def each_include # :yields: include + @includes.each do |i| yield i end + end + + ## + # Iterator for extension modules + + def each_extend # :yields: extend + @extends.each do |e| yield e end + end + + ## + # Iterator for methods + + def each_method # :yields: method + return enum_for __method__ unless block_given? + + @method_list.sort.each { |m| yield m } + end + + ## + # Iterator for each section's contents sorted by title. The +section+, the + # section's +constants+ and the sections +attributes+ are yielded. The + # +constants+ and +attributes+ collections are sorted. + # + # To retrieve methods in a section use #methods_by_type with the optional + # +section+ parameter. + # + # NOTE: Do not edit collections yielded by this method + + def each_section # :yields: section, constants, attributes + return enum_for __method__ unless block_given? + + constants = @constants.group_by do |constant| constant.section end + attributes = @attributes.group_by do |attribute| attribute.section end + + constants.default = [] + attributes.default = [] + + sort_sections.each do |section| + yield section, constants[section].select(&:display?).sort, attributes[section].select(&:display?).sort + end + end + + ## + # Finds an attribute +name+ with singleton value +singleton+. + + def find_attribute(name, singleton) + name = $1 if name =~ /^(.*)=$/ + @attributes.find { |a| a.name == name && a.singleton == singleton } + end + + ## + # Finds an attribute with +name+ in this context + + def find_attribute_named(name) + case name + when /\A#/ then + find_attribute name[1..-1], false + when /\A::/ then + find_attribute name[2..-1], true + else + @attributes.find { |a| a.name == name } + end + end + + ## + # Finds a class method with +name+ in this context + + def find_class_method_named(name) + @method_list.find { |meth| meth.singleton && meth.name == name } + end + + ## + # Finds a constant with +name+ in this context + + def find_constant_named(name) + @constants.find do |m| + m.name == name || m.full_name == name + end + end + + ## + # Find a module at a higher scope + + def find_enclosing_module_named(name) + parent && parent.find_module_named(name) + end + + ## + # Finds an external alias +name+ with singleton value +singleton+. + + def find_external_alias(name, singleton) + @external_aliases.find { |m| m.name == name && m.singleton == singleton } + end + + ## + # Finds an external alias with +name+ in this context + + def find_external_alias_named(name) + case name + when /\A#/ then + find_external_alias name[1..-1], false + when /\A::/ then + find_external_alias name[2..-1], true + else + @external_aliases.find { |a| a.name == name } + end + end + + ## + # Finds a file with +name+ in this context + + def find_file_named name + @store.find_file_named name + end + + ## + # Finds an instance method with +name+ in this context + + def find_instance_method_named(name) + @method_list.find { |meth| !meth.singleton && meth.name == name } + end + + ## + # Finds a method, constant, attribute, external alias, module or file + # named +symbol+ in this context. + + def find_local_symbol(symbol) + find_method_named(symbol) or + find_constant_named(symbol) or + find_attribute_named(symbol) or + find_external_alias_named(symbol) or + find_module_named(symbol) or + find_file_named(symbol) + end + + ## + # Finds a method named +name+ with singleton value +singleton+. + + def find_method(name, singleton) + @method_list.find { |m| + if m.singleton + m.name == name && m.singleton == singleton + else + m.name == name && !m.singleton && !singleton + end + } + end + + ## + # Finds a instance or module method with +name+ in this context + + def find_method_named(name) + case name + when /\A#/ then + find_method name[1..-1], false + when /\A::/ then + find_method name[2..-1], true + else + @method_list.find { |meth| meth.name == name } + end + end + + ## + # Find a module with +name+ using ruby's scoping rules + + def find_module_named(name) + res = @modules[name] || @classes[name] + return res if res + return self if self.name == name + find_enclosing_module_named name + end + + ## + # Look up +symbol+, first as a module, then as a local symbol. + + def find_symbol(symbol) + find_symbol_module(symbol) || find_local_symbol(symbol) + end + + ## + # Look up a module named +symbol+. + + def find_symbol_module(symbol) + result = nil + + # look for a class or module 'symbol' + case symbol + when /^::/ then + result = @store.find_class_or_module symbol + when /^(\w+):+(.+)$/ + suffix = $2 + top = $1 + searched = self + while searched do + mod = searched.find_module_named(top) + break unless mod + result = @store.find_class_or_module "#{mod.full_name}::#{suffix}" + break if result || searched.is_a?(RDoc::TopLevel) + searched = searched.parent + end + else + searched = self + while searched do + result = searched.find_module_named(symbol) + break if result || searched.is_a?(RDoc::TopLevel) + searched = searched.parent + end + end + + result + end + + ## + # The full name for this context. This method is overridden by subclasses. + + def full_name + '(unknown)' + end + + ## + # Does this context and its methods and constants all have documentation? + # + # (Yes, fully documented doesn't mean everything.) + + def fully_documented? + documented? and + attributes.all? { |a| a.documented? } and + method_list.all? { |m| m.documented? } and + constants.all? { |c| c.documented? } + end + + ## + # URL for this with a +prefix+ + + def http_url(prefix) + path = name_for_path + path = path.gsub(/<<\s*(\w*)/, 'from-\1') if path =~ /<'class' or + # 'instance') and visibility (+:public+, +:protected+, +:private+). + # + # If +section+ is provided only methods in that RDoc::Context::Section will + # be returned. + + def methods_by_type section = nil + methods = {} + + TYPES.each do |type| + visibilities = {} + RDoc::VISIBILITIES.each do |vis| + visibilities[vis] = [] + end + + methods[type] = visibilities + end + + each_method do |method| + next if section and not method.section == section + methods[method.type][method.visibility] << method + end + + methods + end + + ## + # Yields AnyMethod and Attr entries matching the list of names in +methods+. + + def methods_matching(methods, singleton = false, &block) + (@method_list + @attributes).each do |m| + yield m if methods.include?(m.name) and m.singleton == singleton + end + + each_ancestor do |parent| + parent.methods_matching(methods, singleton, &block) + end + end + + ## + # Array of modules in this context + + def modules + @modules.values + end + + ## + # Hash of modules keyed by module name + + def modules_hash + @modules + end + + ## + # Name to use to generate the url. + # #full_name by default. + + def name_for_path + full_name + end + + ## + # Changes the visibility for new methods to +visibility+ + + def ongoing_visibility=(visibility) + @visibility = visibility + end + + ## + # Record +top_level+ as a file +self+ is in. + + def record_location(top_level) + @in_files << top_level unless @in_files.include?(top_level) + end + + ## + # Should we remove this context from the documentation? + # + # The answer is yes if: + # * #received_nodoc is +true+ + # * #any_content is +false+ (not counting includes) + # * All #includes are modules (not a string), and their module has + # #remove_from_documentation? == true + # * All classes and modules have #remove_from_documentation? == true + + def remove_from_documentation? + @remove_from_documentation ||= + @received_nodoc && + !any_content(false) && + @includes.all? { |i| !i.module.is_a?(String) && i.module.remove_from_documentation? } && + classes_and_modules.all? { |cm| cm.remove_from_documentation? } + end + + ## + # Removes methods and attributes with a visibility less than +min_visibility+. + #-- + # TODO mark the visibility of attributes in the template (if not public?) + + def remove_invisible min_visibility + return if [:private, :nodoc].include? min_visibility + remove_invisible_in @method_list, min_visibility + remove_invisible_in @attributes, min_visibility + remove_invisible_in @constants, min_visibility + end + + ## + # Only called when min_visibility == :public or :private + + def remove_invisible_in array, min_visibility # :nodoc: + if min_visibility == :public then + array.reject! { |e| + e.visibility != :public and not e.force_documentation + } + else + array.reject! { |e| + e.visibility == :private and not e.force_documentation + } + end + end + + ## + # Tries to resolve unmatched aliases when a method or attribute has just + # been added. + + def resolve_aliases added + # resolve any pending unmatched aliases + key = added.pretty_name + unmatched_alias_list = @unmatched_alias_lists[key] + return unless unmatched_alias_list + unmatched_alias_list.each do |unmatched_alias| + added.add_alias unmatched_alias, self + @external_aliases.delete unmatched_alias + end + @unmatched_alias_lists.delete key + end + + ## + # Returns RDoc::Context::Section objects referenced in this context for use + # in a table of contents. + + def section_contents + used_sections = {} + + each_method do |method| + next unless method.display? + + used_sections[method.section] = true + end + + # order found sections + sections = sort_sections.select do |section| + used_sections[section] + end + + # only the default section is used + return [] if + sections.length == 1 and not sections.first.title + + sections + end + + ## + # Sections in this context + + def sections + @sections.values + end + + def sections_hash # :nodoc: + @sections + end + + ## + # Sets the current section to a section with +title+. See also #add_section + + def set_current_section title, comment + @current_section = add_section title, comment + end + + ## + # Given an array +methods+ of method names, set the visibility of each to + # +visibility+ + + def set_visibility_for(methods, visibility, singleton = false) + methods_matching methods, singleton do |m| + m.visibility = visibility + end + end + + ## + # Given an array +names+ of constants, set the visibility of each constant to + # +visibility+ + + def set_constant_visibility_for(names, visibility) + names.each do |name| + constant = @constants_hash[name] or next + constant.visibility = visibility + end + end + + ## + # Sorts sections alphabetically (default) or in TomDoc fashion (none, + # Public, Internal, Deprecated) + + def sort_sections + titles = @sections.map { |title, _| title } + + if titles.length > 1 and + TOMDOC_TITLES_SORT == + (titles | TOMDOC_TITLES).sort_by { |title| title.to_s } then + @sections.values_at(*TOMDOC_TITLES).compact + else + @sections.sort_by { |title, _| + title.to_s + }.map { |_, section| + section + } + end + end + + def to_s # :nodoc: + "#{self.class.name} #{self.full_name}" + end + + ## + # Return the TopLevel that owns us + #-- + # FIXME we can be 'owned' by several TopLevel (see #record_location & + # #in_files) + + def top_level + return @top_level if defined? @top_level + @top_level = self + @top_level = @top_level.parent until RDoc::TopLevel === @top_level + @top_level + end + + ## + # Upgrades NormalModule +mod+ in +enclosing+ to a +class_type+ + + def upgrade_to_class mod, class_type, enclosing + enclosing.modules_hash.delete mod.name + + klass = RDoc::ClassModule.from_module class_type, mod + klass.store = @store + + # if it was there, then we keep it even if done_documenting + @store.classes_hash[mod.full_name] = klass + enclosing.classes_hash[mod.name] = klass + + klass + end + + autoload :Section, 'rdoc/context/section' + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/context/section.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/context/section.rb new file mode 100644 index 0000000..5fef4a9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/context/section.rb @@ -0,0 +1,232 @@ +# frozen_string_literal: true +## +# A section of documentation like: +# +# # :section: The title +# # The body +# +# Sections can be referenced multiple times and will be collapsed into a +# single section. + +class RDoc::Context::Section + + include RDoc::Text + + MARSHAL_VERSION = 0 # :nodoc: + + ## + # Section comment + + attr_reader :comment + + ## + # Section comments + + attr_reader :comments + + ## + # Context this Section lives in + + attr_reader :parent + + ## + # Section title + + attr_reader :title + + ## + # Creates a new section with +title+ and +comment+ + + def initialize parent, title, comment + @parent = parent + @title = title ? title.strip : title + + @comments = [] + + add_comment comment + end + + ## + # Sections are equal when they have the same #title + + def == other + self.class === other and @title == other.title + end + + alias eql? == + + ## + # Adds +comment+ to this section + + def add_comment comment + comment = extract_comment comment + + return if comment.empty? + + case comment + when RDoc::Comment then + @comments << comment + when RDoc::Markup::Document then + @comments.concat comment.parts + when Array then + @comments.concat comment + else + raise TypeError, "unknown comment type: #{comment.inspect}" + end + end + + ## + # Anchor reference for linking to this section + + def aref + title = @title || '[untitled]' + + CGI.escape(title).gsub('%', '-').sub(/^-/, '') + end + + ## + # Extracts the comment for this section from the original comment block. + # If the first line contains :section:, strip it and use the rest. + # Otherwise remove lines up to the line containing :section:, and look + # for those lines again at the end and remove them. This lets us write + # + # # :section: The title + # # The body + + def extract_comment comment + case comment + when Array then + comment.map do |c| + extract_comment c + end + when nil + RDoc::Comment.new '' + when RDoc::Comment then + if comment.text =~ /^#[ \t]*:section:.*\n/ then + start = $` + rest = $' + + comment.text = if start.empty? then + rest + else + rest.sub(/#{start.chomp}\Z/, '') + end + end + + comment + when RDoc::Markup::Document then + comment + else + raise TypeError, "unknown comment #{comment.inspect}" + end + end + + def inspect # :nodoc: + "#<%s:0x%x %p>" % [self.class, object_id, title] + end + + def hash # :nodoc: + @title.hash + end + + ## + # The files comments in this section come from + + def in_files + return [] if @comments.empty? + + case @comments + when Array then + @comments.map do |comment| + comment.file + end + when RDoc::Markup::Document then + @comment.parts.map do |document| + document.file + end + else + raise RDoc::Error, "BUG: unknown comment class #{@comments.class}" + end + end + + ## + # Serializes this Section. The title and parsed comment are saved, but not + # the section parent which must be restored manually. + + def marshal_dump + [ + MARSHAL_VERSION, + @title, + parse, + ] + end + + ## + # De-serializes this Section. The section parent must be restored manually. + + def marshal_load array + @parent = nil + + @title = array[1] + @comments = array[2] + end + + ## + # Parses +comment_location+ into an RDoc::Markup::Document composed of + # multiple RDoc::Markup::Documents with their file set. + + def parse + case @comments + when String then + super + when Array then + docs = @comments.map do |comment, location| + doc = super comment + doc.file = location if location + doc + end + + RDoc::Markup::Document.new(*docs) + when RDoc::Comment then + doc = super @comments.text, comments.format + doc.file = @comments.location + doc + when RDoc::Markup::Document then + return @comments + else + raise ArgumentError, "unknown comment class #{comments.class}" + end + end + + ## + # The section's title, or 'Top Section' if the title is nil. + # + # This is used by the table of contents template so the name is silly. + + def plain_html + @title || 'Top Section' + end + + ## + # Removes a comment from this section if it is from the same file as + # +comment+ + + def remove_comment comment + return if @comments.empty? + + case @comments + when Array then + @comments.delete_if do |my_comment| + my_comment.file == comment.file + end + when RDoc::Markup::Document then + @comments.parts.delete_if do |document| + document.file == comment.file.name + end + else + raise RDoc::Error, "BUG: unknown comment class #{@comments.class}" + end + end + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/cross_reference.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/cross_reference.rb new file mode 100644 index 0000000..ef8e21b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/cross_reference.rb @@ -0,0 +1,210 @@ +# frozen_string_literal: true +## +# RDoc::CrossReference is a reusable way to create cross references for names. + +class RDoc::CrossReference + + ## + # Regular expression to match class references + # + # 1. There can be a '\\' in front of text to suppress the cross-reference + # 2. There can be a '::' in front of class names to reference from the + # top-level namespace. + # 3. The method can be followed by parenthesis (not recommended) + + CLASS_REGEXP_STR = '\\\\?((?:\:{2})?[A-Z]\w*(?:\:\:\w+)*)' + + ## + # Regular expression to match method references. + # + # See CLASS_REGEXP_STR + + METHOD_REGEXP_STR = '([A-Za-z]\w*[!?=]?|%|===?|\[\]=?|<<|>>|\+@|-@|-|\+|\*)(?:\([\w.+*/=<>-]*\))?' + + ## + # Regular expressions matching text that should potentially have + # cross-reference links generated are passed to add_regexp_handling. Note + # that these expressions are meant to pick up text for which cross-references + # have been suppressed, since the suppression characters are removed by the + # code that is triggered. + + CROSSREF_REGEXP = /(?:^|[\s()]) + ( + (?: + # A::B::C.meth + #{CLASS_REGEXP_STR}(?:[.#]|::)#{METHOD_REGEXP_STR} + + # A::B::C + # The stuff after CLASS_REGEXP_STR is a + # nasty hack. CLASS_REGEXP_STR unfortunately matches + # words like dog and cat (these are legal "class" + # names in Fortran 95). When a word is flagged as a + # potential cross-reference, limitations in the markup + # engine suppress other processing, such as typesetting. + # This is particularly noticeable for contractions. + # In order that words like "can't" not + # be flagged as potential cross-references, only + # flag potential class cross-references if the character + # after the cross-reference is a space, sentence + # punctuation, tag start character, or attribute + # marker. + | #{CLASS_REGEXP_STR}(?=[@\s).?!,;<\000]|\z) + + # Stand-alone method (preceded by a #) + | \\?\##{METHOD_REGEXP_STR} + + # Stand-alone method (preceded by ::) + | ::#{METHOD_REGEXP_STR} + + # Things that look like filenames + # The key thing is that there must be at least + # one special character (period, slash, or + # underscore). + | (?:\.\.\/)*[-\/\w]+[_\/.][-\w\/.]+ + + # Things that have markup suppressed + # Don't process things like '\<' in \, though. + # TODO: including < is a hack, not very satisfying. + | \\[^\s<] + ) + + # labels for headings + (?:@[\w+%-]+(?:\.[\w|%-]+)?)? + )/x + + ## + # Version of CROSSREF_REGEXP used when --hyperlink-all is specified. + + ALL_CROSSREF_REGEXP = / + (?:^|[\s()]) + ( + (?: + # A::B::C.meth + #{CLASS_REGEXP_STR}(?:[.#]|::)#{METHOD_REGEXP_STR} + + # A::B::C + | #{CLASS_REGEXP_STR}(?=[@\s).?!,;<\000]|\z) + + # Stand-alone method + | \\?#{METHOD_REGEXP_STR} + + # Things that look like filenames + | (?:\.\.\/)*[-\/\w]+[_\/.][-\w\/.]+ + + # Things that have markup suppressed + | \\[^\s<] + ) + + # labels for headings + (?:@[\w+%-]+)? + )/x + + ## + # Hash of references that have been looked-up to their replacements + + attr_accessor :seen + + ## + # Allows cross-references to be created based on the given +context+ + # (RDoc::Context). + + def initialize context + @context = context + @store = context.store + + @seen = {} + end + + def resolve_method name + ref = nil + + if /#{CLASS_REGEXP_STR}([.#]|::)#{METHOD_REGEXP_STR}/o =~ name then + type = $2 + if '.' == type # will find either #method or ::method + method = $3 + else + method = "#{type}#{$3}" + end + container = @context.find_symbol_module($1) + elsif /^([.#]|::)#{METHOD_REGEXP_STR}/o =~ name then + type = $1 + if '.' == type + method = $2 + else + method = "#{type}#{$2}" + end + container = @context + else + type = nil + container = nil + end + + if container then + unless RDoc::TopLevel === container then + if '.' == type then + if 'new' == method then # AnyClassName.new will be class method + ref = container.find_local_symbol method + ref = container.find_ancestor_local_symbol method unless ref + else + ref = container.find_local_symbol "::#{method}" + ref = container.find_ancestor_local_symbol "::#{method}" unless ref + ref = container.find_local_symbol "##{method}" unless ref + ref = container.find_ancestor_local_symbol "##{method}" unless ref + end + else + ref = container.find_local_symbol method + ref = container.find_ancestor_local_symbol method unless ref + end + end + end + + ref + end + + ## + # Returns a reference to +name+. + # + # If the reference is found and +name+ is not documented +text+ will be + # returned. If +name+ is escaped +name+ is returned. If +name+ is not + # found +text+ is returned. + + def resolve name, text + return @seen[name] if @seen.include? name + + ref = case name + when /^\\(#{CLASS_REGEXP_STR})$/o then + @context.find_symbol $1 + else + @context.find_symbol name + end + + ref = resolve_method name unless ref + + # Try a page name + ref = @store.page name if not ref and name =~ /^[\w.]+$/ + + ref = nil if RDoc::Alias === ref # external alias, can't link to it + + out = if name == '\\' then + name + elsif name =~ /^\\/ then + # we remove the \ only in front of what we know: + # other backslashes are treated later, only outside of + ref ? $' : name + elsif ref then + if ref.display? then + ref + else + text + end + else + text + end + + @seen[name] = out + + out + end + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/encoding.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/encoding.rb new file mode 100644 index 0000000..cf60bad --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/encoding.rb @@ -0,0 +1,136 @@ +# coding: US-ASCII +# frozen_string_literal: true + +## +# This class is a wrapper around File IO and Encoding that helps RDoc load +# files and convert them to the correct encoding. + +module RDoc::Encoding + + HEADER_REGEXP = /^ + (?: + \A\#!.*\n + | + ^\#\s+frozen[-_]string[-_]literal[=:].+\n + | + ^\#[^\n]+\b(?:en)?coding[=:]\s*(?[^\s;]+).*\n + | + <\?xml[^?]*encoding=(?["'])(?.*?)\k.*\n + )+ + /xi # :nodoc: + + ## + # Reads the contents of +filename+ and handles any encoding directives in + # the file. + # + # The content will be converted to the +encoding+. If the file cannot be + # converted a warning will be printed and nil will be returned. + # + # If +force_transcode+ is true the document will be transcoded and any + # unknown character in the target encoding will be replaced with '?' + + def self.read_file filename, encoding, force_transcode = false + content = File.open filename, "rb" do |f| f.read end + content.gsub!("\r\n", "\n") if RUBY_PLATFORM =~ /mswin|mingw/ + + utf8 = content.sub!(/\A\xef\xbb\xbf/, '') + + enc = RDoc::Encoding.detect_encoding content + content = RDoc::Encoding.change_encoding content, enc if enc + + begin + encoding ||= Encoding.default_external + orig_encoding = content.encoding + + if not orig_encoding.ascii_compatible? then + content = content.encode encoding + elsif utf8 then + content = RDoc::Encoding.change_encoding content, Encoding::UTF_8 + content = content.encode encoding + else + # assume the content is in our output encoding + content = RDoc::Encoding.change_encoding content, encoding + end + + unless content.valid_encoding? then + # revert and try to transcode + content = RDoc::Encoding.change_encoding content, orig_encoding + content = content.encode encoding + end + + unless content.valid_encoding? then + warn "unable to convert #{filename} to #{encoding}, skipping" + content = nil + end + rescue Encoding::InvalidByteSequenceError, + Encoding::UndefinedConversionError => e + if force_transcode then + content = RDoc::Encoding.change_encoding content, orig_encoding + content = content.encode(encoding, + :invalid => :replace, + :undef => :replace, + :replace => '?') + return content + else + warn "unable to convert #{e.message} for #{filename}, skipping" + return nil + end + end + + content + rescue ArgumentError => e + raise unless e.message =~ /unknown encoding name - (.*)/ + warn "unknown encoding name \"#{$1}\" for #{filename}, skipping" + nil + rescue Errno::EISDIR, Errno::ENOENT + nil + end + + def self.remove_frozen_string_literal string + string =~ /\A(?:#!.*\n)?(.*\n)/ + first_line = $1 + + if first_line =~ /\A# +frozen[-_]string[-_]literal[=:].+$/i + string = string.sub first_line, '' + end + + string + end + + ## + # Detects the encoding of +string+ based on the magic comment + + def self.detect_encoding string + result = HEADER_REGEXP.match string + name = result && result[:name] + + name ? Encoding.find(name) : nil + end + + ## + # Removes magic comments and shebang + + def self.remove_magic_comment string + string.sub HEADER_REGEXP do |s| + s.gsub(/[^\n]/, '') + end + end + + ## + # Changes encoding based on +encoding+ without converting and returns new + # string + + def self.change_encoding text, encoding + if text.kind_of? RDoc::Comment + text.encode! encoding + else + # TODO: Remove this condition after Ruby 2.2 EOL + if RUBY_VERSION < '2.3.0' + text.force_encoding encoding + else + String.new text, encoding: encoding + end + end + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/erb_partial.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/erb_partial.rb new file mode 100644 index 0000000..d6e3f41 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/erb_partial.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true +## +# Allows an ERB template to be rendered in the context (binding) of an +# existing ERB template evaluation. + +class RDoc::ERBPartial < ERB + + ## + # Overrides +compiler+ startup to set the +eoutvar+ to an empty string only + # if it isn't already set. + + def set_eoutvar compiler, eoutvar = '_erbout' + super + + compiler.pre_cmd = ["#{eoutvar} ||= +''"] + end + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/erbio.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/erbio.rb new file mode 100644 index 0000000..0d5f96e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/erbio.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true +require 'erb' + +## +# A subclass of ERB that writes directly to an IO. Credit to Aaron Patterson +# and Masatoshi SEKI. +# +# To use: +# +# erbio = RDoc::ERBIO.new '<%= "hello world" %>', nil, nil +# +# File.open 'hello.txt', 'w' do |io| +# erbio.result binding +# end +# +# Note that binding must enclose the io you wish to output on. + +class RDoc::ERBIO < ERB + + ## + # Defaults +eoutvar+ to 'io', otherwise is identical to ERB's initialize + + def initialize str, safe_level = nil, legacy_trim_mode = nil, legacy_eoutvar = 'io', trim_mode: nil, eoutvar: 'io' + if RUBY_VERSION >= '2.6' + super(str, trim_mode: trim_mode, eoutvar: eoutvar) + else + super(str, safe_level, legacy_trim_mode, legacy_eoutvar) + end + end + + ## + # Instructs +compiler+ how to write to +io_variable+ + + def set_eoutvar compiler, io_variable + compiler.put_cmd = "#{io_variable}.write" + compiler.insert_cmd = "#{io_variable}.write" + compiler.pre_cmd = [] + compiler.post_cmd = [] + end + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/extend.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/extend.rb new file mode 100644 index 0000000..e1b1829 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/extend.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true +## +# A Module extension to a class with \#extend +# +# RDoc::Extend.new 'Enumerable', 'comment ...' + +class RDoc::Extend < RDoc::Mixin + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator.rb new file mode 100644 index 0000000..340dcbf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true +## +# RDoc uses generators to turn parsed source code in the form of an +# RDoc::CodeObject tree into some form of output. RDoc comes with the HTML +# generator RDoc::Generator::Darkfish and an ri data generator +# RDoc::Generator::RI. +# +# == Registering a Generator +# +# Generators are registered by calling RDoc::RDoc.add_generator with the class +# of the generator: +# +# class My::Awesome::Generator +# RDoc::RDoc.add_generator self +# end +# +# == Adding Options to +rdoc+ +# +# Before option processing in +rdoc+, RDoc::Options will call ::setup_options +# on the generator class with an RDoc::Options instance. The generator can +# use RDoc::Options#option_parser to add command-line options to the +rdoc+ +# tool. See RDoc::Options@Custom+Options for an example and see OptionParser +# for details on how to add options. +# +# You can extend the RDoc::Options instance with additional accessors for your +# generator. +# +# == Generator Instantiation +# +# After parsing, RDoc::RDoc will instantiate a generator by calling +# #initialize with an RDoc::Store instance and an RDoc::Options instance. +# +# The RDoc::Store instance holds documentation for parsed source code. In +# RDoc 3 and earlier the RDoc::TopLevel class held this data. When upgrading +# a generator from RDoc 3 and earlier you should only need to replace +# RDoc::TopLevel with the store instance. +# +# RDoc will then call #generate on the generator instance. You can use the +# various methods on RDoc::Store and in the RDoc::CodeObject tree to create +# your desired output format. + +module RDoc::Generator + + autoload :Markup, 'rdoc/generator/markup' + + autoload :Darkfish, 'rdoc/generator/darkfish' + autoload :JsonIndex, 'rdoc/generator/json_index' + autoload :RI, 'rdoc/generator/ri' + autoload :POT, 'rdoc/generator/pot' + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/darkfish.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/darkfish.rb new file mode 100644 index 0000000..60e0265 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/darkfish.rb @@ -0,0 +1,790 @@ +# frozen_string_literal: true +# -*- mode: ruby; ruby-indent-level: 2; tab-width: 2 -*- + +require 'erb' +require 'fileutils' +require 'pathname' +require_relative 'markup' + +## +# Darkfish RDoc HTML Generator +# +# $Id: darkfish.rb 52 2009-01-07 02:08:11Z deveiant $ +# +# == Author/s +# * Michael Granger (ged@FaerieMUD.org) +# +# == Contributors +# * Mahlon E. Smith (mahlon@martini.nu) +# * Eric Hodel (drbrain@segment7.net) +# +# == License +# +# Copyright (c) 2007, 2008, Michael Granger. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# * Neither the name of the author/s, nor the names of the project's +# contributors may be used to endorse or promote products derived from this +# software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# == Attributions +# +# Darkfish uses the {Silk Icons}[http://www.famfamfam.com/lab/icons/silk/] set +# by Mark James. + +class RDoc::Generator::Darkfish + + RDoc::RDoc.add_generator self + + include ERB::Util + + ## + # Stylesheets, fonts, etc. that are included in RDoc. + + BUILTIN_STYLE_ITEMS = # :nodoc: + %w[ + css/fonts.css + fonts/Lato-Light.ttf + fonts/Lato-LightItalic.ttf + fonts/Lato-Regular.ttf + fonts/Lato-RegularItalic.ttf + fonts/SourceCodePro-Bold.ttf + fonts/SourceCodePro-Regular.ttf + css/rdoc.css + ] + + ## + # Path to this file's parent directory. Used to find templates and other + # resources. + + GENERATOR_DIR = File.join 'rdoc', 'generator' + + ## + # Release Version + + VERSION = '3' + + ## + # Description of this generator + + DESCRIPTION = 'HTML generator, written by Michael Granger' + + ## + # The relative path to style sheets and javascript. By default this is set + # the same as the rel_prefix. + + attr_accessor :asset_rel_path + + ## + # The path to generate files into, combined with --op from the + # options for a full path. + + attr_reader :base_dir + + ## + # Classes and modules to be used by this generator, not necessarily + # displayed. See also #modsort + + attr_reader :classes + + ## + # No files will be written when dry_run is true. + + attr_accessor :dry_run + + ## + # When false the generate methods return a String instead of writing to a + # file. The default is true. + + attr_accessor :file_output + + ## + # Files to be displayed by this generator + + attr_reader :files + + ## + # The JSON index generator for this Darkfish generator + + attr_reader :json_index + + ## + # Methods to be displayed by this generator + + attr_reader :methods + + ## + # Sorted list of classes and modules to be displayed by this generator + + attr_reader :modsort + + ## + # The RDoc::Store that is the source of the generated content + + attr_reader :store + + ## + # The directory where the template files live + + attr_reader :template_dir # :nodoc: + + ## + # The output directory + + attr_reader :outputdir + + ## + # Initialize a few instance variables before we start + + def initialize store, options + @store = store + @options = options + + @asset_rel_path = '' + @base_dir = Pathname.pwd.expand_path + @dry_run = @options.dry_run + @file_output = true + @template_dir = Pathname.new options.template_dir + @template_cache = {} + + @classes = nil + @context = nil + @files = nil + @methods = nil + @modsort = nil + + @json_index = RDoc::Generator::JsonIndex.new self, options + end + + ## + # Output progress information if debugging is enabled + + def debug_msg *msg + return unless $DEBUG_RDOC + $stderr.puts(*msg) + end + + ## + # Directory where generated class HTML files live relative to the output + # dir. + + def class_dir + nil + end + + ## + # Directory where generated class HTML files live relative to the output + # dir. + + def file_dir + nil + end + + ## + # Create the directories the generated docs will live in if they don't + # already exist. + + def gen_sub_directories + @outputdir.mkpath + end + + ## + # Copy over the stylesheet into the appropriate place in the output + # directory. + + def write_style_sheet + debug_msg "Copying static files" + options = { :verbose => $DEBUG_RDOC, :noop => @dry_run } + + BUILTIN_STYLE_ITEMS.each do |item| + install_rdoc_static_file @template_dir + item, "./#{item}", options + end + + unless @options.template_stylesheets.empty? + FileUtils.cp @options.template_stylesheets, '.', **options + end + + Dir[(@template_dir + "{js,images}/**/*").to_s].each do |path| + next if File.directory? path + next if File.basename(path) =~ /^\./ + + dst = Pathname.new(path).relative_path_from @template_dir + + install_rdoc_static_file @template_dir + path, dst, options + end + end + + ## + # Build the initial indices and output objects based on an array of TopLevel + # objects containing the extracted information. + + def generate + setup + + write_style_sheet + generate_index + generate_class_files + generate_file_files + generate_table_of_contents + @json_index.generate + @json_index.generate_gzipped + + copy_static + + rescue => e + debug_msg "%s: %s\n %s" % [ + e.class.name, e.message, e.backtrace.join("\n ") + ] + + raise + end + + ## + # Copies static files from the static_path into the output directory + + def copy_static + return if @options.static_path.empty? + + fu_options = { :verbose => $DEBUG_RDOC, :noop => @dry_run } + + @options.static_path.each do |path| + unless File.directory? path then + FileUtils.install path, @outputdir, **fu_options.merge(:mode => 0644) + next + end + + Dir.chdir path do + Dir[File.join('**', '*')].each do |entry| + dest_file = @outputdir + entry + + if File.directory? entry then + FileUtils.mkdir_p entry, **fu_options + else + FileUtils.install entry, dest_file, **fu_options.merge(:mode => 0644) + end + end + end + end + end + + ## + # Return a list of the documented modules sorted by salience first, then + # by name. + + def get_sorted_module_list classes + classes.select do |klass| + klass.display? + end.sort + end + + ## + # Generate an index page which lists all the classes which are documented. + + def generate_index + setup + + template_file = @template_dir + 'index.rhtml' + return unless template_file.exist? + + debug_msg "Rendering the index page..." + + out_file = @base_dir + @options.op_dir + 'index.html' + rel_prefix = @outputdir.relative_path_from out_file.dirname + search_index_rel_prefix = rel_prefix + search_index_rel_prefix += @asset_rel_path if @file_output + + asset_rel_prefix = rel_prefix + @asset_rel_path + + @title = @options.title + + render_template template_file, out_file do |io| + here = binding + # suppress 1.9.3 warning + here.local_variable_set(:asset_rel_prefix, asset_rel_prefix) + here + end + rescue => e + error = RDoc::Error.new \ + "error generating index.html: #{e.message} (#{e.class})" + error.set_backtrace e.backtrace + + raise error + end + + ## + # Generates a class file for +klass+ + + def generate_class klass, template_file = nil + setup + + current = klass + + template_file ||= @template_dir + 'class.rhtml' + + debug_msg " working on %s (%s)" % [klass.full_name, klass.path] + out_file = @outputdir + klass.path + rel_prefix = @outputdir.relative_path_from out_file.dirname + search_index_rel_prefix = rel_prefix + search_index_rel_prefix += @asset_rel_path if @file_output + + asset_rel_prefix = rel_prefix + @asset_rel_path + svninfo = get_svninfo(current) + + @title = "#{klass.type} #{klass.full_name} - #{@options.title}" + + debug_msg " rendering #{out_file}" + render_template template_file, out_file do |io| + here = binding + # suppress 1.9.3 warning + here.local_variable_set(:asset_rel_prefix, asset_rel_prefix) + here.local_variable_set(:svninfo, svninfo) + here + end + end + + ## + # Generate a documentation file for each class and module + + def generate_class_files + setup + + template_file = @template_dir + 'class.rhtml' + template_file = @template_dir + 'classpage.rhtml' unless + template_file.exist? + return unless template_file.exist? + debug_msg "Generating class documentation in #{@outputdir}" + + current = nil + + @classes.each do |klass| + current = klass + + generate_class klass, template_file + end + rescue => e + error = RDoc::Error.new \ + "error generating #{current.path}: #{e.message} (#{e.class})" + error.set_backtrace e.backtrace + + raise error + end + + ## + # Generate a documentation file for each file + + def generate_file_files + setup + + page_file = @template_dir + 'page.rhtml' + fileinfo_file = @template_dir + 'fileinfo.rhtml' + + # for legacy templates + filepage_file = @template_dir + 'filepage.rhtml' unless + page_file.exist? or fileinfo_file.exist? + + return unless + page_file.exist? or fileinfo_file.exist? or filepage_file.exist? + + debug_msg "Generating file documentation in #{@outputdir}" + + out_file = nil + current = nil + + @files.each do |file| + current = file + + if file.text? and page_file.exist? then + generate_page file + next + end + + template_file = nil + out_file = @outputdir + file.path + debug_msg " working on %s (%s)" % [file.full_name, out_file] + rel_prefix = @outputdir.relative_path_from out_file.dirname + search_index_rel_prefix = rel_prefix + search_index_rel_prefix += @asset_rel_path if @file_output + + asset_rel_prefix = rel_prefix + @asset_rel_path + + unless filepage_file then + if file.text? then + next unless page_file.exist? + template_file = page_file + @title = file.page_name + else + next unless fileinfo_file.exist? + template_file = fileinfo_file + @title = "File: #{file.base_name}" + end + end + + @title += " - #{@options.title}" + template_file ||= filepage_file + + render_template template_file, out_file do |io| + here = binding + # suppress 1.9.3 warning + here.local_variable_set(:asset_rel_prefix, asset_rel_prefix) + here.local_variable_set(:current, current) + here + end + end + rescue => e + error = + RDoc::Error.new "error generating #{out_file}: #{e.message} (#{e.class})" + error.set_backtrace e.backtrace + + raise error + end + + ## + # Generate a page file for +file+ + + def generate_page file + setup + + template_file = @template_dir + 'page.rhtml' + + out_file = @outputdir + file.path + debug_msg " working on %s (%s)" % [file.full_name, out_file] + rel_prefix = @outputdir.relative_path_from out_file.dirname + search_index_rel_prefix = rel_prefix + search_index_rel_prefix += @asset_rel_path if @file_output + + current = file + asset_rel_prefix = rel_prefix + @asset_rel_path + + @title = "#{file.page_name} - #{@options.title}" + + debug_msg " rendering #{out_file}" + render_template template_file, out_file do |io| + here = binding + # suppress 1.9.3 warning + here.local_variable_set(:current, current) + here.local_variable_set(:asset_rel_prefix, asset_rel_prefix) + here + end + end + + ## + # Generates the 404 page for the RDoc servlet + + def generate_servlet_not_found message + setup + + template_file = @template_dir + 'servlet_not_found.rhtml' + return unless template_file.exist? + + debug_msg "Rendering the servlet 404 Not Found page..." + + rel_prefix = rel_prefix = '' + search_index_rel_prefix = rel_prefix + search_index_rel_prefix += @asset_rel_path if @file_output + + asset_rel_prefix = '' + + @title = 'Not Found' + + render_template template_file do |io| + here = binding + # suppress 1.9.3 warning + here.local_variable_set(:asset_rel_prefix, asset_rel_prefix) + here + end + rescue => e + error = RDoc::Error.new \ + "error generating servlet_not_found: #{e.message} (#{e.class})" + error.set_backtrace e.backtrace + + raise error + end + + ## + # Generates the servlet root page for the RDoc servlet + + def generate_servlet_root installed + setup + + template_file = @template_dir + 'servlet_root.rhtml' + return unless template_file.exist? + + debug_msg 'Rendering the servlet root page...' + + rel_prefix = '.' + asset_rel_prefix = rel_prefix + search_index_rel_prefix = asset_rel_prefix + search_index_rel_prefix += @asset_rel_path if @file_output + + @title = 'Local RDoc Documentation' + + render_template template_file do |io| binding end + rescue => e + error = RDoc::Error.new \ + "error generating servlet_root: #{e.message} (#{e.class})" + error.set_backtrace e.backtrace + + raise error + end + + ## + # Generate an index page which lists all the classes which are documented. + + def generate_table_of_contents + setup + + template_file = @template_dir + 'table_of_contents.rhtml' + return unless template_file.exist? + + debug_msg "Rendering the Table of Contents..." + + out_file = @outputdir + 'table_of_contents.html' + rel_prefix = @outputdir.relative_path_from out_file.dirname + search_index_rel_prefix = rel_prefix + search_index_rel_prefix += @asset_rel_path if @file_output + + asset_rel_prefix = rel_prefix + @asset_rel_path + + @title = "Table of Contents - #{@options.title}" + + render_template template_file, out_file do |io| + here = binding + # suppress 1.9.3 warning + here.local_variable_set(:asset_rel_prefix, asset_rel_prefix) + here + end + rescue => e + error = RDoc::Error.new \ + "error generating table_of_contents.html: #{e.message} (#{e.class})" + error.set_backtrace e.backtrace + + raise error + end + + def install_rdoc_static_file source, destination, options # :nodoc: + return unless source.exist? + + begin + FileUtils.mkdir_p File.dirname(destination), **options + + begin + FileUtils.ln source, destination, **options + rescue Errno::EEXIST + FileUtils.rm destination + retry + end + rescue + FileUtils.cp source, destination, **options + end + end + + ## + # Prepares for generation of output from the current directory + + def setup + return if instance_variable_defined? :@outputdir + + @outputdir = Pathname.new(@options.op_dir).expand_path @base_dir + + return unless @store + + @classes = @store.all_classes_and_modules.sort + @files = @store.all_files.sort + @methods = @classes.map { |m| m.method_list }.flatten.sort + @modsort = get_sorted_module_list @classes + end + + ## + # Return a string describing the amount of time in the given number of + # seconds in terms a human can understand easily. + + def time_delta_string seconds + return 'less than a minute' if seconds < 60 + return "#{seconds / 60} minute#{seconds / 60 == 1 ? '' : 's'}" if + seconds < 3000 # 50 minutes + return 'about one hour' if seconds < 5400 # 90 minutes + return "#{seconds / 3600} hours" if seconds < 64800 # 18 hours + return 'one day' if seconds < 86400 # 1 day + return 'about one day' if seconds < 172800 # 2 days + return "#{seconds / 86400} days" if seconds < 604800 # 1 week + return 'about one week' if seconds < 1209600 # 2 week + return "#{seconds / 604800} weeks" if seconds < 7257600 # 3 months + return "#{seconds / 2419200} months" if seconds < 31536000 # 1 year + return "#{seconds / 31536000} years" + end + + # %q$Id: darkfish.rb 52 2009-01-07 02:08:11Z deveiant $" + SVNID_PATTERN = / + \$Id:\s + (\S+)\s # filename + (\d+)\s # rev + (\d{4}-\d{2}-\d{2})\s # Date (YYYY-MM-DD) + (\d{2}:\d{2}:\d{2}Z)\s # Time (HH:MM:SSZ) + (\w+)\s # committer + \$$ + /x + + ## + # Try to extract Subversion information out of the first constant whose + # value looks like a subversion Id tag. If no matching constant is found, + # and empty hash is returned. + + def get_svninfo klass + constants = klass.constants or return {} + + constants.find { |c| c.value =~ SVNID_PATTERN } or return {} + + filename, rev, date, time, committer = $~.captures + commitdate = Time.parse "#{date} #{time}" + + return { + :filename => filename, + :rev => Integer(rev), + :commitdate => commitdate, + :commitdelta => time_delta_string(Time.now - commitdate), + :committer => committer, + } + end + + ## + # Creates a template from its components and the +body_file+. + # + # For backwards compatibility, if +body_file+ contains " + + + +#{head_file.read} + +#{body} + +#{footer_file.read} + TEMPLATE + end + + ## + # Renders the ERb contained in +file_name+ relative to the template + # directory and returns the result based on the current context. + + def render file_name + template_file = @template_dir + file_name + + template = template_for template_file, false, RDoc::ERBPartial + + template.filename = template_file.to_s + + template.result @context + end + + ## + # Load and render the erb template in the given +template_file+ and write + # it out to +out_file+. + # + # Both +template_file+ and +out_file+ should be Pathname-like objects. + # + # An io will be yielded which must be captured by binding in the caller. + + def render_template template_file, out_file = nil # :yield: io + io_output = out_file && !@dry_run && @file_output + erb_klass = io_output ? RDoc::ERBIO : ERB + + template = template_for template_file, true, erb_klass + + if io_output then + debug_msg "Outputting to %s" % [out_file.expand_path] + + out_file.dirname.mkpath + out_file.open 'w', 0644 do |io| + io.set_encoding @options.encoding + + @context = yield io + + template_result template, @context, template_file + end + else + @context = yield nil + + output = template_result template, @context, template_file + + debug_msg " would have written %d characters to %s" % [ + output.length, out_file.expand_path + ] if @dry_run + + output + end + end + + ## + # Creates the result for +template+ with +context+. If an error is raised a + # Pathname +template_file+ will indicate the file where the error occurred. + + def template_result template, context, template_file + template.filename = template_file.to_s + template.result context + rescue NoMethodError => e + raise RDoc::Error, "Error while evaluating %s: %s" % [ + template_file.expand_path, + e.message, + ], e.backtrace + end + + ## + # Retrieves a cache template for +file+, if present, or fills the cache. + + def template_for file, page = true, klass = ERB + template = @template_cache[file] + + return template if template + + if page then + template = assemble_template file + erbout = 'io' + else + template = file.read + template = template.encode @options.encoding + + file_var = File.basename(file).sub(/\..*/, '') + + erbout = "_erbout_#{file_var}" + end + + if RUBY_VERSION >= '2.6' + template = klass.new template, trim_mode: '-', eoutvar: erbout + else + template = klass.new template, nil, '-', erbout + end + @template_cache[file] = template + template + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/json_index.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/json_index.rb new file mode 100644 index 0000000..3a10000 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/json_index.rb @@ -0,0 +1,300 @@ +# frozen_string_literal: true +require 'json' +begin + require 'zlib' +rescue LoadError +end + +## +# The JsonIndex generator is designed to complement an HTML generator and +# produces a JSON search index. This generator is derived from sdoc by +# Vladimir Kolesnikov and contains verbatim code written by him. +# +# This generator is designed to be used with a regular HTML generator: +# +# class RDoc::Generator::Darkfish +# def initialize options +# # ... +# @base_dir = Pathname.pwd.expand_path +# +# @json_index = RDoc::Generator::JsonIndex.new self, options +# end +# +# def generate +# # ... +# @json_index.generate +# end +# end +# +# == Index Format +# +# The index is output as a JSON file assigned to the global variable +# +search_data+. The structure is: +# +# var search_data = { +# "index": { +# "searchIndex": +# ["a", "b", ...], +# "longSearchIndex": +# ["a", "a::b", ...], +# "info": [ +# ["A", "A", "A.html", "", ""], +# ["B", "A::B", "A::B.html", "", ""], +# ... +# ] +# } +# } +# +# The same item is described across the +searchIndex+, +longSearchIndex+ and +# +info+ fields. The +searchIndex+ field contains the item's short name, the +# +longSearchIndex+ field contains the full_name (when appropriate) and the +# +info+ field contains the item's name, full_name, path, parameters and a +# snippet of the item's comment. +# +# == LICENSE +# +# Copyright (c) 2009 Vladimir Kolesnikov +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +class RDoc::Generator::JsonIndex + + include RDoc::Text + + ## + # Where the search index lives in the generated output + + SEARCH_INDEX_FILE = File.join 'js', 'search_index.js' + + attr_reader :index # :nodoc: + + ## + # Creates a new generator. +parent_generator+ is used to determine the + # class_dir and file_dir of links in the output index. + # + # +options+ are the same options passed to the parent generator. + + def initialize parent_generator, options + @parent_generator = parent_generator + @store = parent_generator.store + @options = options + + @template_dir = File.expand_path '../template/json_index', __FILE__ + @base_dir = @parent_generator.base_dir + + @classes = nil + @files = nil + @index = nil + end + + ## + # Builds the JSON index as a Hash. + + def build_index + reset @store.all_files.sort, @store.all_classes_and_modules.sort + + index_classes + index_methods + index_pages + + { :index => @index } + end + + ## + # Output progress information if debugging is enabled + + def debug_msg *msg + return unless $DEBUG_RDOC + $stderr.puts(*msg) + end + + ## + # Writes the JSON index to disk + + def generate + debug_msg "Generating JSON index" + + debug_msg " writing search index to %s" % SEARCH_INDEX_FILE + data = build_index + + return if @options.dry_run + + out_dir = @base_dir + @options.op_dir + index_file = out_dir + SEARCH_INDEX_FILE + + FileUtils.mkdir_p index_file.dirname, :verbose => $DEBUG_RDOC + + index_file.open 'w', 0644 do |io| + io.set_encoding Encoding::UTF_8 + io.write 'var search_data = ' + + JSON.dump data, io, 0 + end + unless ENV['SOURCE_DATE_EPOCH'].nil? + index_file.utime index_file.atime, Time.at(ENV['SOURCE_DATE_EPOCH'].to_i).gmtime + end + + Dir.chdir @template_dir do + Dir['**/*.js'].each do |source| + dest = File.join out_dir, source + + FileUtils.install source, dest, :mode => 0644, :preserve => true, :verbose => $DEBUG_RDOC + end + end + end + + ## + # Compress the search_index.js file using gzip + + def generate_gzipped + return if @options.dry_run or not defined?(Zlib) + + debug_msg "Compressing generated JSON index" + out_dir = @base_dir + @options.op_dir + + search_index_file = out_dir + SEARCH_INDEX_FILE + outfile = out_dir + "#{search_index_file}.gz" + + debug_msg "Reading the JSON index file from %s" % search_index_file + search_index = search_index_file.read(mode: 'r:utf-8') + + debug_msg "Writing gzipped search index to %s" % outfile + + Zlib::GzipWriter.open(outfile) do |gz| + gz.mtime = File.mtime(search_index_file) + gz.orig_name = search_index_file.basename.to_s + gz.write search_index + gz.close + end + + # GZip the rest of the js files + Dir.chdir @template_dir do + Dir['**/*.js'].each do |source| + dest = out_dir + source + outfile = out_dir + "#{dest}.gz" + + debug_msg "Reading the original js file from %s" % dest + data = dest.read + + debug_msg "Writing gzipped file to %s" % outfile + + Zlib::GzipWriter.open(outfile) do |gz| + gz.mtime = File.mtime(dest) + gz.orig_name = dest.basename.to_s + gz.write data + gz.close + end + end + end + end + + ## + # Adds classes and modules to the index + + def index_classes + debug_msg " generating class search index" + + documented = @classes.uniq.select do |klass| + klass.document_self_or_methods + end + + documented.each do |klass| + debug_msg " #{klass.full_name}" + record = klass.search_record + @index[:searchIndex] << search_string(record.shift) + @index[:longSearchIndex] << search_string(record.shift) + @index[:info] << record + end + end + + ## + # Adds methods to the index + + def index_methods + debug_msg " generating method search index" + + list = @classes.uniq.map do |klass| + klass.method_list + end.flatten.sort_by do |method| + [method.name, method.parent.full_name] + end + + list.each do |method| + debug_msg " #{method.full_name}" + record = method.search_record + @index[:searchIndex] << "#{search_string record.shift}()" + @index[:longSearchIndex] << "#{search_string record.shift}()" + @index[:info] << record + end + end + + ## + # Adds pages to the index + + def index_pages + debug_msg " generating pages search index" + + pages = @files.select do |file| + file.text? + end + + pages.each do |page| + debug_msg " #{page.page_name}" + record = page.search_record + @index[:searchIndex] << search_string(record.shift) + @index[:longSearchIndex] << '' + record.shift + @index[:info] << record + end + end + + ## + # The directory classes are written to + + def class_dir + @parent_generator.class_dir + end + + ## + # The directory files are written to + + def file_dir + @parent_generator.file_dir + end + + def reset files, classes # :nodoc: + @files = files + @classes = classes + + @index = { + :searchIndex => [], + :longSearchIndex => [], + :info => [] + } + end + + ## + # Removes whitespace and downcases +string+ + + def search_string string + string.downcase.gsub(/\s/, '') + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/markup.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/markup.rb new file mode 100644 index 0000000..41e1324 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/markup.rb @@ -0,0 +1,160 @@ +# frozen_string_literal: true +## +# Handle common RDoc::Markup tasks for various CodeObjects +# +# This module is loaded by generators. It allows RDoc's CodeObject tree to +# avoid loading generator code to improve startup time for +ri+. + +module RDoc::Generator::Markup + + ## + # Generates a relative URL from this object's path to +target_path+ + + def aref_to(target_path) + RDoc::Markup::ToHtml.gen_relative_url path, target_path + end + + ## + # Generates a relative URL from +from_path+ to this object's path + + def as_href(from_path) + RDoc::Markup::ToHtml.gen_relative_url from_path, path + end + + ## + # Handy wrapper for marking up this object's comment + + def description + markup @comment + end + + ## + # Creates an RDoc::Markup::ToHtmlCrossref formatter + + def formatter + return @formatter if defined? @formatter + + options = @store.rdoc.options + this = RDoc::Context === self ? self : @parent + + @formatter = RDoc::Markup::ToHtmlCrossref.new options, this.path, this + @formatter.code_object = self + @formatter + end + + ## + # Build a webcvs URL starting for the given +url+ with +full_path+ appended + # as the destination path. If +url+ contains '%s' +full_path+ will be + # will replace the %s using sprintf on the +url+. + + def cvs_url(url, full_path) + if /%s/ =~ url then + sprintf url, full_path + else + url + full_path + end + end + +end + +class RDoc::CodeObject + + include RDoc::Generator::Markup + +end + +class RDoc::MethodAttr + + ## + # Prepend +src+ with line numbers. Relies on the first line of a source + # code listing having: + # + # # File xxxxx, line dddd + # + # If it has this comment then line numbers are added to +src+ and the , + # line dddd portion of the comment is removed. + + def add_line_numbers(src) + return unless src.sub!(/\A(.*)(, line (\d+))/, '\1') + first = $3.to_i - 1 + last = first + src.count("\n") + size = last.to_s.length + + line = first + src.gsub!(/^/) do + res = if line == first then + " " * (size + 1) + else + "%2$*1$d " % [size, line] + end + + line += 1 + res + end + end + + ## + # Turns the method's token stream into HTML. + # + # Prepends line numbers if +options.line_numbers+ is true. + + def markup_code + return '' unless @token_stream + + src = RDoc::TokenStream.to_html @token_stream + + # dedent the source + indent = src.length + lines = src.lines.to_a + lines.shift if src =~ /\A.*#\ *File/i # remove '# File' comment + lines.each do |line| + if line =~ /^ *(?=\S)/ + n = $&.length + indent = n if n < indent + break if n == 0 + end + end + src.gsub!(/^#{' ' * indent}/, '') if indent > 0 + + add_line_numbers(src) if options.line_numbers + + src + end + +end + +class RDoc::ClassModule + + ## + # Handy wrapper for marking up this class or module's comment + + def description + markup @comment_location + end + +end + +class RDoc::Context::Section + + include RDoc::Generator::Markup + +end + +class RDoc::TopLevel + + ## + # Returns a URL for this source file on some web repository. Use the -W + # command line option to set. + + def cvs_url + url = @store.rdoc.options.webcvs + + if /%s/ =~ url then + url % @relative_name + else + url + @relative_name + end + end + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot.rb new file mode 100644 index 0000000..bee1133 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot.rb @@ -0,0 +1,98 @@ +# frozen_string_literal: true +## +# Generates a POT file. +# +# Here is a translator work flow with the generator. +# +# == Create .pot +# +# You create .pot file by pot formatter: +# +# % rdoc --format pot +# +# It generates doc/rdoc.pot. +# +# == Create .po +# +# You create .po file from doc/rdoc.pot. This operation is needed only +# the first time. This work flow assumes that you are a translator +# for Japanese. +# +# You create locale/ja/rdoc.po from doc/rdoc.pot. You can use msginit +# provided by GNU gettext or rmsginit provided by gettext gem. This +# work flow uses gettext gem because it is more portable than GNU +# gettext for Rubyists. Gettext gem is implemented by pure Ruby. +# +# % gem install gettext +# % mkdir -p locale/ja +# % rmsginit --input doc/rdoc.pot --output locale/ja/rdoc.po --locale ja +# +# Translate messages in .po +# +# You translate messages in .po by a PO file editor. po-mode.el exists +# for Emacs users. There are some GUI tools such as GTranslator. +# There are some Web services such as POEditor and Tansifex. You can +# edit by your favorite text editor because .po is a text file. +# Generate localized documentation +# +# You can generate localized documentation with locale/ja/rdoc.po: +# +# % rdoc --locale ja +# +# You can find documentation in Japanese in doc/. Yay! +# +# == Update translation +# +# You need to update translation when your application is added or +# modified messages. +# +# You can update .po by the following command lines: +# +# % rdoc --format pot +# % rmsgmerge --update locale/ja/rdoc.po doc/rdoc.pot +# +# You edit locale/ja/rdoc.po to translate new messages. + +class RDoc::Generator::POT + + RDoc::RDoc.add_generator self + + ## + # Description of this generator + + DESCRIPTION = 'creates .pot file' + + ## + # Set up a new .pot generator + + def initialize store, options #:not-new: + @options = options + @store = store + end + + ## + # Writes .pot to disk. + + def generate + po = extract_messages + pot_path = 'rdoc.pot' + File.open(pot_path, "w") do |pot| + pot.print(po.to_s) + end + end + + def class_dir + nil + end + + private + def extract_messages + extractor = MessageExtractor.new(@store) + extractor.extract + end + + require_relative 'pot/message_extractor' + require_relative 'pot/po' + require_relative 'pot/po_entry' + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot/message_extractor.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot/message_extractor.rb new file mode 100644 index 0000000..313dfd2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot/message_extractor.rb @@ -0,0 +1,68 @@ +# frozen_string_literal: true +## +# Extracts message from RDoc::Store + +class RDoc::Generator::POT::MessageExtractor + + ## + # Creates a message extractor for +store+. + + def initialize store + @store = store + @po = RDoc::Generator::POT::PO.new + end + + ## + # Extracts messages from +store+, stores them into + # RDoc::Generator::POT::PO and returns it. + + def extract + @store.all_classes_and_modules.each do |klass| + extract_from_klass(klass) + end + @po + end + + private + + def extract_from_klass klass + extract_text(klass.comment_location, klass.full_name) + + klass.each_section do |section, constants, attributes| + extract_text(section.title ,"#{klass.full_name}: section title") + section.comments.each do |comment| + extract_text(comment, "#{klass.full_name}: #{section.title}") + end + end + + klass.each_constant do |constant| + extract_text(constant.comment, constant.full_name) + end + + klass.each_attribute do |attribute| + extract_text(attribute.comment, attribute.full_name) + end + + klass.each_method do |method| + extract_text(method.comment, method.full_name) + end + end + + def extract_text text, comment, location = nil + return if text.nil? + + options = { + :extracted_comment => comment, + :references => [location].compact, + } + i18n_text = RDoc::I18n::Text.new(text) + i18n_text.extract_messages do |part| + @po.add(entry(part[:paragraph], options)) + end + end + + def entry msgid, options + RDoc::Generator::POT::POEntry.new(msgid, options) + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot/po.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot/po.rb new file mode 100644 index 0000000..37d45e5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot/po.rb @@ -0,0 +1,84 @@ +# frozen_string_literal: true +## +# Generates a PO format text + +class RDoc::Generator::POT::PO + + ## + # Creates an object that represents PO format. + + def initialize + @entries = {} + add_header + end + + ## + # Adds a PO entry to the PO. + + def add entry + existing_entry = @entries[entry.msgid] + if existing_entry + entry = existing_entry.merge(entry) + end + @entries[entry.msgid] = entry + end + + ## + # Returns PO format text for the PO. + + def to_s + po = '' + sort_entries.each do |entry| + po += "\n" unless po.empty? + po += entry.to_s + end + po + end + + private + + def add_header + add(header_entry) + end + + def header_entry + comment = <<-COMMENT +SOME DESCRIPTIVE TITLE. +Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +This file is distributed under the same license as the PACKAGE package. +FIRST AUTHOR , YEAR. + COMMENT + + content = <<-CONTENT +Project-Id-Version: PACKAGE VERSEION +Report-Msgid-Bugs-To: +PO-Revision-Date: YEAR-MO_DA HO:MI+ZONE +Last-Translator: FULL NAME +Language-Team: LANGUAGE +Language: +MIME-Version: 1.0 +Content-Type: text/plain; charset=CHARSET +Content-Transfer-Encoding: 8bit +Plural-Forms: nplurals=INTEGER; plural=EXPRESSION; + CONTENT + + options = { + :msgstr => content, + :translator_comment => comment, + :flags => ['fuzzy'], + } + RDoc::Generator::POT::POEntry.new('', options) + end + + def sort_entries + headers, messages = @entries.values.partition do |entry| + entry.msgid.empty? + end + # TODO: sort by location + sorted_messages = messages.sort_by do |entry| + entry.msgid + end + headers + sorted_messages + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot/po_entry.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot/po_entry.rb new file mode 100644 index 0000000..3c27882 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/pot/po_entry.rb @@ -0,0 +1,141 @@ +# frozen_string_literal: true +## +# A PO entry in PO + +class RDoc::Generator::POT::POEntry + + # The msgid content + attr_reader :msgid + + # The msgstr content + attr_reader :msgstr + + # The comment content created by translator (PO editor) + attr_reader :translator_comment + + # The comment content extracted from source file + attr_reader :extracted_comment + + # The locations where the PO entry is extracted + attr_reader :references + + # The flags of the PO entry + attr_reader :flags + + ## + # Creates a PO entry for +msgid+. Other valus can be specified by + # +options+. + + def initialize msgid, options = {} + @msgid = msgid + @msgstr = options[:msgstr] || "" + @translator_comment = options[:translator_comment] + @extracted_comment = options[:extracted_comment] + @references = options[:references] || [] + @flags = options[:flags] || [] + end + + ## + # Returns the PO entry in PO format. + + def to_s + entry = '' + entry += format_translator_comment + entry += format_extracted_comment + entry += format_references + entry += format_flags + entry += <<-ENTRY +msgid #{format_message(@msgid)} +msgstr #{format_message(@msgstr)} + ENTRY + end + + ## + # Merges the PO entry with +other_entry+. + + def merge other_entry + options = { + :extracted_comment => merge_string(@extracted_comment, + other_entry.extracted_comment), + :translator_comment => merge_string(@translator_comment, + other_entry.translator_comment), + :references => merge_array(@references, + other_entry.references), + :flags => merge_array(@flags, + other_entry.flags), + } + self.class.new(@msgid, options) + end + + private + + def format_comment mark, comment + return '' unless comment + return '' if comment.empty? + + formatted_comment = '' + comment.each_line do |line| + formatted_comment += "#{mark} #{line}" + end + formatted_comment += "\n" unless formatted_comment.end_with?("\n") + formatted_comment + end + + def format_translator_comment + format_comment('#', @translator_comment) + end + + def format_extracted_comment + format_comment('#.', @extracted_comment) + end + + def format_references + return '' if @references.empty? + + formatted_references = '' + @references.sort.each do |file, line| + formatted_references += "\#: #{file}:#{line}\n" + end + formatted_references + end + + def format_flags + return '' if @flags.empty? + + formatted_flags = flags.join(",") + "\#, #{formatted_flags}\n" + end + + def format_message message + return "\"#{escape(message)}\"" unless message.include?("\n") + + formatted_message = '""' + message.each_line do |line| + formatted_message += "\n" + formatted_message += "\"#{escape(line)}\"" + end + formatted_message + end + + def escape string + string.gsub(/["\\\t\n]/) do |special_character| + case special_character + when "\t" + "\\t" + when "\n" + "\\n" + else + "\\#{special_character}" + end + end + end + + def merge_string string1, string2 + [string1, string2].compact.join("\n") + end + + def merge_array array1, array2 + (array1 + array2).uniq + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/ri.rb b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/ri.rb new file mode 100644 index 0000000..0eef1d0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/ri.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true +## +# Generates ri data files + +class RDoc::Generator::RI + + RDoc::RDoc.add_generator self + + ## + # Description of this generator + + DESCRIPTION = 'creates ri data files' + + ## + # Set up a new ri generator + + def initialize store, options #:not-new: + @options = options + @store = store + @store.path = '.' + end + + ## + # Writes the parsed data store to disk for use by ri. + + def generate + @store.save + end + +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/.document b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/.document new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_footer.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_footer.rhtml new file mode 100644 index 0000000..9791b42 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_footer.rhtml @@ -0,0 +1,5 @@ + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_head.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_head.rhtml new file mode 100644 index 0000000..4f33124 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_head.rhtml @@ -0,0 +1,20 @@ + + +<%= h @title %> + + + + + + + + + + + +<%- @options.template_stylesheets.each do |stylesheet| -%> + +<%- end -%> diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_VCS_info.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_VCS_info.rhtml new file mode 100644 index 0000000..22a12d9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_VCS_info.rhtml @@ -0,0 +1,19 @@ +<%- if !svninfo.empty? then %> + +<%- end -%> diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_classes.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_classes.rhtml new file mode 100644 index 0000000..530f25c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_classes.rhtml @@ -0,0 +1,9 @@ + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_extends.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_extends.rhtml new file mode 100644 index 0000000..7602076 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_extends.rhtml @@ -0,0 +1,15 @@ +<%- unless klass.extends.empty? then %> + +<%- end -%> diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_in_files.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_in_files.rhtml new file mode 100644 index 0000000..74869a4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_in_files.rhtml @@ -0,0 +1,9 @@ + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_includes.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_includes.rhtml new file mode 100644 index 0000000..5b600e5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_includes.rhtml @@ -0,0 +1,15 @@ +<%- unless klass.includes.empty? then %> + +<%- end -%> diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_installed.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_installed.rhtml new file mode 100644 index 0000000..faed7e0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_installed.rhtml @@ -0,0 +1,15 @@ + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_methods.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_methods.rhtml new file mode 100644 index 0000000..5b4c295 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_methods.rhtml @@ -0,0 +1,12 @@ +<%- unless klass.method_list.empty? then %> + + +<%- end -%> diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_navigation.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_navigation.rhtml new file mode 100644 index 0000000..d7f3308 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_navigation.rhtml @@ -0,0 +1,11 @@ + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_pages.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_pages.rhtml new file mode 100644 index 0000000..8ec83ab --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_pages.rhtml @@ -0,0 +1,12 @@ +<%- simple_files = @files.select { |f| f.text? } %> +<%- unless simple_files.empty? then -%> + +<%- end -%> diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_parent.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_parent.rhtml new file mode 100644 index 0000000..1420da3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_parent.rhtml @@ -0,0 +1,11 @@ +<%- if klass.type == 'class' then %> + +<%- end -%> diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_search.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_search.rhtml new file mode 100644 index 0000000..9c49b31 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_search.rhtml @@ -0,0 +1,14 @@ + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_sections.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_sections.rhtml new file mode 100644 index 0000000..6dcd2ae --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_sections.rhtml @@ -0,0 +1,11 @@ +<%- unless klass.sections.length == 1 then %> + +<%- end -%> diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_table_of_contents.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_table_of_contents.rhtml new file mode 100644 index 0000000..bf70819 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/_sidebar_table_of_contents.rhtml @@ -0,0 +1,18 @@ +<%- comment = if current.respond_to? :comment_location then + current.comment_location + else + current.comment + end + table = current.parse(comment).table_of_contents + + if table.length > 1 then %> + +<%- end -%> diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/class.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/class.rhtml new file mode 100644 index 0000000..5d7b6a1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/class.rhtml @@ -0,0 +1,172 @@ + + + +
+

+ <%= klass.type %> <%= klass.full_name %> +

+ +
+ <%= klass.description %> +
+ + <%- klass.each_section do |section, constants, attributes| -%> +
+ <%- if section.title then -%> +
+

+ <%= section.title %> +

+ + ↑ top + +
+ <%- end -%> + + <%- if section.comment then -%> +
+ <%= section.description %> +
+ <%- end -%> + + <%- unless constants.empty? then -%> +
+
+

Constants

+
+
+ <%- constants.each do |const| -%> +
<%= const.name %> + <%- if const.comment then -%> +
<%= const.description.strip %> + <%- else -%> +
(Not documented) + <%- end -%> + <%- end -%> +
+
+ <%- end -%> + + <%- unless attributes.empty? then -%> +
+
+

Attributes

+
+ + <%- attributes.each do |attrib| -%> +
+
+ <%= h attrib.name %>[<%= attrib.rw %>] +
+ +
+ <%- if attrib.comment then -%> + <%= attrib.description.strip %> + <%- else -%> +

(Not documented) + <%- end -%> +

+
+ <%- end -%> +
+ <%- end -%> + + <%- klass.methods_by_type(section).each do |type, visibilities| + next if visibilities.empty? + visibilities.each do |visibility, methods| + next if methods.empty? %> +
+
+

<%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods

+
+ + <%- methods.each do |method| -%> +
"> + <%- if (call_seq = method.call_seq) then -%> + <%- call_seq.strip.split("\n").each_with_index do |call_seq, i| -%> +
+ + <%= h(call_seq.strip. + gsub( /^\w+\./m, '')). + gsub(/(.*)[-=]>/, '\1→') %> + + <%- if i == 0 and method.token_stream then -%> + click to toggle source + <%- end -%> +
+ <%- end -%> + <%- else -%> +
+ <%= h method.name %><%= h method.param_seq %> + <%- if method.token_stream then -%> + click to toggle source + <%- end -%> +
+ <%- end -%> + +
+ <%- if method.comment then -%> + <%= method.description.strip %> + <%- else -%> +

(Not documented) + <%- end -%> + <%- if method.calls_super then -%> +

+ Calls superclass method + <%= + method.superclass_method ? + method.formatter.link(method.superclass_method.full_name, method.superclass_method.full_name) : nil + %> +
+ <%- end -%> + + <%- if method.token_stream then -%> +
+
<%= method.markup_code %>
+
+ <%- end -%> +
+ + <%- unless method.aliases.empty? then -%> +
+ Also aliased as: <%= method.aliases.map do |aka| + if aka.parent then # HACK lib/rexml/encodings + %{#{h aka.name}} + else + h aka.name + end + end.join ", " %> +
+ <%- end -%> + + <%- if method.is_alias_for then -%> + + <%- end -%> +
+ + <%- end -%> +
+ <%- end + end %> +
+<%- end -%> +
diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/css/fonts.css b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/css/fonts.css new file mode 100644 index 0000000..57302b5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/css/fonts.css @@ -0,0 +1,167 @@ +/* + * Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), + * with Reserved Font Name "Source". All Rights Reserved. Source is a + * trademark of Adobe Systems Incorporated in the United States and/or other + * countries. + * + * This Font Software is licensed under the SIL Open Font License, Version + * 1.1. + * + * This license is copied below, and is also available with a FAQ at: + * http://scripts.sil.org/OFL + */ + +@font-face { + font-family: "Source Code Pro"; + font-style: normal; + font-weight: 400; + src: local("Source Code Pro"), + local("SourceCodePro-Regular"), + url("../fonts/SourceCodePro-Regular.ttf") format("truetype"); +} + +@font-face { + font-family: "Source Code Pro"; + font-style: normal; + font-weight: 700; + src: local("Source Code Pro Bold"), + local("SourceCodePro-Bold"), + url("../fonts/SourceCodePro-Bold.ttf") format("truetype"); +} + +/* + * Copyright (c) 2010, Łukasz Dziedzic (dziedzic@typoland.com), + * with Reserved Font Name Lato. + * + * This Font Software is licensed under the SIL Open Font License, Version + * 1.1. + * + * This license is copied below, and is also available with a FAQ at: + * http://scripts.sil.org/OFL + */ + +@font-face { + font-family: "Lato"; + font-style: normal; + font-weight: 300; + src: local("Lato Light"), + local("Lato-Light"), + url("../fonts/Lato-Light.ttf") format("truetype"); +} + +@font-face { + font-family: "Lato"; + font-style: italic; + font-weight: 300; + src: local("Lato Light Italic"), + local("Lato-LightItalic"), + url("../fonts/Lato-LightItalic.ttf") format("truetype"); +} + +@font-face { + font-family: "Lato"; + font-style: normal; + font-weight: 700; + src: local("Lato Regular"), + local("Lato-Regular"), + url("../fonts/Lato-Regular.ttf") format("truetype"); +} + +@font-face { + font-family: "Lato"; + font-style: italic; + font-weight: 700; + src: local("Lato Italic"), + local("Lato-Italic"), + url("../fonts/Lato-RegularItalic.ttf") format("truetype"); +} + +/* + * ----------------------------------------------------------- + * SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 + * ----------------------------------------------------------- + * + * PREAMBLE + * The goals of the Open Font License (OFL) are to stimulate worldwide + * development of collaborative font projects, to support the font creation + * efforts of academic and linguistic communities, and to provide a free and + * open framework in which fonts may be shared and improved in partnership + * with others. + * + * The OFL allows the licensed fonts to be used, studied, modified and + * redistributed freely as long as they are not sold by themselves. The + * fonts, including any derivative works, can be bundled, embedded, + * redistributed and/or sold with any software provided that any reserved + * names are not used by derivative works. The fonts and derivatives, + * however, cannot be released under any other type of license. The + * requirement for fonts to remain under this license does not apply + * to any document created using the fonts or their derivatives. + * + * DEFINITIONS + * "Font Software" refers to the set of files released by the Copyright + * Holder(s) under this license and clearly marked as such. This may + * include source files, build scripts and documentation. + * + * "Reserved Font Name" refers to any names specified as such after the + * copyright statement(s). + * + * "Original Version" refers to the collection of Font Software components as + * distributed by the Copyright Holder(s). + * + * "Modified Version" refers to any derivative made by adding to, deleting, + * or substituting -- in part or in whole -- any of the components of the + * Original Version, by changing formats or by porting the Font Software to a + * new environment. + * + * "Author" refers to any designer, engineer, programmer, technical + * writer or other person who contributed to the Font Software. + * + * PERMISSION & CONDITIONS + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of the Font Software, to use, study, copy, merge, embed, modify, + * redistribute, and sell modified and unmodified copies of the Font + * Software, subject to the following conditions: + * + * 1) Neither the Font Software nor any of its individual components, + * in Original or Modified Versions, may be sold by itself. + * + * 2) Original or Modified Versions of the Font Software may be bundled, + * redistributed and/or sold with any software, provided that each copy + * contains the above copyright notice and this license. These can be + * included either as stand-alone text files, human-readable headers or + * in the appropriate machine-readable metadata fields within text or + * binary files as long as those fields can be easily viewed by the user. + * + * 3) No Modified Version of the Font Software may use the Reserved Font + * Name(s) unless explicit written permission is granted by the corresponding + * Copyright Holder. This restriction only applies to the primary font name as + * presented to the users. + * + * 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font + * Software shall not be used to promote, endorse or advertise any + * Modified Version, except to acknowledge the contribution(s) of the + * Copyright Holder(s) and the Author(s) or with their explicit written + * permission. + * + * 5) The Font Software, modified or unmodified, in part or in whole, + * must be distributed entirely under this license, and must not be + * distributed under any other license. The requirement for fonts to + * remain under this license does not apply to any document created + * using the Font Software. + * + * TERMINATION + * This license becomes null and void if any of the above conditions are + * not met. + * + * DISCLAIMER + * THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL + * DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM + * OTHER DEALINGS IN THE FONT SOFTWARE. + */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/css/rdoc.css b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/css/rdoc.css new file mode 100644 index 0000000..ebe2e93 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/css/rdoc.css @@ -0,0 +1,639 @@ +/* + * "Darkfish" Rdoc CSS + * $Id: rdoc.css 54 2009-01-27 01:09:48Z deveiant $ + * + * Author: Michael Granger + * + */ + +/* vim: ft=css et sw=2 ts=2 sts=2 */ +/* Base Green is: #6C8C22 */ + +.hide { display: none !important; } + +* { padding: 0; margin: 0; } + +body { + background: #fafafa; + font-family: Lato, sans-serif; + font-weight: 300; +} + +h1 span, +h2 span, +h3 span, +h4 span, +h5 span, +h6 span { + position: relative; + + display: none; + padding-left: 1em; + line-height: 0; + vertical-align: baseline; + font-size: 10px; +} + +h1 span { top: -1.3em; } +h2 span { top: -1.2em; } +h3 span { top: -1.0em; } +h4 span { top: -0.8em; } +h5 span { top: -0.5em; } +h6 span { top: -0.5em; } + +h1:hover span, +h2:hover span, +h3:hover span, +h4:hover span, +h5:hover span, +h6:hover span { + display: inline; +} + +h1:target, +h2:target, +h3:target, +h4:target, +h5:target, +h6:target { + margin-left: -10px; + border-left: 10px solid #f1edba; +} + +:link, +:visited { + color: #6C8C22; + text-decoration: none; +} + +:link:hover, +:visited:hover { + border-bottom: 1px dotted #6C8C22; +} + +code, +pre { + font-family: "Source Code Pro", Monaco, monospace; + background-color: rgba(27,31,35,0.05); + padding: 0em 0.2em; + border-radius: 0.2em; +} + +table { + margin: 0; + border-spacing: 0; + border-collapse: collapse; +} + +table tr th, table tr td { + padding: 0.2em 0.4em; + border: 1px solid #ccc; +} + +table tr th { + background-color: #eceaed; +} + +table tr:nth-child(even) td { + background-color: #f5f4f6; +} + +/* @group Generic Classes */ + +.initially-hidden { + display: none; +} + +#search-field { + width: 98%; + background: white; + border: none; + height: 1.5em; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + text-align: left; +} +#search-field:focus { + background: #f1edba; +} +#search-field:-moz-placeholder, +#search-field::-webkit-input-placeholder { + font-weight: bold; + color: #666; +} + +.missing-docs { + font-size: 120%; + background: white url(../images/wrench_orange.png) no-repeat 4px center; + color: #ccc; + line-height: 2em; + border: 1px solid #d00; + opacity: 1; + padding-left: 20px; + text-indent: 24px; + letter-spacing: 3px; + font-weight: bold; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; +} + +.target-section { + border: 2px solid #dcce90; + border-left-width: 8px; + padding: 0 1em; + background: #fff3c2; +} + +/* @end */ + +/* @group Index Page, Standalone file pages */ +.table-of-contents ul { + margin: 1em; + list-style: none; +} + +.table-of-contents ul ul { + margin-top: 0.25em; +} + +.table-of-contents ul :link, +.table-of-contents ul :visited { + font-size: 16px; +} + +.table-of-contents li { + margin-bottom: 0.25em; +} + +.table-of-contents li .toc-toggle { + width: 16px; + height: 16px; + background: url(../images/add.png) no-repeat; +} + +.table-of-contents li .toc-toggle.open { + background: url(../images/delete.png) no-repeat; +} + +/* @end */ + +/* @group Top-Level Structure */ + +nav { + float: left; + width: 260px; + font-family: Helvetica, sans-serif; + font-size: 14px; + border-right: 1px solid #ccc; +} + +main { + display: block; + margin: 0 2em 5em 260px; + padding-left: 20px; + min-width: 340px; + font-size: 16px; +} + +main h1, +main h2, +main h3, +main h4, +main h5, +main h6 { + font-family: Helvetica, sans-serif; +} + +.table-of-contents main { + margin-left: 2em; +} + +#validator-badges { + clear: both; + margin: 1em 1em 2em; + font-size: smaller; +} + +/* @end */ + +/* @group navigation */ +nav { + margin-bottom: 1em; +} + +nav .nav-section { + margin-top: 2em; + border-top: 2px solid #aaa; + font-size: 90%; + overflow: hidden; +} + +nav h2 { + margin: 0; + padding: 2px 8px 2px 8px; + background-color: #e8e8e8; + color: #555; + font-size: 125%; + text-align: center; +} + +nav h3, +#table-of-contents-navigation { + margin: 0; + padding: 2px 8px 2px 8px; + text-align: right; + background-color: #e8e8e8; + color: #555; +} + +nav ul, +nav dl, +nav p { + padding: 4px 8px 0; + list-style: none; +} + +#project-navigation .nav-section { + margin: 0; + border-top: 0; +} + +#home-section h2 { + text-align: center; +} + +#table-of-contents-navigation { + font-size: 1.2em; + font-weight: bold; + text-align: center; +} + +#search-section { + margin-top: 0; + border-top: 0; +} + +#search-field-wrapper { + border-top: 1px solid #aaa; + border-bottom: 1px solid #aaa; + padding: 3px 8px; + background-color: #e8e8e8; + color: #555; +} + +ul.link-list li { + white-space: nowrap; + line-height: 1.4em; +} + +ul.link-list .type { + font-size: 8px; + text-transform: uppercase; + color: white; + background: #969696; + padding: 2px 4px; + -webkit-border-radius: 5px; +} + +dl.note-list dt { + float: left; + margin-right: 1em; +} + +.calls-super { + background: url(../images/arrow_up.png) no-repeat right center; +} + +/* @end */ + +/* @group Documentation Section */ +main { + color: #333; +} + +main > h1:first-child, +main > h2:first-child, +main > h3:first-child, +main > h4:first-child, +main > h5:first-child, +main > h6:first-child { + margin-top: 0px; +} + +main sup { + vertical-align: super; + font-size: 0.8em; +} + +/* The heading with the class name */ +main h1[class] { + margin-top: 0; + margin-bottom: 1em; + font-size: 2em; + color: #6C8C22; +} + +main h1 { + margin: 2em 0 0.5em; + font-size: 1.7em; +} + +main h2 { + margin: 2em 0 0.5em; + font-size: 1.5em; +} + +main h3 { + margin: 2em 0 0.5em; + font-size: 1.2em; +} + +main h4 { + margin: 2em 0 0.5em; + font-size: 1.1em; +} + +main h5 { + margin: 2em 0 0.5em; + font-size: 1em; +} + +main h6 { + margin: 2em 0 0.5em; + font-size: 1em; +} + +main p { + margin: 0 0 0.5em; + line-height: 1.4em; +} + +main pre { + margin: 1.2em 0.5em; + padding: 1em; + font-size: 0.8em; +} + +main hr { + margin: 1.5em 1em; + border: 2px solid #ddd; +} + +main blockquote { + margin: 0 2em 1.2em 1.2em; + padding-left: 0.5em; + border-left: 2px solid #ddd; +} + +main ol, +main ul { + margin: 1em 2em; +} + +main li > p { + margin-bottom: 0.5em; +} + +main dl { + margin: 1em 0.5em; +} + +main dt { + margin-bottom: 0.5em; + font-weight: bold; +} + +main dd { + margin: 0 1em 1em 0.5em; +} + +main header h2 { + margin-top: 2em; + border-width: 0; + border-top: 4px solid #bbb; + font-size: 130%; +} + +main header h3 { + margin: 2em 0 1.5em; + border-width: 0; + border-top: 3px solid #bbb; + font-size: 120%; +} + +.documentation-section-title { + position: relative; +} +.documentation-section-title .section-click-top { + position: absolute; + top: 6px; + left: 12px; + font-size: 10px; + color: #9b9877; + visibility: hidden; + padding-left: 0.5px; +} + +.documentation-section-title:hover .section-click-top { + visibility: visible; +} + +.constants-list > dl { + margin: 1em 0 2em; + border: 0; +} + +.constants-list > dl dt { + margin-bottom: 0.75em; + padding-left: 0; + font-family: "Source Code Pro", Monaco, monospace; + font-size: 110%; +} + +.constants-list > dl dt a { + color: inherit; +} + +.constants-list > dl dd { + margin: 0 0 2em 0; + padding: 0; + color: #666; +} + +.documentation-section h2 { + position: relative; +} + +.documentation-section h2 a { + position: absolute; + top: 8px; + right: 10px; + font-size: 12px; + color: #9b9877; + visibility: hidden; +} + +.documentation-section h2:hover a { + visibility: visible; +} + +/* @group Method Details */ + +main .method-source-code { + max-height: 0; + overflow: hidden; + transition-duration: 200ms; + transition-delay: 0ms; + transition-property: all; + transition-timing-function: ease-in-out; +} + +main .method-source-code.active-menu { + max-height: 100vh; +} + +main .method-description .method-calls-super { + color: #333; + font-weight: bold; +} + +main .method-detail { + margin-bottom: 2.5em; + cursor: pointer; +} + +main .method-detail:target { + margin-left: -10px; + border-left: 10px solid #f1edba; +} + +main .method-heading { + position: relative; + font-family: "Source Code Pro", Monaco, monospace; + font-size: 110%; + font-weight: bold; + color: #333; +} +main .method-heading :link, +main .method-heading :visited { + color: inherit; +} +main .method-click-advice { + position: absolute; + top: 2px; + right: 5px; + font-size: 12px; + color: #9b9877; + visibility: hidden; + padding-right: 20px; + line-height: 20px; + background: url(../images/zoom.png) no-repeat right top; +} +main .method-heading:hover .method-click-advice { + visibility: visible; +} + +main .method-alias .method-heading { + color: #666; +} + +main .method-description, +main .aliases { + margin-top: 0.75em; + color: #333; +} + +main .aliases { + padding-top: 4px; + font-style: italic; + cursor: default; +} +main .method-description ul { + margin-left: 1.5em; +} + +main #attribute-method-details .method-detail:hover { + background-color: transparent; + cursor: default; +} +main .attribute-access-type { + text-transform: uppercase; + padding: 0 1em; +} +/* @end */ + +/* @end */ + +/* @group Source Code */ + +pre { + margin: 0.5em 0; + border: 1px dashed #999; + padding: 0.5em; + background: #262626; + color: white; + overflow: auto; +} + +.ruby-constant { color: #7fffd4; background: transparent; } +.ruby-keyword { color: #00ffff; background: transparent; } +.ruby-ivar { color: #eedd82; background: transparent; } +.ruby-operator { color: #00ffee; background: transparent; } +.ruby-identifier { color: #ffdead; background: transparent; } +.ruby-node { color: #ffa07a; background: transparent; } +.ruby-comment { color: #dc0000; background: transparent; } +.ruby-regexp { color: #ffa07a; background: transparent; } +.ruby-value { color: #7fffd4; background: transparent; } + +/* @end */ + + +/* @group search results */ +#search-results { + font-family: Lato, sans-serif; + font-weight: 300; +} + +#search-results .search-match { + font-family: Helvetica, sans-serif; + font-weight: normal; +} + +#search-results .search-selected { + background: #e8e8e8; + border-bottom: 1px solid transparent; +} + +#search-results li { + list-style: none; + border-bottom: 1px solid #aaa; + margin-bottom: 0.5em; +} + +#search-results li:last-child { + border-bottom: none; + margin-bottom: 0; +} + +#search-results li p { + padding: 0; + margin: 0.5em; +} + +#search-results .search-namespace { + font-weight: bold; +} + +#search-results li em { + background: yellow; + font-style: normal; +} + +#search-results pre { + margin: 0.5em; + font-family: "Source Code Pro", Monaco, monospace; +} + +/* @end */ + diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-Light.ttf b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-Light.ttf new file mode 100644 index 0000000..b49dd43 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-Light.ttf differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-LightItalic.ttf b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-LightItalic.ttf new file mode 100644 index 0000000..7959fef Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-LightItalic.ttf differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-Regular.ttf b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-Regular.ttf new file mode 100644 index 0000000..839cd58 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-Regular.ttf differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-RegularItalic.ttf b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-RegularItalic.ttf new file mode 100644 index 0000000..bababa0 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/Lato-RegularItalic.ttf differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Bold.ttf b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Bold.ttf new file mode 100644 index 0000000..dd00982 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Bold.ttf differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Regular.ttf b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Regular.ttf new file mode 100644 index 0000000..1decfb9 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/fonts/SourceCodePro-Regular.ttf differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/add.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/add.png new file mode 100644 index 0000000..6332fef Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/add.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/arrow_up.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/arrow_up.png new file mode 100644 index 0000000..1ebb193 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/arrow_up.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/brick.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/brick.png new file mode 100644 index 0000000..7851cf3 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/brick.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/brick_link.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/brick_link.png new file mode 100644 index 0000000..9ebf013 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/brick_link.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bug.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bug.png new file mode 100644 index 0000000..2d5fb90 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bug.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bullet_black.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bullet_black.png new file mode 100644 index 0000000..5761970 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bullet_black.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bullet_toggle_minus.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bullet_toggle_minus.png new file mode 100644 index 0000000..b47ce55 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bullet_toggle_minus.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bullet_toggle_plus.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bullet_toggle_plus.png new file mode 100644 index 0000000..9ab4a89 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/bullet_toggle_plus.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/date.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/date.png new file mode 100644 index 0000000..783c833 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/date.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/delete.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/delete.png new file mode 100644 index 0000000..08f2493 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/delete.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/find.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/find.png new file mode 100644 index 0000000..1547479 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/find.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/loadingAnimation.gif b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/loadingAnimation.gif new file mode 100644 index 0000000..82290f4 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/loadingAnimation.gif differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/macFFBgHack.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/macFFBgHack.png new file mode 100644 index 0000000..c6473b3 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/macFFBgHack.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/package.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/package.png new file mode 100644 index 0000000..da3c2a2 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/package.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/page_green.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/page_green.png new file mode 100644 index 0000000..de8e003 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/page_green.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/page_white_text.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/page_white_text.png new file mode 100644 index 0000000..813f712 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/page_white_text.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/page_white_width.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/page_white_width.png new file mode 100644 index 0000000..1eb8809 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/page_white_width.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/plugin.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/plugin.png new file mode 100644 index 0000000..6187b15 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/plugin.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/ruby.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/ruby.png new file mode 100644 index 0000000..f763a16 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/ruby.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/tag_blue.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/tag_blue.png new file mode 100644 index 0000000..3f02b5f Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/tag_blue.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/tag_green.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/tag_green.png new file mode 100644 index 0000000..83ec984 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/tag_green.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/transparent.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/transparent.png new file mode 100644 index 0000000..d665e17 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/transparent.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/wrench.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/wrench.png new file mode 100644 index 0000000..5c8213f Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/wrench.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/wrench_orange.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/wrench_orange.png new file mode 100644 index 0000000..565a933 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/wrench_orange.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/zoom.png b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/zoom.png new file mode 100644 index 0000000..908612e Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/images/zoom.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/index.rhtml b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/index.rhtml new file mode 100644 index 0000000..13fa3dc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/index.rhtml @@ -0,0 +1,22 @@ + + + +
+<%- if @options.main_page and + main_page = @files.find { |f| f.full_name == @options.main_page } then %> +<%= main_page.description %> +<%- else -%> +

This is the API documentation for <%= @title %>. +<%- end -%> +

diff --git a/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/js/darkfish.js b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/js/darkfish.js new file mode 100644 index 0000000..111bbf8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/rdoc-6.4.0/lib/rdoc/generator/template/darkfish/js/darkfish.js @@ -0,0 +1,84 @@ +/** + * + * Darkfish Page Functions + * $Id: darkfish.js 53 2009-01-07 02:52:03Z deveiant $ + * + * Author: Michael Granger + * + */ + +/* Provide console simulation for firebug-less environments */ +/* +if (!("console" in window) || !("firebug" in console)) { + var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", + "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; + + window.console = {}; + for (var i = 0; i < names.length; ++i) + window.console[names[i]] = function() {}; +}; +*/ + + +function showSource( e ) { + var target = e.target; + while (!target.classList.contains('method-detail')) { + target = target.parentNode; + } + if (typeof target !== "undefined" && target !== null) { + target = target.querySelector('.method-source-code'); + } + if (typeof target !== "undefined" && target !== null) { + target.classList.toggle('active-menu') + } +}; + +function hookSourceViews() { + document.querySelectorAll('.method-heading').forEach(function (codeObject) { + codeObject.addEventListener('click', showSource); + }); +}; + +function hookSearch() { + var input = document.querySelector('#search-field'); + var result = document.querySelector('#search-results'); + result.classList.remove("initially-hidden"); + + var search_section = document.querySelector('#search-section'); + search_section.classList.remove("initially-hidden"); + + var search = new Search(search_data, input, result); + + search.renderItem = function(result) { + var li = document.createElement('li'); + var html = ''; + + // TODO add relative path to + + <%= yield %> + + +@@ login +
+ + + +
+ +@@ chat +

+
+ +
+ + + diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/rainbows.conf b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/rainbows.conf new file mode 100644 index 0000000..31742e9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/rainbows.conf @@ -0,0 +1,3 @@ +Rainbows! do + use :EventMachine +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/rainbows.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/rainbows.rb new file mode 100644 index 0000000..895e19a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/rainbows.rb @@ -0,0 +1,20 @@ +require 'rainbows' + +module Rack + module Handler + class Rainbows + def self.run(app, **options) + rainbows_options = { + listeners: ["#{options[:Host]}:#{options[:Port]}"], + worker_processes: 1, + timeout: 30, + config_file: ::File.expand_path('rainbows.conf', __dir__), + } + + ::Rainbows::HttpServer.new(app, rainbows_options).start.join + end + end + + register :rainbows, ::Rack::Handler::Rainbows + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/simple.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/simple.rb new file mode 100755 index 0000000..2697f94 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/simple.rb @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby -I ../lib -I lib +require 'sinatra' +get('/') { 'this is a simple app' } diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/stream.ru b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/stream.ru new file mode 100644 index 0000000..74af0a6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/examples/stream.ru @@ -0,0 +1,26 @@ +# this example does *not* work properly with WEBrick +# +# run *one* of these: +# +# rackup -s mongrel stream.ru # gem install mongrel +# unicorn stream.ru # gem install unicorn +# puma stream.ru # gem install puma +# rainbows -c rainbows.conf stream.ru # gem install rainbows eventmachine + +require 'sinatra/base' + +class Stream < Sinatra::Base + get '/' do + content_type :txt + + stream do |out| + out << "It's gonna be legen -\n" + sleep 0.5 + out << " (wait for it) \n" + sleep 1 + out << "- dary!\n" + end + end +end + +run Stream diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra.rb new file mode 100644 index 0000000..6826138 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra.rb @@ -0,0 +1,3 @@ +require 'sinatra/main' + +enable :inline_templates diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/base.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/base.rb new file mode 100644 index 0000000..6ced0a6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/base.rb @@ -0,0 +1,2021 @@ +# coding: utf-8 +# frozen_string_literal: true + +# external dependencies +require 'rack' +require 'tilt' +require 'rack/protection' +require 'mustermann' +require 'mustermann/sinatra' +require 'mustermann/regular' + +# stdlib dependencies +require 'thread' +require 'time' +require 'uri' + +# other files we need +require 'sinatra/indifferent_hash' +require 'sinatra/show_exceptions' +require 'sinatra/version' + +module Sinatra + # The request object. See Rack::Request for more info: + # http://rubydoc.info/github/rack/rack/master/Rack/Request + class Request < Rack::Request + HEADER_PARAM = /\s*[\w.]+=(?:[\w.]+|"(?:[^"\\]|\\.)*")?\s*/ + HEADER_VALUE_WITH_PARAMS = /(?:(?:\w+|\*)\/(?:\w+(?:\.|\-|\+)?|\*)*)\s*(?:;#{HEADER_PARAM})*/ + + # Returns an array of acceptable media types for the response + def accept + @env['sinatra.accept'] ||= begin + if @env.include? 'HTTP_ACCEPT' and @env['HTTP_ACCEPT'].to_s != '' + @env['HTTP_ACCEPT'].to_s.scan(HEADER_VALUE_WITH_PARAMS). + map! { |e| AcceptEntry.new(e) }.sort + else + [AcceptEntry.new('*/*')] + end + end + end + + def accept?(type) + preferred_type(type).to_s.include?(type) + end + + def preferred_type(*types) + return accept.first if types.empty? + types.flatten! + return types.first if accept.empty? + accept.detect do |accept_header| + type = types.detect { |t| MimeTypeEntry.new(t).accepts?(accept_header) } + return type if type + end + end + + alias secure? ssl? + + def forwarded? + @env.include? "HTTP_X_FORWARDED_HOST" + end + + def safe? + get? or head? or options? or trace? + end + + def idempotent? + safe? or put? or delete? or link? or unlink? + end + + def link? + request_method == "LINK" + end + + def unlink? + request_method == "UNLINK" + end + + def params + super + rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e + raise BadRequest, "Invalid query parameters: #{Rack::Utils.escape_html(e.message)}" + rescue EOFError => e + raise BadRequest, "Invalid multipart/form-data: #{Rack::Utils.escape_html(e.message)}" + end + + class AcceptEntry + attr_accessor :params + attr_reader :entry + + def initialize(entry) + params = entry.scan(HEADER_PARAM).map! do |s| + key, value = s.strip.split('=', 2) + value = value[1..-2].gsub(/\\(.)/, '\1') if value.start_with?('"') + [key, value] + end + + @entry = entry + @type = entry[/[^;]+/].delete(' ') + @params = Hash[params] + @q = @params.delete('q') { 1.0 }.to_f + end + + def <=>(other) + other.priority <=> self.priority + end + + def priority + # We sort in descending order; better matches should be higher. + [ @q, -@type.count('*'), @params.size ] + end + + def to_str + @type + end + + def to_s(full = false) + full ? entry : to_str + end + + def respond_to?(*args) + super or to_str.respond_to?(*args) + end + + def method_missing(*args, &block) + to_str.send(*args, &block) + end + end + + class MimeTypeEntry + attr_reader :params + + def initialize(entry) + params = entry.scan(HEADER_PARAM).map! do |s| + key, value = s.strip.split('=', 2) + value = value[1..-2].gsub(/\\(.)/, '\1') if value.start_with?('"') + [key, value] + end + + @type = entry[/[^;]+/].delete(' ') + @params = Hash[params] + end + + def accepts?(entry) + File.fnmatch(entry, self) && matches_params?(entry.params) + end + + def to_str + @type + end + + def matches_params?(params) + return true if @params.empty? + + params.all? { |k,v| !@params.has_key?(k) || @params[k] == v } + end + end + end + + # The response object. See Rack::Response and Rack::Response::Helpers for + # more info: + # http://rubydoc.info/github/rack/rack/master/Rack/Response + # http://rubydoc.info/github/rack/rack/master/Rack/Response/Helpers + class Response < Rack::Response + DROP_BODY_RESPONSES = [204, 304] + + def body=(value) + value = value.body while Rack::Response === value + @body = String === value ? [value.to_str] : value + end + + def each + block_given? ? super : enum_for(:each) + end + + def finish + result = body + + if drop_content_info? + headers.delete "Content-Length" + headers.delete "Content-Type" + end + + if drop_body? + close + result = [] + end + + if calculate_content_length? + # if some other code has already set Content-Length, don't muck with it + # currently, this would be the static file-handler + headers["Content-Length"] = body.map(&:bytesize).reduce(0, :+).to_s + end + + [status, headers, result] + end + + private + + def calculate_content_length? + headers["Content-Type"] and not headers["Content-Length"] and Array === body + end + + def drop_content_info? + informational? or drop_body? + end + + def drop_body? + DROP_BODY_RESPONSES.include?(status) + end + end + + # Some Rack handlers (Rainbows!) implement an extended body object protocol, however, + # some middleware (namely Rack::Lint) will break it by not mirroring the methods in question. + # This middleware will detect an extended body object and will make sure it reaches the + # handler directly. We do this here, so our middleware and middleware set up by the app will + # still be able to run. + class ExtendedRack < Struct.new(:app) + def call(env) + result, callback = app.call(env), env['async.callback'] + return result unless callback and async?(*result) + after_response { callback.call result } + setup_close(env, *result) + throw :async + end + + private + + def setup_close(env, status, headers, body) + return unless body.respond_to? :close and env.include? 'async.close' + env['async.close'].callback { body.close } + env['async.close'].errback { body.close } + end + + def after_response(&block) + raise NotImplementedError, "only supports EventMachine at the moment" unless defined? EventMachine + EventMachine.next_tick(&block) + end + + def async?(status, headers, body) + return true if status == -1 + body.respond_to? :callback and body.respond_to? :errback + end + end + + # Behaves exactly like Rack::CommonLogger with the notable exception that it does nothing, + # if another CommonLogger is already in the middleware chain. + class CommonLogger < Rack::CommonLogger + def call(env) + env['sinatra.commonlogger'] ? @app.call(env) : super + end + + superclass.class_eval do + alias call_without_check call unless method_defined? :call_without_check + def call(env) + env['sinatra.commonlogger'] = true + call_without_check(env) + end + end + end + + class BadRequest < TypeError #:nodoc: + def http_status; 400 end + end + + class NotFound < NameError #:nodoc: + def http_status; 404 end + end + + # Methods available to routes, before/after filters, and views. + module Helpers + # Set or retrieve the response status code. + def status(value = nil) + response.status = Rack::Utils.status_code(value) if value + response.status + end + + # Set or retrieve the response body. When a block is given, + # evaluation is deferred until the body is read with #each. + def body(value = nil, &block) + if block_given? + def block.each; yield(call) end + response.body = block + elsif value + # Rack 2.0 returns a Rack::File::Iterator here instead of + # Rack::File as it was in the previous API. + unless request.head? || value.is_a?(Rack::File::Iterator) || value.is_a?(Stream) + headers.delete 'Content-Length' + end + response.body = value + else + response.body + end + end + + # Halt processing and redirect to the URI provided. + def redirect(uri, *args) + if env['HTTP_VERSION'] == 'HTTP/1.1' and env["REQUEST_METHOD"] != 'GET' + status 303 + else + status 302 + end + + # According to RFC 2616 section 14.30, "the field value consists of a + # single absolute URI" + response['Location'] = uri(uri.to_s, settings.absolute_redirects?, settings.prefixed_redirects?) + halt(*args) + end + + # Generates the absolute URI for a given path in the app. + # Takes Rack routers and reverse proxies into account. + def uri(addr = nil, absolute = true, add_script_name = true) + return addr if addr =~ /\A[a-z][a-z0-9\+\.\-]*:/i + uri = [host = String.new] + if absolute + host << "http#{'s' if request.secure?}://" + if request.forwarded? or request.port != (request.secure? ? 443 : 80) + host << request.host_with_port + else + host << request.host + end + end + uri << request.script_name.to_s if add_script_name + uri << (addr ? addr : request.path_info).to_s + File.join uri + end + + alias url uri + alias to uri + + # Halt processing and return the error status provided. + def error(code, body = nil) + code, body = 500, code.to_str if code.respond_to? :to_str + response.body = body unless body.nil? + halt code + end + + # Halt processing and return a 404 Not Found. + def not_found(body = nil) + error 404, body + end + + # Set multiple response headers with Hash. + def headers(hash = nil) + response.headers.merge! hash if hash + response.headers + end + + # Access the underlying Rack session. + def session + request.session + end + + # Access shared logger object. + def logger + request.logger + end + + # Look up a media type by file extension in Rack's mime registry. + def mime_type(type) + Base.mime_type(type) + end + + # Set the Content-Type of the response body given a media type or file + # extension. + def content_type(type = nil, params = {}) + return response['Content-Type'] unless type + default = params.delete :default + mime_type = mime_type(type) || default + fail "Unknown media type: %p" % type if mime_type.nil? + mime_type = mime_type.dup + unless params.include? :charset or settings.add_charset.all? { |p| not p === mime_type } + params[:charset] = params.delete('charset') || settings.default_encoding + end + params.delete :charset if mime_type.include? 'charset' + unless params.empty? + mime_type << (mime_type.include?(';') ? ', ' : ';') + mime_type << params.map do |key, val| + val = val.inspect if val =~ /[";,]/ + "#{key}=#{val}" + end.join(', ') + end + response['Content-Type'] = mime_type + end + + # Set the Content-Disposition to "attachment" with the specified filename, + # instructing the user agents to prompt to save. + def attachment(filename = nil, disposition = :attachment) + response['Content-Disposition'] = disposition.to_s.dup + if filename + params = '; filename="%s"' % File.basename(filename) + response['Content-Disposition'] << params + ext = File.extname(filename) + content_type(ext) unless response['Content-Type'] or ext.empty? + end + end + + # Use the contents of the file at +path+ as the response body. + def send_file(path, opts = {}) + if opts[:type] or not response['Content-Type'] + content_type opts[:type] || File.extname(path), :default => 'application/octet-stream' + end + + disposition = opts[:disposition] + filename = opts[:filename] + disposition = :attachment if disposition.nil? and filename + filename = path if filename.nil? + attachment(filename, disposition) if disposition + + last_modified opts[:last_modified] if opts[:last_modified] + + file = Rack::File.new(File.dirname(settings.app_file)) + result = file.serving(request, path) + + result[1].each { |k,v| headers[k] ||= v } + headers['Content-Length'] = result[1]['Content-Length'] + opts[:status] &&= Integer(opts[:status]) + halt (opts[:status] || result[0]), result[2] + rescue Errno::ENOENT + not_found + end + + # Class of the response body in case you use #stream. + # + # Three things really matter: The front and back block (back being the + # block generating content, front the one sending it to the client) and + # the scheduler, integrating with whatever concurrency feature the Rack + # handler is using. + # + # Scheduler has to respond to defer and schedule. + class Stream + def self.schedule(*) yield end + def self.defer(*) yield end + + def initialize(scheduler = self.class, keep_open = false, &back) + @back, @scheduler, @keep_open = back.to_proc, scheduler, keep_open + @callbacks, @closed = [], false + end + + def close + return if closed? + @closed = true + @scheduler.schedule { @callbacks.each { |c| c.call } } + end + + def each(&front) + @front = front + @scheduler.defer do + begin + @back.call(self) + rescue Exception => e + @scheduler.schedule { raise e } + end + close unless @keep_open + end + end + + def <<(data) + @scheduler.schedule { @front.call(data.to_s) } + self + end + + def callback(&block) + return yield if closed? + @callbacks << block + end + + alias errback callback + + def closed? + @closed + end + end + + # Allows to start sending data to the client even though later parts of + # the response body have not yet been generated. + # + # The close parameter specifies whether Stream#close should be called + # after the block has been executed. This is only relevant for evented + # servers like Rainbows. + def stream(keep_open = false) + scheduler = env['async.callback'] ? EventMachine : Stream + current = @params.dup + body Stream.new(scheduler, keep_open) { |out| with_params(current) { yield(out) } } + end + + # Specify response freshness policy for HTTP caches (Cache-Control header). + # Any number of non-value directives (:public, :private, :no_cache, + # :no_store, :must_revalidate, :proxy_revalidate) may be passed along with + # a Hash of value directives (:max_age, :s_maxage). + # + # cache_control :public, :must_revalidate, :max_age => 60 + # => Cache-Control: public, must-revalidate, max-age=60 + # + # See RFC 2616 / 14.9 for more on standard cache control directives: + # http://tools.ietf.org/html/rfc2616#section-14.9.1 + def cache_control(*values) + if values.last.kind_of?(Hash) + hash = values.pop + hash.reject! { |k, v| v == false } + hash.reject! { |k, v| values << k if v == true } + else + hash = {} + end + + values.map! { |value| value.to_s.tr('_','-') } + hash.each do |key, value| + key = key.to_s.tr('_', '-') + value = value.to_i if ['max-age', 's-maxage'].include? key + values << "#{key}=#{value}" + end + + response['Cache-Control'] = values.join(', ') if values.any? + end + + # Set the Expires header and Cache-Control/max-age directive. Amount + # can be an integer number of seconds in the future or a Time object + # indicating when the response should be considered "stale". The remaining + # "values" arguments are passed to the #cache_control helper: + # + # expires 500, :public, :must_revalidate + # => Cache-Control: public, must-revalidate, max-age=500 + # => Expires: Mon, 08 Jun 2009 08:50:17 GMT + # + def expires(amount, *values) + values << {} unless values.last.kind_of?(Hash) + + if amount.is_a? Integer + time = Time.now + amount.to_i + max_age = amount + else + time = time_for amount + max_age = time - Time.now + end + + values.last.merge!(:max_age => max_age) + cache_control(*values) + + response['Expires'] = time.httpdate + end + + # Set the last modified time of the resource (HTTP 'Last-Modified' header) + # and halt if conditional GET matches. The +time+ argument is a Time, + # DateTime, or other object that responds to +to_time+. + # + # When the current request includes an 'If-Modified-Since' header that is + # equal or later than the time specified, execution is immediately halted + # with a '304 Not Modified' response. + def last_modified(time) + return unless time + time = time_for time + response['Last-Modified'] = time.httpdate + return if env['HTTP_IF_NONE_MATCH'] + + if status == 200 and env['HTTP_IF_MODIFIED_SINCE'] + # compare based on seconds since epoch + since = Time.httpdate(env['HTTP_IF_MODIFIED_SINCE']).to_i + halt 304 if since >= time.to_i + end + + if (success? or status == 412) and env['HTTP_IF_UNMODIFIED_SINCE'] + # compare based on seconds since epoch + since = Time.httpdate(env['HTTP_IF_UNMODIFIED_SINCE']).to_i + halt 412 if since < time.to_i + end + rescue ArgumentError + end + + ETAG_KINDS = [:strong, :weak] + # Set the response entity tag (HTTP 'ETag' header) and halt if conditional + # GET matches. The +value+ argument is an identifier that uniquely + # identifies the current version of the resource. The +kind+ argument + # indicates whether the etag should be used as a :strong (default) or :weak + # cache validator. + # + # When the current request includes an 'If-None-Match' header with a + # matching etag, execution is immediately halted. If the request method is + # GET or HEAD, a '304 Not Modified' response is sent. + def etag(value, options = {}) + # Before touching this code, please double check RFC 2616 14.24 and 14.26. + options = {:kind => options} unless Hash === options + kind = options[:kind] || :strong + new_resource = options.fetch(:new_resource) { request.post? } + + unless ETAG_KINDS.include?(kind) + raise ArgumentError, ":strong or :weak expected" + end + + value = '"%s"' % value + value = "W/#{value}" if kind == :weak + response['ETag'] = value + + if success? or status == 304 + if etag_matches? env['HTTP_IF_NONE_MATCH'], new_resource + halt(request.safe? ? 304 : 412) + end + + if env['HTTP_IF_MATCH'] + halt 412 unless etag_matches? env['HTTP_IF_MATCH'], new_resource + end + end + end + + # Sugar for redirect (example: redirect back) + def back + request.referer + end + + # whether or not the status is set to 1xx + def informational? + status.between? 100, 199 + end + + # whether or not the status is set to 2xx + def success? + status.between? 200, 299 + end + + # whether or not the status is set to 3xx + def redirect? + status.between? 300, 399 + end + + # whether or not the status is set to 4xx + def client_error? + status.between? 400, 499 + end + + # whether or not the status is set to 5xx + def server_error? + status.between? 500, 599 + end + + # whether or not the status is set to 404 + def not_found? + status == 404 + end + + # whether or not the status is set to 400 + def bad_request? + status == 400 + end + + # Generates a Time object from the given value. + # Used by #expires and #last_modified. + def time_for(value) + if value.is_a? Numeric + Time.at value + elsif value.respond_to? :to_s + Time.parse value.to_s + else + value.to_time + end + rescue ArgumentError => boom + raise boom + rescue Exception + raise ArgumentError, "unable to convert #{value.inspect} to a Time object" + end + + private + + # Helper method checking if a ETag value list includes the current ETag. + def etag_matches?(list, new_resource = request.post?) + return !new_resource if list == '*' + list.to_s.split(/\s*,\s*/).include? response['ETag'] + end + + def with_params(temp_params) + original, @params = @params, temp_params + yield + ensure + @params = original if original + end + end + + # Template rendering methods. Each method takes the name of a template + # to render as a Symbol and returns a String with the rendered output, + # as well as an optional hash with additional options. + # + # `template` is either the name or path of the template as symbol + # (Use `:'subdir/myview'` for views in subdirectories), or a string + # that will be rendered. + # + # Possible options are: + # :content_type The content type to use, same arguments as content_type. + # :layout If set to something falsy, no layout is rendered, otherwise + # the specified layout is used (Ignored for `sass` and `less`) + # :layout_engine Engine to use for rendering the layout. + # :locals A hash with local variables that should be available + # in the template + # :scope If set, template is evaluate with the binding of the given + # object rather than the application instance. + # :views Views directory to use. + module Templates + module ContentTyped + attr_accessor :content_type + end + + def initialize + super + @default_layout = :layout + @preferred_extension = nil + end + + def erb(template, options = {}, locals = {}, &block) + render(:erb, template, options, locals, &block) + end + + def erubis(template, options = {}, locals = {}) + warn "Sinatra::Templates#erubis is deprecated and will be removed, use #erb instead.\n" \ + "If you have Erubis installed, it will be used automatically." + render :erubis, template, options, locals + end + + def haml(template, options = {}, locals = {}, &block) + render(:haml, template, options, locals, &block) + end + + def sass(template, options = {}, locals = {}) + options.merge! :layout => false, :default_content_type => :css + render :sass, template, options, locals + end + + def scss(template, options = {}, locals = {}) + options.merge! :layout => false, :default_content_type => :css + render :scss, template, options, locals + end + + def less(template, options = {}, locals = {}) + options.merge! :layout => false, :default_content_type => :css + render :less, template, options, locals + end + + def stylus(template, options = {}, locals = {}) + options.merge! :layout => false, :default_content_type => :css + render :styl, template, options, locals + end + + def builder(template = nil, options = {}, locals = {}, &block) + options[:default_content_type] = :xml + render_ruby(:builder, template, options, locals, &block) + end + + def liquid(template, options = {}, locals = {}, &block) + render(:liquid, template, options, locals, &block) + end + + def markdown(template, options = {}, locals = {}) + options[:exclude_outvar] = true + render :markdown, template, options, locals + end + + def textile(template, options = {}, locals = {}) + render :textile, template, options, locals + end + + def rdoc(template, options = {}, locals = {}) + render :rdoc, template, options, locals + end + + def asciidoc(template, options = {}, locals = {}) + render :asciidoc, template, options, locals + end + + def radius(template, options = {}, locals = {}) + render :radius, template, options, locals + end + + def markaby(template = nil, options = {}, locals = {}, &block) + render_ruby(:mab, template, options, locals, &block) + end + + def coffee(template, options = {}, locals = {}) + options.merge! :layout => false, :default_content_type => :js + render :coffee, template, options, locals + end + + def nokogiri(template = nil, options = {}, locals = {}, &block) + options[:default_content_type] = :xml + render_ruby(:nokogiri, template, options, locals, &block) + end + + def slim(template, options = {}, locals = {}, &block) + render(:slim, template, options, locals, &block) + end + + def creole(template, options = {}, locals = {}) + render :creole, template, options, locals + end + + def mediawiki(template, options = {}, locals = {}) + render :mediawiki, template, options, locals + end + + def wlang(template, options = {}, locals = {}, &block) + render(:wlang, template, options, locals, &block) + end + + def yajl(template, options = {}, locals = {}) + options[:default_content_type] = :json + render :yajl, template, options, locals + end + + def rabl(template, options = {}, locals = {}) + Rabl.register! + render :rabl, template, options, locals + end + + # Calls the given block for every possible template file in views, + # named name.ext, where ext is registered on engine. + def find_template(views, name, engine) + yield ::File.join(views, "#{name}.#{@preferred_extension}") + + Tilt.default_mapping.extensions_for(engine).each do |ext| + yield ::File.join(views, "#{name}.#{ext}") unless ext == @preferred_extension + end + end + + private + + # logic shared between builder and nokogiri + def render_ruby(engine, template, options = {}, locals = {}, &block) + options, template = template, nil if template.is_a?(Hash) + template = Proc.new { block } if template.nil? + render engine, template, options, locals + end + + def render(engine, data, options = {}, locals = {}, &block) + # merge app-level options + engine_options = settings.respond_to?(engine) ? settings.send(engine) : {} + options.merge!(engine_options) { |key, v1, v2| v1 } + + # extract generic options + locals = options.delete(:locals) || locals || {} + views = options.delete(:views) || settings.views || "./views" + layout = options[:layout] + layout = false if layout.nil? && options.include?(:layout) + eat_errors = layout.nil? + layout = engine_options[:layout] if layout.nil? or (layout == true && engine_options[:layout] != false) + layout = @default_layout if layout.nil? or layout == true + layout_options = options.delete(:layout_options) || {} + content_type = options.delete(:default_content_type) + content_type = options.delete(:content_type) || content_type + layout_engine = options.delete(:layout_engine) || engine + scope = options.delete(:scope) || self + exclude_outvar = options.delete(:exclude_outvar) + options.delete(:layout) + + # set some defaults + options[:outvar] ||= '@_out_buf' unless exclude_outvar + options[:default_encoding] ||= settings.default_encoding + + # compile and render template + begin + layout_was = @default_layout + @default_layout = false + template = compile_template(engine, data, options, views) + output = template.render(scope, locals, &block) + ensure + @default_layout = layout_was + end + + # render layout + if layout + options = options.merge(:views => views, :layout => false, :eat_errors => eat_errors, :scope => scope). + merge!(layout_options) + catch(:layout_missing) { return render(layout_engine, layout, options, locals) { output } } + end + + output.extend(ContentTyped).content_type = content_type if content_type + output + end + + def compile_template(engine, data, options, views) + eat_errors = options.delete :eat_errors + template = Tilt[engine] + raise "Template engine not found: #{engine}" if template.nil? + + case data + when Symbol + template_cache.fetch engine, data, options, views do + body, path, line = settings.templates[data] + if body + body = body.call if body.respond_to?(:call) + template.new(path, line.to_i, options) { body } + else + found = false + @preferred_extension = engine.to_s + find_template(views, data, template) do |file| + path ||= file # keep the initial path rather than the last one + if found = File.exist?(file) + path = file + break + end + end + throw :layout_missing if eat_errors and not found + template.new(path, 1, options) + end + end + when Proc + compile_block_template(template, options, &data) + when String + template_cache.fetch engine, data, options, views do + compile_block_template(template, options) { data } + end + else + raise ArgumentError, "Sorry, don't know how to render #{data.inspect}." + end + end + + def compile_block_template(template, options, &body) + caller = settings.caller_locations.first + path = options[:path] || caller[0] + line = options[:line] || caller[1] + template.new(path, line.to_i, options, &body) + end + end + + # Base class for all Sinatra applications and middleware. + class Base + include Rack::Utils + include Helpers + include Templates + + URI_INSTANCE = URI::Parser.new + + attr_accessor :app, :env, :request, :response, :params + attr_reader :template_cache + + def initialize(app = nil, **kwargs) + super() + @app = app + @template_cache = Tilt::Cache.new + @pinned_response = nil # whether a before! filter pinned the content-type + yield self if block_given? + end + + # Rack call interface. + def call(env) + dup.call!(env) + end + + def call!(env) # :nodoc: + @env = env + @params = IndifferentHash.new + @request = Request.new(env) + @response = Response.new + @pinned_response = nil + template_cache.clear if settings.reload_templates + + invoke { dispatch! } + invoke { error_block!(response.status) } unless @env['sinatra.error'] + + unless @response['Content-Type'] + if Array === body && body[0].respond_to?(:content_type) + content_type body[0].content_type + elsif default = settings.default_content_type + content_type default + end + end + + @response.finish + end + + # Access settings defined with Base.set. + def self.settings + self + end + + # Access settings defined with Base.set. + def settings + self.class.settings + end + + def options + warn "Sinatra::Base#options is deprecated and will be removed, " \ + "use #settings instead." + settings + end + + # Exit the current block, halts any further processing + # of the request, and returns the specified response. + def halt(*response) + response = response.first if response.length == 1 + throw :halt, response + end + + # Pass control to the next matching route. + # If there are no more matching routes, Sinatra will + # return a 404 response. + def pass(&block) + throw :pass, block + end + + # Forward the request to the downstream app -- middleware only. + def forward + fail "downstream app not set" unless @app.respond_to? :call + status, headers, body = @app.call env + @response.status = status + @response.body = body + @response.headers.merge! headers + nil + end + + private + + # Run filters defined on the class and all superclasses. + # Accepts an optional block to call after each filter is applied. + def filter!(type, base = settings, &block) + filter!(type, base.superclass, &block) if base.superclass.respond_to?(:filters) + base.filters[type].each do |args| + result = process_route(*args) + block.call(result) if block_given? + end + end + + # Run routes defined on the class and all superclasses. + def route!(base = settings, pass_block = nil) + if routes = base.routes[@request.request_method] + routes.each do |pattern, conditions, block| + response.delete_header('Content-Type') unless @pinned_response + + returned_pass_block = process_route(pattern, conditions) do |*args| + env['sinatra.route'] = "#{@request.request_method} #{pattern}" + route_eval { block[*args] } + end + + # don't wipe out pass_block in superclass + pass_block = returned_pass_block if returned_pass_block + end + end + + # Run routes defined in superclass. + if base.superclass.respond_to?(:routes) + return route!(base.superclass, pass_block) + end + + route_eval(&pass_block) if pass_block + route_missing + end + + # Run a route block and throw :halt with the result. + def route_eval + throw :halt, yield + end + + # If the current request matches pattern and conditions, fill params + # with keys and call the given block. + # Revert params afterwards. + # + # Returns pass block. + def process_route(pattern, conditions, block = nil, values = []) + route = @request.path_info + route = '/' if route.empty? and not settings.empty_path_info? + route = route[0..-2] if !settings.strict_paths? && route != '/' && route.end_with?('/') + return unless params = pattern.params(route) + + params.delete("ignore") # TODO: better params handling, maybe turn it into "smart" object or detect changes + force_encoding(params) + @params = @params.merge(params) if params.any? + + regexp_exists = pattern.is_a?(Mustermann::Regular) || (pattern.respond_to?(:patterns) && pattern.patterns.any? {|subpattern| subpattern.is_a?(Mustermann::Regular)} ) + if regexp_exists + captures = pattern.match(route).captures.map { |c| URI_INSTANCE.unescape(c) if c } + values += captures + @params[:captures] = force_encoding(captures) unless captures.nil? || captures.empty? + else + values += params.values.flatten + end + + catch(:pass) do + conditions.each { |c| throw :pass if c.bind(self).call == false } + block ? block[self, values] : yield(self, values) + end + rescue + @env['sinatra.error.params'] = @params + raise + ensure + params ||= {} + params.each { |k, _| @params.delete(k) } unless @env['sinatra.error.params'] + end + + # No matching route was found or all routes passed. The default + # implementation is to forward the request downstream when running + # as middleware (@app is non-nil); when no downstream app is set, raise + # a NotFound exception. Subclasses can override this method to perform + # custom route miss logic. + def route_missing + if @app + forward + else + raise NotFound, "#{request.request_method} #{request.path_info}" + end + end + + # Attempt to serve static files from public directory. Throws :halt when + # a matching file is found, returns nil otherwise. + def static!(options = {}) + return if (public_dir = settings.public_folder).nil? + path = "#{public_dir}#{URI_INSTANCE.unescape(request.path_info)}" + return unless valid_path?(path) + + path = File.expand_path(path) + return unless path.start_with?(File.expand_path(public_dir) + '/') + return unless File.file?(path) + + env['sinatra.static_file'] = path + cache_control(*settings.static_cache_control) if settings.static_cache_control? + send_file path, options.merge(:disposition => nil) + end + + # Run the block with 'throw :halt' support and apply result to the response. + def invoke + res = catch(:halt) { yield } + + res = [res] if Integer === res or String === res + if Array === res and Integer === res.first + res = res.dup + status(res.shift) + body(res.pop) + headers(*res) + elsif res.respond_to? :each + body res + end + nil # avoid double setting the same response tuple twice + end + + # Dispatch a request with error handling. + def dispatch! + # Avoid passing frozen string in force_encoding + @params.merge!(@request.params).each do |key, val| + next unless val.respond_to?(:force_encoding) + val = val.dup if val.frozen? + @params[key] = force_encoding(val) + end + + invoke do + static! if settings.static? && (request.get? || request.head?) + filter! :before do + @pinned_response = !response['Content-Type'].nil? + end + route! + end + rescue ::Exception => boom + invoke { handle_exception!(boom) } + ensure + begin + filter! :after unless env['sinatra.static_file'] + rescue ::Exception => boom + invoke { handle_exception!(boom) } unless @env['sinatra.error'] + end + end + + # Error handling during requests. + def handle_exception!(boom) + if error_params = @env['sinatra.error.params'] + @params = @params.merge(error_params) + end + @env['sinatra.error'] = boom + + if boom.respond_to? :http_status and boom.http_status.between? 400, 599 + status(boom.http_status) + elsif settings.use_code? and boom.respond_to? :code and boom.code.between? 400, 599 + status(boom.code) + else + status(500) + end + + if server_error? + dump_errors! boom if settings.dump_errors? + raise boom if settings.show_exceptions? and settings.show_exceptions != :after_handler + elsif not_found? + headers['X-Cascade'] = 'pass' if settings.x_cascade? + end + + if res = error_block!(boom.class, boom) || error_block!(status, boom) + return res + end + + if not_found? || bad_request? + if boom.message && boom.message != boom.class.name + body Rack::Utils.escape_html(boom.message) + else + content_type 'text/html' + body '

' + (not_found? ? 'Not Found' : 'Bad Request') + '

' + end + end + + return unless server_error? + raise boom if settings.raise_errors? or settings.show_exceptions? + error_block! Exception, boom + end + + # Find an custom error block for the key(s) specified. + def error_block!(key, *block_params) + base = settings + while base.respond_to?(:errors) + next base = base.superclass unless args_array = base.errors[key] + args_array.reverse_each do |args| + first = args == args_array.first + args += [block_params] + resp = process_route(*args) + return resp unless resp.nil? && !first + end + end + return false unless key.respond_to? :superclass and key.superclass < Exception + error_block!(key.superclass, *block_params) + end + + def dump_errors!(boom) + msg = ["#{Time.now.strftime("%Y-%m-%d %H:%M:%S")} - #{boom.class} - #{boom.message}:", *boom.backtrace].join("\n\t") + @env['rack.errors'].puts(msg) + end + + class << self + CALLERS_TO_IGNORE = [ # :nodoc: + /\/sinatra(\/(base|main|show_exceptions))?\.rb$/, # all sinatra code + /lib\/tilt.*\.rb$/, # all tilt code + /^\(.*\)$/, # generated code + /rubygems\/(custom|core_ext\/kernel)_require\.rb$/, # rubygems require hacks + /active_support/, # active_support require hacks + /bundler(\/(?:runtime|inline))?\.rb/, # bundler require hacks + /= 1.9.2 + /src\/kernel\/bootstrap\/[A-Z]/ # maglev kernel files + ] + + # contrary to what the comment said previously, rubinius never supported this + if defined?(RUBY_IGNORE_CALLERS) + warn "RUBY_IGNORE_CALLERS is deprecated and will no longer be supported by Sinatra 2.0" + CALLERS_TO_IGNORE.concat(RUBY_IGNORE_CALLERS) + end + + attr_reader :routes, :filters, :templates, :errors + + # Removes all routes, filters, middleware and extension hooks from the + # current class (not routes/filters/... defined by its superclass). + def reset! + @conditions = [] + @routes = {} + @filters = {:before => [], :after => []} + @errors = {} + @middleware = [] + @prototype = nil + @extensions = [] + + if superclass.respond_to?(:templates) + @templates = Hash.new { |hash, key| superclass.templates[key] } + else + @templates = {} + end + end + + # Extension modules registered on this class and all superclasses. + def extensions + if superclass.respond_to?(:extensions) + (@extensions + superclass.extensions).uniq + else + @extensions + end + end + + # Middleware used in this class and all superclasses. + def middleware + if superclass.respond_to?(:middleware) + superclass.middleware + @middleware + else + @middleware + end + end + + # Sets an option to the given value. If the value is a proc, + # the proc will be called every time the option is accessed. + def set(option, value = (not_set = true), ignore_setter = false, &block) + raise ArgumentError if block and !not_set + value, not_set = block, false if block + + if not_set + raise ArgumentError unless option.respond_to?(:each) + option.each { |k,v| set(k, v) } + return self + end + + if respond_to?("#{option}=") and not ignore_setter + return __send__("#{option}=", value) + end + + setter = proc { |val| set option, val, true } + getter = proc { value } + + case value + when Proc + getter = value + when Symbol, Integer, FalseClass, TrueClass, NilClass + getter = value.inspect + when Hash + setter = proc do |val| + val = value.merge val if Hash === val + set option, val, true + end + end + + define_singleton("#{option}=", setter) + define_singleton(option, getter) + define_singleton("#{option}?", "!!#{option}") unless method_defined? "#{option}?" + self + end + + # Same as calling `set :option, true` for each of the given options. + def enable(*opts) + opts.each { |key| set(key, true) } + end + + # Same as calling `set :option, false` for each of the given options. + def disable(*opts) + opts.each { |key| set(key, false) } + end + + # Define a custom error handler. Optionally takes either an Exception + # class, or an HTTP status code to specify which errors should be + # handled. + def error(*codes, &block) + args = compile! "ERROR", /.*/, block + codes = codes.flat_map(&method(:Array)) + codes << Exception if codes.empty? + codes << Sinatra::NotFound if codes.include?(404) + codes.each { |c| (@errors[c] ||= []) << args } + end + + # Sugar for `error(404) { ... }` + def not_found(&block) + error(404, &block) + end + + # Define a named template. The block must return the template source. + def template(name, &block) + filename, line = caller_locations.first + templates[name] = [block, filename, line.to_i] + end + + # Define the layout template. The block must return the template source. + def layout(name = :layout, &block) + template name, &block + end + + # Load embedded templates from the file; uses the caller's __FILE__ + # when no file is specified. + def inline_templates=(file = nil) + file = (file.nil? || file == true) ? (caller_files.first || File.expand_path($0)) : file + + begin + io = ::IO.respond_to?(:binread) ? ::IO.binread(file) : ::IO.read(file) + app, data = io.gsub("\r\n", "\n").split(/^__END__$/, 2) + rescue Errno::ENOENT + app, data = nil + end + + if data + if app and app =~ /([^\n]*\n)?#[^\n]*coding: *(\S+)/m + encoding = $2 + else + encoding = settings.default_encoding + end + lines = app.count("\n") + 1 + template = nil + force_encoding data, encoding + data.each_line do |line| + lines += 1 + if line =~ /^@@\s*(.*\S)\s*$/ + template = force_encoding(String.new, encoding) + templates[$1.to_sym] = [template, file, lines] + elsif template + template << line + end + end + end + end + + # Lookup or register a mime type in Rack's mime registry. + def mime_type(type, value = nil) + return type if type.nil? + return type.to_s if type.to_s.include?('/') + type = ".#{type}" unless type.to_s[0] == ?. + return Rack::Mime.mime_type(type, nil) unless value + Rack::Mime::MIME_TYPES[type] = value + end + + # provides all mime types matching type, including deprecated types: + # mime_types :html # => ['text/html'] + # mime_types :js # => ['application/javascript', 'text/javascript'] + def mime_types(type) + type = mime_type type + type =~ /^application\/(xml|javascript)$/ ? [type, "text/#$1"] : [type] + end + + # Define a before filter; runs before all requests within the same + # context as route handlers and may access/modify the request and + # response. + def before(path = /.*/, **options, &block) + add_filter(:before, path, **options, &block) + end + + # Define an after filter; runs after all requests within the same + # context as route handlers and may access/modify the request and + # response. + def after(path = /.*/, **options, &block) + add_filter(:after, path, **options, &block) + end + + # add a filter + def add_filter(type, path = /.*/, **options, &block) + filters[type] << compile!(type, path, block, **options) + end + + # Add a route condition. The route is considered non-matching when the + # block returns false. + def condition(name = "#{caller.first[/`.*'/]} condition", &block) + @conditions << generate_method(name, &block) + end + + def public=(value) + warn ":public is no longer used to avoid overloading Module#public, use :public_folder or :public_dir instead" + set(:public_folder, value) + end + + def public_dir=(value) + self.public_folder = value + end + + def public_dir + public_folder + end + + # Defining a `GET` handler also automatically defines + # a `HEAD` handler. + def get(path, opts = {}, &block) + conditions = @conditions.dup + route('GET', path, opts, &block) + + @conditions = conditions + route('HEAD', path, opts, &block) + end + + def put(path, opts = {}, &bk) route 'PUT', path, opts, &bk end + def post(path, opts = {}, &bk) route 'POST', path, opts, &bk end + def delete(path, opts = {}, &bk) route 'DELETE', path, opts, &bk end + def head(path, opts = {}, &bk) route 'HEAD', path, opts, &bk end + def options(path, opts = {}, &bk) route 'OPTIONS', path, opts, &bk end + def patch(path, opts = {}, &bk) route 'PATCH', path, opts, &bk end + def link(path, opts = {}, &bk) route 'LINK', path, opts, &bk end + def unlink(path, opts = {}, &bk) route 'UNLINK', path, opts, &bk end + + # Makes the methods defined in the block and in the Modules given + # in `extensions` available to the handlers and templates + def helpers(*extensions, &block) + class_eval(&block) if block_given? + include(*extensions) if extensions.any? + end + + # Register an extension. Alternatively take a block from which an + # extension will be created and registered on the fly. + def register(*extensions, &block) + extensions << Module.new(&block) if block_given? + @extensions += extensions + extensions.each do |extension| + extend extension + extension.registered(self) if extension.respond_to?(:registered) + end + end + + def development?; environment == :development end + def production?; environment == :production end + def test?; environment == :test end + + # Set configuration options for Sinatra and/or the app. + # Allows scoping of settings for certain environments. + def configure(*envs) + yield self if envs.empty? || envs.include?(environment.to_sym) + end + + # Use the specified Rack middleware + def use(middleware, *args, &block) + @prototype = nil + @middleware << [middleware, args, block] + end + ruby2_keywords(:use) if respond_to?(:ruby2_keywords, true) + + # Stop the self-hosted server if running. + def quit! + return unless running? + # Use Thin's hard #stop! if available, otherwise just #stop. + running_server.respond_to?(:stop!) ? running_server.stop! : running_server.stop + $stderr.puts "== Sinatra has ended his set (crowd applauds)" unless suppress_messages? + set :running_server, nil + set :handler_name, nil + end + + alias_method :stop!, :quit! + + # Run the Sinatra app as a self-hosted server using + # Puma, Mongrel, or WEBrick (in that order). If given a block, will call + # with the constructed handler once we have taken the stage. + def run!(options = {}, &block) + return if running? + set options + handler = Rack::Handler.pick(server) + handler_name = handler.name.gsub(/.*::/, '') + server_settings = settings.respond_to?(:server_settings) ? settings.server_settings : {} + server_settings.merge!(:Port => port, :Host => bind) + + begin + start_server(handler, server_settings, handler_name, &block) + rescue Errno::EADDRINUSE + $stderr.puts "== Someone is already performing on port #{port}!" + raise + ensure + quit! + end + end + + alias_method :start!, :run! + + # Check whether the self-hosted server is running or not. + def running? + running_server? + end + + # The prototype instance used to process requests. + def prototype + @prototype ||= new + end + + # Create a new instance without middleware in front of it. + alias new! new unless method_defined? :new! + + # Create a new instance of the class fronted by its middleware + # pipeline. The object is guaranteed to respond to #call but may not be + # an instance of the class new was called on. + def new(*args, **kwargs, &bk) + instance = new!(*args, **kwargs, &bk) + Wrapper.new(build(instance).to_app, instance) + end + + # Creates a Rack::Builder instance with all the middleware set up and + # the given +app+ as end point. + def build(app) + builder = Rack::Builder.new + setup_default_middleware builder + setup_middleware builder + builder.run app + builder + end + + def call(env) + synchronize { prototype.call(env) } + end + + # Like Kernel#caller but excluding certain magic entries and without + # line / method information; the resulting array contains filenames only. + def caller_files + cleaned_caller(1).flatten + end + + # Like caller_files, but containing Arrays rather than strings with the + # first element being the file, and the second being the line. + def caller_locations + cleaned_caller 2 + end + + private + + # Starts the server by running the Rack Handler. + def start_server(handler, server_settings, handler_name) + # Ensure we initialize middleware before startup, to match standard Rack + # behavior, by ensuring an instance exists: + prototype + # Run the instance we created: + handler.run(self, **server_settings) do |server| + unless suppress_messages? + $stderr.puts "== Sinatra (v#{Sinatra::VERSION}) has taken the stage on #{port} for #{environment} with backup from #{handler_name}" + end + + setup_traps + set :running_server, server + set :handler_name, handler_name + server.threaded = settings.threaded if server.respond_to? :threaded= + + yield server if block_given? + end + end + + def suppress_messages? + handler_name =~ /cgi/i || quiet + end + + def setup_traps + if traps? + at_exit { quit! } + + [:INT, :TERM].each do |signal| + old_handler = trap(signal) do + quit! + old_handler.call if old_handler.respond_to?(:call) + end + end + + set :traps, false + end + end + + # Dynamically defines a method on settings. + def define_singleton(name, content = Proc.new) + singleton_class.class_eval do + undef_method(name) if method_defined? name + String === content ? class_eval("def #{name}() #{content}; end") : define_method(name, &content) + end + end + + # Condition for matching host name. Parameter might be String or Regexp. + def host_name(pattern) + condition { pattern === request.host } + end + + # Condition for matching user agent. Parameter should be Regexp. + # Will set params[:agent]. + def user_agent(pattern) + condition do + if request.user_agent.to_s =~ pattern + @params[:agent] = $~[1..-1] + true + else + false + end + end + end + alias_method :agent, :user_agent + + # Condition for matching mimetypes. Accepts file extensions. + def provides(*types) + types.map! { |t| mime_types(t) } + types.flatten! + condition do + if type = response['Content-Type'] + types.include? type or types.include? type[/^[^;]+/] + elsif type = request.preferred_type(types) + params = (type.respond_to?(:params) ? type.params : {}) + content_type(type, params) + true + else + false + end + end + end + + def route(verb, path, options = {}, &block) + enable :empty_path_info if path == "" and empty_path_info.nil? + signature = compile!(verb, path, block, **options) + (@routes[verb] ||= []) << signature + invoke_hook(:route_added, verb, path, block) + signature + end + + def invoke_hook(name, *args) + extensions.each { |e| e.send(name, *args) if e.respond_to?(name) } + end + + def generate_method(method_name, &block) + define_method(method_name, &block) + method = instance_method method_name + remove_method method_name + method + end + + def compile!(verb, path, block, **options) + # Because of self.options.host + host_name(options.delete(:host)) if options.key?(:host) + # Pass Mustermann opts to compile() + route_mustermann_opts = options.key?(:mustermann_opts) ? options.delete(:mustermann_opts) : {}.freeze + + options.each_pair { |option, args| send(option, *args) } + + pattern = compile(path, route_mustermann_opts) + method_name = "#{verb} #{path}" + unbound_method = generate_method(method_name, &block) + conditions, @conditions = @conditions, [] + wrapper = block.arity != 0 ? + proc { |a, p| unbound_method.bind(a).call(*p) } : + proc { |a, p| unbound_method.bind(a).call } + + [ pattern, conditions, wrapper ] + end + + def compile(path, route_mustermann_opts = {}) + Mustermann.new(path, **mustermann_opts.merge(route_mustermann_opts)) + end + + def setup_default_middleware(builder) + builder.use ExtendedRack + builder.use ShowExceptions if show_exceptions? + builder.use Rack::MethodOverride if method_override? + builder.use Rack::Head + setup_logging builder + setup_sessions builder + setup_protection builder + end + + def setup_middleware(builder) + middleware.each { |c,a,b| builder.use(c, *a, &b) } + end + + def setup_logging(builder) + if logging? + setup_common_logger(builder) + setup_custom_logger(builder) + elsif logging == false + setup_null_logger(builder) + end + end + + def setup_null_logger(builder) + builder.use Rack::NullLogger + end + + def setup_common_logger(builder) + builder.use Sinatra::CommonLogger + end + + def setup_custom_logger(builder) + if logging.respond_to? :to_int + builder.use Rack::Logger, logging + else + builder.use Rack::Logger + end + end + + def setup_protection(builder) + return unless protection? + options = Hash === protection ? protection.dup : {} + options = { + img_src: "'self' data:", + font_src: "'self'" + }.merge options + + protect_session = options.fetch(:session) { sessions? } + options[:without_session] = !protect_session + + options[:reaction] ||= :drop_session + + builder.use Rack::Protection, options + end + + def setup_sessions(builder) + return unless sessions? + options = {} + options[:secret] = session_secret if session_secret? + options.merge! sessions.to_hash if sessions.respond_to? :to_hash + builder.use session_store, options + end + + def inherited(subclass) + subclass.reset! + subclass.set :app_file, caller_files.first unless subclass.app_file? + super + end + + @@mutex = Mutex.new + def synchronize(&block) + if lock? + @@mutex.synchronize(&block) + else + yield + end + end + + # used for deprecation warnings + def warn(message) + super message + "\n\tfrom #{cleaned_caller.first.join(':')}" + end + + # Like Kernel#caller but excluding certain magic entries + def cleaned_caller(keep = 3) + caller(1). + map! { |line| line.split(/:(?=\d|in )/, 3)[0,keep] }. + reject { |file, *_| CALLERS_TO_IGNORE.any? { |pattern| file =~ pattern } } + end + end + + # Force data to specified encoding. It defaults to settings.default_encoding + # which is UTF-8 by default + def self.force_encoding(data, encoding = default_encoding) + return if data == settings || data.is_a?(Tempfile) + if data.respond_to? :force_encoding + data.force_encoding(encoding).encode! + elsif data.respond_to? :each_value + data.each_value { |v| force_encoding(v, encoding) } + elsif data.respond_to? :each + data.each { |v| force_encoding(v, encoding) } + end + data + end + + def force_encoding(*args) settings.force_encoding(*args) end + + reset! + + set :environment, (ENV['APP_ENV'] || ENV['RACK_ENV'] || :development).to_sym + set :raise_errors, Proc.new { test? } + set :dump_errors, Proc.new { !test? } + set :show_exceptions, Proc.new { development? } + set :sessions, false + set :session_store, Rack::Session::Cookie + set :logging, false + set :protection, true + set :method_override, false + set :use_code, false + set :default_encoding, "utf-8" + set :x_cascade, true + set :add_charset, %w[javascript xml xhtml+xml].map { |t| "application/#{t}" } + settings.add_charset << /^text\// + set :mustermann_opts, {} + set :default_content_type, 'text/html' + + # explicitly generating a session secret eagerly to play nice with preforking + begin + require 'securerandom' + set :session_secret, SecureRandom.hex(64) + rescue LoadError, NotImplementedError + # SecureRandom raises a NotImplementedError if no random device is available + set :session_secret, "%064x" % Kernel.rand(2**256-1) + end + + class << self + alias_method :methodoverride?, :method_override? + alias_method :methodoverride=, :method_override= + end + + set :run, false # start server via at-exit hook? + set :running_server, nil + set :handler_name, nil + set :traps, true + set :server, %w[HTTP webrick] + set :bind, Proc.new { development? ? 'localhost' : '0.0.0.0' } + set :port, Integer(ENV['PORT'] && !ENV['PORT'].empty? ? ENV['PORT'] : 4567) + set :quiet, false + + ruby_engine = defined?(RUBY_ENGINE) && RUBY_ENGINE + + if ruby_engine == 'macruby' + server.unshift 'control_tower' + else + server.unshift 'reel' + server.unshift 'puma' + server.unshift 'mongrel' if ruby_engine.nil? + server.unshift 'thin' if ruby_engine != 'jruby' + server.unshift 'trinidad' if ruby_engine == 'jruby' + end + + set :absolute_redirects, true + set :prefixed_redirects, false + set :empty_path_info, nil + set :strict_paths, true + + set :app_file, nil + set :root, Proc.new { app_file && File.expand_path(File.dirname(app_file)) } + set :views, Proc.new { root && File.join(root, 'views') } + set :reload_templates, Proc.new { development? } + set :lock, false + set :threaded, true + + set :public_folder, Proc.new { root && File.join(root, 'public') } + set :static, Proc.new { public_folder && File.exist?(public_folder) } + set :static_cache_control, false + + error ::Exception do + response.status = 500 + content_type 'text/html' + '

Internal Server Error

' + end + + configure :development do + get '/__sinatra__/:image.png' do + filename = __dir__ + "/images/#{params[:image].to_i}.png" + content_type :png + send_file filename + end + + error NotFound do + content_type 'text/html' + + if self.class == Sinatra::Application + code = <<-RUBY.gsub(/^ {12}/, '') + #{request.request_method.downcase} '#{request.path_info}' do + "Hello World" + end + RUBY + else + code = <<-RUBY.gsub(/^ {12}/, '') + class #{self.class} + #{request.request_method.downcase} '#{request.path_info}' do + "Hello World" + end + end + RUBY + + file = settings.app_file.to_s.sub(settings.root.to_s, '').sub(/^\//, '') + code = "# in #{file}\n#{code}" unless file.empty? + end + + (<<-HTML).gsub(/^ {10}/, '') + + + + + + +

Sinatra doesn’t know this ditty.

+ +
+ Try this: +
#{Rack::Utils.escape_html(code)}
+
+ + + HTML + end + end + end + + # Execution context for classic style (top-level) applications. All + # DSL methods executed on main are delegated to this class. + # + # The Application class should not be subclassed, unless you want to + # inherit all settings, routes, handlers, and error pages from the + # top-level. Subclassing Sinatra::Base is highly recommended for + # modular applications. + class Application < Base + set :logging, Proc.new { !test? } + set :method_override, true + set :run, Proc.new { !test? } + set :app_file, nil + + def self.register(*extensions, &block) #:nodoc: + added_methods = extensions.flat_map(&:public_instance_methods) + Delegator.delegate(*added_methods) + super(*extensions, &block) + end + end + + # Sinatra delegation mixin. Mixing this module into an object causes all + # methods to be delegated to the Sinatra::Application class. Used primarily + # at the top-level. + module Delegator #:nodoc: + def self.delegate(*methods) + methods.each do |method_name| + define_method(method_name) do |*args, &block| + return super(*args, &block) if respond_to? method_name + Delegator.target.send(method_name, *args, &block) + end + # ensure keyword argument passing is compatible with ruby >= 2.7 + ruby2_keywords(method_name) if respond_to?(:ruby2_keywords, true) + private method_name + end + end + + delegate :get, :patch, :put, :post, :delete, :head, :options, :link, :unlink, + :template, :layout, :before, :after, :error, :not_found, :configure, + :set, :mime_type, :enable, :disable, :use, :development?, :test?, + :production?, :helpers, :settings, :register + + class << self + attr_accessor :target + end + + self.target = Application + end + + class Wrapper + def initialize(stack, instance) + @stack, @instance = stack, instance + end + + def settings + @instance.settings + end + + def helpers + @instance + end + + def call(env) + @stack.call(env) + end + + def inspect + "#<#{@instance.class} app_file=#{settings.app_file.inspect}>" + end + end + + # Create a new Sinatra application; the block is evaluated in the class scope. + def self.new(base = Base, &block) + base = Class.new(base) + base.class_eval(&block) if block_given? + base + end + + # Extend the top-level DSL with the modules provided. + def self.register(*extensions, &block) + Delegator.target.register(*extensions, &block) + end + + # Include the helper modules provided in Sinatra's request context. + def self.helpers(*extensions, &block) + Delegator.target.helpers(*extensions, &block) + end + + # Use the middleware for classic applications. + def self.use(*args, &block) + Delegator.target.use(*args, &block) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/images/404.png b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/images/404.png new file mode 100644 index 0000000..f16a914 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/images/404.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/images/500.png b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/images/500.png new file mode 100644 index 0000000..e08b17d Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/images/500.png differ diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/indifferent_hash.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/indifferent_hash.rb new file mode 100644 index 0000000..89b348f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/indifferent_hash.rb @@ -0,0 +1,214 @@ +# frozen_string_literal: true +$stderr.puts <:foo
and "foo" are + # considered to be the same. + # + # rgb = Sinatra::IndifferentHash.new + # + # rgb[:black] = '#000000' # symbol assignment + # rgb[:black] # => '#000000' # symbol retrieval + # rgb['black'] # => '#000000' # string retrieval + # + # rgb['white'] = '#FFFFFF' # string assignment + # rgb[:white] # => '#FFFFFF' # symbol retrieval + # rgb['white'] # => '#FFFFFF' # string retrieval + # + # Internally, symbols are mapped to strings when used as keys in the entire + # writing interface (calling e.g. []=, merge). This mapping + # belongs to the public interface. For example, given: + # + # hash = Sinatra::IndifferentHash.new(:a=>1) + # + # You are guaranteed that the key is returned as a string: + # + # hash.keys # => ["a"] + # + # Technically other types of keys are accepted: + # + # hash = Sinatra::IndifferentHash.new(:a=>1) + # hash[0] = 0 + # hash # => { "a"=>1, 0=>0 } + # + # But this class is intended for use cases where strings or symbols are the + # expected keys and it is convenient to understand both as the same. For + # example the +params+ hash in Sinatra. + class IndifferentHash < Hash + def self.[](*args) + new.merge!(Hash[*args]) + end + + def initialize(*args) + args.map!(&method(:convert_value)) + + super(*args) + end + + def default(*args) + args.map!(&method(:convert_key)) + + super(*args) + end + + def default=(value) + super(convert_value(value)) + end + + def assoc(key) + super(convert_key(key)) + end + + def rassoc(value) + super(convert_value(value)) + end + + def fetch(key, *args) + args.map!(&method(:convert_value)) + + super(convert_key(key), *args) + end + + def [](key) + super(convert_key(key)) + end + + def []=(key, value) + super(convert_key(key), convert_value(value)) + end + + alias_method :store, :[]= + + def key(value) + super(convert_value(value)) + end + + def key?(key) + super(convert_key(key)) + end + + alias_method :has_key?, :key? + alias_method :include?, :key? + alias_method :member?, :key? + + def value?(value) + super(convert_value(value)) + end + + alias_method :has_value?, :value? + + def delete(key) + super(convert_key(key)) + end + + def dig(key, *other_keys) + super(convert_key(key), *other_keys) + end if method_defined?(:dig) # Added in Ruby 2.3 + + def fetch_values(*keys) + keys.map!(&method(:convert_key)) + + super(*keys) + end if method_defined?(:fetch_values) # Added in Ruby 2.3 + + def slice(*keys) + keys.map!(&method(:convert_key)) + + self.class[super(*keys)] + end if method_defined?(:slice) # Added in Ruby 2.5 + + def values_at(*keys) + keys.map!(&method(:convert_key)) + + super(*keys) + end + + def merge!(*other_hashes) + other_hashes.each do |other_hash| + if other_hash.is_a?(self.class) + super(other_hash) + else + other_hash.each_pair do |key, value| + key = convert_key(key) + value = yield(key, self[key], value) if block_given? && key?(key) + self[key] = convert_value(value) + end + end + end + + self + end + + alias_method :update, :merge! + + def merge(*other_hashes, &block) + dup.merge!(*other_hashes, &block) + end + + def replace(other_hash) + super(other_hash.is_a?(self.class) ? other_hash : self.class[other_hash]) + end + + if method_defined?(:transform_values!) # Added in Ruby 2.4 + def transform_values(&block) + dup.transform_values!(&block) + end + + def transform_values! + super + super(&method(:convert_value)) + end + end + + if method_defined?(:transform_keys!) # Added in Ruby 2.5 + def transform_keys(&block) + dup.transform_keys!(&block) + end + + def transform_keys! + super + super(&method(:convert_key)) + end + end + + def select(*args, &block) + return to_enum(:select) unless block_given? + dup.tap { |hash| hash.select!(*args, &block) } + end + + def reject(*args, &block) + return to_enum(:reject) unless block_given? + dup.tap { |hash| hash.reject!(*args, &block) } + end + + def compact + dup.tap(&:compact!) + end if method_defined?(:compact) # Added in Ruby 2.4 + + private + + def convert_key(key) + key.is_a?(Symbol) ? key.to_s : key + end + + def convert_value(value) + case value + when Hash + value.is_a?(self.class) ? value : self.class[value] + when Array + value.map(&method(:convert_value)) + else + value + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/main.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/main.rb new file mode 100644 index 0000000..e4231c3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/main.rb @@ -0,0 +1,54 @@ +module Sinatra + ParamsConfig = {} + + if ARGV.any? + require 'optparse' + parser = OptionParser.new { |op| + op.on('-p port', 'set the port (default is 4567)') { |val| ParamsConfig[:port] = Integer(val) } + op.on('-s server', 'specify rack server/handler') { |val| ParamsConfig[:server] = val } + op.on('-q', 'turn on quiet mode (default is off)') { ParamsConfig[:quiet] = true } + op.on('-x', 'turn on the mutex lock (default is off)') { ParamsConfig[:lock] = true } + op.on('-e env', 'set the environment (default is development)') do |val| + ENV['RACK_ENV'] = val + ParamsConfig[:environment] = val.to_sym + end + op.on('-o addr', "set the host (default is (env == 'development' ? 'localhost' : '0.0.0.0'))") do |val| + ParamsConfig[:bind] = val + end + } + begin + parser.parse!(ARGV.dup) + rescue => evar + ParamsConfig[:optparse_error] = evar + end + end + + require 'sinatra/base' + + class Application < Base + + # we assume that the first file that requires 'sinatra' is the + # app_file. all other path related options are calculated based + # on this path by default. + set :app_file, caller_files.first || $0 + + set :run, Proc.new { File.expand_path($0) == File.expand_path(app_file) } + + if run? && ARGV.any? + error = ParamsConfig.delete(:optparse_error) + raise error if error + ParamsConfig.each { |k, v| set k, v } + end + end + + remove_const(:ParamsConfig) + at_exit { Application.run! if $!.nil? && Application.run? } +end + +# include would include the module in Object +# extend only extends the `main` object +extend Sinatra::Delegator + +class Rack::Builder + include Sinatra::Delegator +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/show_exceptions.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/show_exceptions.rb new file mode 100644 index 0000000..de468c0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/show_exceptions.rb @@ -0,0 +1,362 @@ +# frozen_string_literal: true + +require 'rack/show_exceptions' + +module Sinatra + # Sinatra::ShowExceptions catches all exceptions raised from the app it + # wraps. It shows a useful backtrace with the sourcefile and clickable + # context, the whole Rack environment and the request data. + # + # Be careful when you use this on public-facing sites as it could reveal + # information helpful to attackers. + class ShowExceptions < Rack::ShowExceptions + @@eats_errors = Object.new + def @@eats_errors.flush(*) end + def @@eats_errors.puts(*) end + + def initialize(app) + @app = app + end + + def call(env) + @app.call(env) + rescue Exception => e + errors, env["rack.errors"] = env["rack.errors"], @@eats_errors + + if prefers_plain_text?(env) + content_type = "text/plain" + body = dump_exception(e) + else + content_type = "text/html" + body = pretty(env, e) + end + + env["rack.errors"] = errors + + [ + 500, + { + "Content-Type" => content_type, + "Content-Length" => body.bytesize.to_s + }, + [body] + ] + end + + def template + TEMPLATE + end + + private + + def bad_request?(e) + Sinatra::BadRequest === e + end + + def prefers_plain_text?(env) + !(Request.new(env).preferred_type("text/plain","text/html") == "text/html") && + [/curl/].index { |item| item =~ env["HTTP_USER_AGENT"] } + end + + def frame_class(frame) + if frame.filename =~ %r{lib/sinatra.*\.rb} + "framework" + elsif (defined?(Gem) && frame.filename.include?(Gem.dir)) || + frame.filename =~ %r{/bin/(\w+)\z} + "system" + else + "app" + end + end + +TEMPLATE = ERB.new <<-HTML # :nodoc: + + + + + <%=h exception.class %> at <%=h path %> + + + + + + +
+ + +
+

BACKTRACE

+

(expand)

+ +
+ +
    + + <% id = 1 %> + <% frames.each do |frame| %> + <% if frame.context_line && frame.context_line != "#" %> + +
  • + <%=h frame.filename %> in + <%=h frame.function %> +
  • + +
  • + <% if frame.pre_context %> +
      + <% frame.pre_context.each do |line| %> +
    1. <%=h line %>
    2. + <% end %> +
    + <% end %> + +
      +
    1. <%= + h frame.context_line %>
    2. +
    + + <% if frame.post_context %> +
      + <% frame.post_context.each do |line| %> +
    1. <%=h line %>
    2. + <% end %> +
    + <% end %> +
    +
  • + + <% end %> + + <% id += 1 %> + <% end %> + +
+
+ + <% unless bad_request?(exception) %> +
+

GET

+ <% if req.GET and not req.GET.empty? %> + + + + + + <% req.GET.sort_by { |k, v| k.to_s }.each { |key, val| %> + + + + + <% } %> +
VariableValue
<%=h key %>
<%=h val.inspect %>
+ <% else %> +

No GET data.

+ <% end %> +
+
+ +
+

POST

+ <% if req.POST and not req.POST.empty? %> + + + + + + <% req.POST.sort_by { |k, v| k.to_s }.each { |key, val| %> + + + + + <% } %> +
VariableValue
<%=h key %>
<%=h val.inspect %>
+ <% else %> +

No POST data.

+ <% end %> +
+
+ <% end %> + +
+ + <% unless req.cookies.empty? %> + + + + + + <% req.cookies.each { |key, val| %> + + + + + <% } %> +
VariableValue
<%=h key %>
<%=h val.inspect %>
+ <% else %> +

No cookie data.

+ <% end %> +
+
+ +
+

Rack ENV

+ + + + + + <% env.sort_by { |k, v| k.to_s }.each { |key, val| %> + + + + + <% } %> +
VariableValue
<%=h key %>
<%=h val %>
+
+
+ +

You're seeing this error because you have +enabled the show_exceptions setting.

+
+ + +HTML + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/version.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/version.rb new file mode 100644 index 0000000..3c8b2f7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/lib/sinatra/version.rb @@ -0,0 +1,3 @@ +module Sinatra + VERSION = '2.2.0' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/sinatra.gemspec b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/sinatra.gemspec new file mode 100644 index 0000000..46c23f7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-2.2.0/sinatra.gemspec @@ -0,0 +1,49 @@ +version = File.read(File.expand_path("../VERSION", __FILE__)).strip + +Gem::Specification.new 'sinatra', version do |s| + s.description = "Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort." + s.summary = "Classy web-development dressed in a DSL" + s.authors = ["Blake Mizerany", "Ryan Tomayko", "Simon Rozet", "Konstantin Haase"] + s.email = "sinatrarb@googlegroups.com" + s.homepage = "http://sinatrarb.com/" + s.license = 'MIT' + s.files = Dir['README*.md', 'lib/**/*', 'examples/*'] + [ + ".yardopts", + "AUTHORS.md", + "CHANGELOG.md", + "CONTRIBUTING.md", + "Gemfile", + "LICENSE", + "MAINTENANCE.md", + "Rakefile", + "SECURITY.md", + "sinatra.gemspec", + "VERSION"] + s.extra_rdoc_files = %w[README.md LICENSE] + s.rdoc_options = %w[--line-numbers --title Sinatra --main README.rdoc --encoding=UTF-8] + + if s.respond_to?(:metadata) + s.metadata = { + 'source_code_uri' => 'https://github.com/sinatra/sinatra', + 'changelog_uri' => 'https://github.com/sinatra/sinatra/blob/master/CHANGELOG.md', + 'homepage_uri' => 'http://sinatrarb.com/', + 'bug_tracker_uri' => 'https://github.com/sinatra/sinatra/issues', + 'mailing_list_uri' => 'http://groups.google.com/group/sinatrarb', + 'documentation_uri' => 'https://www.rubydoc.info/gems/sinatra' + } + else + raise <<-EOF +RubyGems 2.0 or newer is required to protect against public gem pushes. You can update your rubygems version by running: + gem install rubygems-update + update_rubygems: + gem update --system +EOF + end + + s.required_ruby_version = '>= 2.3.0' + + s.add_dependency 'rack', '~> 2.2' + s.add_dependency 'tilt', '~> 2.0' + s.add_dependency 'rack-protection', version + s.add_dependency 'mustermann', '~> 1.0' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/LICENSE b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/LICENSE new file mode 100644 index 0000000..9522a75 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) 2008-2017 Nicolas Sanguinetti, entp.com, Konstantin Haase +Copyright (c) 2015-2017 Zachary Scott + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/README.md b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/README.md new file mode 100644 index 0000000..b1c9a2a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/README.md @@ -0,0 +1,178 @@ +# Sinatra::Contrib + +Collection of common Sinatra extensions, semi-officially supported. + +## Goals + +* For every future Sinatra release, have at least one fully compatible release +* High code quality, high test coverage +* Include plugins people usually ask for a lot + +## Included extensions + +### Common Extensions + +These are common extension which will not add significant overhead or change any +behavior of already existing APIs. They do not add any dependencies not already +installed with this gem. + +Currently included: + +* [`sinatra/capture`][sinatra-capture]: Let's you capture the content of blocks in templates. + +* [`sinatra/config_file`][sinatra-config-file]: Allows loading configuration from yaml files. + +* [`sinatra/content_for`][sinatra-content-for]: Adds Rails-style `content_for` helpers to Haml, Erb, Erubi, + Erubis and Slim. + +* [`sinatra/cookies`][sinatra-cookies]: A `cookies` helper for reading and writing cookies. + +* [`sinatra/engine_tracking`][sinatra-engine-tracking]: Adds methods like `haml?` that allow helper + methods to check whether they are called from within a template. + +* [`sinatra/json`][sinatra-json]: Adds a `#json` helper method to return JSON documents. + +* [`sinatra/link_header`][sinatra-link-header]: Helpers for generating `link` HTML tags and + corresponding `Link` HTTP headers. Adds `link`, `stylesheet` and `prefetch` + helper methods. + +* [`sinatra/multi_route`][sinatra-multi-route]: Adds ability to define one route block for multiple + routes and multiple or custom HTTP verbs. + +* [`sinatra/namespace`][sinatra-namespace]: Adds namespace support to Sinatra. + +* [`sinatra/respond_with`][sinatra-respond-with]: Choose action and/or template automatically + depending on the incoming request. Adds helpers `respond_to` and + `respond_with`. + +* [`sinatra/custom_logger`][sinatra-custom-logger]: This extension allows you to define your own + logger instance using +logger+ setting. That logger then will + be available as #logger helper method in your routes and views. + +* [`sinatra/required_params`][sinatra-required-params]: Ensure if required query parameters exist + +### Custom Extensions + +These extensions may add additional dependencies and enhance the behavior of the +existing APIs. + +Currently included: + +* [`sinatra/reloader`][sinatra-reloader]: Automatically reloads Ruby files on code changes. + +### Other Tools + +* [`sinatra/extension`][sinatra-extension]: Mixin for writing your own Sinatra extensions. + +* [`sinatra/test_helpers`][sinatra-test-helpers]: Helper methods to ease testing your Sinatra + application. Partly extracted from Sinatra. Testing framework agnostic + +* `sinatra/quiet_logger`: Extension to exclude specific pathes from access log. + It works by patching Rack::CommonLogger + +## Installation + +Add `gem 'sinatra-contrib'` to *Gemfile*, then execute `bundle install`. + +If you don't use Bundler, install the gem manually by executing `gem install sinatra-contrib` in your command line. + +### Git + +If you want to use the gem from git, for whatever reason, you can do the following: + +```ruby +github 'sinatra/sinatra' do + gem 'sinatra-contrib' +end +``` + +Within this block you can also specify other gems from this git repository. + +## Usage + +### Classic Style + +A single extension (example: sinatra-content-for): + +``` ruby +require 'sinatra' +require 'sinatra/content_for' +``` + +Common extensions: + +``` ruby +require 'sinatra' +require 'sinatra/contrib' +``` + +All extensions: + +``` ruby +require 'sinatra' +require 'sinatra/contrib/all' +``` + +### Modular Style + +A single extension (example: sinatra-content-for): + +``` ruby +require 'sinatra/base' +require 'sinatra/content_for' +require 'sinatra/namespace' + +class MyApp < Sinatra::Base + # Note: Some modules are extensions, some helpers, see the specific + # documentation or the source + helpers Sinatra::ContentFor + register Sinatra::Namespace +end +``` + +Common extensions: + +``` ruby +require 'sinatra/base' +require 'sinatra/contrib' + +class MyApp < Sinatra::Base + register Sinatra::Contrib +end +``` + +All extensions: + +``` ruby +require 'sinatra/base' +require 'sinatra/contrib/all' + +class MyApp < Sinatra::Base + register Sinatra::Contrib +end +``` + +### Documentation + +For more info check the [official docs](http://www.sinatrarb.com/contrib/) and +[api docs](http://www.rubydoc.info/gems/sinatra-contrib). + +[sinatra-reloader]: http://www.sinatrarb.com/contrib/reloader +[sinatra-namespace]: http://www.sinatrarb.com/contrib/namespace +[sinatra-content-for]: http://www.sinatrarb.com/contrib/content_for +[sinatra-cookies]: http://www.sinatrarb.com/contrib/cookies +[sinatra-streaming]: http://www.sinatrarb.com/contrib/streaming +[sinatra-webdav]: http://www.sinatrarb.com/contrib/webdav +[sinatra-runner]: http://www.sinatrarb.com/contrib/runner +[sinatra-extension]: http://www.sinatrarb.com/contrib/extension +[sinatra-test-helpers]: https://github.com/sinatra/sinatra/blob/master/sinatra-contrib/lib/sinatra/test_helpers.rb +[sinatra-required-params]: http://www.sinatrarb.com/contrib/required_params +[sinatra-custom-logger]: http://www.sinatrarb.com/contrib/custom_logger +[sinatra-multi-route]: http://www.sinatrarb.com/contrib/multi_route +[sinatra-json]: http://www.sinatrarb.com/contrib/json +[sinatra-respond-with]: http://www.sinatrarb.com/contrib/respond_with +[sinatra-config-file]: http://www.sinatrarb.com/contrib/config_file +[sinatra-link-header]: http://www.sinatrarb.com/contrib/link_header +[sinatra-capture]: http://www.sinatrarb.com/contrib/capture +[sinatra-engine-tracking]: https://github.com/sinatra/sinatra/blob/master/sinatra-contrib/lib/sinatra/engine_tracking.rb + diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/Rakefile b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/Rakefile new file mode 100644 index 0000000..1ec39dd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/Rakefile @@ -0,0 +1,73 @@ +$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) +require 'open-uri' +require 'yaml' +require 'sinatra/contrib/version' + +desc "run specs" +task(:spec) { ruby '-S rspec spec -cw' } +task(:test => :spec) +task(:default => :spec) + +namespace :doc do + task :readmes do + Dir.glob 'lib/sinatra/*.rb' do |file| + puts "Trying file... #{file}" + excluded_files = %w[lib/sinatra/contrib.rb lib/sinatra/decompile.rb] + next if excluded_files.include?(file) + doc = File.read(file)[/^module Sinatra(\n)+( #[^\n]*\n)*/m].scan(/^ *#(?!#) ?(.*)\n/).join("\n") + file = "doc/#{file[4..-4].tr("/_", "-")}.rdoc" + Dir.mkdir "doc" unless File.directory? "doc" + puts "writing #{file}" + File.open(file, "w") { |f| f << doc } + end + end + + task :index do + doc = File.read("README.md") + file = "doc/sinatra-contrib-readme.md" + Dir.mkdir "doc" unless File.directory? "doc" + puts "writing #{file}" + File.open(file, "w") { |f| f << doc } + end + + task :all => [:readmes, :index] +end + +desc "generate documentation" +task :doc => 'doc:all' + +desc "generate gemspec" +task 'sinatra-contrib.gemspec' do + content = File.read 'sinatra-contrib.gemspec' + + fields = { + :authors => `git shortlog -sn`.scan(/[^\d\s].*/), + :email => `git shortlog -sne`.scan(/[^<]+@[^>]+/), + :files => `git ls-files`.split("\n").reject { |f| f =~ /^(\.|Gemfile)/ } + } + + fields.each do |field, values| + updated = " s.#{field} = [" + updated << values.map { |v| "\n %p" % v }.join(',') + updated << "\n ]" + content.sub!(/ s\.#{field} = \[\n( .*\n)* \]/, updated) + end + + File.open('sinatra-contrib.gemspec', 'w') { |f| f << content } +end + +task :gemspec => 'sinatra-contrib.gemspec' + +task :release => :gemspec do + sh <<-SH + rm -Rf sinatra-contrib*.gem && + gem build sinatra-contrib.gemspec && + gem install sinatra-contrib*.gem --local && + gem push sinatra-contrib*.gem && + git commit --allow-empty -a -m '#{Sinatra::Contrib::VERSION} release' && + git tag -s v#{Sinatra::Contrib::VERSION} -m '#{Sinatra::Contrib::VERSION} release' && + git push && (git push origin master || true) && + git push --tags && (git push origin --tags || true) + SH +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/ideas.md b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/ideas.md new file mode 100644 index 0000000..8460115 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/ideas.md @@ -0,0 +1,29 @@ +* Extension that does something like this: + + def build(*) + if settings.memcached? + use Rack::Cache, :backend => :memcached + use Rack::Session::Memcached + # ... + end + super + end + +* `sinatra-smart-cache`: update cache header only if arguments are more + restrictive than curent value, set caching headers that way for most helper + methods (i.e. `sass` or `send_file`) + +* Some verbose logging extension: Log what filters, routes, error handlers, + templates, and so on is used. + +* Form helpers, with forms as first class objects that accepts hashes or + something, so the form meta data can also be used to expose a JSON API or + similar, possibly defining routes (like "Sinatra's Hat"), strictly using + the ActiveModel API. + +* Extend `sinatra-content-for` to support Liquid, Radius, Markaby, Nokogiri and + Builder. At least the first two probably involve patching Tilt. + +* Rewrite of `sinatra-compass`? + +* Helpers for HTML escaping and such. \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/capture.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/capture.rb new file mode 100644 index 0000000..3a74688 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/capture.rb @@ -0,0 +1,111 @@ +require 'sinatra/base' +require 'sinatra/engine_tracking' + +module Sinatra + # + # = Sinatra::Capture + # + # Extension that enables blocks inside other extensions. + # It currently works for erb, slim and haml. + # Enables mixing of different template languages. + # + # Example: + # + # # in hello_world.erb + # + # Say + # <% a = capture do %>World<% end %> + # Hello <%= a %>! + # + # # in hello_world.slim + # + # | Say + # - a = capture do + # | World + # | Hello #{a}! + # + # # in hello_world.haml + # + # Say + # - a = capture do + # World + # Hello #{a.strip}! + # + # + # You can also use nested blocks. + # + # Example + # + # # in hello_world.erb + # + # Say + # <% a = capture do %> + # <% b = capture do %>World<% end %> + # <%= b %>! + # <% end %> + # Hello <%= a.strip %> + # + # + # The main advantage of capture is mixing of different template engines. + # + # Example + # + # # in mix_me_up.slim + # + # - two = capture do + # - erb "<%= 1 + 1 %>" + # | 1 + 1 = #{two} + # + # == Usage + # + # === Classic Application + # + # In a classic application simply require the helpers, and start using them: + # + # require "sinatra" + # require "sinatra/capture" + # + # # The rest of your classic application code goes here... + # + # === Modular Application + # + # In a modular application you need to require the helpers, and then tell + # the application you will use them: + # + # require "sinatra/base" + # require "sinatra/capture" + # + # class MyApp < Sinatra::Base + # helpers Sinatra::Capture + # + # # The rest of your modular application code goes here... + # end + # + module Capture + include Sinatra::EngineTracking + + def capture(*args, &block) + return block[*args] if ruby? + if haml? && Tilt[:haml] == Tilt::HamlTemplate + buffer = Haml::Buffer.new(nil, Haml::Options.new.for_buffer) + with_haml_buffer(buffer) { capture_haml(*args, &block) } + else + @_out_buf, _buf_was = '', @_out_buf + begin + raw = block[*args] + captured = block.binding.eval('@_out_buf') + captured.empty? ? raw : captured + ensure + @_out_buf = _buf_was + end + end + end + + def capture_later(&block) + engine = current_engine + proc { |*a| with_engine(engine) { @capture = capture(*a, &block) } } + end + end + + helpers Capture +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/config_file.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/config_file.rb new file mode 100644 index 0000000..701e99a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/config_file.rb @@ -0,0 +1,173 @@ +require 'sinatra/base' +require 'yaml' +require 'erb' + +module Sinatra + + # = Sinatra::ConfigFile + # + # Sinatra::ConfigFile is an extension that allows you to load the + # application's configuration from YAML files. It automatically detects if + # the files contain specific environment settings and it will use those + # corresponding to the current one. + # + # You can access those options through +settings+ within the application. If + # you try to get the value for a setting that hasn't been defined in the + # config file for the current environment, you will get whatever it was set + # to in the application. + # + # == Usage + # + # Once you have written your configurations to a YAML file you can tell the + # extension to load them. See below for more information about how these + # files are interpreted. + # + # For the examples, lets assume the following config.yml file: + # + # greeting: Welcome to my file configurable application + # + # === Classic Application + # + # require "sinatra" + # require "sinatra/config_file" + # + # config_file 'path/to/config.yml' + # + # get '/' do + # @greeting = settings.greeting + # haml :index + # end + # + # # The rest of your classic application code goes here... + # + # === Modular Application + # + # require "sinatra/base" + # require "sinatra/config_file" + # + # class MyApp < Sinatra::Base + # register Sinatra::ConfigFile + # + # config_file 'path/to/config.yml' + # + # get '/' do + # @greeting = settings.greeting + # haml :index + # end + # + # # The rest of your modular application code goes here... + # end + # + # === Config File Format + # + # In its most simple form this file is just a key-value list: + # + # foo: bar + # something: 42 + # nested: + # a: 1 + # b: 2 + # + # But it also can provide specific environment configuration. There are two + # ways to do that: at the file level and at the settings level. + # + # At the settings level (e.g. in 'path/to/config.yml'): + # + # development: + # foo: development + # bar: bar + # test: + # foo: test + # bar: bar + # production: + # foo: production + # bar: bar + # + # Or at the file level: + # + # foo: + # development: development + # test: test + # production: production + # bar: bar + # + # In either case, settings.foo will return the environment name, and + # settings.bar will return "bar". + # + # If you wish to provide defaults that may be shared among all the + # environments, this can be done by using a YAML alias, and then overwriting + # values in environments where appropriate: + # + # default: &common_settings + # foo: 'foo' + # bar: 'bar' + # + # production: + # <<: *common_settings + # bar: 'baz' # override the default value + # + module ConfigFile + + # When the extension is registered sets the +environments+ setting to the + # traditional environments: development, test and production. + def self.registered(base) + base.set :environments, %w[test production development] + end + + # Loads the configuration from the YAML files whose +paths+ are passed as + # arguments, filtering the settings for the current environment. Note that + # these +paths+ can actually be globs. + def config_file(*paths) + Dir.chdir(root || '.') do + paths.each do |pattern| + Dir.glob(pattern) do |file| + raise UnsupportedConfigType unless ['.yml', '.yaml', '.erb'].include?(File.extname(file)) + logger.info "loading config file '#{file}'" if logging? && respond_to?(:logger) + document = ERB.new(IO.read(file)).result + yaml = YAML.load(document) + config = config_for_env(yaml) + config.each_pair { |key, value| set(key, value) } + end + end + end + end + + class UnsupportedConfigType < Exception + def message + 'Invalid config file type, use .yml, .yaml or .erb' + end + end + + private + + # Given a +hash+ containing application configuration it returns + # settings applicable to the current environment. Note: It gives + # precedence to environment settings defined at the root-level. + def config_for_env(hash) + return from_environment_key(hash) if environment_keys?(hash) + + hash.each_with_object(IndifferentHash[]) do |(k, v), acc| + if environment_keys?(v) + acc.merge!(k => v[environment.to_s]) if v.key?(environment.to_s) + else + acc.merge!(k => v) + end + end + end + + # Given a +hash+ returns the settings corresponding to the current + # environment. + def from_environment_key(hash) + hash[environment.to_s] || hash[environment.to_sym] || {} + end + + # Returns true if supplied with a hash that has any recognized + # +environments+ in its root keys. + def environment_keys?(hash) + hash.is_a?(Hash) && hash.any? { |k, _| environments.include?(k.to_s) } + end + end + + register ConfigFile + Delegator.delegate :config_file +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/content_for.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/content_for.rb new file mode 100644 index 0000000..c5e4bf6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/content_for.rb @@ -0,0 +1,196 @@ +require 'sinatra/base' +require 'sinatra/capture' + +module Sinatra + + # = Sinatra::ContentFor + # + # Sinatra::ContentFor is a set of helpers that allows you to capture + # blocks inside views to be rendered later during the request. The most + # common use is to populate different parts of your layout from your view. + # + # The currently supported engines are: Erb, Erubi, Erubis, Haml and Slim. + # + # == Usage + # + # You call +content_for+, generally from a view, to capture a block of markup + # giving it an identifier: + # + # # index.erb + # <% content_for :some_key do %> + # ... + # <% end %> + # + # Then, you call +yield_content+ with that identifier, generally from a + # layout, to render the captured block: + # + # # layout.erb + # <%= yield_content :some_key %> + # + # If you have provided +yield_content+ with a block and no content for the + # specified key is found, it will render the results of the block provided + # to yield_content. + # + # # layout.erb + # <% yield_content :some_key_with_no_content do %> + # ... + # <% end %> + # + # === Classic Application + # + # To use the helpers in a classic application all you need to do is require + # them: + # + # require "sinatra" + # require "sinatra/content_for" + # + # # Your classic application code goes here... + # + # === Modular Application + # + # To use the helpers in a modular application you need to require them, and + # then, tell the application you will use them: + # + # require "sinatra/base" + # require "sinatra/content_for" + # + # class MyApp < Sinatra::Base + # helpers Sinatra::ContentFor + # + # # The rest of your modular application code goes here... + # end + # + # == And How Is This Useful? + # + # For example, some of your views might need a few javascript tags and + # stylesheets, but you don't want to force this files in all your pages. + # Then you can put <%= yield_content :scripts_and_styles %> on your + # layout, inside the tag, and each view can call content_for + # setting the appropriate set of tags that should be added to the layout. + # + # == Limitations + # + # Due to the rendering process limitation using <%= yield_content %> + # from within nested templates do not work above the <%= yield %> statement. + # For more details https://github.com/sinatra/sinatra-contrib/issues/140#issuecomment-48831668 + # + # # app.rb + # get '/' do + # erb :body, :layout => :layout do + # erb :foobar + # end + # end + # + # # foobar.erb + # <% content_for :one do %> + # + # <% end %> + # <% content_for :two do %> + # + # <% end %> + # + # Using <%= yield_content %> before <%= yield %> will cause only the second + # alert to display: + # + # # body.erb + # # Display only second alert + # <%= yield_content :one %> + # <%= yield %> + # <%= yield_content :two %> + # + # # body.erb + # # Display both alerts + # <%= yield %> + # <%= yield_content :one %> + # <%= yield_content :two %> + # + module ContentFor + include Capture + + # Capture a block of content to be rendered later. For example: + # + # <% content_for :head do %> + # + # <% end %> + # + # You can also pass an immediate value instead of a block: + # + # <% content_for :title, "foo" %> + # + # You can call +content_for+ multiple times with the same key + # (in the example +:head+), and when you render the blocks for + # that key all of them will be rendered, in the same order you + # captured them. + # + # Your blocks can also receive values, which are passed to them + # by yield_content + def content_for(key, value = nil, options = {}, &block) + block ||= proc { |*| value } + clear_content_for(key) if options[:flush] + content_blocks[key.to_sym] << capture_later(&block) + end + + # Check if a block of content with the given key was defined. For + # example: + # + # <% content_for :head do %> + # + # <% end %> + # + # <% if content_for? :head %> + # content "head" was defined. + # <% end %> + def content_for?(key) + content_blocks[key.to_sym].any? + end + + # Unset a named block of content. For example: + # + # <% clear_content_for :head %> + def clear_content_for(key) + content_blocks.delete(key.to_sym) if content_for?(key) + end + + # Render the captured blocks for a given key. For example: + # + # + # Example + # <%= yield_content :head %> + # + # + # Would render everything you declared with content_for + # :head before closing the tag. + # + # You can also pass values to the content blocks by passing them + # as arguments after the key: + # + # <%= yield_content :head, 1, 2 %> + # + # Would pass 1 and 2 to all the blocks registered + # for :head. + def yield_content(key, *args, &block) + if block_given? && !content_for?(key) + (haml? && Tilt[:haml] == Tilt::HamlTemplate) ? capture_haml(*args, &block) : yield(*args) + else + content = content_blocks[key.to_sym].map { |b| capture(*args, &b) } + content.join.tap do |c| + if block_given? && (erb? || erubi? || erubis?) + @_out_buf << c + end + end + end + end + + private + + def content_blocks + @content_blocks ||= Hash.new { |h, k| h[k] = [] } + end + end + + helpers ContentFor +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib.rb new file mode 100644 index 0000000..e27888b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib.rb @@ -0,0 +1,39 @@ +require 'sinatra/contrib/setup' + +module Sinatra + module Contrib + ## + # Common middleware that doesn't bring run time overhead if not used + # or breaks if external dependencies are missing. Will extend + # Sinatra::Application by default. + module Common + register :ConfigFile, 'sinatra/config_file' + register :MultiRoute, 'sinatra/multi_route' + register :Namespace, 'sinatra/namespace' + register :RespondWith, 'sinatra/respond_with' + + helpers :Capture, 'sinatra/capture' + helpers :ContentFor, 'sinatra/content_for' + helpers :Cookies, 'sinatra/cookies' + helpers :EngineTracking, 'sinatra/engine_tracking' + helpers :JSON, 'sinatra/json' + helpers :LinkHeader, 'sinatra/link_header' + helpers :Streaming, 'sinatra/streaming' + helpers :RequiredParams, 'sinatra/required_params' + end + + ## + # Other extensions you don't want to be loaded unless needed. + module Custom + # register :Compass, 'sinatra/compass' + register :Reloader, 'sinatra/reloader' + end + + ## + # Stuff that aren't Sinatra extensions, technically. + autoload :Extension, 'sinatra/extension' + autoload :TestHelpers, 'sinatra/test_helpers' + end + + register Sinatra::Contrib::Common +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib/all.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib/all.rb new file mode 100644 index 0000000..427be26 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib/all.rb @@ -0,0 +1,2 @@ +require 'sinatra/contrib' +Sinatra.register Sinatra::Contrib::All diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib/setup.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib/setup.rb new file mode 100644 index 0000000..61e4f87 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib/setup.rb @@ -0,0 +1,51 @@ +require 'sinatra/base' +require 'sinatra/contrib/version' + +module Sinatra + module Contrib + module Loader + def extensions + @extensions ||= {:helpers => [], :register => []} + end + + def register(name, path) + autoload name, path, :register + end + + def helpers(name, path) + autoload name, path, :helpers + end + + def autoload(name, path, method = nil) + extensions[method] << name if method + Sinatra.autoload(name, path) + end + + def registered(base) + @extensions.each do |method, list| + list = list.map { |name| Sinatra.const_get name } + base.send(method, *list) unless base == ::Sinatra::Application + end + end + end + + module Common + extend Loader + end + + module Custom + extend Loader + end + + module All + def self.registered(base) + base.register Common, Custom + end + end + + extend Loader + def self.registered(base) + base.register Common, Custom + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib/version.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib/version.rb new file mode 100644 index 0000000..adeb376 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/contrib/version.rb @@ -0,0 +1,6 @@ +module Sinatra + module Contrib + VERSION = '2.2.0' + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/cookies.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/cookies.rb new file mode 100644 index 0000000..e30b03f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/cookies.rb @@ -0,0 +1,332 @@ +require 'sinatra/base' + +module Sinatra + # = Sinatra::Cookies + # + # Easy way to deal with cookies + # + # == Usage + # + # Allows you to read cookies: + # + # get '/' do + # "value: #{cookies[:something]}" + # end + # + # And of course to write cookies: + # + # get '/set' do + # cookies[:something] = 'foobar' + # redirect to('/') + # end + # + # And generally behaves like a hash: + # + # get '/demo' do + # cookies.merge! 'foo' => 'bar', 'bar' => 'baz' + # cookies.keep_if { |key, value| key.start_with? 'b' } + # foo, bar = cookies.values_at 'foo', 'bar' + # "size: #{cookies.length}" + # end + # + # === Classic Application + # + # In a classic application simply require the helpers, and start using them: + # + # require "sinatra" + # require "sinatra/cookies" + # + # # The rest of your classic application code goes here... + # + # === Modular Application + # + # In a modular application you need to require the helpers, and then tell + # the application to use them: + # + # require "sinatra/base" + # require "sinatra/cookies" + # + # class MyApp < Sinatra::Base + # helpers Sinatra::Cookies + # + # # The rest of your modular application code goes here... + # end + # + module Cookies + class Jar + include Enumerable + attr_reader :options + + def initialize(app) + @response_string = nil + @response_hash = {} + @response = app.response + @request = app.request + @deleted = [] + + @options = { + :path => @request.script_name.to_s.empty? ? '/' : @request.script_name, + :domain => @request.host == 'localhost' ? nil : @request.host, + :secure => @request.secure?, + :httponly => true + } + + if app.settings.respond_to? :cookie_options + @options.merge! app.settings.cookie_options + end + end + + def ==(other) + other.respond_to? :to_hash and to_hash == other.to_hash + end + + def [](key) + response_cookies[key.to_s] || request_cookies[key.to_s] + end + + def []=(key, value) + set(key, value: value) + end + + def assoc(key) + to_hash.assoc(key.to_s) + end if Hash.method_defined? :assoc + + def clear + each_key { |k| delete(k) } + end + + def compare_by_identity? + false + end + + def default + nil + end + + alias default_proc default + + def delete(key) + result = self[key] + @response.delete_cookie(key.to_s, @options) + result + end + + def delete_if + return enum_for(__method__) unless block_given? + each { |k, v| delete(k) if yield(k, v) } + self + end + + def each(&block) + return enum_for(__method__) unless block_given? + to_hash.each(&block) + end + + def each_key(&block) + return enum_for(__method__) unless block_given? + to_hash.each_key(&block) + end + + alias each_pair each + + def each_value(&block) + return enum_for(__method__) unless block_given? + to_hash.each_value(&block) + end + + def empty? + to_hash.empty? + end + + def fetch(key, &block) + response_cookies.fetch(key.to_s) do + request_cookies.fetch(key.to_s, &block) + end + end + + def flatten + to_hash.flatten + end if Hash.method_defined? :flatten + + def has_key?(key) + response_cookies.has_key? key.to_s or request_cookies.has_key? key.to_s + end + + def has_value?(value) + response_cookies.has_value? value or request_cookies.has_value? value + end + + def hash + to_hash.hash + end + + alias include? has_key? + alias member? has_key? + + def index(value) + warn "Hash#index is deprecated; use Hash#key" + key(value) + end + + def inspect + "<##{self.class}: #{to_hash.inspect[1..-2]}>" + end + + def invert + to_hash.invert + end if Hash.method_defined? :invert + + def keep_if + return enum_for(__method__) unless block_given? + delete_if { |*a| not yield(*a) } + end + + def key(value) + to_hash.key(value) + end + + alias key? has_key? + + def keys + to_hash.keys + end + + def length + to_hash.length + end + + def merge(other, &block) + to_hash.merge(other, &block) + end + + def merge!(other) + other.each_pair do |key, value| + if block_given? and include? key + self[key] = yield(key.to_s, self[key], value) + else + self[key] = value + end + end + end + + def rassoc(value) + to_hash.rassoc(value) + end + + def rehash + response_cookies.rehash + request_cookies.rehash + self + end + + def reject(&block) + return enum_for(__method__) unless block_given? + to_hash.reject(&block) + end + + alias reject! delete_if + + def replace(other) + select! { |k, v| other.include?(k) or other.include?(k.to_s) } + merge! other + end + + def select(&block) + return enum_for(__method__) unless block_given? + to_hash.select(&block) + end + + alias select! keep_if if Hash.method_defined? :select! + + def set(key, options = {}) + @response.set_cookie key.to_s, @options.merge(options) + end + + def shift + key, value = to_hash.shift + delete(key) + [key, value] + end + + alias size length + + def sort(&block) + to_hash.sort(&block) + end if Hash.method_defined? :sort + + alias store []= + + def to_hash + request_cookies.merge(response_cookies) + end + + def to_a + to_hash.to_a + end + + def to_s + to_hash.to_s + end + + alias update merge! + alias value? has_value? + + def values + to_hash.values + end + + def values_at(*list) + list.map { |k| self[k] } + end + + private + + def warn(message) + super "#{caller.first[/^[^:]:\d+:/]} warning: #{message}" + end + + def deleted + parse_response + @deleted + end + + def response_cookies + parse_response + @response_hash + end + + def parse_response + string = @response['Set-Cookie'] + return if @response_string == string + + hash = {} + + string.each_line do |line| + key, value = line.split(';', 2).first.to_s.split('=', 2) + next if key.nil? + key = Rack::Utils.unescape(key) + if line =~ /expires=Thu, 01[-\s]Jan[-\s]1970/ + @deleted << key + else + @deleted.delete key + hash[key] = value + end + end + + @response_hash.replace hash + @response_string = string + end + + def request_cookies + @request.cookies.reject { |key, value| deleted.include? key } + end + end + + def cookies + @cookies ||= Jar.new(self) + end + end + + helpers Cookies +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/custom_logger.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/custom_logger.rb new file mode 100644 index 0000000..42c0d63 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/custom_logger.rb @@ -0,0 +1,60 @@ +module Sinatra + + # = Sinatra::CustomLogger + # + # CustomLogger extension allows you to define your own logger instance + # using +logger+ setting. That logger then will be available + # as #logger helper method in your routes and views. + # + # == Usage + # + # === Classic Application + # + # To define your custom logger instance in a classic application: + # + # require 'sinatra' + # require 'sinatra/custom_logger' + # require 'logger' + # + # set :logger, Logger.new(STDOUT) + # + # get '/' do + # logger.info 'Some message' # STDOUT logger is used + # # Other code... + # end + # + # === Modular Application + # + # The same for modular application: + # + # require 'sinatra/base' + # require 'sinatra/custom_logger' + # require 'logger' + # + # class MyApp < Sinatra::Base + # helpers Sinatra::CustomLogger + # + # configure :development, :production do + # logger = Logger.new(File.open("#{root}/log/#{environment}.log", 'a')) + # logger.level = Logger::DEBUG if development? + # set :logger, logger + # end + # + # get '/' do + # logger.info 'Some message' # File-based logger is used + # # Other code... + # end + # end + # + module CustomLogger + def logger + if settings.respond_to?(:logger) + settings.logger + else + request.logger + end + end + end + + helpers CustomLogger +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/decompile.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/decompile.rb new file mode 100644 index 0000000..056f929 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/decompile.rb @@ -0,0 +1,5 @@ +warn "Sinatra::Decompile is deprecated without replacement." + +def warn(message) + super "#{caller.first[/^[^:]:\d+:/]} warning: #{message}" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/engine_tracking.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/engine_tracking.rb new file mode 100644 index 0000000..154d5c9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/engine_tracking.rb @@ -0,0 +1,133 @@ +require 'sinatra/base' + +module Sinatra + # Adds methods like `haml?` that allow helper methods to check whether they + # are called from within a template. + module EngineTracking + attr_reader :current_engine + + # @return [Boolean] Returns true if current engine is `:erb`. + def erb? + @current_engine == :erb + end + + # Returns true if the current engine is `:erubi`, or `Tilt[:erb]` is set + # to Tilt::ErubisTemplate. + # + # @return [Boolean] Returns true if current engine is `:erubi`. + def erubi? + @current_engine == :erubi or + erb? && Tilt[:erb] == Tilt::ErubiTemplate + end + + # Returns true if the current engine is `:erubis`, or `Tilt[:erb]` is set + # to Tilt::ErubisTemplate. + # + # @return [Boolean] Returns true if current engine is `:erubis`. + def erubis? + @current_engine == :erubis or + erb? && Tilt[:erb] == Tilt::ErubisTemplate + end + + # @return [Boolean] Returns true if current engine is `:haml`. + def haml? + @current_engine == :haml + end + + # @return [Boolean] Returns true if current engine is `:sass`. + def sass? + @current_engine == :sass + end + + # @return [Boolean] Returns true if current engine is `:scss`. + def scss? + @current_engine == :scss + end + + # @return [Boolean] Returns true if current engine is `:less`. + def less? + @current_engine == :less + end + + # @return [Boolean] Returns true if current engine is `:builder`. + def builder? + @current_engine == :builder + end + + # @return [Boolean] Returns true if current engine is `:liquid`. + def liquid? + @current_engine == :liquid + end + + # @return [Boolean] Returns true if current engine is `:markdown`. + def markdown? + @current_engine == :markdown + end + + # @return [Boolean] Returns true if current engine is `:textile. + def textile? + @current_engine == :textile + end + + # @return [Boolean] Returns true if current engine is `:rdoc`. + def rdoc? + @current_engine == :rdoc + end + + # @return [Boolean] Returns true if current engine is `:radius. + def radius? + @current_engine == :radius + end + + # @return [Boolean] Returns true if current engine is `:markaby`. + def markaby? + @current_engine == :markaby + end + + # @return [Boolean] Returns true if current engine is `:coffee`. + def coffee? + @current_engine == :coffee + end + + # @return [Boolean] Returns true if current engine is `:nokogiri`. + def nokogiri? + @current_engine == :nokogiri + end + + # @return [Boolean] Returns true if current engine is `:slim`. + def slim? + @current_engine == :slim + end + + # @return [Boolean] Returns true if current engine is `:creole`. + def creole? + @current_engine == :creole + end + + # @return [Boolean] Returns true if current engine is `:ruby`. + def ruby? + @current_engine == :ruby + end + + def initialize(*) + @current_engine = :ruby + super + end + + # @param engine [Symbol, String] Name of Engine to shift to. + def with_engine(engine) + @current_engine, engine_was = engine.to_sym, @current_engine + yield + ensure + @current_engine = engine_was + end + + private + + def render(engine, *) + with_engine(engine) { super } + end + end + + helpers EngineTracking +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/extension.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/extension.rb new file mode 100644 index 0000000..2a5cda7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/extension.rb @@ -0,0 +1,94 @@ +require 'sinatra/base' + +module Sinatra + + # = Sinatra::Extension + # + # Sinatra::Extension is a mixin that provides some syntactic sugar + # for your extensions. It allows you to call almost any + # Sinatra::Base method directly inside your extension + # module. This means you can use +get+ to define a route, +before+ + # to define a before filter, +set+ to define a setting and so on. + # + # Is important to be aware that this mixin remembers the method calls you + # make, and then, when your extension is registered, replays them on the + # Sinatra application that has been extended. In order to do that, it + # defines a registered method, so, if your extension defines one + # too, remember to call +super+. + # + # == Usage + # + # Just require the mixin and extend your extension with it: + # + # require 'sinatra/extension' + # + # module MyExtension + # extend Sinatra::Extension + # + # # set some settings for development + # configure :development do + # set :reload_stuff, true + # end + # + # # define a route + # get '/' do + # 'Hello World' + # end + # + # # The rest of your extension code goes here... + # end + # + # You can also create an extension with the +new+ method: + # + # MyExtension = Sinatra::Extension.new do + # # Your extension code goes here... + # end + # + # This is useful when you just want to pass a block to + # Sinatra::Base.register. + module Extension + def self.new(&block) + ext = Module.new.extend(self) + ext.class_eval(&block) + ext + end + + def settings + self + end + + def configure(*args, &block) + record(:configure, *args) { |c| c.instance_exec(c, &block) } + end + + def registered(base = nil, &block) + base ? replay(base) : record(:class_eval, &block) + end + + private + + def record(method, *args, &block) + recorded_methods << [method, args, block] + end + + def replay(object) + recorded_methods.each { |m, a, b| object.send(m, *a, &b) } + end + + def recorded_methods + @recorded_methods ||= [] + end + + def method_missing(method, *args, &block) + return super unless Sinatra::Base.respond_to? method + record(method, *args, &block) + DontCall.new(method) + end + + class DontCall < BasicObject + def initialize(method) @method = method end + def method_missing(*) fail "not supposed to use result of #@method!" end + def inspect; "#<#{self.class}: #{@method}>" end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/json.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/json.rb new file mode 100644 index 0000000..712419b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/json.rb @@ -0,0 +1,131 @@ +require 'sinatra/base' +require 'multi_json' +module Sinatra + + # = Sinatra::JSON + # + # Sinatra::JSON adds a helper method, called +json+, for (obviously) + # json generation. + # + # == Usage + # + # === Classic Application + # + # In a classic application simply require the helper, and start using it: + # + # require "sinatra" + # require "sinatra/json" + # + # # define a route that uses the helper + # get '/' do + # json :foo => 'bar' + # end + # + # # The rest of your classic application code goes here... + # + # === Modular Application + # + # In a modular application you need to require the helper, and then tell the + # application you will use it: + # + # require "sinatra/base" + # require "sinatra/json" + # + # class MyApp < Sinatra::Base + # + # # define a route that uses the helper + # get '/' do + # json :foo => 'bar' + # end + # + # # The rest of your modular application code goes here... + # end + # + # === Encoders + # + # By default it will try to call +to_json+ on the object, but if it doesn't + # respond to that message, it will use its own rather simple encoder. You can + # easily change that anyways. To use +JSON+, simply require it: + # + # require 'json' + # + # The same goes for Yajl::Encoder: + # + # require 'yajl' + # + # For other encoders, besides requiring them, you need to define the + # :json_encoder setting. For instance, for the +Whatever+ encoder: + # + # require 'whatever' + # set :json_encoder, Whatever + # + # To force +json+ to simply call +to_json+ on the object: + # + # set :json_encoder, :to_json + # + # Actually, it can call any method: + # + # set :json_encoder, :my_fancy_json_method + # + # === Content-Type + # + # It will automatically set the content type to "application/json". As + # usual, you can easily change that, with the :json_content_type + # setting: + # + # set :json_content_type, :js + # + # === Overriding the Encoder and the Content-Type + # + # The +json+ helper will also take two options :encoder and + # :content_type. The values of this options are the same as the + # :json_encoder and :json_content_type settings, + # respectively. You can also pass those to the json method: + # + # get '/' do + # json({:foo => 'bar'}, :encoder => :to_json, :content_type => :js) + # end + # + module JSON + class << self + def encode(object) + ::MultiJson.dump(object) + end + end + + def json(object, options = {}) + content_type resolve_content_type(options) + resolve_encoder_action object, resolve_encoder(options) + end + + private + + def resolve_content_type(options = {}) + options[:content_type] || settings.json_content_type + end + + def resolve_encoder(options = {}) + options[:json_encoder] || settings.json_encoder + end + + def resolve_encoder_action(object, encoder) + [:encode, :generate].each do |method| + return encoder.send(method, object) if encoder.respond_to? method + end + if encoder.is_a? Symbol + object.__send__(encoder) + else + fail "#{encoder} does not respond to #generate nor #encode" + end #if + end #resolve_encoder_action + end #JSON + + Base.set :json_encoder do + ::MultiJson + end + + Base.set :json_content_type, :json + + # Load the JSON helpers in modular style automatically + Base.helpers JSON +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/link_header.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/link_header.rb new file mode 100644 index 0000000..6d9bac4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/link_header.rb @@ -0,0 +1,132 @@ +require 'sinatra/base' + +module Sinatra + + # = Sinatra::LinkHeader + # + # Sinatra::LinkHeader adds a set of helper methods to generate link + # HTML tags and their corresponding Link HTTP headers. + # + # == Usage + # + # Once you had set up the helpers in your application (see below), you will + # be able to call the following methods from inside your route handlers, + # filters and templates: + # + # +prefetch+:: + # Sets the Link HTTP headers and returns HTML tags to prefetch the given + # resources. + # + # +stylesheet+:: + # Sets the Link HTTP headers and returns HTML tags to use the given + # stylesheets. + # + # +link+:: + # Sets the Link HTTP headers and returns the corresponding HTML tags + # for the given resources. + # + # +link_headers+:: + # Returns the corresponding HTML tags for the current Link HTTP headers. + # + # === Classic Application + # + # In a classic application simply require the helpers, and start using them: + # + # require "sinatra" + # require "sinatra/link_header" + # + # # The rest of your classic application code goes here... + # + # === Modular Application + # + # In a modular application you need to require the helpers, and then tell + # the application you will use them: + # + # require "sinatra/base" + # require "sinatra/link_header" + # + # class MyApp < Sinatra::Base + # helpers Sinatra::LinkHeader + # + # # The rest of your modular application code goes here... + # end + # + module LinkHeader + ## + # Sets Link HTTP header and returns HTML tags for telling the browser to + # prefetch given resources (only supported by Opera and Firefox at the + # moment). + def prefetch(*urls) + link(:prefetch, *urls) + end + + ## + # Sets Link HTTP header and returns HTML tags for using stylesheets. + def stylesheet(*urls) + urls << {} unless urls.last.respond_to? :to_hash + urls.last[:type] ||= mime_type(:css) + link(:stylesheet, *urls) + end + + ## + # Sets Link HTTP header and returns corresponding HTML tags. + # + # Example: + # + # # Sets header: + # # Link: ; rel="next" + # # Returns String: + # # '' + # link '/foo', :rel => :next + # + # # Multiple URLs + # link :stylesheet, '/a.css', '/b.css' + def link(*urls) + opts = urls.last.respond_to?(:to_hash) ? urls.pop : {} + opts[:rel] = urls.shift unless urls.first.respond_to? :to_str + options = opts.map { |k, v| " #{k}=#{v.to_s.inspect}" } + html_pattern = "" + http_pattern = ["<%s>", *options].join ";" + link = (response["Link"] ||= "") + + urls.map do |url| + link << ",\n" unless link.empty? + link << (http_pattern % url) + html_pattern % url + end.join "\n" + end + + ## + # Takes the current value of th Link header(s) and generates HTML tags + # from it. + # + # Example: + # + # get '/' do + # # You can of course use fancy helpers like #link, #stylesheet + # # or #prefetch + # response["Link"] = '; rel="next"' + # haml :some_page + # end + # + # __END__ + # + # @@ layout + # %head= link_headers + # %body= yield + def link_headers + yield if block_given? + return "" unless response.include? "Link" + response["Link"].split(",\n").map do |line| + url, *opts = line.split(';').map(&:strip) + "" + end.join "\n" + end + + def self.registered(base) + puts "WARNING: #{self} is a helpers module, not an extension." + end + end + + helpers LinkHeader +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/multi_route.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/multi_route.rb new file mode 100644 index 0000000..af48ac0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/multi_route.rb @@ -0,0 +1,87 @@ +require 'sinatra/base' + +module Sinatra + # = Sinatra::MultiRoute + # + # Create multiple routes with one statement. + # + # == Usage + # + # Use this extension to create a handler for multiple routes: + # + # get '/foo', '/bar' do + # # ... + # end + # + # Or for multiple verbs: + # + # route :get, :post, '/' do + # # ... + # end + # + # Or for multiple verbs and multiple routes: + # + # route :get, :post, ['/foo', '/bar'] do + # # ... + # end + # + # Or even for custom verbs: + # + # route 'LIST', '/' do + # # ... + # end + # + # === Classic Application + # + # To use the extension in a classic application all you need to do is require + # it: + # + # require "sinatra" + # require "sinatra/multi_route" + # + # # Your classic application code goes here... + # + # === Modular Application + # + # To use the extension in a modular application you need to require it, and + # then, tell the application you will use it: + # + # require "sinatra/base" + # require "sinatra/multi_route" + # + # class MyApp < Sinatra::Base + # register Sinatra::MultiRoute + # + # # The rest of your modular application code goes here... + # end + # + module MultiRoute + def head(*args, &block) super(*route_args(args), &block) end + def delete(*args, &block) super(*route_args(args), &block) end + def get(*args, &block) super(*route_args(args), &block) end + def options(*args, &block) super(*route_args(args), &block) end + def patch(*args, &block) super(*route_args(args), &block) end + def post(*args, &block) super(*route_args(args), &block) end + def put(*args, &block) super(*route_args(args), &block) end + + def route(*args, &block) + options = Hash === args.last ? args.pop : {} + routes = [*args.pop] + args.each do |verb| + verb = verb.to_s.upcase if Symbol === verb + routes.each do |route| + super(verb, route, options, &block) + end + end + end + + private + + def route_args(args) + options = Hash === args.last ? args.pop : {} + [args, options] + end + end + + register MultiRoute +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/namespace.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/namespace.rb new file mode 100644 index 0000000..1b0c58a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/namespace.rb @@ -0,0 +1,366 @@ +require 'sinatra/base' +require 'mustermann' + +module Sinatra + + # = Sinatra::Namespace + # + # Sinatra::Namespace is an extension that adds namespaces to an + # application. This namespaces will allow you to share a path prefix for the + # routes within the namespace, and define filters, conditions and error + # handlers exclusively for them. Besides that, you can also register helpers + # and extensions that will be used only within the namespace. + # + # == Usage + # + # Once you have loaded the extension (see below), you can use the +namespace+ + # method to define namespaces in your application. + # + # You can define a namespace by a path prefix: + # + # namespace '/blog' do + # get { haml :blog } + # get '/:entry_permalink' do + # @entry = Entry.find_by_permalink!(params[:entry_permalink]) + # haml :entry + # end + # + # # More blog routes... + # end + # + # by a condition: + # + # namespace :host_name => 'localhost' do + # get('/admin/dashboard') { haml :dashboard } + # get('/admin/login') { haml :login } + # + # # More admin routes... + # end + # + # or both: + # + # namespace '/admin', :host_name => 'localhost' do + # get('/dashboard') { haml :dashboard } + # get('/login') { haml :login } + # post('/login') { login_user } + # + # # More admin routes... + # end + # + # Regex is also accepted: + # + # namespace /\/posts\/([^\/&?]+)\// do + # get { haml :blog } + # + # # More blog routes... + # end + # + # When you define a filter or an error handler, or register an extension or a + # set of helpers within a namespace, they only affect the routes defined in + # it. For instance, lets define a before filter to prevent the access of + # unauthorized users to the admin section of the application: + # + # namespace '/admin' do + # helpers AdminHelpers + # before { authenticate unless request.path_info == '/admin/login' } + # + # get '/dashboard' do + # # Only authenticated users can access here... + # haml :dashboard + # end + # + # # More admin routes... + # end + # + # get '/' do + # # Any user can access here... + # haml :index + # end + # + # Well, they actually also affect the nested namespaces: + # + # namespace '/admin' do + # helpers AdminHelpers + # before { authenticate unless request.path_info == '/admin/login' } + # + # namespace '/users' do + # get do + # # Only authenticated users can access here... + # @users = User.all + # haml :users + # end + # + # # More user admin routes... + # end + # + # # More admin routes... + # end + # + # Redirecting within the namespace can be done using redirect_to: + # + # namespace '/admin' do + # get '/foo' do + # redirect_to '/bar' # Redirects to /admin/bar + # end + # + # get '/foo' do + # redirect '/bar' # Redirects to /bar + # end + # end + # + # === Classic Application Setup + # + # To be able to use namespaces in a classic application all you need to do is + # require the extension: + # + # require "sinatra" + # require "sinatra/namespace" + # + # namespace '/users' do + # end + # + # === Modular Application Setup + # + # To be able to use namespaces in a modular application all you need to do is + # require the extension, and then, register it: + # + # require "sinatra/base" + # require "sinatra/namespace" + # + # class MyApp < Sinatra::Base + # register Sinatra::Namespace + # + # namespace '/users' do + # end + # end + # + # === Within an extension + # + # To be able to use namespaces within an extension, you need to first create + # an extension. This includes defining the `registered(app)` method in the + # module. + # + # require 'sinatra/base' # For creating Sinatra extensions + # require 'sinatra/namespace' # To create namespaces + # + # module Zomg # Keep everything under "Zomg" namespace for sanity + # module Routes # Define a new "Routes" module + # + # def self.registered(app) + # # First, register the Namespace extension + # app.register Sinatra::Namespace + # + # # This defines an `/api` namespace on the application + # app.namespace '/api' do + # get '/users' do + # # do something with `GET "/api/users"` + # end + # end + # + # end + # end + # + # # Lastly, register the extension to use in our app + # Sinatra.register Routes + # end + # + # In order to use this extension, is the same as any other Sinatra extension: + # + # module Zomg + # # Define our app class, we use modular app for this example + # class App < Sinatra::Base + # # this gives us all the namespaces we defined earlier + # register Routes + # + # get '/' do + # "Welcome to my application!" + # end + # end + # end + # + # Zomg::App.run! # Don't forget to start your app ;) + # + # Phew! That was a mouthful. + # + # I hope that helps you use `Sinatra::Namespace` in every way imaginable! + # + module Namespace + def self.new(base, pattern, conditions = {}, &block) + Module.new do + #quelch uninitialized variable warnings, since these get used by compile method. + @pattern, @conditions = nil, nil + extend NamespacedMethods + include InstanceMethods + @base, @extensions, @errors = base, [], {} + @pattern, @conditions = compile(pattern, conditions) + @templates = Hash.new { |h,k| @base.templates[k] } + namespace = self + before { extend(@namespace = namespace) } + class_eval(&block) + end + end + + module InstanceMethods + def settings + @namespace + end + + def template_cache + super.fetch(:nested, @namespace) { Tilt::Cache.new } + end + + def redirect_to(uri, *args) + redirect("#{@namespace.pattern}#{uri}", *args) + end + end + + module SharedMethods + def namespace(pattern, conditions = {}, &block) + Sinatra::Namespace.new(self, pattern, conditions, &block) + end + end + + module NamespacedMethods + include SharedMethods + attr_reader :base, :templates + + ALLOWED_ENGINES = [ + :erb, :erubi, :erubis, :haml, :hamlit, :builder, :nokogiri, :sass, :scss, + :less, :liquid, :markdown, :textile, :rdoc, :asciidoc, :radius, :markaby, + :rabl, :slim, :creole, :mediawiki, :coffee, :stylus, :yajl, :wlang + ] + + def self.prefixed(*names) + names.each { |n| define_method(n) { |*a, &b| prefixed(n, *a, &b) }} + end + + prefixed :before, :after, :delete, :get, :head, :options, :patch, :post, :put + + def helpers(*extensions, &block) + class_eval(&block) if block_given? + include(*extensions) if extensions.any? + end + + def register(*extensions, &block) + extensions << Module.new(&block) if block_given? + @extensions += extensions + extensions.each do |extension| + extend extension + extension.registered(self) if extension.respond_to?(:registered) + end + end + + def invoke_hook(name, *args) + @extensions.each { |e| e.send(name, *args) if e.respond_to?(name) } + end + + def not_found(&block) + error(Sinatra::NotFound, &block) + end + + def errors + base.errors.merge(namespace_errors) + end + + def namespace_errors + @errors + end + + def error(*codes, &block) + args = Sinatra::Base.send(:compile!, "ERROR", /.*/, block) + codes = codes.map { |c| Array(c) }.flatten + codes << Exception if codes.empty? + codes << Sinatra::NotFound if codes.include?(404) + + codes.each do |c| + errors = @errors[c] ||= [] + errors << args + end + end + + def respond_to(*args) + return @conditions[:provides] || base.respond_to if args.empty? + @conditions[:provides] = args + end + + def set(key, value = self, &block) + return key.each { |k,v| set(k, v) } if key.respond_to?(:each) and block.nil? and value == self + raise ArgumentError, "may not set #{key}" unless ([:views] + ALLOWED_ENGINES).include?(key) + block ||= proc { value } + singleton_class.send(:define_method, key, &block) + end + + def enable(*opts) + opts.each { |key| set(key, true) } + end + + def disable(*opts) + opts.each { |key| set(key, false) } + end + + def template(name, &block) + filename, line = caller_locations.first + templates[name] = [block, filename, line.to_i] + end + + def layout(name=:layout, &block) + template name, &block + end + + def pattern + @pattern + end + + private + + def app + base.respond_to?(:base) ? base.base : base + end + + def compile(pattern, conditions, default_pattern = nil) + if pattern.respond_to? :to_hash + conditions = conditions.merge pattern.to_hash + pattern = nil + end + base_pattern, base_conditions = @pattern, @conditions + pattern ||= default_pattern + [ prefixed_path(base_pattern, pattern), + (base_conditions || {}).merge(conditions) ] + end + + def prefixed_path(a, b) + return a || b || /.*/ unless a and b + return Mustermann.new(b) if a == /.*/ + + Mustermann.new(a) + Mustermann.new(b) + end + + def prefixed(method, pattern = nil, conditions = {}, &block) + default = %r{(?:/.*)?} if method == :before or method == :after + pattern, conditions = compile pattern, conditions, default + result = base.send(method, pattern, **conditions, &block) + invoke_hook :route_added, method.to_s.upcase, pattern, block + result + end + + def method_missing(method, *args, &block) + base.send(method, *args, &block) + end + + def respond_to?(method, include_private = false) + super || base.respond_to?(method, include_private) + end + end + + module BaseMethods + include SharedMethods + end + + def self.extended(base) + base.extend BaseMethods + end + end + + register Sinatra::Namespace + Delegator.delegate :namespace +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/quiet_logger.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/quiet_logger.rb new file mode 100644 index 0000000..7c00b40 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/quiet_logger.rb @@ -0,0 +1,50 @@ +module Sinatra + # = Sinatra::QuietLogger + # + # QuietLogger extension allows you to define paths excluded + # from logging using the +quiet_logger_prefixes+ setting. + # It is inspired from rails quiet_logger, but handles multiple paths. + # + # == Usage + # + # === Classic Application + # + # You have to require the quiet_logger, set the prefixes + # and register the extension in your application. + # + # require 'sinatra' + # require 'sinatra/quiet_logger' + # + # set :quiet_logger_prefixes, %w(css js images fonts) + # register Sinatra::QuietLogger + # + # === Modular Application + # + # The same for modular application: + # + # require 'sinatra/base' + # require 'sinatra/quiet_logger' + # + # set :quiet_logger_prefixes, %w(css js images fonts) + # + # class App < Sinatra::Base + # register Sinatra::QuietLogger + # end + # + module QuietLogger + + def self.registered(app) + quiet_logger_prefixes = app.settings.quiet_logger_prefixes.join('|') rescue '' + return warn('You need to specify the paths you wish to exclude from logging via `set :quiet_logger_prefixes, %w(images css fonts)`') if quiet_logger_prefixes.empty? + const_set('QUIET_LOGGER_REGEX', %r(\A/{0,2}(?:#{quiet_logger_prefixes}))) + ::Rack::CommonLogger.prepend( + ::Module.new do + def log(env, *) + super unless env['PATH_INFO'] =~ QUIET_LOGGER_REGEX + end + end + ) + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/reloader.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/reloader.rb new file mode 100644 index 0000000..0949681 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/reloader.rb @@ -0,0 +1,417 @@ +require 'sinatra/base' + +module Sinatra + + # = Sinatra::Reloader + # + # Extension to reload modified files. Useful during development, + # since it will automatically require files defining routes, filters, + # error handlers and inline templates, with every incoming request, + # but only if they have been updated. + # + # == Usage + # + # === Classic Application + # + # To enable the reloader in a classic application all you need to do is + # require it: + # + # require "sinatra" + # require "sinatra/reloader" if development? + # + # # Your classic application code goes here... + # + # === Modular Application + # + # To enable the reloader in a modular application all you need to do is + # require it, and then, register it: + # + # require "sinatra/base" + # require "sinatra/reloader" + # + # class MyApp < Sinatra::Base + # configure :development do + # register Sinatra::Reloader + # end + # + # # Your modular application code goes here... + # end + # + # == Using the Reloader in Other Environments + # + # By default, the reloader is only enabled for the development + # environment. Similar to registering the reloader in a modular + # application, a classic application requires manually enabling the + # extension for it to be available in a non-development environment. + # + # require "sinatra" + # require "sinatra/reloader" + # + # configure :production do + # enable :reloader + # end + # + # == Changing the Reloading Policy + # + # You can refine the reloading policy with +also_reload+ and + # +dont_reload+, to customize which files should, and should not, be + # reloaded, respectively. You can also use +after_reload+ to execute a + # block after any file being reloaded. + # + # === Classic Application + # + # Simply call the methods: + # + # require "sinatra" + # require "sinatra/reloader" if development? + # + # also_reload '/path/to/some/file' + # dont_reload '/path/to/other/file' + # after_reload do + # puts 'reloaded' + # end + # + # # Your classic application code goes here... + # + # === Modular Application + # + # Call the methods inside the +configure+ block: + # + # require "sinatra/base" + # require "sinatra/reloader" + # + # class MyApp < Sinatra::Base + # configure :development do + # register Sinatra::Reloader + # also_reload '/path/to/some/file' + # dont_reload '/path/to/other/file' + # after_reload do + # puts 'reloaded' + # end + # end + # + # # Your modular application code goes here... + # end + # + module Reloader + + # Watches a file so it can tell when it has been updated, and what + # elements does it contain. + class Watcher + + # Represents an element of a Sinatra application that may need to + # be reloaded. An element could be: + # * a route + # * a filter + # * an error handler + # * a middleware + # * inline templates + # + # Its +representation+ attribute is there to allow to identify the + # element within an application, that is, to match it with its + # Sinatra's internal representation. + class Element < Struct.new(:type, :representation) + end + + # Collection of file +Watcher+ that can be associated with a + # Sinatra application. That way, we can know which files belong + # to a given application and which files have been modified. It + # also provides a mechanism to inform a Watcher of the elements + # defined in the file being watched and if its changes should be + # ignored. + class List + @app_list_map = Hash.new { |hash, key| hash[key] = new } + + # Returns the +List+ for the application +app+. + def self.for(app) + @app_list_map[app] + end + + # Creates a new +List+ instance. + def initialize + @path_watcher_map = Hash.new do |hash, key| + hash[key] = Watcher.new(key) + end + end + + # Lets the +Watcher+ for the file located at +path+ know that the + # +element+ is defined there, and adds the +Watcher+ to the +List+, + # if it isn't already there. + def watch(path, element) + watcher_for(path).elements << element + end + + # Tells the +Watcher+ for the file located at +path+ to ignore + # the file changes, and adds the +Watcher+ to the +List+, if + # it isn't already there. + def ignore(path) + watcher_for(path).ignore + end + + # Adds a +Watcher+ for the file located at +path+ to the + # +List+, if it isn't already there. + def watcher_for(path) + @path_watcher_map[File.expand_path(path)] + end + alias watch_file watcher_for + + # Returns an array with all the watchers in the +List+. + def watchers + @path_watcher_map.values + end + + # Returns an array with all the watchers in the +List+ that + # have been updated. + def updated + watchers.find_all(&:updated?) + end + end + + attr_reader :path, :elements, :mtime + + # Creates a new +Watcher+ instance for the file located at +path+. + def initialize(path) + @ignore = nil + @path, @elements = path, [] + update + end + + # Indicates whether or not the file being watched has been modified. + def updated? + !ignore? && !removed? && mtime != File.mtime(path) + end + + # Updates the mtime of the file being watched. + def update + @mtime = File.mtime(path) + end + + # Indicates whether or not the file being watched has inline + # templates. + def inline_templates? + elements.any? { |element| element.type == :inline_templates } + end + + # Informs that the modifications to the file being watched + # should be ignored. + def ignore + @ignore = true + end + + # Indicates whether or not the modifications to the file being + # watched should be ignored. + def ignore? + !!@ignore + end + + # Indicates whether or not the file being watched has been removed. + def removed? + !File.exist?(path) + end + end + + MUTEX_FOR_PERFORM = Mutex.new + + # Allow a block to be executed after any file being reloaded + @@after_reload = [] + def after_reload(&block) + @@after_reload << block + end + + # When the extension is registered it extends the Sinatra application + # +klass+ with the modules +BaseMethods+ and +ExtensionMethods+ and + # defines a before filter to +perform+ the reload of the modified files. + def self.registered(klass) + @reloader_loaded_in ||= {} + return if @reloader_loaded_in[klass] + + @reloader_loaded_in[klass] = true + + klass.extend BaseMethods + klass.extend ExtensionMethods + klass.set(:reloader) { klass.development? } + klass.set(:reload_templates) { klass.reloader? } + klass.before do + if klass.reloader? + MUTEX_FOR_PERFORM.synchronize { Reloader.perform(klass) } + end + end + klass.set(:inline_templates, klass.app_file) if klass == Sinatra::Application + end + + # Reloads the modified files, adding, updating and removing the + # needed elements. + def self.perform(klass) + Watcher::List.for(klass).updated.each do |watcher| + klass.set(:inline_templates, watcher.path) if watcher.inline_templates? + watcher.elements.each { |element| klass.deactivate(element) } + $LOADED_FEATURES.delete(watcher.path) + require watcher.path + watcher.update + end + @@after_reload.each(&:call) + end + + # Contains the methods defined in Sinatra::Base that are overridden. + module BaseMethods + # Protects Sinatra::Base.run! from being called more than once. + def run!(*args) + if settings.reloader? + super unless running? + else + super + end + end + + # Does everything Sinatra::Base#route does, but it also tells the + # +Watcher::List+ for the Sinatra application to watch the defined + # route. + # + # Note: We are using #compile! so we don't interfere with extensions + # changing #route. + def compile!(verb, path, block, **options) + source_location = block.respond_to?(:source_location) ? + block.source_location.first : caller_files[1] + signature = super + watch_element( + source_location, :route, { :verb => verb, :signature => signature } + ) + signature + end + + # Does everything Sinatra::Base#inline_templates= does, but it also + # tells the +Watcher::List+ for the Sinatra application to watch the + # inline templates in +file+ or the file who made the call to this + # method. + def inline_templates=(file=nil) + file = (file.nil? || file == true) ? + (caller_files[1] || File.expand_path($0)) : file + watch_element(file, :inline_templates) + super + end + + # Does everything Sinatra::Base#use does, but it also tells the + # +Watcher::List+ for the Sinatra application to watch the middleware + # being used. + def use(middleware, *args, &block) + path = caller_files[1] || File.expand_path($0) + watch_element(path, :middleware, [middleware, args, block]) + super + end + + # Does everything Sinatra::Base#add_filter does, but it also tells + # the +Watcher::List+ for the Sinatra application to watch the defined + # filter. + def add_filter(type, path = nil, **options, &block) + source_location = block.respond_to?(:source_location) ? + block.source_location.first : caller_files[1] + result = super + watch_element(source_location, :"#{type}_filter", filters[type].last) + result + end + + # Does everything Sinatra::Base#error does, but it also tells the + # +Watcher::List+ for the Sinatra application to watch the defined + # error handler. + def error(*codes, &block) + path = caller_files[1] || File.expand_path($0) + result = super + codes.each do |c| + watch_element(path, :error, :code => c, :handler => @errors[c]) + end + result + end + + # Does everything Sinatra::Base#register does, but it also lets the + # reloader know that an extension is being registered, because the + # elements defined in its +registered+ method need a special treatment. + def register(*extensions, &block) + start_registering_extension + result = super + stop_registering_extension + result + end + + # Does everything Sinatra::Base#register does and then registers the + # reloader in the +subclass+. + def inherited(subclass) + result = super + subclass.register Sinatra::Reloader + result + end + end + + # Contains the methods that the extension adds to the Sinatra application. + module ExtensionMethods + # Removes the +element+ from the Sinatra application. + def deactivate(element) + case element.type + when :route then + verb = element.representation[:verb] + signature = element.representation[:signature] + (routes[verb] ||= []).delete(signature) + when :middleware then + @middleware.delete(element.representation) + when :before_filter then + filters[:before].delete(element.representation) + when :after_filter then + filters[:after].delete(element.representation) + when :error then + code = element.representation[:code] + handler = element.representation[:handler] + @errors.delete(code) if @errors[code] == handler + end + end + + # Indicates with a +glob+ which files should be reloaded if they + # have been modified. It can be called several times. + def also_reload(*glob) + Dir[*glob].each { |path| Watcher::List.for(self).watch_file(path) } + end + + # Indicates with a +glob+ which files should not be reloaded even if + # they have been modified. It can be called several times. + def dont_reload(*glob) + Dir[*glob].each { |path| Watcher::List.for(self).ignore(path) } + end + + private + + # attr_reader :register_path warn on -w (private attribute) + def register_path; @register_path ||= nil; end + + # Indicates an extesion is being registered. + def start_registering_extension + @register_path = caller_files[2] + end + + # Indicates the extesion has already been registered. + def stop_registering_extension + @register_path = nil + end + + # Indicates whether or not an extension is being registered. + def registering_extension? + !register_path.nil? + end + + # Builds a Watcher::Element from +type+ and +representation+ and + # tells the Watcher::List for the current application to watch it + # in the file located at +path+. + # + # If an extension is being registered, it also tells the list to + # watch it in the file where the extension has been registered. + # This prevents the duplication of the elements added by the + # extension in its +registered+ method with every reload. + def watch_element(path, type, representation=nil) + list = Watcher::List.for(self) + element = Watcher::Element.new(type, representation) + list.watch(path, element) + list.watch(register_path, element) if registering_extension? + end + end + end + + register Reloader + Delegator.delegate :also_reload, :dont_reload +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/required_params.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/required_params.rb new file mode 100644 index 0000000..c14525e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/required_params.rb @@ -0,0 +1,71 @@ +require 'sinatra/base' + +module Sinatra + # = Sinatra::RequiredParams + # + # Ensure required query parameters + # + # == Usage + # + # Set required query parameter keys in the argument. + # It'll halt with 400 if required keys don't exist. + # + # get '/simple_keys' do + # required_params :p1, :p2 + # end + # + # Complicated pattern is also fine. + # + # get '/complicated_keys' do + # required_params :p1, :p2 => [:p3, :p4] + # end + # + # === Classic Application + # + # In a classic application simply require the helpers, and start using them: + # + # require "sinatra" + # require "sinatra/required_params" + # + # # The rest of your classic application code goes here... + # + # === Modular Application + # + # In a modular application you need to require the helpers, and then tell + # the application to use them: + # + # require "sinatra/base" + # require "sinatra/required_params" + # + # class MyApp < Sinatra::Base + # helpers Sinatra::RequiredParams + # + # # The rest of your modular application code goes here... + # end + # + module RequiredParams + def required_params(*keys) + _required_params(params, *keys) + end + + private + + def _required_params(p, *keys) + keys.each do |key| + if key.is_a?(Hash) + _required_params(p, *key.keys) + key.each do |k, v| + _required_params(p[k.to_s], v) + end + elsif key.is_a?(Array) + _required_params(p, *key) + else + halt 400 unless p && p.respond_to?(:has_key?) && p.has_key?(key.to_s) + end + end + true + end + end + + helpers RequiredParams +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/respond_with.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/respond_with.rb new file mode 100644 index 0000000..ad208c0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/respond_with.rb @@ -0,0 +1,263 @@ +require 'sinatra/json' +require 'sinatra/base' + +module Sinatra + # + # = Sinatra::RespondWith + # + # These extensions let Sinatra automatically choose what template to render or + # action to perform depending on the request's Accept header. + # + # Example: + # + # # Without Sinatra::RespondWith + # get '/' do + # data = { :name => 'example' } + # request.accept.each do |type| + # case type.to_s + # when 'text/html' + # halt haml(:index, :locals => data) + # when 'text/json' + # halt data.to_json + # when 'application/atom+xml' + # halt nokogiri(:'index.atom', :locals => data) + # when 'application/xml', 'text/xml' + # halt nokogiri(:'index.xml', :locals => data) + # when 'text/plain' + # halt 'just an example' + # end + # end + # error 406 + # end + # + # # With Sinatra::RespondWith + # get '/' do + # respond_with :index, :name => 'example' do |f| + # f.txt { 'just an example' } + # end + # end + # + # Both helper methods +respond_to+ and +respond_with+ let you define custom + # handlers like the one above for +text/plain+. +respond_with+ additionally + # takes a template name and/or an object to offer the following default + # behavior: + # + # * If a template name is given, search for a template called + # +name.format.engine+ (+index.xml.nokogiri+ in the above example). + # * If a template name is given, search for a templated called +name.engine+ + # for engines known to result in the requested format (+index.haml+). + # * If a file extension associated with the mime type is known to Sinatra, and + # the object responds to +to_extension+, call that method and use the result + # (+data.to_json+). + # + # == Security + # + # Since methods are triggered based on client input, this can lead to security + # issues (but not as severe as those might appear in the first place: keep in + # mind that only known file extensions are used). You should limit + # the possible formats you serve. + # + # This is possible with the +provides+ condition: + # + # get '/', :provides => [:html, :json, :xml, :atom] do + # respond_with :index, :name => 'example' + # end + # + # However, since you have to set +provides+ for every route, this extension + # adds an app global (class method) `respond_to`, that lets you define content + # types for all routes: + # + # respond_to :html, :json, :xml, :atom + # get('/a') { respond_with :index, :name => 'a' } + # get('/b') { respond_with :index, :name => 'b' } + # + # == Custom Types + # + # Use the +on+ method for defining actions for custom types: + # + # get '/' do + # respond_to do |f| + # f.xml { nokogiri :index } + # f.on('application/custom') { custom_action } + # f.on('text/*') { data.to_s } + # f.on('*/*') { "matches everything" } + # end + # end + # + # Definition order does not matter. + module RespondWith + class Format + def initialize(app) + @app, @map, @generic, @default = app, {}, {}, nil + end + + def on(type, &block) + @app.settings.mime_types(type).each do |mime| + case mime + when '*/*' then @default = block + when /^([^\/]+)\/\*$/ then @generic[$1] = block + else @map[mime] = block + end + end + end + + def finish + yield self if block_given? + mime_type = @app.content_type || + @app.request.preferred_type(@map.keys) || + @app.request.preferred_type || + 'text/html' + type = mime_type.split(/\s*;\s*/, 2).first + handlers = [@map[type], @generic[type[/^[^\/]+/]], @default].compact + handlers.each do |block| + if result = block.call(type) + @app.content_type mime_type + @app.halt result + end + end + @app.halt 500, "Unknown template engine" + end + + def method_missing(method, *args, &block) + return super if args.any? or block.nil? or not @app.mime_type(method) + on(method, &block) + end + end + + module Helpers + include Sinatra::JSON + + def respond_with(template, object = nil, &block) + object, template = template, nil unless Symbol === template + format = Format.new(self) + format.on "*/*" do |type| + exts = settings.ext_map[type] + exts << :xml if type.end_with? '+xml' + if template + args = template_cache.fetch(type, template) { template_for(template, exts) } + if args.any? + locals = { :object => object } + locals.merge! object.to_hash if object.respond_to? :to_hash + + renderer = args.first + options = args[1..-1] + [{:locals => locals}] + + halt send(renderer, *options) + end + end + if object + exts.each do |ext| + halt json(object) if ext == :json + next unless object.respond_to? method = "to_#{ext}" + halt(*object.send(method)) + end + end + false + end + format.finish(&block) + end + + def respond_to(&block) + Format.new(self).finish(&block) + end + + private + + def template_for(name, exts) + # in production this is cached, so don't worry too much about runtime + possible = [] + settings.template_engines[:all].each do |engine| + exts.each { |ext| possible << [engine, "#{name}.#{ext}"] } + end + + exts.each do |ext| + settings.template_engines[ext].each { |e| possible << [e, name] } + end + + possible.each do |engine, template| + klass = Tilt.default_mapping.template_map[engine.to_s] || + Tilt.lazy_map[engine.to_s].fetch(0, [])[0] + + find_template(settings.views, template, klass) do |file| + next unless File.exist? file + return settings.rendering_method(engine) << template.to_sym + end + end + [] # nil or false would not be cached + end + end + + def remap_extensions + ext_map.clear + Rack::Mime::MIME_TYPES.each { |e,t| ext_map[t] << e[1..-1].to_sym } + ext_map['text/javascript'] << 'js' + ext_map['text/xml'] << 'xml' + end + + def mime_type(*) + result = super + remap_extensions + result + end + + def respond_to(*formats) + @respond_to ||= nil + + if formats.any? + @respond_to ||= [] + @respond_to.concat formats + elsif @respond_to.nil? and superclass.respond_to? :respond_to + superclass.respond_to + else + @respond_to + end + end + + def rendering_method(engine) + return [engine] if Sinatra::Templates.method_defined? engine + return [:mab] if engine.to_sym == :markaby + [:render, :engine] + end + + private + + def compile!(verb, path, block, **options) + options[:provides] ||= respond_to if respond_to + super + end + + def self.jrubyify(engs) + not_supported = [:markdown] + engs.keys.each do |key| + engs[key].collect! { |eng| (eng == :yajl) ? :json_pure : eng } + engs[key].delete_if { |eng| not_supported.include?(eng) } + end + engs + end + + def self.engines + engines = { + :css => [:less, :sass, :scss], + :xml => [:builder, :nokogiri], + :js => [:coffee], + :html => [:erb, :erubi, :erubis, :haml, :hamlit, :slim, :liquid, :radius, + :mab, :markdown, :textile, :rdoc], + :all => (Sinatra::Templates.instance_methods.map(&:to_sym) + + [:mab] - [:find_template, :markaby]), + :json => [:yajl], + } + engines.default = [] + (defined? JRUBY_VERSION) ? jrubyify(engines) : engines + end + + def self.registered(base) + base.set :ext_map, Hash.new { |h,k| h[k] = [] } + base.set :template_engines, engines + base.remap_extensions + base.helpers Helpers + end + end + + register RespondWith + Delegator.delegate :respond_to +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/runner.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/runner.rb new file mode 100644 index 0000000..c1c59cc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/runner.rb @@ -0,0 +1,155 @@ +require 'open-uri' +require 'net/http' +require 'timeout' + +module Sinatra + # NOTE: This feature is experimental, and missing tests! + # + # Helps you spinning up and shutting down your own sinatra app. This is especially helpful for running + # real network tests against a sinatra backend. + # + # The backend server could look like the following (in test/server.rb). + # + # require "sinatra" + # + # get "/" do + # "Cheers from test server" + # end + # + # get "/ping" do + # "1" + # end + # + # Note that you need to implement a ping action for internal use. + # + # Next, you need to write your runner. + # + # require 'sinatra/runner' + # + # class Runner < Sinatra::Runner + # def app_file + # File.expand_path("../server.rb", __FILE__) + # end + # end + # + # Override Runner#app_file, #command, #port, #protocol and #ping_path for customization. + # + # **Don't forget to override #app_file specific to your application!** + # + # Wherever you need this test backend, here's how you manage it. The following example assumes you + # have a test in your app that needs to be run against your test backend. + # + # runner = ServerRunner.new + # runner.run + # + # # ..tests against localhost:4567 here.. + # + # runner.kill + # + # For an example, check https://github.com/apotonick/roar/blob/master/test/integration/runner.rb + class Runner + def app_file + File.expand_path("../server.rb", __FILE__) + end + + def run + @pipe = start + @started = Time.now + warn "#{server} up and running on port #{port}" if ping + end + + def kill + return unless pipe + Process.kill("KILL", pipe.pid) + rescue NotImplementedError + system "kill -9 #{pipe.pid}" + rescue Errno::ESRCH + end + + def get(url) + Timeout.timeout(1) { get_url("#{protocol}://127.0.0.1:#{port}#{url}") } + end + + def get_stream(url = "/stream", &block) + Net::HTTP.start '127.0.0.1', port do |http| + request = Net::HTTP::Get.new url + http.request request do |response| + response.read_body(&block) + end + end + end + + def get_response(url) + Net::HTTP.start '127.0.0.1', port do |http| + request = Net::HTTP::Get.new url + http.request request do |response| + response + end + end + end + + def log + @log ||= "" + loop { @log << pipe.read_nonblock(1) } + rescue Exception + @log + end + + private + attr_accessor :pipe + + def start + IO.popen(command) + end + + def command # to be overwritten + "bundle exec ruby #{app_file} -p #{port} -e production" + end + + def ping(timeout=30) + loop do + return if alive? + if Time.now - @started > timeout + $stderr.puts command, log + fail "timeout" + else + sleep 0.1 + end + end + end + + def alive? + 3.times { get(ping_path) } + true + rescue Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError, SystemCallError, OpenURI::HTTPError, Timeout::Error + false + end + + def ping_path # to be overwritten + '/ping' + end + + def port # to be overwritten + 4567 + end + + def protocol + "http" + end + + def get_url(url) + uri = URI.parse(url) + + return uri.read unless protocol == "https" + get_https_url(uri) + end + + def get_https_url(uri) + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_NONE + request = Net::HTTP::Get.new(uri.request_uri) + http.request(request).body + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/streaming.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/streaming.rb new file mode 100644 index 0000000..aa9e717 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/streaming.rb @@ -0,0 +1,246 @@ +require 'sinatra/base' + +module Sinatra + + # = Sinatra::Streaming + # + # Sinatra 1.3 introduced the +stream+ helper. This addon improves the + # streaming API by making the stream object imitate an IO object, turning + # it into a real Deferrable and making the body play nicer with middleware + # unaware of streaming. + # + # == IO-like behavior + # + # This is useful when passing the stream object to a library expecting an + # IO or StringIO object. + # + # get '/' do + # stream do |out| + # out.puts "Hello World!", "How are you?" + # out.write "Written #{out.pos} bytes so far!\n" + # out.putc(65) unless out.closed? + # out.flush + # end + # end + # + # == Better Middleware Handling + # + # Blocks passed to #map! or #map will actually be applied when streaming + # takes place (as you might have suspected, #map! applies modifications + # to the current body, while #map creates a new one): + # + # class StupidMiddleware + # def initialize(app) @app = app end + # + # def call(env) + # status, headers, body = @app.call(env) + # body.map! { |e| e.upcase } + # [status, headers, body] + # end + # end + # + # use StupidMiddleware + # + # get '/' do + # stream do |out| + # out.puts "still" + # sleep 1 + # out.puts "streaming" + # end + # end + # + # Even works if #each is used to generate an Enumerator: + # + # def call(env) + # status, headers, body = @app.call(env) + # body = body.each.map { |s| s.upcase } + # [status, headers, body] + # end + # + # Note that both examples violate the Rack specification. + # + # == Setup + # + # In a classic application: + # + # require "sinatra" + # require "sinatra/streaming" + # + # In a modular application: + # + # require "sinatra/base" + # require "sinatra/streaming" + # + # class MyApp < Sinatra::Base + # helpers Sinatra::Streaming + # end + module Streaming + def stream(*) + stream = super + stream.extend Stream + stream.app = self + env['async.close'].callback { stream.close } if env.key? 'async.close' + stream + end + + module Stream + + attr_accessor :app, :lineno, :pos, :transformer, :closed + alias tell pos + alias closed? closed + + def self.extended(obj) + obj.closed, obj.lineno, obj.pos = false, 0, 0 + obj.callback { obj.closed = true } + obj.errback { obj.closed = true } + end + + def <<(data) + raise IOError, 'not opened for writing' if closed? + + @transformer ||= nil + data = data.to_s + data = @transformer[data] if @transformer + @pos += data.bytesize + super(data) + end + + def each + # that way body.each.map { ... } works + return self unless block_given? + super + end + + def map(&block) + # dup would not copy the mixin + clone.map!(&block) + end + + def map!(&block) + @transformer ||= nil + + if @transformer + inner, outer = @transformer, block + block = proc { |value| outer[inner[value]] } + end + @transformer = block + self + end + + def write(data) + self << data + data.to_s.bytesize + end + + alias syswrite write + alias write_nonblock write + + def print(*args) + args.each { |arg| self << arg } + nil + end + + def printf(format, *args) + print(format.to_s % args) + end + + def putc(c) + print c.chr + end + + def puts(*args) + args.each { |arg| self << "#{arg}\n" } + nil + end + + def close_read + raise IOError, "closing non-duplex IO for reading" + end + + def closed_read? + true + end + + def closed_write? + closed? + end + + def external_encoding + Encoding.find settings.default_encoding + rescue NameError + settings.default_encoding + end + + def closed? + @closed + end + + def settings + app.settings + end + + def rewind + @pos = @lineno = 0 + end + + def not_open_for_reading(*) + raise IOError, "not opened for reading" + end + + alias bytes not_open_for_reading + alias eof? not_open_for_reading + alias eof not_open_for_reading + alias getbyte not_open_for_reading + alias getc not_open_for_reading + alias gets not_open_for_reading + alias read not_open_for_reading + alias read_nonblock not_open_for_reading + alias readbyte not_open_for_reading + alias readchar not_open_for_reading + alias readline not_open_for_reading + alias readlines not_open_for_reading + alias readpartial not_open_for_reading + alias sysread not_open_for_reading + alias ungetbyte not_open_for_reading + alias ungetc not_open_for_reading + private :not_open_for_reading + + def enum_not_open_for_reading(*) + not_open_for_reading if block_given? + enum_for(:not_open_for_reading) + end + + alias chars enum_not_open_for_reading + alias each_line enum_not_open_for_reading + alias each_byte enum_not_open_for_reading + alias each_char enum_not_open_for_reading + alias lines enum_not_open_for_reading + undef enum_not_open_for_reading + + def dummy(*) end + alias flush dummy + alias fsync dummy + alias internal_encoding dummy + alias pid dummy + undef dummy + + def seek(*) + 0 + end + + alias sysseek seek + + def sync + true + end + + def tty? + false + end + + alias isatty tty? + end + end + + helpers Streaming +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/test_helpers.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/test_helpers.rb new file mode 100644 index 0000000..6b5ad64 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/test_helpers.rb @@ -0,0 +1,216 @@ +require 'sinatra/base' +require 'rack' +begin + require 'rack/test' +rescue LoadError + abort 'Add rack-test to your Gemfile to use this module!' +end +require 'forwardable' + +module Sinatra + Base.set :environment, :test + + # Helper methods to ease testing your Sinatra application. Partly extracted + # from Sinatra. Testing framework agnostic. + module TestHelpers + # Test variant of session, which exposes a `global_env`. + class Session < Rack::Test::Session + def global_env + @global_env ||= {} + end + + private + + def default_env + super.merge global_env + end + end + + include Rack::Test::Methods + extend Forwardable + attr_accessor :settings + + # @!group Instance Methods delegated to last_response + + # @!method body + # + # Body of last_response + # + # @see http://www.rubydoc.info/github/rack/rack/master/Rack/Response#body-instance_method + # @return [String] body of the last response + + # @!method headers + # + # Headers of last_response + # + # @return [Hash] hash of the last response + + # @!method status + # + # HTTP status of last_response + # + # @return [Integer] HTTP status of the last response + + # @!method errors + # + # Errors of last_response + # + # @return [Array] errors of the last response + def_delegators :last_response, :body, :headers, :status, :errors + # @!endgroup + + # @!group Class Methods delegated to app + + # @!method configure(*envs) {|_self| ... } + # @!scope class + # @yieldparam _self [Sinatra::Base] the object that the method was called on + # + # Set configuration options for Sinatra and/or the app. Allows scoping of + # settings for certain environments. + + # @!method set(option, value = (not_set = true), ignore_setter = false, &block) + # @!scope class + # Sets an option to the given value. If the value is a proc, the proc will + # be called every time the option is accessed. + # @raise [ArgumentError] + + # @!method enable(*opts) + # @!scope class + # + # Same as calling `set :option, true` for each of the given options. + + # @!method disable(*opts) + # @!scope class + # + # Same as calling `set :option, false` for each of the given options. + + # @!method use(middleware, *args, &block) + # @!scope class + # Use the specified Rack middleware + + # @!method helpers(*extensions, &block) + # @!scope class + # + # Makes the methods defined in the block and in the Modules given in + # `extensions` available to the handlers and templates. + + # @!method register(*extensions, &block) + # @!scope class + # Register an extension. Alternatively take a block from which an + # extension will be created and registered on the fly. + + def_delegators :app, :configure, :set, :enable, :disable, :use, :helpers, :register + # @!endgroup + + # @!group Instance Methods delegated to current_session + + # @!method env_for(uri = "", opts = {}) + # + # Return the Rack environment used for a request to `uri`. + # + # @return [Hash] + def_delegators :current_session, :env_for + # @!endgroup + + # @!group Instance Methods delegated to rack_mock_session + # @!method cookie_jar + # + # Returns a {http://www.rubydoc.info/github/rack-test/rack-test/Rack/Test/CookieJar Rack::Test::CookieJar}. + # + # @return [Rack::Test::CookieJar] + def_delegators :rack_mock_session, :cookie_jar + + # @!endgroup + + # Instantiate and configure a mock Sinatra app. + # + # Takes a `base` app class, or defaults to Sinatra::Base, and instantiates + # an app instance. Any given code in `block` is `class_eval`'d on this new + # instance before the instance is returned. + # + # @param base [Sinatra::Base] App base class + # + # @return [Sinatra] Configured mocked app + def mock_app(base = Sinatra::Base, &block) + inner = nil + @app = Sinatra.new(base) do + inner = self + class_eval(&block) + end + @settings = inner + app + end + + # Replaces the configured app. + # + # @param base [Sinatra::Base] a configured app + def app=(base) + @app = base + end + + alias set_app app= + + # Returns a Rack::Lint-wrapped Sinatra app. + # + # If no app has been configured, a new subclass of Sinatra::Base will be + # used and stored. + # + # (Rack::Lint validates your application and the requests and + # responses according to the Rack spec.) + # + # @return [Sinatra::Base] + def app + @app ||= Class.new Sinatra::Base + Rack::Lint.new @app + end + + unless method_defined? :options + # Processes an OPTIONS request in the context of the current session. + # + # @param uri [String] + # @param params [Hash] + # @param env [Hash] + def options(uri, params = {}, env = {}, &block) + env = env_for(uri, env.merge(:method => "OPTIONS", :params => params)) + current_session.send(:process_request, uri, env, &block) + end + end + + unless method_defined? :patch + # Processes a PATCH request in the context of the current session. + # + # @param uri [String] + # @param params [Hash] + # @param env [Hash] + def patch(uri, params = {}, env = {}, &block) + env = env_for(uri, env.merge(:method => "PATCH", :params => params)) + current_session.send(:process_request, uri, env, &block) + end + end + + # @return [Boolean] + def last_request? + last_request + true + rescue Rack::Test::Error + false + end + + # @raise [Rack::Test:Error] If sessions are not enabled for app + # @return [Hash] Session of last request, or the empty Hash + def session + return {} unless last_request? + raise Rack::Test::Error, "session not enabled for app" unless last_env["rack.session"] or app.session? + last_request.session + end + + # @return The env of the last request + def last_env + last_request.env + end + + def build_rack_test_session(name) # :nodoc: + Session.new rack_mock_session(name) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/webdav.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/webdav.rb new file mode 100644 index 0000000..6529c8b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/lib/sinatra/webdav.rb @@ -0,0 +1,93 @@ +require 'sinatra/base' + +module Sinatra + + # = Sinatra::WebDAV + # + # This extensions provides WebDAV verbs, as defined by RFC 4918 + # (https://tools.ietf.org/html/rfc4918). To use this in your app, + # just +register+ it: + # + # require 'sinatra/base' + # require 'sinatra/webdav' + # + # class Application < Sinatra::Base + # register Sinatra::WebDAV + # + # # Now you can use any WebDAV verb: + # propfind '/2014/january/21' do + # 'I have a lunch at 9 PM' + # end + # end + # + # You can use it in classic application just by requring the extension: + # + # require 'sinatra' + # require 'sinatra/webdav' + # + # mkcol '/2015' do + # 'You started 2015!' + # end + # + module WebDAV + def self.registered(_) + Sinatra::Request.include WebDAV::Request + end + + module Request + def self.included(base) + base.class_eval do + alias _safe? safe? + alias _idempotent? idempotent? + + def safe? + _safe? or propfind? + end + + def idempotent? + _idempotent? or propfind? or move? or unlock? # or lock? + end + end + end + + def propfind? + request_method == 'PROPFIND' + end + + def proppatch? + request_method == 'PROPPATCH' + end + + def mkcol? + request_method == 'MKCOL' + end + + def copy? + request_method == 'COPY' + end + + def move? + request_method == 'MOVE' + end + + #def lock? + # request_method == 'LOCK' + #end + + def unlock? + request_method == 'UNLOCK' + end + end + + def propfind(path, opts = {}, &bk) route 'PROPFIND', path, opts, &bk end + def proppatch(path, opts = {}, &bk) route 'PROPPATCH', path, opts, &bk end + def mkcol(path, opts = {}, &bk) route 'MKCOL', path, opts, &bk end + def copy(path, opts = {}, &bk) route 'COPY', path, opts, &bk end + def move(path, opts = {}, &bk) route 'MOVE', path, opts, &bk end + #def lock(path, opts = {}, &bk) route 'LOCK', path, opts, &bk end + def unlock(path, opts = {}, &bk) route 'UNLOCK', path, opts, &bk end + end + + register WebDAV + Delegator.delegate :propfind, :proppatch, :mkcol, :copy, :move, :unlock # :lock +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/sinatra-contrib.gemspec b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/sinatra-contrib.gemspec new file mode 100644 index 0000000..e969e3e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-contrib-2.2.0/sinatra-contrib.gemspec @@ -0,0 +1,65 @@ +# -*- encoding: utf-8 -*- + +version = File.read(File.expand_path("../../VERSION", __FILE__)).strip + +Gem::Specification.new do |s| + s.name = "sinatra-contrib" + s.version = version + s.description = "Collection of useful Sinatra extensions" + s.homepage = "http://sinatrarb.com/contrib/" + s.license = "MIT" + s.summary = s.description + s.authors = ["https://github.com/sinatra/sinatra/graphs/contributors"] + s.email = "sinatrarb@googlegroups.com" + s.files = Dir["lib/**/*.rb"] + [ + "LICENSE", + "README.md", + "Rakefile", + "ideas.md", + "sinatra-contrib.gemspec" + ] + + if s.respond_to?(:metadata) + s.metadata = { + 'source_code_uri' => 'https://github.com/sinatra/sinatra/tree/master/sinatra-contrib', + 'homepage_uri' => 'http://sinatrarb.com/contrib/', + 'documentation_uri' => 'https://www.rubydoc.info/gems/sinatra-contrib' + } + else + raise <<-EOF +RubyGems 2.0 or newer is required to protect against public gem pushes. You can update your rubygems version by running: + gem install rubygems-update + update_rubygems: + gem update --system +EOF + end + + s.required_ruby_version = '>= 2.3.0' + + s.add_dependency "sinatra", version + s.add_dependency "mustermann", "~> 1.0" + s.add_dependency "tilt", "~> 2.0" + s.add_dependency "rack-protection", version + s.add_dependency "multi_json" + + s.add_development_dependency "rspec", "~> 3.4" + s.add_development_dependency "haml" + s.add_development_dependency "erubi" + s.add_development_dependency "erubis" + s.add_development_dependency "slim" + s.add_development_dependency "less" + s.add_development_dependency "sass" + s.add_development_dependency "builder" + s.add_development_dependency "liquid" + s.add_development_dependency "redcarpet" + s.add_development_dependency "RedCloth", "~> 4.2.9" + s.add_development_dependency "asciidoctor" + s.add_development_dependency "radius" + s.add_development_dependency "coffee-script" + s.add_development_dependency "nokogiri" + s.add_development_dependency "creole" + s.add_development_dependency "wikicloth" + s.add_development_dependency "markaby" + s.add_development_dependency "rake", "< 11" + s.add_development_dependency "rack-test" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/.document b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/.document new file mode 100644 index 0000000..dc6a67d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/.document @@ -0,0 +1,5 @@ +README.markdown +lib/**/*.rb +bin/* +features/**/*.feature +LICENSE.markdown diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/.gitignore b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/.gitignore new file mode 100644 index 0000000..c1e0daf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/.gitignore @@ -0,0 +1,21 @@ +## MAC OS +.DS_Store + +## TEXTMATE +*.tmproj +tmtags + +## EMACS +*~ +\#* +.\#* + +## VIM +*.swp + +## PROJECT::GENERAL +coverage +rdoc +pkg + +## PROJECT::SPECIFIC diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/LICENSE.markdown b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/LICENSE.markdown new file mode 100644 index 0000000..7fbedc4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/LICENSE.markdown @@ -0,0 +1,113 @@ +The Don't Be a Dick License +=========================== +_version 0.2_ + +**Project:** [Sinatra::Flash](http://github.com/SFEley/sinatra-flash) +**Author:** Stephen Eley () + +This is a proposed draft of the **Don't Be a Dick** license for open source projects. The purpose of this license is to permit the broadest feasible scope for reuse and modification of creative work, restricted only by the requirement that one is not a dick about it. + +1. Legal Parameters +------------------- +For legal purposes, the DBAD license is a superset of the [Apache License, Version 2.0][1] and incorporates all terms, conditions, privileges and limitations therein. The following text is a binding part of this license for this project: + +> Copyright 2010 Stephen Eley + +> Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + +> + +> Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Nothing in the following text should be construed to inhibit, contradict, or override any part of the Apache License, Version 2.0. + +2. Definitions +-------------- +The following terms and definitions shall be in effect for the rest of this document. + +> **NOTE:** Singular nouns and pronouns are used throughout this License for + grammatical convenience. However, any of the terms below _may_ refer to a + collective work or group of people. If this pegs your punctiliousness, you + are directed to mentally substitute "Person _or persons_," "Dick _or + dicks,_" etc., throughout this license. Just don't tell us about it. + +### A. Project + +A creative work of (software | writing | visual art | music) into which significant time and energy have been invested by people who _are not you,_ and which has been released into the world for the benefit of the general public (_including you._) + +The **Project** may include, incorporate, derive from, or be inspired by other works. The Author, being a Reasonable Person, has made use of such source materials only as permitted by their own licenses or applicable law. The License you are reading applies only to those portions of the Project which are original and distinct to it. Source materials may be covered by their own licenses or conditions, and should not be assumed to have coverage under this License. (However, you are strongly encouraged not to be a dick about them either.) + +### B. Author + +A person who has invested significant time and energy into the Project licensed herein. Given the Author's release of the Project to the world under a liberal license, the Author is declared a Reasonable Person (at least within this context) and inherits all attributes, freedoms, and responsibilities thereof. No other assumptions are made about the Author, nor should you make any. + +### C. Reasonable Person + +A person who respects the time and energy that have been invested in the Project licensed herein, and acts accordingly. A Reasonable Person is broadly characterized as one who exercises his or her privilege to use, _not_ use, redistribute, modify, improve, worsen, review, report issues upon, participate in the community of, or ignore the work _without_ placing undue demands upon the Author. I.e., a Reasonable Person is a constituent of the majority of open source users and the population at large who are not Dicks. + +### D. Dick + +A person who _does not_ respect the time and energy that have been invested in the Project, and acts to punish such effort by giving others associated with the Project -- including, but not limited to, the Author -- a hard time. A Dick is nearly always selfish, but not necessarily with deliberate intent; some Dicks are merely thoughtless. The distinguishing characteristic of a Dick is that he or she places burdens upon Reasonable People, reducing their motivation to engage in open source activities. This damping effect is a significant detriment to the Project, to open source in general, to the production of new intellectual value in the world -- and, ultimately, to the Dick himself or herself. + +> **NOTE:** Despite its original gender association, the word "Dick" is used herein in a _cultural_ context and not a _genital_ context. This License has chosen to adopt the term for its linguistic force and psychological impact, and sincerely regrets any inference of sexism. For purposes of the terms and conditions contained herein, it is understood that both men and women are equally capable of being Dicks. + +> (But they shouldn't be.) + +3. Permissions +-------------- + +The following privileges are granted explicitly and exclusively to Reasonable People. Although the Author acknowledges the practical unfeasibility of barring Dicks from enjoying the same privileges, they are nevertheless asked to refrain from any activity related to the Project _and/or_ to reconsider their behavior and stop being Dicks. + +1. You are permitted to use the Project or any component of the Project. + +2. You are permitted to redistribute the Project or any component of the Project, by itself or as part of a different work, provided that you give fair and reasonable credit back to the Author. + +3. You are permitted to change the Project for your own needs or anyone else's. You may keep your changes to yourself or submit them back to the Author or the community, as you see fit, provided you are not a Dick about it. + +4. You are permitted and encouraged to participate in any community related to the Project, or to create new communities. + +5. You are permitted to report issues or problems with the Project, and to request that they be addressed, so long as the request is made in a reasonable fashion. (This privilege does _not_ oblige the Author to respond.) + +6. You are permitted to make money from the Project. No recompense is owed to the Author unless by separate agreement, although sharing opportunities for mutual benefit is by no means discouraged. + +7. You are permitted to discuss the Project in any medium, in any positive or negative spirit, so long as criticism is not libelous nor _ad hominem._ (I.e., don't lie, and keep it about the _work_ and not the _people._) + +8. You are permitted to ignore the Project completely and make no use of it whatsoever. This right is irrevocable and absolute, and extended to Dicks and Reasonable People alike. + +4. Limitations +-------------- + +The following restrictions are imposed explicitly and exclusively upon Dicks. These limitations are the inverse of the above privileges and are also tautological, as the prohibited actions are those _definitive_ of Dickhood. + +1. You may not impede Reasonable People from exercising their privilege to use, redistribute, change, participate in, profit from, discuss, or ignore the Project. + +2. You may not withhold the Author's credit for the Project, nor otherwise present the work of anyone else as your own. + +3. You may not hold the Author responsible for any use or abuse of the Project by you or anyone else. + +4. You may not troll, flame, nor dumb down any community associated with the Project. + +5. Barring separate agreements, you may not _demand_ any time or attention on the part of the Author nor anyone else in the community. You may not hold the Author personally accountable for any issues you discover nor otherwise spread your own problems to other people. + +6. You may not attempt to _compel_ time nor money from the Author nor any other community member by any means, including but not limited to legal action, intimidation, or annoyance. + +7. You may not engage in _ad hominem_ (i.e. personal) attacks or criticism of the Author in the course of criticizing the Project. + +8. You may not impede the absolute and irrevocable privilege of the Author and other members of the community to ignore you. + +5. Use of This License +---------------------- +The Don't Be a Dick License is released under the terms of the Don't Be a Dick License. Projects released under this License should remain under the License, and the terms of the License may not be modified by anyone other than the Project's original Author. + +If you wish to make use of the License for your own open work, you may do so without asking permission, provided said work is truly your own, truly open, and you are truly not a Dick. You may modify the terms of the License to suit your own needs, but are strongly advised to annotate said changes. Modifications may not reduce the freedoms granted to Reasonable People as described in Section 3. + +Reasonable People are _invited,_ but not compelled, to visit the Web site at and browse or add their project to the repository of works released under the License. + + +[1]: http://apache.org/licenses/LICENSE-2.0 \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/README.markdown b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/README.markdown new file mode 100644 index 0000000..3c3ab6f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/README.markdown @@ -0,0 +1,164 @@ +Sinatra::Flash +============== +This is an implementation of show-'em-once 'flash' messages for the [Sinatra][1] Web framework. It offers the following feature set: + +* Simplicity (less than 50 significant lines of code) +* Implements the documented [behavior][3] and [public API][4] of the Rails flash that many developers are used to +* Acts entirely like a hash, including iterations and merging +* Optional multiple named flash collections, each with their own message hash, so that different embedded applications can access different sets of messages +* An HTML helper for displaying flash messages with CSS styling +* Verbose documentation in [YARD][5] format +* Full RSpec tests + +The primary catch for experienced Rack developers is that it _does not_ function as standalone Rack middleware. (You could get to the messages inside the session if you needed to, but the message rotation occurs in a Sinatra `after` hook.) It should function just fine across multiple Sinatra apps, but if you need flash that's accessible from non-Sinatra applications, consider the [Rack::Flash][2] middleware. + +Setting Up +---------- +You should know this part: + + $ gem install sinatra-flash + +(Or `sudo gem install` if you're the last person on Earth who isn't using [RVM][6] yet.) + +If you're developing a Sinatra ['classic'][7] application, then all you need to do is enable sessions and require the library: + + # blah_app.rb + require 'sinatra' + require 'sinatra/flash' + + enable :sessions + + post '/blah' do + # This message won't be seen until the NEXT Web request that accesses the flash collection + flash[:blah] = "You were feeling blah at #{Time.now}." + + # Accessing the flash displays messages set from the LAST request + "Feeling blah again? That's too bad. #{flash[:blah]}" + end + +If you're using the [Sinatra::Base][7] style, you also need to register the extension: + + # bleh_app.rb + require 'sinatra/base' + require 'sinatra/flash' + + class BlehApp < Sinatra::Base + enable :sessions + register Sinatra::Flash + + get '/bleh' do + if flash[:blah] + # The flash collection is cleared after any request that uses it + "Have you ever felt blah? Oh yes. #{flash[:blah]} Remember?" + else + "Oh, now you're only feeling bleh?" + end + end + end + +See the Sinatra documentation on [using extensions][8] for more detail and rationale. + +styled_flash +------------ +The gem comes with a handy view helper that iterates through current flash messages and renders them in styled HTML: + + # Using HAML, 'cause the cool kids are all doing it + %html + %body + =styled_flash + +Yields (assuming three flash messages with different keys): + + + +
+
I'm sorry, Dave. I'm afraid I can't do that.
+
This mission is too important for me to allow you to jeopardize it.
+
Without your space helmet, Dave, you're going to find reaching the emergency airlock rather difficult.
+
+ + + +Styling the CSS for the #flash id, the .flash class, or any of the key-based classes is entirely up to you. + +(_Side note:_ This view helper was my initial reason for making this gem. I'd gotten used to pasting this little method in on every Rails project, and when I switched to Sinatra was distraught to discover that [Rack::Flash][2] couldn't do it, because the FlashHash isn't really a hash and you can't iterate it. Reinventing flash was sort of a side effect.) + +Advanced Tips +------------- +### Now vs. Next +The flash object acts like a hash, but it's really _two_ hashes: + +* The **now** hash displays messages for the current request. +* The **next** hash stores messages to be displayed in the _next_ request. + +When you access the **flash** helper, the _now_ hash is initialized from a session value. (Named `:flash` by default, but see 'Scoped Flash' below.) Every method except assignment (`[]=`) is delegated to _now_; assignments occur on the _next_ hash. At the end of the request, a Sinatra `after` hook sets the session value to the _next_ hash, effectively rotating it to _now_ for the next request that uses it. + +This is usually what you want, and you don't have to worry about the details. However, you occasionally want to set a message to display during _this_ request, or access values that are coming up. In these cases you can access the `.now` and `.next` hashes directly: + + # This will be displayed during the current request + flash.now[:error] = "We're shutting down now. Goodbye!" + + # Look at messages upcoming in the next request + @weapon = Stake.new if flash.next[:warning] == "The vampire is attacking." + +In practice, you'll probably want to set `.now` any time you're displaying errors with an immediate render instead of redirecting. It's hard to think of a common reason to check `.next` -- but it's there if you want it. + +### Keep, Discard, and Sweep +These convenience methods allow you to modify the standard rotation cycle, and are based directly on the [Rails flash API][4]: + + flash.keep # Will show all messages again + flash.keep(:groundhog) # Will show the message on key :groundhog again + flash.discard # Clears the next messages without showing them + flash.discard(:amnesia) # Clears only the message on key :amnesia + flash.sweep # Rotates the flash manually, discarding _now_ and moving _next_ into its place + +### Sessions +The basic _concept_ of flash messages relies on having an active session for your application. Sinatra::Flash is built on the assumption that Sinatra's `session` helper points to something that will persist beyond the current request. You are responsible for ensuring that it does. No other assumptions are made about the session -- you can use any [session strategy][17] you like. + +(**Note:** Early versions of this extension attempted to detect the absence of a session and create one for you at the last moment. Thanks to [rkh][15] for [pointing out][16] that this is unreliable in Sinatra. You'll have to be a grownup now ) + +### Scoped Flash +If one flash collection isn't exciting enough for your application stack, you can have multiple sets of flash messages scoped by a symbol. Each has its own lifecycle and will _not_ be rotated by any Web request that ignores it. + + get "/complicated" do + flash(:one)[:hello] = "This will appear the next time flash(:one) is called" + flash(:two).discard(:hello) # Clear a message someone else set on flash(:two) + "A message for you on line three: #{flash(:three)[:hello]}" + end + +Both the **flash** and **styled_flash** helper methods accept such keys as optional parameters. If don't specify one, the default key is `:flash`. Whatever keys you use will become session keys as well, so take heed that you don't run into naming conflicts. + +Do you need this? Probably not. The principal use case is for complex application stacks in which some messages are only relevant within specific subsystems. If you _do_ use it, be sure to model your message flows carefully, and don't confuse collection keys with message keys. + +Credit, Support, and Contributions +---------------------------------- +This extension is the fault of **Stephen Eley**. You can reach me at . If you like science fiction stories, I know a [good podcast][9] for them as well. + +If you find bugs, please report them on the [Github issue tracker][10]. + +The documentation can of course be found on [RDoc.info][11]. + +Contributions are welcome. I'm not sure how much more _must_ be done on a flash message extension, but I'm sure there's plenty that _could_ be done. Please note that the test suite uses RSpec, and you'll need the [Sessionography][14] helper for testing sessions. (I actually developed Sessionography in order to TDD _this_ gem.) + +License +------- +This project is licensed under the **Don't Be a Dick License**, version 0.2, and is copyright 2010 by Stephen Eley. See the [LICENSE.markdown][12] file or the [DBAD License site][13] for elaboration on not being a dick. + + +[1]: http://sinatrarb.com +[2]: http://nakajima.github.com/rack-flash/ +[3]: http://api.rubyonrails.org/classes/ActionController/Flash.html +[4]: http://api.rubyonrails.org/classes/ActionController/Flash/FlashHash.html +[5]: http://yardoc.org +[6]: http://rvm.beginrescueend.com +[7]: https://sinatra.lighthouseapp.com/projects/9779/tickets/240-sinatrabase-vs-sinatradefault-vs-sinatraapplication +[8]: http://www.sinatrarb.com/extensions-wild.html +[9]: http://escapepod.org +[10]: http://github.com/SFEley/sinatra-flash/issues +[11]: http://rdoc.info/projects/SFEley/sinatra-flash +[12]: http://github.com/SFEley/sinatra-flash/blob/master/LICENSE.markdown +[13]: http://dbad-license.org +[14]: http://github.com/SFEley/sinatra-sessionography +[15]: http://github.com/rkh +[16]: http://github.com/SFEley/sinatra-flash/issues/issue/1 +[17]: http://www.sinatrarb.com/faq.html#sessions diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/Rakefile b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/Rakefile new file mode 100644 index 0000000..b10f7af --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/Rakefile @@ -0,0 +1,48 @@ +require 'rubygems' +require 'rake' + +begin + require 'jeweler' + Jeweler::Tasks.new do |gem| + gem.name = "sinatra-flash" + gem.summary = %Q{Proper flash messages in Sinatra} + gem.description = %Q{A Sinatra extension for setting and showing Rails-like flash messages. This extension improves on the Rack::Flash gem by being simpler to use, providing a full range of hash operations (including iterating through various flash keys, testing the size of the hash, etc.), and offering a 'styled_flash' view helper to render the entire flash hash with sensible CSS classes. The downside is reduced flexibility -- these methods will *only* work in Sinatra.} + gem.email = "sfeley@gmail.com" + gem.homepage = "http://github.com/SFEley/sinatra-flash" + gem.authors = ["Stephen Eley"] + gem.add_dependency "sinatra", ">= 1.0.0" + gem.add_development_dependency "rspec", ">= 1.2.9" + gem.add_development_dependency "yard", ">= 0" + gem.add_development_dependency "sinatra-sessionography" + # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings + end + Jeweler::GemcutterTasks.new +rescue LoadError + puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" +end + +require 'spec/rake/spectask' +Spec::Rake::SpecTask.new(:spec) do |spec| + spec.libs << 'lib' << 'spec' + spec.spec_files = FileList['spec/**/*_spec.rb'] +end + +Spec::Rake::SpecTask.new(:rcov) do |spec| + spec.libs << 'lib' << 'spec' + spec.pattern = 'spec/**/*_spec.rb' + spec.rcov = true +end + +task :spec => :check_dependencies + +task :default => :spec + +begin + require 'yard' + YARD::Rake::YardocTask.new +rescue LoadError + task :yardoc do + abort "YARD is not available. In order to run yardoc, you must: sudo gem install yard" + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/VERSION b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/VERSION new file mode 100644 index 0000000..0d91a54 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/VERSION @@ -0,0 +1 @@ +0.3.0 diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash.rb new file mode 100644 index 0000000..07b07ff --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash.rb @@ -0,0 +1,21 @@ +require 'sinatra/base' +require 'sinatra/flash/storage' +require 'sinatra/flash/style' + + +module Sinatra + module Flash + + def self.registered(app) + app.helpers Flash::Storage + app.helpers Flash::Style + + # This callback rotates any flash structure we referenced, placing the 'next' hash into the session + # for the next request. + app.after {@flash.each{|key, flash| session[key] = @flash[key].next} if @flash} + end + + end + + register Flash +end \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash/hash.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash/hash.rb new file mode 100644 index 0000000..6e20641 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash/hash.rb @@ -0,0 +1,49 @@ +require 'delegate' + +module Sinatra + module Flash + + # A subclass of Hash that "remembers forward" by exactly one action. + # Tastes just like the API of Rails's ActionController::Flash::FlashHash, but with fewer calories. + class FlashHash < DelegateClass(Hash) + attr_reader :now, :next + + # Builds a new FlashHash. It takes the hash for this action's values as an initialization variable. + def initialize(session) + @now = session || Hash.new + @next = Hash.new + super(@now) + end + + # We assign to the _next_ hash, but retrieve values from the _now_ hash. Freaky, huh? + def []=(key, value) + self.next[key] = value + end + + # Swaps out the current flash for the future flash, then returns it. + def sweep + @now.replace(@next) + @next = Hash.new + @now + end + + # Keep all or one of the current values for next time. + def keep(key=nil) + if key + @next[key] = @now[key] + else + @next.merge!(@now) + end + end + + # Tosses any values or one value before next time. + def discard(key=nil) + if key + @next.delete(key) + else + @next = Hash.new + end + end + end + end +end \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash/storage.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash/storage.rb new file mode 100644 index 0000000..26ee86e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash/storage.rb @@ -0,0 +1,23 @@ +require 'sinatra/flash/hash' + +module Sinatra + module Flash + module Storage + + # The main Sinatra helper for accessing the flash. You can have multiple flash collections (e.g., + # for different apps in your Rack stack) by passing a symbol to it. + # + # @param [optional, String, Symbol] key Specifies which key in the session contains the hash + # you want to reference. Defaults to ':flash'. If there is no session or the key is not found, + # an empty hash is used. Note that this is only used in the case of multiple flash _collections_, + # which is rarer than multiple flash messages. + # + # @return [FlashHash] Assign to this like any other hash. + def flash(key=:flash) + @flash ||= {} + @flash[key.to_sym] ||= FlashHash.new((session ? session[key.to_sym] : {})) + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash/style.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash/style.rb new file mode 100644 index 0000000..f09c65e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/lib/sinatra/flash/style.rb @@ -0,0 +1,33 @@ +module Sinatra + module Flash + module Style + + # A view helper for rendering flash messages to HTML with reasonable CSS structure. Handles + # multiple flash messages in one request. Wraps them in a
tag with id #flash containing + # a
for each message with classes of .flash and the message type. E.g.: + # + # @example + #
+ #
Today is Tuesday, April 27th.
+ #
Missiles are headed to destroy the Earth!
+ #
+ # + # It is your responsibility to style these classes the way you want in your stylesheets. + # + # @param[optional, String, Symbol] key Specifies which flash collection you want to display. + # If you use this, the collection key will be appended to the top-level div id (e.g., + # 'flash_login' if you pass a key of :login). + # + # @return [String] Styled HTML if the flash contains messages, or an empty string if it's empty. + def styled_flash(key=:flash) + return "" if flash(key).empty? + id = (key == :flash ? "flash" : "flash_#{key}") + messages = flash(key).collect {|message| "
#{message[1]}
\n"} + "
\n" + messages.join + "
" + end + + end + end +end + + diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/sinatra-flash.gemspec b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/sinatra-flash.gemspec new file mode 100644 index 0000000..8b48c9a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/sinatra-flash.gemspec @@ -0,0 +1,73 @@ +# Generated by jeweler +# DO NOT EDIT THIS FILE DIRECTLY +# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command +# -*- encoding: utf-8 -*- + +Gem::Specification.new do |s| + s.name = %q{sinatra-flash} + s.version = "0.3.0" + + s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= + s.authors = ["Stephen Eley"] + s.date = %q{2010-05-02} + s.description = %q{A Sinatra extension for setting and showing Rails-like flash messages. This extension improves on the Rack::Flash gem by being simpler to use, providing a full range of hash operations (including iterating through various flash keys, testing the size of the hash, etc.), and offering a 'styled_flash' view helper to render the entire flash hash with sensible CSS classes. The downside is reduced flexibility -- these methods will *only* work in Sinatra.} + s.email = %q{sfeley@gmail.com} + s.extra_rdoc_files = [ + "LICENSE.markdown", + "README.markdown" + ] + s.files = [ + ".document", + ".gitignore", + "LICENSE.markdown", + "README.markdown", + "Rakefile", + "VERSION", + "lib/sinatra/flash.rb", + "lib/sinatra/flash/hash.rb", + "lib/sinatra/flash/storage.rb", + "lib/sinatra/flash/style.rb", + "sinatra-flash.gemspec", + "spec/base_spec.rb", + "spec/flash/hash_spec.rb", + "spec/flash/style_spec.rb", + "spec/flash_spec.rb", + "spec/spec.opts", + "spec/spec_helper.rb" + ] + s.homepage = %q{http://github.com/SFEley/sinatra-flash} + s.rdoc_options = ["--charset=UTF-8"] + s.require_paths = ["lib"] + s.rubygems_version = %q{1.3.6} + s.summary = %q{Proper flash messages in Sinatra} + s.test_files = [ + "spec/base_spec.rb", + "spec/flash/hash_spec.rb", + "spec/flash/style_spec.rb", + "spec/flash_spec.rb", + "spec/spec_helper.rb" + ] + + if s.respond_to? :specification_version then + current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION + s.specification_version = 3 + + if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then + s.add_runtime_dependency(%q, [">= 1.0.0"]) + s.add_development_dependency(%q, [">= 1.2.9"]) + s.add_development_dependency(%q, [">= 0"]) + s.add_development_dependency(%q, [">= 0"]) + else + s.add_dependency(%q, [">= 1.0.0"]) + s.add_dependency(%q, [">= 1.2.9"]) + s.add_dependency(%q, [">= 0"]) + s.add_dependency(%q, [">= 0"]) + end + else + s.add_dependency(%q, [">= 1.0.0"]) + s.add_dependency(%q, [">= 1.2.9"]) + s.add_dependency(%q, [">= 0"]) + s.add_dependency(%q, [">= 0"]) + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/base_spec.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/base_spec.rb new file mode 100644 index 0000000..8854b24 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/base_spec.rb @@ -0,0 +1,50 @@ +require File.dirname(__FILE__) + '/spec_helper' +require 'sinatra/base' + +class BaseApp < Sinatra::Base + helpers Sinatra::Sessionography + register Sinatra::Flash + + + get '/flash' do + if params[:key] + flash(params[:key]).inspect + else + flash.inspect + end + end + + post '/flash' do + if (key = params.delete('key')) + params.each{|k,v| flash(key)[k.to_sym] = v.to_sym} + flash(key).inspect + else + params.each{|k,v| flash[k.to_sym] = v.to_sym} + flash.inspect + end + end + +end + +describe "Sinatra::Flash in a Sinatra::Base application" do + + def app + BaseApp + end + + before(:each) do + Sinatra::Sessionography.session = nil + end + + it "shows nothing when no flash has been set" do + get '/flash' + last_response.body.should == "{}" + end + + it "can set and retrieve the flash" do + post '/flash', {:foo => :bar} + get '/flash' + last_response.body.should == "{:foo=>:bar}" + end + +end \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/flash/hash_spec.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/flash/hash_spec.rb new file mode 100644 index 0000000..b6ff2c9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/flash/hash_spec.rb @@ -0,0 +1,88 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') + +module Sinatra::Flash + describe FlashHash do + before(:each) do + @flash = {:do => 'A deer, a female deer', :re => 'A drop of golden sun'} + @this = FlashHash.new(@flash) # Stubbing out the session with a simple hash + @this[:one] = "My thumb" + @this[:two] = "My shoe" + @this[:three] = "My knee" + end + + it "requires a session to be passed to it" do + lambda{FlashHash.new}.should raise_error(ArgumentError) + end + + it "acts just like a Hash" do + Hash.instance_methods.each do |method| + @this.should respond_to(method) + end + end + + it "knows its length" do + @this.length.should == 2 + end + + it "swaps its contents after one sweep" do + @this.sweep + @this.length.should == 3 + end + + it "gets rid of its contents after two sweeps" do + @this.sweep + @this.sweep + @this.should be_empty + end + + it "can discard the whole flash" do + @this.discard + @this.sweep + @this.should be_empty + end + + it "can discard just one key" do + @this.discard(:two) + @this.sweep + @this.length.should == 2 + end + + it "can keep the whole flash" do + @this.sweep + @this.keep + @this.sweep + @this.length.should == 3 + end + + it "can keep just one key" do + @this.sweep + @this.keep(:three) + @this.sweep + @this.length.should == 1 + end + + it "doesn't know the values you set right away" do + @this[:foo] = "bar" + @this[:foo].should be_nil + end + + it "knows the values you set next time" do + @this[:foo] = "bar" + @this.sweep + @this[:foo].should == "bar" + end + + it "can set values only for now" do + @this.now[:foo] = "bar" + @this[:foo].should == "bar" + end + + it "forgets values you set only for now next time" do + @this.now[:foo] = "bar" + @this.sweep + @this.now[:foo].should be_nil + end + + + end +end \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/flash/style_spec.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/flash/style_spec.rb new file mode 100644 index 0000000..cdf8734 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/flash/style_spec.rb @@ -0,0 +1,43 @@ +require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') +require 'sinatra/flash/style' + +describe 'styled_flash method' do + include Sinatra::Sessionography # for the 'session' method + include Sinatra::Flash::Storage + include Sinatra::Flash::Style + + before(:each) do + Sinatra::Sessionography.session = {:flash => {:foo=>:bar, :too=>'tar'}, + :smash => {:yoo=>:yar, :zoo=>'zar'}} + end + + it "returns an empty string if the flash is empty" do + Sinatra::Sessionography.session = {} + styled_flash.should == "" + end + + it "returns a div of #flash if the structure is the default" do + styled_flash.should =~ /
/ + end + + it "contains each key as a class" do + styled_flash.should =~ /
bar<\/div>/ + styled_flash.should =~ /
tar<\/div>/ + end + + describe "if a key is passed" do + it "returns an empty string if that structure is empty" do + styled_flash(:trash).should == "" + end + + it "returns a div containing the key name if a key is passed" do + styled_flash(:smash).should =~ /
/ + end + + it "returns each of the keys within that key as a class" do + styled_flash(:smash).should =~ /
yar<\/div>/ + styled_flash(:smash).should =~ /
zar<\/div>/ + end + + end +end \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/flash_spec.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/flash_spec.rb new file mode 100644 index 0000000..a395abb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/flash_spec.rb @@ -0,0 +1,67 @@ +require File.expand_path(File.dirname(__FILE__) + '/spec_helper') + +# See the spec_helper for the 'app' that we're testing. +describe Sinatra::Flash do + before(:each) do + Sinatra::Sessionography.session = { + :flash => {:marco => :polo}, + :smash => {:applecore => :baltimore}} + end + + it "provides a 'flash' helper" do + get '/flash' + last_response.body.should =~ /\{.*\}/ + end + + it "looks up the :flash variable in the session by default" do + get '/flash' + last_response.body.should == "{:marco=>:polo}" + end + + it "is empty, not nil, if there's no session" do + Sinatra::Sessionography.session = nil + get '/flash' + last_response.body.should == "{}" + end + + it "can take a different flash key" do + get '/flash', {:key => :smash} + last_response.body.should == "{:applecore=>:baltimore}" + end + + it "is empty, not nil, if the session doesn't have the flash key" do + get '/flash', {:key => :trash} + last_response.body.should == "{}" + end + + it "can set the flash for the future" do + post '/flash', {:fire => :ice} + last_response.body.should == "{:marco=>:polo}" + end + + it "knows the future flash" do + post '/flash', {:fire => :ice} + get '/flash' + last_response.body.should == "{:fire=>:ice}" + end + + it "can set a different flash key for the future" do + post '/flash', {:key => :smash, :knockknock => :whosthere} + get '/flash', {:key => :smash} + last_response.body.should == "{:knockknock=>:whosthere}" + end + + it "sweeps only the flash that gets used" do + post '/flash', {:hi => :ho} + post '/flash', {:aweem => :owep, :key => :smash} + get '/flash', {:key => :smash} + last_response.body.should == "{:aweem=>:owep}" + get '/flash' + last_response.body.should == "{:hi=>:ho}" + end + + it "behaves well when nothing ever checks the flash" do + get '/dummy' + last_response.body.should == "This page does not invoke the flash at all." + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/spec.opts b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/spec.opts new file mode 100644 index 0000000..ad561bd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/spec.opts @@ -0,0 +1,4 @@ +--colour +--format progress +--loadby mtime +--reverse \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/spec_helper.rb b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/spec_helper.rb new file mode 100644 index 0000000..f1f3ca6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sinatra-flash-0.3.0/spec/spec_helper.rb @@ -0,0 +1,46 @@ +$LOAD_PATH.unshift(File.dirname(__FILE__)) +$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) +require 'sinatra' +require 'rack/test' +require 'spec' +require 'spec/autorun' + +set :environment, :test +require 'sinatra/flash' +require 'sinatra/sessionography' + +get '/dummy' do + "This page does not invoke the flash at all." +end + +get '/flash' do + if params[:key] + flash(params[:key]).inspect + else + flash.inspect + end +end + +post '/flash' do + if (key = params.delete('key')) + params.each{|k,v| flash(key)[k.to_sym] = v.to_sym} + flash(key).inspect + else + params.each{|k,v| flash[k.to_sym] = v.to_sym} + flash.inspect + end +end + + +# Stub out our application; it's silly, but we have to do it. (http://www.sinatrarb.com/testing.html) +module SinatraApp + def app + Sinatra::Application + end +end + +Spec::Runner.configure do |config| + include SinatraApp + include Rack::Test::Methods + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/.gitignore b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/.gitignore new file mode 100644 index 0000000..3a4b01a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/.gitignore @@ -0,0 +1,13 @@ +*.swp +*.gem +Gemfile.lock +.bundle +.redcar +.rvmrc +.yardoc +coverage +pkg +test/rails/log +test/rails/tmp +/.ruby-gemset +/.ruby-version diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/.travis.yml b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/.travis.yml new file mode 100644 index 0000000..b49dc5c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/.travis.yml @@ -0,0 +1,38 @@ +# https://www.ruby-lang.org/en/downloads/releases/ +language: ruby +rvm: + - 2.6.1 + - 2.5.3 + - 2.4.5 + - jruby-9.2.6.0 + - jruby-9.1.17.0 + +# Recommend sudo required when using trusty dist +# https://docs.travis-ci.com/user/reference/trusty/ +sudo: required +dist: trusty + +script: "bundle exec rake $TASK" + +after_success: + - bundle exec codeclimate-test-reporter + +env: + global: + - secure: "a7sD9iwPJJn3Fj+mn62GAmy/PEguh3elrilsp1KS+WfDiCiIKD8Q5KG2Jv67DGcQAGI3dPWeh7+ZhZ/W7nEipwWUBmSvGYVeoF63y8j6mNRLeekqspj94l47hXyFePj9bCadY1b1/xY4lE1pMEU8eA8AOUHUqCSuH+Kk/MuvyLM=" + matrix: + - "TASK=test:core_and_plugins" + - "TASK=test:rails RAILS=6.0.0.beta2" + - "TASK=test:rails RAILS=5.2.2" + - "TASK=test:rails RAILS=5.2.1.1" + - "TASK=test:rails RAILS=5.2.1" + - "TASK=test:sinatra SINATRA=2.0.5" + - "TASK=test:sinatra SINATRA=2.0.4" + - "TASK=test:sinatra SINATRA=2.0.3" + +matrix: + exclude: + - rvm: 2.4.5 + env: "TASK=test:rails RAILS=6.0.0.beta2" + - rvm: jruby-9.1.17.0 + env: "TASK=test:rails RAILS=6.0.0.beta2" diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/.yardopts b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/.yardopts new file mode 100644 index 0000000..5a103b4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/.yardopts @@ -0,0 +1,4 @@ +--markup-provider redcarpet +--markup markdown +- README.md CHANGES LICENSE test/literate/TESTS.md doc/logic_less.md doc/translator.md doc/smart.md + diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/CHANGES b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/CHANGES new file mode 100644 index 0000000..95d193a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/CHANGES @@ -0,0 +1,460 @@ +4.1.0 (2020-05-07) + * Add support for Tailwind CSS - #841 + * Update dependencies and testing + +4.0.1 (2018-09-02) + + * Fix incompatibility issue with Slim Include plugin and new ability to specifiy attributes for embedded engines #819 + +4.0.0 (2018-08-26) + + * Add ability to specify attributes for embedded engines using TagEngine - #653 + * Set Tilt's default encoding to utf-8 - #800 + * Prevent generation of invalid Ruby code in heredoc - #770 + * Don't convert underscores to dashes on data attributes - #807 [Backward incompatible] + * Update description in README.jp.md - #795 + * Removed support for embedded engines: Asciidoc, Builder, Creole, Erb, Nokogiri, Opal, Org-Ruby, Styl, Wikicloth + * Fix tests + +3.0.9 (2017-11-09) + + * Fixed Cross-site Scripting in splat attributes names (See #767) + * Restrict access to public methods in logic_less templates (See #781) + +3.0.8 (2017-05-06) + + * Added splat_prefix configuration option for Angular2 syntax support + * Require Ruby >= 2.0.0 + * Relax temple dependency + +3.0.7 (2016-05-22) + + * Add additional attributes feature to shortcuts + * Freeze string literals + +3.0.6 (2015-06-05) + + * Fix warnings #625 + +3.0.4 (2015-06-02) + + * javascript: doesn't add type='text/javascript' anymore + * slimrb: --require added + * Fix #624 + +3.0.3 (2015-03-06) + + * Fix #392, capturing for splat attributes didn't work correctly under Rails + +3.0.2 (2015-02-02) + + * slimrb: Add option --locals + * Fix issues in the test suite (#576), thanks @dmke! + +3.0.1 (2014-12-22) + + * Allow more special characters in html attribute names (See https://html.spec.whatwg.org/multipage/syntax.html#attributes-2), #567 + * Fix: Code attributes mutate their argument (#571) + +3.0.0 (2014-12-07) + + * Drop 1.8.7 support + * Deprecate default_options in favor of options + * Support xml pretty printing with format: :xml + * Deprecate `='`, `=='` and `tag'` syntax for trailing whitespace. Use `=<` etc. instead. + * slimrb: Remove deprecated plugin options -l and -t + +2.1.0 (2014-10-15) + + * Parser: Require pairwise braces in quoted attributes + * Parser: add :attr_list_delims and :code_attr_delims + * Parser: deprecate :attr_delims + * Parser: relax text indentation requirements: + | line + next line + tag some text + more text + * Parser: allow first line to be indented + * Parser: allow inline embedded languages: + .content: markdown: This is **important** + * Parser: allow line breaks in quoted attributes + * Added Opal as embedded engine + * slimrb: Change meaning of -r, deprecate -t and -l + * Fix issue with inserted end (#485) + * Add experimental 'slim/include' plugin (Might change in the future) + * Add experimental 'slim/smart' plugin (Might change in the future) + * Drop jruby18 support + * Fix rails error reporting #587 (Manipulate stacktrace) + * Splat: handle html_safe + +2.0.3 (2014-07-04) + + * slimrb: Don't update HTML output on exceptions + * Allow dashes at the beginning of class names (#474) + * Render empty attributes as standalone in html mode (#480) + * Fix #482: problem with whitespace modifier `tag=<` + * Fix #485: missing end for empty `if` control blocks + * Fix #510: double dash in class name + +2.0.2 (2013-10-27) + + * Add option :attr_delims + +2.0.1 (2013-07-31) + + * Support multiple attributes per shortcut (See issue #415) + * Add support for org-ruby embedded engine + * Render true boolean attributes with empty value + * Support case-when statements + * Fix issue #431 + * Also escape ' to ' + +2.0.0 (2013-05-27) + + * IMPORTANT: Backward incompatible syntax change: '{...}' and '[...]' are not + allowed as ruby attribute wrappers anymore. Use parentheses '(...)' + if you want to wrap code with spaces. This allows to write arrays and hashes directly. + Old: + div id={'obj' + name} data=({:a => 1, :b => 2}) class=['alpha', 'beta'] + New: + div id=('obj' + name) data={:a => 1, :b => 2} class=['alpha', 'beta'] + * Quoted attributes are escaped by default + Old: + a href='http://slim-lang.com/?a=1&b=2' + New: + a href='http://slim-lang.com/?a=1&b=2' + a href=='http://slim-lang.com/?a=1&b=2' + You can always disable escaping completly by using :disable_escape if you don't want to write '=='. + * Added hyphenation support for data attributes (Option :hyphen_attrs) + Example: div data={key1_key2: 2, key1: {key3: 3}} will render as '
' + * Removed deprecated options: + - :escape_quoted_attrs + - :remove_empty_attrs + - :chain + - :attr_wrapper (renamed to :attr_quote) + - :attr_delimiter (renamed to :merge_attrs) + - Slim::LogicLess :wrapped dictionary + - Slim::Parser :shortcut string option + * Allow spaces around attributes, e.g 'a [ href = url ] text' and 'a href = url text' + * Add unicode support for tags and attributes (Issue #212) + * Generate missing `do` keywords for code blocks (see #342) + * Logic-less: Add keyword `self` for string access + * Added Slim::ERBConverter, require 'slim/erb_converter' + * Added option '-e' for ERB conversion to slimrb + * Add syntax for trailing or leading whitespace after tag, e.g. input>, input< + * Add syntax for trailing or leading whitespace after output, e.g. =>, =< + +1.3.8 (2013-04-11) + + * Disable some superflous deprecation warnings + +1.3.7 (2013-04-10) + + * Fixed issue #374, rescue and ensure blocks + * Fixed issue #333 (Throw syntax error if you write text after closed tag) + * Deprecated :attr_delimiter (renamed to :merge_attrs) + * Deprecated :attr_wrapper (renamed to :attr_quote) + * Warn if you use curly braces or brackets for ruby attributes since + curly braces and brackets will be interpreted as Hash/Array in Slim 2.0.0 + Old syntax: + div id={person && person.id} + div id=[person && person.id] + New syntax in 2.0.0: + div id=(person && person.id) + * Deprecated :escape_quoted_attrs (done by default in 2.0) + * Warn if quoted attributes might be double escaped in Slim 2.0.0 + Old syntax: + a href='http://slim-lang.com/?a=1&b=2' + a href=='http://slim-lang.com/?a=1&b=2' + New syntax in 2.0.0: + a href='http://slim-lang.com/?a=1&b=2' + a href=='http://slim-lang.com/?a=1&b=2' + * Improved pretty printing (Issue #202) + * Renamed Slim::EmbeddedEngine to Slim::Embedded (Old constant still available until 2.0) + * Renamed Slim::ControlStructures to Slim::Controls + * Tab expansion improved (tab + space is interpreted as equivalent to tab) + * Support for wrapping javascript in HTML comments or CDATA (Issue #340) + * Asciidoc embedded engine added + +1.3.6 (2013-01-06) + + * Allow attribute values to be broken with `\` (Issue #331) + * Tag shortcuts implemented (Issue #306) + * Hash format of Slim::Parser option :shortcut changed, old configuration deprecated but still supported + +1.3.5 (2012-12-19) + + * Logic-less: + - Rewrote logic-less mode (Issue #326, #327) + - Logic-less mode supports lambdas + - Option :dictionary_access made more powerful, value :wrapped deprecated + +1.3.4 (2012-11-15) + + * Fixed #314 + * Logic-less test cases added + +1.3.3 (2012-10-16) + + * Attribute handling made consistent: + - Splat attributes, static and dynamic attributes are now all handled the same + - Merged attributes are removed if empty (in the default configuration this is only "class") + - Dynamic attributes which are not merged are checked for false or nil and removed if this is the case + - Dynamic attributes which are not merged are checked for true and generated as attribute-name="attribute-name" + * Rename class BooleanAttributes to CodeAttributes + * Add literate test suite (still incomplete), run with `rake test:literate` + * Remove UTF BOM when parsing Slim code + * Fixed issue #303 + +1.3.2 (2012-09-26) + + * Fix boolean attributes #299 + +1.3.1 (2012-09-23) + + * Support inline html at the beginning of a line (New line indicator <). No pipe symbol is | necessary. + It is even possible to wrap other Slim syntax in such a html block. + * Code restructured - Handling of boolean and splat attributes improved and PERFORMANCE improved. + * BACKWARD INCOMPATIBLE CHANGE - Dynamic attributes which return empty value "" are not removed anymore + (this means "" is now interpreted as true), whereas false and nil are still removed. + This corresponds to the definition of boolean attributes in XHTML and HTML5. + * Deprecated option :remove_empty_attrs (TODO: Remove in 1.4.0) + * Add option :escape_quoted_attrs to escape quoted attributes, use == if you don't want that. + The default is false to stay backward compatible. + * Use Temple::FilterError exception + * Use Temple::Parser + * / is not escaped anymore to / + * Parser: check for missing closing quote in quoted attributes + * Use new temple option validation to make Slim configuration more user friendly. + * Support thread options Slim::Engine.with_options which especially useful for Rails + * Add explicit column number to SyntaxError.to_s + +1.3.0 (2012-09-04) + + * Parser wraps text blocks in [:slim, :text, ...] (Used by Translator/I18n plugin) + * Added Translator/I18n plugin which uses GetText or FastGettext (require 'slim/translator') + * Moved logic less mode out of the core to plugin (require 'slim/logic_less') + +1.2.2 (2012-06-21) + + * Fix issue #264 + +1.2.1 (2012-05-22) + + * Support stylus as embedded engine + * Fix issue #257 + +1.2.0 (2012-03-30) + + * Add option :shortcut which configures attribute shortcuts + Default setting: + Slim::Parser.default_options[:shortcut] = {'#' => 'id', '.' => 'class', '*' => '*'} + Define custom shortcut attribute (e.g. a@ajax-link renders ) + Slim::Parser.default_options[:shortcut] = {'@' => 'role'} + Define custom shortcut attribute with tag (e.g. @ajax-link renders ) + Slim::Parser.default_options[:shortcut] = {'@' => 'a role'} + * Add syntax for splat attributes (#109) + * Support for dynamic tags, e.g. *{:tag => 'img', :src => 'image.jpg'} + +1.1.1 (2012-02-29) + + * Evaluating a html attribute now happens only once (#219) + * Code with trailing comma is treated as broken line (#226) + * Support option :remove_empty_attrs (default true) + * Require temple 0.4.0 + +1.1.0 (2012-01-06) + + * Support for special characters in class/id shortcut removed + * Do not allow : in class/id shortcut + * Add support for block expansion syntax + * Support options :indent, :sort_attrs + * Require temple 0.3.5 + +1.0.4 (2011-11-03) + + * Pass options to embedded Tilt engine + Slim::EmbeddedEngine.set_default_options :markdown => {...} + * Add test case for precompiled embedded engine 'builder' + * Bug #204 fixed, tabs were not parsed correctly + +1.0.3 (2011-10-08) + + * Fix rubinius test cases + * Fix line numbers for embedded engines + * Require temple 0.3.4 + * Remove dynamic embedded engines Haml, Liquid, Radius, Markaby + * More thorough integration testing using travis-ci + See http://travis-ci.org/#!/stonean/slim + * Empty static attributes are not removed anymore + * Line indicator =' is supported in tags + +1.0.2 (2011-08-26) + + * Support for Rails 3.1 streaming (Temple > 0.3.2 required) + * Switch to default format xhtml (supports all doctypes, including html5) + * Improve parsing of #{interpolation} in quoted attributes (issue #159) + * Use travis-ci for continous integration testing + +1.0.1 (2011-08-07) + + * Only delimiting brackets must be balanced in ruby attributes + e.g this is possible now `a href=(ruby_code "{") + * Skip empty lines in text block (#156) + +1.0.0 (2011-07-24) + + * Fixed html attribute issue in sections mode (#127) + * Obsolete directive syntax removed + * Syntax for trailing whitespace added (==' and =') + * Deprecated file 'slim/rails.rb' removed + * Parsing of #{interpolation} in markdown fixed + * Support for attributes which span multiple lines + * Dynamic attributes with value true/false are interpreted as boolean + * Support boolean attributes without value e.g. option(selected id="abc") + +0.9.3 (2011-05-15) + + * Allow for bypassing escaping in attributes + * check if string encoding is valid + * support for html conditional comments + * Use new Temple html attribute expression [:html, :attrs, [:html, :attr, ...], ...] + * Use new slim html attribute expression (similiar to Temple) + * Option :id_delimiter replaced with :attr_delimiter + * Attribute value merging improved (nil/empty values are ignored now) + * Arrays attribute values are joined + * Boolean attributes (e.g. selected=true is converted to selected="selected") + * Option :debug removed + * Slim expression grammar provided, Temple validator used in tests + * Option :auto_escape replaced with inverse option :disable_escape + * Require temple 0.3.0 + +0.9.2 (2011-03-30) + + * add SassEngine which respects :pretty + * embedded engine code refactored + * temple supports denser template registration + * deprecate slim/rails (just require 'slim') + * use temple rails and tilt templates + * add encoding option to Slim::Parser/Slim::Engine to enforce template encoding + * vim support is now an external project + +0.9.1 (2011-03-10) + + * add new doctype syntax without ! + * slim directive expression has type and args + +0.9.0 (2011-01-30) + + * slim should not be registered as the default template handler. + * add support for unescaped text interpolation + +0.8.4 (2011-01-26) + + * Added the option to turn off automatic HTML escaping. + * update to tilt 1.2.2 + * allow call to yield in logic less mode + * allow doctype declaration to be capitalized + +0.8.3 (2010-12-23) + + * Added support for html comments. The parser uses the :static filter instead of the :comment filter due to the way the parser is constructed. + +0.8.2 (2010-12-22) + + * fix issue #96 + * Added the Temple Debugger filter. + * Rails problems fixed + +0.8.1 (2010-12-17) + + * remove backtick slim syntax -- no longer supported + * slim executable conflict. issue #91 + * vim syntax support improved + +0.8.0 (2010-11-29) + + * rails logic less support + +0.7.4 (2010-11-22) + + * use ' for text block with trailing whitespace + * allow to disable/enable embedded engines + +0.7.3 (2010-11-16) + + * fix #82 + * basic rails test added + +0.7.2 (2010-11-09) + + * get rid of rails deprecation warning + * use_html_safe is activated automatically by temple + +0.7.1 (2010-11-03) + + * logic less mode + * add syntax for explicitly closed tags + +0.7.0 (2010-10-25) + + * slim-mode.el for emacs added (modified haml-mode.el, needs some work to be fully functional for slim) + * embedded engines + * escape interpolated strings/attributes + * Slim#Filter now uses optional configuration hash + * Initial implementation for Rail's `html_safe`. Closes #25 + * fallback to escape_html stolen from cgi.rb if escape_utils is unavailable, use normal requires because slim is on the load path + * Limit the allowed characters used for attributes delimiters (now only allows parentheses, square brackets and curly braces). See #16 for more info. + * Default to HTML5-mode + * Slim now uses Temple and Tilt. + * Choose your own attribute delimiter! + +0.6.1 (2010-10-17) + + * can wrap parens around attributes if you so desire + * added erubis to the benchmarks + +0.6.0 (2010-10-17) + + * Added slim itself, haml and mustache to the development env for easier benchmarking. + * added escape_html functionality. need to tweak for speed + +0.5.1 (2010-10-08) + + * Consecutive condition statements now working as expected. + +0.5.0 (2010-10-07) + + * Added 'unless' to the list of control words. + * Fixes for inline conditions. There must be a better way of doing this?? + * '-' is a valid character in HTML attributes, so let's allow that. + * Improved the regex so that control code now supports code blocks. + * Output code (start with '=') can now accept code blocks. + * Method calls no longer need parenthesis. We need more tests to ensure the implementation's robustness. + +0.4.1 (2010-10-03) + + * Added '|' as an alias of '`' for parsing plain text. This simulates the syntax of the Jade template engine. + * Added instructions of how to use the gem. + +0.4.0 (2010-09-21) + + * support for nesting lines under backtick + * make it so that one space is the left margin. any additional spaces will be copied over + * support for using indentation after backtick to denote paragraphs. useful for script tags and paragraphs + +0.3.1 (2010-09-17) + + * fix bug with adding end to nesting ruby code + +0.3.0 (2010-09-17) + + * Optimize compiled string to reduce number of concatentations to the buffer + +0.2.0 (2010-09-17) + + * can now make code call on same line as tag + +0.1.0 (2010-09-15) + + * Initial release diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/Gemfile b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/Gemfile new file mode 100644 index 0000000..671e114 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/Gemfile @@ -0,0 +1,70 @@ +source 'https://rubygems.org/' + +gemspec + +group :test do + gem 'sinatra' + gem 'rack-test' +end + +group :perf do + gem 'benchmark-ips' + gem 'erubis' + gem 'haml' +end + +if ENV['TRAVIS'] + gem 'rails-controller-testing' +end + +if ENV['TEMPLE'] == 'master' + gem 'temple', :github => 'judofyr/temple' +end + +if ENV['TILT'] + if ENV['TILT'] == 'master' + gem 'tilt', :github => 'rtomayko/tilt' + else + gem 'tilt', "= #{ENV['TILT']}" + end +end + +if ENV['RAILS'] + # we need some smarter test logic for the different Rails versions + if ENV['RAILS'] == 'master' + gem 'rails', :github => 'rails/rails' + else + gem 'rails', "= #{ENV['RAILS']}" + end + + gem 'slim-rails', require: false +end + +gem 'test-unit', '~> 3.3', '>= 3.3.5' +gem 'minitest', '~> 5.14' + +if RUBY_ENGINE == 'rbx' && !ENV['TRAVIS'] + gem 'psych' +end + +if ENV['SINATRA'] + if ENV['SINATRA'] == 'master' + gem 'sinatra', :github => 'sinatra/sinatra' + else + gem 'sinatra', :tag => "v#{ENV['SINATRA']}" + end +end + +gem 'rake', '~> 13.0', '>= 13.0.1' +gem 'sassc', '~> 2.2', '>= 2.2.1' +gem 'kramdown', '~> 2.1' + +if ENV['TASK'] == 'bench' + gem 'benchmark-ips' + gem 'erubis' + gem 'haml' +end + +if ENV['CODECLIMATE_REPO_TOKEN'] + gem 'codeclimate-test-reporter' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/LICENSE b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/LICENSE new file mode 100644 index 0000000..887f5b6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2010 - 2016 Slim Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/README.jp.md b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/README.jp.md new file mode 100644 index 0000000..1d46793 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/README.jp.md @@ -0,0 +1,1289 @@ +# Slim + +[![Gem Version](https://img.shields.io/gem/v/slim.svg)](http://rubygems.org/gems/slim) [![Build Status](https://img.shields.io/travis/slim-template/slim.svg?branch=master)](http://travis-ci.org/slim-template/slim) [![Code Climate](https://codeclimate.com/github/slim-template/slim/badges/gpa.svg)](https://codeclimate.com/github/slim-template/slim) [![Test Coverage](https://codeclimate.com/github/slim-template/slim/badges/coverage.svg)](https://codeclimate.com/github/slim-template/slim/coverage) +[![Flattr donate button](https://raw.github.com/balupton/flattr-buttons/master/badge-89x18.gif)](https://flattr.com/submit/auto?user_id=min4d&url=http%3A%2F%2Fslim-lang.org%2F "Donate monthly to this project using Flattr") + +Slim は 不可解にならない程度に view の構文を本質的な部品まで減らすことを目指したテンプレート言語です。標準的な HTML テンプレートからどれだけのものを減らせるか、検証するところから始まりました。(<, >, 閉じタグなど) 多くの人が Slim に興味を持ったことで, 機能的で柔軟な構文に成長しました。 + +簡単な特徴 + +* すっきりした構文 + * 閉じタグの無い短い構文 (代わりにインデントを用いる) + * 閉じタグを用いた HTML 形式の構文 + * 設定可能なショートカットタグ (デフォルトでは `#` は `
` に, `.` は `
` に) +* 安全性 + * デフォルトで自動 HTML エスケープ + * Rails の `html_safe?` に対応 +* 柔軟な設定 +* プラグインを用いた拡張性: + * Mustache と同様のロジックレスモード + * インクルード + * 多言語化/I18n +* 高性能 + * ERB/Erubis に匹敵するスピード + * Rails のストリーミングに対応 +* 全てのメジャーフレームワークが対応 (Rails, Sinatra, ...) +* タグや属性の Unicode に完全対応 +* Markdown や Textile のような埋め込みエンジン + +## リンク + +* ホームページ: +* ソース: +* バグ: +* リスト: +* API ドキュメント: + * 最新の Gem: + * GitHub master: + +## イントロダクション + +### Slim とは? + +Slim は __Rails3 以降__ に対応した高速, 軽量なテンプレートエンジンです。主要な Ruby の実装全てでしっかりテストされています。 +私たちは継続的インテグレーションを採用しています。(travis-ci) + +Slim の核となる構文は1つの考えによって導かれています: "この動作を行うために最低限必要なものは何か。" + +多くの人々の Slim への貢献によって, 彼らが使う [Haml](https://github.com/haml/haml) や [Jade](https://github.com/visionmedia/jade) の影響を受け構文の追加が行われています。 Slim の開発チームは美は見る人の目の中にあることを分っているので、こういった追加にオープンです。 + +Slim は 構文解析/コンパイルに [Temple](https://github.com/judofyr/temple) を使い [Tilt](https://github.com/rtomayko/tilt) に組み込まれます。これにより [Sinatra](https://github.com/sinatra/sinatra) やプレーンな [Rack](https://github.com/rack/rack) とも一緒に使えます。 + +Temple のアーキテクチャはとても柔軟で, モンキーパッチなしで構文解析とコンパイルのプロセスの拡張が可能です。これはロジックレスのプラグインや I18n が提供する翻訳プラグインに +使用されます。ロジックレスモードでは HTML をビルドするために Slim の構文を使いたいが, テンプレートの中で Ruby を書きたくない場合にも Slim を使うことができます。 + +### なぜ Slim を使うのか? + +* Slim によって メンテナンスが容易な限りなく最小限のテンプレートを作成でき, 正しい文法の HTML や XML が書けることを保証します。 +* Slim の構文は美しく, テンプレートを書くのがより楽しくなります。Slim は主要なフレームワークで互換性があるので, 簡単に始めることができます。 +* Slim のアーキテクチャは非常に柔軟なので, 構文の拡張やプラグインを書くことができます。 + +___そう, Slim は速い!___ Slim は開発当初からパフォーマンスに注意して開発されてきました。 +ベンチマークはコミット毎に で取られています。 +この数字が信じられませんか? それは仕方ないことです。是非 rake タスクを使って自分でベンチマークを取ってみてください! + +私たちの考えでは, あなたは Slim の機能と構文を使うべきです。Slim はあなたのアプリケーションのパフォーマンスに悪影響を与えないことを保証します。 + +### どうやって使い始めるの? + +Slim を gem としてインストール: + +~~~ +gem install slim +~~~ + +あなたの Gemfile に `gem 'slim'` と書いてインクルードするか, ファイルに `require 'slim'` と書く必要があります。これだけです! 後は拡張子に .slim を使うだけで準備完了です。 + +### 構文例 + +Slim テンプレートがどのようなものか簡単な例を示します: + +~~~ slim +doctype html +html + head + title Slim のファイル例 + meta name="keywords" content="template language" + meta name="author" content=author + link rel="icon" type="image/png" href=file_path("favicon.png") + javascript: + alert('Slim は javascript の埋め込みに対応しています!') + + body + h1 マークアップ例 + + #content + p このマークアップ例は Slim の典型的なファイルがどのようなものか示します。 + + == yield + + - if items.any? + table#items + - for item in items + tr + td.name = item.name + td.price = item.price + - else + p アイテムが見つかりませんでした。いくつか目録を追加してください。 + ありがとう! + + div id="footer" + == render 'footer' + | Copyright © #{@year} #{@author} +~~~ + +インデントについて, インデントの深さはあなたの好みで選択できます。もしあなたが最初のインデントをスペース2つ, その次に5スペースを使いたい場合, それも自由です。マークアップを入れ子にするには最低1つのスペースによるインデントが必要なだけです。 + +## ラインインジケータ + +### テキスト `|` + +パイプを使うと, Slim はパイプよりも深くインデントされた全ての行をコピーします。行中の処理は基本的にどのようなものでもエスケープされます。 + +~~~ slim +body + p + | + これはテキストブロックのテストです。 +~~~ + + 構文解析結果は以下: + +~~~ html +

これはテキストブロックのテストです。

+~~~ + + ブロックの左端はパイプ +1 スペースのインデントに設定されています。 + 追加のスペースはコピーされます。 + +~~~ slim +body + p + | この行は左端になります。 + この行はスペース 1 つを持つことになります。 + この行はスペース 2 つを持つことになります。 + 以下同様に... +~~~ + +テキスト行に HTML を埋め込むこともできます。 + +~~~ slim +- articles.each do |a| + | #{a.name}#{a.description} +~~~ + +### 末尾スペース付きのテキスト `'` + +シングルクォートは `|` と同様に行をコピーしますが, 末尾にスペースが1つ追加されます。 + +### インライン html `<` (HTML 形式) + +HTML タグを直接 Slim の中に書くことができます。Slim では, 閉じタグを使った HTML タグ形式や HTML と Slim を混ぜてテンプレートの中に書くことができます。 +行頭が '<' の場合, 暗黙的に `|` があるものとして動作します: + +~~~ slim + + head + title Example + + - if articles.empty? + - else + table + - articles.each do |a| + #{a.name}#{a.description} + + +~~~ + +### 制御コード `-` + +ダッシュは制御コードを意味します。制御コードの例としてループと条件文があります。`end` は `-` の後ろに置くことができません。ブロックはインデントによってのみ定義されます。 +複数行にわたる Ruby のコードが必要な場合, 行末にバックスラッシュ `\` を追加します。行末がカンマ `,` で終わる場合 (例 関数呼び出し) には, 行末にバックスラッシュを追加する必要はありません。 + +~~~ slim +body + - if articles.empty? + | 在庫なし +~~~ + +### 出力 `=` + +イコールはバッファに追加する出力を生成する Ruby コードの呼び出しを Slim に命令します。Ruby のコードが複数行にわたる場合, 例のように行末にバックスラッシュを追加します。 + +~~~ slim += javascript_include_tag \ + "jquery", + "application" +~~~ + +行末がカンマ `,` で終わる場合 (例 関数呼び出し) には行末にバックスラッシュを追加する必要はありません。行末・行頭にスペースを追加するために修飾子の `>` や `<` がサポートされています。 + +* `=>` は末尾のスペースを伴った出力をします。 末尾のスペースが追加されることを除いて, 単一の等合 (`=`) と同じです。 +* `=<` は先頭のスペースを伴った出力をします。先頭のスペースが追加されることを除いて, 単一の等号 (`=`) と同じです。 + +### HTML エスケープを伴わない出力 `==` + +単一のイコール (`=`) と同じですが, `escape_html` メソッドを経由しません。 末尾や先頭のスペースを追加するための修飾子 `>` と `<` はサポートされています。 + +* `==>` は HTML エスケープを行わずに, 末尾のスペースを伴った出力をします。末尾のスペースが追加されることを除いて, 二重等号 (`==`) と同じです。 +* `==<` は HTML エスケープを行わずに, 先頭のスペースを伴った出力をします。先頭のスペースが追加されることを除いて, 二重等号 (`==`) と同じです。 + +### コードコメント `/` + +コードコメントにはスラッシュを使います。スラッシュ以降は最終的なレンダリング結果に表示されません。コードコメントには `/` を, html コメントには `/!` を使います。 + +~~~ slim +body + p + / この行は表示されません。 + この行も表示されません。 + /! html コメントとして表示されます。 +~~~ + + 構文解析結果は以下: + +~~~ html +

+~~~ + +### HTML コメント `/!` + +html コメントにはスラッシュの直後にエクスクラメーションマークを使います (``)。 + +### IE コンディショナルコメント `/[...]` + +~~~ slim +/[if IE] + p もっといいブラウザを使ってください。 +~~~ + +レンダリング結果: + +~~~ html + +~~~ + +## HTML タグ + +### 宣言 + +doctype キーワードでは, とても簡単な方法で複雑な DOCTYPE を生成できます。 + +XML バージョン + +~~~ slim +doctype xml + + +doctype xml ISO-8859-1 + +~~~ + +XHTML DOCTYPES + +~~~ slim +doctype html + + +doctype 5 + + +doctype 1.1 + + +doctype strict + + +doctype frameset + + +doctype mobile + + +doctype basic + + +doctype transitional + +~~~ + +HTML 4 DOCTYPES + +~~~ slim +doctype strict + + +doctype frameset + + +doctype transitional + +~~~ + +### 閉じタグ (末尾の `/`) + +末尾に `/` を付けることで明示的にタグを閉じることができます。 + +~~~ slim +img src="image.png"/ +~~~ + +(注) 標準的な html タグ (img, br, ...) は自動的にタグを閉じるので, +通常必要ありません。 + +### 行頭・行末にスペースを追加する (`<`, `>`) + +a タグの後に > を追加することで末尾にスペースを追加するよう Slim に強制することができます。 + +~~~ slim +a> href='url1' リンク1 +a> href='url2' リンク2 +~~~ + +< を追加することで先頭にスペースを追加できます。 + +~~~ slim +a< href='url1' リンク1 +a< href='url2' リンク2 +~~~ + +これらを組み合わせて使うこともできます。 + +~~~ slim +a<> href='url1' リンク1 +~~~ + +### インラインタグ + +タグをよりコンパクトにインラインにしたくなることがあるかもしれません。 + +~~~ slim +ul + li.first: a href="/a" A リンク + li: a href="/b" B リンク +~~~ + +可読性のために, 属性を囲むことができるのを忘れないでください。 + +~~~ slim +ul + li.first: a[href="/a"] A リンク + li: a[href="/b"] B リンク +~~~ + +### テキストコンテンツ + +タグと同じ行で開始するか + +~~~ slim +body + h1 id="headline" 私のサイトへようこそ。 +~~~ + +入れ子にするかのどちらかです。エスケープ処理を行うためにはパイプかシングルクォートを使わなければなりません。 + + +~~~ slim +body + h1 id="headline" + | 私のサイトへようこそ。 +~~~ + +スマートテキストモードを有効化して利用する場合 + +~~~ slim +body + h1 id="headline" + 私のサイトへようこそ。 +~~~ + +### 動的コンテンツ (`=` と `==`) + +同じ行で呼び出すか + +~~~ slim +body + h1 id="headline" = page_headline +~~~ + +入れ子にすることができます。 + +~~~ slim +body + h1 id="headline" + = page_headline +~~~ + +### 属性 + +タグの後に直接属性を書きます。通常の属性記述にはダブルクォート `"` か シングルクォート `'` を使わなければなりません (引用符で囲まれた属性)。 + +~~~ slim +a href="http://slim-lang.com" title='Slim のホームページ' Slim のホームページへ +~~~ + +引用符で囲まれたテキストを属性として使えます。 + +#### 属性の囲み + +区切り文字が構文を読みやすくするのであれば, +`{...}`, `(...)`, `[...]` で属性を囲むことができます。 +これらの記号は設定で変更できます (`:attr_list_delims` オプション参照)。 + +~~~ slim +body + h1(id="logo") = page_logo + h2[id="tagline" class="small tagline"] = page_tagline +~~~ + +属性を囲んだ場合, 属性を複数行にわたって書くことができます: + +~~~ slim +h2[id="tagline" + class="small tagline"] = page_tagline +~~~ + +属性の囲みや変数まわりにスペースを使うことができます: + +~~~ slim +h1 id = "logo" = page_logo +h2 [ id = "tagline" ] = page_tagline +~~~ + +#### 引用符で囲まれた属性 + +例: + +~~~ slim +a href="http://slim-lang.com" title='Slim のホームページ' Slim のホームページへ +~~~ + +引用符で囲まれたテキストを属性として使えます: + +~~~ slim +a href="http://#{url}" #{url} へ +~~~ + +属性値はデフォルトでエスケープされます。属性のエスケープを無効にしたい場合 == を使います。 + +~~~ slim +a href=="&" +~~~ + +引用符で囲まれた属性をバックスラッシュ `\` で改行できます。 + +~~~ slim +a data-title="help" data-content="極めて長い長い長いヘルプテキストで\ + 続けてその後はまたやり直して繰り返し...." +~~~ + +#### Ruby コードを用いた属性 + +`=` の後に直接 Ruby コードを書きます。コードにスペースが含まれる場合, +`(...)` の括弧でコードを囲まなければなりません。ハッシュを `{...}` に, 配列を `[...]` に書くこともできます。 + +~~~ slim +body + table + - for user in users + td id="user_#{user.id}" class=user.role + a href=user_action(user, :edit) Edit #{user.name} + a href=(path_to_user user) = user.name +~~~ + +属性値はデフォルトでエスケープされます。属性のエスケープを無効にしたい場合 == を使います。 + +~~~ slim +a href==action_path(:start) +~~~ + +Ruby コードの属性は, コントロールセクションにあるようにバックスラッシュ `\` や `,` を用いて改行できます。 + +#### 真偽値属性 + +属性値の `true`, `false` や `nil` は真偽値として +評価されます。属性を括弧で囲む場合, 属性値の指定を省略することができます。 + +~~~ slim +input type="text" disabled="disabled" +input type="text" disabled=true +input(type="text" disabled) + +input type="text" +input type="text" disabled=false +input type="text" disabled=nil +~~~ + +#### 属性の結合 + +複数の属性が与えられた場合に属性をまとめるように設定することができます (`:merge_attrs` 参照)。デフォルト設定では + class 属性はスペース区切りで結合されます。 + +~~~ slim +a.menu class="highlight" href="http://slim-lang.com/" Slim-lang.com +~~~ + +レンダリング結果: + +~~~ html +Slim-lang.com +~~~ + +また, `Array` を属性値として使うと、配列要素が区切り文字で結合されます。 + +~~~ slim +a class=["menu","highlight"] +a class=:menu,:highlight +~~~ + +#### アスタリスク属性 `*` + +アスタリスクによってハッシュを属性/値のペアとして使うことができます。 + +~~~ slim +.card*{'data-url'=>place_path(place), 'data-id'=>place.id} = place.name +~~~ + +レンダリング結果: + +~~~ html +
Slim の家
+~~~ + +次のようにハッシュを返すメソッドやインスタンス変数を使うこともできます。 + +~~~ slim +.card *method_which_returns_hash = place.name +.card *@hash_instance_variable = place.name +~~~ + +属性の結合 (Slim オプション `:merge_attrs` 参照) に対応するハッシュ属性には `Array` を与えることもできます。 + +~~~ slim +.first *{class: [:second, :third]} テキスト +~~~ + +レンダリング結果 + +~~~ slim +div class="first second third" +~~~ + +アスタリスク(スプラット)属性のプレフィックスは `splat_prefix` オプションで設定できます。デフォルト値は `'*'` です。 + +#### 動的タグ `*` + +アスタリスク属性を使用することで完全に動的なタグを作ることができます。:tag をキーにもつハッシュを返すメソッドを +作るだけです。 + +~~~ slim +ruby: + def a_unless_current + @page_current ? {tag: 'span'} : {tag: 'a', href: 'http://slim-lang.com/'} + end +- @page_current = true +*a_unless_current リンク +- @page_current = false +*a_unless_current リンク +~~~ + +レンダリング結果: + +~~~ html +リンクリンク +~~~ + +### ショートカット + +#### タグショートカット + +`:shortcut` オプションを設定することで独自のタグショートカットを定義できます。Rails アプリケーションでは, `config/initializers/slim.rb` のようなイニシャライザに定義します。Sinatra アプリでは, `require 'slim'` を書いた行以降であれば, どこにでも設定を定義することができます。 + +~~~ ruby +Slim::Engine.set_options shortcut: {'c' => {tag: 'container'}, '#' => {attr: 'id'}, '.' => {attr: 'class'} } +~~~ + +Slim コードの中でこの様に使用できます。 + +~~~ slim +c.content テキスト +~~~ + +レンダリング結果 + +~~~ html +テキスト +~~~ + +#### 属性のショートカット + +カスタムショートカットを定義することができます (id の`#` , class の `.` のように)。 + +例として, type 属性付きの input 要素のショートカット `&` を追加します。 + +~~~ ruby +Slim::Engine.set_options shortcut: {'&' => {tag: 'input', attr: 'type'}, '#' => {attr: 'id'}, '.' => {attr: 'class'}} +~~~ + +Slim コードの中でこの様に使用できます。 + +~~~ slim +&text name="user" +&password name="pw" +&submit +~~~ + +レンダリング結果 + +~~~ html + + + +~~~ + +別の例として, role 属性のショートカット `@` を追加します。 + +~~~ ruby +Slim::Engine.set_options shortcut: {'@' => 'role', '#' => 'id', '.' => 'class'} +~~~ + +Slim コードの中でこの様に使用できます。 + +~~~ slim +.person@admin = person.name +~~~ + +レンダリング結果 + +~~~ html +
Daniel
+~~~ + +1つのショートカットを使って複数の属性を設定することもできます。 + +~~~ ruby +Slim::Engine.set_options shortcut: {'@' => {attr: %w(data-role role)}} +~~~ + +Slim の中で次のように使用すると, + +~~~ slim +.person@admin = person.name +~~~ + +このようにレンダリングされます。 + +~~~ html +
Daniel
+~~~ + +次のように追加の属性固定値を設定することもできます。 + +~~~ ruby +Slim::Engine.set_options shortcut: {'^' => {tag: 'script', attr: 'data-binding', + additional_attrs: { type: "text/javascript" }}} +~~~ + +このように使用します。 + +~~~ slim +^products + == @products.to_json +~~~ + +レンダリング結果です。 + +~~~ html + +~~~ + +#### ID ショートカット `#` と class ショートカット `.` + +`id` と `class` の属性を次のショートカットで指定できます。 + +~~~ slim +body + h1#headline + = page_headline + h2#tagline.small.tagline + = page_tagline + .content + = show_content +~~~ + +これは次に同じです + +~~~ slim +body + h1 id="headline" + = page_headline + h2 id="tagline" class="small tagline" + = page_tagline + div class="content" + = show_content +~~~ + +## ヘルパ, キャプチャとインクルード + +いくつかのヘルパを使用してテンプレートを拡張することもできます。次のヘルパが定義されているとして, + +~~~ruby +module Helpers + def headline(&block) + if defined?(::Rails) + # Rails の場合には capture メソッドを使う + "

#{capture(&block)}

" + else + # フレームワークなしで Slim を使う場合(Tilt の場合), + # そのまま出力する + "

#{yield}

" + end + end +end +~~~ + +実行する Slim のテンプレートコードのスコープにインクルードされます。このヘルパは, Slim テンプレートの中で次のように使用することができます。 + +~~~ slim +p + = headline do + ' Hello + = user.name +~~~ + +`do` ブロック内のコンテンツが自動的にキャプチャされ `yield` を通してヘルパに渡されます。糖衣構文として +`do` キーワードを省略して書くこともできます。 + +~~~ slim +p + = headline + ' Hello + = user.name +~~~ + +### ローカル変数のキャプチャ + +次のように `Binding` を使ってローカル変数をキャプチャすることができます: + +~~~ruby +module Helpers + def capture_to_local(var, &block) + set_var = block.binding.eval("lambda {|x| #{var} = x }") + # Rails では capture! を使います + # Slim をフレームワークなしで使う場合 (Tilt のみを使う場合), + # キャプチャブロックを取得するには yield だけが利用できます + set_var.call(defined?(::Rails) ? capture(&block) : yield) + end +end +~~~ + +このヘルパは次のように使用できます + +~~~ slim +/ captured_content 変数は Binding 前に定義されていなければいけません。 += capture_to_local captured_content=:captured_content + p この段落は captured_content 変数にキャプチャされます += captured_content +~~~ + +別の興味深いユースケースは, enumerableを使いそれぞれの要素をキャプチャすることです。ヘルパは, このようになります。 + +~~~ ruby +module Capture + def capture(var, enumerable = nil, &block) + value = enumerable ? enumerable.map(&block) : yield + block.binding.eval("lambda {|x| #{var} = x }").call(value) + nil + end +end +~~~ + +そして, 次のように使用出来ます。 + +~~~ slim +- links = { 'http://slim-lang.com' => 'The Slim Template Language' } += capture link_list=:link_list, links do |url, text| + a href=url = text +~~~ + +その後は, `link_list`はキャプチャしたコンテンツを含みます。 + +### インクルードヘルパ + +コンパイル時にインクルード機能を使いたい場合には, [パーシャルのインクルード](doc/jp/include.md) を見てください。 +実行時にサブテンプレートを実行すること ( Rails の `#render` のように) もできます。インクルードヘルパを自分で用意する必要があります: + +~~~ ruby +module Helpers + def include_slim(name, options = {}, &block) + Slim::Template.new("#{name}.slim", options).render(self, &block) + end +end +~~~ + +このヘルパは次のように使用できます + +~~~ slim +nav = include_slim 'menu' +section = include_slim 'content' +~~~ + +しかし, このヘルパはキャッシュを行いません。その為, 目的にあったよりインテリジェントなバージョンを +実装する必要があります。また, ほとんどのフレームワークにはすでに同様のヘルパが含まれるので注意してください。(例: Rails の `render` メソッド) + +## テキストの展開 + +Ruby の標準的な展開方法を使用します。テキストはデフォルトで html エスケープされます。2 重括弧にすることでエスケープしないこともできます。 + +~~~ slim +body + h1 ようこそ #{current_user.name} ショーへ。 + | エスケープしない #{{content}} こともできます。 +~~~ + +展開したテキストのエスケープ方法 (言い換えればそのままのレンダリング) + +~~~ slim +body + h1 ようこそ \#{current_user.name} ショーへ。 +~~~ + +## 埋め込みエンジン (Markdown, ...) + +[Tilt](https://github.com/rtomayko/tilt)のおかげで, Slim は他のテンプレートエンジンの埋め込みに見事に対応しています。 + +例: + +~~~ slim + coffee: + square = (x) -> x * x + + markdown: + #Header + #{"Markdown"} からこんにちわ! + 2行目! + +p: markdown: Tag with **inline** markdown! +~~~ + +対応エンジン: + +| フィルタ | 必要な gems | 種類 | 説明 | +| -------- | ----------- | ---- | ----------- | +| ruby: | なし | ショートカット | Ruby コードを埋め込むショートカット | +| javascript: | なし | ショートカット | javascript コードを埋め込み、script タグで囲む | +| css: | なし | ショートカット | css コードを埋め込み、style タグで囲む | +| sass: | sass | コンパイル時 | sass コードを埋め込み、style タグで囲む | +| scss: | sass | コンパイル時 | scss コードを埋め込み、style タグで囲む | +| less: | less | コンパイル時 | less コードを埋め込み、style タグで囲む | +| coffee: | coffee-script | コンパイル時 | CoffeeScript をコンパイルし、 script タグで囲む | +| markdown: | redcarpet/rdiscount/kramdown | コンパイル時 + 展開 | Markdown をコンパイルし、テキスト中の # \{variables} を展開 | +| textile: | redcloth | コンパイル時 + 展開 | textile をコンパイルし、テキスト中の # \{variables} を展開 | +| rdoc: | rdoc | コンパイル時 + 展開 | RDoc をコンパイルし、テキスト中の # \{variables} を展開 | + +埋め込みエンジンは Slim の `Slim::Embedded` フィルタのオプションで直接設定されます。例: + +~~~ ruby +Slim::Embedded.options[:markdown] = {auto_ids: false} +~~~ + +以下埋め込みエンジンの場合はHTMLのattributeも指定できます: + +* Javascript +* CSS +* CoffeeScript +* LESS +* SASS +* SCSS + +例: + +~~~ scss +scss class="myClass": + $color: #f00; + body { color: $color; } +~~~ + +レンダリング結果: + +~~~ html + +~~~ + +## Slim の設定 + +Slim とその基礎となる [Temple](https://github.com/judofyr/temple) は非常に柔軟に設定可能です。 +Slim を設定する方法はコンパイル機構に少し依存します。(Rails や [Tilt](https://github.com/rtomayko/tilt))。デフォルトオプションの設定は `Slim::Engine` クラスでいつでも可能です。Rails の 環境設定ファイルで設定可能です。例えば, config/environments/developers.rb で設定したいとします: + +### デフォルトオプション + +~~~ ruby +# デバック用に html をきれいにインデントし属性をソートしない +Slim::Engine.set_options pretty: true, sort_attrs: false +~~~ + +ハッシュで直接オプションにアクセスすることもできます: + +~~~ ruby +Slim::Engine.options[:pretty] = true +~~~ + +### 実行時のオプション設定 + +実行時のオプション設定の方法は2つあります。Tilt テンプレート (`Slim::Template`) の場合, テンプレートを +インスタンス化する時にオプションを設定できます。 + +~~~ ruby +Slim::Template.new('template.slim', optional_option_hash).render(scope) +~~~ + +他の方法は Rails に主に関係がありますがスレッド毎にオプション設定を行う方法です: + +~~~ slim +Slim::Engine.with_options(option_hash) do + # ここで作成される Slim エンジンは option_hash を使用します + # Rails での使用例: + render :page, layout: true +end +~~~ + +Rails ではコンパイルされたテンプレートエンジンのコードとオプションはテンプレート毎にキャッシュされ, 後でオプションを変更できないことに注意する必要があります。 + +~~~ slim +# 最初のレンダリング呼び出し +Slim::Engine.with_options(pretty: true) do + render :page, layout: true +end + +# 2回目のレンダリング呼び出し +Slim::Engine.with_options(pretty: false) do + render :page, layout: true # :pretty is still true because it is cached +end +~~~ + +### 設定可能なオプション + +次のオプションが `Slim::Engine` によって用意され `Slim::Engine.set_options` で設定することができます。 +沢山ありますが, 素晴らしいことに, Slim は設定キーをチェックし, 無効な設定キーを使用しようとしていた場合, エラーを返してくれます。 + + +| 型 | 名前 | デフォルト | 用途 | +| ---- | ---- | ---------- | ---- | +| String | :file | nil | 解析対象のファイル名。 Slim::Template によって自動的に設定されます | +| Integer | :tabsize | 4 | 1 タブあたりのスペース数 (構文解析で利用されます) | +| String | :encoding | "utf-8" | テンプレートのエンコーディングを設定 | +| String | :default_tag | "div" | タグ名が省略されている場合デフォルトのタグとして使用される | +| Hash | :shortcut | \{'.' => {attr: 'class'}, '#' => {attr: 'id'}} | 属性のショートカット | +| Hash | :code_attr_delims | \{'(' => ')', '[' => ']', '{' => '}'} | Ruby コードの属性区切り文字 | +| Hash | :attr_list_delims | \{'(' => ')', '[' => ']', '{' => '}'} | 属性リスト区切り文字 | +| Array<Symbol,String> | :enable_engines | nil (すべて有効) | 有効な埋め込みエンジンリスト (ホワイトリスト) | +| Array<Symbol,String> | :disable_engines | nil (無効なし) | 無効な埋め込みエンジンリスト (ブラックリスト) | +| Boolean | :disable_capture | false (Rails では true) | ブロック内キャプチャ無効 (ブロックはデフォルトのバッファに書き込む) | +| Boolean | :disable_escape | false | Stringの自動エスケープ無効 | +| Boolean | :use_html_safe | false (Rails では true) | ActiveSupport の String# html_safe? を使う (:disable_escape と一緒に機能する) | +| Symbol | :format | :xhtml | HTML の出力フォーマット (対応フォーマット :html, :xhtml, :xml) | +| String | :attr_quote | '"' | HTML の属性を囲む文字 (' または " が可能) | +| Hash | :merge_attrs | \{'class' => ' '} | 複数の html 属性が与えられたときに, 結合に使われる文字 (例: class="class1 class2") | +| Array<String> | :hyphen_attrs | %w(data) | 属性にハッシュが与えられたとき, ハイフンで区切られます。(例: data={a:1, b:2} は data-a="1" data-b="2" のように) | +| Boolean | :sort_attrs | true | 名前順に属性をソート | +| Symbol | :js_wrapper | nil | :commentや :cdata , :both で JavaScript をラップします。:guess を指定することで :format オプションに基いて設定することもできます | +| Boolean | :pretty | false | HTML を綺麗にインデントします。ブロック要素のタグでのみ、インデントされます。 (遅くなります!) | +| String | :indent | ' ' | インデントに使用される文字列 | +| Boolean | :streaming | false (Rails では true, 無効化するにはストリーミングを参照) | ストリーミング出力の有効化, 体感的なパフォーマンスの向上 | +| Class | :generator | Temple::Generators::StringBuffer/ RailsOutputBuffer | Temple コードジェネレータ (デフォルトのジェネレータはStringバッファを生成します) | +| String | :buffer | '_buf' (Rails では '@output_buffer') | バッファに使用される変数 | +| String | :splat_prefix | '*' | アスタリスク(スプラット)属性のプレフィックス | + +Temple フィルタによってもっと多くのオプションがサポートされていますが一覧には載せず公式にはサポートしません。 +Slim と Temple のコードを確認しなければなりません。 + +### オプションの優先順位と継承 + +Slim や Temple のアーキテクチャについてよく知っている開発者は, 別の場所で設定を +上書きすることができます。 Temple はサブクラスがスーパークラスのオプションを上書きできるように +継承メカニズムを採用しています。オプションの優先順位は次のとおりです: + +1. `Slim::Template` オプションはエンジン初期化時に適用されます +2. `Slim::Template.options` +3. `Slim::Engine.thread_options`, `Slim::Engine.options` +5. Praser/Filter/Generator `thread_options`, `options` (例: `Slim::Parser`, `Slim::Compiler`) + +`Temple::Engine` のようにスーパークラスのオプションを設定することも可能です。しかし, こうするとすべての Temple テンプレートエンジンに影響します。 + +~~~ ruby +Slim::Engine < Temple::Engine +Slim::Compiler < Temple::Filter +~~~ + +## プラグイン + +Slim はロジックレスモードと I18n, インクルードプラグインを提供しています。プラグインのドキュメントを確認してください。 + +* [ロジックレスモード](doc/jp/logic_less.md) +* [パーシャルのインクルード](doc/jp/include.md) +* [多言語化/I18n](doc/jp/translator.md) +* [スマートテキストモード](doc/jp/smart.md) + +## フレームワークサポート + +### Tilt + +Slim は生成されたコードをコンパイルするために [Tilt](https://github.com/rtomayko/tilt) を使用します。Slim テンプレートを直接使いたい場合, Tilt インターフェイスが使用できます。 + +~~~ ruby +Tilt.new['template.slim'].render(scope) +Slim::Template.new('template.slim', optional_option_hash).render(scope) +Slim::Template.new(optional_option_hash) { source }.render(scope) +~~~ + +optional_option_hash は前述のオプションを持つことができます。スコープはコードが実行されるテンプレートの +オブジェクトです。 + +### Sinatra + +~~~ ruby +require 'sinatra' +require 'slim' + +get('/') { slim :index } + + __END__ +@@ index +doctype html +html + head + title Slim で Sinatra + body + h1 Slim は楽しい! +~~~ + +### Rails + +Rails のジェネレータは [slim-rails](https://github.com/slim-template/slim-rails) によって提供されます。 +slim-rails は Rails で Slim を使用する場合に必須ではありません。Slim をインストールし Gemfile に `gem 'slim'` を追加するだけです。 +後は .slim 拡張子を使うだけです。 + +#### ストリーミング + +HTTP ストリーミングをサポートしているバージョンの Rails であれば, デフォルトで有効化されています。しかし, ストリーミングは体感的なパフォーマンスを改善しているだけであることに注意してください。 +レンダリング時間は増加するでしょう。ストリーミングを無効化したい場合, 以下のように設定します: + +~~~ ruby +Slim::RailsTemplate.set_options streaming: false +~~~ + +### Angular2 + +Slim は Angular2 の構文に対応しています。ただし, いくつかのオプションを設定する必要があります: + +#### `splat_prefix` オプション + +このオプションは, アスタリスク(スプラット)属性に使用する構文をパーサに指定します。 +デフォルト値はアスタリスクです: `splat_prefix: '*'` +アスタリスクは Angular2 でも構造ディレクティブとして `*ngIf` などで使われます。デフォルトの設定値では, Slim と Angular2 の構文は衝突します。 + +解決方法は 2 つあります: + +* `splat_prefix` に 2重アスタリスクのようなカスタム値(`splat_prefix: '**'`)を設定します。これで構造ディレクティブは期待通りに機能するはずです。アスタリスク属性は設定したカスタム値のプレフィックスで書かなければならないので注意してください。 +* アスタリスクではない代わりのディレクティブ構文を使います。 + +#### 属性区切り文字 + +Angular と Slim はそれぞれの構文で括弧を使います。この場合も解決方法は 2 つあります: +* バインディングに代わりの構文を使う (`bind-...` など) +* 属性区切り文字を波括弧に限定する +``` +code_attr_delims: { + '{' => '}', +}, +attr_list_delims: { + '{' => '}', +}, +``` + +これで次のように書けます: +``` +h1{ #var (bind1)="test" [bind2]="ok" [(bind3)]="works?" *ngIf="expr" *ngFor="expression" } {{it works}} +``` + +コンパイル結果: +``` +

+ {{it works}} +

+``` + +## ツール + +### Slim コマンド 'slimrb' + +gem の 'slim' にはコマンドラインから Slim をテストするための小さなツール 'slimrb' が付属します。 + +
+$ slimrb --help
+Usage: slimrb [options]
+    -s, --stdin                      Read input from standard input instead of an input file
+        --trace                      Show a full traceback on error
+    -c, --compile                    Compile only but do not run
+    -e, --erb                        Convert to ERB
+        --rails                      Generate rails compatible code (Implies --compile)
+    -r, --require library            Load library or plugin with -r slim/plugin
+    -p, --pretty                     Produce pretty html
+    -o, --option name=code           Set slim option
+    -l, --locals Hash|YAML|JSON      Set local variables
+    -h, --help                       Show this message
+    -v, --version                    Print version
+
+ +'slimrb' で起動し, コードをタイプし Ctrl-d で EOF を送ります。Windows のコマンドプロンプトでは Ctrl-z で EOF を送ります。使い方例: + +
+$ slimrb
+markdown:
+  最初の段落。
+
+  2つ目の段落。
+
+  * 1つ
+  * 2つ
+  * 3つ
+
+//Enter Ctrl-d
+<p>最初の段落。 </p>
+
+<p>2つめの段落。 </p>
+
+<ul>
+<li>1つ</li>
+<li>2つ</li>
+<li>3つ</li>
+</ul>
+
+ +### 構文ハイライト + +様々なテキストエディタ(Vim や Emacs, Textmateなど)のためのプラグインがあります。: + +* [Vim](https://github.com/slim-template/vim-slim) +* [Emacs](https://github.com/slim-template/emacs-slim) +* [Textmate / Sublime Text](https://github.com/slim-template/ruby-slim.tmbundle) +* [Espresso text editor](https://github.com/slim-template/Slim-Sugar) +* [Coda](https://github.com/slim-template/Coda-2-Slim.mode) +* [Atom](https://github.com/slim-template/language-slim) + +### テンプレート変換 (HAML, ERB, ...) + +* Slim は gem に含まれる `slimrb` や `Slim::ERBConverter` を用いて ERB に変換できます。 +* [Haml2Slim converter](https://github.com/slim-template/haml2slim) +* [ERB2Slim, HTML2Slim converter](https://github.com/slim-template/html2slim) + +## テスト + +### ベンチマーク + + *そうです, Slim は最速の Ruby のテンプレートエンジンです! + production モードの Slim は Erubis (最速のテンプレートエンジン) と同じくらい高速です。 + どんな理由であれ, あなたが Slim を選択していただければ嬉しいし, 私たちは + パフォーマンスが障害にならないだろうことを保証します。* + +ベンチマークは `rake bench` で実行します。時間が余計にかかりますが遅い解析ベンチマークを +実行したい場合 `slow` オプションを追加できます。 + +~~~ +rake bench slow=1 iterations=1000 +~~~ + +私たちはコミット毎に Travis-CI でベンチマークをとっています。最新のベンチマーク結果はこちらです: + +### テストスイートと継続的インテグレーション + +Slim は minitest ベースの拡張性のあるテストスイートを提供します。テストは 'rake test' または +rails のインテグレーションテストの場合 'rake test:rails' で実行できます。 + +私たちは現在 markdown ファイルで書かれ, 人間が読み書きしやすいテストを試しています: [TESTS.md](test/literate/TESTS.md) + +Travis-CI は継続的インテグレーションテストに利用されています: + +Slim は主要な Ruby 実装全てで動作します: + +* Ruby 2.0, 2.1, 2.2 および 2.3 +* JRuby 1.9 mode +* Rubinius 2.0 + +## 貢献 + +Slim の改良を支援したい場合, Git で管理されているプロジェクトを clone してください。 + +~~~ +$ git clone git://github.com/slim-template/slim +~~~ + +魔法をかけた後 pull request を送ってください。私たちは pull request が大好きです! + +Ruby の 2.3.0, 2.2.0, 2.1.0 と 2.0.0 でテストをすることを覚えておいてください。 + +もしドキュメントの不足を見つけたら, README.md をアップデートして私たちを助けて下さい。Slim に割ける時間がないが, 私たちが知っておくべきことを見つけた場合には issue を送ってください。 + +## License + +Slim は [MIT license](http://www.opensource.org/licenses/MIT) に基づいてリリースされています。 + +## 作者 + +* [Daniel Mendler](https://github.com/minad) (Lead developer) +* [Andrew Stone](https://github.com/stonean) +* [Fred Wu](https://github.com/fredwu) + +## 寄付と支援 + +このプロジェクトをサポートしたい場合, Gittip や Flattr のページを見てください。 + +[![Gittip donate button](http://img.shields.io/gittip/bevry.png)](https://www.gittip.com/min4d/ "Donate weekly to this project using Gittip") +[![Flattr donate button](https://raw.github.com/balupton/flattr-buttons/master/badge-89x18.gif)](https://flattr.com/submit/auto?user_id=min4d&url=http%3A%2F%2Fslim-lang.org%2F "Donate monthly to this project using Flattr") + +今のところ, 寄付はホスティング費用 (ドメインなど) に当てられる予定です。 + +## 議論 + +* [Google Group](http://groups.google.com/group/slim-template) + +## 関連プロジェクト + +テンプレートのコンパイルフレームワーク: + +* [Temple](https://github.com/judofyr/temple) + +フレームワークサポート: + +* [Rails generators (slim-rails)](https://github.com/slim-template/slim-rails) + * [slimkeyfy - Translation string extraction](https://github.com/phrase/slimkeyfy) + +構文ハイライト: + +* [Vim](https://github.com/slim-template/vim-slim) +* [Emacs](https://github.com/slim-template/emacs-slim) +* [Textmate / Sublime Text](https://github.com/slim-template/ruby-slim.tmbundle) +* [Espresso text editor](https://github.com/slim-template/Slim-Sugar) +* [Coda](https://github.com/slim-template/Coda-2-Slim.mode) +* [Atom](https://github.com/slim-template/language-slim) + +静的コード解析: + +* [Slim-Lint](https://github.com/sds/slim-lint) +* [SublimeLinter-slim-lint](https://github.com/elstgav/SublimeLinter-slim-lint) + +テンプレート変換 (HAML, ERB, ...): + +* [Haml2Slim converter](https://github.com/slim-template/haml2slim) +* [ERB2Slim, HTML2Slim converter](https://github.com/slim-template/html2slim) + +移植言語/同様の言語: + +* [Sliq (Slim/Liquid integration)](https://github.com/slim-template/sliq) +* [Slm (Slim port to Javascript)](https://github.com/slm-lang/slm) +* [Coffee script plugin for Slim](https://github.com/yury/coffee-views) +* [Clojure port of Slim](https://github.com/chaslemley/slim.clj) +* [Hamlet.rb (Similar template language)](https://github.com/gregwebs/hamlet.rb) +* [Plim (Python port of Slim)](https://github.com/2nd/plim) +* [Skim (Slim for Javascript)](https://github.com/jfirebaugh/skim) +* [Emblem.js (Javascript, similar to Slim)](https://github.com/machty/emblem.js) +* [Hamlit (High performance Haml implementation, based on Temple like Slim)](https://github.com/k0kubun/hamlit) +* [Faml (Faster Haml implementation, also using Temple like Slim)](https://github.com/eagletmt/faml) +* [Haml (Older engine which inspired Slim)](https://github.com/haml/haml) +* [Jade (Similar engine for javascript)](https://github.com/visionmedia/jade) +* [Pug (Successor of Jade, Similar engine for javascript)](https://github.com/pugjs/pug) +* [Sweet (Similar engine which also allows to write classes and functions)](https://github.com/joaomdmoura/sweet) +* [Amber (Similar engine for Go)](https://github.com/eknkc/amber) +* [Slang (Slim-inspired templating language for Crystal)](https://github.com/jeromegn/slang) diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/README.md b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/README.md new file mode 100644 index 0000000..5b622a4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/README.md @@ -0,0 +1,1290 @@ +# Slim + +[![Gem Version](https://img.shields.io/gem/v/slim.svg)](http://rubygems.org/gems/slim) [![Build Status](https://img.shields.io/travis/slim-template/slim.svg?branch=master)](http://travis-ci.org/slim-template/slim) [![Code Climate](https://codeclimate.com/github/slim-template/slim/badges/gpa.svg)](https://codeclimate.com/github/slim-template/slim) [![Test Coverage](https://codeclimate.com/github/slim-template/slim/badges/coverage.svg)](https://codeclimate.com/github/slim-template/slim/coverage) +[![Flattr donate button](https://raw.github.com/balupton/flattr-buttons/master/badge-89x18.gif)](https://flattr.com/submit/auto?user_id=min4d&url=http%3A%2F%2Fslim-lang.org%2F "Donate monthly to this project using Flattr") + +Slim is a template language whose goal is to reduce the view syntax to the essential parts without becoming cryptic. It started as an exercise to see how much could be removed from a standard html template (<, >, closing tags, etc...). As more people took an interest in Slim, the functionality grew and so did the flexibility of the syntax. + +A short list of the features... + +* Elegant syntax + * Short syntax without closing tags (Using indentation instead) + * HTML style mode with closing tags + * Configurable shortcut tags (`#` for `
` and `.` for `
` in the default configuration) +* Safety + * Automatic HTML escaping by default + * Support for Rails' `html_safe?` +* Highly configurable +* Extensible via the following plugins: + * Logic less mode similar to Mustache + * Includes + * Translator/I18n +* High performance + * Comparable speed to ERB/Erubis + * Streaming support in Rails +* Supported by all major frameworks (Rails, Sinatra, ...) +* Full Unicode support for tags and attributes +* Embedded engines like Markdown and Textile + +## Links + +* Homepage: +* Source: +* Bugs: +* List: +* API documentation: + * Latest Gem: + * GitHub master: + +## Introduction + +### What is Slim? + +Slim is a fast, lightweight templating engine with support for __Rails 3 and later__. It has been heavily tested on all major ruby implementations. We use +continuous integration (travis-ci). + +Slim's core syntax is guided by one thought: "What's the minimum required to make this work". + +As more people have contributed to Slim, there have been syntax additions influenced from their use of [Haml](https://github.com/haml/haml) and [Jade](https://github.com/visionmedia/jade). The Slim team is open to these additions because we know beauty is in the eye of the beholder. + +Slim uses [Temple](https://github.com/judofyr/temple) for parsing/compilation and is also integrated into [Tilt](https://github.com/rtomayko/tilt), so it can be used together with [Sinatra](https://github.com/sinatra/sinatra) or plain [Rack](https://github.com/rack/rack). + +The architecture of Temple is very flexible and allows the extension of the parsing and compilation process without monkey-patching. This is used +by the logic less plugin and the translator plugin which provides I18n. In logic-less mode you can use Slim if you like the Slim syntax to build your HTML but don't want to write Ruby in your templates. + +### Why use Slim? + +* Slim allows you to write very minimal templates which are easy to maintain and pretty much guarantees that you write well-formed HTML and XML +* The Slim syntax is aesthetic and makes it more fun to write templates. Since you can use Slim as a drop-in replacement in all the major frameworks it is easy to adopt. +* The Slim architecture is very flexible and allows you to write syntax extensions and plugins. + +___Yes, Slim is speedy!___ Slim was developed right from the start with performance in mind. +Benchmarks are done for every commit at . +Don't trust the numbers? That's as it should be. Please try the benchmark rake task yourself! + +However in our opinion you should use Slim because of its features and syntax. We just ensure that Slim doesn't have a negative impact on the performance of your application. + +### How to start? + +Install Slim as a gem: + +~~~ +gem install slim +~~~ + +Include Slim in your Gemfile with `gem 'slim'` or require it with `require 'slim'`. That's it! Now, just use the .slim extension and you're good to go. + +### Syntax example + +Here's a quick example to demonstrate what a Slim template looks like: + +~~~ slim +doctype html +html + head + title Slim Examples + meta name="keywords" content="template language" + meta name="author" content=author + link rel="icon" type="image/png" href=file_path("favicon.png") + javascript: + alert('Slim supports embedded javascript!') + + body + h1 Markup examples + + #content + p This example shows you how a basic Slim file looks. + + == yield + + - if items.any? + table#items + - for item in items + tr + td.name = item.name + td.price = item.price + - else + p No items found. Please add some inventory. + Thank you! + + div id="footer" + == render 'footer' + | Copyright © #{@year} #{@author} +~~~ + +Indentation matters, but the indentation depth can be chosen as you like. If you want to first indent 2 spaces, then 5 spaces, it's your choice. To nest markup you only need to indent by one space, the rest is gravy. + +## Line indicators + +### Verbatim text `|` + +The pipe tells Slim to just copy the line. It essentially escapes any processing. +Each following line that is indented greater than the pipe is copied over. + +~~~ slim +body + p + | + This is a test of the text block. +~~~ + + The parsed result of the above: + +~~~ html +

This is a test of the text block.

+~~~ + + If the text starts on the same line, the left margin is set at the indent of the pipe + one space. + Any additional spaces will be copied over. + +~~~ slim +body + p + | This line is on the left margin. + This line will have one space in front of it. + This line will have two spaces in front of it. + And so on... +~~~ + +You can also embed html in the text line + +~~~ slim +- articles.each do |a| + | #{a.name}#{a.description} +~~~ + +### Verbatim text with trailing white space `'` + +The single quote tells Slim to copy the line (similar to `|`), but makes sure that a single trailing white space is appended. + +### Inline html `<` + +You can write html tags directly in Slim which allows you to write your templates in a more html like style with closing tags or mix html and Slim style. +The leading `<` works like an implicit `|`: + +~~~ slim + + head + title Example + + - if articles.empty? + - else + table + - articles.each do |a| + #{a.name}#{a.description} + + +~~~ + +### Control code `-` + +The dash denotes control code. Examples of control code are loops and conditionals. `end` is forbidden behind `-`. Blocks are defined only by indentation. +If your ruby code needs to use multiple lines, append a backslash `\` at the end of the lines. If your line ends with comma `,` (e.g because of a method call) you don't need the additional backslash before the linebreak. + +~~~ slim +body + - if articles.empty? + | No inventory +~~~ + +### Output `=` + +The equals sign tells Slim it's a Ruby call that produces output to add to the buffer. If your ruby code needs to use multiple lines, append a backslash `\` at the end of the lines. For example: + +~~~ slim += javascript_include_tag \ + "jquery", + "application" +~~~ + +If your line ends with comma `,` (e.g because of a method call) you don't need the additional backslash before the linebreak. For trailing or leading whitespace the modifiers `>` and `<` are supported. + +* Output with trailing white space `=>`. Same as the single equals sign (`=`), except that it adds a trailing white space. +* Output with leading white space `=<`. Same as the single equals sign (`=`), except that it adds a leading white space. + +### Output without HTML escaping `==` + +Same as the single equals sign (`=`), but does not go through the `escape_html` method. For trailing or leading whitespace the modifiers `>` and `<` are supported. + +* Output without HTML escaping and trailing white space `==>`. Same as the double equals sign (`==`), except that it adds a trailing white space. +* Output without HTML escaping and leading white space `==<`. Same as the double equals sign (`==`), except that it adds a leading white space. + +### Code comment `/` + +Use the forward slash for code comments - anything after it won't get displayed in the final render. Use `/` for code comments and `/!` for html comments + +~~~ slim +body + p + / This line won't get displayed. + Neither does this line. + /! This will get displayed as html comments. +~~~ + + The parsed result of the above: + +~~~ html +

+~~~ + +### HTML comment `/!` + +Use the forward slash immediately followed by an exclamation mark for html comments (``). + +### IE conditional comment `/[...]` + +~~~ slim +/[if IE] + p Get a better browser. +~~~ + +This renders as: + +~~~ html + +~~~ + +## HTML tags + +### declaration + +The doctype keyword can be used to generate the complex doctypes in a very simple manner. + +XML VERSION + +~~~ slim +doctype xml + + +doctype xml ISO-8859-1 + +~~~ + +XHTML DOCTYPES + +~~~ slim +doctype html + + +doctype 5 + + +doctype 1.1 + + +doctype strict + + +doctype frameset + + +doctype mobile + + +doctype basic + + +doctype transitional + +~~~ + +HTML 4 DOCTYPES + +~~~ slim +doctype strict + + +doctype frameset + + +doctype transitional + +~~~ + +### Closed tags (trailing `/`) + +You can close tags explicitly by appending a trailing `/`. + +~~~ slim +img src="image.png"/ +~~~ + +Note, that this is usually not necessary since the standard html +tags (img, br, ...) are closed automatically. + +### Trailing and leading whitespace (`<`, `>`) + +You can force Slim to add a trailing whitespace after a tag by adding a `>`. + +~~~ slim +a> href='url1' Link1 +a> href='url2' Link2 +~~~ + +You can add a leading whitespace by adding `<`. + +~~~ slim +a< href='url1' Link1 +a< href='url2' Link2 +~~~ + +You can also combine both. + +~~~ slim +a<> href='url1' Link1 +~~~ + +### Inline tags + +Sometimes you may want to be a little more compact and inline the tags. + +~~~ slim +ul + li.first: a href="/a" A link + li: a href="/b" B link +~~~ + +For readability, don't forget you can wrap the attributes. + +~~~ slim +ul + li.first: a[href="/a"] A link + li: a[href="/b"] B link +~~~ + +### Text content + +Either start on the same line as the tag + +~~~ slim +body + h1 id="headline" Welcome to my site. +~~~ + +Or nest it. You must use a pipe or an apostrophe to escape processing + + +~~~ slim +body + h1 id="headline" + | Welcome to my site. +~~~ + +Or enable and rely on smart text instead + +~~~ slim +body + h1 id="headline" + Welcome to my site. +~~~ + +### Dynamic content (`=` and `==`) + +Can make the call on the same line + +~~~ slim +body + h1 id="headline" = page_headline +~~~ + +Or nest it. + +~~~ slim +body + h1 id="headline" + = page_headline +~~~ + +### Attributes + +You write attributes directly after the tag. For normal text attributes you must use double `"` or single quotes `'` (Quoted attributes). + +~~~ slim +a href="http://slim-lang.com" title='Slim Homepage' Goto the Slim homepage +~~~ + +You can use text interpolation in the quoted attributes. + +#### Attributes wrapper + +If a delimiter makes the syntax more readable for you, +you can use the characters `{...}`, `(...)`, `[...]` to wrap the attributes. +You can configure these symbols (See option `:attr_list_delims`). + +~~~ slim +body + h1(id="logo") = page_logo + h2[id="tagline" class="small tagline"] = page_tagline +~~~ + +If you wrap the attributes, you can spread them across multiple lines: + +~~~ slim +h2[id="tagline" + class="small tagline"] = page_tagline +~~~ + +You may use spaces around the wrappers and assignments: + +~~~ slim +h1 id = "logo" = page_logo +h2 [ id = "tagline" ] = page_tagline +~~~ + +#### Quoted attributes + +Example: + +~~~ slim +a href="http://slim-lang.com" title='Slim Homepage' Goto the Slim homepage +~~~ + +You can use text interpolation in the quoted attributes: + +~~~ slim +a href="http://#{url}" Goto the #{url} +~~~ + +The attribute value will be escaped by default. Use == if you want to disable escaping in the attribute. + +~~~ slim +a href=="&" +~~~ + +You can break quoted attributes with backslash `\` + +~~~ slim +a data-title="help" data-content="extremely long help text that goes on\ + and on and on and then starts over...." +~~~ + +#### Ruby attributes + +Write the ruby code directly after the `=`. If the code contains spaces you have to wrap +the code into parentheses `(...)`. You can also directly write hashes `{...}` and arrays `[...]`. + +~~~ slim +body + table + - for user in users + td id="user_#{user.id}" class=user.role + a href=user_action(user, :edit) Edit #{user.name} + a href=(path_to_user user) = user.name +~~~ + +The attribute value will be escaped by default. Use == if you want to disable escaping in the attribute. + +~~~ slim +a href==action_path(:start) +~~~ + +You can also break ruby attributes with backslash `\` or trailing `,` as described for control sections. + +#### Boolean attributes + +The attribute values `true`, `false` and `nil` are interpreted +as booleans. If you use the attribute wrapper you can omit the attribute assigment. + +~~~ slim +input type="text" disabled="disabled" +input type="text" disabled=true +input(type="text" disabled) + +input type="text" +input type="text" disabled=false +input type="text" disabled=nil +~~~ + +#### Attribute merging + +You can configure attributes to be merged if multiple are given (See option `:merge_attrs`). In the default configuration +this is done for class attributes with the white space as delimiter. + +~~~ slim +a.menu class="highlight" href="http://slim-lang.com/" Slim-lang.com +~~~ + +This renders as: + +~~~ html +Slim-lang.com +~~~ + +You can also use an `Array` as attribute value and the array elements will be merged using the delimiter. + +~~~ slim +a class=["menu","highlight"] +a class=:menu,:highlight +~~~ + +#### Splat attributes `*` + +The splat shortcut allows you to turn a hash into attribute/value pairs. + +~~~ slim +.card*{'data-url'=>place_path(place), 'data-id'=>place.id} = place.name +~~~ + +This renders as: + +~~~ html +
Slim's house
+~~~ + +You can also use methods or instance variables which return a hash as shown here: + +~~~ slim +.card *method_which_returns_hash = place.name +.card *@hash_instance_variable = place.name +~~~ + +The hash attributes which support attribute merging (see Slim option `:merge_attrs`) can be given as an `Array` + +~~~ slim +.first *{class: [:second, :third]} Text +~~~ + +This renders as: + +~~~ html +div class="first second third" +~~~ + +Splat attributes prefix may be configured via `splat_prefix` option. Default value is `'*'` + +#### Dynamic tags `*` + +You can create completely dynamic tags using the splat attributes. Just create a method which returns a hash +with the :tag key. + +~~~ slim +ruby: + def a_unless_current + @page_current ? {tag: 'span'} : {tag: 'a', href: 'http://slim-lang.com/'} + end +- @page_current = true +*a_unless_current Link +- @page_current = false +*a_unless_current Link +~~~ + +This renders as: + +~~~ html +LinkLink +~~~ + +### Shortcuts + +#### Tag shortcuts + +You can define custom tag shortcuts by setting the option `:shortcut`. In Rails apps, you need to put this code for your shortcuts into an initializer like `config/initializers/slim.rb`. In Sinatra, you simply add the same configuration anywhere below the line where you `require 'slim'`. + +~~~ ruby +Slim::Engine.set_options shortcut: {'c' => {tag: 'container'}, '#' => {attr: 'id'}, '.' => {attr: 'class'} } +~~~ + +We can use it in Slim code like this + +~~~ slim +c.content Text +~~~ + +which renders to + +~~~ html +Text +~~~ + +#### Attribute shortcuts + +You can define custom shortcuts (Similar to `#` for id and `.` for class). + +In this example we add `&` to create a shortcut for the input elements with type attribute. + +~~~ ruby +Slim::Engine.set_options shortcut: {'&' => {tag: 'input', attr: 'type'}, '#' => {attr: 'id'}, '.' => {attr: 'class'}} +~~~ + +We can use it in Slim code like this + +~~~ slim +&text name="user" +&password name="pw" +&submit +~~~ + +which renders to + +~~~ html + + + +~~~ + +In another example we add `@` to create a shortcut for the role attribute. + +~~~ ruby +Slim::Engine.set_options shortcut: {'@' => {attr: 'role'}, '#' => {attr: 'id'}, '.' => {attr: 'class'}} +~~~ + +We can use it in Slim code like this + +~~~ slim +.person@admin = person.name +~~~ + +which renders to + +~~~ html +
Daniel
+~~~ + +You can also set multiple attributes with same value at once using one shortcut. + +~~~ ruby +Slim::Engine.set_options shortcut: {'@' => {attr: %w(data-role role)}} +~~~ + +We can use it in Slim code like this + +~~~ slim +.person@admin = person.name +~~~ + +which renders to + +~~~ html +
Daniel
+~~~ + +You can also set additional fixed value attributes to a shortcut. + +~~~ ruby +Slim::Engine.set_options shortcut: {'^' => {tag: 'script', attr: 'data-binding', + additional_attrs: { type: "text/javascript" }}} +~~~ + +Then + +~~~ slim +^products + == @products.to_json +~~~ + +which renders to + +~~~ html + +~~~ + +#### ID shortcut `#` and class shortcut `.` + +You can specify the `id` and `class` attributes in the following shortcut form + +~~~ slim +body + h1#headline + = page_headline + h2#tagline.small.tagline + = page_tagline + .content + = show_content +~~~ + +This is the same as + +~~~ slim +body + h1 id="headline" + = page_headline + h2 id="tagline" class="small tagline" + = page_tagline + div class="content" + = show_content +~~~ + +## Helpers, capturing and includes + +If you use Slim you might want to extend your template with some helpers. Assume that you have the following helper + +~~~ruby +module Helpers + def headline(&block) + if defined?(::Rails) + # In Rails we have to use capture! + "

#{capture(&block)}

" + else + # If we are using Slim without a framework (Plain Tilt), + # this works directly. + "

#{yield}

" + end + end +end +~~~ + +which is included in the scope that executes the Slim template code. The helper can then be used in the Slim template as follows + +~~~ slim +p + = headline do + ' Hello + = user.name +~~~ + +The content in the `do` block is then captured automatically and passed to the helper via `yield`. As a syntactic +sugar you can omit the `do` keyword and write only + +~~~ slim +p + = headline + ' Hello + = user.name +~~~ + +### Capturing to local variables + +Using the `Binding` you can capture to local variables as follows: + +~~~ruby +module Helpers + def capture_to_local(var, &block) + set_var = block.binding.eval("lambda {|x| #{var} = x }") + # In Rails we have to use capture! + # If we are using Slim without a framework (Plain Tilt), + # you can just yield to get the captured block. + set_var.call(defined?(::Rails) ? capture(&block) : yield) + end +end +~~~ + +The helper can then be used in the Slim template as follows + +~~~ slim +/ The captured_content variable must be known by the Binding beforehand. += capture_to_local captured_content=:captured_content + p This will be captured in the variable captured_content += captured_content +~~~ + +Another interesting use case is to use an enumerable and capture for each element. The helper could look like this + +~~~ ruby +module Capture + def capture(var, enumerable = nil, &block) + value = enumerable ? enumerable.map(&block) : yield + block.binding.eval("lambda {|x| #{var} = x }").call(value) + nil + end +end +~~~ + +and it would be used as follows + +~~~ slim +- links = { 'http://slim-lang.com' => 'The Slim Template Language' } += capture link_list=:link_list, links do |url, text| + a href=url = text +~~~ + +Afterwards, `link_list` contains the captured content. + +### Include helper + +If you want includes which are processed at compile time, you can take a look at [Include partials](doc/include.md). +However you can also execute subtemplates at runtime (similar to Rails' `#render`). You have to write your own include helper: + +~~~ ruby +module Helpers + def include_slim(name, options = {}, &block) + Slim::Template.new("#{name}.slim", options).render(self, &block) + end +end +~~~ + +This helper can then be used as follows + +~~~ slim +nav = include_slim 'menu' +section = include_slim 'content' +~~~ + +However this helper doesn't do any caching. You should therefore implement a more intelligent version of the helper which +fits your purposes. You should also be aware that most frameworks already bring their own include helper, e.g. Rails has `render`. + +## Text interpolation + +Use standard Ruby interpolation. The text will be html escaped by default, but you can avoid escaping by using double braces. + +~~~ slim +body + h1 Welcome #{current_user.name} to the show. + | Unescaped #{{content}} is also possible. +~~~ + +To escape the interpolation (i.e. render as is) + +~~~ slim +body + h1 Welcome \#{current_user.name} to the show. +~~~ + +## Embedded engines (Markdown, ...) + +Thanks to [Tilt](https://github.com/rtomayko/tilt), Slim has extensive support for embedding other template engines. + +Examples: + +~~~ slim +coffee: + square = (x) -> x * x + +markdown: + #Header + Hello from #{"Markdown!"} + Second Line! + +p: markdown: Tag with **inline** markdown! +~~~ + +Supported engines: + +| Filter | Required gems | Type | Description | +| ------ | ------------- | ---- | ----------- | +| ruby: | none | Shortcut | Shortcut to embed ruby code | +| javascript: | none | Shortcut | Shortcut to embed javascript code and wrap in script tag | +| css: | none | Shortcut | Shortcut to embed css code and wrap in style tag | +| sass: | sass | Compile time | Embed sass code and wrap in style tag | +| scss: | sass | Compile time | Embed scss code and wrap in style tag | +| less: | less | Compile time | Embed less css code and wrap in style tag | +| coffee: | coffee-script | Compile time | Compile coffee script code and wrap in script tag | +| markdown: | redcarpet/rdiscount/kramdown | Compile time + Interpolation | Compile markdown code and interpolate #\{variables} in text | +| textile: | redcloth | Compile time + Interpolation | Compile textile code and interpolate #\{variables} in text | +| rdoc: | rdoc | Compile time + Interpolation | Compile rdoc code and interpolate #\{variables} in text | + +The embedded engines can be configured in Slim by setting the options directly on the `Slim::Embedded` filter. Example: + +~~~ ruby +Slim::Embedded.options[:markdown] = {auto_ids: false} +~~~ + +You can also specify HTML attributes for the following embedded engines: +* Javascript +* CSS +* CoffeeScript +* LESS +* SASS +* SCSS + +Example: + +~~~ scss +scss class="myClass": + $color: #f00; + body { color: $color; } +~~~ + +This will generate the following HTML: + +~~~ html + +~~~ + +## Configuring Slim + +Slim and the underlying [Temple](https://github.com/judofyr/temple) framework are highly configurable. +The way how you configure Slim depends a bit on the compilation mechanism (Rails or [Tilt](https://github.com/rtomayko/tilt)). It is always possible to set default options per `Slim::Engine` class. This can be done in Rails' environment files. For instance, in config/environments/development.rb you probably want: + +### Default options + +~~~ ruby +# Indent html for pretty debugging and do not sort attributes +Slim::Engine.set_options pretty: true, sort_attrs: false +~~~ + +You can also access the option hash directly: + +~~~ ruby +Slim::Engine.options[:pretty] = true +~~~ + +### Setting options at runtime + +There are two ways to set options at runtime. For Tilt templates (`Slim::Template`) you can set +the options when you instantiate the template: + +~~~ ruby +Slim::Template.new('template.slim', optional_option_hash).render(scope) +~~~ + +The other possibility is to set the options per thread which is interesting mostly for Rails: + +~~~ ruby +Slim::Engine.with_options(option_hash) do + # Any Slim engines which are created here use the option_hash + # For example in Rails: + render :page, layout: true +end +~~~ + +You have to be aware that the compiled engine code and the options are cached per template in Rails and you cannot change the option afterwards. + +~~~ ruby +# First render call +Slim::Engine.with_options(pretty: true) do + render :page, layout: true +end + +# Second render call +Slim::Engine.with_options(pretty: false) do + render :page, layout: true # :pretty is still true because it is cached +end +~~~ + +### Available options + +The following options are exposed by the `Slim::Engine` and can be set with `Slim::Engine.set_options`. +There are a lot of them but the good thing is, that Slim checks the configuration keys and reports an error if you try to use an invalid configuration key. + + +| Type | Name | Default | Purpose | +| ---- | ---- | ------- | ------- | +| String | :file | nil | Name of parsed file, set automatically by Slim::Template | +| Integer | :tabsize | 4 | Number of white spaces per tab (used by the parser) | +| String | :encoding | "utf-8" | Set encoding of template | +| String | :default_tag | "div" | Default tag to be used if tag name is omitted | +| Hash | :shortcut | \{'.' => {attr: 'class'}, '#' => {attr: 'id'}} | Attribute shortcuts | +| Hash | :code_attr_delims | \{'(' => ')', '[' => ']', '{' => '}'} | Attribute delimiters for Ruby code attributes | +| Hash | :attr_list_delims | \{'(' => ')', '[' => ']', '{' => '}'} | Attribute list delimiter | +| Array<Symbol,String> | :enable_engines | nil (All enabled) | List of enabled embedded engines (whitelist) | +| Array<Symbol,String> | :disable_engines | nil (None disabled) | List of disabled embedded engines (blacklist) | +| Boolean | :disable_capture | false (true in Rails) | Disable capturing in blocks (blocks write to the default buffer | +| Boolean | :disable_escape | false | Disable automatic escaping of strings | +| Boolean | :use_html_safe | false (true in Rails) | Use String#html_safe? from ActiveSupport (Works together with :disable_escape) | +| Symbol | :format | :xhtml | HTML output format (Possible formats :html, :xhtml, :xml) | +| String | :attr_quote | '"' | Character to wrap attributes in html (can be ' or ") | +| Hash | :merge_attrs | \{'class' => ' '} | Joining character used if multiple html attributes are supplied (e.g. class="class1 class2") | +| Array<String> | :hyphen_attrs | %w(data) | Attributes which will be hyphenated if a Hash is given (e.g. data={a:1,b:2} will render as data-a="1" data-b="2") | +| Boolean | :sort_attrs | true | Sort attributes by name | +| Symbol | :js_wrapper | nil | Wrap javascript by :comment, :cdata or :both. You can also :guess the wrapper based on :format. | +| Boolean | :pretty | false | Pretty HTML indenting, only block level tags are indented (This is slower!) | +| String | :indent | ' ' | Indentation string | +| Boolean | :streaming | false (true in Rails, see below how to disable it!) | Enable output streaming, improves the perceived performance | +| Class | :generator | Temple::Generators::StringBuffer/ RailsOutputBuffer | Temple code generator (default generator generates string buffer) | +| String | :buffer | '_buf' ('@output_buffer' in Rails) | Variable used for buffer | +| String | :splat_prefix | '*' | Prefix used for splat attributes | + +There are more options which are supported by the Temple filters but which are not exposed and are not officially supported. You +have to take a look at the Slim and Temple code for that. + +### Option priority and inheritance + +For developers who know more about Slim and Temple architecture it is possible to override default +options at different positions. Temple uses an inheritance mechanism to allow subclasses to override +options of the superclass. The option priorities are as follows: + +1. `Slim::Template` options passed at engine instantiation +2. `Slim::Template.options` +3. `Slim::Engine.thread_options`, `Slim::Engine.options` +5. Parser/Filter/Generator `thread_options`, `options` (e.g `Slim::Parser`, `Slim::Compiler`) + +It is also possible to set options for superclasses like `Temple::Engine`. But this will affect all temple template engines then. + +~~~ ruby +Slim::Engine < Temple::Engine +Slim::Compiler < Temple::Filter +~~~ + +## Plugins + +Slim currently provides plugins for logic less mode, includes and I18n. See the plugin documentation. + +* [Logic less mode](doc/logic_less.md) +* [Include partials](doc/include.md) +* [Translator/I18n](doc/translator.md) +* [Smart text mode](doc/smart.md) + +## Framework support + +### Tilt + +Slim uses [Tilt](https://github.com/rtomayko/tilt) to compile the generated code. If you want to use the Slim template directly, you can use the Tilt interface. + +~~~ ruby +Tilt.new['template.slim'].render(scope) +Slim::Template.new('template.slim', optional_option_hash).render(scope) +Slim::Template.new(optional_option_hash) { source }.render(scope) +~~~ + +The optional option hash can have to options which were documented in the section above. The scope is the object in which the template +code is executed. + +### Sinatra + +~~~ ruby +require 'sinatra' +require 'slim' + +get('/') { slim :index } + + __END__ +@@ index +doctype html +html + head + title Sinatra With Slim + body + h1 Slim Is Fun! +~~~ + +### Rails + +Rails generators are provided by [slim-rails](https://github.com/slim-template/slim-rails). slim-rails +is not necessary to use Slim in Rails though. Just install Slim and add it to your Gemfile with `gem 'slim'`. +Then just use the .slim extension and you're good to go. + +#### Streaming + +HTTP streaming is enabled by default if you use a Rails version which supports it. However you have to be aware that streaming only improves the perceived +performance. The rendering time in total will increase. If you want to disable it use: + +~~~ ruby +Slim::RailsTemplate.set_options streaming: false +~~~ + +### Angular2 + +Slim now supports Angular2 syntax. But you need to set some configuration options: + +#### `splat_prefix` option + +This option tells parser what syntax to use for splat attributes. +Default value is asterisk: `splat_prefix: '*'` +Asterisk is also used in Angular2 for structural directives such as `*ngIf` and others, so default configuration causes a conflict between slim and angular2 syntax. + +There are two ways to resolve it: + +* Set `splat_prefix` to any custom value, double asterisk, for example: `splat_prefix: '**'`. Now structural directives should work as expected. Remember that now splat attributes should be written with new custom prefix before them. +* Use alternative directive syntax without asterisk. + +#### Attribute delimeters + +Angular and slim both uses brackets in their syntax. So there are also two ways: +* Use alternative syntax for binding (`bind-...` and so on) +* Limit attribute delimeters to curly braces only: +``` +code_attr_delims: { + '{' => '}', +}, +attr_list_delims: { + '{' => '}', +}, +``` + +Now you can use something like this: +``` +h1{ #var (bind1)="test" [bind2]="ok" [(bind3)]="works?" *ngIf="expr" *ngFor="expression" } {{it works}} +``` + +Will be compiled to: +``` +

+ {{it works}} +

+``` + +## Tools + +### Slim Command 'slimrb' + +The gem 'slim' comes with the small tool 'slimrb' to test Slim from the command line. + +
+$ slimrb --help
+Usage: slimrb [options]
+    -s, --stdin                      Read input from standard input instead of an input file
+        --trace                      Show a full traceback on error
+    -c, --compile                    Compile only but do not run
+    -e, --erb                        Convert to ERB
+        --rails                      Generate rails compatible code (Implies --compile)
+    -r, --require library            Load library or plugin with -r slim/plugin
+    -p, --pretty                     Produce pretty html for debugging purposes
+    -o, --option name=code           Set slim option
+    -l, --locals Hash|YAML|JSON      Set local variables
+    -h, --help                       Show this message
+    -v, --version                    Print version
+
+ +Start 'slimrb', type your code and press Ctrl-d to send EOF. In Windows Command Prompt press Ctrl-z, Enter to send EOF. Example usage: + +
+$ slimrb
+markdown:
+  First paragraph.
+
+  Second paragraph.
+
+  * one
+  * two
+  * three
+
+//Enter Ctrl-d
+<p>First paragraph </p>
+
+<p>Second paragraph </p>
+
+<ul>
+<li>one</li>
+<li>two</li>
+<li>three</li>
+</ul>
+
+ +### Syntax Highlighters + +There are plugins for various text editors (including the most important ones - Vim, Emacs and Textmate): + +* [Vim](https://github.com/slim-template/vim-slim) +* [Emacs](https://github.com/slim-template/emacs-slim) +* [Textmate / Sublime Text](https://github.com/slim-template/ruby-slim.tmbundle) +* [Espresso text editor](https://github.com/slim-template/Slim-Sugar) +* [Coda](https://github.com/slim-template/Coda-2-Slim.mode) +* [Atom](https://github.com/slim-template/language-slim) + +### Template Converters (HAML, ERB, ...) + +* Slim can be converted to ERB using `slimrb` or `Slim::ERBConverter' which are both included in the Slim gem +* [Haml2Slim converter](https://github.com/slim-template/haml2slim) +* [ERB2Slim, HTML2Slim converter](https://github.com/slim-template/html2slim) + +## Testing + +### Benchmarks + + *Yes, Slim is one of the fastest Ruby template engines out there! + In production mode Slim is nearly as fast as Erubis (which is the fastest template engine). + But we would be happy if you chose Slim also for any other reason, we assure + you performance will not be an obstacle.* + +Run the benchmarks with `rake bench`. You can add the option `slow` to +run the slow parsing benchmark which needs more time. You can also increase the number of iterations. + +~~~ +$ rake bench slow=1 iterations=1000 +~~~ + +We run the benchmarks for every commit on Travis-CI. Take a look at the newest benchmarking results: + +### Test suite and continuous integration + +Slim provides an extensive test-suite based on minitest. You can run the tests +with 'rake test' and the rails integration tests with 'rake test:rails'. + +We are currently experimenting with human-readable literate tests which are written as markdown files: [TESTS.md](test/literate/TESTS.md) + +Travis-CI is used for continuous integration testing: + +Slim is working well on all major Ruby implementations: + +* Ruby 2.0, 2.1, 2.2 and 2.3 +* JRuby 1.9 mode +* Rubinius 2.0 + +## Contributing + +If you'd like to help improve Slim, clone the project with Git by running: + +~~~ +$ git clone git://github.com/slim-template/slim +~~~ + +Work your magic and then submit a pull request. We love pull requests! + +Please remember to keep the compatibility with Ruby versions 2.0.0, 2.1.0, 2.2.0 and 2.3.0. + +If you find the documentation lacking, help us out and update this README.md. If you don't have the time to work on Slim, but found something we should know about, please submit an issue. + +## License + +Slim is released under the [MIT license](http://www.opensource.org/licenses/MIT). + +## Authors + +* [Daniel Mendler](https://github.com/minad) (Lead developer) +* [Andrew Stone](https://github.com/stonean) +* [Fred Wu](https://github.com/fredwu) + +## Donations and sponsoring + +If you want to support this project please visit the Gittip and Flattr pages. + +[![Gittip donate button](https://img.shields.io/gratipay/bevry.svg)](https://www.gittip.com/min4d/ "Donate weekly to this project using Gittip") +[![Flattr donate button](https://raw.github.com/balupton/flattr-buttons/master/badge-89x18.gif)](https://flattr.com/submit/auto?user_id=min4d&url=http%3A%2F%2Fslim-lang.org%2F "Donate monthly to this project using Flattr") + +Currently the donations will be used to cover the hosting costs (domain name etc). + +## Discuss + +* [Google Group](http://groups.google.com/group/slim-template) + +## Related projects + +Template compilation framework: + +* [Temple](https://github.com/judofyr/temple) + +Framework support: + +* [Rails generators (slim-rails)](https://github.com/slim-template/slim-rails) + * [slimkeyfy - Translation string extraction](https://github.com/phrase/slimkeyfy) + +Syntax highlighting: + +* [Vim](https://github.com/slim-template/vim-slim) +* [Emacs](https://github.com/slim-template/emacs-slim) +* [Textmate / Sublime Text](https://github.com/slim-template/ruby-slim.tmbundle) +* [Espresso text editor](https://github.com/slim-template/Slim-Sugar) +* [Coda](https://github.com/slim-template/Coda-2-Slim.mode) +* [Atom](https://github.com/slim-template/language-slim) + +Static code analysis: + +* [Slim-Lint](https://github.com/sds/slim-lint) +* [SublimeLinter-slim-lint](https://github.com/elstgav/SublimeLinter-slim-lint) + +Template Converters (HAML, ERB, ...): + +* [ERB 2 Slim](http://erb2slim.com/) +* [Haml2Slim converter](https://github.com/slim-template/haml2slim) +* [ERB2Slim, HTML2Slim converter](https://github.com/slim-template/html2slim) + +Language ports/Similar languages: + +* [Sliq (Slim/Liquid integration)](https://github.com/slim-template/sliq) +* [Slm (Slim port to Javascript)](https://github.com/slm-lang/slm) +* [Coffee script plugin for Slim](https://github.com/yury/coffee-views) +* [Clojure port of Slim](https://github.com/chaslemley/slim.clj) +* [Hamlet.rb (Similar template language)](https://github.com/gregwebs/hamlet.rb) +* [Plim (Python port of Slim)](https://github.com/2nd/plim) +* [Skim (Slim for Javascript)](https://github.com/jfirebaugh/skim) +* [Emblem.js (Javascript, similar to Slim)](https://github.com/machty/emblem.js) +* [Hamlit (High performance Haml implementation, based on Temple like Slim)](https://github.com/k0kubun/hamlit) +* [Faml (Faster Haml implementation, also using Temple like Slim)](https://github.com/eagletmt/faml) +* [Haml (Older engine which inspired Slim)](https://github.com/haml/haml) +* [Jade (Similar engine for javascript)](https://github.com/visionmedia/jade) +* [Pug (Successor of Jade, Similar engine for javascript)](https://github.com/pugjs/pug) +* [Sweet (Similar engine which also allows to write classes and functions)](https://github.com/joaomdmoura/sweet) +* [Amber (Similar engine for Go)](https://github.com/eknkc/amber) +* [Slang (Slim-inspired templating language for Crystal)](https://github.com/jeromegn/slang) diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/Rakefile b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/Rakefile new file mode 100644 index 0000000..9ee81cc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/Rakefile @@ -0,0 +1,87 @@ +begin + require 'bundler/setup' + Bundler::GemHelper.install_tasks +rescue Exception +end + +require 'rake/testtask' + +desc 'Run Slim benchmarks! (default parameters slow=false)' +task :bench, :slow do + ruby('benchmarks/run-benchmarks.rb') +end + +task 'test' => %w(test:core_and_plugins) + +namespace 'test' do + task 'core_and_plugins' => %w(core literate logic_less translator smart include) + + Rake::TestTask.new('core') do |t| + t.libs << 'lib' << 'test/core' + t.test_files = FileList['test/core/test_*.rb'] + t.warning = true + #t.ruby_opts << '-w' << '-v' + end + + Rake::TestTask.new('literate') do |t| + t.libs << 'lib' << 'test/literate' + t.test_files = FileList['test/literate/run.rb'] + t.warning = true + end + + Rake::TestTask.new('logic_less') do |t| + t.libs << 'lib' << 'test/core' + t.test_files = FileList['test/logic_less/test_*.rb'] + t.warning = true + end + + Rake::TestTask.new('translator') do |t| + t.libs << 'lib' << 'test/core' + t.test_files = FileList['test/translator/test_*.rb'] + t.warning = true + end + + Rake::TestTask.new('smart') do |t| + t.libs << 'lib' << 'test/core' + t.test_files = FileList['test/smart/test_*.rb'] + t.warning = true + end + + Rake::TestTask.new('include') do |t| + t.libs << 'lib' << 'test/core' + t.test_files = FileList['test/include/test_*.rb'] + t.warning = true + end + + Rake::TestTask.new('rails') do |t| + t.libs << 'lib' + t.test_files = FileList['test/rails/test/test_*.rb'] + t.warning = true + end + + Rake::TestTask.new('sinatra') do |t| + t.libs << 'lib' + t.test_files = FileList['test/sinatra/test_*.rb'] + + # Copied from test task in Sinatra project to mimic their approach + t.ruby_opts = ['-r rubygems'] if defined? Gem + t.ruby_opts << '-I.' + t.warning = true + end +end + +begin + require 'yard' + YARD::Rake::YardocTask.new do |t| + t.files = %w(lib/**/*.rb) + end +rescue LoadError + task :yard do + abort 'YARD is not available. In order to run yard, you must: gem install yard' + end +end + +desc "Generate Documentation" +task doc: :yard + +task default: 'test' diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/context.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/context.rb new file mode 100644 index 0000000..4d71e34 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/context.rb @@ -0,0 +1,11 @@ +class Context + def header + 'Colors' + end + + def item + [ { name: 'red', current: true, url: '#red' }, + { name: 'green', current: false, url: '#green' }, + { name: 'blue', current: false, url: '#blue' } ] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/profile-parser.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/profile-parser.rb new file mode 100755 index 0000000..e4e121b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/profile-parser.rb @@ -0,0 +1,10 @@ +#!/usr/bin/env ruby + +$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib'), File.dirname(__FILE__)) + +require 'slim' + +content = File.read(File.dirname(__FILE__) + '/view.slim') +engine = Slim::Engine.new + +1000.times { engine.call(content) } diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/profile-render.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/profile-render.rb new file mode 100755 index 0000000..2f58241 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/profile-render.rb @@ -0,0 +1,12 @@ +#!/usr/bin/env ruby + +$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib'), File.dirname(__FILE__)) + +require 'slim' +require 'context' + +content = File.read(File.dirname(__FILE__) + '/view.slim') +slim = Slim::Template.new { content } +context = Context.new + +10000.times { slim.render(context) } diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/run-benchmarks.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/run-benchmarks.rb new file mode 100755 index 0000000..200ebbd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/run-benchmarks.rb @@ -0,0 +1,120 @@ +#!/usr/bin/env ruby + +$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib'), File.dirname(__FILE__)) + +require 'slim' +require 'context' + +require 'benchmark/ips' +require 'tilt' +require 'erubis' +require 'erb' +require 'haml' + +class SlimBenchmarks + def initialize(slow) + @benches = Hash.new { |h, k| h[k] = [] } + + @erb_code = File.read(File.dirname(__FILE__) + '/view.erb') + @haml_code = File.read(File.dirname(__FILE__) + '/view.haml') + @slim_code = File.read(File.dirname(__FILE__) + '/view.slim') + + init_compiled_benches + init_tilt_benches + init_parsing_benches if slow + end + + def init_compiled_benches + haml = Haml::Engine.new(@haml_code, format: :html5, escape_attrs: false) + + context = Context.new + + haml.def_method(context, :run_haml) + context.instance_eval %{ + def run_erb; #{ERB.new(@erb_code).src}; end + def run_erubis; #{Erubis::Eruby.new(@erb_code).src}; end + def run_temple_erb; #{Temple::ERB::Engine.new.call @erb_code}; end + def run_fast_erubis; #{Erubis::FastEruby.new(@erb_code).src}; end + def run_slim_pretty; #{Slim::Engine.new(pretty: true).call @slim_code}; end + def run_slim_ugly; #{Slim::Engine.new.call @slim_code}; end + } + + bench(:compiled, 'erb') { context.run_erb } + bench(:compiled, 'erubis') { context.run_erubis } + bench(:compiled, 'fast erubis') { context.run_fast_erubis } + bench(:compiled, 'temple erb') { context.run_temple_erb } + bench(:compiled, 'slim pretty') { context.run_slim_pretty } + bench(:compiled, 'slim ugly') { context.run_slim_ugly } + bench(:compiled, 'haml') { context.run_haml } + end + + def init_tilt_benches + tilt_erb = Tilt::ERBTemplate.new { @erb_code } + tilt_erubis = Tilt::ErubisTemplate.new { @erb_code } + tilt_temple_erb = Temple::ERB::Template.new { @erb_code } + tilt_haml = Tilt::HamlTemplate.new(format: :html5) { @haml_code } + tilt_slim_pretty = Slim::Template.new(pretty: true) { @slim_code } + tilt_slim_ugly = Slim::Template.new { @slim_code } + + context = Context.new + + bench(:tilt, 'erb') { tilt_erb.render(context) } + bench(:tilt, 'erubis') { tilt_erubis.render(context) } + bench(:tilt, 'temple erb') { tilt_temple_erb.render(context) } + bench(:tilt, 'slim pretty') { tilt_slim_pretty.render(context) } + bench(:tilt, 'slim ugly') { tilt_slim_ugly.render(context) } + bench(:tilt, 'haml') { tilt_haml.render(context) } + end + + def init_parsing_benches + context = Context.new + context_binding = context.instance_eval { binding } + + bench(:parsing, 'erb') { ERB.new(@erb_code).result(context_binding) } + bench(:parsing, 'erubis') { Erubis::Eruby.new(@erb_code).result(context_binding) } + bench(:parsing, 'fast erubis') { Erubis::FastEruby.new(@erb_code).result(context_binding) } + bench(:parsing, 'temple erb') { Temple::ERB::Template.new { @erb_code }.render(context) } + bench(:parsing, 'slim pretty') { Slim::Template.new(pretty: true) { @slim_code }.render(context) } + bench(:parsing, 'slim ugly') { Slim::Template.new { @slim_code }.render(context) } + bench(:parsing, 'haml') { Haml::Engine.new(@haml_code, format: :html5).render(context) } + end + + def run + @benches.each do |group_name, group_benches| + puts "Running #{group_name} benchmarks:" + + Benchmark.ips do |x| + group_benches.each do |name, block| + x.report("#{group_name} #{name}", &block) + end + + x.compare! + end + end + + puts " +Compiled benchmark: Template is parsed before the benchmark and + generated ruby code is compiled into a method. + This is the fastest evaluation strategy because it benchmarks + pure execution speed of the generated ruby code. + +Compiled Tilt benchmark: Template is compiled with Tilt, which gives a more + accurate result of the performance in production mode in frameworks like + Sinatra, Ramaze and Camping. (Rails still uses its own template + compilation.) + +Parsing benchmark: Template is parsed every time. + This is not the recommended way to use the template engine + and Slim is not optimized for it. Activate this benchmark with 'rake bench slow=1'. + +Temple ERB is the ERB implementation using the Temple framework. It shows the +overhead added by the Temple framework compared to ERB. +" + end + + def bench(group, name, &block) + @benches[group].push([name, block]) + end +end + +SlimBenchmarks.new(ENV['slow']).run diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/run-diffbench.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/run-diffbench.rb new file mode 100755 index 0000000..f08ead7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/run-diffbench.rb @@ -0,0 +1,21 @@ +#!/usr/bin/env ruby + +$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib'), File.dirname(__FILE__)) + +require 'slim' +require 'context' +require 'diffbench' + +content = File.read(File.dirname(__FILE__) + '/view.slim') +engine = Slim::Engine.new +template = Slim::Template.new { content } +context = Context.new + +DiffBench.bm do + report("Parse") do + 2000.times { engine.call(content) } + end + report("Render") do + 100000.times { template.render(context) } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/view.erb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/view.erb new file mode 100644 index 0000000..af24efb --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/view.erb @@ -0,0 +1,25 @@ + + + + + Simple Benchmark + + + + +

<%= header %>

+ <% unless item.empty? %> +
    + <% for i in item %> + <% if i[:current] %> +
  • <%= i[:name] %>
  • + <% else %> +
  • <%= i[:name] %>
  • + <% end %> + <% end %> +
+ <% else %> +

The list is empty.

+ <% end %> + + diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/view.haml b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/view.haml new file mode 100644 index 0000000..8eefb92 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/view.haml @@ -0,0 +1,20 @@ +!!! html + +%html{ lang: "en" } + %head + %title Simple Benchmark + %meta{ charset: "utf-8" } + %meta{ name: "description", content: "This is an example of a meta description." } + %body + %h1= header + - unless item.empty? + %ul + - for i in item + - if i[:current] + %li + %strong= i[:name] + - else + %li + %a{:href => i[:url]}= i[:name] + - else + %p The list is empty. diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/view.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/view.slim new file mode 100644 index 0000000..a19a30b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/benchmarks/view.slim @@ -0,0 +1,19 @@ +doctype html +html lang="en" + head + title Simple Benchmark + meta charset="utf-8" + meta name="description" content="This is an example of a meta description." + body + h1 == header + - unless item.empty? + ul + - for i in item + - if i[:current] + li + strong == i[:name] + - else + li + a href==i[:url] == i[:name] + - else + p The list is empty. diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/bin/slimrb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/bin/slimrb new file mode 100755 index 0000000..f6dbcb6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/bin/slimrb @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby + +$:.unshift File.dirname(__FILE__) + '/../lib' +require 'slim/command' + +Slim::Command.new(ARGV).run diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/include.md b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/include.md new file mode 100644 index 0000000..5d827e5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/include.md @@ -0,0 +1,20 @@ +# Include + +The include plugin allows Slim templates to include other files. The .slim extension is appended automatically to the +filename. If the included file is not a Slim file, it is interpreted as a text file with `#{interpolation}`. + +Example: + + include partial.slim + include partial + include partial.txt + +Enable the include plugin with + + require 'slim/include' + +# Options + +| Type | Name | Default | Purpose | +| ---- | ---- | ------- | ------- | +| Array | :include_dirs | [Dir.pwd, '.'] | Directories where to look for the files | diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/include.md b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/include.md new file mode 100644 index 0000000..9c23c3d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/include.md @@ -0,0 +1,20 @@ +# インクルード + +インクルードプラグインを使うことで, Slim テンプレートに他の Slim ファイルを読み込むことができます。.slim 拡張子はファイル名に自動的に付加されます。 +読み込まれたファイルが Slim でない場合は `#{文字列展開}` を含んだテキストファイルとして扱われます。 + +例: + + include partial.slim + include partial + include partial.txt + +インクルードプラグインを有効化 + + require 'slim/include' + +# オプション + +| タイプ | 名前 | デフォルト値 | 目的 | +| ------ | ---- | ------------ | ---- | +| Array | :include_dirs | [Dir.pwd, '.'] | ファイルを検索するディレクトリ | diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/logic_less.md b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/logic_less.md new file mode 100644 index 0000000..9f5391e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/logic_less.md @@ -0,0 +1,137 @@ +# ロジックレスモード + +ロジックレスモードは [Mustache](https://github.com/defunkt/mustache) にインスパイアされています。ロジックレスモードは +例えば動的コンテンツを含む再帰的ハッシュツリーのような辞書オブジェクトを使います。 + +## 条件付き + +オブジェクトが false または empty? ではない場合, コンテンツが表示されます。 + + - article + h1 = title + +## 反転条件付き + +オブジェクトが false または empty? の場合, コンテンツが表示されます。 + + -! article + p Sorry, article not found + +## 繰り返し + +オブジェクトが配列の場合, この部分は繰り返されます。 + + - articles + tr: td = title + +## ラムダ式 + +Mustache のように, Slim はラムダ式をサポートします。 + + = person + = name + +ラムダ式は次のように定義できます: + + def lambda_method + "
#{yield(name: 'Andrew')}
" + end + +任意に 1 つ以上のハッシュを `yield` に渡すことができます。複数のハッシュを渡した場合, 先述したようにブロックが繰り返されます。 + +## 辞書アクセス + +サンプルコード: + + - article + h1 = title + +辞書オブジェクトは `:dictionary_access` オプションによって設定された順序でアクセスされます。デフォルトの順序: + +1. `シンボル` - `article.respond_to?(:has_key?)` 且つ `article.has_key?(:title)` の場合, Slim は `article[:title]` を実行します。 +2. `文字列` - `article.respond_to?(:has_key?)` 且つ `article.has_key?('title')` の場合, Slim は `article['title']` を実行します。 +3. `メソッド` - `article.respond_to?(:title)` の場合, Slim は `article.send(:title)` を実行します。 +4. `インスタンス変数` - `article.instance_variable_defined?(@title)` の場合, Slim は `article.instance_variable_get @title` を実行します。 + +すべて失敗した場合, Slim は親オブジェクトに対して同じ順序で title の参照を解決しようとします。この例では, 親オブジェクトはレンダリングしているテンプレートに対する辞書オブジェクトになります。 + +ご想像のとおり, article への参照は辞書オブジェクトに対して同じ手順で行われます。インスタンス変数はビューのコードでは利用を許されていませんが, Slim はそれを見つけて使います。基本的には, テンプレートの中で @ プレフィックスを落として使っています。パラメータ付きメソッドの呼び出しは許可されません。 + + +## 文字列 + +`self` キーワードは検討中の要素を `.to_s` した値を返します。 + +辞書オブジェクトを与え, + + { + article: [ + 'Article 1', + 'Article 2' + ] + } + +ビューで次のように + + - article + tr: td = self + +これは次のようになります。 + + + Article 1 + + + Article 2 + + + +## Rails でロジックレスモード + +インストール: + + $ gem install slim + +require で指定: + + gem 'slim', require: 'slim/logic_less' + +特定のアクションでのみロジックレスモードを有効化したい場合, まず設定でロジックレスモードを global に無効化します。 + + Slim::Engine.set_options logic_less: false + +さらに, アクションの中でレンダリングする度にロジックレスモードを有効化します。 + + class Controller + def action + Slim::Engine.with_options(logic_less: true) do + render + end + end + end + +## Sinatra でロジックレスモード + +Sinatra には Slim のビルトインサポートがあります。しなければならないのはロジックレス Slim プラグインを require することです。config.ru で require できます: + + require 'slim/logic_less' + +これで準備は整いました! + +特定のアクションでのみロジックレスモードを有効化したい場合, まず設定でロジックレスモードを global に無効化します。 + + Slim::Engine.set_options logic_less: false + +さらに, アクションの中でレンダリングする度にロジックレスモードを有効化します。 + + get '/page' + slim :page, logic_less: true + end + +## オプション + +| 種類 | 名前 | デフォルト | 用途 | +| ---- | ---- | ------- | ------- | +| 真偽値 | :logic_less | true | ロジックレスモードを有効化 ('slim/logic_less' の required が必要) | +| 文字列 | :dictionary | "self" | 変数が検索される辞書への参照 | +| シンボル/配列<シンボル> | :dictionary_access | [:symbol, :string, :method, :instance_variable] | 辞書のアクセス順序 (:symbol, :string, :method, :instance_variable) | diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/smart.md b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/smart.md new file mode 100644 index 0000000..f036653 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/smart.md @@ -0,0 +1,102 @@ +# スマートテキスト + +テキストとマークアップを組み合わせる最も簡単な方法は スマートテキストモード を使うことです。 + +スマートテキストプラグインを有効化します。 + + require 'slim/smart' + +自動的に `:implicit_text` オプションが有効になることで, +次のように簡単にテキストを入力できるようになります: + + p + This is text. + +小文字のタグ名や暗黙的なテキスト行などの特殊文字で始まっていない行を +Slim に自動的に処理させることができます。 +テキストが複数行にわたる場合, 単にそれらをインデントします。 + + p + This is text, + and it spans + several lines. + +`>` を使って明示的にテキストをマークすることもできます。 +例えば, 小文字や特殊文字で始まっている場合, +テキストが複数行にわたる場合, +単に見た目の一貫性のために, +タグ名に大文字を使いたい場合, +`:implicit_text` オプションを無効にしたままにする必要がある場合です。 + + p + > 'This is text, too.' + p + > + This is text + which spans + several lines. + +`:smart_text_escaping` が有効化されている限り, +エスケープされるべきテキストは自動的にエスケープされます。 +しかし, 不便にならないように検出された HTML エンティティはそのまま使われます。 +この方法はいつでも HTML のエスケープを気にすることのない, +最も理想的な方法です。 + + h1 Questions & Answers + footer + Copyright © #{Time.now.year} + +スマートテキストの素晴らしいところの 1 つはマークアップとよくミックスしているところです。 +スマートテキストの行は通常改行を維持するので, +強調やリンクのような他のタグを簡単に混ぜ合わせて使うことができます: + + p + Your credit card + strong will not + > be charged now. + p + Check + a href=r(:faq) our FAQ + > for more info. + +(タグから小文字のテキストを区別する場合明示的なテキストを示すインジケーター `>` の使用には注意してください)。 + +インラインタグのまわりにスペースを入れたくない場合があります。 +幸いなことにスマートテキストはこの一般的なケースを処理できます。 +スマートテキストのブロックが `:smart_text_begin_chars` で指定 (デフォルトは `,.;:!?)]}`) +された文字で始まる場合には先頭の改行が行われません。 +同様に, スマートテキストのブロックが `:smart_text_begin_chars` で指定 (デフォルトは `,.;:!?)]}`) +された文字で終わる場合には改行されません。 +これによって通常のテキストとリンクや span タグを混在させることがとても容易になります: + + p + Please proceed to + a href="/" our homepage + . + p + Status: failed ( + a href="#1" details + ). + +スマートテキストはタグのショートカットをも把握しているので, +次のような場合にも正しく対応します: + + .class + #id + #{'More'} + i text + ... + +当然のことながら, これは短いテキストのスニペットでより便利に作業できることを意味しています。 +ほとんどがテキストのコンテンツの場合, Markdown や Textile のような +ビルトインの埋め込みエンジンを使う方が良いでしょう。 + +## オプション + +| 種類 | 名前 | デフォルト | 用途 | +| ---- | ---- | ---------- | ---- | +| 真偽値 | :implicit_text | true | 暗黙的テキストの判別を有効化 | +| 真偽値 | :smart_text | true | スマートテキストによる処理を有効化 | +| 文字列 | :smart_text_begin_chars | ',.;:!?)]}' | スマートテキストで先頭の改行を抑制する文字 | +| 文字列 | :smart_text_end_chars | '([{' | スマートテキストで末尾の改行を抑制する文字 | +| 真偽値 | :smart_text_escaping | true | 設定すると, スマートテキスト中のエスケープが必要な HTML 文字は自動的にエスケープされる | diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/translator.md b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/translator.md new file mode 100644 index 0000000..a163e33 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/jp/translator.md @@ -0,0 +1,28 @@ +# 翻訳/I18n + +翻訳プラグインは Gettext, Fast-Gettext または Rails I18n を使ったテンプレートの自動翻訳機能を提供します。 +テンプレート内の静的テキストを翻訳版に変換します。 + +例: + + h1 Welcome to #{url}! + +Gettext は文字列を英語からドイツ語に変換し, 文字列が展開される部分は %1, %2, ... の順に変換されます。 + + "Welcome to %1!" -> "Willkommen auf %1!" + +次のようにレンダリングされます。 + +

Willkommen auf slim-lang.com!

+ +翻訳プラグインを有効化します。 + + require 'slim/translator' + +# オプション + +| 種類 | 名前 | デフォルト | 用途 | +| ---- | ---- | ---------- | ---- | +| 真偽値 | :tr | true | 翻訳の有効化 ('slim/translator' の required が必要) | +| シンボル | :tr_mode | :dynamic | 翻訳を :static = コンパイル時に実施, :dynamic = ランタイムで実施 | +| 文字列 | :tr_fn | インストールされた翻訳ライブラリに依存 | 翻訳用ヘルパ, gettext の場合 '_' | diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/logic_less.md b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/logic_less.md new file mode 100644 index 0000000..af5520a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/logic_less.md @@ -0,0 +1,137 @@ +# Logic less mode + +Logic less mode is inspired by [Mustache](https://github.com/defunkt/mustache). Logic less mode uses a dictionary object +e.g. a recursive hash tree which contains the dynamic content. + +## Conditional + +If the object is not false or empty?, the content will show + + - article + h1 = title + +## Inverted conditional + +If the object is false or empty?, the content will show + + -! article + p Sorry, article not found + +## Iteration + +If the object is an array, the section will iterate + + - articles + tr: td = title + +## Lambdas + +Like mustache, Slim supports lambdas. + + = person + = name + +The lambda method could be defined like this + + def lambda_method + "
#{yield(name: 'Andrew')}
" + end + +You can optionally pass one or more hashes to `yield`. If you pass multiple hashes, the block will be iterated as described above. + +## Dictionary access + +Example code: + + - article + h1 = title + +The dictionary object is accessed in the order given by the `:dictionary_access`. Default order: + +1. `:symbol` - If `article.respond_to?(:has_key?)` and `article.has_key?(:title)`, Slim will execute `article[:title]` +2. `:string` - If `article.respond_to?(:has_key?)` and `article.has_key?('title')`, Slim will execute `article['title']` +3. `:method` - If `article.respond_to?(:title)`, Slim will execute `article.send(:title)` +4. `:instance_variable` - If `article.instance_variable_defined?(@title)`, Slim will execute `article.instance_variable_get @title` + +If all the above fails, Slim will try to resolve the title reference in the same order against the parent object. In this example, the parent would be the dictionary object you are rendering the template against. + +As you might have guessed, the article reference goes through the same steps against the dictionary. Instance variables are not allowed in the view code, but Slim will find and use them. Essentially, you're just dropping the @ prefix in your template. Parameterized method calls are not allowed. + + +## Strings + +The `self` keyword will return the `.to_s` value for the element under consideration. + +Given + + { + article: [ + 'Article 1', + 'Article 2' + ] + } + +And + + - article + tr: td = self + +This will yield + + + Article 1 + + + Article 2 + + + +## Logic less in Rails + +Install: + + $ gem install slim + +Require: + + gem 'slim', require: 'slim/logic_less' + +You might want to activate logic less mode only for a few actions, you should disable logic-less mode globally at first in the configuration + + Slim::Engine.set_options logic_less: false + +and activate logic less mode per render call in your action + + class Controller + def action + Slim::Engine.with_options(logic_less: true) do + render + end + end + end + +## Logic less in Sinatra + +Sinatra has built-in support for Slim. All you have to do is require the logic less Slim plugin. This can be done in your config.ru: + + require 'slim/logic_less' + +You are then ready to rock! + +You might want to activate logic less mode only for a few actions, you should disable logic-less mode globally at first in the configuration + + Slim::Engine.set_options logic_less: false + +and activate logic less mode per render call in your application + + get '/page' + slim :page, logic_less: true + end + +## Options + +| Type | Name | Default | Purpose | +| ---- | ---- | ------- | ------- | +| Boolean | :logic_less | true | Enable logic less mode (Enabled if 'slim/logic_less' is required) | +| String | :dictionary | "self" | Dictionary where variables are looked up | +| Symbol/Array<Symbol> | :dictionary_access | [:symbol, :string, :method, :instance_variable] | Dictionary access order (:symbol, :string, :method, :instance_variable) | diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/smart.md b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/smart.md new file mode 100644 index 0000000..3e0988f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/smart.md @@ -0,0 +1,120 @@ +# Smart text + +The smart text plugin was created to simplify the typing and combining of text and markup in Slim templates. +Using the plugin gives you: + +* More convenient ways to type text in Slim templates. +* Smarter and more consistent HTML escaping of typed text. +* Easier combining of the text with inline HTML tags with smart handling of whitespace on the boundaries. + +To get started, enable the smart text plugin with + + require 'slim/smart' + +First of all, this automatically enables the `:implicit_text` option. +When enabled, Slim will treat any line which doesn't start +with a lowercase tag name or any of the special characters as an implicit text line. +If the text needs to span several lines, indent them as usual. + +This allows you to easily type text like this, without any leading indicator: + + This is an implicit text. + This is a text + which spans + several lines. + This is yet another text. + +This works in addition to ways already available in stock Slim: + + p This is an inline text. + p This is an inline text + which spans multiple lines. + | This is a verbatim text. + | This is a verbatim text + which spans multiple lines. +

This is in fact a verbatim text as well.

+ +You can also mark the text explicitly with a leading `>`. +This is used for example when the text starts with a lowercase letter or an unusual character, +or merely for aesthetic consistency when it spans several lines. +It may be also needed if you want to use uppercase tag names +and therefore need to keep the `:implicit_text` option disabled. + + > This is an explicit text. + > This is an explicit text + which spans + several lines. + > 'This is a text, too.' + + > This is another way + > of typing text which spans + > several lines, if you prefer that. + +BTW, all these examples can be pasted to `slimrb -r slim/smart` to see how the generated output looks like. + +The plugin also improves upon Slim's automatic HTML escaping. +As long as you leave the `:smart_text_escaping` enabled, +any non-verbatim text (i.e., any implicit, explicit, and inline text) is automatically escaped for you. +However, for your convenience, any HTML entities detected are still used verbatim. +This way you are most likely to get what you really wanted, +without having to worry about HTML escaping all the time. + + h1 Questions & Answers + footer + Copyright © #{Time.now.year} + +Another cool thing about the plugin is that it makes text mix fairly well with markup. +The text lines are made to preserve newlines as needed, +so it is easy to mix them with other tags, like emphasis or links: + + p + Your credit card + strong will not + > be charged now. + p + Check + a href='/faq' our FAQ + > for more info. + +(Note the use of the explicit text indicator `>` to distinguish lowercase text from tags). + +However, sometimes you do not want any whitespace around the inline tag at all. +Fortunately the plugin takes care of the most common cases for you as well. +The newline before the tag is suppressed if the preceding line ends +with a character from the `:smart_text_end_chars` set (`([{` by default). +Similarly, the newline after the tag is suppressed if the following line begins +with a character from the `:smart_text_begin_chars` set (`,.;:!?)]}` by default). +This makes it quite easy to naturally mix normal text with links or spans like this: + + p + Please proceed to + a href="/" our homepage + . + p + Status: failed ( + a href="#1" see details + ). + +Note that the plugin is smart enough to know about tag shortcuts, too, +so it will correctly deal even with cases like this: + + .class + #id + #{'More'} + i text + ... + +And that's it. +Of course, all this is meant only to make working with short text snippets more convenient. +For bulk text content, you are more than welcome to use one of the builtin embedded engines, +such as Markdown or Textile. + +## Options + +| Type | Name | Default | Purpose | +| ---- | ---- | ------- | ------- | +| Boolean | :implicit_text | true | Enable implicit text recognition | +| Boolean | :smart_text | true | Enable smart text mode newline processing | +| String | :smart_text_begin_chars | ',.;:!?)]}' | Characters suppressing leading newline in smart text | +| String | :smart_text_end_chars | '([{' | Characters suppressing trailing newline in smart text | +| Boolean | :smart_text_escaping | true | When set, HTML characters which need escaping are automatically escaped in smart text | diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/translator.md b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/translator.md new file mode 100644 index 0000000..884621e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/doc/translator.md @@ -0,0 +1,28 @@ +# Translator/I18n + +The translator plugin provides automatic translation of the templates using Gettext, Fast-Gettext or Rails I18n. Static text +in the template is replaced by the translated version. + +Example: + + h1 Welcome to #{url}! + +Gettext translates the string from english to german where interpolations are replaced by %1, %2, ... + + "Welcome to %1!" -> "Willkommen auf %1!" + +and renders as + +

Willkommen auf slim-lang.com!

+ +Enable the translator plugin with + + require 'slim/translator' + +# Options + +| Type | Name | Default | Purpose | +| ---- | ---- | ------- | ------- | +| Boolean | :tr | true | Enable translator (Enabled if 'slim/translator' is required) | +| Symbol | :tr_mode | :dynamic | When to translate: :static = at compile time, :dynamic = at runtime | +| String | :tr_fn | Depending on installed translation library | Translation function, could be '_' for gettext | diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim.rb new file mode 100644 index 0000000..7b03fce --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim.rb @@ -0,0 +1,14 @@ +require 'temple' +require 'slim/parser' +require 'slim/filter' +require 'slim/do_inserter' +require 'slim/end_inserter' +require 'slim/embedded' +require 'slim/interpolation' +require 'slim/controls' +require 'slim/splat/filter' +require 'slim/splat/builder' +require 'slim/code_attributes' +require 'slim/engine' +require 'slim/template' +require 'slim/version' diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/code_attributes.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/code_attributes.rb new file mode 100644 index 0000000..7a20a4e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/code_attributes.rb @@ -0,0 +1,67 @@ +module Slim + # @api private + class CodeAttributes < Filter + define_options :merge_attrs + + # Handle attributes expression `[:html, :attrs, *attrs]` + # + # @param [Array] attrs Array of temple expressions + # @return [Array] Compiled temple expression + def on_html_attrs(*attrs) + [:multi, *attrs.map {|a| compile(a) }] + end + + # Handle attribute expression `[:html, :attr, name, value]` + # + # @param [String] name Attribute name + # @param [Array] value Value expression + # @return [Array] Compiled temple expression + def on_html_attr(name, value) + if value[0] == :slim && value[1] == :attrvalue && !options[:merge_attrs][name] + # We handle the attribute as a boolean attribute + escape, code = value[2], value[3] + case code + when 'true' + [:html, :attr, name, [:multi]] + when 'false', 'nil' + [:multi] + else + tmp = unique_name + [:multi, + [:code, "#{tmp} = #{code}"], + [:if, tmp, + [:if, "#{tmp} == true", + [:html, :attr, name, [:multi]], + [:html, :attr, name, [:escape, escape, [:dynamic, tmp]]]]]] + end + else + # Attribute with merging + @attr = name + super + end + end + + # Handle attribute expression `[:slim, :attrvalue, escape, code]` + # + # @param [Boolean] escape Escape html + # @param [String] code Ruby code + # @return [Array] Compiled temple expression + def on_slim_attrvalue(escape, code) + # We perform attribute merging on Array values + if delimiter = options[:merge_attrs][@attr] + tmp = unique_name + [:multi, + [:code, "#{tmp} = #{code}"], + [:if, "Array === #{tmp}", + [:multi, + [:code, "#{tmp} = #{tmp}.flatten"], + [:code, "#{tmp}.map!(&:to_s)"], + [:code, "#{tmp}.reject!(&:empty?)"], + [:escape, escape, [:dynamic, "#{tmp}.join(#{delimiter.inspect})"]]], + [:escape, escape, [:dynamic, tmp]]]] + else + [:escape, escape, [:dynamic, code]] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/command.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/command.rb new file mode 100644 index 0000000..e562da6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/command.rb @@ -0,0 +1,128 @@ +require 'slim' +require 'optparse' + +module Slim + Engine.set_options pretty: false + + # Slim commandline interface + # @api private + class Command + def initialize(args) + @args = args + @options = {} + end + + # Run command + def run + @opts = OptionParser.new(&method(:set_opts)) + @opts.parse!(@args) + process + end + + private + + # Configure OptionParser + def set_opts(opts) + opts.on('-s', '--stdin', 'Read input from standard input instead of an input file') do + @options[:input] = $stdin + end + + opts.on('--trace', 'Show a full traceback on error') do + @options[:trace] = true + end + + opts.on('-c', '--compile', 'Compile only but do not run') do + @options[:compile] = true + end + + opts.on('-e', '--erb', 'Convert to ERB') do + @options[:erb] = true + end + + opts.on('--rails', 'Generate rails compatible code (Implies --compile)') do + Engine.set_options disable_capture: true, generator: Temple::Generators::RailsOutputBuffer + @options[:compile] = true + end + + opts.on('-r', '--require library', "Load library or plugin with -r slim/plugin") do |lib| + require lib.strip + end + + opts.on('-p', '--pretty', 'Produce pretty html') do + Engine.set_options pretty: true + end + + opts.on('-o', '--option name=code', String, 'Set slim option') do |str| + parts = str.split('=', 2) + Engine.options[parts.first.gsub(/\A:/, '').to_sym] = eval(parts.last) + end + + opts.on('-l', '--locals Hash|YAML|JSON', String, 'Set local variables') do |locals| + @options[:locals] = + if locals =~ /\A\s*\{\s*\p{Word}+:/ + eval(locals) + else + require 'yaml' + if RUBY_ENGINE == 'rbx' + begin + require 'psych' + rescue LoadError + $stderr.puts 'Please install psych gem as Rubunius ships with an old YAML engine.' + end + end + YAML.load(locals) + end + end + + opts.on_tail('-h', '--help', 'Show this message') do + puts opts + exit + end + + opts.on_tail('-v', '--version', 'Print version') do + puts "Slim #{VERSION}" + exit + end + end + + # Process command + def process + args = @args.dup + unless @options[:input] + file = args.shift + if file + @options[:file] = file + @options[:input] = File.open(file, 'r') + else + @options[:file] = 'STDIN' + @options[:input] = $stdin + end + end + + locals = @options.delete(:locals) || {} + result = + if @options[:erb] + require 'slim/erb_converter' + ERBConverter.new(file: @options[:file]).call(@options[:input].read) + elsif @options[:compile] + Engine.new(file: @options[:file]).call(@options[:input].read) + else + Template.new(@options[:file]) { @options[:input].read }.render(nil, locals) + end + + rescue Exception => ex + raise ex if @options[:trace] || SystemExit === ex + $stderr.print "#{ex.class}: " if ex.class != RuntimeError + $stderr.puts ex.message + $stderr.puts ' Use --trace for backtrace.' + exit 1 + else + unless @options[:output] + file = args.shift + @options[:output] = file ? File.open(file, 'w') : $stdout + end + @options[:output].puts(result) + exit 0 + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/controls.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/controls.rb new file mode 100644 index 0000000..9f2d2e6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/controls.rb @@ -0,0 +1,60 @@ +module Slim + # @api private + class Controls < Filter + define_options :disable_capture + + IF_RE = /\A(if|unless)\b|\bdo\s*(\|[^\|]*\|)?\s*$/ + + # Handle control expression `[:slim, :control, code, content]` + # + # @param [String] code Ruby code + # @param [Array] content Temple expression + # @return [Array] Compiled temple expression + def on_slim_control(code, content) + [:multi, + [:code, code], + compile(content)] + end + + # Handle output expression `[:slim, :output, escape, code, content]` + # + # @param [Boolean] escape Escape html + # @param [String] code Ruby code + # @param [Array] content Temple expression + # @return [Array] Compiled temple expression + def on_slim_output(escape, code, content) + if code =~ IF_RE + tmp = unique_name + + [:multi, + # Capture the result of the code in a variable. We can't do + # `[:dynamic, code]` because it's probably not a complete + # expression (which is a requirement for Temple). + [:block, "#{tmp} = #{code}", + + # Capture the content of a block in a separate buffer. This means + # that `yield` will not output the content to the current buffer, + # but rather return the output. + # + # The capturing can be disabled with the option :disable_capture. + # Output code in the block writes directly to the output buffer then. + # Rails handles this by replacing the output buffer for helpers. + options[:disable_capture] ? compile(content) : [:capture, unique_name, compile(content)]], + + # Output the content. + [:escape, escape, [:dynamic, tmp]]] + else + [:multi, [:escape, escape, [:dynamic, code]], content] + end + end + + # Handle text expression `[:slim, :text, type, content]` + # + # @param [Symbol] type Text type + # @param [Array] content Temple expression + # @return [Array] Compiled temple expression + def on_slim_text(type, content) + compile(content) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/do_inserter.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/do_inserter.rb new file mode 100644 index 0000000..1dc765d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/do_inserter.rb @@ -0,0 +1,33 @@ +module Slim + # In Slim you don't need the do keyword sometimes. This + # filter adds the missing keyword. + # + # - 10.times + # | Hello + # + # @api private + class DoInserter < Filter + BLOCK_REGEX = /(\A(if|unless|else|elsif|when|begin|rescue|ensure|case)\b)|\bdo\s*(\|[^\|]*\|\s*)?\Z/ + + # Handle control expression `[:slim, :control, code, content]` + # + # @param [String] code Ruby code + # @param [Array] content Temple expression + # @return [Array] Compiled temple expression + def on_slim_control(code, content) + code = code + ' do' unless code =~ BLOCK_REGEX || empty_exp?(content) + [:slim, :control, code, compile(content)] + end + + # Handle output expression `[:slim, :output, escape, code, content]` + # + # @param [Boolean] escape Escape html + # @param [String] code Ruby code + # @param [Array] content Temple expression + # @return [Array] Compiled temple expression + def on_slim_output(escape, code, content) + code = code + ' do' unless code =~ BLOCK_REGEX || empty_exp?(content) + [:slim, :output, escape, code, compile(content)] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/embedded.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/embedded.rb new file mode 100644 index 0000000..316809c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/embedded.rb @@ -0,0 +1,248 @@ +module Slim + # @api private + class TextCollector < Filter + def call(exp) + @collected = '' + super(exp) + @collected + end + + def on_slim_interpolate(text) + @collected << text + nil + end + end + + # @api private + class NewlineCollector < Filter + def call(exp) + @collected = [:multi] + super(exp) + @collected + end + + def on_newline + @collected << [:newline] + nil + end + end + + # @api private + class OutputProtector < Filter + def call(exp) + @protect, @collected, @tag = [], '', "%#{object_id.abs.to_s(36)}%" + super(exp) + @collected + end + + def on_static(text) + @collected << text + nil + end + + def on_slim_output(escape, text, content) + @collected << @tag + @protect << [:slim, :output, escape, text, content] + nil + end + + def unprotect(text) + block = [:multi] + while text =~ /#{@tag}/ + block << [:static, $`] + block << @protect.shift + text = $' + end + block << [:static, text] + end + end + + # Temple filter which processes embedded engines + # @api private + class Embedded < Filter + @engines = {} + + class << self + attr_reader :engines + + # Register embedded engine + # + # @param [String] name Name of the engine + # @param [Class] klass Engine class + # @param option_filter List of options to pass to engine. + # Last argument can be default option hash. + def register(name, klass, *option_filter) + name = name.to_sym + local_options = option_filter.last.respond_to?(:to_hash) ? option_filter.pop.to_hash : {} + define_options(name, *option_filter) + klass.define_options(name) + engines[name.to_sym] = proc do |options| + klass.new({}.update(options).delete_if {|k,v| !option_filter.include?(k) && k != name }.update(local_options)) + end + end + + def create(name, options) + constructor = engines[name] || raise(Temple::FilterError, "Embedded engine #{name} not found") + constructor.call(options) + end + end + + define_options :enable_engines, :disable_engines + + def initialize(opts = {}) + super + @engines = {} + @enabled = normalize_engine_list(options[:enable_engines]) + @disabled = normalize_engine_list(options[:disable_engines]) + end + + def on_slim_embedded(name, body, attrs) + name = name.to_sym + raise(Temple::FilterError, "Embedded engine #{name} is disabled") unless enabled?(name) + @engines[name] ||= self.class.create(name, options) + @engines[name].on_slim_embedded(name, body, attrs) + end + + def enabled?(name) + (!@enabled || @enabled.include?(name)) && + (!@disabled || !@disabled.include?(name)) + end + + protected + + def normalize_engine_list(list) + raise(ArgumentError, "Option :enable_engines/:disable_engines must be String or Symbol list") unless !list || Array === list + list && list.map(&:to_sym) + end + + class Engine < Filter + protected + + def collect_text(body) + @text_collector ||= TextCollector.new + @text_collector.call(body) + end + + def collect_newlines(body) + @newline_collector ||= NewlineCollector.new + @newline_collector.call(body) + end + end + + # Basic tilt engine + class TiltEngine < Engine + def on_slim_embedded(engine, body, attrs) + tilt_engine = Tilt[engine] || raise(Temple::FilterError, "Tilt engine #{engine} is not available.") + tilt_options = options[engine.to_sym] || {} + tilt_options[:default_encoding] ||= 'utf-8' + [:multi, tilt_render(tilt_engine, tilt_options, collect_text(body)), collect_newlines(body)] + end + + protected + + def tilt_render(tilt_engine, tilt_options, text) + [:static, tilt_engine.new(tilt_options) { text }.render] + end + end + + # Sass engine which supports :pretty option + class SassEngine < TiltEngine + define_options :pretty + + protected + + def tilt_render(tilt_engine, tilt_options, text) + text = tilt_engine.new(tilt_options.merge( + style: options[:pretty] ? :expanded : :compressed, + cache: false)) { text }.render + text.chomp! + [:static, text] + end + end + + # Static template with interpolated ruby code + class InterpolateTiltEngine < TiltEngine + def collect_text(body) + output_protector.call(interpolation.call(body)) + end + + def tilt_render(tilt_engine, tilt_options, text) + output_protector.unprotect(tilt_engine.new(tilt_options) { text }.render) + end + + private + + def interpolation + @interpolation ||= Interpolation.new + end + + def output_protector + @output_protector ||= OutputProtector.new + end + end + + # Tag wrapper engine + # Generates a html tag and wraps another engine (specified via :engine option) + class TagEngine < Engine + disable_option_validator! + + def on_slim_embedded(engine, body, attrs) + + unless options[:attributes].empty? + options[:attributes].map do|k, v| + attrs << [:html, :attr, k, [:static, v]] + end + end + + if options[:engine] + opts = {}.update(options) + opts.delete(:engine) + opts.delete(:tag) + opts.delete(:attributes) + @engine ||= options[:engine].new(opts) + body = @engine.on_slim_embedded(engine, body, attrs) + end + + [:html, :tag, options[:tag], attrs, body] + end + + end + + # Javascript wrapper engine. + # Like TagEngine, but can wrap content in html comment or cdata. + class JavaScriptEngine < TagEngine + disable_option_validator! + + set_options tag: :script, attributes: {} + + def on_slim_embedded(engine, body, attrs) + super(engine, [:html, :js, body], attrs) + end + end + + # Embeds ruby code + class RubyEngine < Engine + def on_slim_embedded(engine, body, attrs) + [:multi, [:newline], [:code, "#{collect_text(body)}\n"]] + end + end + + # These engines are executed at compile time, embedded ruby is interpolated + register :markdown, InterpolateTiltEngine + register :textile, InterpolateTiltEngine + register :rdoc, InterpolateTiltEngine + + # These engines are executed at compile time + register :coffee, JavaScriptEngine, engine: TiltEngine + register :less, TagEngine, tag: :style, attributes: { type: 'text/css' }, engine: TiltEngine + register :sass, TagEngine, :pretty, tag: :style, attributes: { type: 'text/css' }, engine: SassEngine + register :scss, TagEngine, :pretty, tag: :style, attributes: { type: 'text/css' }, engine: SassEngine + + # Embedded javascript/css + register :javascript, JavaScriptEngine + register :css, TagEngine, tag: :style, attributes: { type: 'text/css' } + + # Embedded ruby code + register :ruby, RubyEngine + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/end_inserter.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/end_inserter.rb new file mode 100644 index 0000000..7ec8319 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/end_inserter.rb @@ -0,0 +1,62 @@ +module Slim + # In Slim you don't need to close any blocks: + # + # - if Slim.awesome? + # | But of course it is! + # + # However, the parser is not smart enough (and that's a good thing) to + # automatically insert end's where they are needed. Luckily, this filter + # does *exactly* that (and it does it well!) + # + # @api private + class EndInserter < Filter + IF_RE = /\A(if|begin|unless|else|elsif|when|rescue|ensure)\b|\bdo\s*(\|[^\|]*\|)?\s*$/ + ELSE_RE = /\A(else|elsif|when|rescue|ensure)\b/ + END_RE = /\Aend\b/ + + # Handle multi expression `[:multi, *exps]` + # + # @return [Array] Corrected Temple expression with ends inserted + def on_multi(*exps) + result = [:multi] + # This variable is true if the previous line was + # (1) a control code and (2) contained indented content. + prev_indent = false + + exps.each do |exp| + if control?(exp) + raise(Temple::FilterError, 'Explicit end statements are forbidden') if exp[2] =~ END_RE + + # Two control code in a row. If this one is *not* + # an else block, we should close the previous one. + append_end(result) if prev_indent && exp[2] !~ ELSE_RE + + # Indent if the control code starts a block. + prev_indent = exp[2] =~ IF_RE + elsif exp[0] != :newline && prev_indent + # This is *not* a control code, so we should close the previous one. + # Ignores newlines because they will be inserted after each line. + append_end(result) + prev_indent = false + end + + result << compile(exp) + end + + # The last line can be a control code too. + prev_indent ? append_end(result) : result + end + + private + + # Appends an end + def append_end(result) + result << [:code, 'end'] + end + + # Checks if an expression is a Slim control code + def control?(exp) + exp[0] == :slim && exp[1] == :control + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/engine.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/engine.rb new file mode 100644 index 0000000..5da9ae6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/engine.rb @@ -0,0 +1,39 @@ +# The Slim module contains all Slim related classes (e.g. Engine, Parser). +# Plugins might also reside within the Slim module (e.g. Include, Smart). +# @api public +module Slim + # Slim engine which transforms slim code to executable ruby code + # @api public + class Engine < Temple::Engine + # This overwrites some Temple default options or sets default options for Slim specific filters. + # It is recommended to set the default settings only once in the code and avoid duplication. Only use + # `define_options` when you have to override some default settings. + define_options pretty: false, + sort_attrs: true, + format: :xhtml, + attr_quote: '"', + merge_attrs: {'class' => ' '}, + generator: Temple::Generators::StringBuffer, + default_tag: 'div' + + filter :Encoding + filter :RemoveBOM + use Slim::Parser + use Slim::Embedded + use Slim::Interpolation + use Slim::Splat::Filter + use Slim::DoInserter + use Slim::EndInserter + use Slim::Controls + html :AttributeSorter + html :AttributeMerger + use Slim::CodeAttributes + use(:AttributeRemover) { Temple::HTML::AttributeRemover.new(remove_empty_attrs: options[:merge_attrs].keys) } + html :Pretty + filter :Escapable + filter :ControlFlow + filter :MultiFlattener + filter :StaticMerger + use(:Generator) { options[:generator] } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/erb_converter.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/erb_converter.rb new file mode 100644 index 0000000..d9abe6a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/erb_converter.rb @@ -0,0 +1,14 @@ +require 'slim' + +module Slim + # Slim to ERB converter + # + # @example Conversion + # Slim::ERBConverter.new(options).call(slim_code) # outputs erb_code + # + # @api public + class ERBConverter < Engine + replace :StaticMerger, Temple::Filters::CodeMerger + replace :Generator, Temple::Generators::ERB + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/filter.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/filter.rb new file mode 100644 index 0000000..e3826ee --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/filter.rb @@ -0,0 +1,30 @@ +module Slim + # Base class for Temple filters used in Slim + # + # This base filter passes everything through and allows + # to override only some methods without affecting the rest + # of the expression. + # + # @api private + class Filter < Temple::HTML::Filter + # Pass-through handler + def on_slim_text(type, content) + [:slim, :text, type, compile(content)] + end + + # Pass-through handler + def on_slim_embedded(type, content, attrs) + [:slim, :embedded, type, compile(content), attrs] + end + + # Pass-through handler + def on_slim_control(code, content) + [:slim, :control, code, compile(content)] + end + + # Pass-through handler + def on_slim_output(escape, code, content) + [:slim, :output, escape, code, compile(content)] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/grammar.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/grammar.rb new file mode 100644 index 0000000..9761947 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/grammar.rb @@ -0,0 +1,23 @@ +module Slim + # Slim expression grammar + # @api private + module Grammar + extend Temple::Grammar + + TextTypes << :verbatim | :explicit | :implicit | :inline + + Expression << + [:slim, :control, String, Expression] | + [:slim, :output, Bool, String, Expression] | + [:slim, :interpolate, String] | + [:slim, :embedded, String, Expression, HTMLAttrGroup] | + [:slim, :text, TextTypes, Expression] | + [:slim, :attrvalue, Bool, String] + + HTMLAttr << + [:slim, :splat, String] + + HTMLAttrGroup << + [:html, :attrs, 'HTMLAttr*'] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/include.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/include.rb new file mode 100644 index 0000000..ecb6aaf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/include.rb @@ -0,0 +1,57 @@ +require 'slim' + +module Slim + # Handles inlined includes + # + # Slim files are compiled, non-Slim files are included as text with `#{interpolation}` + # + # @api private + class Include < Slim::Filter + define_options :file, include_dirs: [Dir.pwd, '.'] + + def on_html_tag(tag, attributes, content = nil) + return super if tag != 'include' + name = content.to_a.flatten.select {|s| String === s }.join + raise ArgumentError, 'Invalid include statement' unless attributes == [:html, :attrs] && !name.empty? + unless file = find_file(name) + name = "#{name}.slim" if name !~ /\.slim\Z/i + file = find_file(name) + end + raise Temple::FilterError, "'#{name}' not found in #{options[:include_dirs].join(':')}" unless file + content = File.read(file) + if file =~ /\.slim\Z/i + Thread.current[:slim_include_engine].call(content) + else + [:slim, :interpolate, content] + end + end + + protected + + def find_file(name) + current_dir = File.dirname(File.expand_path(options[:file])) + options[:include_dirs].map {|dir| File.expand_path(File.join(dir, name), current_dir) }.find {|file| File.file?(file) } + end + end + + class Engine + after Slim::Parser, Slim::Include + after Slim::Include, :stop do |exp| + throw :stop, exp if Thread.current[:slim_include_level] > 1 + exp + end + + # @api private + alias call_without_include call + + # @api private + def call(input) + Thread.current[:slim_include_engine] = self + Thread.current[:slim_include_level] ||= 0 + Thread.current[:slim_include_level] += 1 + catch(:stop) { call_without_include(input) } + ensure + Thread.current[:slim_include_engine] = nil if (Thread.current[:slim_include_level] -= 1) == 0 + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/interpolation.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/interpolation.rb new file mode 100644 index 0000000..b2a6b37 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/interpolation.rb @@ -0,0 +1,35 @@ +module Slim + # Perform interpolation of #{var_name} in the + # expressions `[:slim, :interpolate, string]`. + # + # @api private + class Interpolation < Filter + # Handle interpolate expression `[:slim, :interpolate, string]` + # + # @param [String] string Static interpolate + # @return [Array] Compiled temple expression + def on_slim_interpolate(string) + # Interpolate variables in text (#{variable}). + # Split the text into multiple dynamic and static parts. + block = [:multi] + begin + case string + when /\A\\#\{/ + # Escaped interpolation + block << [:static, '#{'] + string = $' + when /\A#\{((?>[^{}]|(\{(?>[^{}]|\g<1>)*\}))*)\}/ + # Interpolation + string, code = $', $1 + escape = code !~ /\A\{.*\}\Z/ + block << [:slim, :output, escape, escape ? code : code[1..-2], [:multi]] + when /\A([#\\]?[^#\\]*([#\\][^\\#\{][^#\\]*)*)/ + # Static text + block << [:static, $&] + string = $' + end + end until string.empty? + block + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/logic_less.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/logic_less.rb new file mode 100644 index 0000000..8639fe9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/logic_less.rb @@ -0,0 +1,5 @@ +require 'slim' +require 'slim/logic_less/filter' +require 'slim/logic_less/context' + +Slim::Engine.after Slim::Interpolation, Slim::LogicLess diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/logic_less/context.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/logic_less/context.rb new file mode 100644 index 0000000..4303d87 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/logic_less/context.rb @@ -0,0 +1,127 @@ +module Slim + class LogicLess + # @api private + class Context + def initialize(dict, lookup) + @scope = [Scope.new(dict, lookup)] + end + + def [](name) + scope[name] + end + + def lambda(name) + scope.lambda(name) do |*dict| + if dict.empty? + yield + else + new_scope do + dict.inject('') do |result, d| + scope.dict = d + result << yield + end + end + end + end + end + + def section(name) + if dict = scope[name] + if !dict.respond_to?(:has_key?) && dict.respond_to?(:each) + new_scope do + dict.each do |d| + scope.dict = d + yield + end + end + else + new_scope(dict) { yield } + end + end + end + + def inverted_section(name) + value = scope[name] + yield if !value || (value.respond_to?(:empty?) && value.empty?) + end + + def to_s + scope.to_s + end + + private + + class Scope + attr_reader :lookup + attr_writer :dict + + def initialize(dict, lookup, parent = nil) + @dict, @lookup, @parent = dict, lookup, parent + end + + def lambda(name, &block) + @lookup.each do |lookup| + case lookup + when :method + return @dict.public_send(name, &block) if @dict.respond_to?(name, false) + when :symbol + return @dict[name].call(&block) if has_key?(name) + when :string + return @dict[name.to_s].call(&block) if has_key?(name.to_s) + when :instance_variable + var_name = "@#{name}" + return @dict.instance_variable_get(var_name).call(&block) if instance_variable?(var_name) + end + end + @parent.lambda(name) if @parent + end + + def [](name) + @lookup.each do |lookup| + case lookup + when :method + return @dict.public_send(name) if @dict.respond_to?(name, false) + when :symbol + return @dict[name] if has_key?(name) + when :string + return @dict[name.to_s] if has_key?(name.to_s) + when :instance_variable + var_name = "@#{name}" + return @dict.instance_variable_get(var_name) if instance_variable?(var_name) + end + end + @parent[name] if @parent + end + + def to_s + @dict.to_s + end + + private + + def has_key?(name) + @dict.respond_to?(:has_key?) && @dict.has_key?(name) + end + + def instance_variable?(name) + begin + @dict.instance_variable_defined?(name) + rescue NameError + false + end + end + end + + def scope + @scope.last + end + + def new_scope(dict = nil) + @scope << Scope.new(dict, scope.lookup, scope) + yield + ensure + @scope.pop + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/logic_less/filter.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/logic_less/filter.rb new file mode 100644 index 0000000..6e45220 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/logic_less/filter.rb @@ -0,0 +1,80 @@ +module Slim + # Handle logic less mode + # This filter can be activated with the option "logic_less" + # @api private + class LogicLess < Filter + # Default dictionary access order, change it with the option :dictionary_access + DEFAULT_ACCESS_ORDER = [:symbol, :string, :method, :instance_variable].freeze + + define_options logic_less: true, + dictionary: 'self', + dictionary_access: DEFAULT_ACCESS_ORDER + + def initialize(opts = {}) + super + access = [options[:dictionary_access]].flatten.compact + access.each do |type| + raise ArgumentError, "Invalid dictionary access #{type.inspect}" unless DEFAULT_ACCESS_ORDER.include?(type) + end + raise ArgumentError, 'Option dictionary access is missing' if access.empty? + @access = access.inspect + end + + def call(exp) + if options[:logic_less] + @context = unique_name + [:multi, + [:code, "#{@context} = ::Slim::LogicLess::Context.new(#{options[:dictionary]}, #{@access})"], + super] + else + exp + end + end + + # Interpret control blocks as sections or inverted sections + def on_slim_control(name, content) + method = + if name =~ /\A!\s*(.*)/ + name = $1 + 'inverted_section' + else + 'section' + end + [:block, "#{@context}.#{method}(#{name.to_sym.inspect}) do", compile(content)] + end + + def on_slim_output(escape, name, content) + [:slim, :output, escape, empty_exp?(content) ? access(name) : + "#{@context}.lambda(#{name.to_sym.inspect}) do", compile(content)] + end + + def on_slim_attrvalue(escape, value) + [:slim, :attrvalue, escape, access(value)] + end + + def on_slim_splat(code) + [:slim, :splat, access(code)] + end + + def on_dynamic(code) + raise Temple::FilterError, 'Embedded code is forbidden in logic less mode' + end + + def on_code(code) + raise Temple::FilterError, 'Embedded code is forbidden in logic less mode' + end + + private + + def access(name) + case name + when 'yield' + 'yield' + when 'self' + "#{@context}.to_s" + else + "#{@context}[#{name.to_sym.inspect}]" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/parser.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/parser.rb new file mode 100644 index 0000000..810779c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/parser.rb @@ -0,0 +1,548 @@ +module Slim + # Parses Slim code and transforms it to a Temple expression + # @api private + class Parser < Temple::Parser + define_options :file, + :default_tag, + tabsize: 4, + code_attr_delims: { + '(' => ')', + '[' => ']', + '{' => '}', + }, + attr_list_delims: { + '(' => ')', + '[' => ']', + '{' => '}', + }, + shortcut: { + '#' => { attr: 'id' }, + '.' => { attr: 'class' } + }, + splat_prefix: '*' + + class SyntaxError < StandardError + attr_reader :error, :file, :line, :lineno, :column + + def initialize(error, file, line, lineno, column) + @error = error + @file = file || '(__TEMPLATE__)' + @line = line.to_s + @lineno = lineno + @column = column + end + + def to_s + line = @line.lstrip + column = @column + line.size - @line.size + %{#{error} + #{file}, Line #{lineno}, Column #{@column} + #{line} + #{' ' * column}^ +} + end + end + + def initialize(opts = {}) + super + @attr_list_delims = options[:attr_list_delims] + @code_attr_delims = options[:code_attr_delims] + tabsize = options[:tabsize] + if tabsize > 1 + @tab_re = /\G((?: {#{tabsize}})*) {0,#{tabsize-1}}\t/ + @tab = '\1' + ' ' * tabsize + else + @tab_re = "\t" + @tab = ' ' + end + @tag_shortcut, @attr_shortcut, @additional_attrs = {}, {}, {} + options[:shortcut].each do |k,v| + raise ArgumentError, 'Shortcut requires :tag and/or :attr' unless (v[:attr] || v[:tag]) && (v.keys - [:attr, :tag, :additional_attrs]).empty? + @tag_shortcut[k] = v[:tag] || options[:default_tag] + if v.include?(:attr) || v.include?(:additional_attrs) + raise ArgumentError, 'You can only use special characters for attribute shortcuts' if k =~ /(\p{Word}|-)/ + end + if v.include?(:attr) + @attr_shortcut[k] = [v[:attr]].flatten + end + if v.include?(:additional_attrs) + @additional_attrs[k] = v[:additional_attrs] + end + end + keys = Regexp.union @attr_shortcut.keys.sort_by {|k| -k.size } + @attr_shortcut_re = /\A(#{keys}+)((?:\p{Word}|-|\/\d+|:(\w|-)+)*)/ + keys = Regexp.union @tag_shortcut.keys.sort_by {|k| -k.size } + @tag_re = /\A(?:#{keys}|\*(?=[^\s]+)|(\p{Word}(?:\p{Word}|:|-)*\p{Word}|\p{Word}+))/ + keys = Regexp.escape @code_attr_delims.keys.join + @code_attr_delims_re = /\A[#{keys}]/ + keys = Regexp.escape @attr_list_delims.keys.join + @attr_list_delims_re = /\A\s*([#{keys}])/ + @embedded_re = /\A(#{Regexp.union(Embedded.engines.keys.map(&:to_s))})(?:\s*(?:(.*)))?:(\s*)/ + keys = Regexp.escape ('"\'> @indents.size + + if indent > @indents.last + # This line was actually indented, so we'll have to check if it was + # supposed to be indented or not. + syntax_error!('Unexpected indentation') unless expecting_indentation + + @indents << indent + else + # This line was *not* indented more than the line before, + # so we'll just forget about the stack that the previous line pushed. + @stacks.pop if expecting_indentation + + # This line was deindented. + # Now we're have to go through the all the indents and figure out + # how many levels we've deindented. + while indent < @indents.last && @indents.size > 1 + @indents.pop + @stacks.pop + end + + # This line's indentation happens to lie "between" two other line's + # indentation: + # + # hello + # world + # this # <- This should not be possible! + syntax_error!('Malformed indentation') if indent != @indents.last + end + + parse_line_indicators + end + + def parse_line_indicators + case @line + when /\A\/!( ?)/ + # HTML comment + @stacks.last << [:html, :comment, [:slim, :text, :verbatim, parse_text_block($', @indents.last + $1.size + 2)]] + when /\A\/\[\s*(.*?)\s*\]\s*\Z/ + # HTML conditional comment + block = [:multi] + @stacks.last << [:html, :condcomment, $1, block] + @stacks << block + when /\A\// + # Slim comment + parse_comment_block + when /\A([\|'])( ?)/ + # Found verbatim text block. + trailing_ws = $1 == "'" + @stacks.last << [:slim, :text, :verbatim, parse_text_block($', @indents.last + $2.size + 1)] + @stacks.last << [:static, ' '] if trailing_ws + when /\A]*)/ + # Found an output block. + # We expect the line to be broken or the next line to be indented. + @line = $' + trailing_ws = $2.include?('>'.freeze) + if $2.include?('\''.freeze) + deprecated_syntax '=\' for trailing whitespace is deprecated in favor of =>' + trailing_ws = true + end + block = [:multi] + @stacks.last << [:static, ' '] if $2.include?('<'.freeze) + @stacks.last << [:slim, :output, $1.empty?, parse_broken_line, block] + @stacks.last << [:static, ' '] if trailing_ws + @stacks << block + when @embedded_re + # Embedded template detected. It is treated as block. + @line = $2 + attrs = parse_attributes + @stacks.last << [:slim, :embedded, $1, parse_text_block($', @orig_line.size - $'.size + $2.size), attrs] + when /\Adoctype\b/ + # Found doctype declaration + @stacks.last << [:html, :doctype, $'.strip] + when @tag_re + # Found a HTML tag. + @line = $' if $1 + parse_tag($&) + else + unknown_line_indicator + end + @stacks.last << [:newline] + end + + # Unknown line indicator found. Overwrite this method if + # you want to add line indicators to the Slim parser. + # The default implementation throws a syntax error. + def unknown_line_indicator + syntax_error! 'Unknown line indicator' + end + + def parse_comment_block + while !@lines.empty? && (@lines.first =~ /\A\s*\Z/ || get_indent(@lines.first) > @indents.last) + next_line + @stacks.last << [:newline] + end + end + + def parse_text_block(first_line = nil, text_indent = nil) + result = [:multi] + if !first_line || first_line.empty? + text_indent = nil + else + result << [:slim, :interpolate, first_line] + end + + empty_lines = 0 + until @lines.empty? + if @lines.first =~ /\A\s*\Z/ + next_line + result << [:newline] + empty_lines += 1 if text_indent + else + indent = get_indent(@lines.first) + break if indent <= @indents.last + + if empty_lines > 0 + result << [:slim, :interpolate, "\n" * empty_lines] + empty_lines = 0 + end + + next_line + @line.lstrip! + + # The text block lines must be at least indented + # as deep as the first line. + offset = text_indent ? indent - text_indent : 0 + if offset < 0 + text_indent += offset + offset = 0 + end + result << [:newline] << [:slim, :interpolate, (text_indent ? "\n" : '') + (' ' * offset) + @line] + + # The indentation of first line of the text block + # determines the text base indentation. + text_indent ||= indent + end + end + result + end + + def parse_broken_line + broken_line = @line.strip + while broken_line =~ /[,\\]\Z/ + expect_next_line + broken_line << "\n" << @line + end + broken_line + end + + def parse_tag(tag) + if @tag_shortcut[tag] + @line.slice!(0, tag.size) unless @attr_shortcut[tag] + tag = @tag_shortcut[tag] + end + + # Find any shortcut attributes + attributes = [:html, :attrs] + while @line =~ @attr_shortcut_re + # The class/id attribute is :static instead of :slim :interpolate, + # because we don't want text interpolation in .class or #id shortcut + syntax_error!('Illegal shortcut') unless shortcut = @attr_shortcut[$1] + shortcut.each {|a| attributes << [:html, :attr, a, [:static, $2]] } + if additional_attr_pairs = @additional_attrs[$1] + additional_attr_pairs.each do |k,v| + attributes << [:html, :attr, k.to_s, [:static, v]] + end + end + @line = $' + end + + @line =~ /\A[<>']*/ + @line = $' + trailing_ws = $&.include?('>'.freeze) + if $&.include?('\''.freeze) + deprecated_syntax 'tag\' for trailing whitespace is deprecated in favor of tag>' + trailing_ws = true + end + + leading_ws = $&.include?('<'.freeze) + + parse_attributes(attributes) + + tag = [:html, :tag, tag, attributes] + + @stacks.last << [:static, ' '] if leading_ws + @stacks.last << tag + @stacks.last << [:static, ' '] if trailing_ws + + case @line + when /\A\s*:\s*/ + # Block expansion + @line = $' + if @line =~ @embedded_re + + # Parse attributes + @line = $2 + attrs = parse_attributes + tag << [:slim, :embedded, $1, parse_text_block($', @orig_line.size - $'.size + $2.size), attrs] + else + (@line =~ @tag_re) || syntax_error!('Expected tag') + @line = $' if $1 + content = [:multi] + tag << content + i = @stacks.size + @stacks << content + parse_tag($&) + @stacks.delete_at(i) + end + when /\A\s*=(=?)(['<>]*)/ + # Handle output code + @line = $' + trailing_ws2 = $2.include?('>'.freeze) + if $2.include?('\''.freeze) + deprecated_syntax '=\' for trailing whitespace is deprecated in favor of =>' + trailing_ws2 = true + end + block = [:multi] + @stacks.last.insert(-2, [:static, ' ']) if !leading_ws && $2.include?('<'.freeze) + tag << [:slim, :output, $1 != '=', parse_broken_line, block] + @stacks.last << [:static, ' '] if !trailing_ws && trailing_ws2 + @stacks << block + when /\A\s*\/\s*/ + # Closed tag. Do nothing + @line = $' + syntax_error!('Unexpected text after closed tag') unless @line.empty? + when /\A\s*\Z/ + # Empty content + content = [:multi] + tag << content + @stacks << content + when /\A ?/ + # Text content + tag << [:slim, :text, :inline, parse_text_block($', @orig_line.size - $'.size)] + end + end + + def parse_attributes(attributes = [:html, :attrs]) + # Check to see if there is a delimiter right after the tag name + delimiter = nil + if @line =~ @attr_list_delims_re + delimiter = @attr_list_delims[$1] + @line = $' + end + + if delimiter + boolean_attr_re = /#{@attr_name}(?=(\s|#{Regexp.escape delimiter}|\Z))/ + end_re = /\A\s*#{Regexp.escape delimiter}/ + end + + while true + case @line + when @splat_attrs_regexp + # Splat attribute + @line = $' + attributes << [:slim, :splat, parse_ruby_code(delimiter)] + when @quoted_attr_re + # Value is quoted (static) + @line = $' + attributes << [:html, :attr, $1, + [:escape, $2.empty?, [:slim, :interpolate, parse_quoted_attribute($3)]]] + when @code_attr_re + # Value is ruby code + @line = $' + name = $1 + escape = $2.empty? + value = parse_ruby_code(delimiter) + syntax_error!('Invalid empty attribute') if value.empty? + attributes << [:html, :attr, name, [:slim, :attrvalue, escape, value]] + else + break unless delimiter + + case @line + when boolean_attr_re + # Boolean attribute + @line = $' + attributes << [:html, :attr, $1, [:multi]] + when end_re + # Find ending delimiter + @line = $' + break + else + # Found something where an attribute should be + @line.lstrip! + syntax_error!('Expected attribute') unless @line.empty? + + # Attributes span multiple lines + @stacks.last << [:newline] + syntax_error!("Expected closing delimiter #{delimiter}") if @lines.empty? + next_line + end + end + end + attributes || [:html, :attrs] + end + + def parse_ruby_code(outer_delimiter) + code, count, delimiter, close_delimiter = '', 0, nil, nil + + # Attribute ends with space or attribute delimiter + end_re = /\A[\s#{Regexp.escape outer_delimiter.to_s}]/ + + until @line.empty? || (count == 0 && @line =~ end_re) + if @line =~ /\A[,\\]\Z/ + code << @line << "\n" + expect_next_line + else + if count > 0 + if @line[0] == delimiter[0] + count += 1 + elsif @line[0] == close_delimiter[0] + count -= 1 + end + elsif @line =~ @code_attr_delims_re + count = 1 + delimiter, close_delimiter = $&, @code_attr_delims[$&] + end + code << @line.slice!(0) + end + end + syntax_error!("Expected closing delimiter #{close_delimiter}") if count != 0 + code + end + + def parse_quoted_attribute(quote) + value, count = '', 0 + + until count == 0 && @line[0] == quote[0] + if @line =~ /\A(\\)?\Z/ + value << ($1 ? ' ' : "\n") + expect_next_line + else + if @line[0] == ?{ + count += 1 + elsif @line[0] == ?} + count -= 1 + end + value << @line.slice!(0) + end + end + + @line.slice!(0) + value + end + + # Helper for raising exceptions + def syntax_error!(message) + raise SyntaxError.new(message, options[:file], @orig_line, @lineno, + @orig_line && @line ? @orig_line.size - @line.size : 0) + rescue SyntaxError => ex + # HACK: Manipulate stacktrace for Rails and other frameworks + # to find the right file. + ex.backtrace.unshift "#{options[:file]}:#{@lineno}" + raise + end + + def deprecated_syntax(message) + line = @orig_line.lstrip + column = (@orig_line && @line ? @orig_line.size - @line.size : 0) + line.size - @orig_line.size + warn %{Deprecated syntax: #{message} + #{options[:file]}, Line #{@lineno}, Column #{column + 1} + #{line} + #{' ' * column}^ +} + end + + def expect_next_line + next_line || syntax_error!('Unexpected end of file') + @line.strip! + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart.rb new file mode 100644 index 0000000..6f76a51 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart.rb @@ -0,0 +1,8 @@ +require 'slim' +require 'slim/smart/filter' +require 'slim/smart/escaper' +require 'slim/smart/parser' + +Slim::Engine.replace Slim::Parser, Slim::Smart::Parser +Slim::Engine.after Slim::Smart::Parser, Slim::Smart::Filter +Slim::Engine.after Slim::Interpolation, Slim::Smart::Escaper diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart/escaper.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart/escaper.rb new file mode 100644 index 0000000..331cd28 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart/escaper.rb @@ -0,0 +1,42 @@ +module Slim + module Smart + # Perform smart entity escaping in the + # expressions `[:slim, :text, type, Expression]`. + # + # @api private + class Escaper < ::Slim::Filter + define_options smart_text_escaping: true + + def call(exp) + if options[:smart_text_escaping] + super + else + exp + end + end + + def on_slim_text(type, content) + [:escape, type != :verbatim, [:slim, :text, type, compile(content)]] + end + + def on_static(string) + # Prevent obvious &foo; and Ӓ and ÿ entities from escaping. + block = [:multi] + until string.empty? + case string + when /\A&([a-z][a-z0-9]*|#x[0-9a-f]+|#\d+);/i + # Entity. + block << [:escape, false, [:static, $&]] + string = $' + when /\A&?[^&]*/ + # Other text. + block << [:static, $&] + string = $' + end + end + block + end + + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart/filter.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart/filter.rb new file mode 100644 index 0000000..ad7536d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart/filter.rb @@ -0,0 +1,96 @@ +module Slim + module Smart + # Perform newline processing in the + # expressions `[:slim, :text, type, Expression]`. + # + # @api private + class Filter < ::Slim::Filter + define_options smart_text: true, + smart_text_end_chars: '([{', + smart_text_begin_chars: ',.;:!?)]}' + + def initialize(opts = {}) + super + @active = @prepend = @append = false + @prepend_re = /\A#{chars_re(options[:smart_text_begin_chars])}/ + @append_re = /#{chars_re(options[:smart_text_end_chars])}\Z/ + end + + def call(exp) + if options[:smart_text] + super + else + exp + end + end + + def on_multi(*exps) + # The [:multi] blocks serve two purposes. + # On outer level, they collect the building blocks like + # tags, verbatim text, and implicit/explicit text. + # Within a text block, they collect the individual + # lines in [:slim, :interpolate, string] blocks. + # + # Our goal here is to decide when we want to prepend and + # append newlines to those individual interpolated lines. + # We basically want the text to come out as it was originally entered, + # while removing newlines next to the enclosing tags. + # + # On outer level, we choose to prepend every time, except + # right after the opening tag or after other text block. + # We also use the append flag to recognize the last expression + # before the closing tag, as we don't want to append newline there. + # + # Within text block, we prepend only before the first line unless + # the outer level tells us not to, and we append only after the last line, + # unless the outer level tells us it is the last line before the closing tag. + # Of course, this is later subject to the special begin/end characters + # which may further suppress the newline at the corresponding line boundary. + # Also note that the lines themselves are already correctly separated by newlines, + # so we don't have to worry about that at all. + block = [:multi] + prev = nil + last_exp = exps.reject{ |exp| exp.first == :newline }.last unless @active && @append + exps.each do |exp| + @append = exp.equal?(last_exp) + if @active + @prepend = false if prev + else + @prepend = prev && ( prev.first != :slim || prev[1] != :text ) + end + block << compile(exp) + prev = exp unless exp.first == :newline + end + block + end + + def on_slim_text(type, content) + @active = type != :verbatim + [:slim, :text, type, compile(content)] + ensure + @active = false + end + + def on_slim_text_inline(content) + # Inline text is not wrapped in multi block, so set it up as if it was. + @prepend = false + @append = true + on_slim_text(:inline, content) + end + + def on_slim_interpolate(string) + if @active + string = "\n" + string if @prepend && string !~ @prepend_re + string += "\n" if @append && string !~ @append_re + end + [:slim, :interpolate, string] + end + + private + + def chars_re(string) + Regexp.union(string.split(//)) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart/parser.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart/parser.rb new file mode 100644 index 0000000..711a0af --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/smart/parser.rb @@ -0,0 +1,34 @@ +module Slim + module Smart + # @api private + class Parser < ::Slim::Parser + define_options implicit_text: true + + def initialize(opts = {}) + super + word_re = options[:implicit_text] ? '[_a-z0-9]' : '\p{Word}' + attr_keys = Regexp.union(@attr_shortcut.keys.sort_by {|k| -k.size } ) + @attr_shortcut_re = /\A(#{attr_keys}+)((?:\p{Word}|-)*)/ + tag_keys = Regexp.union((@tag_shortcut.keys - @attr_shortcut.keys).sort_by {|k| -k.size } ) + @tag_re = /\A(?:#{attr_keys}(?=-*\p{Word})|#{tag_keys}|\*(?=[^\s]+)|(#{word_re}(?:#{word_re}|:|-)*#{word_re}|#{word_re}+))/ + end + + def unknown_line_indicator + if @line =~ /\A>( ?)/ + # Found explicit text block. + @stacks.last << [:slim, :text, :explicit, parse_text_block($', @indents.last + $1.size + 1)] + else + unless options[:implicit_text] + syntax_error! 'Illegal shortcut' if @line =~ @attr_shortcut_re + super + end + # Found implicit smart text block. + if line = @lines.first + indent = ( line =~ /\A\s*\Z/ ? @indents.last + 1 : get_indent(line) ) + end + @stacks.last << [:slim, :text, :implicit, parse_text_block(@line, indent)] + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/splat/builder.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/splat/builder.rb new file mode 100644 index 0000000..4b9a56b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/splat/builder.rb @@ -0,0 +1,107 @@ +module Slim + class InvalidAttributeNameError < StandardError; end + module Splat + # @api private + class Builder + # https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + INVALID_ATTRIBUTE_NAME_REGEX = /[ \0"'>\/=]/ + def initialize(options) + @options = options + @attrs = {} + end + + def code_attr(name, escape, value) + if delim = @options[:merge_attrs][name] + value = Array === value ? value.join(delim) : value.to_s + attr(name, escape_html(escape, value)) unless value.empty? + elsif @options[:hyphen_attrs].include?(name) && Hash === value + hyphen_attr(name, escape, value) + elsif value != false && value != nil + attr(name, escape_html(value != true && escape, value)) + end + end + + def splat_attrs(splat) + splat.each do |name, value| + code_attr(name.to_s, true, value) + end + end + + def attr(name, value) + if name =~ INVALID_ATTRIBUTE_NAME_REGEX + raise InvalidAttributeNameError, "Invalid attribute name '#{name}' was rendered" + end + if @attrs[name] + if delim = @options[:merge_attrs][name] + @attrs[name] += delim + value.to_s + else + raise("Multiple #{name} attributes specified") + end + else + @attrs[name] = value + end + end + + def build_tag(&block) + tag = @attrs.delete('tag').to_s + tag = @options[:default_tag] if tag.empty? + if block + # This is a bit of a hack to get a universal capturing. + # + # TODO: Add this as a helper somewhere to solve these capturing issues + # once and for all. + # + # If we have Slim capturing disabled and the scope defines the method `capture` (i.e. Rails) + # we use this method to capture the content. + # + # otherwise we just use normal Slim capturing (yield). + # + # See https://github.com/slim-template/slim/issues/591 + # https://github.com/slim-template/slim#helpers-capturing-and-includes + # + content = + if @options[:disable_capture] && (scope = block.binding.eval('self')).respond_to?(:capture) + scope.capture(&block) + else + yield + end + "<#{tag}#{build_attrs}>#{content}" + else + "<#{tag}#{build_attrs} />" + end + end + + def build_attrs + attrs = @options[:sort_attrs] ? @attrs.sort_by(&:first) : @attrs + attrs.map do |k, v| + if v == true + if @options[:format] == :xhtml + " #{k}=#{@options[:attr_quote]}#{@options[:attr_quote]}" + else + " #{k}" + end + else + " #{k}=#{@options[:attr_quote]}#{v}#{@options[:attr_quote]}" + end + end.join + end + + private + + def hyphen_attr(name, escape, value) + if Hash === value + value.each do |n, v| + hyphen_attr("#{name}-#{n}", escape, v) + end + else + attr(name, escape_html(value != true && escape, value)) + end + end + + def escape_html(escape, value) + return value unless escape + @options[:use_html_safe] ? Temple::Utils.escape_html_safe(value) : Temple::Utils.escape_html(value) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/splat/filter.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/splat/filter.rb new file mode 100644 index 0000000..63e688a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/splat/filter.rb @@ -0,0 +1,91 @@ +module Slim + module Splat + # @api private + class Filter < ::Slim::Filter + define_options :merge_attrs, :attr_quote, :sort_attrs, :default_tag, :format, :disable_capture, + hyphen_attrs: %w(data aria), use_html_safe: ''.respond_to?(:html_safe?) + + def call(exp) + @splat_options = nil + exp = compile(exp) + if @splat_options + opts = options.to_hash.reject {|k,v| !Filter.options.valid_key?(k) }.inspect + [:multi, [:code, "#{@splat_options} = #{opts}"], exp] + else + exp + end + end + + # Handle tag expression `[:html, :tag, name, attrs, content]` + # + # @param [String] name Tag name + # @param [Array] attrs Temple expression + # @param [Array] content Temple expression + # @return [Array] Compiled temple expression + def on_html_tag(name, attrs, content = nil) + return super if name != '*' + builder, block = make_builder(attrs[2..-1]) + if content + [:multi, + block, + [:slim, :output, false, + "#{builder}.build_tag #{empty_exp?(content) ? '{}' : 'do'}", + compile(content)]] + else + [:multi, + block, + [:dynamic, "#{builder}.build_tag"]] + end + end + + # Handle attributes expression `[:html, :attrs, *attrs]` + # + # @param [Array] attrs Array of temple expressions + # @return [Array] Compiled temple expression + def on_html_attrs(*attrs) + if attrs.any? {|attr| splat?(attr) } + builder, block = make_builder(attrs) + [:multi, + block, + [:dynamic, "#{builder}.build_attrs"]] + else + super + end + end + + protected + + def splat?(attr) + # Splat attribute given + attr[0] == :slim && attr[1] == :splat || + # Hyphenated attribute also needs splat handling + (attr[0] == :html && attr[1] == :attr && options[:hyphen_attrs].include?(attr[2]) && + attr[3][0] == :slim && attr[3][1] == :attrvalue) + end + + def make_builder(attrs) + @splat_options ||= unique_name + builder = unique_name + result = [:multi, [:code, "#{builder} = ::Slim::Splat::Builder.new(#{@splat_options})"]] + attrs.each do |attr| + result << + if attr[0] == :html && attr[1] == :attr + if attr[3][0] == :slim && attr[3][1] == :attrvalue + [:code, "#{builder}.code_attr(#{attr[2].inspect}, #{attr[3][2]}, (#{attr[3][3]}))"] + else + tmp = unique_name + [:multi, + [:capture, tmp, compile(attr[3])], + [:code, "#{builder}.attr(#{attr[2].inspect}, #{tmp})"]] + end + elsif attr[0] == :slim && attr[1] == :splat + [:code, "#{builder}.splat_attrs((#{attr[2]}))"] + else + attr + end + end + return builder, result + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/template.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/template.rb new file mode 100644 index 0000000..9c10967 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/template.rb @@ -0,0 +1,19 @@ +module Slim + # Tilt template implementation for Slim + # @api public + Template = Temple::Templates::Tilt(Slim::Engine, register_as: :slim) + + if defined?(::ActionView) + # Rails template implementation for Slim + # @api public + RailsTemplate = Temple::Templates::Rails(Slim::Engine, + register_as: :slim, + # Use rails-specific generator. This is necessary + # to support block capturing and streaming. + generator: Temple::Generators::RailsOutputBuffer, + # Disable the internal slim capturing. + # Rails takes care of the capturing by itself. + disable_capture: true, + streaming: true) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/translator.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/translator.rb new file mode 100644 index 0000000..3785e2a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/translator.rb @@ -0,0 +1,118 @@ +require 'slim' + +module Slim + # @api private + class Translator < Filter + define_options :tr, + tr_mode: :dynamic, + tr_fn: '_' + + if defined?(::I18n) + set_options tr_fn: '::Slim::Translator.i18n_text', + tr: true + elsif defined?(::GetText) + set_options tr_fn: '::GetText._', + tr: true + elsif defined?(::FastGettext) + set_options tr_fn: '::FastGettext::Translation._', + tr: true + end + + def self.i18n_text(text) + I18n.t!(text) + rescue I18n::MissingTranslationData + text + end + + def self.i18n_key(text) + key = text.parameterize.underscore + I18n.t!(key) + rescue I18n::MissingTranslationData + text + end + + def call(exp) + options[:tr] ? super : exp + end + + def initialize(opts = {}) + super + case options[:tr_mode] + when :static + @translator = StaticTranslator.new(tr_fn: options[:tr_fn]) + when :dynamic + @translator = DynamicTranslator.new(tr_fn: options[:tr_fn]) + else + raise ArgumentError, "Invalid translator mode #{options[:tr_mode].inspect}" + end + end + + def on_slim_text(type, exp) + [:slim, :text, type, @translator.call(exp)] + end + + private + + class StaticTranslator < Filter + define_options :tr_fn + + def initialize(opts = {}) + super + @translate = eval("proc {|string| #{options[:tr_fn]}(string) }") + end + + def call(exp) + @text, @captures = '', [] + result = compile(exp) + + text = @translate.call(@text) + while text =~ /%(\d+)/ + result << [:static, $`] << @captures[$1.to_i - 1] + text = $' + end + result << [:static, text] + end + + def on_static(text) + @text << text + [:multi] + end + + def on_slim_output(escape, code, content) + @captures << [:slim, :output, escape, code, content] + @text << "%#{@captures.size}" + [:multi] + end + end + + class DynamicTranslator < Filter + define_options :tr_fn + + def call(exp) + @captures_count, @captures_var, @text = 0, unique_name, '' + + result = compile(exp) + + if @captures_count > 0 + result.insert(1, [:code, "#{@captures_var}=[]"]) + result << [:slim, :output, false, "#{options[:tr_fn]}(#{@text.inspect}).gsub(/%(\\d+)/) { #{@captures_var}[$1.to_i-1] }", [:multi]] + else + result << [:slim, :output, false, "#{options[:tr_fn]}(#{@text.inspect})", [:multi]] + end + end + + def on_static(text) + @text << text + [:multi] + end + + def on_slim_output(escape, code, content) + @captures_count += 1 + @text << "%#{@captures_count}" + [:capture, "#{@captures_var}[#{@captures_count-1}]", [:slim, :output, escape, code, content]] + end + end + end +end + +Slim::Engine.before Slim::EndInserter, Slim::Translator diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/version.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/version.rb new file mode 100644 index 0000000..a3380cf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/lib/slim/version.rb @@ -0,0 +1,5 @@ +module Slim + # Slim version string + # @api public + VERSION = '4.1.0' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/slim.gemspec b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/slim.gemspec new file mode 100644 index 0000000..0bbc7ae --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/slim.gemspec @@ -0,0 +1,24 @@ +# -*- encoding: utf-8 -*- +require File.dirname(__FILE__) + '/lib/slim/version' +require 'date' + +Gem::Specification.new do |s| + s.name = 'slim' + s.version = Slim::VERSION + s.date = Date.today.to_s + s.authors = ['Daniel Mendler', 'Andrew Stone', 'Fred Wu'] + s.email = ['mail@daniel-mendler.de', 'andy@stonean.com', 'ifredwu@gmail.com'] + s.summary = 'Slim is a template language.' + s.description = 'Slim is a template language whose goal is reduce the syntax to the essential parts without becoming cryptic.' + s.homepage = 'http://slim-lang.com/' + s.license = 'MIT' + + s.files = `git ls-files`.split("\n") + s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } + s.require_paths = %w(lib) + + s.required_ruby_version = '>=2.0.0' + + s.add_runtime_dependency('temple', ['>= 0.7.6', '< 0.9']) + s.add_runtime_dependency('tilt', ['>= 2.0.6', '< 2.1']) +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/helper.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/helper.rb new file mode 100644 index 0000000..5bfc5b6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/helper.rb @@ -0,0 +1,209 @@ +begin + require 'simplecov' + SimpleCov.start +rescue LoadError +end + +require 'minitest/autorun' +require 'slim' +require 'slim/grammar' + +Slim::Engine.after Slim::Parser, Temple::Filters::Validator, grammar: Slim::Grammar +Slim::Engine.before :Pretty, Temple::Filters::Validator + +class TestSlim < Minitest::Test + def setup + @env = Env.new + end + + def render(source, options = {}, &block) + scope = options.delete(:scope) + locals = options.delete(:locals) + Slim::Template.new(options[:file], options) { source }.render(scope || @env, locals, &block) + end + + class HtmlSafeString < String + def html_safe? + true + end + + def to_s + self + end + end + + def with_html_safe + String.send(:define_method, :html_safe?) { false } + String.send(:define_method, :html_safe) { HtmlSafeString.new(self) } + yield + ensure + String.send(:undef_method, :html_safe?) if String.method_defined?(:html_safe?) + String.send(:undef_method, :html_safe) if String.method_defined?(:html_safe) + end + + def assert_html(expected, source, options = {}, &block) + assert_equal expected, render(source, options, &block) + end + + def assert_syntax_error(message, source, options = {}) + render(source, options) + raise 'Syntax error expected' + rescue Slim::Parser::SyntaxError => ex + assert_equal message, ex.message + message =~ /([^\s]+), Line (\d+)/ + assert_backtrace ex, "#{$1}:#{$2}" + end + + def assert_ruby_error(error, from, source, options = {}) + render(source, options) + raise 'Ruby error expected' + rescue error => ex + assert_backtrace(ex, from) + end + + def assert_backtrace(ex, from) + if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx' + # HACK: Rubinius stack trace sometimes has one entry more + if ex.backtrace[0] !~ /^#{Regexp.escape from}/ + ex.backtrace[1] =~ /([^\s]+:\d+)/ + assert_equal from, $1 + end + else + ex.backtrace[0] =~ /([^\s]+:\d+)/ + assert_equal from, $1 + end + end + + def assert_ruby_syntax_error(from, source, options = {}) + render(source, options) + raise 'Ruby syntax error expected' + rescue SyntaxError => ex + ex.message =~ /([^\s]+:\d+):/ + assert_equal from, $1 + end + + def assert_runtime_error(message, source, options = {}) + render(source, options) + raise Exception, 'Runtime error expected' + rescue RuntimeError => ex + assert_equal message, ex.message + end +end + +class Env + attr_reader :var, :x + + def initialize + @var = 'instance' + @x = 0 + end + + def id_helper + "notice" + end + + def hash + {a: 'The letter a', b: 'The letter b'} + end + + def show_first?(show = false) + show + end + + def define_macro(name, &block) + @macro ||= {} + @macro[name.to_s] = block + '' + end + + def call_macro(name, *args) + @macro[name.to_s].call(*args) + end + + def hello_world(text = "Hello World from @env", opts = {}) + text << opts.to_a * " " if opts.any? + if block_given? + "#{text} #{yield} #{text}" + else + text + end + end + + def message(*args) + args.join(' ') + end + + def action_path(*args) + "/action-#{args.join('-')}" + end + + def in_keyword + "starts with keyword" + end + + def evil_method + "" + end + + def output_number + 1337 + end + + def succ_x + @x = @x.succ + end + +end + +class ViewEnv + def output_number + 1337 + end + + def person + [{name: 'Joe'}, {name: 'Jack'}] + end + + def people + %w(Andy Fred Daniel).collect{|n| Person.new(n)} + end + + def cities + %w{Atlanta Melbourne Karlsruhe} + end + + def people_with_locations + array = [] + people.each_with_index do |p,i| + p.location = Location.new cities[i] + array << p + end + array + end +end + +require 'forwardable' + +class Person + extend Forwardable + + attr_accessor :name + + def initialize(name) + @name = name + end + + def location=(location) + @location = location + end + + def_delegators :@location, :city +end + +class Location + attr_accessor :city + + def initialize(city) + @city = city + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_blocks.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_blocks.rb new file mode 100644 index 0000000..a19529a --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_blocks.rb @@ -0,0 +1,194 @@ +require 'helper' + +class TestSlimCodeBlocks < TestSlim + def test_render_with_output_code_block + source = %q{ +p + = hello_world "Hello Ruby!" do + | Hello from within a block! +} + + assert_html '

Hello Ruby! Hello from within a block! Hello Ruby!

', source + end + + def test_render_with_output_code_block_without_do + source = %q{ +p + = hello_world "Hello Ruby!" + | Hello from within a block! +} + + assert_html '

Hello Ruby! Hello from within a block! Hello Ruby!

', source + end + + def test_render_variable_ending_with_do + source = %q{ +- appelido=10 +p= appelido +- appelido +} + + assert_html '

10

', source + end + + + def test_render_with_output_code_within_block + source = %q{ +p + = hello_world "Hello Ruby!" do + = hello_world "Hello from within a block!" +} + + assert_html '

Hello Ruby! Hello from within a block! Hello Ruby!

', source + end + + def test_render_with_output_code_within_block_without_do + source = %q{ +p + = hello_world "Hello Ruby!" + = hello_world "Hello from within a block!" +} + + assert_html '

Hello Ruby! Hello from within a block! Hello Ruby!

', source + end + + def test_render_with_output_code_within_block_2 + source = %q{ +p + = hello_world "Hello Ruby!" do + = hello_world "Hello from within a block!" do + = hello_world "And another one!" +} + + assert_html '

Hello Ruby! Hello from within a block! And another one! Hello from within a block! Hello Ruby!

', source + end + + def test_render_with_output_code_within_block_2_without_do + source = %q{ +p + = hello_world "Hello Ruby!" + = hello_world "Hello from within a block!" + = hello_world "And another one!" +} + + assert_html '

Hello Ruby! Hello from within a block! And another one! Hello from within a block! Hello Ruby!

', source + end + + def test_output_block_with_arguments + source = %q{ +p + = define_macro :person do |first_name, last_name| + .first_name = first_name + .last_name = last_name + == call_macro :person, 'John', 'Doe' + == call_macro :person, 'Max', 'Mustermann' +} + + assert_html '

John
Doe
Max
Mustermann

', source + end + + + def test_render_with_control_code_loop + source = %q{ +p + - 3.times do + | Hey! +} + + assert_html '

Hey!Hey!Hey!

', source + end + + def test_render_with_control_code_loop_without_do + source = %q{ +p + - 3.times + | Hey! +} + + assert_html '

Hey!Hey!Hey!

', source + end + + def test_captured_code_block_with_conditional + source = %q{ += hello_world "Hello Ruby!" do + - if true + | Hello from within a block! +} + + assert_html 'Hello Ruby! Hello from within a block! Hello Ruby!', source + end + + def test_captured_code_block_with_conditional_without_do + source = %q{ += hello_world "Hello Ruby!" + - if true + | Hello from within a block! +} + + assert_html 'Hello Ruby! Hello from within a block! Hello Ruby!', source + end + + def test_if_without_content + source = %q{ +- if true +} + assert_html '', source + end + + def test_unless_without_content + source = %q{ +- unless true +} + assert_html '', source + end + + def test_if_with_comment + source = %q{ +- if true + / comment +} + assert_html '', source + end + + def test_control_do_with_comment + source = %q{ +- hello_world "Hello" + / comment +} + assert_html '', source + end + + def test_output_do_with_comment + source = %q{ += hello_world "Hello" + / comment +} + assert_html 'Hello', source + end + + def test_output_if_without_content + source = %q{ += if true +} + assert_html '', source + end + + def test_output_if_with_comment + source = %q{ += if true + / comment +} + assert_html '', source + end + + def test_output_format_with_if + source = %q{ +h3.subtitle + - if true + a href="#" Title true + - else + a href="#" Title false +} + assert_html '

Title true

', source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_escaping.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_escaping.rb new file mode 100644 index 0000000..9d51b30 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_escaping.rb @@ -0,0 +1,162 @@ +require 'helper' + +class TestSlimCodeEscaping < TestSlim + def test_escaping_evil_method + source = %q{ +p = evil_method +} + + assert_html '

<script>do_something_evil();</script>

', source + end + + def test_render_without_html_safe + source = %q{ +p = "Hello World\\n, meet \\"Slim\\"." +} + + assert_html "

<strong>Hello World\n, meet \"Slim\"</strong>.

", source + end + + def test_render_without_html_safe2 + source = %q{ +p = "Hello World\\n, meet 'Slim'." +} + + assert_html "

<strong>Hello World\n, meet 'Slim'</strong>.

", source + end + + def test_render_with_html_safe_false + source = %q{ +p = "Hello World\\n, meet \\"Slim\\"." +} + + with_html_safe do + assert_html "

<strong>Hello World\n, meet \"Slim\"</strong>.

", source, use_html_safe: true + end + end + + def test_render_with_html_safe_true + source = %q{ +p = "Hello World\\n, meet \\"Slim\\".".html_safe +} + + with_html_safe do + assert_html "

Hello World\n, meet \"Slim\".

", source, use_html_safe: true + end + end + + def test_render_splat_with_html_safe_true + source = %q{ +p *{ title: '&'.html_safe } +} + + with_html_safe do + assert_html "

", source, use_html_safe: true + end + end + + def test_render_splat_with_html_safe_false + source = %q{ +p *{ title: '&' } +} + + with_html_safe do + assert_html "

", source, use_html_safe: true + end + end + + def test_render_splat_injecting_evil_attr_name + source = %q{ +p *{ ">

'test' } +} + + with_html_safe do + assert_raises Slim::InvalidAttributeNameError do + render(source, use_html_safe: true) + end + end + end + + + def test_render_attribute_with_html_safe_true + source = %q{ +p title=('&'.html_safe) +} + + with_html_safe do + assert_html "

", source, use_html_safe: true + end + end + + def test_render_with_disable_escape_false + source = %q{ += "

Hello

" +== "

World

" +} + + assert_html "<p>Hello</p>

World

", source + end + + def test_render_with_disable_escape_true + source = %q{ += "

Hello

" +== "

World

" +} + + assert_html "

Hello

World

", source, disable_escape: true + end + + def test_escaping_evil_method_with_pretty + source = %q{ +p = evil_method +} + + assert_html "

\n <script>do_something_evil();</script>\n

", source, pretty: true + end + + def test_render_without_html_safe_with_pretty + source = %q{ +p = "Hello World\\n, meet \\"Slim\\"." +} + + assert_html "

\n <strong>Hello World\n , meet \"Slim\"</strong>.\n

", source, pretty: true + end + + def test_render_with_html_safe_false_with_pretty + source = %q{ +p = "Hello World\\n, meet \\"Slim\\"." +} + + with_html_safe do + assert_html "

\n <strong>Hello World\n , meet \"Slim\"</strong>.\n

", source, use_html_safe: true, pretty: true + end + end + + def test_render_with_html_safe_true_with_pretty + source = %q{ +p = "Hello World\\n, meet \\"Slim\\".".html_safe +} + + with_html_safe do + assert_html "

\n Hello World\n , meet \"Slim\".\n

", source, use_html_safe: true, pretty: true + end + end + + def test_render_with_disable_escape_false_with_pretty + source = %q{ += "

Hello

" +== "

World

" +} + + assert_html "<p>Hello</p>

World

", source, pretty: true + end + + def test_render_with_disable_escape_true_with_pretty + source = %q{ += "

Hello

" +== "

World

" +} + + assert_html "

Hello

World

", source, disable_escape: true, pretty: true + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_evaluation.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_evaluation.rb new file mode 100644 index 0000000..6ae1198 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_evaluation.rb @@ -0,0 +1,180 @@ +require 'helper' + +class TestSlimCodeEvaluation < TestSlim + def test_render_with_call_to_set_attributes + source = %q{ +p id="#{id_helper}" class="hello world" = hello_world +} + + assert_html '

Hello World from @env

', source + end + + def test_render_with_call_to_set_custom_attributes + source = %q{ +p data-id="#{id_helper}" data-class="hello world" + = hello_world +} + + assert_html '

Hello World from @env

', source + end + + def test_render_with_call_to_set_attributes_and_call_to_set_content + source = %q{ +p id="#{id_helper}" class="hello world" = hello_world +} + + assert_html '

Hello World from @env

', source + end + + def test_render_with_parameterized_call_to_set_attributes_and_call_to_set_content + source = %q{ +p id="#{id_helper}" class="hello world" = hello_world("Hello Ruby!") +} + + assert_html '

Hello Ruby!

', source + end + + def test_render_with_spaced_parameterized_call_to_set_attributes_and_call_to_set_content + source = %q{ +p id="#{id_helper}" class="hello world" = hello_world "Hello Ruby!" +} + + assert_html '

Hello Ruby!

', source + end + + def test_render_with_spaced_parameterized_call_to_set_attributes_and_call_to_set_content_2 + source = %q{ +p id="#{id_helper}" class="hello world" = hello_world "Hello Ruby!", dummy: "value" +} + + assert_html '

Hello Ruby!dummy value

', source + end + + def test_hash_call_in_attribute + source = %q{ +p id="#{hash[:a]}" Test it +} + + assert_html '

Test it

', source + end + + def test_instance_variable_in_attribute_without_quotes + source = %q{ +p id=@var +} + + assert_html '

', source + end + + def test_method_call_in_attribute_without_quotes + source = %q{ +form action=action_path(:page, :save) method='post' +} + + assert_html '
', source + end + + def test_ruby_attribute_with_unbalanced_delimiters + source = %q{ +div crazy=action_path('[') id="crazy_delimiters" +} + + assert_html '
', source + end + + def test_method_call_in_delimited_attribute_without_quotes + source = %q{ +form(action=action_path(:page, :save) method='post') +} + + assert_html '
', source + end + + def test_method_call_in_delimited_attribute_without_quotes2 + source = %q{ +form(method='post' action=action_path(:page, :save)) +} + + assert_html '
', source + end + + def test_hash_call_in_attribute_without_quotes + source = %q{ +p id=hash[:a] Test it +} + + assert_html '

Test it

', source + end + + def test_hash_call_in_delimited_attribute + source = %q{ +p(id=hash[:a]) Test it +} + + assert_html '

Test it

', source + end + + def test_hash_call_in_attribute_with_ruby_evaluation + source = %q{ +p id=(hash[:a] + hash[:a]) Test it +} + + assert_html '

Test it

', source + end + + def test_hash_call_in_delimited_attribute_with_ruby_evaluation + source = %q{ +p(id=(hash[:a] + hash[:a])) Test it +} + + assert_html '

Test it

', source + end + + def test_hash_call_in_delimited_attribute_with_ruby_evaluation_2 + source = %q{ +p[id=(hash[:a] + hash[:a])] Test it +} + + assert_html '

Test it

', source + end + + def test_hash_call_in_delimited_attribute_with_ruby_evaluation_3 + source = %q{ +p(id=(hash[:a] + hash[:a]) class=hash[:a]) Test it +} + + assert_html '

Test it

', source + end + + def test_hash_call_in_delimited_attribute_with_ruby_evaluation_4_ + source = %q{ +p(id=hash[:a] class=hash[:a]) Test it +} + + assert_html '

Test it

', source + end + + def test_computation_in_attribute + source = %q{ +p id=(1 + 1)*5 Test it +} + + assert_html '

Test it

', source + end + + def test_code_attribute_does_not_modify_argument + template = 'span class=attribute' + model = OpenStruct.new(attribute: [:a, :b, [:c, :d]]) + output = Slim::Template.new { template }.render(model) + assert_equal('', output) + assert_equal([:a, :b, [:c, :d]], model.attribute) + end + + def test_number_type_interpolation + source = %q{ +p = output_number +} + + assert_html '

1337

', source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_output.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_output.rb new file mode 100644 index 0000000..0f923d0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_output.rb @@ -0,0 +1,168 @@ +require 'helper' + +class TestSlimCodeOutput < TestSlim + def test_render_with_call + source = %q{ +p + = hello_world +} + + assert_html '

Hello World from @env

', source + end + + def test_render_with_trailing_whitespace + source = %q{ +p + => hello_world +} + + assert_html '

Hello World from @env

', source + end + + def test_render_with_trailing_whitespace_after_tag + source = %q{ +p=> hello_world +} + + assert_html '

Hello World from @env

', source + end + + def test_no_escape_render_with_trailing_whitespace + source = %q{ +p + ==> hello_world +} + + assert_html '

Hello World from @env

', source + end + + def test_no_escape_render_with_trailing_whitespace_after_tag + source = %q{ +p==> hello_world +} + + assert_html '

Hello World from @env

', source + end + + def test_render_with_conditional_call + source = %q{ +p + = hello_world if true +} + + assert_html '

Hello World from @env

', source + end + + def test_render_with_parameterized_call + source = %q{ +p + = hello_world("Hello Ruby!") +} + + assert_html '

Hello Ruby!

', source + end + + def test_render_with_spaced_parameterized_call + source = %q{ +p + = hello_world "Hello Ruby!" +} + + assert_html '

Hello Ruby!

', source + end + + def test_render_with_spaced_parameterized_call_2 + source = %q{ +p + = hello_world "Hello Ruby!", dummy: "value" +} + + assert_html '

Hello Ruby!dummy value

', source + end + + def test_render_with_call_and_inline_text + source = %q{ +h1 This is my title +p + = hello_world +} + + assert_html '

This is my title

Hello World from @env

', source + end + + def test_render_with_attribute_starts_with_keyword + source = %q{ +p = hello_world in_keyword +} + + assert_html '

starts with keyword

', source + end + + def test_hash_call + source = %q{ +p = hash[:a] +} + + assert_html '

The letter a

', source + end + + def test_tag_output_without_space + source = %q{ +p= hello_world +p=hello_world +} + + assert_html '

Hello World from @env

Hello World from @env

', source + end + + def test_class_output_without_space + source = %q{ +.test=hello_world +#test==hello_world +} + + assert_html '
Hello World from @env
Hello World from @env
', source + end + + def test_attribute_output_without_space + source = %q{ +p id="test"=hello_world +p(id="test")==hello_world +} + + assert_html '

Hello World from @env

Hello World from @env

', source + end + + def test_render_with_backslash_end +# Keep trailing spaces! + source = %q{ +p = \ +"Hello" + \ +" Ruby!" +- variable = 1 + \ + 2 + \ + 3 += variable + \ + 1 +} + + assert_html '

Hello Ruby!

7', source + end + + def test_render_with_comma_end + source = %q{ +p = message("Hello", + "Ruby!") +} + + assert_html '

Hello Ruby!

', source + end + + def test_render_with_no_trailing_character + source = %q{ +p + = hello_world} + + assert_html '

Hello World from @env

', source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_structure.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_structure.rb new file mode 100644 index 0000000..0f709b2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_code_structure.rb @@ -0,0 +1,186 @@ +require 'helper' + +class TestSlimCodeStructure < TestSlim + def test_render_with_conditional + source = %q{ +div + - if show_first? + p The first paragraph + - else + p The second paragraph +} + + assert_html '

The second paragraph

', source + end + + def test_render_with_begin + source = %q{ +- if true + - begin + p A +- if true + - begin + p B +- if true + - begin + p C + - rescue + p D +} + + assert_html '

A

B

C

', source + end + + def test_render_with_consecutive_conditionals + source = %q{ +div + - if show_first? true + p The first paragraph + - if show_first? true + p The second paragraph +} + + assert_html '

The first paragraph

The second paragraph

', source + end + + def test_render_with_parameterized_conditional + source = %q{ +div + - if show_first? false + p The first paragraph + - else + p The second paragraph +} + + assert_html '

The second paragraph

', source + end + + def test_render_with_when_string_in_condition + source = %q{ +- if true + | Hello + +- unless 'when' == nil + | world +} + + assert_html 'Hello world', source + end + + def test_render_with_conditional_and_following_nonconditonal + source = %q{ +div + - if true + p The first paragraph + - var = 42 + = var +} + + assert_html '

The first paragraph

42
', source + end + + def test_render_with_inline_condition + source = %q{ +p = hello_world if true +} + + assert_html '

Hello World from @env

', source + end + + def test_render_with_case + source = %q{ +p + - case 42 + - when 41 + | 41 + - when 42 + | 42 + | is the answer +p + - case 41 + - when 41 + | 41 + - when 42 + | 42 + | is the answer +p + - case 42 when 41 + | 41 + - when 42 + | 42 + | is the answer +p + - case 41 when 41 + | 41 + - when 42 + | 42 + | is the answer +} + + assert_html '

42 is the answer

41 is the answer

42 is the answer

41 is the answer

', source + end + + def test_render_with_slim_comments + source = %q{ +p Hello +/ This is a comment + Another comment +p World +} + + assert_html '

Hello

World

', source + end + + def test_render_with_yield + source = %q{ +div + == yield :menu +} + + assert_html '
This is the menu
', source do + 'This is the menu' + end + end + + def test_render_with_begin_rescue + source = %q{ +- begin + p Begin +- rescue + p Rescue +p After +} + + assert_html '

Begin

After

', source + end + + def test_render_with_begin_rescue_exception + source = %q{ +- begin + p Begin + - raise 'Boom' + p After Boom +- rescue => ex + p = ex.message +p After +} + + assert_html '

Begin

Boom

After

', source + end + + def test_render_with_begin_rescue_ensure + source = %q{ +- begin + p Begin + - raise 'Boom' + p After Boom +- rescue => ex + p = ex.message +- ensure + p Ensure +p After +} + + assert_html '

Begin

Boom

Ensure

After

', source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_commands.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_commands.rb new file mode 100644 index 0000000..7cf8e83 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_commands.rb @@ -0,0 +1,222 @@ +require 'helper' +require 'open3' +require 'tempfile' + +class TestSlimCommands < Minitest::Test + # nothing complex + STATIC_TEMPLATE = "p Hello World!\n" + + # requires a `name` variable to exist at render time + DYNAMIC_TEMPLATE = "p Hello \#{name}!\n" + + # a more complex example + LONG_TEMPLATE = "h1 Hello\np\n | World!\n small Tiny text" + + # exception raising example + EXCEPTION_TEMPLATE = '- raise NotImplementedError' + + # Temple has this feature... + STRING_FREEZER = RUBY_VERSION >= '2.1' ? '.freeze' : '' + + def test_option_help + out, err = exec_slimrb '--help' + + assert err.empty? + assert_match %r{Show this message}, out + end + + def test_option_version + out, err = exec_slimrb '--version' + + assert err.empty? + assert_match %r{\ASlim #{Regexp.escape Slim::VERSION}$}, out + end + + def test_render + prepare_common_test STATIC_TEMPLATE do |out, err| + assert err.empty? + assert_equal "

Hello World!

\n", out + end + end + + # superficial test, we don't want to test Tilt/Temple + def test_compile + prepare_common_test STATIC_TEMPLATE, '--compile' do |out, err| + assert err.empty? + assert_match %r{\"

Hello World!<\/p>\"#{STRING_FREEZER}}, out + end + end + + def test_erb + prepare_common_test DYNAMIC_TEMPLATE, '--erb' do |out, err| + assert err.empty? + assert_equal "

Hello <%= ::Temple::Utils.escape_html((name)) %>!

\n", out + end + end + + def test_rails + prepare_common_test DYNAMIC_TEMPLATE, '--rails' do |out, err| + assert err.empty? + + assert out.include? %Q{@output_buffer = ActiveSupport::SafeBuffer.new;} + assert out.include? %Q{@output_buffer.safe_concat(("

Hello "#{STRING_FREEZER}));} + assert out.include? %Q{@output_buffer.safe_concat(((::Temple::Utils.escape_html((name))).to_s));} + assert out.include? %Q{@output_buffer.safe_concat(("!

"#{STRING_FREEZER}));} + end + end + + def test_pretty + prepare_common_test LONG_TEMPLATE, '--pretty' do |out, err| + assert err.empty? + assert_equal "

\n Hello\n

\n

\n World!Tiny text\n

\n", out + end + end + + # We cannot run these two on Travis, because we can't install libyaml. + # See https://github.com/slim-template/slim/issues/576 + if ENV['TRAVIS'] && RUBY_ENGINE != 'rbx' + def test_locals_json + data = '{"name":"from slim"}' + prepare_common_test DYNAMIC_TEMPLATE, '--locals', data do |out, err| + assert err.empty? + assert_equal "

Hello from slim!

\n", out + end + end + + def test_locals_yaml + data = "name: from slim" + prepare_common_test DYNAMIC_TEMPLATE, '--locals', data do |out, err| + assert err.empty? + assert_equal "

Hello from slim!

\n", out + end + end + end + + def test_locals_hash + data = '{name:"from slim"}' + prepare_common_test DYNAMIC_TEMPLATE, '--locals', data do |out, err| + assert err.empty? + assert_equal "

Hello from slim!

\n", out + end + end + + def test_require + with_tempfile 'puts "Not in slim"', 'rb' do |lib| + prepare_common_test STATIC_TEMPLATE, '--require', lib, stdin_file: false, file_file: false do |out, err| + assert err.empty? + assert_equal "Not in slim\n

Hello World!

\n", out + end + end + end + + def test_error + prepare_common_test EXCEPTION_TEMPLATE, stdin_file: false do |out, err| + assert out.empty? + assert_match %r{NotImplementedError: NotImplementedError}, err + assert_match %r{Use --trace for backtrace}, err + end + end + + def test_trace_error + prepare_common_test EXCEPTION_TEMPLATE, '--trace', stdin_file: false do |out, err| + assert out.empty? + assert_match %r{bin\/slimrb}, err + end + end + +private + + # Whether you call slimrb with a file argument or pass the slim content + # via $stdin; whether you want the output written to $stdout or into + # another file given as argument, the output is the same. + # + # This method prepares a test with this exact behaviour: + # + # It yields the tupel (out, err) once after the `content` was passed + # in via $stdin and once it was passed as a (temporary) file argument. + # + # In effect, this method executes a test (given as block) 4 times: + # + # 1. read from $stdin, write to $stdout + # 2. read from file, write to $stdout + # 3. read from $stdin, write to file + # 4. read from file, write to file + def prepare_common_test(content, *args) + options = Hash === args.last ? args.pop : {} + + # case 1. $stdin → $stdout + unless options[:stdin_stdout] == false + out, err = exec_slimrb(*args, '--stdin') do |i| + i.write content + end + yield out, err + end + + # case 2. file → $stdout + unless options[:file_stdout] == false + with_tempfile content do |in_file| + out, err = exec_slimrb(*args, in_file) + yield out, err + end + end + + # case 3. $stdin → file + unless options[:stdin_file] == false + with_tempfile content do |out_file| + _, err = exec_slimrb(*args, '--stdin', out_file) do |i| + i.write content + end + yield File.read(out_file), err + end + end + + # case 3. file → file + unless options[:file_file] == false + with_tempfile '' do |out_file| + with_tempfile content do |in_file| + _, err = exec_slimrb(*args, in_file, out_file) do |i| + i.write content + end + yield File.read(out_file), err + end + end + end + end + + # Calls bin/slimrb as a subprocess. + # + # Yields $stdin to the caller and returns a tupel (out,err) with the + # contents of $stdout and $stderr. + # + # (I'd like to use Minitest::Assertions#capture_subprecess_io here, + # but then there's no way to insert data via $stdin.) + def exec_slimrb(*args) + out, err = nil, nil + + Open3.popen3 'ruby', 'bin/slimrb', *args do |i,o,e,t| + yield i if block_given? + i.close + out, err = o.read, e.read + end + + return out, err + end + + # Creates a temporary file with the given content and yield the path + # to this file. The file itself is only available inside the block and + # will be deleted afterwards. + def with_tempfile(content=nil, extname='slim') + f = Tempfile.new ['slim', ".#{extname}"] + if content + f.write content + f.flush # ensure content is actually saved to disk + f.rewind + end + + yield f.path + ensure + f.close + f.unlink + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_embedded_engines.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_embedded_engines.rb new file mode 100644 index 0000000..1a62853 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_embedded_engines.rb @@ -0,0 +1,243 @@ +require 'helper' +require 'erb' + +class TestSlimEmbeddedEngines < TestSlim + + def test_render_with_markdown + source = %q{ +markdown: + #Header + Hello from #{"Markdown!"} + + #{1+2} + + * one + * two +} + if ::Tilt['md'].name =~ /Redcarpet/ + # redcarpet + assert_html "

Header

\n\n

Hello from Markdown!

\n\n

3

\n\n
    \n
  • one
  • \n
  • two
  • \n
\n", source + elsif ::Tilt['md'].name =~ /RDiscount/ + # rdiscount + assert_html "

Header

\n\n

Hello from Markdown!

\n\n

3

\n\n
    \n
  • one
  • \n
  • two
  • \n
\n\n", source + else + # kramdown, :auto_ids by default + assert_html "

Header

\n

Hello from Markdown!

\n\n

3

\n\n
    \n
  • one
  • \n
  • two
  • \n
\n", source + + Slim::Embedded.with_options(markdown: {auto_ids: false}) do + assert_html "

Header

\n

Hello from Markdown!

\n\n

3

\n\n
    \n
  • one
  • \n
  • two
  • \n
\n", source + end + + assert_html "

Header

\n

Hello from Markdown!

\n\n

3

\n\n
    \n
  • one
  • \n
  • two
  • \n
\n", source + end + end + + def test_render_with_css + source = %q{ +css: + h1 { color: blue } +} + assert_html "", source + end + + def test_render_with_css_empty_attributes + source = %q{ +css []: + h1 { color: blue } +} + assert_html "", source + end + + def test_render_with_css_attribute + source = %q{ +css scoped = "true": + h1 { color: blue } +} + assert_html "", source + end + + def test_render_with_css_multiple_attributes + source = %q{ +css class="myClass" scoped = "true" : + h1 { color: blue } +} + assert_html "", source + end + + def test_render_with_javascript + source = %q{ +javascript: + $(function() {}); + + + alert('hello') +p Hi +} + assert_html %{

Hi

}, source + end + + def test_render_with_javascript_empty_attributes + source = %q{ +javascript (): + alert('hello') +} + assert_html %{}, source + end + + def test_render_with_javascript_attribute + source = %q{ +javascript [class = "myClass"]: + alert('hello') +} + assert_html %{}, source + end + + def test_render_with_javascript_multiple_attributes + source = %q{ +javascript { class = "myClass" id="myId" other-attribute = 'my_other_attribute' } : + alert('hello') +} + assert_html %{}, source + end + + def test_render_with_javascript_with_tabs + source = "javascript:\n\t$(function() {});\n\talert('hello')\np Hi" + assert_html "

Hi

", source + end + + def test_render_with_javascript_including_variable + source = %q{ +- func = "alert('hello');" +javascript: + $(function() { #{func} }); +} + assert_html %q||, source + end + + def test_render_with_javascript_with_explicit_html_comment + Slim::Engine.with_options(js_wrapper: :comment) do + source = "javascript:\n\t$(function() {});\n\talert('hello')\np Hi" + assert_html "

Hi

", source + end + end + + def test_render_with_javascript_with_explicit_cdata_comment + Slim::Engine.with_options(js_wrapper: :cdata) do + source = "javascript:\n\t$(function() {});\n\talert('hello')\np Hi" + assert_html "

Hi

", source + end + end + + def test_render_with_javascript_with_format_xhtml_comment + Slim::Engine.with_options(js_wrapper: :guess, format: :xhtml) do + source = "javascript:\n\t$(function() {});\n\talert('hello')\np Hi" + assert_html "

Hi

", source + end + end + + def test_render_with_javascript_with_format_html_comment + Slim::Engine.with_options(js_wrapper: :guess, format: :html) do + source = "javascript:\n\t$(function() {});\n\talert('hello')\np Hi" + assert_html "

Hi

", source + end + end + + def test_render_with_ruby + source = %q{ +ruby: + variable = 1 + + 2 += variable +} + assert_html '3', source + end + + def test_render_with_ruby_heredoc + source = %q{ +ruby: + variable = <<-MSG + foobar + MSG += variable +} + assert_html "foobar\n", source + end + + def test_render_with_scss + source = %q{ +scss: + $color: #f00; + body { color: $color; } +} + assert_html "", source + end + + def test_render_with_scss_attribute + source = %q{ +scss [class="myClass"]: + $color: #f00; + body { color: $color; } +} + assert_html "", source + end + + def test_render_with_sass + source = %q{ +sass: + $color: #f00 + body + color: $color +} + assert_html "", source + end + + def test_render_with_sass_attribute + source = %q{ +sass [class="myClass"]: + $color: #f00 + body + color: $color +} + assert_html "", source + end + + + def test_disabled_embedded_engine + source = %{ +ruby: + Embedded Ruby +} + assert_runtime_error 'Embedded engine ruby is disabled', source, enable_engines: [:javascript] + assert_runtime_error 'Embedded engine ruby is disabled', source, enable_engines: %w(javascript) + + source = %{ +ruby: + Embedded Ruby +} + assert_runtime_error 'Embedded engine ruby is disabled', source, enable_engines: [:javascript] + assert_runtime_error 'Embedded engine ruby is disabled', source, enable_engines: %w(javascript) + + source = %{ +ruby: + Embedded Ruby +} + assert_runtime_error 'Embedded engine ruby is disabled', source, disable_engines: [:ruby] + assert_runtime_error 'Embedded engine ruby is disabled', source, disable_engines: %w(ruby) + end + + def test_enabled_embedded_engine + source = %q{ +javascript: + $(function() {}); +} + assert_html '', source, disable_engines: [:ruby] + assert_html '', source, disable_engines: %w(ruby) + + source = %q{ +javascript: + $(function() {}); +} + assert_html '', source, enable_engines: [:javascript] + assert_html '', source, enable_engines: %w(javascript) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_encoding.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_encoding.rb new file mode 100644 index 0000000..b69ce5f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_encoding.rb @@ -0,0 +1,28 @@ +require 'helper' + +class TestSlimEncoding < TestSlim + def test_windows_crlf + source = "a href='#' something\r\nbr\r\na href='#' others\r\n" + result = "something
others" + assert_html result, source + end + + def test_binary + source = "| \xFF\xFF" + source.force_encoding(Encoding::BINARY) + + result = "\xFF\xFF" + result.force_encoding(Encoding::BINARY) + + out = render(source, default_encoding: 'binary') + out.force_encoding(Encoding::BINARY) + + assert_equal result, out + end + + def test_bom + source = "\xEF\xBB\xBFh1 Hello World!" + result = '

Hello World!

' + assert_html result, source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_erb_converter.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_erb_converter.rb new file mode 100644 index 0000000..4c9d93c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_erb_converter.rb @@ -0,0 +1,67 @@ +require 'helper' +require 'slim/erb_converter' + +class TestSlimERBConverter < TestSlim + def test_converter + source = %q{ +doctype 5 +html + head + title Hello World! + /! Meta tags + with long explanatory + multiline comment + meta name="description" content="template language" + /! Stylesheets + link href="style.css" media="screen" rel="stylesheet" type="text/css" + link href="colors.css" media="screen" rel="stylesheet" type="text/css" + /! Javascripts + script src="jquery.js" + script src="jquery.ui.js" + /[if lt IE 9] + script src="old-ie1.js" + script src="old-ie2.js" + sass: + body + background-color: red + body + #container + p Hello + World! + p= "dynamic text with\nnewline" +} + + result = %q{ + + + +Hello World! + + + + + + + + +
+

Hello + +World!

+

<%= ::Temple::Utils.escape_html(("dynamic text with\nnewline")) %> +

} + + assert_equal result, Slim::ERBConverter.new.call(source) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_html_attributes.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_html_attributes.rb new file mode 100644 index 0000000..f4bb438 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_html_attributes.rb @@ -0,0 +1,268 @@ +require 'helper' + +class TestSlimHTMLAttributes < TestSlim + def test_ternary_operation_in_attribute + source = %q{ +p id="#{(false ? 'notshown' : 'shown')}" = output_number +} + + assert_html '

1337

', source + end + + def test_ternary_operation_in_attribute_2 + source = %q{ +p id=(false ? 'notshown' : 'shown') = output_number +} + + assert_html '

1337

', source + end + + def test_class_attribute_merging + source = %{ +.alpha class="beta" Test it +} + assert_html '
Test it
', source + end + + def test_class_attribute_merging_with_nil + source = %{ +.alpha class="beta" class=nil class="gamma" Test it +} + assert_html '
Test it
', source + end + + def test_class_attribute_merging_with_empty_static + source = %{ +.alpha class="beta" class="" class="gamma" Test it +} + assert_html '
Test it
', source + end + + def test_id_attribute_merging + source = %{ +#alpha id="beta" Test it +} + assert_html '
Test it
', source, merge_attrs: {'class' => ' ', 'id' => '_' } + end + + def test_id_attribute_merging2 + source = %{ +#alpha id="beta" Test it +} + assert_html '
Test it
', source, merge_attrs: {'class' => ' ', 'id' => '-' } + end + + def test_boolean_attribute_false + source = %{ +- cond=false +option selected=false Text +option selected=cond Text2 +} + + assert_html '', source + end + + def test_boolean_attribute_true + source = %{ +- cond=true +option selected=true Text +option selected=cond Text2 +} + + assert_html '', source + end + + def test_boolean_attribute_nil + source = %{ +- cond=nil +option selected=nil Text +option selected=cond Text2 +} + + assert_html '', source + end + + def test_boolean_attribute_string2 + source = %{ +option selected="selected" Text +} + + assert_html '', source + end + + def test_boolean_attribute_shortcut + source = %{ +option(class="clazz" selected) Text +option(selected class="clazz") Text +} + + assert_html '', source + end + + def test_array_attribute_merging + source = %{ +.alpha class="beta" class=[[""], :gamma, nil, :delta, [true, false]] +.alpha class=:beta,:gamma +} + + assert_html '
', source + end + + def test_hyphenated_attribute + source = %{ +.alpha data={a: 'alpha', b: 'beta', c_d: 'gamma', c: {e: 'epsilon'}} +} + + assert_html '
', source + end + + def test_splat_without_content + source = %q{ +*hash +p*hash +} + + assert_html '

', source + end + + def test_shortcut_splat + source = %q{ +*hash This is my title +} + + assert_html '
This is my title
', source + end + + def test_splat + source = %q{ +h1 *hash class=[] This is my title +} + + assert_html '

This is my title

', source + end + + def test_closed_splat + source = %q{ +*hash / +} + + assert_html '
', source + end + + def test_splat_tag_name + source = %q{ +*{tag: 'h1', id: 'title'} This is my title +} + + assert_html '

This is my title

', source + end + + + def test_splat_empty_tag_name + source = %q{ +*{tag: '', id: 'test'} This is my title +} + + assert_html '
This is my title
', source + end + + def test_closed_splat_tag + source = %q{ +*hash / +} + + assert_html '
', source + end + + def test_splat_with_id_shortcut + source = %q{ +#myid*hash This is my title +} + + assert_html '
This is my title
', source + end + + def test_splat_with_class_shortcut + source = %q{ +.myclass*hash This is my title +} + + assert_html '
This is my title
', source + end + + def test_splat_with_id_and_class_shortcuts + source = %q{ +#myid.myclass*hash This is my title +} + + assert_html '
This is my title
', source + end + + def test_splat_with_class_merging + source = %q{ +#myid.myclass *{class: [:secondclass, %w(x y z)]} *hash This is my title +} + + assert_html '
This is my title
', source + end + + def test_splat_with_boolean_attribute + source = %q{ +*{disabled: true, empty1: false, nonempty: '', empty2: nil} This is my title +} + + assert_html '
This is my title
', source + end + + def test_splat_merging_with_arrays + source = %q{ +*{a: 1, b: 2} *[[:c, 3], [:d, 4]] *[[:e, 5], [:f, 6]] This is my title +} + + assert_html '
This is my title
', source + end + + def test_splat_with_other_attributes + source = %q{ +h1 data-id="123" *hash This is my title +} + + assert_html '

This is my title

', source + end + + def test_attribute_merging + source = %q{ +a class=true class=false +a class=false *{class:true} +a class=true +a class=false +} + + assert_html '', source + end + + def test_static_empty_attribute + source = %q{ +p(id="marvin" name="" class="" data-info="Illudium Q-36")= output_number +} + + assert_html '

1337

', source + end + + def test_dynamic_empty_attribute + source = %q{ +p(id="marvin" class=nil nonempty=("".to_s) data-info="Illudium Q-36")= output_number +} + + assert_html '

1337

', source + end + + def test_weird_attribute + source = %q{ +p + img(src='img.png' whatsthis?!) + img src='img.png' whatsthis?!="wtf" +} + assert_html '

', source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_html_escaping.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_html_escaping.rb new file mode 100644 index 0000000..f707dae --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_html_escaping.rb @@ -0,0 +1,65 @@ +require 'helper' + +class TestSlimHtmlEscaping < TestSlim + def test_html_will_not_be_escaped + source = %q{ +p World, meet "Slim". +} + + assert_html '

World, meet "Slim".

', source + end + + def test_html_with_newline_will_not_be_escaped + source = %q{ +p + | + World, + meet "Slim". +} + + assert_html "

World,\n meet \"Slim\".

", source + end + + def test_html_with_escaped_interpolation + source = %q{ +- x = '"' +- content = '' +p class="#{x}" test #{content} +} + + assert_html '

test <x>

', source + end + + def test_html_nested_escaping + source = %q{ += hello_world do + | escaped & +} + assert_html 'Hello World from @env escaped & Hello World from @env', source + end + + def test_html_quoted_attr_escape + source = %q{ +p id="&" class=="&" +} + + assert_html '

', source + end + + def test_html_quoted_attr_escape_with_interpolation + source = %q{ +p id="&#{'"'}" class=="&#{'"'}" +p id="&#{{'"'}}" class=="&#{{'"'}}" +} + + assert_html '

', source + end + + def test_html_ruby_attr_escape + source = %q{ +p id=('&'.to_s) class==('&'.to_s) +} + + assert_html '

', source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_html_structure.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_html_structure.rb new file mode 100644 index 0000000..8f2189c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_html_structure.rb @@ -0,0 +1,545 @@ +require 'helper' + +class TestSlimHtmlStructure < TestSlim + def test_simple_render + # Keep the trailing space behind "body "! + source = %q{ +html + head + title Simple Test Title + body + p Hello World, meet Slim. +} + + assert_html 'Simple Test Title

Hello World, meet Slim.

', source + end + + def test_relaxed_indentation_of_first_line + source = %q{ + p + .content +} + + assert_html "

", source + end + + def test_html_tag_with_text_and_empty_line + source = %q{ +p Hello + +p World +} + + assert_html "

Hello

World

", source + end + + def test_html_namespaces + source = %q{ +html:body + html:p html:id="test" Text +} + + assert_html 'Text', source + end + + def test_doctype + source = %q{ +doctype 1.1 +html +} + + assert_html '', source, format: :xhtml + end + + def test_doctype_new_syntax + source = %q{ +doctype 5 +html +} + + assert_html '', source, format: :xhtml + end + + def test_doctype_new_syntax_html5 + source = %q{ +doctype html +html +} + + assert_html '', source, format: :xhtml + end + + def test_render_with_shortcut_attributes + source = %q{ +h1#title This is my title +#notice.hello.world + = hello_world +} + + assert_html '

This is my title

Hello World from @env
', source + end + + def test_render_with_overwritten_default_tag + source = %q{ +#notice.hello.world + = hello_world + } + + assert_html '
Hello World from @env
', source, default_tag: 'section' + end + + def test_render_with_custom_shortcut + source = %q{ +#notice.hello.world@test + = hello_world +@abc + = hello_world +} + + assert_html '
Hello World from @env
Hello World from @env
', source, shortcut: {'#' => {attr: 'id'}, '.' => {attr: 'class'}, '@' => {tag: 'section', attr: 'role'}} + end + + def test_render_with_custom_array_shortcut + source = %q{ +#user@.admin Daniel +} + assert_html '
Daniel
', source, shortcut: {'#' => {attr: 'id'}, '.' => {attr: 'class'}, '@' => {attr: 'role'}, '@.' => {attr: ['class', 'role']}} + end + + def test_render_with_custom_shortcut_and_additional_attrs + source = %q{ +^items + == "[{'title':'item0'},{'title':'item1'},{'title':'item2'},{'title':'item3'},{'title':'item4'}]" +} + assert_html '', + source, shortcut: {'^' => {tag: 'script', attr: 'data-binding', additional_attrs: { type: "application/json" }}} + end + + def test_render_with_text_block + source = %q{ +p + | + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +} + + assert_html '

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

', source + end + + def test_render_with_text_block_with_subsequent_markup + source = %q{ +p + | + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +p Some more markup +} + + assert_html '

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Some more markup

', source + end + + def test_render_with_text_block_with_trailing_whitespace + source = %q{ +' this is + a link to +a href="link" page +} + + assert_html "this is\na link to page", source + end + + def test_nested_text + source = %q{ +p + | + This is line one. + This is line two. + This is line three. + This is line four. +p This is a new paragraph. +} + + assert_html "

This is line one.\n This is line two.\n This is line three.\n This is line four.

This is a new paragraph.

", source + end + + def test_nested_text_with_nested_html_one_same_line + source = %q{ +p + | This is line one. + This is line two. + span.bold This is a bold line in the paragraph. + | This is more content. +} + + assert_html "

This is line one.\n This is line two.This is a bold line in the paragraph. This is more content.

", source + end + + def test_nested_text_with_nested_html_one_same_line2 + source = %q{ +p + |This is line one. + This is line two. + span.bold This is a bold line in the paragraph. + | This is more content. +} + + assert_html "

This is line one.\n This is line two.This is a bold line in the paragraph. This is more content.

", source + end + + def test_nested_text_with_nested_html + source = %q{ +p + | + This is line one. + This is line two. + This is line three. + This is line four. + span.bold This is a bold line in the paragraph. + | This is more content. +} + + assert_html "

This is line one.\n This is line two.\n This is line three.\n This is line four.This is a bold line in the paragraph. This is more content.

", source + end + + def test_simple_paragraph_with_padding + source = %q{ +p There will be 3 spaces in front of this line. +} + + assert_html '

There will be 3 spaces in front of this line.

', source + end + + def test_paragraph_with_nested_text + source = %q{ +p This is line one. + This is line two. +} + + assert_html "

This is line one.\n This is line two.

", source + end + + def test_paragraph_with_padded_nested_text + source = %q{ +p This is line one. + This is line two. +} + + assert_html "

This is line one.\n This is line two.

", source + end + + def test_paragraph_with_attributes_and_nested_text + source = %q{ +p#test class="paragraph" This is line one. + This is line two. +} + + assert_html "

This is line one.\nThis is line two.

", source + end + + def test_relaxed_text_indentation + source = %q{ +p + | text block + text + line3 +} + + assert_html "

text block\ntext\n line3

", source + end + + def test_output_code_with_leading_spaces + source = %q{ +p= hello_world +p = hello_world +p = hello_world +} + + assert_html '

Hello World from @env

Hello World from @env

Hello World from @env

', source + end + + def test_single_quoted_attributes + source = %q{ +p class='underscored_class_name' = output_number +} + + assert_html '

1337

', source + end + + def test_nonstandard_attributes + source = %q{ +p id="dashed-id" class="underscored_class_name" = output_number +} + + assert_html '

1337

', source + end + + def test_nonstandard_shortcut_attributes + source = %q{ +p#dashed-id.underscored_class_name = output_number +} + + assert_html '

1337

', source + end + + def test_dashed_attributes + source = %q{ +p data-info="Illudium Q-36" = output_number +} + + assert_html '

1337

', source + end + + def test_dashed_attributes_with_shortcuts + source = %q{ +p#marvin.martian data-info="Illudium Q-36" = output_number +} + + assert_html '

1337

', source + end + + def test_parens_around_attributes + source = %q{ +p(id="marvin" class="martian" data-info="Illudium Q-36") = output_number +} + + assert_html '

1337

', source + end + + def test_square_brackets_around_attributes + source = %q{ +p[id="marvin" class="martian" data-info="Illudium Q-36"] = output_number +} + + assert_html '

1337

', source + end + + def test_parens_around_attributes_with_equal_sign_snug_to_right_paren + source = %q{ +p(id="marvin" class="martian" data-info="Illudium Q-36")= output_number +} + + assert_html '

1337

', source + end + + def test_default_attr_delims_option + source = %q{ +p= output_number +} + Slim::Parser.options[:attr_list_delims].each do |k,v| + str = source.sub('<',k).sub('>',v) + assert_html '

1337

', str + end + end + + def test_custom_attr_delims_option + source = %q{ +p { foo="bar" } +} + + assert_html '

', source + assert_html '

', source, attr_list_delims: {'{' => '}'} + assert_html '

{ foo="bar" }

', source, attr_list_delims: {'(' => ')', '[' => ']'} + end + + def test_closed_tag + source = %q{ +closed/ +} + + assert_html '', source, format: :xhtml + end + + def test_custom_attr_list_delims_option + source = %q{ +p { foo="bar" x=(1+1) } +p < x=(1+1) > Hello +} + + assert_html '

< x=(1+1) > Hello

', source + assert_html '

< x=(1+1) > Hello

', source, attr_list_delims: {'{' => '}'} + assert_html '

{ foo="bar" x=(1+1) }

Hello

', source, attr_list_delims: {'<' => '>'}, code_attr_delims: { '(' => ')' } + end + + def test_attributs_with_parens_and_spaces + source = %q{label{ for='filter' }= hello_world} + assert_html '', source + end + + def test_attributs_with_parens_and_spaces2 + source = %q{label{ for='filter' } = hello_world} + assert_html '', source + end + + def test_attributs_with_multiple_spaces + source = %q{label for='filter' class="test" = hello_world} + assert_html '', source + end + + def test_closed_tag_with_attributes + source = %q{ +closed id="test" / +} + + assert_html '', source, format: :xhtml + end + + def test_closed_tag_with_attributes_and_parens + source = %q{ +closed(id="test")/ +} + + assert_html '', source, format: :xhtml + end + + def test_render_with_html_comments + source = %q{ +p Hello +/! This is a comment + + Another comment +p World +} + + assert_html "

Hello

World

", source + end + + def test_render_with_html_conditional_and_tag + source = %q{ +/[ if IE ] + p Get a better browser. +} + + assert_html "", source + end + + def test_render_with_html_conditional_and_method_output + source = %q{ +/[ if IE ] + = message 'hello' +} + + assert_html "", source + end + + def test_multiline_attributes_with_method + source = %q{ +p = output_number +} + Slim::Parser.options[:attr_list_delims].each do |k,v| + str = source.sub('<',k).sub('>',v) + assert_html '

1337

', str + end + end + + def test_multiline_attributes_with_text_on_same_line + source = %q{ +p THE space modulator +} + Slim::Parser.options[:attr_list_delims].each do |k,v| + str = source.sub('<',k).sub('>',v) + assert_html '

THE space modulator

', str + end + end + + def test_multiline_attributes_with_nested_text + source = %q{ +p + | THE space modulator +} + Slim::Parser.options[:attr_list_delims].each do |k,v| + str = source.sub('<',k).sub('>',v) + assert_html '

THE space modulator

', str + end + end + + def test_multiline_attributes_with_dynamic_attr + source = %q{ +p + | THE space modulator +} + Slim::Parser.options[:attr_list_delims].each do |k,v| + str = source.sub('<',k).sub('>',v) + assert_html '

THE space modulator

', str + end + end + + def test_multiline_attributes_with_nested_tag + source = %q{ +p + span.emphasis THE + | space modulator +} + Slim::Parser.options[:attr_list_delims].each do |k,v| + str = source.sub('<',k).sub('>',v) + assert_html '

THE space modulator

', str + end + end + + def test_multiline_attributes_with_nested_text_and_extra_indentation + source = %q{ +li< id="myid" + class="myclass" +data-info="myinfo"> + a href="link" My Link +} + Slim::Parser.options[:attr_list_delims].each do |k,v| + str = source.sub('<',k).sub('>',v) + assert_html '
  • My Link
  • ', str + end + end + + def test_block_expansion_support + source = %q{ +ul + li.first: a href='a' foo + li: a href='b' bar + li.last: a href='c' baz +} + assert_html %{}, source + end + + def test_block_expansion_class_attributes + source = %q{ +.a: .b: #c d +} + assert_html %{
    d
    }, source + end + + def test_block_expansion_nesting + source = %q{ +html: body: .content + | Text +} + assert_html %{
    Text
    }, source + end + + def test_eval_attributes_once + source = %q{ +input[value=succ_x] +input[value=succ_x] +} + assert_html %{}, source + end + + def test_html_line_indicator + source = %q{ + + head + meta name="keywords" content=hello_world + - if true +

    #{hello_world}

    + span = hello_world + + } + + assert_html '

    Hello World from @env

    Hello World from @env', source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_parser_errors.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_parser_errors.rb new file mode 100644 index 0000000..2143a71 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_parser_errors.rb @@ -0,0 +1,148 @@ +require 'helper' + +class TestParserErrors < TestSlim + def test_correct_filename + source = %q{ +doctype 5 + div Invalid +} + + assert_syntax_error "Unexpected indentation\n test.slim, Line 3, Column 2\n div Invalid\n ^\n", source, file: 'test.slim' + end + + def test_unexpected_indentation + source = %q{ +doctype 5 + div Invalid +} + + assert_syntax_error "Unexpected indentation\n (__TEMPLATE__), Line 3, Column 2\n div Invalid\n ^\n", source + end + + def test_malformed_indentation + source = %q{ +p + div Valid + div Invalid +} + + assert_syntax_error "Malformed indentation\n (__TEMPLATE__), Line 4, Column 1\n div Invalid\n ^\n", source + end + + def test_malformed_indentation2 + source = %q{ + div Valid + div Invalid +} + + assert_syntax_error "Malformed indentation\n (__TEMPLATE__), Line 3, Column 1\n div Invalid\n ^\n", source + end + + def test_unknown_line_indicator + source = %q{ +p + div Valid + .valid + #valid + ?invalid +} + + assert_syntax_error "Unknown line indicator\n (__TEMPLATE__), Line 6, Column 2\n ?invalid\n ^\n", source + end + + def test_expected_closing_delimiter + source = %q{ +p + img(src="img.jpg" title={title} +} + + assert_syntax_error "Expected closing delimiter )\n (__TEMPLATE__), Line 3, Column 33\n img(src=\"img.jpg\" title={title}\n ^\n", source + end + + def test_missing_quote_unexpected_end + source = %q{ +p + img(src="img.jpg +} + + assert_syntax_error "Unexpected end of file\n (__TEMPLATE__), Line 3, Column 0\n \n ^\n", source + end + + def test_expected_closing_attribute_delimiter + source = %q{ +p + img src=[hash[1] + hash[2] +} + + assert_syntax_error "Expected closing delimiter ]\n (__TEMPLATE__), Line 3, Column 28\n img src=[hash[1] + hash[2]\n ^\n", source + end + + def test_invalid_empty_attribute + source = %q{ +p + img{src= } +} + + assert_syntax_error "Invalid empty attribute\n (__TEMPLATE__), Line 3, Column 11\n img{src= }\n ^\n", source + end + + def test_invalid_empty_attribute2 + source = %q{ +p + img{src=} +} + + assert_syntax_error "Invalid empty attribute\n (__TEMPLATE__), Line 3, Column 10\n img{src=}\n ^\n", source + end + + def test_invalid_empty_attribute3 + source = %q{ +p + img src= +} + + assert_syntax_error "Invalid empty attribute\n (__TEMPLATE__), Line 3, Column 10\n img src=\n ^\n", source + end + + def test_missing_tag_in_block_expansion + source = %{ +html: body: +} + + assert_syntax_error "Expected tag\n (__TEMPLATE__), Line 2, Column 11\n html: body:\n ^\n", source + end + + def test_invalid_tag_in_block_expansion + source = %{ +html: body: /comment +} + assert_syntax_error "Expected tag\n (__TEMPLATE__), Line 2, Column 12\n html: body: /comment\n ^\n", source + + source = %{ +html: body:/comment +} + assert_syntax_error "Expected tag\n (__TEMPLATE__), Line 2, Column 11\n html: body:/comment\n ^\n", source + end + + def test_unexpected_text_after_closed + source = %{ +img / text +} + + assert_syntax_error "Unexpected text after closed tag\n (__TEMPLATE__), Line 2, Column 6\n img / text\n ^\n", source + end + + def test_illegal_shortcuts + source = %{ +.#test +} + + assert_syntax_error "Illegal shortcut\n (__TEMPLATE__), Line 2, Column 0\n .#test\n ^\n", source + + source = %{ +div.#test +} + + assert_syntax_error "Illegal shortcut\n (__TEMPLATE__), Line 2, Column 3\n div.#test\n ^\n", source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_pretty.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_pretty.rb new file mode 100644 index 0000000..c167d8e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_pretty.rb @@ -0,0 +1,166 @@ +require 'helper' + +class TestSlimPretty < TestSlim + def setup + super + Slim::Engine.set_options pretty: true + end + + def teardown + Slim::Engine.set_options pretty: false + end + + def test_pretty + source = %q{ +doctype 5 +html + head + title Hello World! + /! Meta tags + with long explanatory + multiline comment + meta name="description" content="template language" + /! Stylesheets + link href="style.css" media="screen" rel="stylesheet" type="text/css" + link href="colors.css" media="screen" rel="stylesheet" type="text/css" + /! Javascripts + script src="jquery.js" + script src="jquery.ui.js" + /[if lt IE 9] + script src="old-ie1.js" + script src="old-ie2.js" + sass: + body + background-color: red + body + #container + p Hello + World! + p= "dynamic text with\nnewline" +} + + result = %q{ + + + Hello World! + + + + + + + + + + + +
    +

    + Hello + World! +

    +

    + dynamic text with + newline +

    +
    + +} + + assert_html result, source + end + + def test_partials + body = %q{body + == render content} + + content = %q{div + | content} + + source = %q{html + == render body, scope: self, locals: { content: content }} + + result = %q{ + +
    + content +
    + +} + + assert_html result, source, scope: self, locals: {body: body, content: content } + end + + def test_correct_line_number + source = %q{ +html + head + body + p Slim + = '' + = '' + = '' + = unknown_ruby_method +} + + assert_ruby_error NameError,"(__TEMPLATE__):9", source + end + + def test_unindenting + source = %q{ +span before +span = " middle " +span after +} + + result = %q{before middle after} + + assert_html result, source + + source = %q{ +html + body == "
    \n link\n
    " +} + + result = %q{ + +
    + link +
    + +} + assert_html result, source + end + + def test_helper_unindent + source = %q{ += define_macro :content + div + a link +html + body + == call_macro :content +} + + result = %q{ + + + +
    + link +
    + +} + + assert_html result, source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_ruby_errors.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_ruby_errors.rb new file mode 100644 index 0000000..0946c71 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_ruby_errors.rb @@ -0,0 +1,181 @@ +require 'helper' + +class TestSlimRubyErrors < TestSlim + def test_multline_attribute + source = %q{ +p(data-1=1 +data2-=1) + p + = unknown_ruby_method +} + + assert_ruby_error NameError, "test.slim:5", source, file: 'test.slim' + end + + def test_broken_output_line + source = %q{ +p = hello_world + \ + hello_world + \ + unknown_ruby_method +} + + assert_ruby_error NameError, "test.slim:4", source, file: 'test.slim' + end + + def test_broken_output_line2 + source = %q{ +p = hello_world + \ + hello_world +p Hello += unknown_ruby_method +} + + assert_ruby_error NameError,"(__TEMPLATE__):5", source + end + + def test_output_block + source = %q{ +p = hello_world "Hello Ruby" do + = unknown_ruby_method +} + + assert_ruby_error NameError,"(__TEMPLATE__):3", source + end + + def test_output_block2 + source = %q{ +p = hello_world "Hello Ruby" do + = "Hello from block" +p Hello += unknown_ruby_method +} + + assert_ruby_error NameError, "(__TEMPLATE__):5", source + end + + def test_text_block + source = %q{ +p Text line 1 + Text line 2 += unknown_ruby_method +} + + assert_ruby_error NameError,"(__TEMPLATE__):4", source + end + + def test_text_block2 + source = %q{ +| + Text line 1 + Text line 2 += unknown_ruby_method +} + + assert_ruby_error NameError,"(__TEMPLATE__):5", source + end + + def test_comment + source = %q{ +/ Comment line 1 + Comment line 2 += unknown_ruby_method +} + + assert_ruby_error NameError,"(__TEMPLATE__):4", source + end + + def test_embedded_ruby1 + source = %q{ +ruby: + a = 1 + b = 2 += a + b += unknown_ruby_method +} + + assert_ruby_error NameError,"(__TEMPLATE__):7", source + end + + def test_embedded_ruby2 + source = %q{ +ruby: + a = 1 + unknown_ruby_method +} + + assert_ruby_error NameError,"(__TEMPLATE__):4", source + end + + def test_embedded_markdown + source = %q{ +markdown: + #Header + Hello from #{"Markdown!"} + "Second Line!" += unknown_ruby_method +} + + assert_ruby_error NameError,"(__TEMPLATE__):6", source + end + + def test_embedded_javascript + source = %q{ +javascript: + alert(); + alert(); += unknown_ruby_method +} + + assert_ruby_error NameError,"(__TEMPLATE__):5", source + end + + def test_invalid_nested_code + source = %q{ +p + - test = 123 + = "Hello from within a block! " +} + assert_ruby_syntax_error "(__TEMPLATE__):3", source + end + + def test_invalid_nested_output + source = %q{ +p + = "Hello Ruby!" + = "Hello from within a block! " +} + assert_ruby_syntax_error "(__TEMPLATE__):3", source + end + + def test_explicit_end + source = %q{ +div + - if show_first? + p The first paragraph + - end +} + + assert_runtime_error 'Explicit end statements are forbidden', source + end + + def test_multiple_id_attribute + source = %{ +#alpha id="beta" Test it +} + assert_runtime_error 'Multiple id attributes specified', source + end + + def test_splat_multiple_id_attribute + source = %{ +#alpha *{id:"beta"} Test it +} + assert_runtime_error 'Multiple id attributes specified', source + end + +# def test_invalid_option +# render('', foobar: 42) +# raise Exception, 'ArgumentError expected' +# rescue ArgumentError => ex +# assert_equal 'Option :foobar is not supported by Slim::Engine', ex.message +# end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_slim_template.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_slim_template.rb new file mode 100644 index 0000000..7d3adab --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_slim_template.rb @@ -0,0 +1,78 @@ +require 'helper' + +class ::MockError < NameError +end + +class TestSlimTemplate < TestSlim + def test_default_mime_type + assert_equal 'text/html', Slim::Template.default_mime_type + end + + def test_registered_extension + assert_equal Slim::Template, Tilt['test.slim'] + end + + def test_preparing_and_evaluating + template = Slim::Template.new { |t| "p Hello World!\n" } + assert_equal "

    Hello World!

    ", template.render + end + + def test_evaluating_in_an_object_scope + template = Slim::Template.new { "p = 'Hey ' + @name + '!'\n" } + scope = Object.new + scope.instance_variable_set :@name, 'Joe' + assert_equal "

    Hey Joe!

    ", template.render(scope) + end + + def test_passing_a_block_for_yield + template = Slim::Template.new { "p = 'Hey ' + yield + '!'\n" } + assert_equal "

    Hey Joe!

    ", template.render { 'Joe' } + end + + def test_backtrace_file_and_line_reporting_without_locals + data = File.read(__FILE__).split("\n__END__\n").last + fail unless data[0] == ?h + template = Slim::Template.new('test.slim', 10) { data } + begin + template.render + fail 'should have raised an exception' + rescue => ex + assert_kind_of NameError, ex + assert_backtrace(ex, 'test.slim:12') + end + end + + def test_backtrace_file_and_line_reporting_with_locals + data = File.read(__FILE__).split("\n__END__\n").last + fail unless data[0] == ?h + template = Slim::Template.new('test.slim') { data } + begin + template.render(Object.new, name: 'Joe', foo: 'bar') + fail 'should have raised an exception' + rescue => ex + assert_kind_of MockError, ex + assert_backtrace(ex, 'test.slim:5') + end + end + + def test_compiling_template_source_to_a_method + template = Slim::Template.new { |t| "Hello World!" } + template.render + method = template.send(:compiled_method, []) + assert_kind_of UnboundMethod, method + end + + def test_passing_locals + template = Slim::Template.new { "p = 'Hey ' + name + '!'\n" } + assert_equal "

    Hey Joe!

    ", template.render(Object.new, name: 'Joe') + end +end + +__END__ +html + body + h1 = "Hey #{name}" + + = raise MockError + + p we never get here diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_splat_prefix_option.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_splat_prefix_option.rb new file mode 100644 index 0000000..2e5f650 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_splat_prefix_option.rb @@ -0,0 +1,155 @@ +require 'helper' + +class TestSplatPrefixOption < TestSlim + + def prefixes + ['*','**','*!','*%','*^','*$'] + end + + def options(prefix) + { splat_prefix: prefix } + end + + def test_splat_without_content + prefixes.each do |prefix| + source = %Q{ + #{prefix}hash + p#{prefix}hash + } + + assert_html '

    ', source, options(prefix) + end + end + + def test_shortcut_splat + prefixes.each do |prefix| + source = %Q{ +#{prefix}hash This is my title +} + + assert_html '
    This is my title
    ', source, options(prefix) + end + end + + def test_splat + prefixes.each do |prefix| + source = %Q{ +h1 #{prefix}hash class=[] This is my title +} + + assert_html '

    This is my title

    ', source, options(prefix) + end + end + + def test_closed_splat + prefixes.each do |prefix| + source = %Q{ +#{prefix}hash / +} + + assert_html '
    ', source, options(prefix) + end + end + + def test_splat_tag_name + prefixes.each do |prefix| + source = %Q{ +#{prefix}{tag: 'h1', id: 'title'} This is my title +} + + assert_html '

    This is my title

    ', source, options(prefix) + end + end + + + def test_splat_empty_tag_name + prefixes.each do |prefix| + source = %Q{ +#{prefix}{tag: '', id: 'test'} This is my title +} + + assert_html '
    This is my title
    ', source, options(prefix) + end + end + + def test_closed_splat_tag + prefixes.each do |prefix| + source = %Q{ +#{prefix}hash / +} + + assert_html '
    ', source, options(prefix) + end + end + + def test_splat_with_id_shortcut + prefixes.each do |prefix| + source = %Q{ +#myid#{prefix}hash This is my title +} + + assert_html '
    This is my title
    ', source, options(prefix) + end + end + + def test_splat_with_class_shortcut + prefixes.each do |prefix| + source = %Q{ +.myclass#{prefix}hash This is my title +} + + assert_html '
    This is my title
    ', source, options(prefix) + end + end + + def test_splat_with_id_and_class_shortcuts + prefixes.each do |prefix| + source = %Q{ +#myid.myclass#{prefix}hash This is my title +} + + assert_html '
    This is my title
    ', source, options(prefix) + end + end + + def test_splat_with_class_merging + prefixes.each do |prefix| + source = %Q{ +#myid.myclass #{prefix}{class: [:secondclass, %w(x y z)]} #{prefix}hash This is my title +} + + assert_html '
    This is my title
    ', source, options(prefix) + end + end + + def test_splat_with_boolean_attribute + prefixes.each do |prefix| + source = %Q{ +#{prefix}{disabled: true, empty1: false, nonempty: '', empty2: nil} This is my title +} + + assert_html '
    This is my title
    ', source, options(prefix) + end + end + + def test_splat_merging_with_arrays + prefixes.each do |prefix| + source = %Q{ +#{prefix}{a: 1, b: 2} #{prefix}[[:c, 3], [:d, 4]] #{prefix}[[:e, 5], [:f, 6]] This is my title +} + + assert_html '
    This is my title
    ', source, options(prefix) + end + end + + def test_splat_with_other_attributes + prefixes.each do |prefix| + source = %Q{ +h1 data-id="123" #{prefix}hash This is my title +} + + assert_html '

    This is my title

    ', source, options(prefix) + end + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_tabs.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_tabs.rb new file mode 100644 index 0000000..965dabe --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_tabs.rb @@ -0,0 +1,169 @@ +require 'helper' + +class TestSlimTabs < TestSlim + + def teardown + Slim::Engine.set_options tabsize: 4 + end + + def test_single_tab1_expansion + + Slim::Engine.set_options tabsize: 1 + + source = %Q{ +| +\t0 + \t1 + \t2 + \t3 + \t4 + \t5 + \t6 + \t7 + \t8 +} + + result = %q{ +0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 +}.strip + + assert_html result, source + end + + def test_single_tab4_expansion + + Slim::Engine.set_options tabsize: 4 + + source = %Q{ +| +\t0 + \t1 + \t2 + \t3 + \t4 + \t5 + \t6 + \t7 + \t8 +} + + result = %q{ +0 +1 +2 +3 + 4 + 5 + 6 + 7 + 8 +}.strip + + assert_html result, source + end + + def test_multi_tab1_expansion + + Slim::Engine.set_options tabsize: 1 + + source = %Q{ +| +\t0 + \t\t1 + \t \t2 + \t \t3 + \t \t4 + \t\t1 + \t \t2 + \t \t3 + \t \t4 + \t\t1 + \t \t2 + \t \t3 + \t \t4 + \t\t1 + \t \t2 + \t \t3 + \t \t4 +} + + result = %q{ +0 + 1 + 2 + 3 + 4 + 1 + 2 + 3 + 4 + 1 + 2 + 3 + 4 + 1 + 2 + 3 + 4 +}.strip + + assert_html result, source + end + + def test_multi_tab4_expansion + + Slim::Engine.set_options tabsize: 4 + + source = %Q{ +| +\t0 + \t\t1 + \t \t2 + \t \t3 + \t \t4 + \t\t1 + \t \t2 + \t \t3 + \t \t4 + \t\t1 + \t \t2 + \t \t3 + \t \t4 + \t\t1 + \t \t2 + \t \t3 + \t \t4 +} + + result = %q{ +0 + 1 + 2 + 3 + 4 + 1 + 2 + 3 + 4 + 1 + 2 + 3 + 4 + 1 + 2 + 3 + 4 +}.strip + + assert_html result, source + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_text_interpolation.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_text_interpolation.rb new file mode 100644 index 0000000..564e6c1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_text_interpolation.rb @@ -0,0 +1,79 @@ +require 'helper' + +class TestSlimTextInterpolation < TestSlim + def test_interpolation_in_attribute + source = %q{ +p id="a#{id_helper}b" = hello_world +} + + assert_html '

    Hello World from @env

    ', source + end + + def test_nested_interpolation_in_attribute + source = %q{ +p id="#{"abc#{1+1}" + "("}" = hello_world +} + + assert_html '

    Hello World from @env

    ', source + end + + def test_interpolation_in_text + source = %q{ +p + | #{hello_world} with "quotes" +p + | + A message from the compiler: #{hello_world} +} + + assert_html '

    Hello World from @env with "quotes"

    A message from the compiler: Hello World from @env

    ', source + end + + def test_interpolation_in_tag + source = %q{ +p #{hello_world} +} + + assert_html '

    Hello World from @env

    ', source + end + + def test_escape_interpolation + source = %q{ +p \\#{hello_world} +p text1 \\#{hello_world} text2 +} + + assert_html '

    #{hello_world}

    text1 #{hello_world} text2

    ', source + end + + def test_complex_interpolation + source = %q{ +p Message: #{message('hello', "user #{output_number}")} +} + + assert_html '

    Message: hello user 1337

    ', source + end + + def test_interpolation_with_escaping + source = %q{ +| #{evil_method} +} + + assert_html '<script>do_something_evil();</script>', source + end + + def test_interpolation_without_escaping + source = %q{ +| #{{evil_method}} +} + + assert_html '', source + end + + def test_interpolation_with_escaping_and_delimiter + source = %q{ +| #{(evil_method)} +} + assert_html '<script>do_something_evil();</script>', source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_thread_options.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_thread_options.rb new file mode 100644 index 0000000..c6e7a68 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_thread_options.rb @@ -0,0 +1,18 @@ +require 'helper' + +class TestSlimThreadOptions < TestSlim + def test_thread_options + source = %q{p.test} + + assert_html '

    ', source + assert_html "

    ", source, attr_quote: "'" + + Slim::Engine.with_options(attr_quote: "'") do + assert_html "

    ", source + assert_html '

    ', source, attr_quote: '"' + end + + assert_html '

    ', source + assert_html "

    ", source, attr_quote: "'" + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_unicode.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_unicode.rb new file mode 100644 index 0000000..e5f420e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/core/test_unicode.rb @@ -0,0 +1,15 @@ +require 'helper' + +class TestSlimUnicode < TestSlim + def test_unicode_tags + source = "Статья года" + result = "<Статья>года" + assert_html result, source + end + + def test_unicode_attrs + source = "Статья года=123 content" + result = "<Статья года=\"123\">content" + assert_html result, source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/recursive.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/recursive.slim new file mode 100644 index 0000000..a625563 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/recursive.slim @@ -0,0 +1 @@ +| rec \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/slimfile.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/slimfile.slim new file mode 100644 index 0000000..563f0e2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/slimfile.slim @@ -0,0 +1,3 @@ +| slim1 +include recursive +| slim2 \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/subdir/test.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/subdir/test.slim new file mode 100644 index 0000000..cfb527b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/subdir/test.slim @@ -0,0 +1 @@ +| subdir \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/textfile b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/textfile new file mode 100644 index 0000000..c7ad539 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/files/textfile @@ -0,0 +1 @@ +1+2=#{1+2} \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/test_include.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/test_include.rb new file mode 100644 index 0000000..ac14283 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/include/test_include.rb @@ -0,0 +1,24 @@ +require 'helper' +require 'slim/include' + +class TestSlimInclude < TestSlim + def test_include + source = %q{ +br/ +a: include slimfile +b: include textfile +c: include slimfile.slim +d: include subdir/test +} + assert_html '
    slim1recslim21+2=3slim1recslim2subdir', source, include_dirs: [File.expand_path('files', File.dirname(__FILE__))] + end + + def test_include_with_newline + source = %q{ +a: include slimfile + +.content +} + assert_html 'slim1recslim2
    ', source, include_dirs: [File.expand_path('files', File.dirname(__FILE__))] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/literate/TESTS.md b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/literate/TESTS.md new file mode 100644 index 0000000..cab99ab --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/literate/TESTS.md @@ -0,0 +1,1273 @@ +# Slim test suite + +You can run this testsuite with `rake test:literate`. + +We use pretty mode in the test suite to make the output more readable. Pretty mode +is enabled by setting the option + +~~~ options +:pretty => true +~~~ + +## Line indicators + +In this section we test all line indicators. + +### Text `|` + +A text blocks starts with the `|` as line indicator. + +~~~ slim +| Text block +~~~ + +renders as + +~~~ html +Text block +~~~ + +Multiple lines can be indented beneath the first text line. + +~~~ slim +| Text + block + + with + + multiple + lines +~~~ + +renders as + +~~~ html + Text + block + + with + + multiple + lines +~~~ + +The first line of a text block determines the indentation. + +~~~ slim +| + + Text + block + + with + + multiple + lines +~~~ + +renders as + +~~~ html +Text + block + + with + + multiple +lines +~~~ + +You can nest text blocks beneath tags. + +~~~ slim +body + | Text +~~~ + +renders as + +~~~ html + + Text + +~~~ + +You can embed html code in the text which is not escaped. + +~~~ slim +| slim-lang.com +~~~ + +renders as + +~~~ html +slim-lang.com +~~~ + +### Text with trailing white space `'` + +A text blocks with trailing white space starts with the `'` as line indicator. + +~~~ slim +' Text block +~~~ + +renders as + +~~~ html +Text block +~~~ + +This is especially useful if you use tags behind a text block. + +~~~ slim +' Link to +a href="http://slim-lang.com" slim-lang.com +~~~ + +renders as + +~~~ html +Link to slim-lang.com +~~~ + +Multiple lines can be indented beneath the first text line. + +~~~ slim +' Text + block + + with + + multiple + lines +~~~ + +renders as + +~~~ html + Text + block + + with + + multiple + lines +~~~ + +The first line of a text block determines the indentation. + +~~~ slim +' + + Text + block + + with + + multiple + lines +~~~ + +renders as + +~~~ html +Text + block + + with + + multiple +lines +~~~ + +### Inline HTML `<` + +HTML can be written directly. + +~~~ slim +slim-lang.com +~~~ + +renders as + +~~~ html +slim-lang.com +~~~ + +HTML tags allow nested blocks inside. + +~~~ slim + + + title Example + + body + - if true + | yes + - else + | no + +~~~ + +renders as + +~~~ html +Example + + yes + + +~~~ + +### Control code `-` + +The dash `-` denotes arbitrary control code. + +~~~ slim +- greeting = 'Hello, World!' +- if false + | Not true +- else + = greeting +~~~ + +renders as + +~~~ html +Hello, World! +~~~ + +Complex code can be broken with backslash `\`. + +~~~ slim +- greeting = 'Hello, '+\ + \ + 'World!' +- if false + | Not true +- else + = greeting +~~~ + +renders as + +~~~ html +Hello, World! +~~~ + +You can also write loops like this + +~~~ slim +- items = [{name: 'table', price: 10}, {name: 'chair', price: 5}] +table#items + - for item in items do + tr + td.name = item[:name] + td.price = item[:price] +~~~ + +which renders as + +~~~ html + + + + + + + + + +
    + table + + 10 +
    + chair + + 5 +
    +~~~ + +The `do` keyword can be omitted. + +~~~ slim +- items = [{name: 'table', price: 10}, {name: 'chair', price: 5}] +table#items + - for item in items + tr + td.name = item[:name] + td.price = item[:price] +~~~ + +which renders as + +~~~ html + + + + + + + + + +
    + table + + 10 +
    + chair + + 5 +
    +~~~ + +### Output `=` + +The equal sign `=` produces dynamic output. + +~~~ slim += 7*7 +~~~ + +renders as + +~~~ html +49 +~~~ + +Dynamic output is escaped by default. + +~~~ slim += '' +~~~ + +renders as + +~~~ html +<script>evil();</script> +~~~ + +Long code lines can be broken with `\`. + +~~~ slim += (0..10).map do |i|\ + 2**i \ +end.join(', ') +~~~ + +renders as + +~~~ html +1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 +~~~ + +You don't need the explicit `\` if the line ends with a comma `,`. + +~~~ slim +ruby: + def self.test(*args) + args.join('-') + end += test('arg1', +'arg2', +'arg3') +~~~ + +renders as + +~~~ html +arg1-arg2-arg3 +~~~ + +You can also disable HTML escaping globally by setting the option + +~~~ options +:disable_escape => true +~~~ + +~~~ slim += '' +~~~ + +renders as + +~~~ html + +~~~ + +The equal sign with modifier `=>` produces dynamic output with a trailing white space. + +~~~ slim +=> 7*7 +~~~ + +renders as + +~~~ html +49 +~~~ + +~~~ slim +=< 7*7 +~~~ + +renders as + +~~~ html + 49 +~~~ + +The equal sign with modifier `=<` produces dynamic output with a leading white space. + +~~~ slim +=< 7*7 +~~~ + +renders as + +~~~ html + 49 +~~~ + +The equal sign with modifiers `=<>` produces dynamic output with a leading and trailing white space. + +~~~ slim +=<> 7*7 +~~~ + +renders as + +~~~ html + 49 +~~~ + +### Output without HTML escaping `==` + +The double equal sign `==` produces dynamic output without HTML escaping. + +~~~ slim +== '' +~~~ + +renders as + +~~~ html + +~~~ + +The option option + +~~~ options +:disable_escape => true +~~~ + +doesn't affect the output of `==`. + +~~~ slim +== '' +~~~ + +renders as + +~~~ html + +~~~ + +The double equal sign with modifier `==>` produces dynamic output without HTML escaping and trailing white space. + +~~~ slim +==> '' +~~~ + +renders as + +~~~ html + +~~~ + +The option option + +~~~ options +:disable_escape => true +~~~ + +doesn't affect the output of `==`. + +~~~ slim +==> '' +~~~ + +renders as + +~~~ html + +~~~ + +### Code comment `/` + +Code comments begin with `/` and produce no output. + +~~~ slim +/ Comment +body + / Another comment + with + + multiple lines + p Hello! +~~~ + +renders as + +~~~ html + +

    + Hello! +

    + +~~~ + +### HTML comment `/!` + +Code comments begin with `/!`. + +~~~ slim +/! Comment +body + /! Another comment + with multiple lines + p Hello! + /! + First line determines indentation + + of the comment +~~~ + +renders as + +~~~ html + + + +

    + Hello! +

    + + +~~~ + +### IE conditional comment `/[...]` + +~~~ slim +/[if IE] + p Get a better browser. +~~~ + +renders as + +~~~ html + +~~~ + +## HTML tags + +### Doctype tags + +The doctype tag is a special tag which can be used to generate the complex doctypes in a very simple way. + +You can output the XML version using the doctype tag. + +~~~ slim +doctype xml +doctype xml ISO-8859-1 +~~~ + +renders as + +~~~ html + + +~~~ + +In XHTML mode the following doctypes are supported: + +~~~ slim +doctype html +doctype 5 +doctype 1.1 +doctype strict +doctype frameset +doctype mobile +doctype basic +doctype transitional +~~~ + +renders as + +~~~ html + + + + + + + + +~~~ + +If we activate HTML mode with the option + +~~~ options +:format => :html +~~~ + +the following doctypes are supported: + +~~~ slim +doctype html +doctype 5 +doctype strict +doctype frameset +doctype transitional +~~~ + +renders as + +~~~ html + + + + + +~~~ + +### Closed tags + +You can close tags explicitly by appending a trailing `/`. + +~~~ slim +div id="not-closed" +.closed/ +#closed/ +div id="closed"/ +~~~ + +renders as + +~~~ html +
    +
    +
    +
    +~~~ + +Note, that this is usually not necessary since the standard html tags (img, br, ...) are closed automatically. + +~~~ slim +img src="image.png" +~~~ + +renders as + +~~~ html + +~~~ + +### Trailing and leading whitespace + +You can force a trailing whitespace behind a tag by adding `>`. + +~~~ slim +a#closed> class="test" / +a#closed> class="test"/ +a> href='url1' Link1 +a< href='url1' Link1 +~~~ + +renders as + +~~~ html + Link1 Link1 +~~~ + +If you combine > and => only one trailing whitespace is added. + +~~~ slim +a> => 'Text1' +a => 'Text2' +a> = 'Text3' +a>= 'Text4' +a=> 'Text5' +a<= 'Text6' +a=< 'Text7' +~~~ + +renders as + +~~~ html +Text1 Text2 Text3 Text4 Text5 Text6 Text7 +~~~ + +You can force a leading whitespace before a tag by adding `<`. + +~~~ slim +a#closed< class="test" / +a#closed< class="test"/ +a< href='url1' Link1 +a< href='url2' Link2 +~~~ + +~~~ html + Link1 Link2 +~~~ + +You can also combine both. + +~~~ slim +a#closed<> class="test" / +a#closed>< class="test"/ +a<> href='url1' Link1 +a<> href='url2' Link2 +~~~ + +~~~ html + Link1 Link2 +~~~ + +### Inline tags + +Sometimes you may want to be a little more compact and inline the tags. + +~~~ slim +ul + li.first: a href="/first" First + li: a href="/second" Second +~~~ + +renders as + +~~~ html + +~~~ + +For readability, don't forget you can wrap the attributes. + +~~~ slim +ul + li.first: a(href="/first") First + li: a(href="/second") Second +~~~ + +renders as + +~~~ html + +~~~ + +### Text content + +### Dynamic content `=` + +### Attributes + +#### Attribute wrapper + +If a delimiter makes the syntax more readable for you, you can use the characters `{...}`, `(...)`, `[...]` to wrap the attributes. + +~~~ slim +li + a(href="http://slim-lang.com" class="important") Link +li + a[href="http://slim-lang.com" class="important"] Link +li + a{href="http://slim-lang.com" class="important"} Link +~~~ + +renders as + +~~~ html +
  • + Link +
  • +
  • + Link +
  • +
  • + Link +
  • +~~~ + +If you wrap the attributes, you can spread them across multiple lines: + +~~~ slim +a(href="http://slim-lang.com" + + class="important") Link +~~~ + +renders as + +~~~ html +Link +~~~ + +~~~ slim +dl( + itemprop='address' + itemscope + itemtype='http://schema.org/PostalAddress' +) +~~~ + +renders as + +~~~ html +
    +~~~ + +You may use spaces around the wrappers and assignments: + +~~~ slim +h1 id = "logo" Logo +h2 [ id = "tagline" ] Tagline +~~~ + +renders as + +~~~ html +

    + Logo +

    +

    + Tagline +

    +~~~ + +#### Quoted attributes + +You can use single or double quotes for simple text attributes. + +~~~ slim +a href="http://slim-lang.com" title='Slim Homepage' Goto the Slim homepage +~~~ + +renders as + +~~~ html +Goto the Slim homepage +~~~ + +You can use text interpolation in the quoted attributes: + +~~~ slim +- url='slim-lang.com' +a href="http://#{url}" Goto the #{url} +a href="{"test"}" Test of quoted text in braces +~~~ + +renders as + +~~~ html +Goto the slim-lang.comTest of quoted text in braces +~~~ + +The attribute value will be escaped by default. Use == if you want to disable escaping in the attribute. + +~~~ slim +li + a href='&' Link +li + a href=="&" Link +~~~ + +renders as + +~~~ html +
  • + Link +
  • +
  • + Link +
  • +~~~ + +You can use newlines in quoted attributes + +~~~ slim +a data-title="help" data-content="extremely long help text that goes on + and one and one and then starts over...." Link +~~~ + +renders as + +~~~ html +Link +~~~ + +You can break quoted attributes with an backslash `\` + +~~~ slim +a data-title="help" data-content="extremely long help text that goes on\ + and one and one and then starts over...." Link +~~~ + +renders as + +~~~ html +Link +~~~ + +#### Ruby attributes + +Long ruby attributes can be broken with backslash `\` + +~~~ slim +a href=1+\ + 1 Link +~~~ + +renders as + +~~~ html +Link +~~~ + +You don't need the explicit `\` if the line ends with a comma `,`. + +~~~ slim +ruby: + def self.test(*args) + args.join('-') + end +a href=test('arg1', +'arg2', +'arg3') Link +~~~ + +renders as + +~~~ html +Link +~~~ + +#### Boolean attributes + +The attribute values `true`, `false` and `nil` are interpreted as booleans. +If you use the attribut wrapper you can omit the attribute assigment. + +~~~ slim +- true_value1 = "" +- true_value2 = true +input type="text" disabled=true_value1 +input type="text" disabled=true_value2 +input type="text" disabled="disabled" +input type="text" disabled=true +input(type="text" disabled) +~~~ + +renders as + +~~~ html + +~~~ + +~~~ slim +- false_value1 = false +- false_value2 = nil +input type="text" disabled=false_value1 +input type="text" disabled=false_value2 +input type="text" +input type="text" disabled=false +input type="text" disabled=nil +~~~ + +renders as + +~~~ html + +~~~ + +If html5 is activated the attributes are written as standalone. + +~~~ options +:format => :html +~~~ + +~~~ slim +- true_value1 = "" +- true_value2 = true +input type="text" disabled=true_value1 +input type="text" disabled=true_value2 +input type="text" disabled="disabled" +input type="text" disabled=true +input(type="text" disabled) +~~~ + +renders as + +~~~ html + +~~~ + +#### Attribute merging + +You can configure attributes to be merged if multiple are given (See option `:merge_attrs`). In the default configuration +this is done for class attributes with the white space as delimiter. + +~~~ slim +a.menu class="highlight" href="http://slim-lang.com/" Slim-lang.com +~~~ + +renders as + +~~~ html +Slim-lang.com +~~~ + +You can also use an `Array` as attribute value and the array elements will be merged using the delimiter. + +~~~ slim +- classes = [:alpha, :beta] +span class=["first","highlight"] class=classes First +span class=:second,:highlight class=classes Second +~~~ + +renders as + +~~~ html +FirstSecond +~~~ + +#### Splat attributes `*` + + +#### Dynamic tags `*` + +You can create completely dynamic tags using the splat attributes. Just create a method which returns a hash +with the :tag key. + +~~~ slim +ruby: + def self.a_unless_current + @page_current ? {tag: 'span'} : {tag: 'a', href: 'http://slim-lang.com/'} + end +- @page_current = true +*a_unless_current Link +- @page_current = false +*a_unless_current Link +~~~ + +renders as + +~~~ html +LinkLink +~~~ + +### Shortcuts + +#### Tag shortcuts + +We add tag shortcuts by setting the option `:shortcut`. + +~~~ options +:shortcut => {'c' => {tag: 'container'}, 'sec' => {tag:'section'}, '#' => {attr: 'id'}, '.' => {attr: 'class'} } +~~~ + +~~~ slim +sec: c.content Text +~~~ + +renders to + +~~~ html +
    + Text +
    +~~~ + +#### Attribute shortcuts + +We add `&` to create a shortcut for the input elements with type attribute by setting the option `:shortcut`. + +~~~ options +:shortcut => {'&' => {tag: 'input', attr: 'type'}, '#' => {attr: 'id'}, '.' => {attr: 'class'} } +~~~ + +~~~ slim +&text name="user" +&password name="pw" +&submit.CLASS#ID +~~~ + +renders to + +~~~ html + +~~~ + +This is stupid, but you can also use multiple character shortcuts. + +~~~ options +:shortcut => {'&' => {tag: 'input', attr: 'type'}, '#<' => {attr: 'id'}, '#>' => {attr: 'class'} } +~~~ + +~~~ slim +&text name="user" +&password name="pw" +&submit#>CLASS# +~~~ + +You can also set multiple attributes per shortcut. + +~~~ options +:shortcut => {'.' => {attr: %w(id class)} } +~~~ + +~~~ slim +.test +~~~ + +renders to + +~~~ html +
    +~~~ + +Shortcuts can also have multiple characters. + +~~~ options +:shortcut => {'.' => {attr: 'class'}, '#' => {attr: 'id'}, '.#' => {attr: %w(class id)} } +~~~ + +~~~ slim +.#test +.test +#test +~~~ + +renders to + +~~~ html +
    +
    +
    +~~~ + +#### ID shortcut and class shortcut `.` + +ID and class shortcuts can contain dashes, slashes with digits, and colons. + +~~~ slim +.-test text +#test- text +.--a#b- text +.a--test-123#--b text +.a-1/2#b-1/2 text +.ab:c-test#d:e text +~~~ + +renders as + +~~~ html +
    + text +
    +
    + text +
    +
    + text +
    +
    + text +
    +
    + text +
    +
    + text +
    +~~~ + +## Text interpolation + +Use standard Ruby interpolation. The text will be html escaped by default. + +~~~ slim +- user="John Doe " +h1 Welcome #{user}! +~~~ + +renders as + +~~~ html +

    + Welcome John Doe <john@doe.net>! +

    +~~~ + +## Pretty printing of XML + +We can enable XML mode with + +~~~ options +:format => :xml +~~~ + +~~~ slim +doctype xml +document + closed-element/ + element(boolean-attribute) + child attribute="value" + | content +~~~ + +~~~ html + + + + + + content + + + +~~~ + +## Embedded engines + +## Configuring Slim + +## Plugins diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/literate/helper.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/literate/helper.rb new file mode 100644 index 0000000..13a04ab --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/literate/helper.rb @@ -0,0 +1,15 @@ +require 'slim' +require 'slim/logic_less' +require 'slim/translator' +require 'slim/grammar' +require 'minitest/autorun' + +Slim::Engine.after Slim::Parser, Temple::Filters::Validator, grammar: Slim::Grammar +Slim::Engine.before :Pretty, Temple::Filters::Validator +Slim::Engine.set_options tr: false, logic_less: false + +class MiniTest::Spec + def render(source, options = {}, &block) + Slim::Template.new(options) { source }.render(self, &block) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/literate/run.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/literate/run.rb new file mode 100644 index 0000000..ce0aa15 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/literate/run.rb @@ -0,0 +1,92 @@ +require 'temple' + +class LiterateTest < Temple::Engine + class Parser < Temple::Parser + def call(lines) + stack = [[:multi]] + until lines.empty? + case lines.shift + when /\A(#+)\s*(.*)\Z/ + stack.pop(stack.size - $1.size) + block = [:multi] + stack.last << [:section, $2, block] + stack << block + when /\A~{3,}\s*(\w+)\s*\Z/ + lang = $1 + code = [] + until lines.empty? + case lines.shift + when /\A~{3,}\s*\Z/ + break + when /\A.*\Z/ + code << $& + end + end + stack.last << [lang.to_sym, code.join("\n")] + when /\A\s*\Z/ + when /\A\s*(.*?)\s*Z/ + stack.last << [:comment, $1] + end + end + stack.first + end + end + + class Compiler < Temple::Filter + def call(exp) + @opts, @in_testcase = {}, false + "require 'helper'\n\n#{compile(exp)}" + end + + def on_section(title, body) + old_opts = @opts.dup + raise Temple::FilterError, 'New section between slim and html block' if @in_testcase + "describe #{title.inspect} do\n #{compile(body).gsub("\n", "\n ")}\nend\n" + ensure + @opts = old_opts + end + + def on_multi(*exps) + exps.map {|exp| compile(exp) }.join("\n") + end + + def on_comment(text) + "#{@in_testcase ? ' ' : ''}# #{text}" + end + + def on_slim(code) + raise Temple::FilterError, 'Slim block must be followed by html block' if @in_testcase + @in_testcase = true + "it 'should render' do\n slim = #{code.inspect}" + end + + def on_html(code) + raise Temple::FilterError, 'Html block must be preceded by slim block' unless @in_testcase + @in_testcase = false + result = " html = #{code.inspect}\n" + if @opts.empty? + result << " render(slim).must_equal html\nend\n" + else + result << " options = #{@opts.inspect}\n render(slim, options).must_equal html\nend\n" + end + end + + def on_options(code) + raise Temple::FilterError, 'Options set inside test case' if @in_testcase + @opts.update(eval("{#{code}}")) + "# #{code.gsub("\n", "\n# ")}" + end + + def on(*exp) + raise Temple::InvalidExpression, exp + end + end + + use Parser + use Compiler + use(:Evaluator) {|code| eval(code) } +end + +Dir.glob(File.join(File.dirname(__FILE__), '*.md')) do |file| + LiterateTest.new.call(File.readlines(file)) +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/logic_less/test_logic_less.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/logic_less/test_logic_less.rb new file mode 100644 index 0000000..57de00f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/logic_less/test_logic_less.rb @@ -0,0 +1,315 @@ +require 'helper' +require 'slim/logic_less' + +class TestSlimLogicLess < TestSlim + class Scope + def initialize + @hash = { + person: [ + { name: 'Joe', age: 1, selected: true }, + { name: 'Jack', age: 2 } + ] + } + end + end + + def test_lambda + source = %q{ +p + == person + .name = name + == simple + .hello= hello + == list + li = key +} + + hash = { + hello: 'Hello!', + person: lambda do |&block| + %w(Joe Jack).map do |name| + "#{block.call(name: name)}" + end.join + end, + simple: lambda do |&block| + "
    #{block.call}
    " + end, + list: lambda do |&block| + list = [{key: 'First'}, {key: 'Second'}] + "
      #{block.call(*list)}
    " + end + } + + assert_html '

    Joe
    Jack
    Hello!
    • First
    • Second

    ', source, scope: hash + end + + def test_symbol_hash + source = %q{ +p + - person + .name = name +} + + hash = { + person: [ + { name: 'Joe', }, + { name: 'Jack', } + ] + } + + assert_html '

    Joe
    Jack

    ', source, scope: hash + end + + def test_string_access + source = %q{ +p + - person + .name = name +} + + hash = { + 'person' => [ + { 'name' => 'Joe', }, + { 'name' => 'Jack', } + ] + } + + assert_html '

    Joe
    Jack

    ', source, scope: hash, dictionary_access: :string + end + + def test_symbol_access + source = %q{ +p + - person + .name = name +} + + hash = { + person: [ + { name: 'Joe', }, + { name: 'Jack', } + ] + } + + assert_html '

    Joe
    Jack

    ', source, scope: hash, dictionary_access: :symbol + end + + def test_method_access + source = %q{ +p + - person + .name = name +} + + object = Object.new + def object.person + %w(Joe Jack).map do |name| + person = Object.new + person.instance_variable_set(:@name, name) + def person.name + @name + end + person + end + end + + assert_html '

    Joe
    Jack

    ', source, scope: object, dictionary_access: :method + end + + def test_method_access_without_private + source = %q{ +p + - person + .age = age +} + + object = Object.new + def object.person + person = Object.new + def person.age + 42 + end + person.singleton_class.class_eval { private :age } + person + end + + assert_html '

    ', source, scope: object, dictionary_access: :method + end + + def test_instance_variable_access + source = %q{ +p + - person + .name = name +} + + object = Object.new + object.instance_variable_set(:@person, %w(Joe Jack).map do |name| + person = Object.new + person.instance_variable_set(:@name, name) + person + end) + + assert_html '

    Joe
    Jack

    ', source, scope: object, dictionary_access: :instance_variable + end + + def test_to_s_access + source = %q{ +p + - people + .name = self +} + + hash = { + people: [ + 'Joe', + 'Jack' + ] + } + + assert_html '

    Joe
    Jack

    ', source, scope: hash, dictionary_access: :symbol + end + + def test_string_hash + source = %q{ +p + - person + .name = name +} + + hash = { + 'person' => [ + { 'name' => 'Joe', }, + { 'name' => 'Jack', } + ] + } + + assert_html '

    Joe
    Jack

    ', source, scope: hash + end + + def test_dictionary_option + source = %q{ +p + - person + .name = name +} + + assert_html '

    Joe
    Jack

    ', source, scope: Scope.new, dictionary: '@hash' + end + + def test_flag_section + source = %q{ +p + - show_person + - person + .name = name + - show_person + | shown +} + + hash = { + show_person: true, + person: [ + { name: 'Joe', }, + { name: 'Jack', } + ] + } + + assert_html '

    Joe
    Jack
    shown

    ', source, scope: hash + end + + def test_inverted_section + source = %q{ +p + - person + .name = name + -! person + | No person + - !person + | No person 2 +} + + hash = {} + + assert_html '

    No person No person 2

    ', source, scope: hash + end + + def test_escaped_interpolation + source = %q{ +p text with \#{123} test +} + + assert_html '

    text with #{123} test

    ', source + end + + def test_ruby_attributes + source = %q{ +p + - person + b name=name Person + a id=name = age + span class=name + Person +} + + assert_html '

    Person1Person2

    ', source, scope: Scope.new, dictionary: '@hash' + end + + def test_boolean_attributes + source = %q{ +p + - person + input checked=selected = name +} + + assert_html '

    JoeJack

    ', source, scope: Scope.new, dictionary: '@hash' + end + + def test_sections + source = %q{ +p + - person + .name = name +} + assert_html '

    Joe
    Jack

    ', source, dictionary: 'ViewEnv.new' + end + + def test_with_array + source = %q{ +ul + - people_with_locations + li = name + li = city +} + assert_html '
    • Andy
    • Atlanta
    • Fred
    • Melbourne
    • Daniel
    • Karlsruhe
    ', source, dictionary: 'ViewEnv.new' + end + + def test_method + source = %q{ +a href=output_number Link +} + assert_html 'Link', source, dictionary: 'ViewEnv.new' + end + + def test_conditional_parent + source = %q{ +- prev_page + li.previous + a href=prev_page Older +- next_page + li.next + a href=next_page Newer} + assert_html'', source, scope: {prev_page: 'prev', next_page: 'next'} + end + + def test_render_with_yield + source = %q{ +div + == yield +} + + assert_html '
    This is the menu
    ', source do + 'This is the menu' + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/Rakefile b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/Rakefile new file mode 100644 index 0000000..9724472 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/Rakefile @@ -0,0 +1,7 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require File.expand_path('../config/application', __FILE__) +require 'rake' + +Dummy::Application.load_tasks diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/assets/config/manifest.js b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/assets/config/manifest.js new file mode 100644 index 0000000..c1beb60 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/assets/config/manifest.js @@ -0,0 +1 @@ +// file required by sprockets >= 4.0 diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/controllers/application_controller.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/controllers/application_controller.rb new file mode 100644 index 0000000..09705d1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::Base +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/controllers/entries_controller.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/controllers/entries_controller.rb new file mode 100644 index 0000000..4191792 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/controllers/entries_controller.rb @@ -0,0 +1,5 @@ +class EntriesController < ApplicationController + def edit + @entry = Entry.new + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/controllers/slim_controller.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/controllers/slim_controller.rb new file mode 100644 index 0000000..e577e80 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/controllers/slim_controller.rb @@ -0,0 +1,40 @@ +class SlimController < ApplicationController + def normal + end + + def xml + end + + def no_layout + render layout: false + end + + def variables + @hello = "Hello Slim with variables!" + end + + def partial + end + + def streaming + @hello = "Hello Streaming!" + render :content_for, stream: true + end + + def integers + @integer = 1337 + end + + def thread_options + Slim::Engine.with_options(shortcut: {'@' => { attr: params[:attr] }}) do + render + end + end + + def content_for + @hello = "Hello Slim!" + end + + def helper + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/helpers/application_helper.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/helpers/application_helper.rb new file mode 100644 index 0000000..1ebdabe --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/helpers/application_helper.rb @@ -0,0 +1,5 @@ +module ApplicationHelper + def headline(&block) + "

    #{capture(&block)}

    ".html_safe + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/models/entry.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/models/entry.rb new file mode 100644 index 0000000..da4c5d8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/models/entry.rb @@ -0,0 +1,16 @@ +class Entry + include ActiveModel::Conversion + extend ActiveModel::Naming + + attr_accessor :name + + def initialize(attributes = {}) + attributes.each do |name, value| + send("#{name}=", value) + end + end + + def persisted? + false + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/entries/edit.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/entries/edit.html.slim new file mode 100644 index 0000000..fac4bf4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/entries/edit.html.slim @@ -0,0 +1,3 @@ += form_for @entry do |f| + label: b Name + = f.text_field :name diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/layouts/application.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/layouts/application.html.slim new file mode 100644 index 0000000..efae074 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/layouts/application.html.slim @@ -0,0 +1,10 @@ +doctype html + +html + head + title Dummy + = csrf_meta_tag + + body + = yield :page_heading + .content= yield diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/_partial.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/_partial.html.slim new file mode 100644 index 0000000..1987dc0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/_partial.html.slim @@ -0,0 +1 @@ +p With a partial! \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/content_for.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/content_for.html.slim new file mode 100644 index 0000000..38c4e0f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/content_for.html.slim @@ -0,0 +1,7 @@ +p Page content +- content_for :page_heading, "Heading set from a view" +- content_for :hello_slim do + p= @hello + +h1= yield :hello_slim +h2= yield :hello_slim \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/erb.html.erb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/erb.html.erb new file mode 100644 index 0000000..269071f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/erb.html.erb @@ -0,0 +1 @@ +

    Hello Erb!

    \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/form_for.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/form_for.html.slim new file mode 100644 index 0000000..eedb8f2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/form_for.html.slim @@ -0,0 +1,2 @@ += form_for @entry do |f| + = f.text_field :name diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/helper.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/helper.html.slim new file mode 100644 index 0000000..e745363 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/helper.html.slim @@ -0,0 +1,4 @@ +p + = headline do + ' Hello + = 'User' diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/integers.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/integers.html.slim new file mode 100644 index 0000000..d937f92 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/integers.html.slim @@ -0,0 +1 @@ +p= @integer \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/no_layout.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/no_layout.html.slim new file mode 100644 index 0000000..cf65191 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/no_layout.html.slim @@ -0,0 +1 @@ +h1 Hello Slim without a layout! \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/normal.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/normal.html.slim new file mode 100644 index 0000000..2721b41 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/normal.html.slim @@ -0,0 +1 @@ +h1 Hello Slim! \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/partial.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/partial.html.slim new file mode 100644 index 0000000..2550477 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/partial.html.slim @@ -0,0 +1,2 @@ +h1 Hello Slim! += render "partial" \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/splat.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/splat.html.slim new file mode 100644 index 0000000..3132b7d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/splat.html.slim @@ -0,0 +1,2 @@ +#splat + *{tag: 'splat'} Hello diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/thread_options.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/thread_options.html.slim new file mode 100644 index 0000000..c3a829c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/thread_options.html.slim @@ -0,0 +1 @@ +p@empty Test diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/variables.html.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/variables.html.slim new file mode 100644 index 0000000..1ec7dcf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/variables.html.slim @@ -0,0 +1 @@ +h1= @hello \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/xml.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/xml.slim new file mode 100644 index 0000000..2721b41 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/app/views/slim/xml.slim @@ -0,0 +1 @@ +h1 Hello Slim! \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config.ru b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config.ru new file mode 100644 index 0000000..1989ed8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config.ru @@ -0,0 +1,4 @@ +# This file is used by Rack-based servers to start the application. + +require ::File.expand_path('../config/environment', __FILE__) +run Dummy::Application diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/application.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/application.rb new file mode 100644 index 0000000..09463ac --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/application.rb @@ -0,0 +1,61 @@ +require File.expand_path('../boot', __FILE__) + +require 'active_model/railtie' +require 'action_controller/railtie' +require 'action_view/railtie' +#require 'active_record/railtie' +#require 'action_mailer/railtie' +require 'sprockets/railtie' + +require 'slim' +require 'slim-rails/register_engine' + +module Dummy + class Application < Rails::Application + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Custom directories with classes and modules you want to be autoloadable. + # config.autoload_paths += %W(#{config.root}/extras) + + # Only load the plugins named here, in the order given (default is alphabetical). + # :all can be used as a placeholder for all plugins not explicitly named. + # config.plugins = [ :exception_notification, :ssl_requirement, :all ] + + # Activate observers that should always be running. + # config.active_record.observers = :cacher, :garbage_collector, :forum_observer + + # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. + # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. + # config.time_zone = 'Central Time (US & Canada)' + + # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. + # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] + # config.i18n.default_locale = :de + + # JavaScript files you want as :defaults (application.js is always included). + # config.action_view.javascript_expansions[:defaults] = %w(jquery rails) + + # Configure the default encoding used in templates for Ruby 1.9. + config.encoding = "utf-8" + + # Configure sensitive parameters which will be filtered from the log file. + config.filter_parameters += [:password] + + # From slim-rails fix for "ActionView::Template::Error: Unknown line indicator" + # https://github.com/slim-template/slim-rails/blob/991589ea5648e5e896781e68912bc51beaf4102a/lib/slim-rails/register_engine.rb + if config.respond_to?(:assets) + config.assets.configure do |env| + if env.respond_to?(:register_transformer) && Sprockets::VERSION.to_i > 3 + env.register_mime_type 'text/slim', extensions: ['.slim', '.slim.html'] + env.register_transformer 'text/slim', 'text/html', Slim::Rails::RegisterEngine::Transformer + elsif env.respond_to?(:register_engine) + args = ['.slim', Slim::Template] + args << { silence_deprecation: true } if Sprockets::VERSION.start_with?('3') + env.register_engine(*args) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/boot.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/boot.rb new file mode 100644 index 0000000..8d133c0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/boot.rb @@ -0,0 +1,10 @@ +require 'rubygems' +gemfile = File.expand_path('../../../../../../Gemfile', __FILE__) + +if File.exist?(gemfile) + ENV['BUNDLE_GEMFILE'] = gemfile + require 'bundler' + Bundler.setup(:default, :integration) +end + +$:.unshift File.expand_path('../../../../../../lib', __FILE__) \ No newline at end of file diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/environment.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/environment.rb new file mode 100644 index 0000000..3da5eb9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/environment.rb @@ -0,0 +1,5 @@ +# Load the rails application +require File.expand_path('../application', __FILE__) + +# Initialize the rails application +Dummy::Application.initialize! diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/environments/test.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/environments/test.rb new file mode 100644 index 0000000..dfe565f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/environments/test.rb @@ -0,0 +1,34 @@ +Dummy::Application.configure do + # Settings specified here will take precedence over those in config/application.rb + + # The test environment is used exclusively to run your application's + # test suite. You never need to work with it otherwise. Remember that + # your test database is "scratch space" for the test suite and is wiped + # and recreated between test runs. Don't rely on the data there! + config.cache_classes = true + + # Show full error reports and disable caching + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Raise exceptions instead of rendering exception templates + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment + config.action_controller.allow_forgery_protection = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + #config.action_mailer.delivery_method = :test + + # Use SQL instead of Active Record's schema dumper when creating the test database. + # This is necessary if your schema can't be completely dumped by the schema dumper, + # like if you have constraints or database-specific column types + # config.active_record.schema_format = :sql + + # Print deprecation notices to the stderr + config.active_support.deprecation = :stderr + + config.eager_load = false +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/backtrace_silencers.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/backtrace_silencers.rb new file mode 100644 index 0000000..59385cd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/inflections.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/inflections.rb new file mode 100644 index 0000000..9e8b013 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/inflections.rb @@ -0,0 +1,10 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format +# (all these examples are active by default): +# ActiveSupport::Inflector.inflections do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/mime_types.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/mime_types.rb new file mode 100644 index 0000000..72aca7e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/mime_types.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf +# Mime::Type.register_alias "text/html", :iphone diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/secret_token.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/secret_token.rb new file mode 100644 index 0000000..172a77c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/secret_token.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +Dummy::Application.config.secret_token = Dummy::Application.config.secret_key_base = '123a9119fb14a410f485f9390286b33f2743b9d348246cf3e4434522078f77c202d7a1fb7e42666dd0844bcb10d0ff3d8b4ee087796269d4c574837948512dbf' diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/session_store.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/session_store.rb new file mode 100644 index 0000000..952473f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/initializers/session_store.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' + +# Use the database for sessions instead of the cookie-based default, +# which shouldn't be used to store highly confidential information +# (create the session table with "rails generate session_migration") +# Dummy::Application.config.session_store :active_record_store diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/locales/en.yml b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/locales/en.yml new file mode 100644 index 0000000..a747bfa --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/locales/en.yml @@ -0,0 +1,5 @@ +# Sample localization file for English. Add more files in this directory for other locales. +# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. + +en: + hello: "Hello world" diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/routes.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/routes.rb new file mode 100644 index 0000000..03ed30b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/config/routes.rb @@ -0,0 +1,60 @@ +Dummy::Application.routes.draw do + # The priority is based upon order of creation: + # first created -> highest priority. + + resources :entries + + # Sample of regular route: + # match 'products/:id' => 'catalog#view' + # Keep in mind you can assign values other than :controller and :action + + # Sample of named route: + # match 'products/:id/purchase' => 'catalog#purchase', as: :purchase + # This route can be invoked with purchase_url(id: product.id) + + # Sample resource route (maps HTTP verbs to controller actions automatically): + # resources :products + + # Sample resource route with options: + # resources :products do + # member do + # get 'short' + # post 'toggle' + # end + # + # collection do + # get 'sold' + # end + # end + + # Sample resource route with sub-resources: + # resources :products do + # resources :comments, :sales + # resource :seller + # end + + # Sample resource route with more complex sub-resources + # resources :products do + # resources :comments + # resources :sales do + # get 'recent', on: :collection + # end + # end + + # Sample resource route within a namespace: + # namespace :admin do + # # Directs /admin/products/* to Admin::ProductsController + # # (app/controllers/admin/products_controller.rb) + # resources :products + # end + + # You can have the root of your site routed with "root" + # just remember to delete public/index.html. + # root to: "welcome#index" + + # See how all your routes lay out with "rake routes" + + # This is a legacy wild controller route that's not recommended for RESTful applications. + # Note: This route will make all actions in every controller accessible via GET requests. + get ':controller(/:action(/:id(.:format)))' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/script/rails b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/script/rails new file mode 100755 index 0000000..f8da2cf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/script/rails @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. + +APP_PATH = File.expand_path('../../config/application', __FILE__) +require File.expand_path('../../config/boot', __FILE__) +require 'rails/commands' diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/test/helper.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/test/helper.rb new file mode 100644 index 0000000..65fe79c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/test/helper.rb @@ -0,0 +1,34 @@ +# Configure Rails Envinronment +ENV["RAILS_ENV"] = "test" + +require File.expand_path("../../config/environment.rb", __FILE__) +require "rails/test_help" +require "nokogiri" + +require 'rails-controller-testing' +Rails::Controller::Testing.install + +Rails.backtrace_cleaner.remove_silencers! + +class ActionDispatch::IntegrationTest + +protected + + def assert_xpath(xpath, message="Unable to find '#{xpath}' in response body.") + assert_response :success, "Response type is not :success (code 200..299)." + + body = @response.body + assert !body.empty?, "No response body found." + + doc = Nokogiri::HTML(body) rescue nil + assert_not_nil doc, "Cannot parse response body." + + assert doc.xpath(xpath).size >= 1, message + end + + def assert_html(expected, options = {}) + expected = "Dummy#{options[:heading]}
    #{expected}
    " unless options[:skip_layout] + assert_equal expected, @response.body + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/test/test_slim.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/test/test_slim.rb new file mode 100644 index 0000000..eb5c166 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/rails/test/test_slim.rb @@ -0,0 +1,90 @@ +require File.expand_path('../helper', __FILE__) + +class TestSlim < ActionDispatch::IntegrationTest + test "normal view" do + get "/slim/normal" + assert_response :success + assert_template "slim/normal" + assert_template "layouts/application" + assert_html "

    Hello Slim!

    " + end + + test "xml view" do + get "/slim/xml" + assert_response :success + assert_template "slim/xml" + assert_template "layouts/application" + assert_html "

    Hello Slim!

    " + end + + test "helper" do + get "/slim/helper" + assert_response :success + assert_template "slim/helper" + assert_template "layouts/application" + assert_html "

    Hello User

    " + end + + test "normal erb view" do + get "/slim/erb" + assert_html "

    Hello Erb!

    " + end + + test "view without a layout" do + get "/slim/no_layout" + assert_template "slim/no_layout" + assert_html "

    Hello Slim without a layout!

    ", skip_layout: true + end + + test "view with variables" do + get "/slim/variables" + assert_html "

    Hello Slim with variables!

    " + end + + test "partial view" do + get "/slim/partial" + assert_html "

    Hello Slim!

    With a partial!

    " + end + + if RUBY_ENGINE == 'jruby' && RUBY_ENGINE < '2.2.0' + puts 'Streaming test disabled for JRuby < 9000.', + 'See https://github.com/jruby/jruby/issues/1243', + 'and https://github.com/jruby/jruby/issues/1789' + else + puts 'Streaming test enabled.' + test "streaming" do + get "/slim/streaming" + output = "2f\r\nDummy\r\nd\r\n\r\n17\r\nHeading set from a view\r\n15\r\n
    \r\n53\r\n

    Page content

    Hello Streaming!

    Hello Streaming!

    \r\n14\r\n
    \r\n0\r\n\r\n" + assert_equal output, @response.body + end + end + + test "render integers" do + get "/slim/integers" + assert_html "

    1337

    " + end + + test "render thread_options" do + get "/slim/thread_options", params: { attr: 'role'} + assert_html '

    Test

    ' + get "/slim/thread_options", params: { attr: 'id'} # Overwriting doesn't work because of caching + assert_html '

    Test

    ' + end + + test "content_for" do + get "/slim/content_for" + assert_html "

    Page content

    Hello Slim!

    Hello Slim!

    ", heading: 'Heading set from a view' + end + + test "form_for" do + get "/entries/edit/1" + assert_match %r{action="/entries"}, @response.body + assert_match %r{}, @response.body + assert_xpath '//input[@id="entry_name" and @name="entry[name]" and @type="text"]' + end + + test "splat" do + get "/slim/splat" + assert_html "
    Hello
    " + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/contest.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/contest.rb new file mode 100644 index 0000000..2b68c41 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/contest.rb @@ -0,0 +1,91 @@ +# Copyright (c) 2009 Damian Janowski and Michel Martens for Citrusbyte +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +require "rubygems" +require "minitest/autorun" + +# Contest adds +teardown+, +test+ and +context+ as class methods, and the +# instance methods +setup+ and +teardown+ now iterate on the corresponding +# blocks. Note that all setup and teardown blocks must be defined with the +# block syntax. Adding setup or teardown instance methods defeats the purpose +# of this library. +class Minitest::Test + def self.setup(&block) setup_blocks << block end + def self.teardown(&block) teardown_blocks << block end + def self.setup_blocks() @setup_blocks ||= [] end + def self.teardown_blocks() @teardown_blocks ||= [] end + + def setup_blocks(base = self.class) + setup_blocks base.superclass if base.superclass.respond_to? :setup_blocks + base.setup_blocks.each do |block| + instance_eval(&block) + end + end + + def teardown_blocks(base = self.class) + teardown_blocks base.superclass if base.superclass.respond_to? :teardown_blocks + base.teardown_blocks.each do |block| + instance_eval(&block) + end + end + + alias setup setup_blocks + alias teardown teardown_blocks + + def self.context(*name, &block) + subclass = Class.new(self) + remove_tests(subclass) + subclass.class_eval(&block) if block_given? + const_set(context_name(name.join(" ")), subclass) + end + + def self.test(name, &block) + define_method(test_name(name), &block) + end + + class << self + alias_method :should, :test + alias_method :describe, :context + end + +private + + def self.context_name(name) + # "Test#{sanitize_name(name).gsub(/(^| )(\w)/) { $2.upcase }}".to_sym + name = "Test#{sanitize_name(name).gsub(/(^| )(\w)/) { $2.upcase }}" + name.tr(" ", "_").to_sym + end + + def self.test_name(name) + name = "test_#{sanitize_name(name).gsub(/\s+/,'_')}_0" + name = name.succ while method_defined? name + name.to_sym + end + + def self.sanitize_name(name) + # name.gsub(/\W+/, ' ').strip + name.gsub(/\W+/, ' ') + end + + def self.remove_tests(subclass) + subclass.public_instance_methods.grep(/^test_/).each do |meth| + subclass.send(:undef_method, meth.to_sym) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/helper.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/helper.rb new file mode 100644 index 0000000..34d7d5f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/helper.rb @@ -0,0 +1,145 @@ +if ENV['COVERAGE'] + require 'simplecov' + SimpleCov.start do + add_filter '/test/' + add_group 'sinatra-contrib', 'sinatra-contrib' + add_group 'rack-protection', 'rack-protection' + end +end + +ENV['APP_ENV'] = 'test' +Encoding.default_external = "UTF-8" if defined? Encoding + +RUBY_ENGINE = 'ruby' unless defined? RUBY_ENGINE + +require 'rack' + +testdir = File.dirname(__FILE__) +$LOAD_PATH.unshift testdir unless $LOAD_PATH.include?(testdir) + +libdir = File.dirname(File.dirname(__FILE__)) + '/lib' +$LOAD_PATH.unshift libdir unless $LOAD_PATH.include?(libdir) + +require 'minitest' +require 'contest' +require 'rack/test' +require 'sinatra' +require 'sinatra/base' + +class Sinatra::Base + include Minitest::Assertions + # Allow assertions in request context + def assertions + @assertions ||= 0 + end + + attr_writer :assertions +end + +class Rack::Builder + def include?(middleware) + @ins.any? { |m| middleware === m } + end +end + +Sinatra::Base.set :environment, :test + +class Minitest::Test + include Rack::Test::Methods + + class << self + alias_method :it, :test + alias_method :section, :context + end + + def self.example(desc = nil, &block) + @example_count = 0 unless instance_variable_defined? :@example_count + @example_count += 1 + it(desc || "Example #{@example_count}", &block) + end + + alias_method :response, :last_response + + setup do + Sinatra::Base.set :environment, :test + end + + # Sets up a Sinatra::Base subclass defined with the block + # given. Used in setup or individual spec methods to establish + # the application. + def mock_app(base=Sinatra::Base, &block) + @app = Sinatra.new(base, &block) + end + + def app + Rack::Lint.new(@app) + end + + def slim_app(&block) + mock_app do + set :views, File.dirname(__FILE__) + '/views' + get('/', &block) + end + get '/' + end + + def body + response.body.to_s + end + + def assert_body(value) + if value.respond_to? :to_str + assert_equal value.lstrip.gsub(/\s*\n\s*/, ""), body.lstrip.gsub(/\s*\n\s*/, "") + else + assert_match value, body + end + end + + def assert_status(expected) + assert_equal Integer(expected), Integer(status) + end + + def assert_like(a,b) + pattern = /id=['"][^"']*["']|\s+/ + assert_equal a.strip.gsub(pattern, ""), b.strip.gsub(pattern, "") + end + + def assert_include(str, substr) + assert str.include?(substr), "expected #{str.inspect} to include #{substr.inspect}" + end + + def options(uri, params = {}, env = {}, &block) + request(uri, env.merge(:method => "OPTIONS", :params => params), &block) + end + + def patch(uri, params = {}, env = {}, &block) + request(uri, env.merge(:method => "PATCH", :params => params), &block) + end + + def link(uri, params = {}, env = {}, &block) + request(uri, env.merge(:method => "LINK", :params => params), &block) + end + + def unlink(uri, params = {}, env = {}, &block) + request(uri, env.merge(:method => "UNLINK", :params => params), &block) + end + + # Delegate other missing methods to response. + def method_missing(name, *args, &block) + if response && response.respond_to?(name) + response.send(name, *args, &block) + else + super + end + rescue Rack::Test::Error + super + end + + # Do not output warnings for the duration of the block. + def silence_warnings + $VERBOSE, v = nil, $VERBOSE + yield + ensure + $VERBOSE = v + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/test_core.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/test_core.rb new file mode 100644 index 0000000..c5b0342 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/test_core.rb @@ -0,0 +1,91 @@ +require_relative 'helper.rb' + +begin + class SlimTest < Minitest::Test + it 'renders inline slim strings' do + slim_app { slim "h1 Hiya\n" } + assert ok? + assert_equal "

    Hiya

    ", body + end + + it 'renders .slim files in views path' do + slim_app { slim :hello } + assert ok? + assert_equal "

    Hello From Slim

    ", body + end + + it "renders with inline layouts" do + mock_app do + layout { %(h1\n | THIS. IS. \n == yield.upcase ) } + get('/') { slim 'em Sparta' } + end + get '/' + assert ok? + assert_equal "

    THIS. IS. SPARTA

    ", body + end + + it "renders with file layouts" do + slim_app { slim('| Hello World', :layout => :layout2) } + assert ok? + assert_equal "

    Slim Layout!

    Hello World

    ", body + end + + it "raises error if template not found" do + mock_app { get('/') { slim(:no_such_template) } } + assert_raises(Errno::ENOENT) { get('/') } + end + + HTML4_DOCTYPE = "" + + it "passes slim options to the slim engine" do + mock_app { get('/') { slim("x foo='bar'", :attr_quote => "'") }} + get '/' + assert ok? + assert_body "" + end + + it "passes default slim options to the slim engine" do + mock_app do + set :slim, :attr_quote => "'" + get('/') { slim("x foo='bar'") } + end + get '/' + assert ok? + assert_body "" + end + + it "merges the default slim options with the overrides and passes them to the slim engine" do + mock_app do + set :slim, :attr_quote => "'" + get('/') { slim("x foo='bar'") } + get('/other') { slim("x foo='bar'", :attr_quote => '"') } + end + get '/' + assert ok? + assert_body "" + get '/other' + assert ok? + assert_body '' + end + + it "can render truly nested layouts by accepting a layout and a block with the contents" do + mock_app do + template(:main_outer_layout) { "h1 Title\n== yield" } + template(:an_inner_layout) { "h2 Subtitle\n== yield" } + template(:a_page) { "p Contents." } + get('/') do + slim :main_outer_layout, :layout => false do + slim :an_inner_layout do + slim :a_page + end + end + end + end + get '/' + assert ok? + assert_body "

    Title

    \n

    Subtitle

    \n

    Contents.

    \n" + end + end +rescue LoadError + warn "#{$!}: skipping slim tests" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/test_include.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/test_include.rb new file mode 100644 index 0000000..63dea21 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/test_include.rb @@ -0,0 +1,16 @@ +require 'slim/include' + +require_relative 'helper.rb' + +begin + class SlimTest < Minitest::Test + it 'renders .slim files includes with js embed' do + slim_app { slim :embed_include_js } + assert ok? + assert_equal "Slim Examples
    Slim
    ", body + end + + end +rescue LoadError + warn "#{$!}: skipping slim tests" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/embed_include_js.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/embed_include_js.slim new file mode 100644 index 0000000..395d8ea --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/embed_include_js.slim @@ -0,0 +1,8 @@ +doctype html +html + head + title Slim Examples + javascript: + alert('Slim supports embedded javascript!') + body + include footer.slim diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/embed_js.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/embed_js.slim new file mode 100644 index 0000000..2e2cf02 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/embed_js.slim @@ -0,0 +1,11 @@ +doctype html +html + head + title Slim Examples + javascript: + alert('Slim supports embedded javascript!') + body + h1 Markup examples + + #content + p This example shows you how a basic Slim file looks. diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/footer.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/footer.slim new file mode 100644 index 0000000..02623f5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/footer.slim @@ -0,0 +1 @@ +footer Slim diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/hello.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/hello.slim new file mode 100644 index 0000000..067e671 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/hello.slim @@ -0,0 +1 @@ +h1 Hello From Slim diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/layout2.slim b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/layout2.slim new file mode 100644 index 0000000..d296686 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/sinatra/views/layout2.slim @@ -0,0 +1,3 @@ +h1 Slim Layout! +p + == yield diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/smart/test_smart_text.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/smart/test_smart_text.rb new file mode 100644 index 0000000..7f3cfee --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/smart/test_smart_text.rb @@ -0,0 +1,294 @@ +require 'helper' +require 'slim/smart' + +class TestSlimSmartText < TestSlim + + def test_explicit_smart_text_recognition + source = %q{ +> + a +> + b + +> + + c +> + + d + +> e +f +> g + h +i +} + + result = %q{a +b +c +d +e + +g +h +} + + assert_html result, source + end + + def test_implicit_smart_text_recognition + source = %q{ +p + A +p + B + +p + + C +p + + D + +p E +F +p G + H +I +} + + result = %q{

    A

    B

    C

    D

    E

    +F +

    G +H

    +I} + + assert_html result, source + end + + def test_multi_line_smart_text + source = %q{ +p + First line. + Second line. + Third line + with a continuation + and one more. + Fourth line. +} + + result = %q{

    First line. +Second line. +Third line +with a continuation +and one more. +Fourth line.

    } + + assert_html result, source + end + + def test_smart_text_escaping + source = %q{ +| Not escaped <&>. +p Escaped <&>. +p + Escaped <&>. + > Escaped <&>. + Protected & < > © Á. + Protected  ÿ. + Escaped &#xx; f; &9; &_; &;. +} + + result = %q{Not escaped <&>.

    Escaped <&>.

    Escaped <&>. +Escaped <&>. +Protected & < > © Á. +Protected  ÿ. +Escaped &#xx; &#1f; &9; &_; &;.

    } + + assert_html result, source + end + + def test_smart_text_disabled_escaping + Slim::Engine.with_options( smart_text_escaping: false ) do + source = %q{ +p Not escaped <&>. +| Not escaped <&>. +p + Not escaped <&>. + > Not escaped <&>. + Not escaped & < > © Á. + Not escaped  ÿ. + Not escaped &#xx; f; &9; &_; &;. +} + + result = %q{

    Not escaped <&>.

    Not escaped <&>.

    Not escaped <&>. +Not escaped <&>. +Not escaped & < > © Á. +Not escaped  ÿ. +Not escaped &#xx; f; &9; &_; &;.

    } + + assert_html result, source + end + end + + def test_smart_text_in_tag_escaping + source = %q{ +p Escaped <&>. + Protected & < > © Á. + Protected  ÿ. + Escaped &#xx; f; &9; &_; &;. +} + + result = %q{

    Escaped <&>. +Protected & < > © Á. +Protected  ÿ. +Escaped &#xx; &#1f; &9; &_; &;.

    } + + assert_html result, source + end + + def test_smart_text_mixed_with_tags + source = %q{ +p + Text + br + >is + strong really + > recognized. + + More + b text + . + + And + i more + ... + + span Really + ?!? + + .bold Really + !!! + + #id + #{'Good'} + ! +} + + result = %q{

    Text +
    +is +really +recognized. +More +text. +And +more... +Really?!? +

    Really
    !!! +
    Good
    !

    } + + assert_html result, source + end + + def test_smart_text_mixed_with_links + source = %q{ +p + Text with + a href="#1" link + . + + Text with + a href="#2" another + link + > to somewhere else. + + a href="#3" + This link + > goes + elsewhere. + + See ( + a href="#4" link + )? +} + + result = %q{

    Text with +link. +Text with +another +link +to somewhere else. +This link +goes +elsewhere. +See (link)?

    } + + assert_html result, source + end + + def test_smart_text_mixed_with_code + source = %q{ +p + Try a list + ul + - 2.times do |i| + li + Item: #{i} + > which stops + b here + . Right? +} + + result = %q{

    Try a list +

    • Item: 0
    • Item: 1
    +which stops +here. Right?

    } + + assert_html result, source + end + + # Without unicode support, we can't distinguish uppercase and lowercase + # unicode characters reliably. So we only test the basic text, not tag names. + def test_basic_unicode_smart_text + source = %q{ +p + 是 + čip + Čip + Žůžo + šíp +} + + result = %q{

    是 +čip +Čip +Žůžo +šíp

    } + + assert_html result, source + end + + def test_unicode_smart_text + source = %q{ +p + 是 + čip + Čip + Žůžo + šíp + .řek + . +} + + result = %q{

    是 +čip +Čip +Žůžo +šíp +

    .

    } + + assert_html result, source + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/translator/test_translator.rb b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/translator/test_translator.rb new file mode 100644 index 0000000..9073ac8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/slim-4.1.0/test/translator/test_translator.rb @@ -0,0 +1,76 @@ +require 'helper' +require 'slim/translator' + +class TestSlimTranslator < TestSlim + def setup + super + Slim::Engine.set_options tr: true, tr_fn: 'TestSlimTranslator.tr' + end + + def self.tr(s) + s.upcase + end + + def self.tr_reverse(s) + s.reverse.gsub(/(\d+)%/, '%\1') + end + + def test_no_translation_of_embedded + source = %q{ +markdown: + #Header + Hello from #{"Markdown!"} + + #{1+2} + + * one + * two +} + + case Tilt['md'].name.downcase + when /redcarpet/ + assert_html "

    Header

    \n\n

    Hello from Markdown!

    \n\n

    3

    \n\n
      \n
    • one
    • \n
    • two
    • \n
    \n", source, tr_mode: :dynamic + assert_html "

    Header

    \n\n

    Hello from Markdown!

    \n\n

    3

    \n\n
      \n
    • one
    • \n
    • two
    • \n
    \n", source, tr_mode: :static + when /rdiscount/ + assert_html "

    Header

    \n\n

    Hello from Markdown!

    \n\n

    3

    \n\n
      \n
    • one
    • \n
    • two
    • \n
    \n\n", source, tr_mode: :dynamic + assert_html "

    Header

    \n\n

    Hello from Markdown!

    \n\n

    3

    \n\n
      \n
    • one
    • \n
    • two
    • \n
    \n\n", source, tr_mode: :static + when /kramdown/ + assert_html "

    Header

    \n

    Hello from Markdown!

    \n\n

    3

    \n\n
      \n
    • one
    • \n
    • two
    • \n
    \n", source, tr_mode: :dynamic + assert_html "

    Header

    \n

    Hello from Markdown!

    \n\n

    3

    \n\n
      \n
    • one
    • \n
    • two
    • \n
    \n", source, tr_mode: :static + else + raise "Missing test for #{Tilt['md']}" + end + end + + def test_no_translation_of_attrs + source = %q{ +' this is + a link to +a href="link" page +} + + assert_html "THIS IS\nA LINK TO PAGE", source, tr_mode: :dynamic + assert_html "THIS IS\nA LINK TO PAGE", source, tr_mode: :static + end + + def test_translation_and_interpolation + source = %q{ +p translate #{hello_world} this + second line + third #{1+2} line +} + + assert_html "

    translate Hello World from @env this\nsecond line\nthird 3 line

    ", source, tr: false + assert_html "

    TRANSLATE Hello World from @env THIS\nSECOND LINE\nTHIRD 3 LINE

    ", source, tr_mode: :dynamic + assert_html "

    TRANSLATE Hello World from @env THIS\nSECOND LINE\nTHIRD 3 LINE

    ", source, tr_mode: :static + end + + def test_translation_reverse + source = %q{ +' alpha #{1} beta #{2} gamma #{3} +} + + assert_html "3 ammag 2 ateb 1 ahpla ", source, tr_mode: :dynamic, tr_fn: 'TestSlimTranslator.tr_reverse' + assert_html "3 ammag 2 ateb 1 ahpla ", source, tr_mode: :static, tr_fn: 'TestSlimTranslator.tr_reverse' + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/.gemtest b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/.gemtest new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/.travis.yml b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/.travis.yml new file mode 100644 index 0000000..4876968 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/.travis.yml @@ -0,0 +1,33 @@ +language: ruby +cache: bundler +before_install: + - gem update --system 2.7.7 + - gem install bundler -v 1.16.2 +addons: + apt: + packages: + - libgmp-dev + +after_failure: + - "find . -name mkmf.log -exec cat {} \\;" + +after_success: + - "find . -name mkmf.log -exec cat {} \\;" + +env: + - USE_MINI_PORTILE=true + - USE_MINI_PORTILE=false +rvm: + - 1.9.3 + - 2.0.0 + - 2.1 + - 2.2 + - 2.3 + - 2.4 + - 2.5 + - 2.6 + - 2.7 + - ruby-head +matrix: + allow_failures: + - env: USE_MINI_PORTILE=false diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/API_CHANGES.rdoc b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/API_CHANGES.rdoc new file mode 100644 index 0000000..7f77a02 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/API_CHANGES.rdoc @@ -0,0 +1,50 @@ += API Changes + +* SQLite3::Database#execute only accepts an array for bind parameters. + +* SQLite3::ResultSet used to query the database for the first row, regardless + of whether the user asked for it or not. I have removed that so that rows + will not be returned until the user asks for them. This is a subtle but + sometimes important change in behavior. + + 83882d2208ed189361617d5ab8532a325aaf729d + +* SQLite3::Database#trace now takes either a block or an object that responds + to "call". The previous implementation passed around a VALUE that was cast + to a void *. This is dangerous because the value could get garbage collected + before the proc was called. If the user wants data passed around with the + block, they should use variables available to the closure or create an + object. + +* SQLite3::Statement#step automatically converts to ruby types, where before + all values were automatically yielded as strings. This will only be a + problem for people who were accessing information about the database that + wasn't previously passed through the pure ruby conversion code. + +* SQLite3::Database#errmsg no longer takes a parameter to return error + messages as UTF-16. Do people even use that? I opt for staying UTF-8 when + possible. See test_integration.rb test_errmsg_utf16 + +* SQLite3::Database#authorize same changes as trace + +* test/test_tc_database.rb was removed because we no longer use the Driver + design pattern. + += Garbage Collection Strategy + +All statements keep pointers back to their respective database connections. +The @connection instance variable on the Statement handle keeps the database +connection alive. Memory allocated for a statement handler will be freed in +two cases: + +* close is called on the statement +* The SQLite3::Database object gets garbage collected + +We can't free the memory for the statement in the garbage collection function +for the statement handler. The reason is because there exists a race +condition. We cannot guarantee the order in which objects will be garbage +collected. So, it is possible that a connection and a statement are up for +garbage collection. If the database connection were to be free'd before the +statement, then boom. Instead we'll be conservative and free unclosed +statements when the connection is terminated. + diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/CHANGELOG.rdoc b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/CHANGELOG.rdoc new file mode 100644 index 0000000..00cfa99 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/CHANGELOG.rdoc @@ -0,0 +1,318 @@ +=== 1.4.2 + +* Travis: Drop unused setting "sudo: false" +* The taint mechanism will be deprecated in Ruby 2.7 +* Fix Ruby 2.7 rb_check_safe_obj warnings +* Update travis config + +=== 1.4.1 + +* Don't mandate dl functions for the extention build +* bumping version + +=== 1.4.0 + +* Enhancements + * Better aggregator support + +* Bugfixes + * Various + +=== 1.3.13 + +* Enancements + * Support SQLite flags when defining functions + * Add definition for SQLITE_DETERMINISTIC flag + +=== 1.3.12 + +* Bugfixes: + * OS X install will default to homebrew if available. Fixes #195 + +=== 1.3.11 / 2015-10-10 + +* Enhancements: + * Windows: build against SQLite 3.8.11.1 + +* Internal: + * Use rake-compiler-dock to build Windows binaries. Pull #159 [larskanis] + * Expand Ruby versions being tested for Travis and AppVeyor + +=== 1.3.10 / 2014-10-30 + +* Enhancements: + * Windows: build against SQLite 3.8.6. Closes #135 [Hubro] + +=== 1.3.9 / 2014-02-25 + +* Bugfixes: + * Reset exception message. Closes #80 + * Reduce warnings due unused pointers. Closes #89 + * Add BSD-3 license reference to gemspec. Refs #99 and #106 + +=== 1.3.8 / 2013-08-17 + +* Enhancements: + * Windows: build against SQLite 3.7.17 + +* Bugfixes: + * Reset exception message. Closes #80 + * Correctly convert BLOB values to Ruby. Closes #65 + * Add MIT license reference to gemspec. Closes #99 + * Remove unused pointer. Closes #89 + +* Internal: + * Backport improvements in cross compilation for Windows + * Use of Minitest for internal tests + * Use Gemfile (generated by Hoe) to deal with dependencies + * Cleanup Travis CI + +=== 1.3.7 / 2013-01-11 + +* Bugfixes + * Closing a bad statement twice will not segv. + * Aggregate handlers are initialized on each query. Closes #44 + +* Internal + * Unset environment variables that could affect cross compilation. + +=== 1.3.6 / 2012-04-16 + +* Enhancements + * Windows: build against SQLite 3.7.11 + * Added SQLite3::ResultSet#each_hash for fetching each row as a hash. + * Added SQLite3::ResultSet#next_hash for fetching one row as a hash. + +* Bugfixes + * Support both UTF-16LE and UTF-16BE encoding modes on PPC. Closes #63 + * Protect parameters to custom functions from being garbage collected too + soon. Fixes #60. Thanks hirataya! + * Fix backwards compatibility with 1.2.5 with bind vars and `query` method. + Fixes #35. + * Fix double definition error caused by defining sqlite3_int64/uint64. + * Fix suspicious version regexp. + +* Deprecations + * ArrayWithTypesAndFields#types is deprecated and the class will be removed + in version 2.0.0. Please use the `types` method on the ResultSet class + that created this object. + * ArrayWithTypesAndFields#fields is deprecated and the class will be removed + in version 2.0.0. Please use the `columns` method on the ResultSet class + that created this object. + * The ArrayWithTypesAndFields class will be removed in 2.0.0 + * The ArrayWithTypes class will be removed in 2.0.0 + * HashWithTypesAndFields#types is deprecated and the class will be removed + in version 2.0.0. Please use the `types` method on the ResultSet class + that created this object. + * HashWithTypesAndFields#fields is deprecated and the class will be removed + in version 2.0.0. Please use the `columns` method on the ResultSet class + that created this object. + +=== 1.3.5 / 2011-12-03 - ZOMG Holidays are here Edition! + +* Enhancements + * Windows: build against SQLite 3.7.9 + * Static: enable SQLITE_ENABLE_COLUMN_METADATA + * Added Statement#clear_bindings! to set bindings back to nil + +* Bugfixes + * Fixed a segv on Database.new. Fixes #34 (thanks nobu!) + * Database error is not reset, so don't check it in Statement#reset! + * Remove conditional around Bignum statement bindings. + Fixes #52. Fixes #56. Thank you Evgeny Myasishchev. + +* Internal + * Use proper endianness when testing database connection with UTF-16. + Fixes #40. Fixes #51 + * Use -fPIC for static compilation when host is x86_64. + +=== 1.3.4 / 2011-07-25 + +* Enhancements: + * Windows: build against SQLite 3.7.7.1 + * Windows: build static binaries that do not depend on sqlite3.dll be + installed anymore + +* Bugfixes + * Backup API is conditionaly required so that older libsqlite3 can be used. + Thanks Hongli Lai. + * Fixed segmentation fault when nil is passed to SQLite3::Statement.new + * Fix extconf's hardcoded path that affected installation on certain systems. + +=== 1.3.3 / 2010-01-16 + +* Bugfixes + * Abort on installation if sqlite3_backup_init is missing. Fixes #19 + * Gem has been renamed to 'sqlite3'. Please use `gem install sqlite3` + +=== 1.3.2 / 2010-10-30 / RubyConf Uruguay Edition! + +* Enhancements: + * Windows: build against 3.7.3 version of SQLite3 + * SQLite3::Database can now be open as readonly + + db = SQLite3::Database.new('my.db', :readonly => true) + + * Added SQLite3::SQLITE_VERSION and SQLite3::SQLITE_VERSION_NUMBER [nurse] + +* Bugfixes + * type_translation= works along with Database#execute and a block + * defined functions are kept in a hash to prevent GC. #7 + * Removed GCC specific flags from extconf. + +* DEPRECATIONS + * SQLite3::Database#type_translation= will be deprecated in the future with + no replacement. + * SQlite3::Version will be deprecated in 2.0.0 with SQLite3::VERSION as the + replacement. + +=== 1.3.1 / 2010-07-09 + +* Enhancements + * Custom collations may be defined using SQLite3::Database#collation + +* Bugfixes + * Statements returning 0 columns are automatically stepped. [RF #28308] + * SQLite3::Database#encoding works on 1.8 and 1.9 + +=== 1.3.0 / 2010-06-06 + +* Enhancements + * Complete rewrite of C-based adapter from SWIG to hand-crafted one [tenderlove] + See API_CHANGES document for details. + This closes: Bug #27300, Bug #27241, Patch #16020 + * Improved UTF, Unicode, M17N, all that handling and proper BLOB handling [tenderlove, nurse] + * Added support for type translations [tenderlove] + + @db.translator.add_translator('sometime') do |type, thing| + 'output' # this will be returned as value for that column + end + +* Experimental + * Added API to access and load extensions. [kashif] + These functions maps directly into SQLite3 own enable_load_extension() + and load_extension() C-API functions. See SQLite3::Database API documentation for details. + This closes: Patches #9178 + +* Bugfixes + * Corrected gem dependencies (runtime and development) + * Fixed threaded tests [Alexey Borzenkov] + * Removed GitHub gemspec + * Fixed "No definition for" warnings from RDoc + * Generate zip and tgz files for releases + * Added Luis Lavena as gem Author (maintainer) + * Prevent mkmf interfere with Mighty Snow Leopard + * Allow extension compilation search for common lib paths [kashif] + (lookup /usr/local, /opt/local and /usr) + * Corrected extension compilation under MSVC [romuloceccon] + * Define load_extension functionality based on availability [tenderlove] + * Deprecation notices for Database#query. Fixes RF #28192 + +=== 1.3.0.beta.2 / 2010-05-15 + +* Enhancements + * Added support for type translations [tenderlove] + + @db.translator.add_translator('sometime') do |type, thing| + 'output' # this will be returned as value for that column + end + +* Bugfixes + * Allow extension compilation search for common lib paths [kashif] + (lookup /usr/local, /opt/local and /usr) + * Corrected extension compilation under MSVC [romuloceccon] + * Define load_extension functionality based on availability [tenderlove] + * Deprecation notices for Database#query. Fixes RF #28192 + +=== 1.3.0.beta.1 / 2010-05-10 + +* Enhancements + * Complete rewrite of C-based adapter from SWIG to hand-crafted one [tenderlove] + See API_CHANGES document for details. + This closes: Bug #27300, Bug #27241, Patch #16020 + * Improved UTF, Unicode, M17N, all that handling and proper BLOB handling [tenderlove, nurse] + +* Experimental + * Added API to access and load extensions. [kashif] + These functions maps directly into SQLite3 own enable_load_extension() + and load_extension() C-API functions. See SQLite3::Database API documentation for details. + This closes: Patches #9178 + +* Bugfixes + * Corrected gem dependencies (runtime and development) + * Fixed threaded tests [Alexey Borzenkov] + * Removed GitHub gemspec + * Fixed "No definition for" warnings from RDoc + * Generate zip and tgz files for releases + * Added Luis Lavena as gem Author (maintainer) + * Prevent mkmf interfere with Mighty Snow Leopard + +=== 1.2.5 / 25 Jul 2009 + +* Check for illegal nil before executing SQL [Erik Veenstra] +* Switch to Hoe for gem task management and packaging. +* Advertise rake-compiler as development dependency. +* Build gem binaries for Windows. +* Improved Ruby 1.9 support compatibility. +* Taint returned values. Patch #20325. +* Database.open and Database.new now take an optional block [Gerrit Kaiser] + + +=== 1.2.4.1 (internal) / 5 Jul 2009 + +* Check for illegal nil before executing SQL [Erik Veenstra] +* Switch to Hoe for gem task management and packaging. +* Advertise rake-compiler as development dependency. +* Build gem binaries for Windows. +* Improved Ruby 1.9 support compatibility. + + +=== 1.2.4 / 27 Aug 2008 + +* Package the updated C file for source builds. [Jamis Buck] + + +=== 1.2.3 / 26 Aug 2008 + +* Fix incorrect permissions on database.rb and translator.rb [Various] + +* Avoid using Object#extend for greater speedups [Erik Veenstra] + +* Ruby 1.9 compatibility tweaks for Array#zip [jimmy88@gmail.com] + +* Fix linking against Ruby 1.8.5 [Rob Holland ] + + +=== 1.2.2 / 31 May 2008 + +* Make the table_info method adjust the returned default value for the rows + so that the sqlite3 change in 3.3.8 and greater can be handled + transparently [Jamis Buck ] + +* Ruby 1.9 compatibility tweaks [Roman Le Negrate ] + +* Various performance enhancements [thanks Erik Veenstra] + +* Correct busy_handler documentation [Rob Holland ] + +* Use int_bind64 on Fixnum values larger than a 32bit C int can take. [Rob Holland ] + +* Work around a quirk in SQLite's error reporting by calling sqlite3_reset + to produce a more informative error code upon a failure from + sqlite3_step. [Rob Holland ] + +* Various documentation, test, and style tweaks [Rob Holland ] + +* Be more granular with time/data translation [Rob Holland ] + +* Use Date directly for parsing rather than going via Time [Rob Holland ] + +* Check for the rt library and fdatasync so we link against that when + needed [Rob Holland ] + +* Rename data structures to avoid collision on win32. based on patch + by: Luis Lavena [Rob Holland ] + +* Add test for defaults [Daniel Rodríguez Troitiño] + +* Correctly unquote double-quoted pragma defaults [Łukasz Dargiewicz ] diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ChangeLog.cvs b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ChangeLog.cvs new file mode 100644 index 0000000..6e9dd51 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ChangeLog.cvs @@ -0,0 +1,88 @@ +2005-01-05 09:40 minam + + * Rakefile, sqlite3-ruby-win32.gemspec, sqlite3-ruby.gemspec: Added + win32 gem. + +2005-01-05 07:31 minam + + * Rakefile, test/tc_integration.rb, test/tests.rb: Added + native-vs-dl benchmark to Rakefile. Added SQLITE3_DRIVERS + environment variable to integration test to specify which + driver(s) should be tested (defaults to "Native"). + +2005-01-04 14:26 minam + + * ext/sqlite3_api/sqlite3_api.i, lib/sqlite3/database.rb, + lib/sqlite3/driver/native/driver.rb, test/tc_database.rb, + test/tc_integration.rb, test/tests.rb: Unit tests: done. Bugs: + fixed. + +2005-01-03 23:13 minam + + * ext/sqlite3_api/sqlite3_api.i, lib/sqlite3/database.rb, + lib/sqlite3/driver/dl/driver.rb, + lib/sqlite3/driver/native/driver.rb, test/tc_integration.rb: + Custom functions (aggregate and otherwise) are supported by the + native driver now. Test cases for the same. + +2005-01-03 13:51 minam + + * ext/sqlite3_api/MANIFEST, ext/sqlite3_api/extconf.rb, + ext/sqlite3_api/post-clean.rb, ext/sqlite3_api/post-distclean.rb, + ext/sqlite3_api/sqlite3_api.i, lib/sqlite3/database.rb, + lib/sqlite3/resultset.rb, lib/sqlite3/version.rb, + lib/sqlite3/driver/dl/driver.rb, + lib/sqlite3/driver/native/driver.rb, test/native-vs-dl.rb, + test/tc_integration.rb: Added preliminary implementation of + native driver (swig-based), and integration tests. + +2004-12-29 19:37 minam + + * lib/sqlite3/driver/dl/driver.rb: Some fixes to allow the DL + driver to work with Ruby 1.8.1. + +2004-12-29 14:52 minam + + * lib/sqlite3/: database.rb, version.rb: Made #quote a class method + (again). Bumped version to 0.6. + +2004-12-25 22:59 minam + + * lib/sqlite3/driver/dl/api.rb: Added check for darwin in supported + platforms (thanks to bitsweat). + +2004-12-22 12:38 minam + + * Rakefile: Rakefile wasn't packaging the README file. + +2004-12-21 22:28 minam + + * Rakefile, sqlite3-ruby.gemspec, test/bm.rb: Packaging now works. + Added benchmarks. + +2004-12-21 21:45 minam + + * LICENSE, README, Rakefile, setup.rb, sqlite3-ruby.gemspec, + doc/faq/faq.rb, doc/faq/faq.yml, lib/sqlite3.rb, + lib/sqlite3/statement.rb, lib/sqlite3/constants.rb, + lib/sqlite3/database.rb, lib/sqlite3/resultset.rb, + lib/sqlite3/translator.rb, lib/sqlite3/value.rb, + lib/sqlite3/version.rb, lib/sqlite3/errors.rb, + lib/sqlite3/pragmas.rb, lib/sqlite3/driver/dl/api.rb, + lib/sqlite3/driver/dl/driver.rb, test/mocks.rb, + test/tc_database.rb, test/tests.rb, test/driver/dl/tc_driver.rb: + Initial import + +2004-12-21 21:45 minam + + * LICENSE, README, Rakefile, setup.rb, sqlite3-ruby.gemspec, + doc/faq/faq.rb, doc/faq/faq.yml, lib/sqlite3.rb, + lib/sqlite3/statement.rb, lib/sqlite3/constants.rb, + lib/sqlite3/database.rb, lib/sqlite3/resultset.rb, + lib/sqlite3/translator.rb, lib/sqlite3/value.rb, + lib/sqlite3/version.rb, lib/sqlite3/errors.rb, + lib/sqlite3/pragmas.rb, lib/sqlite3/driver/dl/api.rb, + lib/sqlite3/driver/dl/driver.rb, test/mocks.rb, + test/tc_database.rb, test/tests.rb, test/driver/dl/tc_driver.rb: + Initial revision + diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/Gemfile b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/Gemfile new file mode 100644 index 0000000..866b428 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/Gemfile @@ -0,0 +1,17 @@ +# -*- ruby -*- + +# DO NOT EDIT THIS FILE. Instead, edit Rakefile, and run `rake bundler:gemfile`. + +source "https://rubygems.org/" + + +gem "minitest", "~>5.11", :group => [:development, :test] +gem "rake-compiler", "~>1.0", :group => [:development, :test] +gem "rake-compiler-dock", "~>0.6.0", :group => [:development, :test] +gem "mini_portile", "~>0.6.2", :group => [:development, :test] +gem "hoe-bundler", "~>1.0", :group => [:development, :test] +gem "hoe-gemspec", "~>1.0", :group => [:development, :test] +gem "rdoc", ">=4.0", "<6", :group => [:development, :test] +gem "hoe", "~>3.17", :group => [:development, :test] + +# vim: syntax=ruby diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/LICENSE b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/LICENSE new file mode 100644 index 0000000..75c0682 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2004, Jamis Buck (jamis@jamisbuck.org) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/Manifest.txt b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/Manifest.txt new file mode 100644 index 0000000..01da367 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/Manifest.txt @@ -0,0 +1,60 @@ +.gemtest +.travis.yml +API_CHANGES.rdoc +CHANGELOG.rdoc +ChangeLog.cvs +Gemfile +LICENSE +Manifest.txt +README.rdoc +Rakefile +appveyor.yml +ext/sqlite3/aggregator.c +ext/sqlite3/aggregator.h +ext/sqlite3/backup.c +ext/sqlite3/backup.h +ext/sqlite3/database.c +ext/sqlite3/database.h +ext/sqlite3/exception.c +ext/sqlite3/exception.h +ext/sqlite3/extconf.rb +ext/sqlite3/sqlite3.c +ext/sqlite3/sqlite3_ruby.h +ext/sqlite3/statement.c +ext/sqlite3/statement.h +faq/faq.rb +faq/faq.yml +lib/sqlite3.rb +lib/sqlite3/constants.rb +lib/sqlite3/database.rb +lib/sqlite3/errors.rb +lib/sqlite3/pragmas.rb +lib/sqlite3/resultset.rb +lib/sqlite3/statement.rb +lib/sqlite3/translator.rb +lib/sqlite3/value.rb +lib/sqlite3/version.rb +rakelib/faq.rake +rakelib/gem.rake +rakelib/native.rake +rakelib/vendor_sqlite3.rake +setup.rb +test/helper.rb +test/test_backup.rb +test/test_collation.rb +test/test_database.rb +test/test_database_flags.rb +test/test_database_readonly.rb +test/test_database_readwrite.rb +test/test_deprecated.rb +test/test_encoding.rb +test/test_integration.rb +test/test_integration_aggregate.rb +test/test_integration_open_close.rb +test/test_integration_pending.rb +test/test_integration_resultset.rb +test/test_integration_statement.rb +test/test_result_set.rb +test/test_sqlite3.rb +test/test_statement.rb +test/test_statement_execute.rb diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/README.rdoc b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/README.rdoc new file mode 100644 index 0000000..9ef8576 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/README.rdoc @@ -0,0 +1,118 @@ += SQLite3/Ruby Interface + +* https://github.com/sparklemotion/sqlite3-ruby +* http://groups.google.com/group/sqlite3-ruby +* http://rubygems.org/gems/sqlite3 +* http://www.rubydoc.info/gems/sqlite3/frames + +{Build Status}[https://travis-ci.org/sparklemotion/sqlite3-ruby] + +== DESCRIPTION + +This module allows Ruby programs to interface with the SQLite3 +database engine (http://www.sqlite.org). You must have the +SQLite engine installed in order to build this module. + +Note that this module is only compatible with SQLite 3.6.16 or newer. + +== SYNOPSIS + + require "sqlite3" + + # Open a database + db = SQLite3::Database.new "test.db" + + # Create a table + rows = db.execute <<-SQL + create table numbers ( + name varchar(30), + val int + ); + SQL + + # Execute a few inserts + { + "one" => 1, + "two" => 2, + }.each do |pair| + db.execute "insert into numbers values ( ?, ? )", pair + end + + # Find a few rows + db.execute( "select * from numbers" ) do |row| + p row + end + + # Create another table with multiple columns + + db.execute <<-SQL + create table students ( + name varchar(50), + email varchar(50), + grade varchar(5), + blog varchar(50) + ); + SQL + + # Execute inserts with parameter markers + db.execute("INSERT INTO students (name, email, grade, blog) + VALUES (?, ?, ?, ?)", ["Jane", "me@janedoe.com", "A", "http://blog.janedoe.com"]) + + db.execute( "select * from students" ) do |row| + p row + end + + +== Compilation and Installation + +Install SQLite3, enabling the option SQLITE_ENABLE_COLUMN_METADATA (see +www.sqlite.org/compile.html for details). + +Then do the following: + + ruby setup.rb config + ruby setup.rb setup + ruby setup.rb install + +Alternatively, you can download and install the RubyGem package for +SQLite3/Ruby (you must have RubyGems and SQLite3 installed, first): + + gem install sqlite3 + +If you have sqlite3 installed in a non-standard location, you can specify the location of the include and lib files by doing: + + gem install sqlite3 -- --with-sqlite3-include=/opt/local/include \ + --with-sqlite3-lib=/opt/local/lib + += SUPPORT!!! + +== OMG! Something has gone wrong! Where do I get help? + +The best place to get help is from the +{sqlite3-ruby mailing list}[http://groups.google.com/group/sqlite3-ruby] which +can be found here: + + * http://groups.google.com/group/sqlite3-ruby + +== I've found a bug! Where do I file it? + +Uh oh. After contacting the mailing list, you've found that you've actually +discovered a bug. You can file the bug at the +{github issues page}[https://github.com/sparklemotion/sqlite3-ruby/issues] +which can be found here: + + * https://github.com/sparklemotion/sqlite3-ruby/issues + +== Usage + +For help figuring out the SQLite3/Ruby interface, check out the +SYNOPSIS as well as the RDoc. It includes examples of +usage. If you have any questions that you feel should be addressed in the +FAQ, please send them to {the mailing list}[http://groups.google.com/group/sqlite3-ruby] + +== Source Code + +The source repository is accessible via git: + + git clone git://github.com/sparklemotion/sqlite3-ruby.git + diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/Rakefile b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/Rakefile new file mode 100644 index 0000000..d947cf8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/Rakefile @@ -0,0 +1,8 @@ +# +# NOTE: Keep this file clean. +# Add your customizations inside tasks directory. +# Thank You. +# + + +# vim: syntax=ruby diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/appveyor.yml b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/appveyor.yml new file mode 100644 index 0000000..57725f0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/appveyor.yml @@ -0,0 +1,36 @@ +--- +version: "{build}" +branches: + only: + - master + - 1-3-stable +clone_depth: 10 +install: + - SET PATH=C:\Ruby%ruby_version%\bin;%PATH% + - ruby --version + - gem --version + - gem install bundler --quiet --no-ri --no-rdoc + - bundler --version + - bundle install +build_script: + - rake native gem +test_script: + - rake test +artifacts: + - path: pkg\*.gem + +environment: + matrix: + - ruby_version: "193" + - ruby_version: "200" + - ruby_version: "200-x64" + - ruby_version: "21" + - ruby_version: "21-x64" + - ruby_version: "22" + - ruby_version: "22-x64" + - ruby_version: "23" + - ruby_version: "23-x64" + - ruby_version: "24" + - ruby_version: "24-x64" + - ruby_version: "25" + - ruby_version: "25-x64" diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/.sitearchdir.-.sqlite3.time b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/.sitearchdir.-.sqlite3.time new file mode 100644 index 0000000..e69de29 diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/Makefile b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/Makefile new file mode 100644 index 0000000..0c2f898 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/Makefile @@ -0,0 +1,266 @@ + +SHELL = /bin/sh + +# V=0 quiet, V=1 verbose. other values don't work. +V = 0 +Q1 = $(V:1=) +Q = $(Q1:0=@) +ECHO1 = $(V:1=@ :) +ECHO = $(ECHO1:0=@ echo) +NULLCMD = : + +#### Start of system configuration section. #### + +srcdir = . +topdir = /usr/include/ruby-3.0.0 +hdrdir = $(topdir) +arch_hdrdir = /usr/include/ruby-3.0.0/x86_64-linux +PATH_SEPARATOR = : +VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby +prefix = $(DESTDIR)/usr +rubysitearchprefix = $(rubylibprefix)/$(sitearch) +rubyarchprefix = $(rubylibprefix)/$(arch) +rubylibprefix = $(libdir)/$(RUBY_BASE_NAME) +exec_prefix = $(prefix) +vendorarchhdrdir = $(vendorhdrdir)/$(sitearch) +sitearchhdrdir = $(sitehdrdir)/$(sitearch) +rubyarchhdrdir = $(rubyhdrdir)/$(arch) +vendorhdrdir = $(rubyhdrdir)/vendor_ruby +sitehdrdir = $(rubyhdrdir)/site_ruby +rubyhdrdir = $(includedir)/$(RUBY_VERSION_NAME) +vendorarchdir = $(vendorlibdir)/$(sitearch) +vendorlibdir = $(vendordir)/$(ruby_version) +vendordir = $(rubylibprefix)/vendor_ruby +sitearchdir = $(DESTDIR)./.gem.20220424-672384-xzlu6m +sitelibdir = $(DESTDIR)./.gem.20220424-672384-xzlu6m +sitedir = $(rubylibprefix)/site_ruby +rubyarchdir = $(rubylibdir)/$(arch) +rubylibdir = $(rubylibprefix)/$(ruby_version) +sitearchincludedir = $(includedir)/$(sitearch) +archincludedir = $(includedir)/$(arch) +sitearchlibdir = $(libdir)/$(sitearch) +archlibdir = $(libdir)/$(arch) +ridir = $(datarootdir)/$(RI_BASE_NAME) +mandir = $(datarootdir)/man +localedir = $(datarootdir)/locale +libdir = $(exec_prefix)/lib +psdir = $(docdir) +pdfdir = $(docdir) +dvidir = $(docdir) +htmldir = $(docdir) +infodir = $(datarootdir)/info +docdir = $(datarootdir)/doc/$(PACKAGE) +oldincludedir = $(DESTDIR)/usr/include +includedir = $(prefix)/include +runstatedir = $(localstatedir)/run +localstatedir = $(DESTDIR)/var +sharedstatedir = $(DESTDIR)/var/lib +sysconfdir = $(DESTDIR)/etc +datadir = $(datarootdir) +datarootdir = $(prefix)/share +libexecdir = $(DESTDIR)/usr/lib/ruby +sbindir = $(exec_prefix)/sbin +bindir = $(exec_prefix)/bin +archdir = $(rubyarchdir) + + +CC_WRAPPER = +CC = gcc +CXX = g++ +LIBRUBY = $(LIBRUBY_SO) +LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a +LIBRUBYARG_SHARED = -l$(RUBY_SO_NAME) +LIBRUBYARG_STATIC = -l$(RUBY_SO_NAME)-static $(MAINLIBS) +empty = +OUTFLAG = -o $(empty) +COUTFLAG = -o $(empty) +CSRCFLAG = $(empty) + +RUBY_EXTCONF_H = +cflags = $(optflags) $(debugflags) $(warnflags) +cxxflags = +optflags = -O3 +debugflags = -ggdb3 +warnflags = -Wall -Wextra -Wdeprecated-declarations -Wduplicated-cond -Wimplicit-function-declaration -Wimplicit-int -Wmisleading-indentation -Wpointer-arith -Wwrite-strings -Wimplicit-fallthrough=0 -Wmissing-noreturn -Wno-cast-function-type -Wno-constant-logical-operand -Wno-long-long -Wno-missing-field-initializers -Wno-overlength-strings -Wno-packed-bitfield-compat -Wno-parentheses-equality -Wno-self-assign -Wno-tautological-compare -Wno-unused-parameter -Wno-unused-value -Wsuggest-attribute=format -Wsuggest-attribute=noreturn -Wunused-variable +cppflags = +CCDLFLAGS = -fPIC +CFLAGS = $(CCDLFLAGS) -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -fPIC $(ARCH_FLAG) +INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir) +DEFS = +CPPFLAGS = -DHAVE_RB_PROC_ARITY -DHAVE_RB_INTEGER_PACK -DHAVE_SQLITE3_INITIALIZE -DHAVE_SQLITE3_BACKUP_INIT -DHAVE_SQLITE3_COLUMN_DATABASE_NAME -DHAVE_SQLITE3_ENABLE_LOAD_EXTENSION -DHAVE_SQLITE3_LOAD_EXTENSION -DHAVE_SQLITE3_OPEN_V2 -DHAVE_SQLITE3_PREPARE_V2 -DHAVE_TYPE_SQLITE3_INT64 -DHAVE_TYPE_SQLITE3_UINT64 $(DEFS) $(cppflags) +CXXFLAGS = $(CCDLFLAGS) -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions -Wp,-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-clash-protection -fcf-protection -Wp,-D_GLIBCXX_ASSERTIONS $(ARCH_FLAG) +ldflags = -L. -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed +dldflags = -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -Wl,--compress-debug-sections=zlib +ARCH_FLAG = +DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG) +LDSHARED = $(CC) -shared +LDSHAREDXX = $(CXX) -shared +AR = gcc-ar +EXEEXT = + +RUBY_INSTALL_NAME = $(RUBY_BASE_NAME) +RUBY_SO_NAME = ruby +RUBYW_INSTALL_NAME = +RUBY_VERSION_NAME = $(RUBY_BASE_NAME)-$(ruby_version) +RUBYW_BASE_NAME = rubyw +RUBY_BASE_NAME = ruby + +arch = x86_64-linux +sitearch = $(arch) +ruby_version = 3.0.0 +ruby = $(bindir)/$(RUBY_BASE_NAME) +RUBY = $(ruby) +ruby_headers = $(hdrdir)/ruby.h $(hdrdir)/ruby/backward.h $(hdrdir)/ruby/ruby.h $(hdrdir)/ruby/defines.h $(hdrdir)/ruby/missing.h $(hdrdir)/ruby/intern.h $(hdrdir)/ruby/st.h $(hdrdir)/ruby/subst.h $(arch_hdrdir)/ruby/config.h + +RM = rm -f +RM_RF = $(RUBY) -run -e rm -- -rf +RMDIRS = rmdir --ignore-fail-on-non-empty -p +MAKEDIRS = /usr/bin/mkdir -p +INSTALL = /usr/bin/install -c +INSTALL_PROG = $(INSTALL) -m 0755 +INSTALL_DATA = $(INSTALL) -m 644 +COPY = cp +TOUCH = exit > + +#### End of system configuration section. #### + +preload = +libpath = . $(libdir) +LIBPATH = -L. -L$(libdir) +DEFFILE = + +CLEANFILES = mkmf.log +DISTCLEANFILES = +DISTCLEANDIRS = + +extout = +extout_prefix = +target_prefix = /sqlite3 +LOCAL_LIBS = +LIBS = $(LIBRUBYARG_SHARED) -lsqlite3 -ldl -lpthread -lsqlite3 -lm -lc +ORIG_SRCS = aggregator.c backup.c database.c exception.c sqlite3.c statement.c +SRCS = $(ORIG_SRCS) +OBJS = aggregator.o backup.o database.o exception.o sqlite3.o statement.o +HDRS = $(srcdir)/aggregator.h $(srcdir)/backup.h $(srcdir)/database.h $(srcdir)/exception.h $(srcdir)/sqlite3_ruby.h $(srcdir)/statement.h +LOCAL_HDRS = +TARGET = sqlite3_native +TARGET_NAME = sqlite3_native +TARGET_ENTRY = Init_$(TARGET_NAME) +DLLIB = $(TARGET).so +EXTSTATIC = +STATIC_LIB = + +TIMESTAMP_DIR = . +BINDIR = $(bindir) +RUBYCOMMONDIR = $(sitedir)$(target_prefix) +RUBYLIBDIR = $(sitelibdir)$(target_prefix) +RUBYARCHDIR = $(sitearchdir)$(target_prefix) +HDRDIR = $(sitehdrdir)$(target_prefix) +ARCHHDRDIR = $(sitearchhdrdir)$(target_prefix) +TARGET_SO_DIR = +TARGET_SO = $(TARGET_SO_DIR)$(DLLIB) +CLEANLIBS = $(TARGET_SO) +CLEANOBJS = *.o *.bak + +all: $(DLLIB) +static: $(STATIC_LIB) +.PHONY: all install static install-so install-rb +.PHONY: clean clean-so clean-static clean-rb + +clean-static:: +clean-rb-default:: +clean-rb:: +clean-so:: +clean: clean-so clean-static clean-rb-default clean-rb + -$(Q)$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES) .*.time + +distclean-rb-default:: +distclean-rb:: +distclean-so:: +distclean-static:: +distclean: clean distclean-so distclean-static distclean-rb-default distclean-rb + -$(Q)$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log + -$(Q)$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES) + -$(Q)$(RMDIRS) $(DISTCLEANDIRS) 2> /dev/null || true + +realclean: distclean +install: install-so install-rb + +install-so: $(DLLIB) $(TIMESTAMP_DIR)/.sitearchdir.-.sqlite3.time + $(INSTALL_PROG) $(DLLIB) $(RUBYARCHDIR) +clean-static:: + -$(Q)$(RM) $(STATIC_LIB) +install-rb: pre-install-rb do-install-rb install-rb-default +install-rb-default: pre-install-rb-default do-install-rb-default +pre-install-rb: Makefile +pre-install-rb-default: Makefile +do-install-rb: +do-install-rb-default: +pre-install-rb-default: + @$(NULLCMD) +$(TIMESTAMP_DIR)/.sitearchdir.-.sqlite3.time: + $(Q) $(MAKEDIRS) $(@D) $(RUBYARCHDIR) + $(Q) $(TOUCH) $@ + +site-install: site-install-so site-install-rb +site-install-so: install-so +site-install-rb: install-rb + +.SUFFIXES: .c .m .cc .mm .cxx .cpp .o .S + +.cc.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cc.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.mm.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.mm.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.cxx.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cxx.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.cpp.o: + $(ECHO) compiling $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.cpp.S: + $(ECHO) translating $(<) + $(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.c.o: + $(ECHO) compiling $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.c.S: + $(ECHO) translating $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +.m.o: + $(ECHO) compiling $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$< + +.m.S: + $(ECHO) translating $(<) + $(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$< + +$(TARGET_SO): $(OBJS) Makefile + $(ECHO) linking shared-object sqlite3/$(DLLIB) + -$(Q)$(RM) $(@) + $(Q) $(LDSHARED) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS) + + + +$(OBJS): $(HDRS) $(ruby_headers) diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/aggregator.c b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/aggregator.c new file mode 100644 index 0000000..df84ff3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/aggregator.c @@ -0,0 +1,273 @@ +#include +#include + +/* wraps a factory "handler" class. The "-aggregators" instance variable of + * the SQLite3::Database holds an array of all AggrogatorWrappers. + * + * An AggregatorWrapper holds the following instance variables: + * -handler_klass: the handler that creates the instances. + * -instances: array of all the cAggregatorInstance objects currently + * in-flight for this aggregator. */ +static VALUE cAggregatorWrapper; + +/* wraps a intance of the "handler" class. Loses its reference at the end of + * the xFinal callback. + * + * An AggregatorInstance holds the following instnace variables: + * -handler_instance: the instance to call `step` and `finalize` on. + * -exc_status: status returned by rb_protect. + * != 0 if an exception occurred. If an exception occured + * `step` and `finalize` won't be called any more. */ +static VALUE cAggregatorInstance; + +typedef struct rb_sqlite3_protected_funcall_args { + VALUE self; + ID method; + int argc; + VALUE *params; +} protected_funcall_args_t; + +/* why isn't there something like this in the ruby API? */ +static VALUE +rb_sqlite3_protected_funcall_body(VALUE protected_funcall_args_ptr) +{ + protected_funcall_args_t *args = + (protected_funcall_args_t*)protected_funcall_args_ptr; + + return rb_funcall2(args->self, args->method, args->argc, args->params); +} + +static VALUE +rb_sqlite3_protected_funcall(VALUE self, ID method, int argc, VALUE *params, + int* exc_status) +{ + protected_funcall_args_t args = { + .self = self, .method = method, .argc = argc, .params = params + }; + return rb_protect(rb_sqlite3_protected_funcall_body, (VALUE)(&args), exc_status); +} + +/* called in rb_sqlite3_aggregator_step and rb_sqlite3_aggregator_final. It + * checks if the exection context already has an associated instance. If it + * has one, it returns it. If there is no instance yet, it creates one and + * associates it with the context. */ +static VALUE +rb_sqlite3_aggregate_instance(sqlite3_context *ctx) +{ + VALUE aw = (VALUE) sqlite3_user_data(ctx); + VALUE handler_klass = rb_iv_get(aw, "-handler_klass"); + VALUE inst; + VALUE *inst_ptr = sqlite3_aggregate_context(ctx, (int)sizeof(VALUE)); + + if (!inst_ptr) { + rb_fatal("SQLite is out-of-merory"); + } + + inst = *inst_ptr; + + if (inst == Qfalse) { /* Qfalse == 0 */ + VALUE instances = rb_iv_get(aw, "-instances"); + int exc_status; + + inst = rb_class_new_instance(0, NULL, cAggregatorInstance); + rb_iv_set(inst, "-handler_instance", rb_sqlite3_protected_funcall( + handler_klass, rb_intern("new"), 0, NULL, &exc_status)); + rb_iv_set(inst, "-exc_status", INT2NUM(exc_status)); + + rb_ary_push(instances, inst); + + *inst_ptr = inst; + } + + if (inst == Qnil) { + rb_fatal("SQLite called us back on an already destroyed aggregate instance"); + } + + return inst; +} + +/* called by rb_sqlite3_aggregator_final. Unlinks and frees the + * aggregator_instance_t, so the handler_instance won't be marked any more + * and Ruby's GC may free it. */ +static void +rb_sqlite3_aggregate_instance_destroy(sqlite3_context *ctx) +{ + VALUE aw = (VALUE) sqlite3_user_data(ctx); + VALUE instances = rb_iv_get(aw, "-instances"); + VALUE *inst_ptr = sqlite3_aggregate_context(ctx, 0); + VALUE inst; + + if (!inst_ptr || (inst = *inst_ptr)) { + return; + } + + if (inst == Qnil) { + rb_fatal("attempt to destroy aggregate instance twice"); + } + + rb_iv_set(inst, "-handler_instance", Qnil); // may catch use-after-free + if (rb_ary_delete(instances, inst) == Qnil) { + rb_fatal("must be in instances at that point"); + } + + *inst_ptr = Qnil; +} + +static void +rb_sqlite3_aggregator_step(sqlite3_context * ctx, int argc, sqlite3_value **argv) +{ + VALUE inst = rb_sqlite3_aggregate_instance(ctx); + VALUE handler_instance = rb_iv_get(inst, "-handler_instance"); + VALUE * params = NULL; + VALUE one_param; + int exc_status = NUM2INT(rb_iv_get(inst, "-exc_status")); + int i; + + if (exc_status) { + return; + } + + if (argc == 1) { + one_param = sqlite3val2rb(argv[0]); + params = &one_param; + } + if (argc > 1) { + params = xcalloc((size_t)argc, sizeof(VALUE)); + for(i = 0; i < argc; i++) { + params[i] = sqlite3val2rb(argv[i]); + } + } + rb_sqlite3_protected_funcall( + handler_instance, rb_intern("step"), argc, params, &exc_status); + if (argc > 1) { + xfree(params); + } + + rb_iv_set(inst, "-exc_status", INT2NUM(exc_status)); +} + +/* we assume that this function is only called once per execution context */ +static void +rb_sqlite3_aggregator_final(sqlite3_context * ctx) +{ + VALUE inst = rb_sqlite3_aggregate_instance(ctx); + VALUE handler_instance = rb_iv_get(inst, "-handler_instance"); + int exc_status = NUM2INT(rb_iv_get(inst, "-exc_status")); + + if (!exc_status) { + VALUE result = rb_sqlite3_protected_funcall( + handler_instance, rb_intern("finalize"), 0, NULL, &exc_status); + if (!exc_status) { + set_sqlite3_func_result(ctx, result); + } + } + + if (exc_status) { + /* the user should never see this, as Statement.step() will pick up the + * outstanding exception and raise it instead of generating a new one + * for SQLITE_ERROR with message "Ruby Exception occured" */ + sqlite3_result_error(ctx, "Ruby Exception occured", -1); + } + + rb_sqlite3_aggregate_instance_destroy(ctx); +} + +/* call-seq: define_aggregator2(aggregator) + * + * Define an aggregrate function according to a factory object (the "handler") + * that knows how to obtain to all the information. The handler must provide + * the following class methods: + * + * +arity+:: corresponds to the +arity+ parameter of #create_aggregate. This + * message is optional, and if the handler does not respond to it, + * the function will have an arity of -1. + * +name+:: this is the name of the function. The handler _must_ implement + * this message. + * +new+:: this must be implemented by the handler. It should return a new + * instance of the object that will handle a specific invocation of + * the function. + * + * The handler instance (the object returned by the +new+ message, described + * above), must respond to the following messages: + * + * +step+:: this is the method that will be called for each step of the + * aggregate function's evaluation. It should take parameters according + * to the *arity* definition. + * +finalize+:: this is the method that will be called to finalize the + * aggregate function's evaluation. It should not take arguments. + * + * Note the difference between this function and #create_aggregate_handler + * is that no FunctionProxy ("ctx") object is involved. This manifests in two + * ways: The return value of the aggregate function is the return value of + * +finalize+ and neither +step+ nor +finalize+ take an additional "ctx" + * parameter. + */ +VALUE +rb_sqlite3_define_aggregator2(VALUE self, VALUE aggregator, VALUE ruby_name) +{ + /* define_aggregator is added as a method to SQLite3::Database in database.c */ + sqlite3RubyPtr ctx; + int arity, status; + VALUE aw; + VALUE aggregators; + + Data_Get_Struct(self, sqlite3Ruby, ctx); + if (!ctx->db) { + rb_raise(rb_path2class("SQLite3::Exception"), "cannot use a closed database"); + } + + if (rb_respond_to(aggregator, rb_intern("arity"))) { + VALUE ruby_arity = rb_funcall(aggregator, rb_intern("arity"), 0); + arity = NUM2INT(ruby_arity); + } else { + arity = -1; + } + + if (arity < -1 || arity > 127) { +#ifdef PRIsVALUE + rb_raise(rb_eArgError, "%"PRIsVALUE" arity=%d out of range -1..127", + self, arity); +#else + rb_raise(rb_eArgError, "Aggregator arity=%d out of range -1..127", arity); +#endif + } + + if (!rb_ivar_defined(self, rb_intern("-aggregators"))) { + rb_iv_set(self, "-aggregators", rb_ary_new()); + } + aggregators = rb_iv_get(self, "-aggregators"); + + aw = rb_class_new_instance(0, NULL, cAggregatorWrapper); + rb_iv_set(aw, "-handler_klass", aggregator); + rb_iv_set(aw, "-instances", rb_ary_new()); + + status = sqlite3_create_function( + ctx->db, + StringValueCStr(ruby_name), + arity, + SQLITE_UTF8, + (void*)aw, + NULL, + rb_sqlite3_aggregator_step, + rb_sqlite3_aggregator_final + ); + + if (status != SQLITE_OK) { + rb_sqlite3_raise(ctx->db, status); + return self; // just in case rb_sqlite3_raise returns. + } + + rb_ary_push(aggregators, aw); + + return self; +} + +void +rb_sqlite3_aggregator_init(void) +{ + rb_gc_register_address(&cAggregatorWrapper); + rb_gc_register_address(&cAggregatorInstance); + /* rb_class_new generatos class with undefined allocator in ruby 1.9 */ + cAggregatorWrapper = rb_funcall(rb_cClass, rb_intern("new"), 0); + cAggregatorInstance = rb_funcall(rb_cClass, rb_intern("new"), 0); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/aggregator.h b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/aggregator.h new file mode 100644 index 0000000..68968d1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/aggregator.h @@ -0,0 +1,12 @@ +#ifndef SQLITE3_AGGREGATOR_RUBY +#define SQLITE3_AGGREGATOR_RUBY + +#include + +VALUE +rb_sqlite3_define_aggregator2(VALUE self, VALUE aggregator, VALUE ruby_name); + +void +rb_sqlite3_aggregator_init(void); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/aggregator.o b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/aggregator.o new file mode 100644 index 0000000..f4429cf Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/aggregator.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/backup.c b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/backup.c new file mode 100644 index 0000000..341df37 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/backup.c @@ -0,0 +1,168 @@ +#ifdef HAVE_SQLITE3_BACKUP_INIT + +#include + +#define REQUIRE_OPEN_BACKUP(_ctxt) \ + if(!_ctxt->p) \ + rb_raise(rb_path2class("SQLite3::Exception"), "cannot use a closed backup"); + +VALUE cSqlite3Backup; + +static void deallocate(void * ctx) +{ + sqlite3BackupRubyPtr c = (sqlite3BackupRubyPtr)ctx; + xfree(c); +} + +static VALUE allocate(VALUE klass) +{ + sqlite3BackupRubyPtr ctx = xcalloc((size_t)1, sizeof(sqlite3BackupRuby)); + return Data_Wrap_Struct(klass, NULL, deallocate, ctx); +} + +/* call-seq: SQLite3::Backup.new(dstdb, dstname, srcdb, srcname) + * + * Initialize backup the backup. + * + * dstdb: + * the destination SQLite3::Database object. + * dstname: + * the destination's database name. + * srcdb: + * the source SQLite3::Database object. + * srcname: + * the source's database name. + * + * The database name is "main", "temp", or the name specified in an + * ATTACH statement. + * + * This feature requires SQLite 3.6.11 or later. + * + * require 'sqlite3' + * sdb = SQLite3::Database.new('src.sqlite3') + * + * ddb = SQLite3::Database.new(':memory:') + * b = SQLite3::Backup.new(ddb, 'main', sdb, 'main') + * p [b.remaining, b.pagecount] # invalid value; for example [0, 0] + * begin + * p b.step(1) #=> OK or DONE + * p [b.remaining, b.pagecount] + * end while b.remaining > 0 + * b.finish + * + * ddb = SQLite3::Database.new(':memory:') + * b = SQLite3::Backup.new(ddb, 'main', sdb, 'main') + * b.step(-1) #=> DONE + * b.finish + * + */ +static VALUE initialize(VALUE self, VALUE dstdb, VALUE dstname, VALUE srcdb, VALUE srcname) +{ + sqlite3BackupRubyPtr ctx; + sqlite3RubyPtr ddb_ctx, sdb_ctx; + sqlite3_backup *pBackup; + + Data_Get_Struct(self, sqlite3BackupRuby, ctx); + Data_Get_Struct(dstdb, sqlite3Ruby, ddb_ctx); + Data_Get_Struct(srcdb, sqlite3Ruby, sdb_ctx); + + if(!sdb_ctx->db) + rb_raise(rb_eArgError, "cannot backup from a closed database"); + if(!ddb_ctx->db) + rb_raise(rb_eArgError, "cannot backup to a closed database"); + + pBackup = sqlite3_backup_init(ddb_ctx->db, StringValuePtr(dstname), + sdb_ctx->db, StringValuePtr(srcname)); + if( pBackup ){ + ctx->p = pBackup; + } + else { + CHECK(ddb_ctx->db, sqlite3_errcode(ddb_ctx->db)); + } + + return self; +} + +/* call-seq: SQLite3::Backup#step(nPage) + * + * Copy database pages up to +nPage+. + * If negative, copy all remaining source pages. + * + * If all pages are copied, it returns SQLite3::Constants::ErrorCode::DONE. + * When coping is not done, it returns SQLite3::Constants::ErrorCode::OK. + * When some errors occur, it returns the error code. + */ +static VALUE step(VALUE self, VALUE nPage) +{ + sqlite3BackupRubyPtr ctx; + int status; + + Data_Get_Struct(self, sqlite3BackupRuby, ctx); + REQUIRE_OPEN_BACKUP(ctx); + status = sqlite3_backup_step(ctx->p, NUM2INT(nPage)); + return INT2NUM(status); +} + +/* call-seq: SQLite3::Backup#finish + * + * Destroy the backup object. + */ +static VALUE finish(VALUE self) +{ + sqlite3BackupRubyPtr ctx; + + Data_Get_Struct(self, sqlite3BackupRuby, ctx); + REQUIRE_OPEN_BACKUP(ctx); + (void)sqlite3_backup_finish(ctx->p); + ctx->p = NULL; + return Qnil; +} + +/* call-seq: SQLite3::Backup#remaining + * + * Returns the number of pages still to be backed up. + * + * Note that the value is only updated after step() is called, + * so before calling step() returned value is invalid. + */ +static VALUE remaining(VALUE self) +{ + sqlite3BackupRubyPtr ctx; + + Data_Get_Struct(self, sqlite3BackupRuby, ctx); + REQUIRE_OPEN_BACKUP(ctx); + return INT2NUM(sqlite3_backup_remaining(ctx->p)); +} + +/* call-seq: SQLite3::Backup#pagecount + * + * Returns the total number of pages in the source database file. + * + * Note that the value is only updated after step() is called, + * so before calling step() returned value is invalid. + */ +static VALUE pagecount(VALUE self) +{ + sqlite3BackupRubyPtr ctx; + + Data_Get_Struct(self, sqlite3BackupRuby, ctx); + REQUIRE_OPEN_BACKUP(ctx); + return INT2NUM(sqlite3_backup_pagecount(ctx->p)); +} + +void init_sqlite3_backup() +{ +#if 0 + VALUE mSqlite3 = rb_define_module("SQLite3"); +#endif + cSqlite3Backup = rb_define_class_under(mSqlite3, "Backup", rb_cObject); + + rb_define_alloc_func(cSqlite3Backup, allocate); + rb_define_method(cSqlite3Backup, "initialize", initialize, 4); + rb_define_method(cSqlite3Backup, "step", step, 1); + rb_define_method(cSqlite3Backup, "finish", finish, 0); + rb_define_method(cSqlite3Backup, "remaining", remaining, 0); + rb_define_method(cSqlite3Backup, "pagecount", pagecount, 0); +} + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/backup.h b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/backup.h new file mode 100644 index 0000000..0c8c620 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/backup.h @@ -0,0 +1,15 @@ +#if !defined(SQLITE3_BACKUP_RUBY) && defined(HAVE_SQLITE3_BACKUP_INIT) +#define SQLITE3_BACKUP_RUBY + +#include + +struct _sqlite3BackupRuby { + sqlite3_backup *p; +}; + +typedef struct _sqlite3BackupRuby sqlite3BackupRuby; +typedef sqlite3BackupRuby * sqlite3BackupRubyPtr; + +void init_sqlite3_backup(); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/backup.o b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/backup.o new file mode 100644 index 0000000..ddecc28 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/backup.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/database.c b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/database.c new file mode 100644 index 0000000..3fa2718 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/database.c @@ -0,0 +1,827 @@ +#include +#include + +#define REQUIRE_OPEN_DB(_ctxt) \ + if(!_ctxt->db) \ + rb_raise(rb_path2class("SQLite3::Exception"), "cannot use a closed database"); + +VALUE cSqlite3Database; + +static void deallocate(void * ctx) +{ + sqlite3RubyPtr c = (sqlite3RubyPtr)ctx; + sqlite3 * db = c->db; + + if(db) sqlite3_close(db); + xfree(c); +} + +static VALUE allocate(VALUE klass) +{ + sqlite3RubyPtr ctx = xcalloc((size_t)1, sizeof(sqlite3Ruby)); + return Data_Wrap_Struct(klass, NULL, deallocate, ctx); +} + +static char * +utf16_string_value_ptr(VALUE str) +{ + StringValue(str); + rb_str_buf_cat(str, "\x00", 1L); + return RSTRING_PTR(str); +} + +static VALUE sqlite3_rb_close(VALUE self); + +static VALUE rb_sqlite3_open_v2(VALUE self, VALUE file, VALUE mode, VALUE zvfs) +{ + sqlite3RubyPtr ctx; + VALUE flags; + int status; + + Data_Get_Struct(self, sqlite3Ruby, ctx); + +#if defined TAINTING_SUPPORT +#if defined StringValueCStr + StringValuePtr(file); + rb_check_safe_obj(file); +#else + Check_SafeStr(file); +#endif +#endif + + status = sqlite3_open_v2( + StringValuePtr(file), + &ctx->db, + NUM2INT(mode), + NIL_P(zvfs) ? NULL : StringValuePtr(zvfs) + ); + + CHECK(ctx->db, status) + + return self; +} + +/* call-seq: db.close + * + * Closes this database. + */ +static VALUE sqlite3_rb_close(VALUE self) +{ + sqlite3RubyPtr ctx; + sqlite3 * db; + Data_Get_Struct(self, sqlite3Ruby, ctx); + + db = ctx->db; + CHECK(db, sqlite3_close(ctx->db)); + + ctx->db = NULL; + + rb_iv_set(self, "-aggregators", Qnil); + + return self; +} + +/* call-seq: db.closed? + * + * Returns +true+ if this database instance has been closed (see #close). + */ +static VALUE closed_p(VALUE self) +{ + sqlite3RubyPtr ctx; + Data_Get_Struct(self, sqlite3Ruby, ctx); + + if(!ctx->db) return Qtrue; + + return Qfalse; +} + +/* call-seq: total_changes + * + * Returns the total number of changes made to this database instance + * since it was opened. + */ +static VALUE total_changes(VALUE self) +{ + sqlite3RubyPtr ctx; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + return INT2NUM((long)sqlite3_total_changes(ctx->db)); +} + +static void tracefunc(void * data, const char *sql) +{ + VALUE self = (VALUE)data; + VALUE thing = rb_iv_get(self, "@tracefunc"); + rb_funcall(thing, rb_intern("call"), 1, rb_str_new2(sql)); +} + +/* call-seq: + * trace { |sql| ... } + * trace(Class.new { def call sql; end }.new) + * + * Installs (or removes) a block that will be invoked for every SQL + * statement executed. The block receives one parameter: the SQL statement + * executed. If the block is +nil+, any existing tracer will be uninstalled. + */ +static VALUE trace(int argc, VALUE *argv, VALUE self) +{ + sqlite3RubyPtr ctx; + VALUE block; + + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + rb_scan_args(argc, argv, "01", &block); + + if(NIL_P(block) && rb_block_given_p()) block = rb_block_proc(); + + rb_iv_set(self, "@tracefunc", block); + + sqlite3_trace(ctx->db, NIL_P(block) ? NULL : tracefunc, (void *)self); + + return self; +} + +static int rb_sqlite3_busy_handler(void * ctx, int count) +{ + VALUE self = (VALUE)(ctx); + VALUE handle = rb_iv_get(self, "@busy_handler"); + VALUE result = rb_funcall(handle, rb_intern("call"), 1, INT2NUM((long)count)); + + if(Qfalse == result) return 0; + + return 1; +} + +/* call-seq: + * busy_handler { |count| ... } + * busy_handler(Class.new { def call count; end }.new) + * + * Register a busy handler with this database instance. When a requested + * resource is busy, this handler will be invoked. If the handler returns + * +false+, the operation will be aborted; otherwise, the resource will + * be requested again. + * + * The handler will be invoked with the name of the resource that was + * busy, and the number of times it has been retried. + * + * See also the mutually exclusive #busy_timeout. + */ +static VALUE busy_handler(int argc, VALUE *argv, VALUE self) +{ + sqlite3RubyPtr ctx; + VALUE block; + int status; + + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + rb_scan_args(argc, argv, "01", &block); + + if(NIL_P(block) && rb_block_given_p()) block = rb_block_proc(); + + rb_iv_set(self, "@busy_handler", block); + + status = sqlite3_busy_handler( + ctx->db, NIL_P(block) ? NULL : rb_sqlite3_busy_handler, (void *)self); + + CHECK(ctx->db, status); + + return self; +} + +/* call-seq: last_insert_row_id + * + * Obtains the unique row ID of the last row to be inserted by this Database + * instance. + */ +static VALUE last_insert_row_id(VALUE self) +{ + sqlite3RubyPtr ctx; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + return LL2NUM(sqlite3_last_insert_rowid(ctx->db)); +} + +VALUE sqlite3val2rb(sqlite3_value * val) +{ + switch(sqlite3_value_type(val)) { + case SQLITE_INTEGER: + return LL2NUM(sqlite3_value_int64(val)); + break; + case SQLITE_FLOAT: + return rb_float_new(sqlite3_value_double(val)); + break; + case SQLITE_TEXT: + return rb_str_new2((const char *)sqlite3_value_text(val)); + break; + case SQLITE_BLOB: { + /* Sqlite warns calling sqlite3_value_bytes may invalidate pointer from sqlite3_value_blob, + so we explicitly get the length before getting blob pointer. + Note that rb_str_new apparently create string with ASCII-8BIT (BINARY) encoding, + which is what we want, as blobs are binary + */ + int len = sqlite3_value_bytes(val); + return rb_str_new((const char *)sqlite3_value_blob(val), len); + break; + } + case SQLITE_NULL: + return Qnil; + break; + default: + rb_raise(rb_eRuntimeError, "bad type"); /* FIXME */ + } +} + +void set_sqlite3_func_result(sqlite3_context * ctx, VALUE result) +{ + switch(TYPE(result)) { + case T_NIL: + sqlite3_result_null(ctx); + break; + case T_FIXNUM: + sqlite3_result_int64(ctx, (sqlite3_int64)FIX2LONG(result)); + break; + case T_BIGNUM: { +#if SIZEOF_LONG < 8 + sqlite3_int64 num64; + + if (bignum_to_int64(result, &num64)) { + sqlite3_result_int64(ctx, num64); + break; + } +#endif + } + case T_FLOAT: + sqlite3_result_double(ctx, NUM2DBL(result)); + break; + case T_STRING: + if(CLASS_OF(result) == cSqlite3Blob + || rb_enc_get_index(result) == rb_ascii8bit_encindex() + ) { + sqlite3_result_blob( + ctx, + (const void *)StringValuePtr(result), + (int)RSTRING_LEN(result), + SQLITE_TRANSIENT + ); + } else { + sqlite3_result_text( + ctx, + (const char *)StringValuePtr(result), + (int)RSTRING_LEN(result), + SQLITE_TRANSIENT + ); + } + break; + default: + rb_raise(rb_eRuntimeError, "can't return %s", + rb_class2name(CLASS_OF(result))); + } +} + +static void rb_sqlite3_func(sqlite3_context * ctx, int argc, sqlite3_value **argv) +{ + VALUE callable = (VALUE)sqlite3_user_data(ctx); + VALUE params = rb_ary_new2(argc); + VALUE result; + int i; + + if (argc > 0) { + for(i = 0; i < argc; i++) { + VALUE param = sqlite3val2rb(argv[i]); + rb_ary_push(params, param); + } + } + + result = rb_apply(callable, rb_intern("call"), params); + + set_sqlite3_func_result(ctx, result); +} + +#ifndef HAVE_RB_PROC_ARITY +int rb_proc_arity(VALUE self) +{ + return (int)NUM2INT(rb_funcall(self, rb_intern("arity"), 0)); +} +#endif + +/* call-seq: define_function_with_flags(name, flags) { |args,...| } + * + * Define a function named +name+ with +args+ using TextRep bitflags +flags+. The arity of the block + * will be used as the arity for the function defined. + */ +static VALUE define_function_with_flags(VALUE self, VALUE name, VALUE flags) +{ + sqlite3RubyPtr ctx; + VALUE block; + int status; + + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + block = rb_block_proc(); + + status = sqlite3_create_function( + ctx->db, + StringValuePtr(name), + rb_proc_arity(block), + NUM2INT(flags), + (void *)block, + rb_sqlite3_func, + NULL, + NULL + ); + + CHECK(ctx->db, status); + + rb_hash_aset(rb_iv_get(self, "@functions"), name, block); + + return self; +} + +/* call-seq: define_function(name) { |args,...| } + * + * Define a function named +name+ with +args+. The arity of the block + * will be used as the arity for the function defined. + */ +static VALUE define_function(VALUE self, VALUE name) +{ + return define_function_with_flags(self, name, INT2FIX(SQLITE_UTF8)); +} + +/* call-seq: interrupt + * + * Interrupts the currently executing operation, causing it to abort. + */ +static VALUE interrupt(VALUE self) +{ + sqlite3RubyPtr ctx; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + sqlite3_interrupt(ctx->db); + + return self; +} + +/* call-seq: errmsg + * + * Return a string describing the last error to have occurred with this + * database. + */ +static VALUE errmsg(VALUE self) +{ + sqlite3RubyPtr ctx; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + return rb_str_new2(sqlite3_errmsg(ctx->db)); +} + +/* call-seq: errcode + * + * Return an integer representing the last error to have occurred with this + * database. + */ +static VALUE errcode_(VALUE self) +{ + sqlite3RubyPtr ctx; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + return INT2NUM((long)sqlite3_errcode(ctx->db)); +} + +/* call-seq: complete?(sql) + * + * Return +true+ if the string is a valid (ie, parsable) SQL statement, and + * +false+ otherwise. + */ +static VALUE complete_p(VALUE UNUSED(self), VALUE sql) +{ + if(sqlite3_complete(StringValuePtr(sql))) + return Qtrue; + + return Qfalse; +} + +/* call-seq: changes + * + * Returns the number of changes made to this database instance by the last + * operation performed. Note that a "delete from table" without a where + * clause will not affect this value. + */ +static VALUE changes(VALUE self) +{ + sqlite3RubyPtr ctx; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + return INT2NUM(sqlite3_changes(ctx->db)); +} + +static int rb_sqlite3_auth( + void *ctx, + int _action, + const char * _a, + const char * _b, + const char * _c, + const char * _d) +{ + VALUE self = (VALUE)ctx; + VALUE action = INT2NUM(_action); + VALUE a = _a ? rb_str_new2(_a) : Qnil; + VALUE b = _b ? rb_str_new2(_b) : Qnil; + VALUE c = _c ? rb_str_new2(_c) : Qnil; + VALUE d = _d ? rb_str_new2(_d) : Qnil; + VALUE callback = rb_iv_get(self, "@authorizer"); + VALUE result = rb_funcall(callback, rb_intern("call"), 5, action, a, b, c, d); + + if(T_FIXNUM == TYPE(result)) return (int)NUM2INT(result); + if(Qtrue == result) return SQLITE_OK; + if(Qfalse == result) return SQLITE_DENY; + + return SQLITE_IGNORE; +} + +/* call-seq: set_authorizer = auth + * + * Set the authorizer for this database. +auth+ must respond to +call+, and + * +call+ must take 5 arguments. + * + * Installs (or removes) a block that will be invoked for every access + * to the database. If the block returns 0 (or +true+), the statement + * is allowed to proceed. Returning 1 or false causes an authorization error to + * occur, and returning 2 or nil causes the access to be silently denied. + */ +static VALUE set_authorizer(VALUE self, VALUE authorizer) +{ + sqlite3RubyPtr ctx; + int status; + + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + status = sqlite3_set_authorizer( + ctx->db, NIL_P(authorizer) ? NULL : rb_sqlite3_auth, (void *)self + ); + + CHECK(ctx->db, status); + + rb_iv_set(self, "@authorizer", authorizer); + + return self; +} + +/* call-seq: db.busy_timeout = ms + * + * Indicates that if a request for a resource terminates because that + * resource is busy, SQLite should sleep and retry for up to the indicated + * number of milliseconds. By default, SQLite does not retry + * busy resources. To restore the default behavior, send 0 as the + * +ms+ parameter. + * + * See also the mutually exclusive #busy_handler. + */ +static VALUE set_busy_timeout(VALUE self, VALUE timeout) +{ + sqlite3RubyPtr ctx; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + CHECK(ctx->db, sqlite3_busy_timeout(ctx->db, (int)NUM2INT(timeout))); + + return self; +} + +/* call-seq: db.extended_result_codes = true + * + * Enable extended result codes in SQLite. These result codes allow for more + * detailed exception reporting, such a which type of constraint is violated. + */ +static VALUE set_extended_result_codes(VALUE self, VALUE enable) +{ + sqlite3RubyPtr ctx; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + CHECK(ctx->db, sqlite3_extended_result_codes(ctx->db, RTEST(enable) ? 1 : 0)); + + return self; +} + +int rb_comparator_func(void * ctx, int a_len, const void * a, int b_len, const void * b) +{ + VALUE comparator; + VALUE a_str; + VALUE b_str; + VALUE comparison; + rb_encoding * internal_encoding; + + internal_encoding = rb_default_internal_encoding(); + + comparator = (VALUE)ctx; + a_str = rb_str_new((const char *)a, a_len); + b_str = rb_str_new((const char *)b, b_len); + + rb_enc_associate_index(a_str, rb_utf8_encindex()); + rb_enc_associate_index(b_str, rb_utf8_encindex()); + + if(internal_encoding) { + a_str = rb_str_export_to_enc(a_str, internal_encoding); + b_str = rb_str_export_to_enc(b_str, internal_encoding); + } + + comparison = rb_funcall(comparator, rb_intern("compare"), 2, a_str, b_str); + + return NUM2INT(comparison); +} + +/* call-seq: db.collation(name, comparator) + * + * Add a collation with name +name+, and a +comparator+ object. The + * +comparator+ object should implement a method called "compare" that takes + * two parameters and returns an integer less than, equal to, or greater than + * 0. + */ +static VALUE collation(VALUE self, VALUE name, VALUE comparator) +{ + sqlite3RubyPtr ctx; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + CHECK(ctx->db, sqlite3_create_collation( + ctx->db, + StringValuePtr(name), + SQLITE_UTF8, + (void *)comparator, + NIL_P(comparator) ? NULL : rb_comparator_func)); + + /* Make sure our comparator doesn't get garbage collected. */ + rb_hash_aset(rb_iv_get(self, "@collations"), name, comparator); + + return self; +} + +#ifdef HAVE_SQLITE3_LOAD_EXTENSION +/* call-seq: db.load_extension(file) + * + * Loads an SQLite extension library from the named file. Extension + * loading must be enabled using db.enable_load_extension(true) prior + * to calling this API. + */ +static VALUE load_extension(VALUE self, VALUE file) +{ + sqlite3RubyPtr ctx; + int status; + char *errMsg; + VALUE errexp; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + status = sqlite3_load_extension(ctx->db, RSTRING_PTR(file), 0, &errMsg); + if (status != SQLITE_OK) + { + errexp = rb_exc_new2(rb_eRuntimeError, errMsg); + sqlite3_free(errMsg); + rb_exc_raise(errexp); + } + + return self; +} +#endif + +#ifdef HAVE_SQLITE3_ENABLE_LOAD_EXTENSION +/* call-seq: db.enable_load_extension(onoff) + * + * Enable or disable extension loading. + */ +static VALUE enable_load_extension(VALUE self, VALUE onoff) +{ + sqlite3RubyPtr ctx; + int onoffparam; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + if (Qtrue == onoff) { + onoffparam = 1; + } else if (Qfalse == onoff) { + onoffparam = 0; + } else { + onoffparam = (int)NUM2INT(onoff); + } + + CHECK(ctx->db, sqlite3_enable_load_extension(ctx->db, onoffparam)); + + return self; +} +#endif + +static int enc_cb(void * _self, int UNUSED(columns), char **data, char **UNUSED(names)) +{ + VALUE self = (VALUE)_self; + + int index = rb_enc_find_index(data[0]); + rb_encoding * e = rb_enc_from_index(index); + rb_iv_set(self, "@encoding", rb_enc_from_encoding(e)); + + return 0; +} + +/* call-seq: db.encoding + * + * Fetch the encoding set on this database + */ +static VALUE db_encoding(VALUE self) +{ + sqlite3RubyPtr ctx; + VALUE enc; + + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + enc = rb_iv_get(self, "@encoding"); + + if(NIL_P(enc)) { + sqlite3_exec(ctx->db, "PRAGMA encoding", enc_cb, (void *)self, NULL); + } + + return rb_iv_get(self, "@encoding"); +} + +/* call-seq: db.transaction_active? + * + * Returns +true+ if there is a transaction active, and +false+ otherwise. + * + */ +static VALUE transaction_active_p(VALUE self) +{ + sqlite3RubyPtr ctx; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + return sqlite3_get_autocommit(ctx->db) ? Qfalse : Qtrue; +} + +static int hash_callback_function(VALUE callback_ary, int count, char **data, char **columns) +{ + VALUE new_hash = rb_hash_new(); + int i; + + for (i = 0; i < count; i++) { + if (data[i] == NULL) { + rb_hash_aset(new_hash, rb_str_new_cstr(columns[i]), Qnil); + } else { + rb_hash_aset(new_hash, rb_str_new_cstr(columns[i]), rb_str_new_cstr(data[i])); + } + } + + rb_ary_push(callback_ary, new_hash); + + return 0; +} + +static int regular_callback_function(VALUE callback_ary, int count, char **data, char **columns) +{ + VALUE new_ary = rb_ary_new(); + int i; + + for (i = 0; i < count; i++) { + if (data[i] == NULL) { + rb_ary_push(new_ary, Qnil); + } else { + rb_ary_push(new_ary, rb_str_new_cstr(data[i])); + } + } + + rb_ary_push(callback_ary, new_ary); + + return 0; +} + + +/* Is invoked by calling db.execute_batch2(sql, &block) + * + * Executes all statments in a given string separated by semicolons. + * If a query is made, all values returned are strings + * (except for 'NULL' values which return nil), + * so the user may parse values with a block. + * If no query is made, an empty array will be returned. + */ +static VALUE exec_batch(VALUE self, VALUE sql, VALUE results_as_hash) +{ + sqlite3RubyPtr ctx; + int status; + VALUE callback_ary = rb_ary_new(); + char *errMsg; + VALUE errexp; + + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + if(results_as_hash == Qtrue) { + status = sqlite3_exec(ctx->db, StringValuePtr(sql), hash_callback_function, callback_ary, &errMsg); + } else { + status = sqlite3_exec(ctx->db, StringValuePtr(sql), regular_callback_function, callback_ary, &errMsg); + } + + if (status != SQLITE_OK) + { + errexp = rb_exc_new2(rb_eRuntimeError, errMsg); + sqlite3_free(errMsg); + rb_exc_raise(errexp); + } + + return callback_ary; +} + +/* call-seq: db.db_filename(database_name) + * + * Returns the file associated with +database_name+. Can return nil or an + * empty string if the database is temporary, or in-memory. + */ +static VALUE db_filename(VALUE self, VALUE db_name) +{ + sqlite3RubyPtr ctx; + const char * fname; + Data_Get_Struct(self, sqlite3Ruby, ctx); + REQUIRE_OPEN_DB(ctx); + + fname = sqlite3_db_filename(ctx->db, StringValueCStr(db_name)); + + if(fname) return SQLITE3_UTF8_STR_NEW2(fname); + return Qnil; +} + +static VALUE rb_sqlite3_open16(VALUE self, VALUE file) +{ + int status; + sqlite3RubyPtr ctx; + + Data_Get_Struct(self, sqlite3Ruby, ctx); + +#if defined TAINTING_SUPPORT +#if defined StringValueCStr + StringValuePtr(file); + rb_check_safe_obj(file); +#else + Check_SafeStr(file); +#endif +#endif + + status = sqlite3_open16(utf16_string_value_ptr(file), &ctx->db); + + CHECK(ctx->db, status) + + return INT2NUM(status); +} + +void init_sqlite3_database() +{ +#if 0 + VALUE mSqlite3 = rb_define_module("SQLite3"); +#endif + cSqlite3Database = rb_define_class_under(mSqlite3, "Database", rb_cObject); + + rb_define_alloc_func(cSqlite3Database, allocate); + rb_define_private_method(cSqlite3Database, "open_v2", rb_sqlite3_open_v2, 3); + rb_define_private_method(cSqlite3Database, "open16", rb_sqlite3_open16, 1); + rb_define_method(cSqlite3Database, "collation", collation, 2); + rb_define_method(cSqlite3Database, "close", sqlite3_rb_close, 0); + rb_define_method(cSqlite3Database, "closed?", closed_p, 0); + rb_define_method(cSqlite3Database, "total_changes", total_changes, 0); + rb_define_method(cSqlite3Database, "trace", trace, -1); + rb_define_method(cSqlite3Database, "last_insert_row_id", last_insert_row_id, 0); + rb_define_method(cSqlite3Database, "define_function", define_function, 1); + rb_define_method(cSqlite3Database, "define_function_with_flags", define_function_with_flags, 2); + /* public "define_aggregator" is now a shim around define_aggregator2 + * implemented in Ruby */ + rb_define_private_method(cSqlite3Database, "define_aggregator2", rb_sqlite3_define_aggregator2, 2); + rb_define_method(cSqlite3Database, "interrupt", interrupt, 0); + rb_define_method(cSqlite3Database, "errmsg", errmsg, 0); + rb_define_method(cSqlite3Database, "errcode", errcode_, 0); + rb_define_method(cSqlite3Database, "complete?", complete_p, 1); + rb_define_method(cSqlite3Database, "changes", changes, 0); + rb_define_method(cSqlite3Database, "authorizer=", set_authorizer, 1); + rb_define_method(cSqlite3Database, "busy_handler", busy_handler, -1); + rb_define_method(cSqlite3Database, "busy_timeout=", set_busy_timeout, 1); + rb_define_method(cSqlite3Database, "extended_result_codes=", set_extended_result_codes, 1); + rb_define_method(cSqlite3Database, "transaction_active?", transaction_active_p, 0); + rb_define_private_method(cSqlite3Database, "exec_batch", exec_batch, 2); + rb_define_private_method(cSqlite3Database, "db_filename", db_filename, 1); + +#ifdef HAVE_SQLITE3_LOAD_EXTENSION + rb_define_method(cSqlite3Database, "load_extension", load_extension, 1); +#endif + +#ifdef HAVE_SQLITE3_ENABLE_LOAD_EXTENSION + rb_define_method(cSqlite3Database, "enable_load_extension", enable_load_extension, 1); +#endif + + rb_define_method(cSqlite3Database, "encoding", db_encoding, 0); + + rb_sqlite3_aggregator_init(); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/database.h b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/database.h new file mode 100644 index 0000000..e087789 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/database.h @@ -0,0 +1,17 @@ +#ifndef SQLITE3_DATABASE_RUBY +#define SQLITE3_DATABASE_RUBY + +#include + +struct _sqlite3Ruby { + sqlite3 *db; +}; + +typedef struct _sqlite3Ruby sqlite3Ruby; +typedef sqlite3Ruby * sqlite3RubyPtr; + +void init_sqlite3_database(); +void set_sqlite3_func_result(sqlite3_context * ctx, VALUE result); +VALUE sqlite3val2rb(sqlite3_value * val); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/database.o b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/database.o new file mode 100644 index 0000000..4df3237 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/database.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/exception.c b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/exception.c new file mode 100644 index 0000000..1dcfe18 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/exception.c @@ -0,0 +1,98 @@ +#include + +void rb_sqlite3_raise(sqlite3 * db, int status) +{ + VALUE klass = Qnil; + + /* Consider only lower 8 bits, to work correctly when + extended result codes are enabled. */ + switch(status & 0xff) { + case SQLITE_OK: + return; + break; + case SQLITE_ERROR: + klass = rb_path2class("SQLite3::SQLException"); + break; + case SQLITE_INTERNAL: + klass = rb_path2class("SQLite3::InternalException"); + break; + case SQLITE_PERM: + klass = rb_path2class("SQLite3::PermissionException"); + break; + case SQLITE_ABORT: + klass = rb_path2class("SQLite3::AbortException"); + break; + case SQLITE_BUSY: + klass = rb_path2class("SQLite3::BusyException"); + break; + case SQLITE_LOCKED: + klass = rb_path2class("SQLite3::LockedException"); + break; + case SQLITE_NOMEM: + klass = rb_path2class("SQLite3::MemoryException"); + break; + case SQLITE_READONLY: + klass = rb_path2class("SQLite3::ReadOnlyException"); + break; + case SQLITE_INTERRUPT: + klass = rb_path2class("SQLite3::InterruptException"); + break; + case SQLITE_IOERR: + klass = rb_path2class("SQLite3::IOException"); + break; + case SQLITE_CORRUPT: + klass = rb_path2class("SQLite3::CorruptException"); + break; + case SQLITE_NOTFOUND: + klass = rb_path2class("SQLite3::NotFoundException"); + break; + case SQLITE_FULL: + klass = rb_path2class("SQLite3::FullException"); + break; + case SQLITE_CANTOPEN: + klass = rb_path2class("SQLite3::CantOpenException"); + break; + case SQLITE_PROTOCOL: + klass = rb_path2class("SQLite3::ProtocolException"); + break; + case SQLITE_EMPTY: + klass = rb_path2class("SQLite3::EmptyException"); + break; + case SQLITE_SCHEMA: + klass = rb_path2class("SQLite3::SchemaChangedException"); + break; + case SQLITE_TOOBIG: + klass = rb_path2class("SQLite3::TooBigException"); + break; + case SQLITE_CONSTRAINT: + klass = rb_path2class("SQLite3::ConstraintException"); + break; + case SQLITE_MISMATCH: + klass = rb_path2class("SQLite3::MismatchException"); + break; + case SQLITE_MISUSE: + klass = rb_path2class("SQLite3::MisuseException"); + break; + case SQLITE_NOLFS: + klass = rb_path2class("SQLite3::UnsupportedException"); + break; + case SQLITE_AUTH: + klass = rb_path2class("SQLite3::AuthorizationException"); + break; + case SQLITE_FORMAT: + klass = rb_path2class("SQLite3::FormatException"); + break; + case SQLITE_RANGE: + klass = rb_path2class("SQLite3::RangeException"); + break; + case SQLITE_NOTADB: + klass = rb_path2class("SQLite3::NotADatabaseException"); + break; + default: + klass = rb_eRuntimeError; + } + + klass = rb_exc_new2(klass, sqlite3_errmsg(db)); + rb_iv_set(klass, "@code", INT2FIX(status)); + rb_exc_raise(klass); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/exception.h b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/exception.h new file mode 100644 index 0000000..55b687e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/exception.h @@ -0,0 +1,8 @@ +#ifndef SQLITE3_EXCEPTION_RUBY +#define SQLITE3_EXCEPTION_RUBY + +#define CHECK(_db, _status) rb_sqlite3_raise(_db, _status); + +void rb_sqlite3_raise(sqlite3 * db, int status); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/exception.o b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/exception.o new file mode 100644 index 0000000..001d335 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/exception.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/extconf.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/extconf.rb new file mode 100644 index 0000000..5b958d0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/extconf.rb @@ -0,0 +1,100 @@ +ENV['RC_ARCHS'] = '' if RUBY_PLATFORM =~ /darwin/ + +require 'mkmf' + +# :stopdoc: + +RbConfig::MAKEFILE_CONFIG['CC'] = ENV['CC'] if ENV['CC'] + +ldflags = cppflags = nil +if RbConfig::CONFIG["host_os"] =~ /darwin/ + begin + if with_config('sqlcipher') + brew_prefix = `brew --prefix sqlcipher`.chomp + ldflags = "#{brew_prefix}/lib" + cppflags = "#{brew_prefix}/include/sqlcipher" + pkg_conf = "#{brew_prefix}/lib/pkgconfig" + else + brew_prefix = `brew --prefix sqlite3`.chomp + ldflags = "#{brew_prefix}/lib" + cppflags = "#{brew_prefix}/include" + pkg_conf = "#{brew_prefix}/lib/pkgconfig" + end + + # pkg_config should be less error prone than parsing compiler + # commandline options, but we need to set default ldflags and cpp flags + # in case the user doesn't have pkg-config installed + ENV['PKG_CONFIG_PATH'] ||= pkg_conf + rescue + end +end + +if with_config('sqlcipher') + pkg_config("sqlcipher") +else + pkg_config("sqlite3") +end + +# --with-sqlite3-{dir,include,lib} +if with_config('sqlcipher') + $CFLAGS << ' -DUSING_SQLCIPHER' + dir_config("sqlcipher", cppflags, ldflags) +else + dir_config("sqlite3", cppflags, ldflags) +end + +if RbConfig::CONFIG["host_os"] =~ /mswin/ + $CFLAGS << ' -W3' +end + +if RUBY_VERSION < '2.7' + $CFLAGS << ' -DTAINTING_SUPPORT' +end + +def asplode missing + if RUBY_PLATFORM =~ /mingw|mswin/ + abort "#{missing} is missing. Install SQLite3 from " + + "http://www.sqlite.org/ first." + else + abort <<-error +#{missing} is missing. Try 'brew install sqlite3', +'yum install sqlite-devel' or 'apt-get install libsqlite3-dev' +and check your shared library search path (the +location where your sqlite3 shared library is located). + error + end +end + +asplode('sqlite3.h') unless find_header 'sqlite3.h' +find_library 'pthread', 'pthread_create' # 1.8 support. *shrug* + +have_library 'dl' # for static builds + +if with_config('sqlcipher') + asplode('sqlcipher') unless find_library 'sqlcipher', 'sqlite3_libversion_number' +else + asplode('sqlite3') unless find_library 'sqlite3', 'sqlite3_libversion_number' +end + +# Functions defined in 1.9 but not 1.8 +have_func('rb_proc_arity') + +# Functions defined in 2.1 but not 2.0 +have_func('rb_integer_pack') + +# These functions may not be defined +have_func('sqlite3_initialize') +have_func('sqlite3_backup_init') +have_func('sqlite3_column_database_name') +have_func('sqlite3_enable_load_extension') +have_func('sqlite3_load_extension') + +unless have_func('sqlite3_open_v2') + abort "Please use a newer version of SQLite3" +end + +have_func('sqlite3_prepare_v2') +have_type('sqlite3_int64', 'sqlite3.h') +have_type('sqlite3_uint64', 'sqlite3.h') + +create_makefile('sqlite3/sqlite3_native') diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3.c b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3.c new file mode 100644 index 0000000..ede81ea --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3.c @@ -0,0 +1,161 @@ +#include + +VALUE mSqlite3; +VALUE cSqlite3Blob; + +int bignum_to_int64(VALUE value, sqlite3_int64 *result) +{ +#ifdef HAVE_RB_INTEGER_PACK + const int nails = 0; + int t = rb_integer_pack(value, result, 1, sizeof(*result), nails, + INTEGER_PACK_NATIVE_BYTE_ORDER| + INTEGER_PACK_2COMP); + switch (t) { + case -2: case +2: + return 0; + case +1: + if (!nails) { + if (*result < 0) return 0; + } + break; + case -1: + if (!nails) { + if (*result >= 0) return 0; + } + else { + *result += INT64_MIN; + } + break; + } + return 1; +#else +# ifndef RBIGNUM_LEN +# define RBIGNUM_LEN(x) RBIGNUM(x)->len +# endif + const long len = RBIGNUM_LEN(value); + if (len == 0) { + *result = 0; + return 1; + } + if (len > 63 / (SIZEOF_BDIGITS * CHAR_BIT) + 1) return 0; + if (len == 63 / (SIZEOF_BDIGITS * CHAR_BIT) + 1) { + const BDIGIT *digits = RBIGNUM_DIGITS(value); + BDIGIT blast = digits[len-1]; + BDIGIT bmax = (BDIGIT)1UL << (63 % (CHAR_BIT * SIZEOF_BDIGITS)); + if (blast > bmax) return 0; + if (blast == bmax) { + if (RBIGNUM_POSITIVE_P(value)) { + return 0; + } + else { + long i = len-1; + while (i) { + if (digits[--i]) return 0; + } + } + } + } + *result = (sqlite3_int64)NUM2LL(value); + return 1; +#endif +} + +static VALUE libversion(VALUE UNUSED(klass)) +{ + return INT2NUM(sqlite3_libversion_number()); +} + +static VALUE using_sqlcipher(VALUE UNUSED(klass)) +{ +#ifdef USING_SQLCIPHER + return Qtrue; +#else + return Qfalse; +#endif +} + +/* Returns the compile time setting of the SQLITE_THREADSAFE flag. + * See: https://www.sqlite.org/c3ref/threadsafe.html + */ +static VALUE threadsafe_p(VALUE UNUSED(klass)) +{ + return INT2NUM(sqlite3_threadsafe()); +} + +void init_sqlite3_constants() +{ + VALUE mSqlite3Constants; + VALUE mSqlite3Open; + + mSqlite3Constants = rb_define_module_under(mSqlite3, "Constants"); + + /* sqlite3_open_v2 flags for Database::new */ + mSqlite3Open = rb_define_module_under(mSqlite3Constants, "Open"); + + /* symbols = IO.readlines('sqlite3.h').map { |n| /\A#define\s+(SQLITE_OPEN_\w+)\s/ =~ n && $1 }.compact + * pad = symbols.map(&:length).max - 9 + * symbols.each { |s| printf %Q{ rb_define_const(mSqlite3Open, %-#{pad}s INT2FIX(#{s}));\n}, '"' + s[12..-1] + '",' } + */ + rb_define_const(mSqlite3Open, "READONLY", INT2FIX(SQLITE_OPEN_READONLY)); + rb_define_const(mSqlite3Open, "READWRITE", INT2FIX(SQLITE_OPEN_READWRITE)); + rb_define_const(mSqlite3Open, "CREATE", INT2FIX(SQLITE_OPEN_CREATE)); + rb_define_const(mSqlite3Open, "DELETEONCLOSE", INT2FIX(SQLITE_OPEN_DELETEONCLOSE)); + rb_define_const(mSqlite3Open, "EXCLUSIVE", INT2FIX(SQLITE_OPEN_EXCLUSIVE)); + rb_define_const(mSqlite3Open, "MAIN_DB", INT2FIX(SQLITE_OPEN_MAIN_DB)); + rb_define_const(mSqlite3Open, "TEMP_DB", INT2FIX(SQLITE_OPEN_TEMP_DB)); + rb_define_const(mSqlite3Open, "TRANSIENT_DB", INT2FIX(SQLITE_OPEN_TRANSIENT_DB)); + rb_define_const(mSqlite3Open, "MAIN_JOURNAL", INT2FIX(SQLITE_OPEN_MAIN_JOURNAL)); + rb_define_const(mSqlite3Open, "TEMP_JOURNAL", INT2FIX(SQLITE_OPEN_TEMP_JOURNAL)); + rb_define_const(mSqlite3Open, "SUBJOURNAL", INT2FIX(SQLITE_OPEN_SUBJOURNAL)); + rb_define_const(mSqlite3Open, "MASTER_JOURNAL", INT2FIX(SQLITE_OPEN_MASTER_JOURNAL)); + rb_define_const(mSqlite3Open, "NOMUTEX", INT2FIX(SQLITE_OPEN_NOMUTEX)); + rb_define_const(mSqlite3Open, "FULLMUTEX", INT2FIX(SQLITE_OPEN_FULLMUTEX)); +#ifdef SQLITE_OPEN_AUTOPROXY + /* SQLITE_VERSION_NUMBER>=3007002 */ + rb_define_const(mSqlite3Open, "AUTOPROXY", INT2FIX(SQLITE_OPEN_AUTOPROXY)); + rb_define_const(mSqlite3Open, "SHAREDCACHE", INT2FIX(SQLITE_OPEN_SHAREDCACHE)); + rb_define_const(mSqlite3Open, "PRIVATECACHE", INT2FIX(SQLITE_OPEN_PRIVATECACHE)); + rb_define_const(mSqlite3Open, "WAL", INT2FIX(SQLITE_OPEN_WAL)); +#endif +#ifdef SQLITE_OPEN_URI + /* SQLITE_VERSION_NUMBER>=3007007 */ + rb_define_const(mSqlite3Open, "URI", INT2FIX(SQLITE_OPEN_URI)); +#endif +#ifdef SQLITE_OPEN_MEMORY + /* SQLITE_VERSION_NUMBER>=3007013 */ + rb_define_const(mSqlite3Open, "MEMORY", INT2FIX(SQLITE_OPEN_MEMORY)); +#endif +} + +void Init_sqlite3_native() +{ + /* + * SQLite3 is a wrapper around the popular database + * sqlite[http://sqlite.org]. + * + * For an example of usage, see SQLite3::Database. + */ + mSqlite3 = rb_define_module("SQLite3"); + + /* A class for differentiating between strings and blobs, when binding them + * into statements. + */ + cSqlite3Blob = rb_define_class_under(mSqlite3, "Blob", rb_cString); + + /* Initialize the sqlite3 library */ +#ifdef HAVE_SQLITE3_INITIALIZE + sqlite3_initialize(); +#endif + + init_sqlite3_constants(); + init_sqlite3_database(); + init_sqlite3_statement(); +#ifdef HAVE_SQLITE3_BACKUP_INIT + init_sqlite3_backup(); +#endif + rb_define_singleton_method(mSqlite3, "sqlcipher?", using_sqlcipher, 0); + rb_define_singleton_method(mSqlite3, "libversion", libversion, 0); + rb_define_singleton_method(mSqlite3, "threadsafe", threadsafe_p, 0); + rb_define_const(mSqlite3, "SQLITE_VERSION", rb_str_new2(SQLITE_VERSION)); + rb_define_const(mSqlite3, "SQLITE_VERSION_NUMBER", INT2FIX(SQLITE_VERSION_NUMBER)); +} diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3.o b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3.o new file mode 100644 index 0000000..e9c330f Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3_native.so b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3_native.so new file mode 100755 index 0000000..a9e91f6 Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3_native.so differ diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3_ruby.h b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3_ruby.h new file mode 100644 index 0000000..a647c44 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/sqlite3_ruby.h @@ -0,0 +1,45 @@ +#ifndef SQLITE3_RUBY +#define SQLITE3_RUBY + +#include + +#ifdef UNUSED +#elif defined(__GNUC__) +# define UNUSED(x) UNUSED_ ## x __attribute__((unused)) +#elif defined(__LCLINT__) +# define UNUSED(x) /*@unused@*/ x +#else +# define UNUSED(x) x +#endif + +#include + +#define USASCII_P(_obj) (rb_enc_get_index(_obj) == rb_usascii_encindex()) +#define UTF8_P(_obj) (rb_enc_get_index(_obj) == rb_utf8_encindex()) +#define UTF16_LE_P(_obj) (rb_enc_get_index(_obj) == rb_enc_find_index("UTF-16LE")) +#define UTF16_BE_P(_obj) (rb_enc_get_index(_obj) == rb_enc_find_index("UTF-16BE")) +#define SQLITE3_UTF8_STR_NEW2(_obj) \ + (rb_enc_associate_index(rb_str_new2(_obj), rb_utf8_encindex())) + + +#include + +#ifndef HAVE_TYPE_SQLITE3_INT64 +typedef sqlite_int64 sqlite3_int64; +#endif + +#ifndef HAVE_TYPE_SQLITE3_UINT64 +typedef sqlite_uint64 sqlite3_uint64; +#endif + +extern VALUE mSqlite3; +extern VALUE cSqlite3Blob; + +#include +#include +#include +#include + +int bignum_to_int64(VALUE big, sqlite3_int64 *result); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/statement.c b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/statement.c new file mode 100644 index 0000000..44e1a5c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/statement.c @@ -0,0 +1,442 @@ +#include + +#define REQUIRE_OPEN_STMT(_ctxt) \ + if(!_ctxt->st) \ + rb_raise(rb_path2class("SQLite3::Exception"), "cannot use a closed statement"); + +VALUE cSqlite3Statement; + +static void deallocate(void * ctx) +{ + sqlite3StmtRubyPtr c = (sqlite3StmtRubyPtr)ctx; + xfree(c); +} + +static VALUE allocate(VALUE klass) +{ + sqlite3StmtRubyPtr ctx = xcalloc((size_t)1, sizeof(sqlite3StmtRuby)); + ctx->st = NULL; + ctx->done_p = 0; + + return Data_Wrap_Struct(klass, NULL, deallocate, ctx); +} + +/* call-seq: SQLite3::Statement.new(db, sql) + * + * Create a new statement attached to the given Database instance, and which + * encapsulates the given SQL text. If the text contains more than one + * statement (i.e., separated by semicolons), then the #remainder property + * will be set to the trailing text. + */ +static VALUE initialize(VALUE self, VALUE db, VALUE sql) +{ + sqlite3RubyPtr db_ctx; + sqlite3StmtRubyPtr ctx; + const char *tail = NULL; + int status; + + StringValue(sql); + + Data_Get_Struct(db, sqlite3Ruby, db_ctx); + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + + if(!db_ctx->db) + rb_raise(rb_eArgError, "prepare called on a closed database"); + + if(!UTF8_P(sql)) { + sql = rb_str_export_to_enc(sql, rb_utf8_encoding()); + } + +#ifdef HAVE_SQLITE3_PREPARE_V2 + status = sqlite3_prepare_v2( +#else + status = sqlite3_prepare( +#endif + db_ctx->db, + (const char *)StringValuePtr(sql), + (int)RSTRING_LEN(sql), + &ctx->st, + &tail + ); + + CHECK(db_ctx->db, status); + + rb_iv_set(self, "@connection", db); + rb_iv_set(self, "@remainder", rb_str_new2(tail)); + rb_iv_set(self, "@columns", Qnil); + rb_iv_set(self, "@types", Qnil); + + return self; +} + +/* call-seq: stmt.close + * + * Closes the statement by finalizing the underlying statement + * handle. The statement must not be used after being closed. + */ +static VALUE sqlite3_rb_close(VALUE self) +{ + sqlite3StmtRubyPtr ctx; + + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + + REQUIRE_OPEN_STMT(ctx); + + sqlite3_finalize(ctx->st); + ctx->st = NULL; + + return self; +} + +/* call-seq: stmt.closed? + * + * Returns true if the statement has been closed. + */ +static VALUE closed_p(VALUE self) +{ + sqlite3StmtRubyPtr ctx; + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + + if(!ctx->st) return Qtrue; + + return Qfalse; +} + +static VALUE step(VALUE self) +{ + sqlite3StmtRubyPtr ctx; + sqlite3_stmt *stmt; + int value, length; + VALUE list; + rb_encoding * internal_encoding; + + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + + REQUIRE_OPEN_STMT(ctx); + + if(ctx->done_p) return Qnil; + + { + VALUE db = rb_iv_get(self, "@connection"); + rb_funcall(db, rb_intern("encoding"), 0); + internal_encoding = rb_default_internal_encoding(); + } + + stmt = ctx->st; + + value = sqlite3_step(stmt); + if (rb_errinfo() != Qnil) { + /* some user defined function was invoked as a callback during step and + * it raised an exception that has been suppressed until step returns. + * Now re-raise it. */ + VALUE exception = rb_errinfo(); + rb_set_errinfo(Qnil); + rb_exc_raise(exception); + } + + length = sqlite3_column_count(stmt); + list = rb_ary_new2((long)length); + + switch(value) { + case SQLITE_ROW: + { + int i; + for(i = 0; i < length; i++) { + switch(sqlite3_column_type(stmt, i)) { + case SQLITE_INTEGER: + rb_ary_push(list, LL2NUM(sqlite3_column_int64(stmt, i))); + break; + case SQLITE_FLOAT: + rb_ary_push(list, rb_float_new(sqlite3_column_double(stmt, i))); + break; + case SQLITE_TEXT: + { + VALUE str = rb_str_new( + (const char *)sqlite3_column_text(stmt, i), + (long)sqlite3_column_bytes(stmt, i) + ); + rb_enc_associate_index(str, rb_utf8_encindex()); + if(internal_encoding) + str = rb_str_export_to_enc(str, internal_encoding); + rb_ary_push(list, str); + } + break; + case SQLITE_BLOB: + { + VALUE str = rb_str_new( + (const char *)sqlite3_column_blob(stmt, i), + (long)sqlite3_column_bytes(stmt, i) + ); + rb_ary_push(list, str); + } + break; + case SQLITE_NULL: + rb_ary_push(list, Qnil); + break; + default: + rb_raise(rb_eRuntimeError, "bad type"); + } + } + } + break; + case SQLITE_DONE: + ctx->done_p = 1; + return Qnil; + break; + default: + sqlite3_reset(stmt); + ctx->done_p = 0; + CHECK(sqlite3_db_handle(ctx->st), value); + } + + return list; +} + +/* call-seq: stmt.bind_param(key, value) + * + * Binds value to the named (or positional) placeholder. If +param+ is a + * Fixnum, it is treated as an index for a positional placeholder. + * Otherwise it is used as the name of the placeholder to bind to. + * + * See also #bind_params. + */ +static VALUE bind_param(VALUE self, VALUE key, VALUE value) +{ + sqlite3StmtRubyPtr ctx; + int status; + int index; + + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + REQUIRE_OPEN_STMT(ctx); + + switch(TYPE(key)) { + case T_SYMBOL: + key = rb_funcall(key, rb_intern("to_s"), 0); + case T_STRING: + if(RSTRING_PTR(key)[0] != ':') key = rb_str_plus(rb_str_new2(":"), key); + index = sqlite3_bind_parameter_index(ctx->st, StringValuePtr(key)); + break; + default: + index = (int)NUM2INT(key); + } + + if(index == 0) + rb_raise(rb_path2class("SQLite3::Exception"), "no such bind parameter"); + + switch(TYPE(value)) { + case T_STRING: + if(CLASS_OF(value) == cSqlite3Blob + || rb_enc_get_index(value) == rb_ascii8bit_encindex() + ) { + status = sqlite3_bind_blob( + ctx->st, + index, + (const char *)StringValuePtr(value), + (int)RSTRING_LEN(value), + SQLITE_TRANSIENT + ); + } else { + + + if (UTF16_LE_P(value) || UTF16_BE_P(value)) { + status = sqlite3_bind_text16( + ctx->st, + index, + (const char *)StringValuePtr(value), + (int)RSTRING_LEN(value), + SQLITE_TRANSIENT + ); + } else { + if (!UTF8_P(value) || !USASCII_P(value)) { + value = rb_str_encode(value, rb_enc_from_encoding(rb_utf8_encoding()), 0, Qnil); + } + status = sqlite3_bind_text( + ctx->st, + index, + (const char *)StringValuePtr(value), + (int)RSTRING_LEN(value), + SQLITE_TRANSIENT + ); + } + } + break; + case T_BIGNUM: { + sqlite3_int64 num64; + if (bignum_to_int64(value, &num64)) { + status = sqlite3_bind_int64(ctx->st, index, num64); + break; + } + } + case T_FLOAT: + status = sqlite3_bind_double(ctx->st, index, NUM2DBL(value)); + break; + case T_FIXNUM: + status = sqlite3_bind_int64(ctx->st, index, (sqlite3_int64)FIX2LONG(value)); + break; + case T_NIL: + status = sqlite3_bind_null(ctx->st, index); + break; + default: + rb_raise(rb_eRuntimeError, "can't prepare %s", + rb_class2name(CLASS_OF(value))); + break; + } + + CHECK(sqlite3_db_handle(ctx->st), status); + + return self; +} + +/* call-seq: stmt.reset! + * + * Resets the statement. This is typically done internally, though it might + * occassionally be necessary to manually reset the statement. + */ +static VALUE reset_bang(VALUE self) +{ + sqlite3StmtRubyPtr ctx; + + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + REQUIRE_OPEN_STMT(ctx); + + sqlite3_reset(ctx->st); + + ctx->done_p = 0; + + return self; +} + +/* call-seq: stmt.clear_bindings! + * + * Resets the statement. This is typically done internally, though it might + * occassionally be necessary to manually reset the statement. + */ +static VALUE clear_bindings_bang(VALUE self) +{ + sqlite3StmtRubyPtr ctx; + + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + REQUIRE_OPEN_STMT(ctx); + + sqlite3_clear_bindings(ctx->st); + + ctx->done_p = 0; + + return self; +} + +/* call-seq: stmt.done? + * + * returns true if all rows have been returned. + */ +static VALUE done_p(VALUE self) +{ + sqlite3StmtRubyPtr ctx; + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + + if(ctx->done_p) return Qtrue; + return Qfalse; +} + +/* call-seq: stmt.column_count + * + * Returns the number of columns to be returned for this statement + */ +static VALUE column_count(VALUE self) +{ + sqlite3StmtRubyPtr ctx; + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + REQUIRE_OPEN_STMT(ctx); + + return INT2NUM((long)sqlite3_column_count(ctx->st)); +} + +/* call-seq: stmt.column_name(index) + * + * Get the column name at +index+. 0 based. + */ +static VALUE column_name(VALUE self, VALUE index) +{ + sqlite3StmtRubyPtr ctx; + const char * name; + + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + REQUIRE_OPEN_STMT(ctx); + + name = sqlite3_column_name(ctx->st, (int)NUM2INT(index)); + + if(name) return SQLITE3_UTF8_STR_NEW2(name); + return Qnil; +} + +/* call-seq: stmt.column_decltype(index) + * + * Get the column type at +index+. 0 based. + */ +static VALUE column_decltype(VALUE self, VALUE index) +{ + sqlite3StmtRubyPtr ctx; + const char * name; + + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + REQUIRE_OPEN_STMT(ctx); + + name = sqlite3_column_decltype(ctx->st, (int)NUM2INT(index)); + + if(name) return rb_str_new2(name); + return Qnil; +} + +/* call-seq: stmt.bind_parameter_count + * + * Return the number of bind parameters + */ +static VALUE bind_parameter_count(VALUE self) +{ + sqlite3StmtRubyPtr ctx; + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + REQUIRE_OPEN_STMT(ctx); + + return INT2NUM((long)sqlite3_bind_parameter_count(ctx->st)); +} + +#ifdef HAVE_SQLITE3_COLUMN_DATABASE_NAME + +/* call-seq: stmt.database_name(column_index) + * + * Return the database name for the column at +column_index+ + */ +static VALUE database_name(VALUE self, VALUE index) +{ + sqlite3StmtRubyPtr ctx; + Data_Get_Struct(self, sqlite3StmtRuby, ctx); + REQUIRE_OPEN_STMT(ctx); + + return SQLITE3_UTF8_STR_NEW2( + sqlite3_column_database_name(ctx->st, NUM2INT(index))); +} + +#endif + +void init_sqlite3_statement() +{ + cSqlite3Statement = rb_define_class_under(mSqlite3, "Statement", rb_cObject); + + rb_define_alloc_func(cSqlite3Statement, allocate); + rb_define_method(cSqlite3Statement, "initialize", initialize, 2); + rb_define_method(cSqlite3Statement, "close", sqlite3_rb_close, 0); + rb_define_method(cSqlite3Statement, "closed?", closed_p, 0); + rb_define_method(cSqlite3Statement, "bind_param", bind_param, 2); + rb_define_method(cSqlite3Statement, "reset!", reset_bang, 0); + rb_define_method(cSqlite3Statement, "clear_bindings!", clear_bindings_bang, 0); + rb_define_method(cSqlite3Statement, "step", step, 0); + rb_define_method(cSqlite3Statement, "done?", done_p, 0); + rb_define_method(cSqlite3Statement, "column_count", column_count, 0); + rb_define_method(cSqlite3Statement, "column_name", column_name, 1); + rb_define_method(cSqlite3Statement, "column_decltype", column_decltype, 1); + rb_define_method(cSqlite3Statement, "bind_parameter_count", bind_parameter_count, 0); + +#ifdef HAVE_SQLITE3_COLUMN_DATABASE_NAME + rb_define_method(cSqlite3Statement, "database_name", database_name, 1); +#endif +} diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/statement.h b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/statement.h new file mode 100644 index 0000000..e7ef1f3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/statement.h @@ -0,0 +1,16 @@ +#ifndef SQLITE3_STATEMENT_RUBY +#define SQLITE3_STATEMENT_RUBY + +#include + +struct _sqlite3StmtRuby { + sqlite3_stmt *st; + int done_p; +}; + +typedef struct _sqlite3StmtRuby sqlite3StmtRuby; +typedef sqlite3StmtRuby * sqlite3StmtRubyPtr; + +void init_sqlite3_statement(); + +#endif diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/statement.o b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/statement.o new file mode 100644 index 0000000..a9bb69a Binary files /dev/null and b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3/statement.o differ diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/faq/faq.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/faq/faq.rb new file mode 100644 index 0000000..61d7d01 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/faq/faq.rb @@ -0,0 +1,145 @@ +require 'yaml' +require 'redcloth' + +def process_faq_list( faqs ) + puts "
      " + faqs.each do |faq| + process_faq_list_item faq + end + puts "
    " +end + +def process_faq_list_item( faq ) + question = faq.keys.first + answer = faq.values.first + + print "
  • " + + question_text = RedCloth.new(question).to_html.gsub( %r{},"" ) + if answer.is_a?( Array ) + puts question_text + process_faq_list answer + else + print "#{question_text}" + end + + puts "
  • " +end + +def process_faq_descriptions( faqs, path=nil ) + faqs.each do |faq| + process_faq_description faq, path + end +end + +def process_faq_description( faq, path ) + question = faq.keys.first + path = ( path ? path + " " : "" ) + question + answer = faq.values.first + + if answer.is_a?( Array ) + process_faq_descriptions( answer, path ) + else + title = RedCloth.new( path ).to_html.gsub( %r{}, "" ) + answer = RedCloth.new( answer || "" ) + + puts "" + puts "
    #{title}
    " + puts "
    #{add_api_links(answer.to_html)}
    " + end +end + +API_OBJECTS = [ "Database", "Statement", "ResultSet", + "ParsedStatement", "Pragmas", "Translator" ].inject( "(" ) { |acc,name| + acc << "|" if acc.length > 1 + acc << name + acc + } + ")" + +def add_api_links( text ) + text.gsub( /#{API_OBJECTS}(#(\w+))?/ ) do + disp_obj = obj = $1 + + case obj + when "Pragmas"; disp_obj = "Database" + end + + method = $3 + s = "#{disp_obj}" + s << "##{method}" if method + s << "" + s + end +end + +faqs = YAML.load( File.read( "faq.yml" ) ) + +puts <<-EOF + + + SQLite3/Ruby FAQ + + + +

    SQLite/Ruby FAQ

    +
    +EOF + +process_faq_list( faqs ) +puts "
    " +process_faq_descriptions( faqs ) + +puts "" diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/faq/faq.yml b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/faq/faq.yml new file mode 100644 index 0000000..155259f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/faq/faq.yml @@ -0,0 +1,426 @@ +--- +- "How do I do a database query?": + - "I just want an array of the rows...": >- + + Use the Database#execute method. If you don't give it a block, it will + return an array of all the rows: + + +
    +        require 'sqlite3'
    +
    +        db = SQLite3::Database.new( "test.db" )
    +        rows = db.execute( "select * from test" )
    +      
    + + - "I'd like to use a block to iterate through the rows...": >- + + Use the Database#execute method. If you give it a block, each row of the + result will be yielded to the block: + + +
    +        require 'sqlite3'
    +
    +        db = SQLite3::Database.new( "test.db" )
    +        db.execute( "select * from test" ) do |row|
    +          ...
    +        end
    +      
    + + - "I need to get the column names as well as the rows...": >- + + Use the Database#execute2 method. This works just like Database#execute; + if you don't give it a block, it returns an array of rows; otherwise, it + will yield each row to the block. _However_, the first row returned is + always an array of the column names from the query: + + +
    +        require 'sqlite3'
    +
    +        db = SQLite3::Database.new( "test.db" )
    +        columns, *rows = db.execute2( "select * from test" )
    +
    +        # or use a block:
    +
    +        columns = nil
    +        db.execute2( "select * from test" ) do |row|
    +          if columns.nil?
    +            columns = row
    +          else
    +            # process row
    +          end
    +        end
    +      
    + + - "I just want the first row of the result set...": >- + + Easy. Just call Database#get_first_row: + + +
    +        row = db.get_first_row( "select * from table" )
    +      
    + + + This also supports bind variables, just like Database#execute + and friends. + + - "I just want the first value of the first row of the result set...": >- + + Also easy. Just call Database#get_first_value: + + +
    +        count = db.get_first_value( "select count(*) from table" )
    +      
    + + + This also supports bind variables, just like Database#execute + and friends. + +- "How do I prepare a statement for repeated execution?": >- + If the same statement is going to be executed repeatedly, you can speed + things up a bit by _preparing_ the statement. You do this via the + Database#prepare method. It returns a Statement object, and you can + then invoke #execute on that to get the ResultSet: + + +
    +      stmt = db.prepare( "select * from person" )
    +
    +      1000.times do
    +        stmt.execute do |result|
    +          ...
    +        end
    +      end
    +
    +      stmt.close
    +
    +      # or, use a block
    +
    +      db.prepare( "select * from person" ) do |stmt|
    +        1000.times do
    +          stmt.execute do |result|
    +            ...
    +          end
    +        end
    +      end
    +    
    + + + This is made more useful by the ability to bind variables to placeholders + via the Statement#bind_param and Statement#bind_params methods. (See the + next FAQ for details.) + +- "How do I use placeholders in an SQL statement?": >- + Placeholders in an SQL statement take any of the following formats: + + + * @?@ + + * @?_nnn_@ + + * @:_word_@ + + + Where _n_ is an integer, and _word_ is an alpha-numeric identifier (or + number). When the placeholder is associated with a number, that number + identifies the index of the bind variable to replace it with. When it + is an identifier, it identifies the name of the correponding bind + variable. (In the instance of the first format--a single question + mark--the placeholder is assigned a number one greater than the last + index used, or 1 if it is the first.) + + + For example, here is a query using these placeholder formats: + + +
    +      select *
    +        from table
    +       where ( c = ?2 or c = ? )
    +         and d = :name
    +         and e = :1
    +    
    + + + This defines 5 different placeholders: 1, 2, 3, and "name". + + + You replace these placeholders by _binding_ them to values. This can be + accomplished in a variety of ways. + + + The Database#execute, and Database#execute2 methods all accept additional + arguments following the SQL statement. These arguments are assumed to be + bind parameters, and they are bound (positionally) to their corresponding + placeholders: + + +
    +      db.execute( "select * from table where a = ? and b = ?",
    +                  "hello",
    +                  "world" )
    +    
    + + + The above would replace the first question mark with 'hello' and the + second with 'world'. If the placeholders have an explicit index given, they + will be replaced with the bind parameter at that index (1-based). + + + If a Hash is given as a bind parameter, then its key/value pairs are bound + to the placeholders. This is how you bind by name: + + +
    +      db.execute( "select * from table where a = :name and b = :value",
    +                  "name" => "bob",
    +                  "value" => "priceless" )
    +    
    + + + You can also bind explicitly using the Statement object itself. Just pass + additional parameters to the Statement#execute statement: + + +
    +      db.prepare( "select * from table where a = :name and b = ?" ) do |stmt|
    +        stmt.execute "value", "name" => "bob"
    +      end
    +    
    + + + Or do a Database#prepare to get the Statement, and then use either + Statement#bind_param or Statement#bind_params: + + +
    +      stmt = db.prepare( "select * from table where a = :name and b = ?" )
    +
    +      stmt.bind_param( "name", "bob" )
    +      stmt.bind_param( 1, "value" )
    +
    +      # or
    +
    +      stmt.bind_params( "value", "name" => "bob" )
    +    
    + +- "How do I discover metadata about a query?": >- + + If you ever want to know the names or types of the columns in a result + set, you can do it in several ways. + + + The first way is to ask the row object itself. Each row will have a + property "fields" that returns an array of the column names. The row + will also have a property "types" that returns an array of the column + types: + + +
    +      rows = db.execute( "select * from table" )
    +      p rows[0].fields
    +      p rows[0].types
    +    
    + + + Obviously, this approach requires you to execute a statement that actually + returns data. If you don't know if the statement will return any rows, but + you still need the metadata, you can use Database#query and ask the + ResultSet object itself: + + +
    +      db.query( "select * from table" ) do |result|
    +        p result.columns
    +        p result.types
    +        ...
    +      end
    +    
    + + + Lastly, you can use Database#prepare and ask the Statement object what + the metadata are: + + +
    +      stmt = db.prepare( "select * from table" )
    +      p stmt.columns
    +      p stmt.types
    +    
    + +- "I'd like the rows to be indexible by column name.": >- + By default, each row from a query is returned as an Array of values. This + means that you can only obtain values by their index. Sometimes, however, + you would like to obtain values by their column name. + + + The first way to do this is to set the Database property "results_as_hash" + to true. If you do this, then all rows will be returned as Hash objects, + with the column names as the keys. (In this case, the "fields" property + is unavailable on the row, although the "types" property remains.) + + +
    +      db.results_as_hash = true
    +      db.execute( "select * from table" ) do |row|
    +        p row['column1']
    +        p row['column2']
    +      end
    +    
    + + + The other way is to use Ara Howard's + "ArrayFields":http://rubyforge.org/projects/arrayfields + module. Just require "arrayfields", and all of your rows will be indexable + by column name, even though they are still arrays! + + +
    +      require 'arrayfields'
    +
    +      ...
    +      db.execute( "select * from table" ) do |row|
    +        p row[0] == row['column1']
    +        p row[1] == row['column2']
    +      end
    +    
    + +- "I'd like the values from a query to be the correct types, instead of String.": >- + You can turn on "type translation" by setting Database#type_translation to + true: + + +
    +      db.type_translation = true
    +      db.execute( "select * from table" ) do |row|
    +        p row
    +      end
    +    
    + + + By doing this, each return value for each row will be translated to its + correct type, based on its declared column type. + + + You can even declare your own translation routines, if (for example) you are + using an SQL type that is not handled by default: + + +
    +      # assume "objects" table has the following schema:
    +      #   create table objects (
    +      #     name varchar2(20),
    +      #     thing object
    +      #   )
    +
    +      db.type_translation = true
    +      db.translator.add_translator( "object" ) do |type, value|
    +        db.decode( value )
    +      end
    +
    +      h = { :one=>:two, "three"=>"four", 5=>6 }
    +      dump = db.encode( h )
    +
    +      db.execute( "insert into objects values ( ?, ? )", "bob", dump )
    +
    +      obj = db.get_first_value( "select thing from objects where name='bob'" )
    +      p obj == h
    +    
    + +- "How do I insert binary data into the database?": >- + Use blobs. Blobs are new features of SQLite3. You have to use bind + variables to make it work: + + +
    +      db.execute( "insert into foo ( ?, ? )",
    +        SQLite3::Blob.new( "\0\1\2\3\4\5" ),
    +        SQLite3::Blob.new( "a\0b\0c\0d ) )
    +    
    + + + The blob values must be indicated explicitly by binding each parameter to + a value of type SQLite3::Blob. + +- "How do I do a DDL (insert, update, delete) statement?": >- + You can actually do inserts, updates, and deletes in exactly the same way + as selects, but in general the Database#execute method will be most + convenient: + + +
    +      db.execute( "insert into table values ( ?, ? )", *bind_vars )
    +    
    + +- "How do I execute multiple statements in a single string?": >- + The standard query methods (Database#execute, Database#execute2, + Database#query, and Statement#execute) will only execute the first + statement in the string that is given to them. Thus, if you have a + string with multiple SQL statements, each separated by a string, + you can't use those methods to execute them all at once. + + + Instead, use Database#execute_batch: + + +
    +      sql = <
    +
    +
    +    Unlike the other query methods, Database#execute_batch accepts no
    +    block. It will also only ever return +nil+. Thus, it is really only
    +    suitable for batch processing of DDL statements.
    +
    +- "How do I begin/end a transaction?":
    +    Use Database#transaction to start a transaction. If you give it a block,
    +    the block will be automatically committed at the end of the block,
    +    unless an exception was raised, in which case the transaction will be
    +    rolled back. (Never explicitly call Database#commit or Database#rollback
    +    inside of a transaction block--you'll get errors when the block
    +    terminates!)
    +
    +
    +    
    +      database.transaction do |db|
    +        db.execute( "insert into table values ( 'a', 'b', 'c' )" )
    +        ...
    +      end
    +    
    + + + Alternatively, if you don't give a block to Database#transaction, the + transaction remains open until you explicitly call Database#commit or + Database#rollback. + + +
    +      db.transaction
    +      db.execute( "insert into table values ( 'a', 'b', 'c' )" )
    +      db.commit
    +    
    + + + Note that SQLite does not allow nested transactions, so you'll get errors + if you try to open a new transaction while one is already active. Use + Database#transaction_active? to determine whether a transaction is + active or not. + +#- "How do I discover metadata about a table/index?": +# +#- "How do I do tweak database settings?": diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3.rb new file mode 100644 index 0000000..f6110e1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3.rb @@ -0,0 +1,15 @@ +# support multiple ruby version (fat binaries under windows) +begin + RUBY_VERSION =~ /(\d+\.\d+)/ + require "sqlite3/#{$1}/sqlite3_native" +rescue LoadError + require 'sqlite3/sqlite3_native' +end + +require 'sqlite3/database' +require 'sqlite3/version' + +module SQLite3 + # Was sqlite3 compiled with thread safety on? + def self.threadsafe?; threadsafe > 0; end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/constants.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/constants.rb new file mode 100644 index 0000000..d52a001 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/constants.rb @@ -0,0 +1,50 @@ +module SQLite3 ; module Constants + + module TextRep + UTF8 = 1 + UTF16LE = 2 + UTF16BE = 3 + UTF16 = 4 + ANY = 5 + DETERMINISTIC = 0x800 + end + + module ColumnType + INTEGER = 1 + FLOAT = 2 + TEXT = 3 + BLOB = 4 + NULL = 5 + end + + module ErrorCode + OK = 0 # Successful result + ERROR = 1 # SQL error or missing database + INTERNAL = 2 # An internal logic error in SQLite + PERM = 3 # Access permission denied + ABORT = 4 # Callback routine requested an abort + BUSY = 5 # The database file is locked + LOCKED = 6 # A table in the database is locked + NOMEM = 7 # A malloc() failed + READONLY = 8 # Attempt to write a readonly database + INTERRUPT = 9 # Operation terminated by sqlite_interrupt() + IOERR = 10 # Some kind of disk I/O error occurred + CORRUPT = 11 # The database disk image is malformed + NOTFOUND = 12 # (Internal Only) Table or record not found + FULL = 13 # Insertion failed because database is full + CANTOPEN = 14 # Unable to open the database file + PROTOCOL = 15 # Database lock protocol error + EMPTY = 16 # (Internal Only) Database table is empty + SCHEMA = 17 # The database schema changed + TOOBIG = 18 # Too much data for one row of a table + CONSTRAINT = 19 # Abort due to contraint violation + MISMATCH = 20 # Data type mismatch + MISUSE = 21 # Library used incorrectly + NOLFS = 22 # Uses OS features not supported on host + AUTH = 23 # Authorization denied + + ROW = 100 # sqlite_step() has another row ready + DONE = 101 # sqlite_step() has finished executing + end + +end ; end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/database.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/database.rb new file mode 100644 index 0000000..643b6c7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/database.rb @@ -0,0 +1,736 @@ +require 'sqlite3/constants' +require 'sqlite3/errors' +require 'sqlite3/pragmas' +require 'sqlite3/statement' +require 'sqlite3/translator' +require 'sqlite3/value' + +module SQLite3 + + # The Database class encapsulates a single connection to a SQLite3 database. + # Its usage is very straightforward: + # + # require 'sqlite3' + # + # SQLite3::Database.new( "data.db" ) do |db| + # db.execute( "select * from table" ) do |row| + # p row + # end + # end + # + # It wraps the lower-level methods provides by the selected driver, and + # includes the Pragmas module for access to various pragma convenience + # methods. + # + # The Database class provides type translation services as well, by which + # the SQLite3 data types (which are all represented as strings) may be + # converted into their corresponding types (as defined in the schemas + # for their tables). This translation only occurs when querying data from + # the database--insertions and updates are all still typeless. + # + # Furthermore, the Database class has been designed to work well with the + # ArrayFields module from Ara Howard. If you require the ArrayFields + # module before performing a query, and if you have not enabled results as + # hashes, then the results will all be indexible by field name. + class Database + attr_reader :collations + + include Pragmas + + class << self + + alias :open :new + + # Quotes the given string, making it safe to use in an SQL statement. + # It replaces all instances of the single-quote character with two + # single-quote characters. The modified string is returned. + def quote( string ) + string.gsub( /'/, "''" ) + end + + end + + # A boolean that indicates whether rows in result sets should be returned + # as hashes or not. By default, rows are returned as arrays. + attr_accessor :results_as_hash + + # call-seq: SQLite3::Database.new(file, options = {}) + # + # Create a new Database object that opens the given file. If utf16 + # is +true+, the filename is interpreted as a UTF-16 encoded string. + # + # By default, the new database will return result rows as arrays + # (#results_as_hash) and has type translation disabled (#type_translation=). + + def initialize file, options = {}, zvfs = nil + mode = Constants::Open::READWRITE | Constants::Open::CREATE + + if file.encoding == ::Encoding::UTF_16LE || file.encoding == ::Encoding::UTF_16BE || options[:utf16] + open16 file + else + # The three primary flag values for sqlite3_open_v2 are: + # SQLITE_OPEN_READONLY + # SQLITE_OPEN_READWRITE + # SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE -- always used for sqlite3_open and sqlite3_open16 + mode = Constants::Open::READONLY if options[:readonly] + + if options[:readwrite] + raise "conflicting options: readonly and readwrite" if options[:readonly] + mode = Constants::Open::READWRITE + end + + if options[:flags] + if options[:readonly] || options[:readwrite] + raise "conflicting options: flags with readonly and/or readwrite" + end + mode = options[:flags] + end + + open_v2 file.encode("utf-8"), mode, zvfs + end + + @tracefunc = nil + @authorizer = nil + @encoding = nil + @busy_handler = nil + @collations = {} + @functions = {} + @results_as_hash = options[:results_as_hash] + @type_translation = options[:type_translation] + @type_translator = make_type_translator @type_translation + @readonly = mode & Constants::Open::READONLY != 0 + + if block_given? + begin + yield self + ensure + close + end + end + end + + def type_translation= value # :nodoc: + warn(<<-eowarn) if $VERBOSE +#{caller[0]} is calling SQLite3::Database#type_translation= +SQLite3::Database#type_translation= is deprecated and will be removed +in version 2.0.0. + eowarn + @type_translator = make_type_translator value + @type_translation = value + end + attr_reader :type_translation # :nodoc: + + # Return the type translator employed by this database instance. Each + # database instance has its own type translator; this allows for different + # type handlers to be installed in each instance without affecting other + # instances. Furthermore, the translators are instantiated lazily, so that + # if a database does not use type translation, it will not be burdened by + # the overhead of a useless type translator. (See the Translator class.) + def translator + @translator ||= Translator.new + end + + # Installs (or removes) a block that will be invoked for every access + # to the database. If the block returns 0 (or +nil+), the statement + # is allowed to proceed. Returning 1 causes an authorization error to + # occur, and returning 2 causes the access to be silently denied. + def authorizer( &block ) + self.authorizer = block + end + + # Returns a Statement object representing the given SQL. This does not + # execute the statement; it merely prepares the statement for execution. + # + # The Statement can then be executed using Statement#execute. + # + def prepare sql + stmt = SQLite3::Statement.new( self, sql ) + return stmt unless block_given? + + begin + yield stmt + ensure + stmt.close unless stmt.closed? + end + end + + # Returns the filename for the database named +db_name+. +db_name+ defaults + # to "main". Main return `nil` or an empty string if the database is + # temporary or in-memory. + def filename db_name = 'main' + db_filename db_name + end + + # Executes the given SQL statement. If additional parameters are given, + # they are treated as bind variables, and are bound to the placeholders in + # the query. + # + # Note that if any of the values passed to this are hashes, then the + # key/value pairs are each bound separately, with the key being used as + # the name of the placeholder to bind the value to. + # + # The block is optional. If given, it will be invoked for each row returned + # by the query. Otherwise, any results are accumulated into an array and + # returned wholesale. + # + # See also #execute2, #query, and #execute_batch for additional ways of + # executing statements. + def execute sql, bind_vars = [], *args, &block + if bind_vars.nil? || !args.empty? + if args.empty? + bind_vars = [] + else + bind_vars = [bind_vars] + args + end + + warn(<<-eowarn) if $VERBOSE +#{caller[0]} is calling SQLite3::Database#execute with nil or multiple bind params +without using an array. Please switch to passing bind parameters as an array. +Support for bind parameters as *args will be removed in 2.0.0. + eowarn + end + + prepare( sql ) do |stmt| + stmt.bind_params(bind_vars) + stmt = ResultSet.new self, stmt + + if block_given? + stmt.each do |row| + yield row + end + else + stmt.to_a + end + end + end + + # Executes the given SQL statement, exactly as with #execute. However, the + # first row returned (either via the block, or in the returned array) is + # always the names of the columns. Subsequent rows correspond to the data + # from the result set. + # + # Thus, even if the query itself returns no rows, this method will always + # return at least one row--the names of the columns. + # + # See also #execute, #query, and #execute_batch for additional ways of + # executing statements. + def execute2( sql, *bind_vars ) + prepare( sql ) do |stmt| + result = stmt.execute( *bind_vars ) + if block_given? + yield stmt.columns + result.each { |row| yield row } + else + return result.inject( [ stmt.columns ] ) { |arr,row| + arr << row; arr } + end + end + end + + # Executes all SQL statements in the given string. By contrast, the other + # means of executing queries will only execute the first statement in the + # string, ignoring all subsequent statements. This will execute each one + # in turn. The same bind parameters, if given, will be applied to each + # statement. + # + # This always returns +nil+, making it unsuitable for queries that return + # rows. + # + # See also #execute_batch2 for additional ways of + # executing statments. + def execute_batch( sql, bind_vars = [], *args ) + # FIXME: remove this stuff later + unless [Array, Hash].include?(bind_vars.class) + bind_vars = [bind_vars] + warn(<<-eowarn) if $VERBOSE +#{caller[0]} is calling SQLite3::Database#execute_batch with bind parameters +that are not a list of a hash. Please switch to passing bind parameters as an +array or hash. Support for this behavior will be removed in version 2.0.0. + eowarn + end + + # FIXME: remove this stuff later + if bind_vars.nil? || !args.empty? + if args.empty? + bind_vars = [] + else + bind_vars = [nil] + args + end + + warn(<<-eowarn) if $VERBOSE +#{caller[0]} is calling SQLite3::Database#execute_batch with nil or multiple bind params +without using an array. Please switch to passing bind parameters as an array. +Support for this behavior will be removed in version 2.0.0. + eowarn + end + + sql = sql.strip + until sql.empty? do + prepare( sql ) do |stmt| + unless stmt.closed? + # FIXME: this should probably use sqlite3's api for batch execution + # This implementation requires stepping over the results. + if bind_vars.length == stmt.bind_parameter_count + stmt.bind_params(bind_vars) + end + stmt.step + end + sql = stmt.remainder.strip + end + end + # FIXME: we should not return `nil` as a success return value + nil + end + + # Executes all SQL statements in the given string. By contrast, the other + # means of executing queries will only execute the first statement in the + # string, ignoring all subsequent statements. This will execute each one + # in turn. Bind parameters cannot be passed to #execute_batch2. + # + # If a query is made, all values will be returned as strings. + # If no query is made, an empty array will be returned. + # + # Because all values except for 'NULL' are returned as strings, + # a block can be passed to parse the values accordingly. + # + # See also #execute_batch for additional ways of + # executing statments. + def execute_batch2(sql, &block) + if block_given? + result = exec_batch(sql, @results_as_hash) + result.map do |val| + yield val + end + else + exec_batch(sql, @results_as_hash) + end + end + + # This is a convenience method for creating a statement, binding + # paramters to it, and calling execute: + # + # result = db.query( "select * from foo where a=?", [5]) + # # is the same as + # result = db.prepare( "select * from foo where a=?" ).execute( 5 ) + # + # You must be sure to call +close+ on the ResultSet instance that is + # returned, or you could have problems with locks on the table. If called + # with a block, +close+ will be invoked implicitly when the block + # terminates. + def query( sql, bind_vars = [], *args ) + + if bind_vars.nil? || !args.empty? + if args.empty? + bind_vars = [] + else + bind_vars = [bind_vars] + args + end + + warn(<<-eowarn) if $VERBOSE +#{caller[0]} is calling SQLite3::Database#query with nil or multiple bind params +without using an array. Please switch to passing bind parameters as an array. +Support for this will be removed in version 2.0.0. + eowarn + end + + result = prepare( sql ).execute( bind_vars ) + if block_given? + begin + yield result + ensure + result.close + end + else + return result + end + end + + # A convenience method for obtaining the first row of a result set, and + # discarding all others. It is otherwise identical to #execute. + # + # See also #get_first_value. + def get_first_row( sql, *bind_vars ) + execute( sql, *bind_vars ).first + end + + # A convenience method for obtaining the first value of the first row of a + # result set, and discarding all other values and rows. It is otherwise + # identical to #execute. + # + # See also #get_first_row. + def get_first_value( sql, *bind_vars ) + query( sql, bind_vars ) do |rs| + if (row = rs.next) + return @results_as_hash ? row[rs.columns[0]] : row[0] + end + end + nil + end + + alias :busy_timeout :busy_timeout= + + # Creates a new function for use in SQL statements. It will be added as + # +name+, with the given +arity+. (For variable arity functions, use + # -1 for the arity.) + # + # The block should accept at least one parameter--the FunctionProxy + # instance that wraps this function invocation--and any other + # arguments it needs (up to its arity). + # + # The block does not return a value directly. Instead, it will invoke + # the FunctionProxy#result= method on the +func+ parameter and + # indicate the return value that way. + # + # Example: + # + # db.create_function( "maim", 1 ) do |func, value| + # if value.nil? + # func.result = nil + # else + # func.result = value.split(//).sort.join + # end + # end + # + # puts db.get_first_value( "select maim(name) from table" ) + def create_function name, arity, text_rep=Constants::TextRep::UTF8, &block + define_function_with_flags(name, text_rep) do |*args| + fp = FunctionProxy.new + block.call(fp, *args) + fp.result + end + self + end + + # Creates a new aggregate function for use in SQL statements. Aggregate + # functions are functions that apply over every row in the result set, + # instead of over just a single row. (A very common aggregate function + # is the "count" function, for determining the number of rows that match + # a query.) + # + # The new function will be added as +name+, with the given +arity+. (For + # variable arity functions, use -1 for the arity.) + # + # The +step+ parameter must be a proc object that accepts as its first + # parameter a FunctionProxy instance (representing the function + # invocation), with any subsequent parameters (up to the function's arity). + # The +step+ callback will be invoked once for each row of the result set. + # + # The +finalize+ parameter must be a +proc+ object that accepts only a + # single parameter, the FunctionProxy instance representing the current + # function invocation. It should invoke FunctionProxy#result= to + # store the result of the function. + # + # Example: + # + # db.create_aggregate( "lengths", 1 ) do + # step do |func, value| + # func[ :total ] ||= 0 + # func[ :total ] += ( value ? value.length : 0 ) + # end + # + # finalize do |func| + # func.result = func[ :total ] || 0 + # end + # end + # + # puts db.get_first_value( "select lengths(name) from table" ) + # + # See also #create_aggregate_handler for a more object-oriented approach to + # aggregate functions. + def create_aggregate( name, arity, step=nil, finalize=nil, + text_rep=Constants::TextRep::ANY, &block ) + + proxy = Class.new do + def self.step( &block ) + define_method(:step_with_ctx, &block) + end + + def self.finalize( &block ) + define_method(:finalize_with_ctx, &block) + end + end + + if block_given? + proxy.instance_eval(&block) + else + proxy.class_eval do + define_method(:step_with_ctx, step) + define_method(:finalize_with_ctx, finalize) + end + end + + proxy.class_eval do + # class instance variables + @name = name + @arity = arity + + def self.name + @name + end + + def self.arity + @arity + end + + def initialize + @ctx = FunctionProxy.new + end + + def step( *args ) + step_with_ctx(@ctx, *args) + end + + def finalize + finalize_with_ctx(@ctx) + @ctx.result + end + end + define_aggregator2(proxy, name) + end + + # This is another approach to creating an aggregate function (see + # #create_aggregate). Instead of explicitly specifying the name, + # callbacks, arity, and type, you specify a factory object + # (the "handler") that knows how to obtain all of that information. The + # handler should respond to the following messages: + # + # +arity+:: corresponds to the +arity+ parameter of #create_aggregate. This + # message is optional, and if the handler does not respond to it, + # the function will have an arity of -1. + # +name+:: this is the name of the function. The handler _must_ implement + # this message. + # +new+:: this must be implemented by the handler. It should return a new + # instance of the object that will handle a specific invocation of + # the function. + # + # The handler instance (the object returned by the +new+ message, described + # above), must respond to the following messages: + # + # +step+:: this is the method that will be called for each step of the + # aggregate function's evaluation. It should implement the same + # signature as the +step+ callback for #create_aggregate. + # +finalize+:: this is the method that will be called to finalize the + # aggregate function's evaluation. It should implement the + # same signature as the +finalize+ callback for + # #create_aggregate. + # + # Example: + # + # class LengthsAggregateHandler + # def self.arity; 1; end + # def self.name; 'lengths'; end + # + # def initialize + # @total = 0 + # end + # + # def step( ctx, name ) + # @total += ( name ? name.length : 0 ) + # end + # + # def finalize( ctx ) + # ctx.result = @total + # end + # end + # + # db.create_aggregate_handler( LengthsAggregateHandler ) + # puts db.get_first_value( "select lengths(name) from A" ) + def create_aggregate_handler( handler ) + # This is a compatiblity shim so the (basically pointless) FunctionProxy + # "ctx" object is passed as first argument to both step() and finalize(). + # Now its up to the library user whether he prefers to store his + # temporaries as instance varibales or fields in the FunctionProxy. + # The library user still must set the result value with + # FunctionProxy.result= as there is no backwards compatible way to + # change this. + proxy = Class.new(handler) do + def initialize + super + @fp = FunctionProxy.new + end + + def step( *args ) + super(@fp, *args) + end + + def finalize + super(@fp) + @fp.result + end + end + define_aggregator2(proxy, proxy.name) + self + end + + # Define an aggregate function named +name+ using a object template + # object +aggregator+. +aggregator+ must respond to +step+ and +finalize+. + # +step+ will be called with row information and +finalize+ must return the + # return value for the aggregator function. + # + # _API Change:_ +aggregator+ must also implement +clone+. The provided + # +aggregator+ object will serve as template that is cloned to provide the + # individual instances of the aggregate function. Regular ruby objects + # already provide a suitable +clone+. + # The functions arity is the arity of the +step+ method. + def define_aggregator( name, aggregator ) + # Previously, this has been implemented in C. Now this is just yet + # another compatiblity shim + proxy = Class.new do + @template = aggregator + @name = name + + def self.template + @template + end + + def self.name + @name + end + + def self.arity + # this is what sqlite3_obj_method_arity did before + @template.method(:step).arity + end + + def initialize + @klass = self.class.template.clone + end + + def step(*args) + @klass.step(*args) + end + + def finalize + @klass.finalize + end + end + define_aggregator2(proxy, name) + self + end + + # Begins a new transaction. Note that nested transactions are not allowed + # by SQLite, so attempting to nest a transaction will result in a runtime + # exception. + # + # The +mode+ parameter may be either :deferred (the default), + # :immediate, or :exclusive. + # + # If a block is given, the database instance is yielded to it, and the + # transaction is committed when the block terminates. If the block + # raises an exception, a rollback will be performed instead. Note that if + # a block is given, #commit and #rollback should never be called + # explicitly or you'll get an error when the block terminates. + # + # If a block is not given, it is the caller's responsibility to end the + # transaction explicitly, either by calling #commit, or by calling + # #rollback. + def transaction( mode = :deferred ) + execute "begin #{mode.to_s} transaction" + + if block_given? + abort = false + begin + yield self + rescue + abort = true + raise + ensure + abort and rollback or commit + end + end + + true + end + + # Commits the current transaction. If there is no current transaction, + # this will cause an error to be raised. This returns +true+, in order + # to allow it to be used in idioms like + # abort? and rollback or commit. + def commit + execute "commit transaction" + true + end + + # Rolls the current transaction back. If there is no current transaction, + # this will cause an error to be raised. This returns +true+, in order + # to allow it to be used in idioms like + # abort? and rollback or commit. + def rollback + execute "rollback transaction" + true + end + + # Returns +true+ if the database has been open in readonly mode + # A helper to check before performing any operation + def readonly? + @readonly + end + + # A helper class for dealing with custom functions (see #create_function, + # #create_aggregate, and #create_aggregate_handler). It encapsulates the + # opaque function object that represents the current invocation. It also + # provides more convenient access to the API functions that operate on + # the function object. + # + # This class will almost _always_ be instantiated indirectly, by working + # with the create methods mentioned above. + class FunctionProxy + attr_accessor :result + + # Create a new FunctionProxy that encapsulates the given +func+ object. + # If context is non-nil, the functions context will be set to that. If + # it is non-nil, it must quack like a Hash. If it is nil, then none of + # the context functions will be available. + def initialize + @result = nil + @context = {} + end + + # Set the result of the function to the given error message. + # The function will then return that error. + def set_error( error ) + @driver.result_error( @func, error.to_s, -1 ) + end + + # (Only available to aggregate functions.) Returns the number of rows + # that the aggregate has processed so far. This will include the current + # row, and so will always return at least 1. + def count + @driver.aggregate_count( @func ) + end + + # Returns the value with the given key from the context. This is only + # available to aggregate functions. + def []( key ) + @context[ key ] + end + + # Sets the value with the given key in the context. This is only + # available to aggregate functions. + def []=( key, value ) + @context[ key ] = value + end + end + + # Translates a +row+ of data from the database with the given +types+ + def translate_from_db types, row + @type_translator.call types, row + end + + private + + NULL_TRANSLATOR = lambda { |_, row| row } + + def make_type_translator should_translate + if should_translate + lambda { |types, row| + types.zip(row).map do |type, value| + translator.translate( type, value ) + end + } + else + NULL_TRANSLATOR + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/errors.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/errors.rb new file mode 100644 index 0000000..87c7b4e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/errors.rb @@ -0,0 +1,35 @@ +require 'sqlite3/constants' + +module SQLite3 + class Exception < ::StandardError + # A convenience for accessing the error code for this exception. + attr_reader :code + end + + class SQLException < Exception; end + class InternalException < Exception; end + class PermissionException < Exception; end + class AbortException < Exception; end + class BusyException < Exception; end + class LockedException < Exception; end + class MemoryException < Exception; end + class ReadOnlyException < Exception; end + class InterruptException < Exception; end + class IOException < Exception; end + class CorruptException < Exception; end + class NotFoundException < Exception; end + class FullException < Exception; end + class CantOpenException < Exception; end + class ProtocolException < Exception; end + class EmptyException < Exception; end + class SchemaChangedException < Exception; end + class TooBigException < Exception; end + class ConstraintException < Exception; end + class MismatchException < Exception; end + class MisuseException < Exception; end + class UnsupportedException < Exception; end + class AuthorizationException < Exception; end + class FormatException < Exception; end + class RangeException < Exception; end + class NotADatabaseException < Exception; end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/pragmas.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/pragmas.rb new file mode 100644 index 0000000..6fd4ae1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/pragmas.rb @@ -0,0 +1,588 @@ +require 'sqlite3/errors' + +module SQLite3 + + # This module is intended for inclusion solely by the Database class. It + # defines convenience methods for the various pragmas supported by SQLite3. + # + # For a detailed description of these pragmas, see the SQLite3 documentation + # at http://sqlite.org/pragma.html. + module Pragmas + + # Returns +true+ or +false+ depending on the value of the named pragma. + def get_boolean_pragma( name ) + get_first_value( "PRAGMA #{name}" ) != "0" + end + + # Sets the given pragma to the given boolean value. The value itself + # may be +true+ or +false+, or any other commonly used string or + # integer that represents truth. + def set_boolean_pragma( name, mode ) + case mode + when String + case mode.downcase + when "on", "yes", "true", "y", "t"; mode = "'ON'" + when "off", "no", "false", "n", "f"; mode = "'OFF'" + else + raise Exception, + "unrecognized pragma parameter #{mode.inspect}" + end + when true, 1 + mode = "ON" + when false, 0, nil + mode = "OFF" + else + raise Exception, + "unrecognized pragma parameter #{mode.inspect}" + end + + execute( "PRAGMA #{name}=#{mode}" ) + end + + # Requests the given pragma (and parameters), and if the block is given, + # each row of the result set will be yielded to it. Otherwise, the results + # are returned as an array. + def get_query_pragma( name, *parms, &block ) # :yields: row + if parms.empty? + execute( "PRAGMA #{name}", &block ) + else + args = "'" + parms.join("','") + "'" + execute( "PRAGMA #{name}( #{args} )", &block ) + end + end + + # Return the value of the given pragma. + def get_enum_pragma( name ) + get_first_value( "PRAGMA #{name}" ) + end + + # Set the value of the given pragma to +mode+. The +mode+ parameter must + # conform to one of the values in the given +enum+ array. Each entry in + # the array is another array comprised of elements in the enumeration that + # have duplicate values. See #synchronous, #default_synchronous, + # #temp_store, and #default_temp_store for usage examples. + def set_enum_pragma( name, mode, enums ) + match = enums.find { |p| p.find { |i| i.to_s.downcase == mode.to_s.downcase } } + raise Exception, + "unrecognized #{name} #{mode.inspect}" unless match + execute( "PRAGMA #{name}='#{match.first.upcase}'" ) + end + + # Returns the value of the given pragma as an integer. + def get_int_pragma( name ) + get_first_value( "PRAGMA #{name}" ).to_i + end + + # Set the value of the given pragma to the integer value of the +value+ + # parameter. + def set_int_pragma( name, value ) + execute( "PRAGMA #{name}=#{value.to_i}" ) + end + + # The enumeration of valid synchronous modes. + SYNCHRONOUS_MODES = [ [ 'full', 2 ], [ 'normal', 1 ], [ 'off', 0 ] ] + + # The enumeration of valid temp store modes. + TEMP_STORE_MODES = [ [ 'default', 0 ], [ 'file', 1 ], [ 'memory', 2 ] ] + + # The enumeration of valid auto vacuum modes. + AUTO_VACUUM_MODES = [ [ 'none', 0 ], [ 'full', 1 ], [ 'incremental', 2 ] ] + + # The list of valid journaling modes. + JOURNAL_MODES = [ [ 'delete' ], [ 'truncate' ], [ 'persist' ], [ 'memory' ], + [ 'wal' ], [ 'off' ] ] + + # The list of valid locking modes. + LOCKING_MODES = [ [ 'normal' ], [ 'exclusive' ] ] + + # The list of valid encodings. + ENCODINGS = [ [ 'utf-8' ], [ 'utf-16' ], [ 'utf-16le' ], [ 'utf-16be ' ] ] + + # The list of valid WAL checkpoints. + WAL_CHECKPOINTS = [ [ 'passive' ], [ 'full' ], [ 'restart' ], [ 'truncate' ] ] + + def application_id + get_int_pragma "application_id" + end + + def application_id=( integer ) + set_int_pragma "application_id", integer + end + + def auto_vacuum + get_enum_pragma "auto_vacuum" + end + + def auto_vacuum=( mode ) + set_enum_pragma "auto_vacuum", mode, AUTO_VACUUM_MODES + end + + def automatic_index + get_boolean_pragma "automatic_index" + end + + def automatic_index=( mode ) + set_boolean_pragma "automatic_index", mode + end + + def busy_timeout + get_int_pragma "busy_timeout" + end + + def busy_timeout=( milliseconds ) + set_int_pragma "busy_timeout", milliseconds + end + + def cache_size + get_int_pragma "cache_size" + end + + def cache_size=( size ) + set_int_pragma "cache_size", size + end + + def cache_spill + get_boolean_pragma "cache_spill" + end + + def cache_spill=( mode ) + set_boolean_pragma "cache_spill", mode + end + + def case_sensitive_like=( mode ) + set_boolean_pragma "case_sensitive_like", mode + end + + def cell_size_check + get_boolean_pragma "cell_size_check" + end + + def cell_size_check=( mode ) + set_boolean_pragma "cell_size_check", mode + end + + def checkpoint_fullfsync + get_boolean_pragma "checkpoint_fullfsync" + end + + def checkpoint_fullfsync=( mode ) + set_boolean_pragma "checkpoint_fullfsync", mode + end + + def collation_list( &block ) # :yields: row + get_query_pragma "collation_list", &block + end + + def compile_options( &block ) # :yields: row + get_query_pragma "compile_options", &block + end + + def count_changes + get_boolean_pragma "count_changes" + end + + def count_changes=( mode ) + set_boolean_pragma "count_changes", mode + end + + def data_version + get_int_pragma "data_version" + end + + def database_list( &block ) # :yields: row + get_query_pragma "database_list", &block + end + + def default_cache_size + get_int_pragma "default_cache_size" + end + + def default_cache_size=( size ) + set_int_pragma "default_cache_size", size + end + + def default_synchronous + get_enum_pragma "default_synchronous" + end + + def default_synchronous=( mode ) + set_enum_pragma "default_synchronous", mode, SYNCHRONOUS_MODES + end + + def default_temp_store + get_enum_pragma "default_temp_store" + end + + def default_temp_store=( mode ) + set_enum_pragma "default_temp_store", mode, TEMP_STORE_MODES + end + + def defer_foreign_keys + get_boolean_pragma "defer_foreign_keys" + end + + def defer_foreign_keys=( mode ) + set_boolean_pragma "defer_foreign_keys", mode + end + + def encoding + get_enum_pragma "encoding" + end + + def encoding=( mode ) + set_enum_pragma "encoding", mode, ENCODINGS + end + + def foreign_key_check( *table, &block ) # :yields: row + get_query_pragma "foreign_key_check", *table, &block + end + + def foreign_key_list( table, &block ) # :yields: row + get_query_pragma "foreign_key_list", table, &block + end + + def foreign_keys + get_boolean_pragma "foreign_keys" + end + + def foreign_keys=( mode ) + set_boolean_pragma "foreign_keys", mode + end + + def freelist_count + get_int_pragma "freelist_count" + end + + def full_column_names + get_boolean_pragma "full_column_names" + end + + def full_column_names=( mode ) + set_boolean_pragma "full_column_names", mode + end + + def fullfsync + get_boolean_pragma "fullfsync" + end + + def fullfsync=( mode ) + set_boolean_pragma "fullfsync", mode + end + + def ignore_check_constraints=( mode ) + set_boolean_pragma "ignore_check_constraints", mode + end + + def incremental_vacuum( pages, &block ) # :yields: row + get_query_pragma "incremental_vacuum", pages, &block + end + + def index_info( index, &block ) # :yields: row + get_query_pragma "index_info", index, &block + end + + def index_list( table, &block ) # :yields: row + get_query_pragma "index_list", table, &block + end + + def index_xinfo( index, &block ) # :yields: row + get_query_pragma "index_xinfo", index, &block + end + + def integrity_check( *num_errors, &block ) # :yields: row + get_query_pragma "integrity_check", *num_errors, &block + end + + def journal_mode + get_enum_pragma "journal_mode" + end + + def journal_mode=( mode ) + set_enum_pragma "journal_mode", mode, JOURNAL_MODES + end + + def journal_size_limit + get_int_pragma "journal_size_limit" + end + + def journal_size_limit=( size ) + set_int_pragma "journal_size_limit", size + end + + def legacy_file_format + get_boolean_pragma "legacy_file_format" + end + + def legacy_file_format=( mode ) + set_boolean_pragma "legacy_file_format", mode + end + + def locking_mode + get_enum_pragma "locking_mode" + end + + def locking_mode=( mode ) + set_enum_pragma "locking_mode", mode, LOCKING_MODES + end + + def max_page_count + get_int_pragma "max_page_count" + end + + def max_page_count=( size ) + set_int_pragma "max_page_count", size + end + + def mmap_size + get_int_pragma "mmap_size" + end + + def mmap_size=( size ) + set_int_pragma "mmap_size", size + end + + def page_count + get_int_pragma "page_count" + end + + def page_size + get_int_pragma "page_size" + end + + def page_size=( size ) + set_int_pragma "page_size", size + end + + def parser_trace=( mode ) + set_boolean_pragma "parser_trace", mode + end + + def query_only + get_boolean_pragma "query_only" + end + + def query_only=( mode ) + set_boolean_pragma "query_only", mode + end + + def quick_check( *num_errors, &block ) # :yields: row + get_query_pragma "quick_check", *num_errors, &block + end + + def read_uncommitted + get_boolean_pragma "read_uncommitted" + end + + def read_uncommitted=( mode ) + set_boolean_pragma "read_uncommitted", mode + end + + def recursive_triggers + get_boolean_pragma "recursive_triggers" + end + + def recursive_triggers=( mode ) + set_boolean_pragma "recursive_triggers", mode + end + + def reverse_unordered_selects + get_boolean_pragma "reverse_unordered_selects" + end + + def reverse_unordered_selects=( mode ) + set_boolean_pragma "reverse_unordered_selects", mode + end + + def schema_cookie + get_int_pragma "schema_cookie" + end + + def schema_cookie=( cookie ) + set_int_pragma "schema_cookie", cookie + end + + def schema_version + get_int_pragma "schema_version" + end + + def schema_version=( version ) + set_int_pragma "schema_version", version + end + + def secure_delete + get_boolean_pragma "secure_delete" + end + + def secure_delete=( mode ) + set_boolean_pragma "secure_delete", mode + end + + def short_column_names + get_boolean_pragma "short_column_names" + end + + def short_column_names=( mode ) + set_boolean_pragma "short_column_names", mode + end + + def shrink_memory + execute( "PRAGMA shrink_memory" ) + end + + def soft_heap_limit + get_int_pragma "soft_heap_limit" + end + + def soft_heap_limit=( mode ) + set_int_pragma "soft_heap_limit", mode + end + + def stats( &block ) # :yields: row + get_query_pragma "stats", &block + end + + def synchronous + get_enum_pragma "synchronous" + end + + def synchronous=( mode ) + set_enum_pragma "synchronous", mode, SYNCHRONOUS_MODES + end + + def temp_store + get_enum_pragma "temp_store" + end + + def temp_store=( mode ) + set_enum_pragma "temp_store", mode, TEMP_STORE_MODES + end + + def threads + get_int_pragma "threads" + end + + def threads=( count ) + set_int_pragma "threads", count + end + + def user_cookie + get_int_pragma "user_cookie" + end + + def user_cookie=( cookie ) + set_int_pragma "user_cookie", cookie + end + + def user_version + get_int_pragma "user_version" + end + + def user_version=( version ) + set_int_pragma "user_version", version + end + + def vdbe_addoptrace=( mode ) + set_boolean_pragma "vdbe_addoptrace", mode + end + + def vdbe_debug=( mode ) + set_boolean_pragma "vdbe_debug", mode + end + + def vdbe_listing=( mode ) + set_boolean_pragma "vdbe_listing", mode + end + + def vdbe_trace + get_boolean_pragma "vdbe_trace" + end + + def vdbe_trace=( mode ) + set_boolean_pragma "vdbe_trace", mode + end + + def wal_autocheckpoint + get_int_pragma "wal_autocheckpoint" + end + + def wal_autocheckpoint=( mode ) + set_int_pragma "wal_autocheckpoint", mode + end + + def wal_checkpoint + get_enum_pragma "wal_checkpoint" + end + + def wal_checkpoint=( mode ) + set_enum_pragma "wal_checkpoint", mode, WAL_CHECKPOINTS + end + + def writable_schema=( mode ) + set_boolean_pragma "writable_schema", mode + end + + ### + # Returns information about +table+. Yields each row of table information + # if a block is provided. + def table_info table + stmt = prepare "PRAGMA table_info(#{table})" + columns = stmt.columns + + needs_tweak_default = + version_compare(SQLite3.libversion.to_s, "3.3.7") > 0 + + result = [] unless block_given? + stmt.each do |row| + new_row = Hash[columns.zip(row)] + + # FIXME: This should be removed but is required for older versions + # of rails + if(Object.const_defined?(:ActiveRecord)) + new_row['notnull'] = new_row['notnull'].to_s + end + + tweak_default(new_row) if needs_tweak_default + + if block_given? + yield new_row + else + result << new_row + end + end + stmt.close + + result + end + + private + + # Compares two version strings + def version_compare(v1, v2) + v1 = v1.split(".").map { |i| i.to_i } + v2 = v2.split(".").map { |i| i.to_i } + parts = [v1.length, v2.length].max + v1.push 0 while v1.length < parts + v2.push 0 while v2.length < parts + v1.zip(v2).each do |a,b| + return -1 if a < b + return 1 if a > b + end + return 0 + end + + # Since SQLite 3.3.8, the table_info pragma has returned the default + # value of the row as a quoted SQL value. This method essentially + # unquotes those values. + def tweak_default(hash) + case hash["dflt_value"] + when /^null$/i + hash["dflt_value"] = nil + when /^'(.*)'$/m + hash["dflt_value"] = $1.gsub(/''/, "'") + when /^"(.*)"$/m + hash["dflt_value"] = $1.gsub(/""/, '"') + end + end + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/resultset.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/resultset.rb new file mode 100644 index 0000000..5c1cc19 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/resultset.rb @@ -0,0 +1,187 @@ +require 'sqlite3/constants' +require 'sqlite3/errors' + +module SQLite3 + + # The ResultSet object encapsulates the enumerability of a query's output. + # It is a simple cursor over the data that the query returns. It will + # very rarely (if ever) be instantiated directly. Instead, clients should + # obtain a ResultSet instance via Statement#execute. + class ResultSet + include Enumerable + + class ArrayWithTypes < Array # :nodoc: + attr_accessor :types + end + + class ArrayWithTypesAndFields < Array # :nodoc: + attr_writer :types + attr_writer :fields + + def types + warn(<<-eowarn) if $VERBOSE +#{caller[0]} is calling #{self.class}#types. This method will be removed in +sqlite3 version 2.0.0, please call the `types` method on the SQLite3::ResultSet +object that created this object + eowarn + @types + end + + def fields + warn(<<-eowarn) if $VERBOSE +#{caller[0]} is calling #{self.class}#fields. This method will be removed in +sqlite3 version 2.0.0, please call the `columns` method on the SQLite3::ResultSet +object that created this object + eowarn + @fields + end + end + + # The class of which we return an object in case we want a Hash as + # result. + class HashWithTypesAndFields < Hash # :nodoc: + attr_writer :types + attr_writer :fields + + def types + warn(<<-eowarn) if $VERBOSE +#{caller[0]} is calling #{self.class}#types. This method will be removed in +sqlite3 version 2.0.0, please call the `types` method on the SQLite3::ResultSet +object that created this object + eowarn + @types + end + + def fields + warn(<<-eowarn) if $VERBOSE +#{caller[0]} is calling #{self.class}#fields. This method will be removed in +sqlite3 version 2.0.0, please call the `columns` method on the SQLite3::ResultSet +object that created this object + eowarn + @fields + end + + def [] key + key = fields[key] if key.is_a? Numeric + super key + end + end + + # Create a new ResultSet attached to the given database, using the + # given sql text. + def initialize db, stmt + @db = db + @stmt = stmt + end + + # Reset the cursor, so that a result set which has reached end-of-file + # can be rewound and reiterated. + def reset( *bind_params ) + @stmt.reset! + @stmt.bind_params( *bind_params ) + @eof = false + end + + # Query whether the cursor has reached the end of the result set or not. + def eof? + @stmt.done? + end + + # Obtain the next row from the cursor. If there are no more rows to be + # had, this will return +nil+. If type translation is active on the + # corresponding database, the values in the row will be translated + # according to their types. + # + # The returned value will be an array, unless Database#results_as_hash has + # been set to +true+, in which case the returned value will be a hash. + # + # For arrays, the column names are accessible via the +fields+ property, + # and the column types are accessible via the +types+ property. + # + # For hashes, the column names are the keys of the hash, and the column + # types are accessible via the +types+ property. + def next + if @db.results_as_hash + return next_hash + end + + row = @stmt.step + return nil if @stmt.done? + + row = @db.translate_from_db @stmt.types, row + + if row.respond_to?(:fields) + # FIXME: this can only happen if the translator returns something + # that responds to `fields`. Since we're removing the translator + # in 2.0, we can remove this branch in 2.0. + row = ArrayWithTypes.new(row) + else + # FIXME: the `fields` and `types` methods are deprecated on this + # object for version 2.0, so we can safely remove this branch + # as well. + row = ArrayWithTypesAndFields.new(row) + end + + row.fields = @stmt.columns + row.types = @stmt.types + row + end + + # Required by the Enumerable mixin. Provides an internal iterator over the + # rows of the result set. + def each + while node = self.next + yield node + end + end + + # Provides an internal iterator over the rows of the result set where + # each row is yielded as a hash. + def each_hash + while node = next_hash + yield node + end + end + + # Closes the statement that spawned this result set. + # Use with caution! Closing a result set will automatically + # close any other result sets that were spawned from the same statement. + def close + @stmt.close + end + + # Queries whether the underlying statement has been closed or not. + def closed? + @stmt.closed? + end + + # Returns the types of the columns returned by this result set. + def types + @stmt.types + end + + # Returns the names of the columns returned by this result set. + def columns + @stmt.columns + end + + # Return the next row as a hash + def next_hash + row = @stmt.step + return nil if @stmt.done? + + # FIXME: type translation is deprecated, so this can be removed + # in 2.0 + row = @db.translate_from_db @stmt.types, row + + # FIXME: this can be switched to a regular hash in 2.0 + row = HashWithTypesAndFields[*@stmt.columns.zip(row).flatten] + + # FIXME: these methods are deprecated for version 2.0, so we can remove + # this code in 2.0 + row.fields = @stmt.columns + row.types = @stmt.types + row + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/statement.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/statement.rb new file mode 100644 index 0000000..d3ae4dd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/statement.rb @@ -0,0 +1,144 @@ +require 'sqlite3/errors' +require 'sqlite3/resultset' + +class String + def to_blob + SQLite3::Blob.new( self ) + end +end + +module SQLite3 + # A statement represents a prepared-but-unexecuted SQL query. It will rarely + # (if ever) be instantiated directly by a client, and is most often obtained + # via the Database#prepare method. + class Statement + include Enumerable + + # This is any text that followed the first valid SQL statement in the text + # with which the statement was initialized. If there was no trailing text, + # this will be the empty string. + attr_reader :remainder + + # Binds the given variables to the corresponding placeholders in the SQL + # text. + # + # See Database#execute for a description of the valid placeholder + # syntaxes. + # + # Example: + # + # stmt = db.prepare( "select * from table where a=? and b=?" ) + # stmt.bind_params( 15, "hello" ) + # + # See also #execute, #bind_param, Statement#bind_param, and + # Statement#bind_params. + def bind_params( *bind_vars ) + index = 1 + bind_vars.flatten.each do |var| + if Hash === var + var.each { |key, val| bind_param key, val } + else + bind_param index, var + index += 1 + end + end + end + + # Execute the statement. This creates a new ResultSet object for the + # statement's virtual machine. If a block was given, the new ResultSet will + # be yielded to it; otherwise, the ResultSet will be returned. + # + # Any parameters will be bound to the statement using #bind_params. + # + # Example: + # + # stmt = db.prepare( "select * from table" ) + # stmt.execute do |result| + # ... + # end + # + # See also #bind_params, #execute!. + def execute( *bind_vars ) + reset! if active? || done? + + bind_params(*bind_vars) unless bind_vars.empty? + @results = ResultSet.new(@connection, self) + + step if 0 == column_count + + yield @results if block_given? + @results + end + + # Execute the statement. If no block was given, this returns an array of + # rows returned by executing the statement. Otherwise, each row will be + # yielded to the block. + # + # Any parameters will be bound to the statement using #bind_params. + # + # Example: + # + # stmt = db.prepare( "select * from table" ) + # stmt.execute! do |row| + # ... + # end + # + # See also #bind_params, #execute. + def execute!( *bind_vars, &block ) + execute(*bind_vars) + block_given? ? each(&block) : to_a + end + + # Returns true if the statement is currently active, meaning it has an + # open result set. + def active? + !done? + end + + # Return an array of the column names for this statement. Note that this + # may execute the statement in order to obtain the metadata; this makes it + # a (potentially) expensive operation. + def columns + get_metadata unless @columns + return @columns + end + + def each + loop do + val = step + break self if done? + yield val + end + end + + # Return an array of the data types for each column in this statement. Note + # that this may execute the statement in order to obtain the metadata; this + # makes it a (potentially) expensive operation. + def types + must_be_open! + get_metadata unless @types + @types + end + + # Performs a sanity check to ensure that the statement is not + # closed. If it is, an exception is raised. + def must_be_open! # :nodoc: + if closed? + raise SQLite3::Exception, "cannot use a closed statement" + end + end + + private + # A convenience method for obtaining the metadata about the query. Note + # that this will actually execute the SQL, which means it can be a + # (potentially) expensive operation. + def get_metadata + @columns = Array.new(column_count) do |column| + column_name column + end + @types = Array.new(column_count) do |column| + column_decltype column + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/translator.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/translator.rb new file mode 100644 index 0000000..69f623b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/translator.rb @@ -0,0 +1,118 @@ +require 'time' +require 'date' + +module SQLite3 + + # The Translator class encapsulates the logic and callbacks necessary for + # converting string data to a value of some specified type. Every Database + # instance may have a Translator instance, in order to assist in type + # translation (Database#type_translation). + # + # Further, applications may define their own custom type translation logic + # by registering translator blocks with the corresponding database's + # translator instance (Database#translator). + class Translator + + # Create a new Translator instance. It will be preinitialized with default + # translators for most SQL data types. + def initialize + @translators = Hash.new( proc { |type,value| value } ) + @type_name_cache = {} + register_default_translators + end + + # Add a new translator block, which will be invoked to process type + # translations to the given type. The type should be an SQL datatype, and + # may include parentheses (i.e., "VARCHAR(30)"). However, any parenthetical + # information is stripped off and discarded, so type translation decisions + # are made solely on the "base" type name. + # + # The translator block itself should accept two parameters, "type" and + # "value". In this case, the "type" is the full type name (including + # parentheses), so the block itself may include logic for changing how a + # type is translated based on the additional data. The "value" parameter + # is the (string) data to convert. + # + # The block should return the translated value. + def add_translator( type, &block ) # :yields: type, value + warn(<<-eowarn) if $VERBOSE +#{caller[0]} is calling `add_translator`. +Built in translators are deprecated and will be removed in version 2.0.0 + eowarn + @translators[ type_name( type ) ] = block + end + + # Translate the given string value to a value of the given type. In the + # absense of an installed translator block for the given type, the value + # itself is always returned. Further, +nil+ values are never translated, + # and are always passed straight through regardless of the type parameter. + def translate( type, value ) + unless value.nil? + # FIXME: this is a hack to support Sequel + if type && %w{ datetime timestamp }.include?(type.downcase) + @translators[ type_name( type ) ].call( type, value.to_s ) + else + @translators[ type_name( type ) ].call( type, value ) + end + end + end + + # A convenience method for working with type names. This returns the "base" + # type name, without any parenthetical data. + def type_name( type ) + @type_name_cache[type] ||= begin + type = "" if type.nil? + type = $1 if type =~ /^(.*?)\(/ + type.upcase + end + end + private :type_name + + # Register the default translators for the current Translator instance. + # This includes translators for most major SQL data types. + def register_default_translators + [ "time", + "timestamp" ].each { |type| add_translator( type ) { |t, v| Time.parse( v ) } } + + add_translator( "date" ) { |t,v| Date.parse(v) } + add_translator( "datetime" ) { |t,v| DateTime.parse(v) } + + [ "decimal", + "float", + "numeric", + "double", + "real", + "dec", + "fixed" ].each { |type| add_translator( type ) { |t,v| v.to_f } } + + [ "integer", + "smallint", + "mediumint", + "int", + "bigint" ].each { |type| add_translator( type ) { |t,v| v.to_i } } + + [ "bit", + "bool", + "boolean" ].each do |type| + add_translator( type ) do |t,v| + !( v.strip.gsub(/00+/,"0") == "0" || + v.downcase == "false" || + v.downcase == "f" || + v.downcase == "no" || + v.downcase == "n" ) + end + end + + add_translator( "tinyint" ) do |type, value| + if type =~ /\(\s*1\s*\)/ + value.to_i == 1 + else + value.to_i + end + end + end + private :register_default_translators + + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/value.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/value.rb new file mode 100644 index 0000000..e5e5bf2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/value.rb @@ -0,0 +1,57 @@ +require 'sqlite3/constants' + +module SQLite3 + + class Value + attr_reader :handle + + def initialize( db, handle ) + @driver = db.driver + @handle = handle + end + + def null? + type == :null + end + + def to_blob + @driver.value_blob( @handle ) + end + + def length( utf16=false ) + if utf16 + @driver.value_bytes16( @handle ) + else + @driver.value_bytes( @handle ) + end + end + + def to_f + @driver.value_double( @handle ) + end + + def to_i + @driver.value_int( @handle ) + end + + def to_int64 + @driver.value_int64( @handle ) + end + + def to_s( utf16=false ) + @driver.value_text( @handle, utf16 ) + end + + def type + case @driver.value_type( @handle ) + when Constants::ColumnType::INTEGER then :int + when Constants::ColumnType::FLOAT then :float + when Constants::ColumnType::TEXT then :text + when Constants::ColumnType::BLOB then :blob + when Constants::ColumnType::NULL then :null + end + end + + end + +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/version.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/version.rb new file mode 100644 index 0000000..efbd396 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/lib/sqlite3/version.rb @@ -0,0 +1,25 @@ +module SQLite3 + + VERSION = '1.4.2' + + module VersionProxy + + MAJOR = 1 + MINOR = 4 + TINY = 2 + BUILD = nil + + STRING = [ MAJOR, MINOR, TINY, BUILD ].compact.join( "." ) + #:beta-tag: + + VERSION = ::SQLite3::VERSION + end + + def self.const_missing(name) + return super unless name == :Version + warn(<<-eowarn) if $VERBOSE +#{caller[0]}: SQLite::Version will be removed in sqlite3-ruby version 2.0.0 + eowarn + VersionProxy + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/faq.rake b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/faq.rake new file mode 100644 index 0000000..9f8f652 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/faq.rake @@ -0,0 +1,9 @@ +# Generate FAQ +desc "Generate the FAQ document" +task :faq => ['faq/faq.html'] + +file 'faq/faq.html' => ['faq/faq.rb', 'faq/faq.yml'] do + cd 'faq' do + ruby "faq.rb > faq.html" + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/gem.rake b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/gem.rake new file mode 100644 index 0000000..be41dff --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/gem.rake @@ -0,0 +1,40 @@ +begin + require 'hoe' +rescue LoadError + # try with rubygems? + require 'rubygems' + require 'hoe' +end + +Hoe.plugin :debugging, :doofus, :git, :minitest, :bundler, :gemspec + +HOE = Hoe.spec 'sqlite3' do + developer 'Jamis Buck', 'jamis@37signals.com' + developer 'Luis Lavena', 'luislavena@gmail.com' + developer 'Aaron Patterson', 'aaron@tenderlovemaking.com' + + license "BSD-3-Clause" + + self.readme_file = 'README.rdoc' + self.history_file = 'CHANGELOG.rdoc' + self.extra_rdoc_files = FileList['*.rdoc', 'ext/**/*.c'] + + require_ruby_version ">= 1.8.7" + require_rubygems_version ">= 1.3.5" + + spec_extras[:extensions] = ["ext/sqlite3/extconf.rb"] + spec_extras[:metadata] = {'msys2_mingw_dependencies' => 'sqlite3'} + + extra_dev_deps << ['rake-compiler', "~> 1.0"] + extra_dev_deps << ['rake-compiler-dock', "~> 0.6.0"] + extra_dev_deps << ["mini_portile", "~> 0.6.2"] + extra_dev_deps << ["minitest", "~> 5.0"] + extra_dev_deps << ["hoe-bundler", "~> 1.0"] + extra_dev_deps << ["hoe-gemspec", "~> 1.0"] + + clean_globs.push('**/test.db') +end + +Hoe.add_include_dirs '.' + +# vim: syntax=ruby diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/native.rake b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/native.rake new file mode 100644 index 0000000..c5aea6d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/native.rake @@ -0,0 +1,56 @@ +# use rake-compiler for building the extension +require 'rake/extensiontask' +require 'rake/extensioncompiler' + +# NOTE: version used by cross compilation of Windows native extension +# It do not affect compilation under other operating systems +# The version indicated is the minimum DLL suggested for correct functionality +BINARY_VERSION = "3.8.11.1" +URL_VERSION = "3081101" +URL_PATH = "/2015" + +task :devkit do + begin + require "devkit" + rescue LoadError => e + abort "Failed to activate RubyInstaller's DevKit required for compilation." + end +end + +# build sqlite3_native C extension +RUBY_EXTENSION = Rake::ExtensionTask.new('sqlite3_native', HOE.spec) do |ext| + # where to locate the extension + ext.ext_dir = 'ext/sqlite3' + + # where native extension will be copied (matches makefile) + ext.lib_dir = "lib/sqlite3" + + # clean binary folders always + CLEAN.include("#{ext.lib_dir}/?.?") + + # automatically add build options to avoid need of manual input + if RUBY_PLATFORM =~ /mswin|mingw/ then + # define target for extension (supporting fat binaries) + RUBY_VERSION =~ /(\d+\.\d+)/ + ext.lib_dir = "lib/sqlite3/#{$1}" + else + + # detect cross-compiler available + begin + Rake::ExtensionCompiler.mingw_host + ext.cross_compile = true + ext.cross_platform = ['i386-mswin32-60', 'i386-mingw32', 'x64-mingw32'] + ext.cross_compiling do |spec| + # The fat binary gem doesn't depend on the sqlite3 package, since it bundles the library. + spec.metadata.delete('msys2_mingw_dependencies') + end + rescue RuntimeError + # noop + end + end +end + +# ensure things are compiled prior testing +task :test => [:compile] + +# vim: syntax=ruby diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/vendor_sqlite3.rake b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/vendor_sqlite3.rake new file mode 100644 index 0000000..bb0df79 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/rakelib/vendor_sqlite3.rake @@ -0,0 +1,97 @@ +require "rake/clean" +require "rake/extensioncompiler" +require "mini_portile" + +CLOBBER.include("ports") + +directory "ports" + +def define_sqlite_task(platform, host) + recipe = MiniPortile.new "sqlite3", BINARY_VERSION + recipe.files << "http://sqlite.org#{URL_PATH}/sqlite-autoconf-#{URL_VERSION}.tar.gz" + recipe.host = host + + desc "Compile sqlite3 for #{platform} (#{host})" + task "ports:sqlite3:#{platform}" => ["ports"] do |t| + checkpoint = "ports/.#{recipe.name}-#{recipe.version}-#{recipe.host}.installed" + + unless File.exist?(checkpoint) + cflags = "-O2 -DSQLITE_ENABLE_COLUMN_METADATA" + cflags << " -fPIC" if recipe.host && recipe.host.include?("x86_64") + recipe.configure_options << "CFLAGS='#{cflags}'" + recipe.cook + touch checkpoint + end + end + + recipe +end + +# native sqlite3 compilation +recipe = define_sqlite_task(RUBY_PLATFORM, RbConfig::CONFIG["host"]) + +# force compilation of sqlite3 when working natively under MinGW +if RUBY_PLATFORM =~ /mingw/ + RUBY_EXTENSION.config_options << "--with-opt-dir=#{recipe.path}" + + # also prepend DevKit into compilation phase + Rake::Task["compile"].prerequisites.unshift "devkit", "ports:sqlite3:#{RUBY_PLATFORM}" + Rake::Task["native"].prerequisites.unshift "devkit", "ports:sqlite3:#{RUBY_PLATFORM}" +end + +# trick to test local compilation of sqlite3 +if ENV["USE_MINI_PORTILE"] == "true" + # fake recipe so we can build a directory to it + recipe = MiniPortile.new "sqlite3", BINARY_VERSION + recipe.host = RbConfig::CONFIG["host"] + + RUBY_EXTENSION.config_options << "--with-opt-dir=#{recipe.path}" + + # compile sqlite3 first + Rake::Task["compile"].prerequisites.unshift "ports:sqlite3:#{RUBY_PLATFORM}" +end + +# iterate over all cross-compilation platforms and define the proper +# sqlite3 recipe for it. +if RUBY_EXTENSION.cross_compile + config_path = File.expand_path("~/.rake-compiler/config.yml") + if File.exist?(config_path) + # obtains platforms from rake-compiler's config.yml + config_file = YAML.load_file(config_path) + + Array(RUBY_EXTENSION.cross_platform).each do |platform| + # obtain platform from rbconfig file + config_key = config_file.keys.sort.find { |key| + key.start_with?("rbconfig-#{platform}-") + } + rbfile = config_file[config_key] + + # skip if rbconfig cannot be read + next unless File.exist?(rbfile) + + host = IO.read(rbfile).match(/CONFIG\["CC"\] = "(.*)"/)[1].sub(/\-gcc/, '') + recipe = define_sqlite_task(platform, host) + + RUBY_EXTENSION.cross_config_options << { + platform => "--with-opt-dir=#{recipe.path}" + } + + # pre-compile sqlite3 port when cross-compiling + task :cross => "ports:sqlite3:#{platform}" + end + else + warn "rake-compiler configuration doesn't exist, but is required for ports" + end +end + +task :cross do + ["CC", "CXX", "LDFLAGS", "CPPFLAGS", "RUBYOPT"].each do |var| + ENV.delete(var) + end +end + +desc "Build windows binary gems per rake-compiler-dock." +task "gem:windows" do + require "rake_compiler_dock" + RakeCompilerDock.sh "bundle && rake cross native gem MAKE='nice make -j`nproc`'" +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/setup.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/setup.rb new file mode 100644 index 0000000..bce201d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/setup.rb @@ -0,0 +1,1333 @@ +# +# setup.rb +# +# Copyright (c) 2000-2004 Minero Aoki +# +# This program is free software. +# You can distribute/modify this program under the terms of +# the GNU LGPL, Lesser General Public License version 2.1. +# + +# +# For backward compatibility +# + +unless Enumerable.method_defined?(:map) + module Enumerable + alias map collect + end +end + +unless Enumerable.method_defined?(:detect) + module Enumerable + alias detect find + end +end + +unless Enumerable.method_defined?(:select) + module Enumerable + alias select find_all + end +end + +unless Enumerable.method_defined?(:reject) + module Enumerable + def reject + select {|i| not yield(i) } + end + end +end + +unless Enumerable.method_defined?(:inject) + module Enumerable + def inject(result) + each do |i| + result = yield(result, i) + end + result + end + end +end + +unless Enumerable.method_defined?(:any?) + module Enumerable + def any? + each do |i| + return true if yield(i) + end + false + end + end +end + +unless File.respond_to?(:read) + def File.read(fname) + open(fname) {|f| + return f.read + } + end +end + +# +# Application independent utilities +# + +def File.binread(fname) + open(fname, 'rb') {|f| + return f.read + } +end + +# for corrupted windows stat(2) +def File.dir?(path) + File.directory?((path[-1,1] == '/') ? path : path + '/') +end + +# +# Config +# + +if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } + ARGV.delete(arg) + require arg.split(/=/, 2)[1] + $".push 'rbconfig.rb' +else + require 'rbconfig' +end + +def multipackage_install? + FileTest.directory?(File.dirname($0) + '/packages') +end + + +class ConfigTable + + c = ::RbConfig::CONFIG + + rubypath = c['bindir'] + '/' + c['ruby_install_name'] + + major = c['MAJOR'].to_i + minor = c['MINOR'].to_i + teeny = c['TEENY'].to_i + version = "#{major}.#{minor}" + + # ruby ver. >= 1.4.4? + newpath_p = ((major >= 2) or + ((major == 1) and + ((minor >= 5) or + ((minor == 4) and (teeny >= 4))))) + + subprefix = lambda {|path| + path.sub(/\A#{Regexp.quote(c['prefix'])}/o, '$prefix') + } + + if c['rubylibdir'] + # V < 1.6.3 + stdruby = subprefix.call(c['rubylibdir']) + siteruby = subprefix.call(c['sitedir']) + versite = subprefix.call(c['sitelibdir']) + sodir = subprefix.call(c['sitearchdir']) + elsif newpath_p + # 1.4.4 <= V <= 1.6.3 + stdruby = "$prefix/lib/ruby/#{version}" + siteruby = subprefix.call(c['sitedir']) + versite = siteruby + '/' + version + sodir = "$site-ruby/#{c['arch']}" + else + # V < 1.4.4 + stdruby = "$prefix/lib/ruby/#{version}" + siteruby = "$prefix/lib/ruby/#{version}/site_ruby" + versite = siteruby + sodir = "$site-ruby/#{c['arch']}" + end + + if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } + makeprog = arg.sub(/'/, '').split(/=/, 2)[1] + else + makeprog = 'make' + end + + common_descripters = [ + [ 'prefix', [ c['prefix'], + 'path', + 'path prefix of target environment' ] ], + [ 'std-ruby', [ stdruby, + 'path', + 'the directory for standard ruby libraries' ] ], + [ 'site-ruby-common', [ siteruby, + 'path', + 'the directory for version-independent non-standard ruby libraries' ] ], + [ 'site-ruby', [ versite, + 'path', + 'the directory for non-standard ruby libraries' ] ], + [ 'bin-dir', [ '$prefix/bin', + 'path', + 'the directory for commands' ] ], + [ 'rb-dir', [ '$site-ruby', + 'path', + 'the directory for ruby scripts' ] ], + [ 'so-dir', [ sodir, + 'path', + 'the directory for ruby extentions' ] ], + [ 'data-dir', [ '$prefix/share', + 'path', + 'the directory for shared data' ] ], + [ 'ruby-path', [ rubypath, + 'path', + 'path to set to #! line' ] ], + [ 'ruby-prog', [ rubypath, + 'name', + 'the ruby program using for installation' ] ], + [ 'make-prog', [ makeprog, + 'name', + 'the make program to compile ruby extentions' ] ], + [ 'without-ext', [ 'no', + 'yes/no', + 'does not compile/install ruby extentions' ] ] + ] + multipackage_descripters = [ + [ 'with', [ '', + 'name,name...', + 'package names that you want to install', + 'ALL' ] ], + [ 'without', [ '', + 'name,name...', + 'package names that you do not want to install', + 'NONE' ] ] + ] + if multipackage_install? + DESCRIPTER = common_descripters + multipackage_descripters + else + DESCRIPTER = common_descripters + end + + SAVE_FILE = '.config' + + def ConfigTable.each_name(&block) + keys().each(&block) + end + + def ConfigTable.keys + DESCRIPTER.map {|name, *dummy| name } + end + + def ConfigTable.each_definition(&block) + DESCRIPTER.each(&block) + end + + def ConfigTable.get_entry(name) + name, ent = DESCRIPTER.assoc(name) + ent + end + + def ConfigTable.get_entry!(name) + get_entry(name) or raise ArgumentError, "no such config: #{name}" + end + + def ConfigTable.add_entry(name, vals) + ConfigTable::DESCRIPTER.push [name,vals] + end + + def ConfigTable.remove_entry(name) + get_entry(name) or raise ArgumentError, "no such config: #{name}" + DESCRIPTER.delete_if {|n, arr| n == name } + end + + def ConfigTable.config_key?(name) + get_entry(name) ? true : false + end + + def ConfigTable.bool_config?(name) + ent = get_entry(name) or return false + ent[1] == 'yes/no' + end + + def ConfigTable.value_config?(name) + ent = get_entry(name) or return false + ent[1] != 'yes/no' + end + + def ConfigTable.path_config?(name) + ent = get_entry(name) or return false + ent[1] == 'path' + end + + + class << self + alias newobj new + end + + def ConfigTable.new + c = newobj() + c.initialize_from_table + c + end + + def ConfigTable.load + c = newobj() + c.initialize_from_file + c + end + + def initialize_from_table + @table = {} + DESCRIPTER.each do |k, (default, vname, desc, default2)| + @table[k] = default + end + end + + def initialize_from_file + raise InstallError, "#{File.basename $0} config first"\ + unless File.file?(SAVE_FILE) + @table = {} + File.foreach(SAVE_FILE) do |line| + k, v = line.split(/=/, 2) + @table[k] = v.strip + end + end + + def save + File.open(SAVE_FILE, 'w') {|f| + @table.each do |k, v| + f.printf "%s=%s\n", k, v if v + end + } + end + + def []=(k, v) + raise InstallError, "unknown config option #{k}"\ + unless ConfigTable.config_key?(k) + @table[k] = v + end + + def [](key) + return nil unless @table[key] + @table[key].gsub(%r<\$([^/]+)>) { self[$1] } + end + + def set_raw(key, val) + @table[key] = val + end + + def get_raw(key) + @table[key] + end + +end + + +module MetaConfigAPI + + def eval_file_ifexist(fname) + instance_eval File.read(fname), fname, 1 if File.file?(fname) + end + + def config_names + ConfigTable.keys + end + + def config?(name) + ConfigTable.config_key?(name) + end + + def bool_config?(name) + ConfigTable.bool_config?(name) + end + + def value_config?(name) + ConfigTable.value_config?(name) + end + + def path_config?(name) + ConfigTable.path_config?(name) + end + + def add_config(name, argname, default, desc) + ConfigTable.add_entry name,[default,argname,desc] + end + + def add_path_config(name, default, desc) + add_config name, 'path', default, desc + end + + def add_bool_config(name, default, desc) + add_config name, 'yes/no', default ? 'yes' : 'no', desc + end + + def set_config_default(name, default) + if bool_config?(name) + ConfigTable.get_entry!(name)[0] = (default ? 'yes' : 'no') + else + ConfigTable.get_entry!(name)[0] = default + end + end + + def remove_config(name) + ent = ConfigTable.get_entry(name) + ConfigTable.remove_entry name + ent + end + +end + +# +# File Operations +# + +module FileOperations + + def mkdir_p(dirname, prefix = nil) + dirname = prefix + dirname if prefix + $stderr.puts "mkdir -p #{dirname}" if verbose? + return if no_harm? + + # does not check '/'... it's too abnormal case + dirs = dirname.split(%r<(?=/)>) + if /\A[a-z]:\z/i =~ dirs[0] + disk = dirs.shift + dirs[0] = disk + dirs[0] + end + dirs.each_index do |idx| + path = dirs[0..idx].join('') + Dir.mkdir path unless File.dir?(path) + end + end + + def rm_f(fname) + $stderr.puts "rm -f #{fname}" if verbose? + return if no_harm? + + if File.exist?(fname) or File.symlink?(fname) + File.chmod 0777, fname + File.unlink fname + end + end + + def rm_rf(dn) + $stderr.puts "rm -rf #{dn}" if verbose? + return if no_harm? + + Dir.chdir dn + Dir.foreach('.') do |fn| + next if fn == '.' + next if fn == '..' + if File.dir?(fn) + verbose_off { + rm_rf fn + } + else + verbose_off { + rm_f fn + } + end + end + Dir.chdir '..' + Dir.rmdir dn + end + + def move_file(src, dest) + File.unlink dest if File.exist?(dest) + begin + File.rename src, dest + rescue + File.open(dest, 'wb') {|f| f.write File.binread(src) } + File.chmod File.stat(src).mode, dest + File.unlink src + end + end + + def install(from, dest, mode, prefix = nil) + $stderr.puts "install #{from} #{dest}" if verbose? + return if no_harm? + + realdest = prefix ? prefix + dest : dest + realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) + str = File.binread(from) + if diff?(str, realdest) + verbose_off { + rm_f realdest if File.exist?(realdest) + } + File.open(realdest, 'wb') {|f| + f.write str + } + File.chmod mode, realdest + + File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| + if prefix + f.puts realdest.sub(prefix, '') + else + f.puts realdest + end + } + end + end + + def diff?(new_content, path) + return true unless File.exist?(path) + new_content != File.binread(path) + end + + def command(str) + $stderr.puts str if verbose? + system str or raise RuntimeError, "'system #{str}' failed" + end + + def ruby(str) + command config('ruby-prog') + ' ' + str + end + + def make(task = '') + command config('make-prog') + ' ' + task + end + + def extdir?(dir) + File.exist?(dir + '/MANIFEST') or File.exist?("#{dir}/extconf.rb") + end + + def all_files_in(dirname) + Dir.open(dirname) {|d| + return d.select {|ent| File.file?("#{dirname}/#{ent}") } + } + end + + REJECT_DIRS = %w( + CVS SCCS RCS CVS.adm .svn + ) + + def all_dirs_in(dirname) + Dir.open(dirname) {|d| + return d.select {|n| File.dir?("#{dirname}/#{n}") } - %w(. ..) - REJECT_DIRS + } + end + +end + +# +# Main Installer +# + +class InstallError < StandardError; end + + +module HookUtils + + def run_hook(name) + try_run_hook "#{curr_srcdir()}/#{name}" or + try_run_hook "#{curr_srcdir()}/#{name}.rb" + end + + def try_run_hook(fname) + return false unless File.file?(fname) + begin + instance_eval File.read(fname), fname, 1 + rescue + raise InstallError, "hook #{fname} failed:\n" + $!.message + end + true + end + +end + + +module HookScriptAPI + + def get_config(key) + @config[key] + end + + alias config get_config + + def set_config(key, val) + @config[key] = val + end + + # + # srcdir/objdir (works only in the package directory) + # + + #abstract srcdir_root + #abstract objdir_root + #abstract relpath + + def curr_srcdir + "#{srcdir_root()}/#{relpath()}" + end + + def curr_objdir + "#{objdir_root()}/#{relpath()}" + end + + def srcfile(path) + "#{curr_srcdir()}/#{path}" + end + + def srcexist?(path) + File.exist?(srcfile(path)) + end + + def srcdirectory?(path) + File.dir?(srcfile(path)) + end + + def srcfile?(path) + File.file? srcfile(path) + end + + def srcentries(path = '.') + Dir.open("#{curr_srcdir()}/#{path}") {|d| + return d.to_a - %w(. ..) + } + end + + def srcfiles(path = '.') + srcentries(path).select {|fname| + File.file?(File.join(curr_srcdir(), path, fname)) + } + end + + def srcdirectories(path = '.') + srcentries(path).select {|fname| + File.dir?(File.join(curr_srcdir(), path, fname)) + } + end + +end + + +class ToplevelInstaller + + Version = '3.3.0' + Copyright = 'Copyright (c) 2000-2004 Minero Aoki' + + TASKS = [ + [ 'all', 'do config, setup, then install' ], + [ 'config', 'saves your configurations' ], + [ 'show', 'shows current configuration' ], + [ 'setup', 'compiles ruby extentions and others' ], + [ 'install', 'installs files' ], + [ 'clean', "does `make clean' for each extention" ], + [ 'distclean',"does `make distclean' for each extention" ] + ] + + def ToplevelInstaller.invoke + instance().invoke + end + + @singleton = nil + + def ToplevelInstaller.instance + @singleton ||= new(File.dirname($0)) + @singleton + end + + include MetaConfigAPI + + def initialize(ardir_root) + @config = nil + @options = { 'verbose' => true } + @ardir = File.expand_path(ardir_root) + end + + def inspect + "#<#{self.class} #{__id__()}>" + end + + def invoke + run_metaconfigs + case task = parsearg_global() + when nil, 'all' + @config = load_config('config') + parsearg_config + init_installers + exec_config + exec_setup + exec_install + else + @config = load_config(task) + __send__ "parsearg_#{task}" + init_installers + __send__ "exec_#{task}" + end + end + + def run_metaconfigs + eval_file_ifexist "#{@ardir}/metaconfig" + end + + def load_config(task) + case task + when 'config' + ConfigTable.new + when 'clean', 'distclean' + if File.exist?(ConfigTable::SAVE_FILE) + then ConfigTable.load + else ConfigTable.new + end + else + ConfigTable.load + end + end + + def init_installers + @installer = Installer.new(@config, @options, @ardir, File.expand_path('.')) + end + + # + # Hook Script API bases + # + + def srcdir_root + @ardir + end + + def objdir_root + '.' + end + + def relpath + '.' + end + + # + # Option Parsing + # + + def parsearg_global + valid_task = /\A(?:#{TASKS.map {|task,desc| task }.join '|'})\z/ + + while arg = ARGV.shift + case arg + when /\A\w+\z/ + raise InstallError, "invalid task: #{arg}" unless valid_task =~ arg + return arg + + when '-q', '--quiet' + @options['verbose'] = false + + when '--verbose' + @options['verbose'] = true + + when '-h', '--help' + print_usage $stdout + exit 0 + + when '-v', '--version' + puts "#{File.basename($0)} version #{Version}" + exit 0 + + when '--copyright' + puts Copyright + exit 0 + + else + raise InstallError, "unknown global option '#{arg}'" + end + end + + nil + end + + + def parsearg_no_options + raise InstallError, "#{task}: unknown options: #{ARGV.join ' '}"\ + unless ARGV.empty? + end + + alias parsearg_show parsearg_no_options + alias parsearg_setup parsearg_no_options + alias parsearg_clean parsearg_no_options + alias parsearg_distclean parsearg_no_options + + def parsearg_config + re = /\A--(#{ConfigTable.keys.join '|'})(?:=(.*))?\z/ + @options['config-opt'] = [] + + while i = ARGV.shift + if /\A--?\z/ =~ i + @options['config-opt'] = ARGV.dup + break + end + m = re.match(i) or raise InstallError, "config: unknown option #{i}" + name, value = m.to_a[1,2] + if value + if ConfigTable.bool_config?(name) + raise InstallError, "config: --#{name} allows only yes/no for argument"\ + unless /\A(y(es)?|n(o)?|t(rue)?|f(alse))\z/i =~ value + value = (/\Ay(es)?|\At(rue)/i =~ value) ? 'yes' : 'no' + end + else + raise InstallError, "config: --#{name} requires argument"\ + unless ConfigTable.bool_config?(name) + value = 'yes' + end + @config[name] = value + end + end + + def parsearg_install + @options['no-harm'] = false + @options['install-prefix'] = '' + while a = ARGV.shift + case a + when /\A--no-harm\z/ + @options['no-harm'] = true + when /\A--prefix=(.*)\z/ + path = $1 + path = File.expand_path(path) unless path[0,1] == '/' + @options['install-prefix'] = path + else + raise InstallError, "install: unknown option #{a}" + end + end + end + + def print_usage(out) + out.puts 'Typical Installation Procedure:' + out.puts " $ ruby #{File.basename $0} config" + out.puts " $ ruby #{File.basename $0} setup" + out.puts " # ruby #{File.basename $0} install (may require root privilege)" + out.puts + out.puts 'Detailed Usage:' + out.puts " ruby #{File.basename $0} " + out.puts " ruby #{File.basename $0} [] []" + + fmt = " %-20s %s\n" + out.puts + out.puts 'Global options:' + out.printf fmt, '-q,--quiet', 'suppress message outputs' + out.printf fmt, ' --verbose', 'output messages verbosely' + out.printf fmt, '-h,--help', 'print this message' + out.printf fmt, '-v,--version', 'print version and quit' + out.printf fmt, ' --copyright', 'print copyright and quit' + + out.puts + out.puts 'Tasks:' + TASKS.each do |name, desc| + out.printf " %-10s %s\n", name, desc + end + + out.puts + out.puts 'Options for CONFIG or ALL:' + ConfigTable.each_definition do |name, (default, arg, desc, default2)| + out.printf " %-20s %s [%s]\n", + '--'+ name + (ConfigTable.bool_config?(name) ? '' : '='+arg), + desc, + default2 || default + end + out.printf " %-20s %s [%s]\n", + '--rbconfig=path', 'your rbconfig.rb to load', "running ruby's" + + out.puts + out.puts 'Options for INSTALL:' + out.printf " %-20s %s [%s]\n", + '--no-harm', 'only display what to do if given', 'off' + out.printf " %-20s %s [%s]\n", + '--prefix', 'install path prefix', '$prefix' + + out.puts + end + + # + # Task Handlers + # + + def exec_config + @installer.exec_config + @config.save # must be final + end + + def exec_setup + @installer.exec_setup + end + + def exec_install + @installer.exec_install + end + + def exec_show + ConfigTable.each_name do |k| + v = @config.get_raw(k) + if not v or v.empty? + v = '(not specified)' + end + printf "%-10s %s\n", k, v + end + end + + def exec_clean + @installer.exec_clean + end + + def exec_distclean + @installer.exec_distclean + end + +end + + +class ToplevelInstallerMulti < ToplevelInstaller + + include HookUtils + include HookScriptAPI + include FileOperations + + def initialize(ardir) + super + @packages = all_dirs_in("#{@ardir}/packages") + raise 'no package exists' if @packages.empty? + end + + def run_metaconfigs + eval_file_ifexist "#{@ardir}/metaconfig" + @packages.each do |name| + eval_file_ifexist "#{@ardir}/packages/#{name}/metaconfig" + end + end + + def init_installers + @installers = {} + @packages.each do |pack| + @installers[pack] = Installer.new(@config, @options, + "#{@ardir}/packages/#{pack}", + "packages/#{pack}") + end + + with = extract_selection(config('with')) + without = extract_selection(config('without')) + @selected = @installers.keys.select {|name| + (with.empty? or with.include?(name)) \ + and not without.include?(name) + } + end + + def extract_selection(list) + a = list.split(/,/) + a.each do |name| + raise InstallError, "no such package: #{name}" \ + unless @installers.key?(name) + end + a + end + + def print_usage(f) + super + f.puts 'Inluded packages:' + f.puts ' ' + @packages.sort.join(' ') + f.puts + end + + # + # multi-package metaconfig API + # + + attr_reader :packages + + def declare_packages(list) + raise 'package list is empty' if list.empty? + list.each do |name| + raise "directory packages/#{name} does not exist"\ + unless File.dir?("#{@ardir}/packages/#{name}") + end + @packages = list + end + + # + # Task Handlers + # + + def exec_config + run_hook 'pre-config' + each_selected_installers {|inst| inst.exec_config } + run_hook 'post-config' + @config.save # must be final + end + + def exec_setup + run_hook 'pre-setup' + each_selected_installers {|inst| inst.exec_setup } + run_hook 'post-setup' + end + + def exec_install + run_hook 'pre-install' + each_selected_installers {|inst| inst.exec_install } + run_hook 'post-install' + end + + def exec_clean + rm_f ConfigTable::SAVE_FILE + run_hook 'pre-clean' + each_selected_installers {|inst| inst.exec_clean } + run_hook 'post-clean' + end + + def exec_distclean + rm_f ConfigTable::SAVE_FILE + run_hook 'pre-distclean' + each_selected_installers {|inst| inst.exec_distclean } + run_hook 'post-distclean' + end + + # + # lib + # + + def each_selected_installers + Dir.mkdir 'packages' unless File.dir?('packages') + @selected.each do |pack| + $stderr.puts "Processing the package `#{pack}' ..." if @options['verbose'] + Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") + Dir.chdir "packages/#{pack}" + yield @installers[pack] + Dir.chdir '../..' + end + end + + def verbose? + @options['verbose'] + end + + def no_harm? + @options['no-harm'] + end + +end + + +class Installer + + FILETYPES = %w( bin lib ext data ) + + include HookScriptAPI + include HookUtils + include FileOperations + + def initialize(config, opt, srcroot, objroot) + @config = config + @options = opt + @srcdir = File.expand_path(srcroot) + @objdir = File.expand_path(objroot) + @currdir = '.' + end + + def inspect + "#<#{self.class} #{File.basename(@srcdir)}>" + end + + # + # Hook Script API bases + # + + def srcdir_root + @srcdir + end + + def objdir_root + @objdir + end + + def relpath + @currdir + end + + # + # configs/options + # + + def no_harm? + @options['no-harm'] + end + + def verbose? + @options['verbose'] + end + + def verbose_off + begin + save, @options['verbose'] = @options['verbose'], false + yield + ensure + @options['verbose'] = save + end + end + + # + # TASK config + # + + def exec_config + exec_task_traverse 'config' + end + + def config_dir_bin(rel) + end + + def config_dir_lib(rel) + end + + def config_dir_ext(rel) + extconf if extdir?(curr_srcdir()) + end + + def extconf + opt = @options['config-opt'].join(' ') + command "#{config('ruby-prog')} #{curr_srcdir()}/extconf.rb #{opt}" + end + + def config_dir_data(rel) + end + + # + # TASK setup + # + + def exec_setup + exec_task_traverse 'setup' + end + + def setup_dir_bin(rel) + all_files_in(curr_srcdir()).each do |fname| + adjust_shebang "#{curr_srcdir()}/#{fname}" + end + end + + def adjust_shebang(path) + return if no_harm? + tmpfile = File.basename(path) + '.tmp' + begin + File.open(path, 'rb') {|r| + File.open(tmpfile, 'wb') {|w| + first = r.gets + return unless should_modify_shebang?(first) + $stderr.puts "adjusting shebang: #{File.basename(path)}" if verbose? + w.print first.sub(SHEBANG_RE, '#!' + config('ruby-path')) + w.write r.read + } + } + move_file tmpfile, File.basename(path) + ensure + File.unlink tmpfile if File.exist?(tmpfile) + end + end + + def should_modify_shebang?(line) + File.basename(config('ruby-path')) == 'ruby' or + shebang_command(line) == 'ruby' + end + + def shebang_command(line) + cmd, arg = *line.sub(/\A\#!/, '').strip.split(/\s+/, 2) + cmd + end + + def setup_dir_lib(rel) + end + + def setup_dir_ext(rel) + make if extdir?(curr_srcdir()) + end + + def setup_dir_data(rel) + end + + # + # TASK install + # + + def exec_install + exec_task_traverse 'install' + end + + def install_dir_bin(rel) + install_files collect_filenames_auto(), "#{config('bin-dir')}/#{rel}", 0755 + end + + def install_dir_lib(rel) + install_files ruby_scripts(), "#{config('rb-dir')}/#{rel}", 0644 + end + + def install_dir_ext(rel) + return unless extdir?(curr_srcdir()) + install_files ruby_extentions('.'), + "#{config('so-dir')}/#{rel}", + 0555 + end + + def install_dir_data(rel) + install_files collect_filenames_auto(), "#{config('data-dir')}/#{rel}", 0644 + end + + def install_files(list, dest, mode) + mkdir_p dest, @options['install-prefix'] + list.each do |fname| + install fname, dest, mode, @options['install-prefix'] + end + end + + def ruby_scripts + collect_filenames_auto().select {|n| /\.rb\z/ =~ n } + end + + # picked up many entries from cvs-1.11.1/src/ignore.c + reject_patterns = %w( + core RCSLOG tags TAGS .make.state + .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb + *~ *.old *.bak *.BAK *.orig *.rej _$* *$ + + *.org *.in .* + ) + mapping = { + '.' => '\.', + '$' => '\$', + '#' => '\#', + '*' => '.*' + } + REJECT_PATTERNS = Regexp.new('\A(?:' + + reject_patterns.map {|pat| + pat.gsub(/[\.\$\#\*]/) {|ch| mapping[ch] } + }.join('|') + + ')\z') + + def collect_filenames_auto + mapdir((existfiles() - hookfiles()).reject {|fname| + REJECT_PATTERNS =~ fname + }) + end + + def existfiles + all_files_in(curr_srcdir()) | all_files_in('.') + end + + def hookfiles + %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| + %w( config setup install clean ).map {|t| sprintf(fmt, t) } + }.flatten + end + + def mapdir(filelist) + filelist.map {|fname| + if File.exist?(fname) # objdir + fname + else # srcdir + File.join(curr_srcdir(), fname) + end + } + end + + def ruby_extentions(dir) + _ruby_extentions(dir) or + raise InstallError, "no ruby extention exists: 'ruby #{$0} setup' first" + end + + DLEXT = /\.#{ ::RbConfig::CONFIG['DLEXT'] }\z/ + + def _ruby_extentions(dir) + Dir.open(dir) {|d| + return d.select {|fname| DLEXT =~ fname } + } + end + + # + # TASK clean + # + + def exec_clean + exec_task_traverse 'clean' + rm_f ConfigTable::SAVE_FILE + rm_f 'InstalledFiles' + end + + def clean_dir_bin(rel) + end + + def clean_dir_lib(rel) + end + + def clean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'clean' if File.file?('Makefile') + end + + def clean_dir_data(rel) + end + + # + # TASK distclean + # + + def exec_distclean + exec_task_traverse 'distclean' + rm_f ConfigTable::SAVE_FILE + rm_f 'InstalledFiles' + end + + def distclean_dir_bin(rel) + end + + def distclean_dir_lib(rel) + end + + def distclean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'distclean' if File.file?('Makefile') + end + + # + # lib + # + + def exec_task_traverse(task) + run_hook "pre-#{task}" + FILETYPES.each do |type| + if config('without-ext') == 'yes' and type == 'ext' + $stderr.puts 'skipping ext/* by user option' if verbose? + next + end + traverse task, type, "#{task}_dir_#{type}" + end + run_hook "post-#{task}" + end + + def traverse(task, rel, mid) + dive_into(rel) { + run_hook "pre-#{task}" + __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') + all_dirs_in(curr_srcdir()).each do |d| + traverse task, "#{rel}/#{d}", mid + end + run_hook "post-#{task}" + } + end + + def dive_into(rel) + return unless File.dir?("#{@srcdir}/#{rel}") + + dir = File.basename(rel) + Dir.mkdir dir unless File.dir?(dir) + prevdir = Dir.pwd + Dir.chdir dir + $stderr.puts '---> ' + rel if verbose? + @currdir = rel + yield + Dir.chdir prevdir + $stderr.puts '<--- ' + rel if verbose? + @currdir = File.dirname(rel) + end + +end + + +if $0 == __FILE__ + begin + if multipackage_install? + ToplevelInstallerMulti.invoke + else + ToplevelInstaller.invoke + end + rescue + raise if $DEBUG + $stderr.puts $!.message + $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." + exit 1 + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/helper.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/helper.rb new file mode 100644 index 0000000..efa4a39 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/helper.rb @@ -0,0 +1,18 @@ +require 'sqlite3' +require 'minitest/autorun' + +unless RUBY_VERSION >= "1.9" + require 'iconv' +end + +module SQLite3 + class TestCase < Minitest::Test + alias :assert_not_equal :refute_equal + alias :assert_not_nil :refute_nil + alias :assert_raise :assert_raises + + def assert_nothing_raised + yield + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_backup.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_backup.rb new file mode 100644 index 0000000..4e9570b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_backup.rb @@ -0,0 +1,33 @@ +require 'helper' + +module SQLite3 + class TestBackup < SQLite3::TestCase + def setup + @sdb = SQLite3::Database.new(':memory:') + @ddb = SQLite3::Database.new(':memory:') + @sdb.execute('CREATE TABLE foo (idx, val);'); + @data = ('A'..'Z').map{|x|x * 40} + @data.each_with_index do |v, i| + @sdb.execute('INSERT INTO foo (idx, val) VALUES (?, ?);', [i, v]) + end + end + + def test_backup_step + b = SQLite3::Backup.new(@ddb, 'main', @sdb, 'main') + while b.step(1) == SQLite3::Constants::ErrorCode::OK + assert_not_equal(0, b.remaining) + end + assert_equal(0, b.remaining) + b.finish + assert_equal(@data.length, @ddb.execute('SELECT * FROM foo;').length) + end + + def test_backup_all + b = SQLite3::Backup.new(@ddb, 'main', @sdb, 'main') + assert_equal(SQLite3::Constants::ErrorCode::DONE, b.step(-1)) + assert_equal(0, b.remaining) + b.finish + assert_equal(@data.length, @ddb.execute('SELECT * FROM foo;').length) + end + end if defined?(SQLite3::Backup) +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_collation.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_collation.rb new file mode 100644 index 0000000..360335e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_collation.rb @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- + +require 'helper' + +module SQLite3 + class TestCollation < SQLite3::TestCase + class Comparator + attr_reader :calls + def initialize + @calls = [] + end + + def compare left, right + @calls << [left, right] + left <=> right + end + end + + def setup + @db = SQLite3::Database.new(':memory:') + @create = "create table ex(id int, data string)" + @db.execute(@create); + [ [1, 'hello'], [2, 'world'] ].each do |vals| + @db.execute('insert into ex (id, data) VALUES (?, ?)', vals) + end + end + + def test_custom_collation + comparator = Comparator.new + + @db.collation 'foo', comparator + + assert_equal comparator, @db.collations['foo'] + @db.execute('select data from ex order by 1 collate foo') + assert_equal 1, comparator.calls.length + end + + def test_remove_collation + comparator = Comparator.new + + @db.collation 'foo', comparator + @db.collation 'foo', nil + + assert_nil @db.collations['foo'] + assert_raises(SQLite3::SQLException) do + @db.execute('select data from ex order by 1 collate foo') + end + end + + if RUBY_VERSION >= '1.9.1' + def test_encoding + comparator = Comparator.new + @db.collation 'foo', comparator + @db.execute('select data from ex order by 1 collate foo') + + a, b = *comparator.calls.first + + assert_equal Encoding.find('UTF-8'), a.encoding + assert_equal Encoding.find('UTF-8'), b.encoding + end + + def test_encoding_default_internal + warn_before = $-w + $-w = false + before_enc = Encoding.default_internal + + Encoding.default_internal = 'EUC-JP' + comparator = Comparator.new + @db.collation 'foo', comparator + @db.execute('select data from ex order by 1 collate foo') + + a, b = *comparator.calls.first + + assert_equal Encoding.find('EUC-JP'), a.encoding + assert_equal Encoding.find('EUC-JP'), b.encoding + ensure + Encoding.default_internal = before_enc + $-w = warn_before + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database.rb new file mode 100644 index 0000000..c255ed8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database.rb @@ -0,0 +1,503 @@ +require 'helper' +require 'tempfile' +require 'pathname' + +module SQLite3 + class TestDatabase < SQLite3::TestCase + attr_reader :db + + def setup + @db = SQLite3::Database.new(':memory:') + super + end + + def test_segv + assert_raises { SQLite3::Database.new 1 } + end + + def test_db_filename + tf = nil + assert_equal '', @db.filename('main') + tf = Tempfile.new 'thing' + @db = SQLite3::Database.new tf.path + assert_equal File.expand_path(tf.path), File.expand_path(@db.filename('main')) + ensure + tf.unlink if tf + end + + def test_filename + tf = nil + assert_equal '', @db.filename + tf = Tempfile.new 'thing' + @db = SQLite3::Database.new tf.path + assert_equal File.expand_path(tf.path), File.expand_path(@db.filename) + ensure + tf.unlink if tf + end + + def test_filename_with_attachment + tf = nil + assert_equal '', @db.filename + tf = Tempfile.new 'thing' + @db.execute "ATTACH DATABASE '#{tf.path}' AS 'testing'" + assert_equal File.expand_path(tf.path), File.expand_path(@db.filename('testing')) + ensure + tf.unlink if tf + end + + def test_error_code + begin + db.execute 'SELECT' + rescue SQLite3::SQLException => e + end + assert_equal 1, e.code + end + + def test_extended_error_code + db.extended_result_codes = true + db.execute 'CREATE TABLE "employees" ("token" integer NOT NULL)' + begin + db.execute 'INSERT INTO employees (token) VALUES (NULL)' + rescue SQLite3::ConstraintException => e + end + assert_equal 1299, e.code + end + + def test_bignum + num = 4907021672125087844 + db.execute 'CREATE TABLE "employees" ("token" integer(8), "name" varchar(20) NOT NULL)' + db.execute "INSERT INTO employees(name, token) VALUES('employee-1', ?)", [num] + rows = db.execute 'select token from employees' + assert_equal num, rows.first.first + end + + def test_blob + @db.execute("CREATE TABLE blobs ( id INTEGER, hash BLOB(10) )") + blob = Blob.new("foo\0bar") + @db.execute("INSERT INTO blobs VALUES (0, ?)", [blob]) + assert_equal [[0, blob, blob.length, blob.length*2]], @db.execute("SELECT id, hash, length(hash), length(hex(hash)) FROM blobs") + end + + def test_get_first_row + assert_equal [1], @db.get_first_row('SELECT 1') + end + + def test_get_first_row_with_type_translation_and_hash_results + @db.results_as_hash = true + @db.type_translation = true + assert_equal({"1"=>1}, @db.get_first_row('SELECT 1')) + end + + def test_execute_with_type_translation_and_hash + @db.results_as_hash = true + @db.type_translation = true + rows = [] + @db.execute('SELECT 1') { |row| rows << row } + + assert_equal({"1"=>1}, rows.first) + end + + def test_encoding + assert @db.encoding, 'database has encoding' + end + + def test_changes + @db.execute("CREATE TABLE items (id integer PRIMARY KEY AUTOINCREMENT, number integer)") + assert_equal 0, @db.changes + @db.execute("INSERT INTO items (number) VALUES (10)") + assert_equal 1, @db.changes + @db.execute_batch( + "UPDATE items SET number = (number + :nn) WHERE (number = :n)", + {"nn" => 20, "n" => 10}) + assert_equal 1, @db.changes + assert_equal [[30]], @db.execute("select number from items") + end + + def test_batch_last_comment_is_processed + # FIXME: nil as a successful return value is kinda dumb + assert_nil @db.execute_batch <<-eosql + CREATE TABLE items (id integer PRIMARY KEY AUTOINCREMENT); + -- omg + eosql + end + + def test_execute_batch2 + @db.results_as_hash = true + return_value = @db.execute_batch2 <<-eosql + CREATE TABLE items (id integer PRIMARY KEY AUTOINCREMENT, name string); + INSERT INTO items (name) VALUES ("foo"); + INSERT INTO items (name) VALUES ("bar"); + SELECT * FROM items; + eosql + assert_equal return_value, [{"id"=>"1","name"=>"foo"}, {"id"=>"2", "name"=>"bar"}] + + return_value = @db.execute_batch2('SELECT * FROM items;') do |result| + result["id"] = result["id"].to_i + result + end + assert_equal return_value, [{"id"=>1,"name"=>"foo"}, {"id"=>2, "name"=>"bar"}] + + return_value = @db.execute_batch2('INSERT INTO items (name) VALUES ("oof")') + assert_equal return_value, [] + + return_value = @db.execute_batch2( + 'CREATE TABLE employees (id integer PRIMARY KEY AUTOINCREMENT, name string, age integer(3)); + INSERT INTO employees (age) VALUES (30); + INSERT INTO employees (age) VALUES (40); + INSERT INTO employees (age) VALUES (20); + SELECT age FROM employees;') do |result| + result["age"] = result["age"].to_i + result + end + assert_equal return_value, [{"age"=>30}, {"age"=>40}, {"age"=>20}] + + return_value = @db.execute_batch2('SELECT name FROM employees'); + assert_equal return_value, [{"name"=>nil}, {"name"=>nil}, {"name"=>nil}] + + @db.results_as_hash = false + return_value = @db.execute_batch2( + 'CREATE TABLE managers (id integer PRIMARY KEY AUTOINCREMENT, age integer(3)); + INSERT INTO managers (age) VALUES (50); + INSERT INTO managers (age) VALUES (60); + SELECT id, age from managers;') do |result| + result = result.map do |res| + res.to_i + end + result + end + assert_equal return_value, [[1, 50], [2, 60]] + + assert_raises (RuntimeError) do + # "names" is not a valid column + @db.execute_batch2 'INSERT INTO items (names) VALUES ("bazz")' + end + + end + + def test_new + db = SQLite3::Database.new(':memory:') + assert db + end + + def test_new_yields_self + thing = nil + SQLite3::Database.new(':memory:') do |db| + thing = db + end + assert_instance_of(SQLite3::Database, thing) + end + + def test_new_with_options + # determine if Ruby is running on Big Endian platform + utf16 = ([1].pack("I") == [1].pack("N")) ? "UTF-16BE" : "UTF-16LE" + + if RUBY_VERSION >= "1.9" + db = SQLite3::Database.new(':memory:'.encode(utf16), :utf16 => true) + else + db = SQLite3::Database.new(Iconv.conv(utf16, 'UTF-8', ':memory:'), + :utf16 => true) + end + assert db + end + + def test_close + db = SQLite3::Database.new(':memory:') + db.close + assert db.closed? + end + + def test_block_closes_self + thing = nil + SQLite3::Database.new(':memory:') do |db| + thing = db + assert !thing.closed? + end + assert thing.closed? + end + + def test_block_closes_self_even_raised + thing = nil + begin + SQLite3::Database.new(':memory:') do |db| + thing = db + raise + end + rescue + end + assert thing.closed? + end + + def test_prepare + db = SQLite3::Database.new(':memory:') + stmt = db.prepare('select "hello world"') + assert_instance_of(SQLite3::Statement, stmt) + end + + def test_block_prepare_does_not_double_close + db = SQLite3::Database.new(':memory:') + r = db.prepare('select "hello world"') do |stmt| + stmt.close + :foo + end + assert_equal :foo, r + end + + def test_total_changes + db = SQLite3::Database.new(':memory:') + db.execute("create table foo ( a integer primary key, b text )") + db.execute("insert into foo (b) values ('hello')") + assert_equal 1, db.total_changes + end + + def test_execute_returns_list_of_hash + db = SQLite3::Database.new(':memory:', :results_as_hash => true) + db.execute("create table foo ( a integer primary key, b text )") + db.execute("insert into foo (b) values ('hello')") + rows = db.execute("select * from foo") + assert_equal [{"a"=>1, "b"=>"hello"}], rows + end + + def test_execute_yields_hash + db = SQLite3::Database.new(':memory:', :results_as_hash => true) + db.execute("create table foo ( a integer primary key, b text )") + db.execute("insert into foo (b) values ('hello')") + db.execute("select * from foo") do |row| + assert_equal({"a"=>1, "b"=>"hello"}, row) + end + end + + def test_table_info + db = SQLite3::Database.new(':memory:', :results_as_hash => true) + db.execute("create table foo ( a integer primary key, b text )") + info = [{ + "name" => "a", + "pk" => 1, + "notnull" => 0, + "type" => "integer", + "dflt_value" => nil, + "cid" => 0 + }, + { + "name" => "b", + "pk" => 0, + "notnull" => 0, + "type" => "text", + "dflt_value" => nil, + "cid" => 1 + }] + assert_equal info, db.table_info('foo') + end + + def test_total_changes_closed + db = SQLite3::Database.new(':memory:') + db.close + assert_raise(SQLite3::Exception) do + db.total_changes + end + end + + def test_trace_requires_opendb + @db.close + assert_raise(SQLite3::Exception) do + @db.trace { |x| } + end + end + + def test_trace_with_block + result = nil + @db.trace { |sql| result = sql } + @db.execute "select 'foo'" + assert_equal "select 'foo'", result + end + + def test_trace_with_object + obj = Class.new { + attr_accessor :result + def call sql; @result = sql end + }.new + + @db.trace(obj) + @db.execute "select 'foo'" + assert_equal "select 'foo'", obj.result + end + + def test_trace_takes_nil + @db.trace(nil) + @db.execute "select 'foo'" + end + + def test_last_insert_row_id_closed + @db.close + assert_raise(SQLite3::Exception) do + @db.last_insert_row_id + end + end + + def test_define_function + called_with = nil + @db.define_function("hello") do |value| + called_with = value + end + @db.execute("select hello(10)") + assert_equal 10, called_with + end + + def test_call_func_arg_type + called_with = nil + @db.define_function("hello") do |b, c, d| + called_with = [b, c, d] + nil + end + @db.execute("select hello(2.2, 'foo', NULL)") + assert_equal [2.2, 'foo', nil], called_with + end + + def test_define_varargs + called_with = nil + @db.define_function("hello") do |*args| + called_with = args + nil + end + @db.execute("select hello(2.2, 'foo', NULL)") + assert_equal [2.2, 'foo', nil], called_with + end + + def test_call_func_blob + called_with = nil + @db.define_function("hello") do |a, b| + called_with = [a, b, a.length] + nil + end + blob = Blob.new("a\0fine\0kettle\0of\0fish") + @db.execute("select hello(?, length(?))", [blob, blob]) + assert_equal [blob, blob.length, 21], called_with + end + + def test_function_return + @db.define_function("hello") { |a| 10 } + assert_equal [10], @db.execute("select hello('world')").first + end + + def test_function_return_types + [10, 2.2, nil, "foo", Blob.new("foo\0bar")].each do |thing| + @db.define_function("hello") { |a| thing } + assert_equal [thing], @db.execute("select hello('world')").first + end + end + + def test_function_gc_segfault + @db.create_function("bug", -1) { |func, *values| func.result = values.join } + # With a lot of data and a lot of threads, try to induce a GC segfault. + params = Array.new(127, "?" * 28000) + proc = Proc.new { + db.execute("select bug(#{Array.new(params.length, "?").join(",")})", params) + } + m = Mutex.new + 30.times.map { Thread.new { m.synchronize { proc.call } } }.each(&:join) + end + + def test_function_return_type_round_trip + [10, 2.2, nil, "foo", Blob.new("foo\0bar")].each do |thing| + @db.define_function("hello") { |a| a } + assert_equal [thing], @db.execute("select hello(hello(?))", [thing]).first + end + end + + def test_define_function_closed + @db.close + assert_raise(SQLite3::Exception) do + @db.define_function('foo') { } + end + end + + def test_inerrupt_closed + @db.close + assert_raise(SQLite3::Exception) do + @db.interrupt + end + end + + def test_define_aggregate + @db.execute "create table foo ( a integer primary key, b text )" + @db.execute "insert into foo ( b ) values ( 'foo' )" + @db.execute "insert into foo ( b ) values ( 'bar' )" + @db.execute "insert into foo ( b ) values ( 'baz' )" + + acc = Class.new { + attr_reader :sum + alias :finalize :sum + def initialize + @sum = 0 + end + + def step a + @sum += a + end + }.new + + @db.define_aggregator("accumulate", acc) + value = @db.get_first_value( "select accumulate(a) from foo" ) + assert_equal 6, value + end + + def test_authorizer_ok + @db.authorizer = Class.new { + def call action, a, b, c, d; true end + }.new + @db.prepare("select 'fooooo'") + + @db.authorizer = Class.new { + def call action, a, b, c, d; 0 end + }.new + @db.prepare("select 'fooooo'") + end + + def test_authorizer_ignore + @db.authorizer = Class.new { + def call action, a, b, c, d; nil end + }.new + stmt = @db.prepare("select 'fooooo'") + assert_nil stmt.step + end + + def test_authorizer_fail + @db.authorizer = Class.new { + def call action, a, b, c, d; false end + }.new + assert_raises(SQLite3::AuthorizationException) do + @db.prepare("select 'fooooo'") + end + end + + def test_remove_auth + @db.authorizer = Class.new { + def call action, a, b, c, d; false end + }.new + assert_raises(SQLite3::AuthorizationException) do + @db.prepare("select 'fooooo'") + end + + @db.authorizer = nil + @db.prepare("select 'fooooo'") + end + + def test_close_with_open_statements + @db.prepare("select 'foo'") + assert_raises(SQLite3::BusyException) do + @db.close + end + end + + def test_execute_with_empty_bind_params + assert_equal [['foo']], @db.execute("select 'foo'", []) + end + + def test_query_with_named_bind_params + assert_equal [['foo']], @db.query("select :n", {'n' => 'foo'}).to_a + end + + def test_execute_with_named_bind_params + assert_equal [['foo']], @db.execute("select :n", {'n' => 'foo'}) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database_flags.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database_flags.rb new file mode 100644 index 0000000..9a1205e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database_flags.rb @@ -0,0 +1,95 @@ +require 'helper' + +module SQLite3 + class TestDatabaseFlags < SQLite3::TestCase + def setup + File.unlink 'test-flags.db' if File.exist?('test-flags.db') + @db = SQLite3::Database.new('test-flags.db') + @db.execute("CREATE TABLE foos (id integer)") + @db.close + end + + def teardown + @db.close unless @db.closed? + File.unlink 'test-flags.db' if File.exist?('test-flags.db') + end + + def test_open_database_flags_constants + defined_to_date = [:READONLY, :READWRITE, :CREATE, :DELETEONCLOSE, + :EXCLUSIVE, :MAIN_DB, :TEMP_DB, :TRANSIENT_DB, + :MAIN_JOURNAL, :TEMP_JOURNAL, :SUBJOURNAL, + :MASTER_JOURNAL, :NOMUTEX, :FULLMUTEX] + if SQLite3::SQLITE_VERSION_NUMBER > 3007002 + defined_to_date += [:AUTOPROXY, :SHAREDCACHE, :PRIVATECACHE, :WAL] + end + if SQLite3::SQLITE_VERSION_NUMBER > 3007007 + defined_to_date += [:URI] + end + if SQLite3::SQLITE_VERSION_NUMBER > 3007013 + defined_to_date += [:MEMORY] + end + assert defined_to_date.sort == SQLite3::Constants::Open.constants.sort + end + + def test_open_database_flags_conflicts_with_readonly + assert_raise(RuntimeError) do + @db = SQLite3::Database.new('test-flags.db', :flags => 2, :readonly => true) + end + end + + def test_open_database_flags_conflicts_with_readwrite + assert_raise(RuntimeError) do + @db = SQLite3::Database.new('test-flags.db', :flags => 2, :readwrite => true) + end + end + + def test_open_database_readonly_flags + @db = SQLite3::Database.new('test-flags.db', :flags => SQLite3::Constants::Open::READONLY) + assert @db.readonly? + end + + def test_open_database_readwrite_flags + @db = SQLite3::Database.new('test-flags.db', :flags => SQLite3::Constants::Open::READWRITE) + assert !@db.readonly? + end + + def test_open_database_readonly_flags_cant_open + File.unlink 'test-flags.db' + assert_raise(SQLite3::CantOpenException) do + @db = SQLite3::Database.new('test-flags.db', :flags => SQLite3::Constants::Open::READONLY) + end + end + + def test_open_database_readwrite_flags_cant_open + File.unlink 'test-flags.db' + assert_raise(SQLite3::CantOpenException) do + @db = SQLite3::Database.new('test-flags.db', :flags => SQLite3::Constants::Open::READWRITE) + end + end + + def test_open_database_misuse_flags + assert_raise(SQLite3::MisuseException) do + flags = SQLite3::Constants::Open::READONLY | SQLite3::Constants::Open::READWRITE # <== incompatible flags + @db = SQLite3::Database.new('test-flags.db', :flags => flags) + end + end + + def test_open_database_create_flags + File.unlink 'test-flags.db' + flags = SQLite3::Constants::Open::READWRITE | SQLite3::Constants::Open::CREATE + @db = SQLite3::Database.new('test-flags.db', :flags => flags) do |db| + db.execute("CREATE TABLE foos (id integer)") + db.execute("INSERT INTO foos (id) VALUES (12)") + end + assert File.exist?('test-flags.db') + end + + def test_open_database_exotic_flags + flags = SQLite3::Constants::Open::READWRITE | SQLite3::Constants::Open::CREATE + exotic_flags = SQLite3::Constants::Open::NOMUTEX | SQLite3::Constants::Open::TEMP_DB + @db = SQLite3::Database.new('test-flags.db', :flags => flags | exotic_flags) + @db.execute("INSERT INTO foos (id) VALUES (12)") + assert @db.changes == 1 + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database_readonly.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database_readonly.rb new file mode 100644 index 0000000..def34b2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database_readonly.rb @@ -0,0 +1,36 @@ +require 'helper' + +module SQLite3 + class TestDatabaseReadonly < SQLite3::TestCase + def setup + File.unlink 'test-readonly.db' if File.exist?('test-readonly.db') + @db = SQLite3::Database.new('test-readonly.db') + @db.execute("CREATE TABLE foos (id integer)") + @db.close + end + + def teardown + @db.close unless @db.closed? + File.unlink 'test-readonly.db' if File.exist?('test-readonly.db') + end + + def test_open_readonly_database + @db = SQLite3::Database.new('test-readonly.db', :readonly => true) + assert @db.readonly? + end + + def test_open_readonly_not_exists_database + File.unlink 'test-readonly.db' + assert_raise(SQLite3::CantOpenException) do + @db = SQLite3::Database.new('test-readonly.db', :readonly => true) + end + end + + def test_insert_readonly_database + @db = SQLite3::Database.new('test-readonly.db', :readonly => true) + assert_raise(SQLite3::ReadOnlyException) do + @db.execute("INSERT INTO foos (id) VALUES (12)") + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database_readwrite.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database_readwrite.rb new file mode 100644 index 0000000..f848573 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_database_readwrite.rb @@ -0,0 +1,41 @@ +require 'helper' + +module SQLite3 + class TestDatabaseReadwrite < SQLite3::TestCase + def setup + File.unlink 'test-readwrite.db' if File.exist?('test-readwrite.db') + @db = SQLite3::Database.new('test-readwrite.db') + @db.execute("CREATE TABLE foos (id integer)") + @db.close + end + + def teardown + @db.close unless @db.closed? + File.unlink 'test-readwrite.db' if File.exist?('test-readwrite.db') + end + + def test_open_readwrite_database + @db = SQLite3::Database.new('test-readwrite.db', :readwrite => true) + assert !@db.readonly? + end + + def test_open_readwrite_readonly_database + assert_raise(RuntimeError) do + @db = SQLite3::Database.new('test-readwrite.db', :readwrite => true, :readonly => true) + end + end + + def test_open_readwrite_not_exists_database + File.unlink 'test-readwrite.db' + assert_raise(SQLite3::CantOpenException) do + @db = SQLite3::Database.new('test-readwrite.db', :readonly => true) + end + end + + def test_insert_readwrite_database + @db = SQLite3::Database.new('test-readwrite.db', :readwrite => true) + @db.execute("INSERT INTO foos (id) VALUES (12)") + assert @db.changes == 1 + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_deprecated.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_deprecated.rb new file mode 100644 index 0000000..4fa1dc4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_deprecated.rb @@ -0,0 +1,44 @@ +require 'helper' + +module SQLite3 + class TestDeprecated < SQLite3::TestCase + attr_reader :db + + def setup + super + @warn_before = $-w + $-w = false + @db = SQLite3::Database.new(':memory:') + @db.execute 'CREATE TABLE test_table (name text, age int)' + end + + def teardown + super + $-w = @warn_before + end + + def test_query_with_many_bind_params_not_nil + assert_equal [[1, 2]], db.query('select ?, ?', 1, 2).to_a + end + + def test_execute_with_many_bind_params_not_nil + assert_equal [[1, 2]], @db.execute("select ?, ?", 1, 2).to_a + end + + def test_query_with_many_bind_params + assert_equal [[nil, 1]], @db.query("select ?, ?", nil, 1).to_a + end + + def test_query_with_nil_bind_params + assert_equal [['foo']], @db.query("select 'foo'", nil).to_a + end + + def test_execute_with_many_bind_params + assert_equal [[nil, 1]], @db.execute("select ?, ?", nil, 1) + end + + def test_execute_with_nil_bind_params + assert_equal [['foo']], @db.execute("select 'foo'", nil) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_encoding.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_encoding.rb new file mode 100644 index 0000000..32bf616 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_encoding.rb @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- + +require 'helper' + +module SQLite3 + class TestEncoding < SQLite3::TestCase + def setup + @db = SQLite3::Database.new(':memory:') + @create = "create table ex(id int, data string)" + @insert = "insert into ex(id, data) values (?, ?)" + @db.execute(@create); + end + + def test_select_encoding_on_utf_16 + str = "foo" + utf16 = ([1].pack("I") == [1].pack("N")) ? "UTF-16BE" : "UTF-16LE" + db = SQLite3::Database.new(':memory:'.encode(utf16)) + db.execute @create + db.execute "insert into ex (id, data) values (1, \"#{str}\")" + + stmt = db.prepare 'select * from ex where data = ?' + ['US-ASCII', utf16, 'EUC-JP', 'UTF-8'].each do |enc| + stmt.bind_param 1, str.encode(enc) + assert_equal 1, stmt.to_a.length + stmt.reset! + end + end + + def test_insert_encoding + str = "foo" + utf16 = ([1].pack("I") == [1].pack("N")) ? "UTF-16BE" : "UTF-16LE" + db = SQLite3::Database.new(':memory:'.encode(utf16)) + db.execute @create + stmt = db.prepare @insert + + ['US-ASCII', utf16, 'EUC-JP', 'UTF-8'].each_with_index do |enc,i| + stmt.bind_param 1, i + stmt.bind_param 2, str.encode(enc) + stmt.to_a + stmt.reset! + end + + db.execute('select data from ex').flatten.each do |s| + assert_equal str, s + end + end + + def test_default_internal_is_honored + warn_before = $-w + $-w = false + + before_enc = Encoding.default_internal + + str = "壁に耳あり、障子に目あり" + stmt = @db.prepare('insert into ex(data) values (?)') + stmt.bind_param 1, str + stmt.step + + Encoding.default_internal = 'EUC-JP' + string = @db.execute('select data from ex').first.first + + assert_equal Encoding.default_internal, string.encoding + assert_equal str.encode('EUC-JP'), string + assert_equal str, string.encode(str.encoding) + ensure + Encoding.default_internal = before_enc + $-w = warn_before + end + + def test_blob_is_binary + str = "猫舌" + @db.execute('create table foo(data text)') + stmt = @db.prepare('insert into foo(data) values (?)') + stmt.bind_param(1, SQLite3::Blob.new(str)) + stmt.step + + string = @db.execute('select data from foo').first.first + assert_equal Encoding.find('ASCII-8BIT'), string.encoding + assert_equal str, string.force_encoding('UTF-8') + end + + def test_blob_is_ascii8bit + str = "猫舌" + @db.execute('create table foo(data text)') + stmt = @db.prepare('insert into foo(data) values (?)') + stmt.bind_param(1, str.dup.force_encoding("ASCII-8BIT")) + stmt.step + + string = @db.execute('select data from foo').first.first + assert_equal Encoding.find('ASCII-8BIT'), string.encoding + assert_equal str, string.force_encoding('UTF-8') + end + + def test_blob_with_eucjp + str = "猫舌".encode("EUC-JP") + @db.execute('create table foo(data text)') + stmt = @db.prepare('insert into foo(data) values (?)') + stmt.bind_param(1, SQLite3::Blob.new(str)) + stmt.step + + string = @db.execute('select data from foo').first.first + assert_equal Encoding.find('ASCII-8BIT'), string.encoding + assert_equal str, string.force_encoding('EUC-JP') + end + + def test_db_with_eucjp + db = SQLite3::Database.new(':memory:'.encode('EUC-JP')) + assert_equal(Encoding.find('UTF-8'), db.encoding) + end + + def test_db_with_utf16 + utf16 = ([1].pack("I") == [1].pack("N")) ? "UTF-16BE" : "UTF-16LE" + + db = SQLite3::Database.new(':memory:'.encode(utf16)) + assert_equal(Encoding.find(utf16), db.encoding) + end + + def test_statement_eucjp + str = "猫舌" + @db.execute("insert into ex(data) values ('#{str}')".encode('EUC-JP')) + row = @db.execute("select data from ex") + assert_equal @db.encoding, row.first.first.encoding + assert_equal str, row.first.first + end + + def test_statement_utf8 + str = "猫舌" + @db.execute("insert into ex(data) values ('#{str}')") + row = @db.execute("select data from ex") + assert_equal @db.encoding, row.first.first.encoding + assert_equal str, row.first.first + end + + def test_encoding + assert_equal Encoding.find("UTF-8"), @db.encoding + end + + def test_utf_8 + str = "猫舌" + @db.execute(@insert, [10, str]) + row = @db.execute("select data from ex") + assert_equal @db.encoding, row.first.first.encoding + assert_equal str, row.first.first + end + + def test_euc_jp + str = "猫舌".encode('EUC-JP') + @db.execute(@insert, [10, str]) + row = @db.execute("select data from ex") + assert_equal @db.encoding, row.first.first.encoding + assert_equal str.encode('UTF-8'), row.first.first + end + + end if RUBY_VERSION >= '1.9.1' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_integration.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_integration.rb new file mode 100644 index 0000000..d5ea3a5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_integration.rb @@ -0,0 +1,507 @@ +require 'helper' + +class TC_Database_Integration < SQLite3::TestCase + def setup + @db = SQLite3::Database.new(":memory:") + @db.transaction do + @db.execute "create table foo ( a integer primary key, b text )" + @db.execute "insert into foo ( b ) values ( 'foo' )" + @db.execute "insert into foo ( b ) values ( 'bar' )" + @db.execute "insert into foo ( b ) values ( 'baz' )" + end + end + + def teardown + @db.close + end + + def test_table_info_with_type_translation_active + assert_nothing_raised { @db.table_info("foo") } + end + + def test_table_info_with_defaults_for_version_3_3_8_and_higher + @db.transaction do + @db.execute "create table defaults_test ( a string default NULL, b string default 'Hello', c string default '--- []\n' )" + data = @db.table_info( "defaults_test" ) + assert_equal({"name" => "a", "type" => "string", "dflt_value" => nil, "notnull" => 0, "cid" => 0, "pk" => 0}, + data[0]) + assert_equal({"name" => "b", "type" => "string", "dflt_value" => "Hello", "notnull" => 0, "cid" => 1, "pk" => 0}, + data[1]) + assert_equal({"name" => "c", "type" => "string", "dflt_value" => "--- []\n", "notnull" => 0, "cid" => 2, "pk" => 0}, + data[2]) + end + end + + def test_table_info_without_defaults_for_version_3_3_8_and_higher + @db.transaction do + @db.execute "create table no_defaults_test ( a integer default 1, b integer )" + data = @db.table_info( "no_defaults_test" ) + assert_equal({"name" => "a", "type" => "integer", "dflt_value" => "1", "notnull" => 0, "cid" => 0, "pk" => 0}, + data[0]) + assert_equal({"name" => "b", "type" => "integer", "dflt_value" => nil, "notnull" => 0, "cid" => 1, "pk" => 0}, + data[1]) + end + end + + def test_complete_fail + assert !@db.complete?( "select * from foo" ) + end + def test_complete_success + assert @db.complete?( "select * from foo;" ) + end + + # FIXME: do people really need UTF16 sql statements? + #def test_complete_fail_utf16 + # assert !@db.complete?( "select * from foo".to_utf16(false), true ) + #end + + # FIXME: do people really need UTF16 sql statements? + #def test_complete_success_utf16 + # assert @db.complete?( "select * from foo;".to_utf16(true), true ) + #end + + def test_errmsg + assert_equal "not an error", @db.errmsg + end + + # FIXME: do people really need UTF16 error messages? + #def test_errmsg_utf16 + # msg = Iconv.conv('UTF-16', 'UTF-8', 'not an error') + # assert_equal msg, @db.errmsg(true) + #end + + def test_errcode + assert_equal 0, @db.errcode + end + + def test_trace + result = nil + @db.trace { |sql| result = sql } + @db.execute "select * from foo" + assert_equal "select * from foo", result + end + + def test_authorizer_okay + @db.authorizer { |type,a,b,c,d| 0 } + rows = @db.execute "select * from foo" + assert_equal 3, rows.length + end + + def test_authorizer_error + @db.authorizer { |type,a,b,c,d| 1 } + assert_raise( SQLite3::AuthorizationException ) do + @db.execute "select * from foo" + end + end + + def test_authorizer_silent + @db.authorizer { |type,a,b,c,d| 2 } + rows = @db.execute "select * from foo" + assert rows.empty? + end + + def test_prepare_invalid_syntax + assert_raise( SQLite3::SQLException ) do + @db.prepare "select from foo" + end + end + + def test_prepare_invalid_column + assert_raise( SQLite3::SQLException ) do + @db.prepare "select k from foo" + end + end + + def test_prepare_invalid_table + assert_raise( SQLite3::SQLException ) do + @db.prepare "select * from barf" + end + end + + def test_prepare_no_block + stmt = @db.prepare "select * from foo" + assert stmt.respond_to?(:execute) + stmt.close + end + + def test_prepare_with_block + called = false + @db.prepare "select * from foo" do |stmt| + called = true + assert stmt.respond_to?(:execute) + end + assert called + end + + def test_execute_no_block_no_bind_no_match + rows = @db.execute( "select * from foo where a > 100" ) + assert rows.empty? + end + + def test_execute_with_block_no_bind_no_match + called = false + @db.execute( "select * from foo where a > 100" ) do |row| + called = true + end + assert !called + end + + def test_execute_no_block_with_bind_no_match + rows = @db.execute( "select * from foo where a > ?", 100 ) + assert rows.empty? + end + + def test_execute_with_block_with_bind_no_match + called = false + @db.execute( "select * from foo where a > ?", 100 ) do |row| + called = true + end + assert !called + end + + def test_execute_no_block_no_bind_with_match + rows = @db.execute( "select * from foo where a = 1" ) + assert_equal 1, rows.length + end + + def test_execute_with_block_no_bind_with_match + called = 0 + @db.execute( "select * from foo where a = 1" ) do |row| + called += 1 + end + assert_equal 1, called + end + + def test_execute_no_block_with_bind_with_match + rows = @db.execute( "select * from foo where a = ?", 1 ) + assert_equal 1, rows.length + end + + def test_execute_with_block_with_bind_with_match + called = 0 + @db.execute( "select * from foo where a = ?", 1 ) do |row| + called += 1 + end + assert_equal 1, called + end + + def test_execute2_no_block_no_bind_no_match + columns, *rows = @db.execute2( "select * from foo where a > 100" ) + assert rows.empty? + assert_equal [ "a", "b" ], columns + end + + def test_execute2_with_block_no_bind_no_match + called = 0 + @db.execute2( "select * from foo where a > 100" ) do |row| + assert [ "a", "b" ], row unless called == 0 + called += 1 + end + assert_equal 1, called + end + + def test_execute2_no_block_with_bind_no_match + columns, *rows = @db.execute2( "select * from foo where a > ?", 100 ) + assert rows.empty? + assert_equal [ "a", "b" ], columns + end + + def test_execute2_with_block_with_bind_no_match + called = 0 + @db.execute2( "select * from foo where a > ?", 100 ) do |row| + assert_equal [ "a", "b" ], row unless called == 0 + called += 1 + end + assert_equal 1, called + end + + def test_execute2_no_block_no_bind_with_match + columns, *rows = @db.execute2( "select * from foo where a = 1" ) + assert_equal 1, rows.length + assert_equal [ "a", "b" ], columns + end + + def test_execute2_with_block_no_bind_with_match + called = 0 + @db.execute2( "select * from foo where a = 1" ) do |row| + assert_equal [ 1, "foo" ], row unless called == 0 + called += 1 + end + assert_equal 2, called + end + + def test_execute2_no_block_with_bind_with_match + columns, *rows = @db.execute2( "select * from foo where a = ?", 1 ) + assert_equal 1, rows.length + assert_equal [ "a", "b" ], columns + end + + def test_execute2_with_block_with_bind_with_match + called = 0 + @db.execute2( "select * from foo where a = ?", 1 ) do + called += 1 + end + assert_equal 2, called + end + + def test_execute_batch_empty + assert_nothing_raised { @db.execute_batch "" } + end + + def test_execute_batch_no_bind + @db.transaction do + @db.execute_batch <<-SQL + create table bar ( a, b, c ); + insert into bar values ( 'one', 2, 'three' ); + insert into bar values ( 'four', 5, 'six' ); + insert into bar values ( 'seven', 8, 'nine' ); + SQL + end + rows = @db.execute( "select * from bar" ) + assert_equal 3, rows.length + end + + def test_execute_batch_with_bind + @db.execute_batch( <<-SQL, [1] ) + create table bar ( a, b, c ); + insert into bar values ( 'one', 2, ? ); + insert into bar values ( 'four', 5, ? ); + insert into bar values ( 'seven', 8, ? ); + SQL + rows = @db.execute( "select * from bar" ).map { |a,b,c| c } + assert_equal [1, 1, 1], rows + end + + def test_query_no_block_no_bind_no_match + result = @db.query( "select * from foo where a > 100" ) + assert_nil result.next + result.close + end + + def test_query_with_block_no_bind_no_match + r = nil + @db.query( "select * from foo where a > 100" ) do |result| + assert_nil result.next + r = result + end + assert r.closed? + end + + def test_query_no_block_with_bind_no_match + result = @db.query( "select * from foo where a > ?", 100 ) + assert_nil result.next + result.close + end + + def test_query_with_block_with_bind_no_match + r = nil + @db.query( "select * from foo where a > ?", 100 ) do |result| + assert_nil result.next + r = result + end + assert r.closed? + end + + def test_query_no_block_no_bind_with_match + result = @db.query( "select * from foo where a = 1" ) + assert_not_nil result.next + assert_nil result.next + result.close + end + + def test_query_with_block_no_bind_with_match + r = nil + @db.query( "select * from foo where a = 1" ) do |result| + assert_not_nil result.next + assert_nil result.next + r = result + end + assert r.closed? + end + + def test_query_no_block_with_bind_with_match + result = @db.query( "select * from foo where a = ?", 1 ) + assert_not_nil result.next + assert_nil result.next + result.close + end + + def test_query_with_block_with_bind_with_match + r = nil + @db.query( "select * from foo where a = ?", 1 ) do |result| + assert_not_nil result.next + assert_nil result.next + r = result + end + assert r.closed? + end + + def test_get_first_row_no_bind_no_match + result = @db.get_first_row( "select * from foo where a=100" ) + assert_nil result + end + + def test_get_first_row_no_bind_with_match + result = @db.get_first_row( "select * from foo where a=1" ) + assert_equal [ 1, "foo" ], result + end + + def test_get_first_row_with_bind_no_match + result = @db.get_first_row( "select * from foo where a=?", 100 ) + assert_nil result + end + + def test_get_first_row_with_bind_with_match + result = @db.get_first_row( "select * from foo where a=?", 1 ) + assert_equal [ 1, "foo" ], result + end + + def test_get_first_value_no_bind_no_match + result = @db.get_first_value( "select b, a from foo where a=100" ) + assert_nil result + @db.results_as_hash = true + result = @db.get_first_value( "select b, a from foo where a=100" ) + assert_nil result + end + + def test_get_first_value_no_bind_with_match + result = @db.get_first_value( "select b, a from foo where a=1" ) + assert_equal "foo", result + @db.results_as_hash = true + result = @db.get_first_value( "select b, a from foo where a=1" ) + assert_equal "foo", result + end + + def test_get_first_value_with_bind_no_match + result = @db.get_first_value( "select b, a from foo where a=?", 100 ) + assert_nil result + @db.results_as_hash = true + result = @db.get_first_value( "select b, a from foo where a=?", 100 ) + assert_nil result + end + + def test_get_first_value_with_bind_with_match + result = @db.get_first_value( "select b, a from foo where a=?", 1 ) + assert_equal "foo", result + @db.results_as_hash = true + result = @db.get_first_value( "select b, a from foo where a=?", 1 ) + assert_equal "foo", result + end + + def test_last_insert_row_id + @db.execute "insert into foo ( b ) values ( 'test' )" + assert_equal 4, @db.last_insert_row_id + @db.execute "insert into foo ( b ) values ( 'again' )" + assert_equal 5, @db.last_insert_row_id + end + + def test_changes + @db.execute "insert into foo ( b ) values ( 'test' )" + assert_equal 1, @db.changes + @db.execute "delete from foo where 1=1" + assert_equal 4, @db.changes + end + + def test_total_changes + assert_equal 3, @db.total_changes + @db.execute "insert into foo ( b ) values ( 'test' )" + @db.execute "delete from foo where 1=1" + assert_equal 8, @db.total_changes + end + + def test_transaction_nest + assert_raise( SQLite3::SQLException ) do + @db.transaction do + @db.transaction do + end + end + end + end + + def test_transaction_rollback + @db.transaction + @db.execute_batch <<-SQL + insert into foo (b) values ( 'test1' ); + insert into foo (b) values ( 'test2' ); + insert into foo (b) values ( 'test3' ); + insert into foo (b) values ( 'test4' ); + SQL + assert_equal 7, @db.get_first_value("select count(*) from foo").to_i + @db.rollback + assert_equal 3, @db.get_first_value("select count(*) from foo").to_i + end + + def test_transaction_commit + @db.transaction + @db.execute_batch <<-SQL + insert into foo (b) values ( 'test1' ); + insert into foo (b) values ( 'test2' ); + insert into foo (b) values ( 'test3' ); + insert into foo (b) values ( 'test4' ); + SQL + assert_equal 7, @db.get_first_value("select count(*) from foo").to_i + @db.commit + assert_equal 7, @db.get_first_value("select count(*) from foo").to_i + end + + def test_transaction_rollback_in_block + assert_raise( SQLite3::SQLException ) do + @db.transaction do + @db.rollback + end + end + end + + def test_transaction_commit_in_block + assert_raise( SQLite3::SQLException ) do + @db.transaction do + @db.commit + end + end + end + + def test_transaction_active + assert !@db.transaction_active? + @db.transaction + assert @db.transaction_active? + @db.commit + assert !@db.transaction_active? + end + + def test_transaction_implicit_rollback + assert !@db.transaction_active? + @db.transaction + @db.execute('create table bar (x CHECK(1 = 0))') + assert @db.transaction_active? + assert_raises( SQLite3::ConstraintException ) do + @db.execute("insert or rollback into bar (x) VALUES ('x')") + end + assert !@db.transaction_active? + end + + def test_interrupt + @db.create_function( "abort", 1 ) do |func,x| + @db.interrupt + func.result = x + end + + assert_raise( SQLite3::InterruptException ) do + @db.execute "select abort(a) from foo" + end + end + + def test_create_function + @db.create_function( "munge", 1 ) do |func,x| + func.result = ">>>#{x}<<<" + end + + value = @db.get_first_value( "select munge(b) from foo where a=1" ) + assert_match( />>>.*<<= '1.9' + + busy = Mutex.new + busy.lock + handler_call_count = 0 + + t = Thread.new(busy) do |locker| + begin + db2 = SQLite3::Database.open( "test.db" ) + db2.transaction( :exclusive ) do + locker.lock + end + ensure + db2.close if db2 + end + end + + @db.busy_handler do |data,count| + handler_call_count += 1 + busy.unlock + true + end + + assert_nothing_raised do + @db.execute "insert into foo (b) values ( 'from 2' )" + end + + t.join + + assert_equal 1, handler_call_count + end + + def test_busy_handler_impatient + busy = Mutex.new + busy.lock + handler_call_count = 0 + + t = Thread.new do + begin + db2 = SQLite3::Database.open( "test.db" ) + db2.transaction( :exclusive ) do + busy.lock + end + ensure + db2.close if db2 + end + end + sleep 1 + + @db.busy_handler do + handler_call_count += 1 + false + end + + assert_raise( SQLite3::BusyException ) do + @db.execute "insert into foo (b) values ( 'from 2' )" + end + + busy.unlock + t.join + + assert_equal 1, handler_call_count + end + + def test_busy_timeout + @db.busy_timeout 1000 + busy = Mutex.new + busy.lock + + t = Thread.new do + begin + db2 = SQLite3::Database.open( "test.db" ) + db2.transaction( :exclusive ) do + busy.lock + end + ensure + db2.close if db2 + end + end + + sleep 1 + time = Benchmark.measure do + assert_raise( SQLite3::BusyException ) do + @db.execute "insert into foo (b) values ( 'from 2' )" + end + end + + busy.unlock + t.join + + assert time.real*1000 >= 1000 + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_integration_resultset.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_integration_resultset.rb new file mode 100644 index 0000000..ad89c2e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_integration_resultset.rb @@ -0,0 +1,142 @@ +require 'helper' + +class TC_ResultSet < SQLite3::TestCase + def setup + @db = SQLite3::Database.new(":memory:") + @db.transaction do + @db.execute "create table foo ( a integer primary key, b text )" + @db.execute "insert into foo ( b ) values ( 'foo' )" + @db.execute "insert into foo ( b ) values ( 'bar' )" + @db.execute "insert into foo ( b ) values ( 'baz' )" + end + @stmt = @db.prepare( "select * from foo where a in ( ?, ? )" ) + @result = @stmt.execute + end + + def teardown + @stmt.close + @db.close + end + + def test_reset_unused + assert_nothing_raised { @result.reset } + assert @result.to_a.empty? + end + + def test_reset_used + @result.to_a + assert_nothing_raised { @result.reset } + assert @result.to_a.empty? + end + + def test_reset_with_bind + @result.to_a + assert_nothing_raised { @result.reset( 1, 2 ) } + assert_equal 2, @result.to_a.length + end + + def test_eof_inner + @result.reset( 1 ) + assert !@result.eof? + end + + def test_eof_edge + @result.reset( 1 ) + @result.next # to first row + @result.next # to end of result set + assert @result.eof? + end + + def test_next_eof + @result.reset( 1 ) + assert_not_nil @result.next + assert_nil @result.next + end + + def test_next_no_type_translation_no_hash + @result.reset( 1 ) + assert_equal [ 1, "foo" ], @result.next + end + + def test_next_type_translation + @result.reset( 1 ) + assert_equal [ 1, "foo" ], @result.next + end + + def test_next_type_translation_with_untyped_column + @db.query( "select count(*) from foo" ) do |result| + assert_equal [3], result.next + end + end + + def test_type_translation_with_null_column + time = '1974-07-25 14:39:00' + + @db.execute "create table bar ( a integer, b time, c string )" + @db.execute "insert into bar (a, b, c) values (NULL, '#{time}', 'hello')" + @db.execute "insert into bar (a, b, c) values (1, NULL, 'hello')" + @db.execute "insert into bar (a, b, c) values (2, '#{time}', NULL)" + @db.query( "select * from bar" ) do |result| + assert_equal [nil, time, 'hello'], result.next + assert_equal [1, nil, 'hello'], result.next + assert_equal [2, time, nil], result.next + end + end + + def test_real_translation + @db.execute('create table foo_real(a real)') + @db.execute('insert into foo_real values (42)' ) + @db.query('select a, sum(a), typeof(a), typeof(sum(a)) from foo_real') do |result| + result = result.next + assert result[0].is_a?(Float) + assert result[1].is_a?(Float) + assert result[2].is_a?(String) + assert result[3].is_a?(String) + end + end + + def test_next_results_as_hash + @db.results_as_hash = true + @result.reset( 1 ) + hash = @result.next + assert_equal( { "a" => 1, "b" => "foo" }, + hash ) + assert_equal hash[0], 1 + assert_equal hash[1], "foo" + end + + def test_each + called = 0 + @result.reset( 1, 2 ) + @result.each { |row| called += 1 } + assert_equal 2, called + end + + def test_enumerable + @result.reset( 1, 2 ) + assert_equal 2, @result.to_a.length + end + + def test_types + assert_equal [ "integer", "text" ], @result.types + end + + def test_columns + assert_equal [ "a", "b" ], @result.columns + end + + def test_close + stmt = @db.prepare( "select * from foo" ) + result = stmt.execute + assert !result.closed? + result.close + assert result.closed? + assert stmt.closed? + assert_raise( SQLite3::Exception ) { result.reset } + assert_raise( SQLite3::Exception ) { result.next } + assert_raise( SQLite3::Exception ) { result.each } + assert_raise( SQLite3::Exception ) { result.close } + assert_raise( SQLite3::Exception ) { result.types } + assert_raise( SQLite3::Exception ) { result.columns } + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_integration_statement.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_integration_statement.rb new file mode 100644 index 0000000..20dd6fc --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_integration_statement.rb @@ -0,0 +1,194 @@ +require 'helper' + +class TC_Statement < SQLite3::TestCase + def setup + @db = SQLite3::Database.new(":memory:") + @db.transaction do + @db.execute "create table foo ( a integer primary key, b text )" + @db.execute "insert into foo ( b ) values ( 'foo' )" + @db.execute "insert into foo ( b ) values ( 'bar' )" + @db.execute "insert into foo ( b ) values ( 'baz' )" + end + @stmt = @db.prepare( "select * from foo where a in ( ?, :named )" ) + end + + def teardown + @stmt.close + @db.close + end + + def test_remainder_empty + assert_equal "", @stmt.remainder + end + + def test_remainder_nonempty + called = false + @db.prepare( "select * from foo;\n blah" ) do |stmt| + called = true + assert_equal "\n blah", stmt.remainder + end + assert called + end + + def test_bind_params_empty + assert_nothing_raised { @stmt.bind_params } + assert @stmt.execute!.empty? + end + + def test_bind_params_array + @stmt.bind_params 1, 2 + assert_equal 2, @stmt.execute!.length + end + + def test_bind_params_hash + @stmt.bind_params ":named" => 2 + assert_equal 1, @stmt.execute!.length + end + + def test_bind_params_hash_without_colon + @stmt.bind_params "named" => 2 + assert_equal 1, @stmt.execute!.length + end + + def test_bind_params_hash_as_symbol + @stmt.bind_params :named => 2 + assert_equal 1, @stmt.execute!.length + end + + def test_bind_params_mixed + @stmt.bind_params( 1, ":named" => 2 ) + assert_equal 2, @stmt.execute!.length + end + + def test_bind_param_by_index + @stmt.bind_params( 1, 2 ) + assert_equal 2, @stmt.execute!.length + end + + def test_bind_param_by_name_bad + assert_raise( SQLite3::Exception ) { @stmt.bind_param( "@named", 2 ) } + end + + def test_bind_param_by_name_good + @stmt.bind_param( ":named", 2 ) + assert_equal 1, @stmt.execute!.length + end + + def test_bind_param_with_various_types + @db.transaction do + @db.execute "create table all_types ( a integer primary key, b float, c string, d integer )" + @db.execute "insert into all_types ( b, c, d ) values ( 1.4, 'hello', 68719476735 )" + end + + assert_equal 1, @db.execute( "select * from all_types where b = ?", 1.4 ).length + assert_equal 1, @db.execute( "select * from all_types where c = ?", 'hello').length + assert_equal 1, @db.execute( "select * from all_types where d = ?", 68719476735).length + end + + def test_execute_no_bind_no_block + assert_instance_of SQLite3::ResultSet, @stmt.execute + end + + def test_execute_with_bind_no_block + assert_instance_of SQLite3::ResultSet, @stmt.execute( 1, 2 ) + end + + def test_execute_no_bind_with_block + called = false + @stmt.execute { |row| called = true } + assert called + end + + def test_execute_with_bind_with_block + called = 0 + @stmt.execute( 1, 2 ) { |row| called += 1 } + assert_equal 1, called + end + + def test_reexecute + r = @stmt.execute( 1, 2 ) + assert_equal 2, r.to_a.length + assert_nothing_raised { r = @stmt.execute( 1, 2 ) } + assert_equal 2, r.to_a.length + end + + def test_execute_bang_no_bind_no_block + assert @stmt.execute!.empty? + end + + def test_execute_bang_with_bind_no_block + assert_equal 2, @stmt.execute!( 1, 2 ).length + end + + def test_execute_bang_no_bind_with_block + called = 0 + @stmt.execute! { |row| called += 1 } + assert_equal 0, called + end + + def test_execute_bang_with_bind_with_block + called = 0 + @stmt.execute!( 1, 2 ) { |row| called += 1 } + assert_equal 2, called + end + + def test_columns + c1 = @stmt.columns + c2 = @stmt.columns + assert_same c1, c2 + assert_equal 2, c1.length + end + + def test_columns_computed + called = false + @db.prepare( "select count(*) from foo" ) do |stmt| + called = true + assert_equal [ "count(*)" ], stmt.columns + end + assert called + end + + def test_types + t1 = @stmt.types + t2 = @stmt.types + assert_same t1, t2 + assert_equal 2, t1.length + end + + def test_types_computed + called = false + @db.prepare( "select count(*) from foo" ) do |stmt| + called = true + assert_equal [ nil ], stmt.types + end + assert called + end + + def test_close + stmt = @db.prepare( "select * from foo" ) + assert !stmt.closed? + stmt.close + assert stmt.closed? + assert_raise( SQLite3::Exception ) { stmt.execute } + assert_raise( SQLite3::Exception ) { stmt.execute! } + assert_raise( SQLite3::Exception ) { stmt.close } + assert_raise( SQLite3::Exception ) { stmt.bind_params 5 } + assert_raise( SQLite3::Exception ) { stmt.bind_param 1, 5 } + assert_raise( SQLite3::Exception ) { stmt.columns } + assert_raise( SQLite3::Exception ) { stmt.types } + end + + def test_committing_tx_with_statement_active + called = false + @db.prepare( "select count(*) from foo" ) do |stmt| + called = true + count = stmt.execute!.first.first.to_i + @db.transaction do + @db.execute "insert into foo ( b ) values ( 'hello' )" + end + new_count = stmt.execute!.first.first.to_i + assert_equal new_count, count+1 + end + assert called + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_result_set.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_result_set.rb new file mode 100644 index 0000000..fa3df51 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_result_set.rb @@ -0,0 +1,37 @@ +require 'helper' + +module SQLite3 + class TestResultSet < SQLite3::TestCase + def test_each_hash + db = SQLite3::Database.new ':memory:' + db.execute "create table foo ( a integer primary key, b text )" + list = ('a'..'z').to_a + list.each do |t| + db.execute "insert into foo (b) values (\"#{t}\")" + end + + rs = db.prepare('select * from foo').execute + rs.each_hash do |hash| + assert_equal list[hash['a'] - 1], hash['b'] + end + end + + def test_next_hash + db = SQLite3::Database.new ':memory:' + db.execute "create table foo ( a integer primary key, b text )" + list = ('a'..'z').to_a + list.each do |t| + db.execute "insert into foo (b) values (\"#{t}\")" + end + + rs = db.prepare('select * from foo').execute + rows = [] + while row = rs.next_hash + rows << row + end + rows.each do |hash| + assert_equal list[hash['a'] - 1], hash['b'] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_sqlite3.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_sqlite3.rb new file mode 100644 index 0000000..f5c7972 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_sqlite3.rb @@ -0,0 +1,21 @@ +require 'helper' + +module SQLite3 + class TestSQLite3 < SQLite3::TestCase + def test_libversion + assert_not_nil SQLite3.libversion + end + + def test_threadsafe + assert_not_nil SQLite3.threadsafe + end + + def test_threadsafe? + if SQLite3.threadsafe > 0 + assert SQLite3.threadsafe? + else + refute SQLite3.threadsafe? + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_statement.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_statement.rb new file mode 100644 index 0000000..d78b35c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_statement.rb @@ -0,0 +1,263 @@ +require 'helper' + +module SQLite3 + class TestStatement < SQLite3::TestCase + def setup + @db = SQLite3::Database.new(':memory:') + @stmt = SQLite3::Statement.new(@db, "select 'foo'") + end + + def test_double_close_does_not_segv + @db.execute 'CREATE TABLE "things" ("number" float NOT NULL)' + + stmt = @db.prepare 'INSERT INTO things (number) VALUES (?)' + assert_raises(SQLite3::ConstraintException) { stmt.execute(nil) } + + stmt.close + + assert_raises(SQLite3::Exception) { stmt.close } + end + + def test_raises_type_error + assert_raises(TypeError) do + SQLite3::Statement.new( @db, nil ) + end + end + + def test_insert_duplicate_records + @db.execute 'CREATE TABLE "things" ("name" varchar(20) CONSTRAINT "index_things_on_name" UNIQUE)' + stmt = @db.prepare("INSERT INTO things(name) VALUES(?)") + stmt.execute('ruby') + + exception = assert_raises(SQLite3::ConstraintException) { stmt.execute('ruby') } + # SQLite 3.8.2 returns new error message: + # UNIQUE constraint failed: *table_name*.*column_name* + # Older versions of SQLite return: + # column *column_name* is not unique + assert_match(/(column(s)? .* (is|are) not unique|UNIQUE constraint failed: .*)/, exception.message) + end + + ### + # This method may not exist depending on how sqlite3 was compiled + def test_database_name + @db.execute('create table foo(text BLOB)') + @db.execute('insert into foo(text) values (?)',SQLite3::Blob.new('hello')) + stmt = @db.prepare('select text from foo') + if stmt.respond_to?(:database_name) + assert_equal 'main', stmt.database_name(0) + end + end + + def test_prepare_blob + @db.execute('create table foo(text BLOB)') + stmt = @db.prepare('insert into foo(text) values (?)') + stmt.bind_param(1, SQLite3::Blob.new('hello')) + stmt.step + stmt.close + end + + def test_select_blob + @db.execute('create table foo(text BLOB)') + @db.execute('insert into foo(text) values (?)',SQLite3::Blob.new('hello')) + assert_equal 'hello', @db.execute('select * from foo').first.first + end + + def test_new + assert @stmt + end + + def test_new_closed_handle + @db = SQLite3::Database.new(':memory:') + @db.close + assert_raises(ArgumentError) do + SQLite3::Statement.new(@db, 'select "foo"') + end + end + + def test_new_with_remainder + stmt = SQLite3::Statement.new(@db, "select 'foo';bar") + assert_equal 'bar', stmt.remainder + end + + def test_empty_remainder + assert_equal '', @stmt.remainder + end + + def test_close + @stmt.close + assert @stmt.closed? + end + + def test_double_close + @stmt.close + assert_raises(SQLite3::Exception) do + @stmt.close + end + end + + def test_bind_param_string + stmt = SQLite3::Statement.new(@db, "select ?") + stmt.bind_param(1, "hello") + result = nil + stmt.each { |x| result = x } + assert_equal ['hello'], result + end + + def test_bind_param_int + stmt = SQLite3::Statement.new(@db, "select ?") + stmt.bind_param(1, 10) + result = nil + stmt.each { |x| result = x } + assert_equal [10], result + end + + def test_bind_nil + stmt = SQLite3::Statement.new(@db, "select ?") + stmt.bind_param(1, nil) + result = nil + stmt.each { |x| result = x } + assert_equal [nil], result + end + + def test_bind_blob + @db.execute('create table foo(text BLOB)') + stmt = SQLite3::Statement.new(@db, 'insert into foo(text) values (?)') + stmt.bind_param(1, SQLite3::Blob.new('hello')) + stmt.execute + row = @db.execute('select * from foo') + + assert_equal ['hello'], row.first + assert_equal row.first.types, ['BLOB'] + end + + def test_bind_64 + stmt = SQLite3::Statement.new(@db, "select ?") + stmt.bind_param(1, 2 ** 31) + result = nil + stmt.each { |x| result = x } + assert_equal [2 ** 31], result + end + + def test_bind_double + stmt = SQLite3::Statement.new(@db, "select ?") + stmt.bind_param(1, 2.2) + result = nil + stmt.each { |x| result = x } + assert_equal [2.2], result + end + + def test_named_bind + stmt = SQLite3::Statement.new(@db, "select :foo") + stmt.bind_param(':foo', 'hello') + result = nil + stmt.each { |x| result = x } + assert_equal ['hello'], result + end + + def test_named_bind_no_colon + stmt = SQLite3::Statement.new(@db, "select :foo") + stmt.bind_param('foo', 'hello') + result = nil + stmt.each { |x| result = x } + assert_equal ['hello'], result + end + + def test_named_bind_symbol + stmt = SQLite3::Statement.new(@db, "select :foo") + stmt.bind_param(:foo, 'hello') + result = nil + stmt.each { |x| result = x } + assert_equal ['hello'], result + end + + def test_named_bind_not_found + stmt = SQLite3::Statement.new(@db, "select :foo") + assert_raises(SQLite3::Exception) do + stmt.bind_param('bar', 'hello') + end + end + + def test_each + r = nil + @stmt.each do |row| + r = row + end + assert_equal(['foo'], r) + end + + def test_reset! + r = [] + @stmt.each { |row| r << row } + @stmt.reset! + @stmt.each { |row| r << row } + assert_equal [['foo'], ['foo']], r + end + + def test_step + r = @stmt.step + assert_equal ['foo'], r + end + + def test_step_twice + assert_not_nil @stmt.step + assert !@stmt.done? + assert_nil @stmt.step + assert @stmt.done? + + @stmt.reset! + assert !@stmt.done? + end + + def test_step_never_moves_past_done + 10.times { @stmt.step } + @stmt.done? + end + + def test_column_count + assert_equal 1, @stmt.column_count + end + + def test_column_name + assert_equal "'foo'", @stmt.column_name(0) + assert_nil @stmt.column_name(10) + end + + def test_bind_parameter_count + stmt = SQLite3::Statement.new(@db, "select ?, ?, ?") + assert_equal 3, stmt.bind_parameter_count + end + + def test_execute_with_varargs + stmt = @db.prepare('select ?, ?') + assert_equal [[nil, nil]], stmt.execute(nil, nil).to_a + end + + def test_execute_with_hash + stmt = @db.prepare('select :n, :h') + assert_equal [[10, nil]], stmt.execute('n' => 10, 'h' => nil).to_a + end + + def test_with_error + @db.execute('CREATE TABLE "employees" ("name" varchar(20) NOT NULL CONSTRAINT "index_employees_on_name" UNIQUE)') + stmt = @db.prepare("INSERT INTO Employees(name) VALUES(?)") + stmt.execute('employee-1') + stmt.execute('employee-1') rescue SQLite3::ConstraintException + stmt.reset! + assert stmt.execute('employee-2') + end + + def test_clear_bindings! + stmt = @db.prepare('select ?, ?') + stmt.bind_param 1, "foo" + stmt.bind_param 2, "bar" + + # We can't fetch bound parameters back out of sqlite3, so just call + # the clear_bindings! method and assert that nil is returned + stmt.clear_bindings! + + while x = stmt.step + assert_equal [nil, nil], x + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_statement_execute.rb b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_statement_execute.rb new file mode 100644 index 0000000..63e022b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/sqlite3-1.4.2/test/test_statement_execute.rb @@ -0,0 +1,35 @@ +require 'helper' + +module SQLite3 + class TestStatementExecute < SQLite3::TestCase + def setup + @db = SQLite3::Database.new(':memory:') + @db.execute_batch( + "CREATE TABLE items (id integer PRIMARY KEY, number integer)") + end + + def test_execute_insert + ps = @db.prepare("INSERT INTO items (number) VALUES (:n)") + ps.execute('n'=>10) + assert_equal 1, @db.get_first_value("SELECT count(*) FROM items") + ps.close + end + + def test_execute_update + @db.execute("INSERT INTO items (number) VALUES (?)", [10]) + + ps = @db.prepare("UPDATE items SET number = :new WHERE number = :old") + ps.execute('old'=>10, 'new'=>20) + assert_equal 20, @db.get_first_value("SELECT number FROM items") + ps.close + end + + def test_execute_delete + @db.execute("INSERT INTO items (number) VALUES (?)", [20]) + ps = @db.prepare("DELETE FROM items WHERE number = :n") + ps.execute('n' => 20) + assert_equal 0, @db.get_first_value("SELECT count(*) FROM items") + ps.close + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/.gitignore b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/.gitignore new file mode 100644 index 0000000..c3e4c61 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/.gitignore @@ -0,0 +1,4 @@ +coverage +.yardoc +doc +Gemfile.lock diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/.travis.yml b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/.travis.yml new file mode 100644 index 0000000..4ee977d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/.travis.yml @@ -0,0 +1,30 @@ +language: ruby +dist: trusty + +cache: bundler + +rvm: + - 1.9.3 + - 2.0.0 + - 2.1.10 + - 2.2.6 + - 2.3.3 + - ruby-head + - jruby-19mode + - rbx-3 + +sudo: false + +env: + - ESCAPE_UTILS=1 + - "" + +matrix: + allow_failures: + - rvm: ruby-head + - rvm: rbx-3 + exclude: + - rvm: jruby-19mode + env: ESCAPE_UTILS=1 + - rvm: rbx-3 + env: ESCAPE_UTILS=1 diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/.yardopts b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/.yardopts new file mode 100644 index 0000000..b39cbbe --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/.yardopts @@ -0,0 +1,2 @@ +--title Temple +--files EXPRESSIONS.md,CHANGES,LICENSE diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/CHANGES b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/CHANGES new file mode 100644 index 0000000..b916158 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/CHANGES @@ -0,0 +1,260 @@ +0.8.2 + + * Support TruffleRuby in Temple::Filters::StaticAnalyzer (#127) + * Support TruffleRuby in Temple::Filters::StringSplitter (#127) + +0.8.1 + + * Stop relying on deprecated method in Rails (#121) + * Fix issue with --enable-frozen-string-literal + * Escape html in markdown + +0.8.0 + + * Add Temple::StaticAnalyzer to analyze Ruby expressions + * Support newlines in Temple::Filters::StaticAnalyzer + +0.7.8 + + * Fix an warning in StaticAnalyzer + +0.7.7 + + * Add Temple::Filters::StaticAnalyzer, Temple::Filters::StringSplitter + * Freeze string literals + +0.7.6 + + * EngineDSL - add support for use(:Filter) { FilterClassName } + +0.7.5 + + * HTML::Pretty Fix indentation issue (https://github.com/slim-template/slim-rails/issues/78) + +0.7.4 + + * EngineDSL: allow to replace/remove with regexp + * Fix deprecation warning (#83) + +0.7.3 + + * Temple::ERB::Trimming - replace option trim_mode with trim and switch to erubis-like trimming + +0.7.2 + + * Remove Filters::StaticFreezer, the generator does the freezing + +0.7.1 + + * Rename *Hash to *Map + * Add Filters::StaticFreezer + +0.7.0 + + * Drop Ruby 1.8.7 support + * EngineDSL: Remove option filter + * HTML: Deprecate :html4, :html5 formats + * HTML: Add format :xml + * Rename DefaultOptions to ClassOptions + * Deprecate default_options in favor of options + * Add Utils.indent_dynamic + +0.6.10 + + * Tilt template: Support :outvar and save/restore buffer to make the behaviour compatible with ERB + +0.6.9 + + * HTML::Pretty: Fix wrong line numbers + * Tilt template: Don't overwrite buffer always + * Generator: add preamble and postamble which do nothing + * Tilt template: don't overwrite streaming option + * OptionHash: inherit valid keys + * temple/html/safe: add poor man's html_safe? implementation (not required automatically) + * Temple::Mixins::GrammarDSL - Add some missing match? methods + * Temple::Utils.escape_html_safe - Add parameter safe + +0.6.8 + + * HTML::Fast add svg doctype + * Render standalone html 5 attributes + +0.6.7 + + * HTML::Pretty - change some block level tags + * Reduce memory allocations in immutable hash + +0.6.6 + + * Use default encoding utf-8 + * Escape also ' + * Try to load escape_utils by default + +0.6.5 + + * Added Filters::CodeMerger + * Added Filters::Encoding + * Added Filters::RemoveBOM + * Added Generators::ERB + +0.6.4 + + * Check for ActionView instead of Rails (#72) + +0.6.3 + + * Fix HTML escaping for HTML::Pretty (Issue #69) + +0.6.2 + + * [:html, :js, code] abstraction added + +0.6.1 + + * HTML::Pretty improved + +0.6.0 + + * HTML::AttributeMerger: rename option :attr_delimiter to :merge_attrs + * HTML: rename option :attr_wrapper to :attr_quote + +0.5.5 + + * HTML pretty: Do not remove empty lines, add newline after doctype + +0.5.4 + + * HTML::AttributeMerger fixed, it didn't remove first empty attribute values + * Add HTML::AttributeRemover back, :remove_empty_attrs must be an Array of Strings now + of the attributes to be removed if empty + * Simplify [:case] expression grammar + * Ignore parameter :outvar by sinatra since sinatra assumes also that the buffer is a String, + they should set :buffer and :generator explicitly if they need the access + +0.5.3 + + * Only print an message if invalid options are passed to Temple filters or engines + since many libraries seem to use Slim and Temple in an incorrect way + +0.5.2 + + * Fix the :outvar problem really + +0.5.1 + + * Support Sinatra :outvar option in Tilt template + +0.5.0 + + * Added exception Temple::FilterError which should be thrown by filters + * Added Temple::Parser as default base class for parsers + * escape_html doesn't escape / anymore + * HTML::AttributeSorter uses stable sorting now + * HTML::AttributeRemover removed (Was too Slim specific) + * Engine option :chain removed + * Option validation implemented (Use define_options in your filters) + * Deprecated options implemented (Use deprecated_options in your filters) + * ThreadOptions added, Method #with_options + +0.4.1 + + * Generators: produce optimized code + * remove deprecated method EngineDSL#wildcard + * Set tilt template default_mime_type to text/html + * HTML: Support conditional comments [:html, :condcomment, ...] + +0.4.0 + + * Split Temple::HTML::AttributeMerger in AttributeSorter, + AttributeMerger and AttributeRemover + * Fix issue #58 + +0.3.5 + + * Temple::HTML::Pretty improved + * :sort_attrs option (default: true) added to HTML::AttributeMerger; + if set to false, the attributes will appear in the insertion order + * Temple::Mixins::EngineDSL api changed ("wildcard" is deprecated, use "use" instead) + * Temple::Mixins::CompiledDispatcher supports arbitrary levels now + * Don't use gsub! on incoming strings (#57) + * Fix newlines in erb parser (#46) + +0.3.4 + + * Bugfix release (0.3.3 was yanked) + +0.3.3 + + * Support for rails 3.1 streaming + * Add EngineDSL#wildcard + * HTML::Fast/Pretty supports only :xhtml and :html formats from now on + * HTML::AttributeMerger extracted from HTML::Fast + +0.3.1, 0.3.2 + + * Don't modify strings destructively with gsub! in HTML::Pretty. + This doesn't work with Rails safe buffers in version >= 3.0.8. + +0.3.0 + + * Compiled expression dispatching + * Method temple_dispatch is obsolete + * EscapeHTML renamed to Escapable + * Control flow filter added + * HTML filter: Tag and attribute expressions changed + * Expression grammar added + * Expression validator added + * Debugger filter removed (Validator is better replacement) + +0.2.0 + + * Add mutable/immutable hashes for option inheritance + * Rails template support added + * Rename Filter#compile to Filter#call + * Engine chain reconfiguration (append, prepend, replace, ...) + * HTML filter: Don't output empty attributes + * Escape expression changed [:escape, true/false, Expression] + +0.1.8 + + * HTML filter: Support :format => :html (alias for :html5) + +0.1.7 + + * HTML::Pretty indents dynamic content only if it doesn't contain + preformatted tags + +0.1.6 + + * Flexible chain building + +0.1.5 + + * Default options for engines + +0.1.4 + + * HTML::Pretty added + * Tilt-based template class added + * Escaping filter added + * Filter base class added + * Fix capturing (Issue #15) + +0.1.3 + + * Close issue #10 + * Refactoring + +0.1.2 + + * Add HTML filter + * Remove Escapable filter + * Add method for checking if expression is empty + +0.1.1 + + * Test added + +0.1.0 + + * Initial release diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/EXPRESSIONS.md b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/EXPRESSIONS.md new file mode 100644 index 0000000..5641b4b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/EXPRESSIONS.md @@ -0,0 +1,262 @@ +Temple expression documentation +=============================== + +Temple uses S-expressions to represent the parsed template code. The S-expressions +are passed from filter to filter until the generator. The generator transforms +the S-expression to a ruby code string. See the {file:README.md README} for an introduction. + +In this document we documented all the expressions which are used by Temple. There is also +a formal grammar which can validate expressions. + +The Core Abstraction +-------------------- + +The core abstraction is what every template evetually should be compiled +to. Currently it consists of six types: +multi, static, dynamic, code, newline and capture. + +When compiling, there's two different strings we'll have to think about. +First we have the generated code. This is what your engine (from Temple's +point of view) spits out. If you construct this carefully enough, you can +make exceptions report correct line numbers, which is very convenient. + +Then there's the result. This is what your engine (from the user's point +of view) spits out. It's what happens if you evaluate the generated code. + +### [:multi, *sexp] + +Multi is what glues everything together. It's simply a sexp which combines +several others sexps: + + [:multi, + [:static, "Hello "], + [:dynamic, "@world"]] + +### [:static, string] + +Static indicates that the given string should be appended to the result. + +Example: + + [:static, "Hello World"] +is the same as: + _buf << "Hello World" + + [:static, "Hello \n World"] +is the same as + _buf << "Hello\nWorld" + +### [:dynamic, ruby] + +Dynamic indicates that the given Ruby code should be evaluated and then +appended to the result. + +The Ruby code must be a complete expression in the sense that you can pass +it to eval() and it would not raise SyntaxError. + +Example: + + [:dynamic, 'Math::PI * r**2'] + +### [:code, ruby] + +Code indicates that the given Ruby code should be evaluated, and may +change the control flow. Any \n causes a newline in the generated code. + +Example: + + [:code, 'area = Math::PI * r**2'] + +### [:newline] + +Newline causes a newline in the generated code, but not in the result. + +### [:capture, variable_name, sexp] + +Evaluates the Sexp using the rules above, but instead of appending to the +result, it sets the content to the variable given. + +Example: + + [:multi, + [:static, "Some content"], + [:capture, "foo", [:static, "More content"]], + [:dynamic, "foo.downcase"]] +is the same as: + _buf << "Some content" + foo = "More content" + _buf << foo.downcase + +Control flow abstraction +------------------------ + +Control flow abstractions can be used to write common ruby control flow constructs. +These expressions are compiled to [:code, ruby] by Temple::Filters::ControlFlow + +### [:if, condition, if-sexp, optional-else-sexp] + +Example: + + [:if, + "1+1 == 2", + [:static, "Yes"], + [:static, "No"]] +is the same as: + if 1+1 == 2 + _buf << "Yes" + else + _buf << "No" + end + +### [:block, ruby, sexp] + +Example: + + [:block, + '10.times do', + [:static, 'Hello']] +is the same as: + 10.times do + _buf << 'Hello' + end + +### [:case, argument, [condition, sexp], [condition, sexp], ...] + +Example: + + [:case, + 'value', + ["1", "value is 1"], + ["2", "value is 2"], + [:else, "don't know"]] +is the same as: + case value + when 1 + _buf << "value is 1" + when 2 + _buf << "value is 2" + else + _buf << "don't know" + end + +### [:cond, [condition, sexp], [condition, sexp], ...] + + [:cond, + ["a", "a is true"], + ["b", "b is true"], + [:else, "a and b are false"]] +is the same as: + case + when a + _buf << "a is true" + when b + _buf << "b is true" + else + _buf << "a and b are false" + end + +Escape abstraction +------------------ + +The Escape abstraction is processed by Temple::Filters::Escapable. + +### [:escape, bool, sexp] + +The boolean flag switches escaping on or off for the content sexp. Dynamic and static +expressions are manipulated. + +Example: + + [:escape, true, + [:multi, + [:dynamic, "code"], + [:static, "<"], + [:escape, false, [:static, ">"]]]] +is transformed to + [:multi, + [:dynamic, 'escape_html(code)'], + [:static, '<'], + [:static, '>']] + +HTML abstraction +---------------- + +The HTML abstraction is processed by the html filters (Temple::HTML::Fast and Temple::HTML::Pretty). + +### [:html, :doctype, string] + +Example: + [:html, :doctype, '5'] +generates + + +Supported doctypes: + + + + + + + + + + +
    NameGenerated doctype
    1.1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    html, 5<!DOCTYPE html>
    strict<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    frameset<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
    mobile<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">
    basic<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
    transitional<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    + +### [:html, :comment, sexp] + +Example: + [:html, :comment, [:static, 'comment']] +generates: + + +### [:html, :condcomment, condition, sexp] + +Example: + [:html, :condcomment, 'IE', [:static, 'comment']] +generates: + + +### [:html, :tag, identifier, attributes, optional-sexp] + +HTML tag abstraction. Identifier can be a String or a Symbol. If the optional content Sexp is omitted +the tag is closed (e.g. `
    ` ``). The tag is also closed if the content Sexp is empty +(consists only of :multi and :newline expressions) and the tag is registered as auto-closing. + +Example: + [:html, :tag, 'img', [:html, :attrs, [:html, :attr, 'src', 'image.png']]] + [:html, :tag, 'p', [:multi], [:static, 'Content']] +generates: + + +

    Content

    + +### [:html, :attrs, attributes] + +List of html attributes [:html, :attr, identifier, sexp] + +### [:html, :attr, identifier, sexp] + +HTML attribute abstraction. Identifier can be a String or a Symbol. + +### [:html, :js, code] + +HTML javascript abstraction which wraps the js code in a HTML comment or CDATA depending on document format. + +Formal grammar +-------------- + +Validate expressions with Temple::Grammar.match? and Temple::Grammar.validate! + + Temple::Grammar.match? [:multi, [:static, 'Valid Temple Expression']] + Temple::Grammar.validate! [:multi, 'Invalid Temple Expression'] + +The formal grammar is given in a Ruby DSL similar to EBNF and should be easy to understand if you know EBNF. Repeated tokens +are given by appending ?, * or + as in regular expressions. + +* ? means zero or one occurence +* \* means zero or more occurences +* \+ means one or more occurences + + + diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/Gemfile b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/Gemfile new file mode 100644 index 0000000..ca93a59 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/Gemfile @@ -0,0 +1,3 @@ +source 'https://rubygems.org/' +gemspec +gem 'escape_utils' if ENV['ESCAPE_UTILS'] diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/LICENSE b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/LICENSE new file mode 100644 index 0000000..f881a6e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2010 Magnus Holm + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/README.md b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/README.md new file mode 100644 index 0000000..087b6e6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/README.md @@ -0,0 +1,267 @@ +Temple +====== + +[![Build Status](https://secure.travis-ci.org/judofyr/temple.svg?branch=master)](http://travis-ci.org/judofyr/temple) [![Code Climate](https://codeclimate.com/github/judofyr/temple.svg)](https://codeclimate.com/github/judofyr/temple) [![Gem Version](https://badge.fury.io/rb/temple.svg)](https://rubygems.org/gems/temple) + +Temple is an abstraction and a framework for compiling templates to pure Ruby. +It's all about making it easier to experiment, implement and optimize template +languages. If you're interested in implementing your own template language, or +anything else related to the internals of a template engine: You've come to +the right place. + +Have a look around, and if you're still wondering: Ask on the mailing list and +we'll try to do our best. In fact, it doesn't have to be related to Temple at +all. As long as it has something to do with template languages, we're +interested: . + +Links +----- + +* Source: +* Bugs: +* List: +* API documentation: + * Latest Gem: + * GitHub master: +* Abstractions: + +Overview +-------- + +Temple is built on a theory that every template consists of three elements: + +* Static text +* Dynamic text (pieces of Ruby which are evaluated and sent to the client) +* Codes (pieces of Ruby which are evaluated and *not* sent to the client, but + might change the control flow). + +The goal of a template engine is to take the template and eventually compile +it into *the core abstraction*: + +```ruby + [:multi, + [:static, "Hello "], + [:dynamic, "@user.name"], + [:static, "!\n"], + [:code, "if @user.birthday == Date.today"], + [:static, "Happy birthday!"], + [:code, "end"]] +``` + +Then you can apply some optimizations, feed it to Temple and it generates fast +Ruby code for you: + +```ruby + _buf = [] + _buf << ("Hello #{@user.name}!\n") + if @user.birthday == Date.today + _buf << "Happy birthday!" + end + _buf.join +``` + +S-expression +------------ + +In Temple, an Sexp is simply an array (or a subclass) where the first element +is the *type* and the rest are the *arguments*. The type must be a symbol and +it's recommended to only use strings, symbols, arrays and numbers as +arguments. + +Temple uses Sexps to represent templates because it's a simple and +straightforward data structure, which can easily be written by hand and +manipulated by computers. + +Some examples: + +```ruby + [:static, "Hello World!"] + + [:multi, + [:static, "Hello "], + [:dynamic, "@world"]] + + [:html, :tag, "em", [:html, :attrs], [:static, "Hey hey"]] +``` + +*NOTE:* SexpProcessor, a library written by Ryan Davis, includes a `Sexp` +class. While you can use this class (since it's a subclass of Array), it's not +what Temple mean by "Sexp". + +Abstractions +------------ + +The idea behind Temple is that abstractions are good, and it's better to have +too many than too few. While you should always end up with the core +abstraction, you shouldn't stress about it. Take one step at a time, and only +do one thing at every step. + +So what's an abstraction? An abstraction is when you introduce a new types: + +```ruby + # Instead of: + [:static, "Use the force"] + + # You use: + [:html, :tag, "strong", [:html, :attrs], [:static, "Use the force"]] +``` + +### Why are abstractions so important? + +First of all, it means that several template engines can share code. Instead +of having two engines which goes all the way to generating HTML, you have two +smaller engines which only compiles to the HTML abstraction together with +something that compiles the HTML abstraction to the core abstraction. + +Often you also introduce abstractions because there's more than one way to do +it. There's not a single way to generate HTML. Should it be indented? If so, +with tabs or spaces? Or should it remove as much whitespace as possible? +Single or double quotes in attributes? Escape all weird UTF-8 characters? + +With an abstraction you can easily introduce a completely new HTML compiler, +and whatever is below doesn't have to care about it *at all*. They just +continue to use the HTML abstraction. Maybe you even want to write your +compiler in another language? Sexps are easily serialized and if you don't +mind working across processes, it's not a problem at all. + +All abstractions used by Temple are documented in [EXPRESSIONS.md](EXPRESSIONS.md). + +Compilers +--------- + +A *compiler* is simply an object which responds a method called #call which +takes one argument and returns a value. It's illegal for a compiler to mutate +the argument, and it should be possible to use the same instance several times +(although not by several threads at the same time). + +While a compiler can be any object, you very often want to structure it as a +class. Temple then assumes the initializer takes an optional option hash: + +```ruby + class MyCompiler + def initialize(options = {}) + @options = options + end + + def call(exp) + # do stuff + end + end +``` + +### Parsers + +In Temple, a parser is also a compiler, because a compiler is just something +that takes some input and produces some output. A parser is then something +that takes a string and returns an Sexp. + +It's important to remember that the parser *should be dumb*. No optimization, +no guesses. It should produce an Sexp that is as close to the source as +possible. You should invent your own abstraction. Maybe you even want to +separate the parsers into several parts and introduce several abstractions on +the way? + +### Filters + +A filter is a compiler which take an Sexp and returns an Sexp. It might turn +convert it one step closer to the core-abstraction, it might create a new +abstraction, or it might just optimize in the current abstraction. Ultimately, +it's still just a compiler which takes an Sexp and returns an Sexp. + +For instance, Temple ships with {Temple::Filters::DynamicInliner} and +{Temple::Filters::StaticMerger} which are general optimization filters which +works on the core abstraction. + +An HTML compiler would be a filter, since it would take an Sexp in the HTML +abstraction and compile it down to the core abstraction. + +### Generators + +A generator is a compiler which takes an Sexp and returns a string which is +valid Ruby code. + +Most of the time you would just use {Temple::Generators::ArrayBuffer} or any of the +other generators in {Temple::Generators}, but nothing stops you from writing your +own. + +In fact, one of the great things about Temple is that if you write a new +generator which turns out to be a lot faster then the others, it's going to +make *every single engine* based on Temple faster! So if you have any ideas, +please share them - it's highly appreciated. + +Engines +------- + +When you have a chain of a parsers, some filters and a generator you can finally create your *engine*. Temple provides {Temple::Engine} which makes this very easy: + +```ruby + class MyEngine < Temple::Engine + # First run MyParser + use MyParser + + # Then a custom filter + use MyFilter + + # Then some general optimizations filters + filter :MultiFlattener + filter :StaticMerger + filter :DynamicInliner + + # Finally the generator + generator :ArrayBuffer + end + + engine = MyEngine.new(strict: "For MyParser") + engine.call(something) +``` + +And then? +--------- + +You've ran the template through the parser, some filters and in the end a +generator. What happens next? + +Temple provides helpers to create template classes for [Tilt](http://github.com/rtomayko/tilt) and +Rails. + +```ruby + require 'tilt' + + # Create template class MyTemplate and register your file extension + MyTemplate = Temple::Templates::Tilt(MyEngine, register_as: 'ext') + + Tilt.new('example.ext').render # => Render a file + MyTemplate.new { "String" }.render # => Render a string +``` + +Installation +------------ + +You need at least Ruby 1.9.3 to work with Temple. Temple is published as a Ruby Gem which can be installed +as following: + +```bash + $ gem install temple +``` + +Engines using Temple +-------------------- + +* [Slim](https://github.com/slim-template/slim) +* [Hamlit](https://github.com/k0kubun/hamlit) +* [Faml](https://github.com/eagletmt/faml) +* [Sal](https://github.com/stonean/sal.rb) +* [Temple-Mustache (Example implementation)](https://github.com/minad/temple-mustache) +* Temple ERB example implementation (Temple::ERB::Template) +* [WLang](https://github.com/blambeau/wlang) + +Acknowledgements +---------------- + +Thanks to [_why](http://en.wikipedia.org/wiki/Why_the_lucky_stiff) for +creating an excellent template engine (Markaby) which is quite slow. That's +how I started experimenting with template engines in the first place. + +I also owe [Ryan Davis](http://zenspider.com/) a lot for his excellent +projects ParserTree, RubyParser, Ruby2Ruby and SexpProcessor. Temple is +heavily inspired by how these tools work. diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/Rakefile b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/Rakefile new file mode 100644 index 0000000..ab51fd8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/Rakefile @@ -0,0 +1,25 @@ +require 'rake/testtask' + +task default: :test +task :test do + sh "bacon -Ilib -Itest --automatic --quiet" +end + +#Rake::TestTask.new(:test) do |t| +# t.libs << 'lib' << 'test' +# t.pattern = 'test/**/test_*.rb' +# t.verbose = false +#end + +begin + require 'rcov/rcovtask' + Rcov::RcovTask.new do |t| + t.libs << 'lib' << 'test' + t.pattern = 'test/**/test_*.rb' + t.verbose = false + end +rescue LoadError + task :rcov do + abort "RCov is not available. In order to run rcov, you must: gem install rcov" + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple.rb new file mode 100644 index 0000000..c92bbf8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple.rb @@ -0,0 +1,67 @@ +require 'temple/version' + +module Temple + autoload :InvalidExpression, 'temple/exceptions' + autoload :FilterError, 'temple/exceptions' + autoload :Generator, 'temple/generator' + autoload :Parser, 'temple/parser' + autoload :Engine, 'temple/engine' + autoload :Utils, 'temple/utils' + autoload :Filter, 'temple/filter' + autoload :Templates, 'temple/templates' + autoload :Grammar, 'temple/grammar' + autoload :ImmutableMap, 'temple/map' + autoload :MutableMap, 'temple/map' + autoload :OptionMap, 'temple/map' + autoload :StaticAnalyzer, 'temple/static_analyzer' + + module Mixins + autoload :Dispatcher, 'temple/mixins/dispatcher' + autoload :CompiledDispatcher, 'temple/mixins/dispatcher' + autoload :EngineDSL, 'temple/mixins/engine_dsl' + autoload :GrammarDSL, 'temple/mixins/grammar_dsl' + autoload :Options, 'temple/mixins/options' + autoload :ClassOptions, 'temple/mixins/options' + autoload :Template, 'temple/mixins/template' + end + + module ERB + autoload :Engine, 'temple/erb/engine' + autoload :Parser, 'temple/erb/parser' + autoload :Trimming, 'temple/erb/trimming' + autoload :Template, 'temple/erb/template' + end + + module Generators + autoload :ERB, 'temple/generators/erb' + autoload :Array, 'temple/generators/array' + autoload :ArrayBuffer, 'temple/generators/array_buffer' + autoload :StringBuffer, 'temple/generators/string_buffer' + autoload :RailsOutputBuffer, 'temple/generators/rails_output_buffer' + end + + module Filters + autoload :CodeMerger, 'temple/filters/code_merger' + autoload :ControlFlow, 'temple/filters/control_flow' + autoload :MultiFlattener, 'temple/filters/multi_flattener' + autoload :StaticAnalyzer, 'temple/filters/static_analyzer' + autoload :StaticMerger, 'temple/filters/static_merger' + autoload :StringSplitter, 'temple/filters/string_splitter' + autoload :DynamicInliner, 'temple/filters/dynamic_inliner' + autoload :Escapable, 'temple/filters/escapable' + autoload :Eraser, 'temple/filters/eraser' + autoload :Validator, 'temple/filters/validator' + autoload :Encoding, 'temple/filters/encoding' + autoload :RemoveBOM, 'temple/filters/remove_bom' + end + + module HTML + autoload :Dispatcher, 'temple/html/dispatcher' + autoload :Filter, 'temple/html/filter' + autoload :Fast, 'temple/html/fast' + autoload :Pretty, 'temple/html/pretty' + autoload :AttributeMerger, 'temple/html/attribute_merger' + autoload :AttributeRemover, 'temple/html/attribute_remover' + autoload :AttributeSorter, 'temple/html/attribute_sorter' + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/engine.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/engine.rb new file mode 100644 index 0000000..b7f0c51 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/engine.rb @@ -0,0 +1,67 @@ +module Temple + # An engine is simply a chain of compilers (that often includes a parser, + # some filters and a generator). + # + # class MyEngine < Temple::Engine + # # First run MyParser, passing the :strict option + # use MyParser, :strict + # + # # Then a custom filter + # use MyFilter + # + # # Then some general optimizations filters + # filter :MultiFlattener + # filter :StaticMerger + # filter :DynamicInliner + # + # # Finally the generator + # generator :ArrayBuffer, :buffer + # end + # + # class SpecialEngine < MyEngine + # append MyCodeOptimizer + # before :ArrayBuffer, Temple::Filters::Validator + # replace :ArrayBuffer, Temple::Generators::RailsOutputBuffer + # end + # + # engine = MyEngine.new(strict: "For MyParser") + # engine.call(something) + # + # @api public + class Engine + include Mixins::Options + include Mixins::EngineDSL + extend Mixins::EngineDSL + + define_options :file, :streaming, :buffer, :save_buffer + + attr_reader :chain + + def self.chain + @chain ||= superclass.respond_to?(:chain) ? superclass.chain.dup : [] + end + + def initialize(opts = {}) + super + @chain = self.class.chain.dup + end + + def call(input) + call_chain.inject(input) {|m, e| e.call(m) } + end + + protected + + def chain_modified! + @call_chain = nil + end + + def call_chain + @call_chain ||= @chain.map do |name, constructor| + f = constructor.call(self) + raise "Constructor #{name} must return callable object" if f && !f.respond_to?(:call) + f + end.compact + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/engine.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/engine.rb new file mode 100644 index 0000000..7ade537 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/engine.rb @@ -0,0 +1,15 @@ +module Temple + module ERB + # Example ERB engine implementation + # + # @api public + class Engine < Temple::Engine + use Temple::ERB::Parser + use Temple::ERB::Trimming + filter :Escapable + filter :MultiFlattener + filter :StaticMerger + generator :ArrayBuffer + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/parser.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/parser.rb new file mode 100644 index 0000000..e626691 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/parser.rb @@ -0,0 +1,40 @@ +module Temple + module ERB + # Example ERB parser + # + # @api public + class Parser < Temple::Parser + ERB_PATTERN = /(\n|<%%|%%>)|<%(==?|\#)?(.*?)?-?%>/m + + def call(input) + result = [:multi] + pos = 0 + input.scan(ERB_PATTERN) do |token, indicator, code| + text = input[pos...$~.begin(0)] + pos = $~.end(0) + if token + case token + when "\n" + result << [:static, "#{text}\n"] << [:newline] + when '<%%', '%%>' + result << [:static, text] unless text.empty? + token.slice!(1) + result << [:static, token] + end + else + result << [:static, text] unless text.empty? + case indicator + when '#' + result << [:code, "\n" * code.count("\n")] + when /=/ + result << [:escape, indicator.size <= 1, [:dynamic, code]] + else + result << [:code, code] + end + end + end + result << [:static, input[pos..-1]] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/template.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/template.rb new file mode 100644 index 0000000..3348dc2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/template.rb @@ -0,0 +1,11 @@ +module Temple + # ERB example implementation + # + # Example usage: + # Temple::ERB::Template.new { "<%= 'Hello, world!' %>" }.render + # + module ERB + # ERB Template class + Template = Temple::Templates::Tilt(Engine) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/trimming.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/trimming.rb new file mode 100644 index 0000000..a4742da --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/erb/trimming.rb @@ -0,0 +1,23 @@ +module Temple + module ERB + # ERB trimming like in erubis + # Deletes spaces around '<% %>' and leave spaces around '<%= %>'. + # @api public + class Trimming < Filter + define_options trim: true + + def on_multi(*exps) + exps = exps.each_with_index.map do |e,i| + if e.first == :static && i > 0 && exps[i-1].first == :code + [:static, e.last.lstrip] + elsif e.first == :static && i < exps.size-1 && exps[i+1].first == :code + [:static, e.last.rstrip] + else + e + end + end if options[:trim] + [:multi, *exps] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/exceptions.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/exceptions.rb new file mode 100644 index 0000000..e2a9dd1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/exceptions.rb @@ -0,0 +1,13 @@ +module Temple + # Exception raised if invalid temple expression is found + # + # @api public + class InvalidExpression < RuntimeError + end + + # Exception raised if something bad happens in a Temple filter + # + # @api public + class FilterError < RuntimeError + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filter.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filter.rb new file mode 100644 index 0000000..ca5fb08 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filter.rb @@ -0,0 +1,9 @@ +module Temple + # Temple base filter + # @api public + class Filter + include Utils + include Mixins::Dispatcher + include Mixins::Options + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/code_merger.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/code_merger.rb new file mode 100644 index 0000000..350d518 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/code_merger.rb @@ -0,0 +1,30 @@ +module Temple + module Filters + # @api public + class CodeMerger < Filter + def on_multi(*exps) + result = [:multi] + code = nil + + exps.each do |exp| + if exp.first == :code + if code + code << '; ' unless code =~ /\n\Z/ + code << exp.last + else + code = exp.last.dup + result << [:code, code] + end + elsif code && exp.first == :newline + code << "\n" + else + result << compile(exp) + code = nil + end + end + + result.size == 2 ? result[1] : result + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/control_flow.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/control_flow.rb new file mode 100644 index 0000000..7ddcf29 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/control_flow.rb @@ -0,0 +1,42 @@ +module Temple + module Filters + # Control flow filter which processes [:if, condition, yes-exp, no-exp] + # and [:block, code, content] expressions. + # This is useful for ruby code generation with lots of conditionals. + # + # @api public + class ControlFlow < Filter + def on_if(condition, yes, no = nil) + result = [:multi, [:code, "if #{condition}"], compile(yes)] + while no && no.first == :if + result << [:code, "elsif #{no[1]}"] << compile(no[2]) + no = no[3] + end + result << [:code, 'else'] << compile(no) if no + result << [:code, 'end'] + result + end + + def on_case(arg, *cases) + result = [:multi, [:code, arg ? "case (#{arg})" : 'case']] + cases.map do |c| + condition, exp = c + result << [:code, condition == :else ? 'else' : "when #{condition}"] << compile(exp) + end + result << [:code, 'end'] + result + end + + def on_cond(*cases) + on_case(nil, *cases) + end + + def on_block(code, exp) + [:multi, + [:code, code], + compile(exp), + [:code, 'end']] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/dynamic_inliner.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/dynamic_inliner.rb new file mode 100644 index 0000000..76b29f3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/dynamic_inliner.rb @@ -0,0 +1,71 @@ +module Temple + module Filters + # Inlines several static/dynamic into a single dynamic. + # + # @api public + class DynamicInliner < Filter + def on_multi(*exps) + result = [:multi] + curr = nil + prev = [] + state = :looking + + exps.each do |exp| + type, arg = exp + + case type + when :newline + if state == :looking + # We haven't found any static/dynamic, so let's just add it + result << exp + else + # We've found something, so let's make sure the generated + # dynamic contains a newline by escaping a newline and + # starting a new string: + # + # "Hello "\ + # "#{@world}" + prev << exp + curr[1] << "\"\\\n\"" + end + when :dynamic, :static + case state + when :looking + # Found a single static/dynamic. We don't want to turn this + # into a dynamic yet. Instead we store it, and if we find + # another one, we add both then. + state = :single + prev = [exp] + curr = [:dynamic, '"'] + when :single + # Yes! We found another one. Add the current dynamic to the result. + state = :several + result << curr + end + curr[1] << (type == :static ? arg.inspect[1..-2] : "\#{#{arg}}") + else + if state != :looking + # We need to add the closing quote. + curr[1] << '"' + # If we found a single exp last time, let's add it. + result.concat(prev) if state == :single + end + # Compile the current exp + result << compile(exp) + # Now we're looking for more! + state = :looking + end + end + + if state != :looking + # We need to add the closing quote. + curr[1] << '"' + # If we found a single exp last time, let's add it. + result.concat(prev) if state == :single + end + + result.size == 2 ? result[1] : result + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/encoding.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/encoding.rb new file mode 100644 index 0000000..92eb629 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/encoding.rb @@ -0,0 +1,24 @@ +module Temple + module Filters + # Try to encode input string + # + # @api public + class Encoding < Parser + define_options encoding: 'utf-8' + + def call(s) + if options[:encoding] && s.respond_to?(:encoding) + old_enc = s.encoding + s = s.dup if s.frozen? + s.force_encoding(options[:encoding]) + # Fall back to old encoding if new encoding is invalid + unless s.valid_encoding? + s.force_encoding(old_enc) + s.force_encoding(::Encoding::BINARY) unless s.valid_encoding? + end + end + s + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/eraser.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/eraser.rb new file mode 100644 index 0000000..9d9ff2e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/eraser.rb @@ -0,0 +1,22 @@ +module Temple + module Filters + # Erase expressions with a certain type + # + # @api public + class Eraser < Filter + # [] is the empty type => keep all + define_options :erase, keep: [[]] + + def compile(exp) + exp.first == :multi || (do?(:keep, exp) && !do?(:erase, exp)) ? + super(exp) : [:multi] + end + + protected + + def do?(list, exp) + options[list].to_a.map {|type| [*type] }.any? {|type| exp[0,type.size] == type } + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/escapable.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/escapable.rb new file mode 100644 index 0000000..9271f35 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/escapable.rb @@ -0,0 +1,40 @@ +module Temple + module Filters + # Escape dynamic or static expressions. + # This filter must be used after Temple::HTML::* and before the generators. + # It can be enclosed with Temple::Filters::DynamicInliner filters to + # reduce calls to Temple::Utils#escape_html. + # + # @api public + class Escapable < Filter + # Activate the usage of html_safe? if it is available (for Rails 3 for example) + define_options :escape_code, + :disable_escape, + use_html_safe: ''.respond_to?(:html_safe?) + + def initialize(opts = {}) + super + @escape_code = options[:escape_code] || + "::Temple::Utils.escape_html#{options[:use_html_safe] ? '_safe' : ''}((%s))" + @escaper = eval("proc {|v| #{@escape_code % 'v'} }") + @escape = false + end + + def on_escape(flag, exp) + old = @escape + @escape = flag && !options[:disable_escape] + compile(exp) + ensure + @escape = old + end + + def on_static(value) + [:static, @escape ? @escaper[value] : value] + end + + def on_dynamic(value) + [:dynamic, @escape ? @escape_code % value : value] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/multi_flattener.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/multi_flattener.rb new file mode 100644 index 0000000..d1ce92b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/multi_flattener.rb @@ -0,0 +1,25 @@ +module Temple + module Filters + # Flattens nested multi expressions + # + # @api public + class MultiFlattener < Filter + def on_multi(*exps) + # If the multi contains a single element, just return the element + return compile(exps.first) if exps.size == 1 + result = [:multi] + + exps.each do |exp| + exp = compile(exp) + if exp.first == :multi + result.concat(exp[1..-1]) + else + result << exp + end + end + + result + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/remove_bom.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/remove_bom.rb new file mode 100644 index 0000000..cbbb81d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/remove_bom.rb @@ -0,0 +1,13 @@ +module Temple + module Filters + # Remove BOM from input string + # + # @api public + class RemoveBOM < Parser + def call(s) + return s if s.encoding.name !~ /^UTF-(8|16|32)(BE|LE)?/ + s.gsub(Regexp.new("\\A\uFEFF".encode(s.encoding.name)), ''.freeze) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/static_analyzer.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/static_analyzer.rb new file mode 100644 index 0000000..215c079 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/static_analyzer.rb @@ -0,0 +1,30 @@ +module Temple + module Filters + # Convert [:dynamic, code] to [:static, text] if code is static Ruby expression. + class StaticAnalyzer < Filter + def call(exp) + # Optimize only when Ripper is available. + if ::Temple::StaticAnalyzer.available? + super + else + exp + end + end + + def on_dynamic(code) + if ::Temple::StaticAnalyzer.static?(code) + exp = [:static, eval(code).to_s] + + newlines = code.count("\n") + if newlines == 0 + exp + else + [:multi, exp, *newlines.times.map { [:newline] }] + end + else + [:dynamic, code] + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/static_merger.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/static_merger.rb new file mode 100644 index 0000000..47c15ba --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/static_merger.rb @@ -0,0 +1,37 @@ +module Temple + module Filters + # Merges several statics into a single static. Example: + # + # [:multi, + # [:static, "Hello "], + # [:static, "World!"]] + # + # Compiles to: + # + # [:static, "Hello World!"] + # + # @api public + class StaticMerger < Filter + def on_multi(*exps) + result = [:multi] + text = nil + + exps.each do |exp| + if exp.first == :static + if text + text << exp.last + else + text = exp.last.dup + result << [:static, text] + end + else + result << compile(exp) + text = nil unless exp.first == :newline + end + end + + result.size == 2 ? result[1] : result + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/string_splitter.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/string_splitter.rb new file mode 100644 index 0000000..0a454f5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/string_splitter.rb @@ -0,0 +1,130 @@ +begin + require 'ripper' +rescue LoadError +end + +module Temple + module Filters + # Compile [:dynamic, "foo#{bar}"] to [:multi, [:static, 'foo'], [:dynamic, 'bar']] + class StringSplitter < Filter + if defined?(Ripper) && RUBY_VERSION >= "2.0.0" && Ripper.respond_to?(:lex) + class << self + # `code` param must be valid string literal + def compile(code) + [].tap do |exps| + tokens = Ripper.lex(code.strip) + tokens.pop while tokens.last && [:on_comment, :on_sp].include?(tokens.last[1]) + + if tokens.size < 2 + raise(FilterError, "Expected token size >= 2 but got: #{tokens.size}") + end + compile_tokens!(exps, tokens) + end + end + + private + + def strip_quotes!(tokens) + _, type, beg_str = tokens.shift + if type != :on_tstring_beg + raise(FilterError, "Expected :on_tstring_beg but got: #{type}") + end + + _, type, end_str = tokens.pop + if type != :on_tstring_end + raise(FilterError, "Expected :on_tstring_end but got: #{type}") + end + + [beg_str, end_str] + end + + def compile_tokens!(exps, tokens) + beg_str, end_str = strip_quotes!(tokens) + + until tokens.empty? + _, type, str = tokens.shift + + case type + when :on_tstring_content + exps << [:static, eval("#{beg_str}#{str}#{end_str}").to_s] + when :on_embexpr_beg + embedded = shift_balanced_embexpr(tokens) + exps << [:dynamic, embedded] unless embedded.empty? + end + end + end + + def shift_balanced_embexpr(tokens) + String.new.tap do |embedded| + embexpr_open = 1 + + until tokens.empty? + _, type, str = tokens.shift + case type + when :on_embexpr_beg + embexpr_open += 1 + when :on_embexpr_end + embexpr_open -= 1 + break if embexpr_open == 0 + end + + embedded << str + end + end + end + end + + def on_dynamic(code) + return [:dynamic, code] unless string_literal?(code) + return [:dynamic, code] if code.include?("\n") + + temple = [:multi] + StringSplitter.compile(code).each do |type, content| + case type + when :static + temple << [:static, content] + when :dynamic + temple << on_dynamic(content) + end + end + temple + end + + private + + def string_literal?(code) + return false if SyntaxChecker.syntax_error?(code) + + type, instructions = Ripper.sexp(code) + return false if type != :program + return false if instructions.size > 1 + + type, _ = instructions.first + type == :string_literal + end + + class SyntaxChecker < Ripper + class ParseError < StandardError; end + + def self.syntax_error?(code) + self.new(code).parse + false + rescue ParseError + true + end + + private + + def on_parse_error(*) + raise ParseError + end + end + else + # Do nothing if ripper is unavailable + def call(ast) + ast + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/validator.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/validator.rb new file mode 100644 index 0000000..cea0732 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/filters/validator.rb @@ -0,0 +1,15 @@ +module Temple + module Filters + # Validates temple expression with given grammar + # + # @api public + class Validator < Filter + define_options grammar: Temple::Grammar + + def compile(exp) + options[:grammar].validate!(exp) + exp + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generator.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generator.rb new file mode 100644 index 0000000..1d6067b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generator.rb @@ -0,0 +1,88 @@ +module Temple + # Abstract generator base class + # Generators should inherit this class and + # compile the Core Abstraction to ruby code. + # + # @api public + class Generator + include Utils + include Mixins::CompiledDispatcher + include Mixins::Options + + define_options :save_buffer, + capture_generator: 'StringBuffer', + buffer: '_buf', + freeze_static: RUBY_VERSION >= '2.1' + + def call(exp) + [preamble, compile(exp), postamble].flatten.compact.join('; ') + end + + def preamble + [save_buffer, create_buffer] + end + + def postamble + [return_buffer, restore_buffer] + end + + def save_buffer + "begin; #{@original_buffer = unique_name} = #{buffer} if defined?(#{buffer})" if options[:save_buffer] + end + + def restore_buffer + "ensure; #{buffer} = #{@original_buffer}; end" if options[:save_buffer] + end + + def create_buffer + end + + def return_buffer + 'nil' + end + + def on(*exp) + raise InvalidExpression, "Generator supports only core expressions - found #{exp.inspect}" + end + + def on_multi(*exp) + exp.map {|e| compile(e) }.join('; '.freeze) + end + + def on_newline + "\n" + end + + def on_capture(name, exp) + capture_generator.new(buffer: name).call(exp) + end + + def on_static(text) + concat(options[:freeze_static] ? "#{text.inspect}.freeze" : text.inspect) + end + + def on_dynamic(code) + concat(code) + end + + def on_code(code) + code + end + + protected + + def buffer + options[:buffer] + end + + def capture_generator + @capture_generator ||= Class === options[:capture_generator] ? + options[:capture_generator] : + Generators.const_get(options[:capture_generator]) + end + + def concat(str) + "#{buffer} << (#{str})" + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/array.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/array.rb new file mode 100644 index 0000000..29803ef --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/array.rb @@ -0,0 +1,21 @@ +module Temple + module Generators + # Implements an array buffer. + # + # _buf = [] + # _buf << "static" + # _buf << dynamic + # _buf + # + # @api public + class Array < Generator + def create_buffer + "#{buffer} = []" + end + + def return_buffer + buffer + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/array_buffer.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/array_buffer.rb new file mode 100644 index 0000000..9d3b197 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/array_buffer.rb @@ -0,0 +1,29 @@ +module Temple + module Generators + # Just like Array, but calls #join on the array. + # + # _buf = [] + # _buf << "static" + # _buf << dynamic + # _buf.join("") + # + # @api public + class ArrayBuffer < Array + def call(exp) + case exp.first + when :static + [save_buffer, "#{buffer} = #{exp.last.inspect}", restore_buffer].compact.join('; ') + when :dynamic + [save_buffer, "#{buffer} = (#{exp.last}).to_s", restore_buffer].compact.join('; ') + else + super + end + end + + def return_buffer + freeze = options[:freeze_static] ? '.freeze' : '' + "#{buffer} = #{buffer}.join(\"\"#{freeze})" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/erb.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/erb.rb new file mode 100644 index 0000000..d304807 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/erb.rb @@ -0,0 +1,32 @@ +module Temple + module Generators + # Implements an ERB generator. + # + # @api public + class ERB < Generator + def call(exp) + compile(exp) + end + + def on_multi(*exp) + exp.map {|e| compile(e) }.join('') + end + + def on_capture(name, exp) + on_code(super) + end + + def on_static(text) + text + end + + def on_dynamic(code) + "<%= #{code} %>" + end + + def on_code(code) + "<% #{code} %>" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/rails_output_buffer.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/rails_output_buffer.rb new file mode 100644 index 0000000..69be6ee --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/rails_output_buffer.rb @@ -0,0 +1,35 @@ +module Temple + module Generators + # Implements a rails output buffer. + # + # @output_buffer = ActiveSupport::SafeBuffer + # @output_buffer.safe_concat "static" + # @output_buffer.safe_concat dynamic.to_s + # @output_buffer + # + # @api public + class RailsOutputBuffer < StringBuffer + define_options :streaming, + buffer_class: 'ActiveSupport::SafeBuffer', + buffer: '@output_buffer', + # output_buffer is needed for Rails 3.1 Streaming support + capture_generator: RailsOutputBuffer + + def call(exp) + [preamble, compile(exp), postamble].flatten.compact.join('; '.freeze) + end + + def create_buffer + if options[:streaming] && options[:buffer] == '@output_buffer' + "#{buffer} = output_buffer || #{options[:buffer_class]}.new" + else + "#{buffer} = #{options[:buffer_class]}.new" + end + end + + def concat(str) + "#{buffer}.safe_concat((#{str}))" + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/string_buffer.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/string_buffer.rb new file mode 100644 index 0000000..c22646c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/generators/string_buffer.rb @@ -0,0 +1,25 @@ +module Temple + module Generators + # Implements a string buffer. + # + # _buf = '' + # _buf << "static" + # _buf << dynamic.to_s + # _buf + # + # @api public + class StringBuffer < ArrayBuffer + def create_buffer + "#{buffer} = ''" + end + + def return_buffer + buffer + end + + def on_dynamic(code) + concat("(#{code}).to_s") + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/grammar.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/grammar.rb new file mode 100644 index 0000000..bc9a5a0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/grammar.rb @@ -0,0 +1,57 @@ +module Temple + # Temple expression grammar which can be used to validate Temple expressions. + # + # Example: + # Temple::Grammar.match? [:static, 'Valid Temple Expression'] + # Temple::Grammar.validate! [:multi, 'Invalid Temple Expression'] + # + # See {file:EXPRESSIONS.md Expression documentation}. + # + # @api public + module Grammar + extend Mixins::GrammarDSL + + Expression << + # Core abstraction + [:multi, 'Expression*'] | + [:static, String] | + [:dynamic, String] | + [:code, String] | + [:capture, String, Expression] | + [:newline] | + # Control flow abstraction + [:if, String, Expression, 'Expression?'] | + [:block, String, Expression] | + [:case, String, 'Case*'] | + [:cond, 'Case*'] | + # Escape abstraction + [:escape, Bool, Expression] | + # HTML abstraction + [:html, :doctype, String] | + [:html, :comment, Expression] | + [:html, :condcomment, String, Expression]| + [:html, :js, Expression] | + [:html, :tag, HTMLIdentifier, Expression, 'Expression?'] | + [:html, :attrs, 'HTMLAttr*'] | + HTMLAttr + + EmptyExp << + [:newline] | [:multi, 'EmptyExp*'] + + HTMLAttr << + [:html, :attr, HTMLIdentifier, Expression] + + HTMLIdentifier << + Symbol | String + + Case << + [Condition, Expression] + + Condition << + String | :else + + Bool << + true | false + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/attribute_merger.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/attribute_merger.rb new file mode 100644 index 0000000..bff3a88 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/attribute_merger.rb @@ -0,0 +1,42 @@ +module Temple + module HTML + # This filter merges html attributes (e.g. used for id and class) + # @api public + class AttributeMerger < Filter + define_options merge_attrs: {'id' => '_', 'class' => ' '} + + def on_html_attrs(*attrs) + values = {} + + attrs.each do |_, _, name, value| + name = name.to_s + if values[name] + raise(FilterError, "Multiple #{name} attributes specified") unless options[:merge_attrs][name] + values[name] << value + else + values[name] = [value] + end + end + + attrs = values.map do |name, value| + if (delimiter = options[:merge_attrs][name]) && value.size > 1 + exp = [:multi] + if value.all? {|v| contains_nonempty_static?(v) } + exp << value.first + value[1..-1].each {|v| exp << [:static, delimiter] << v } + else + captures = unique_name + exp << [:code, "#{captures} = []"] + value.each_with_index {|v, i| exp << [:capture, "#{captures}[#{i}]", v] } + exp << [:dynamic, "#{captures}.reject(&:empty?).join(#{delimiter.inspect})"] + end + else + exp = value.first + end + [:html, :attr, name, exp] + end + [:html, :attrs, *attrs] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/attribute_remover.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/attribute_remover.rb new file mode 100644 index 0000000..ff9d1e9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/attribute_remover.rb @@ -0,0 +1,35 @@ +module Temple + module HTML + # This filter removes empty attributes + # @api public + class AttributeRemover < Filter + define_options remove_empty_attrs: %w(id class) + + def initialize(opts = {}) + super + raise ArgumentError, "Option :remove_empty_attrs must be an Array of Strings" unless Array === options[:remove_empty_attrs] && + options[:remove_empty_attrs].all? {|a| String === a } + end + + def on_html_attrs(*attrs) + [:multi, *attrs.map {|attr| compile(attr) }] + end + + def on_html_attr(name, value) + return super unless options[:remove_empty_attrs].include?(name.to_s) + + if empty_exp?(value) + value + elsif contains_nonempty_static?(value) + [:html, :attr, name, value] + else + tmp = unique_name + [:multi, + [:capture, tmp, compile(value)], + [:if, "!#{tmp}.empty?", + [:html, :attr, name, [:dynamic, tmp]]]] + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/attribute_sorter.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/attribute_sorter.rb new file mode 100644 index 0000000..25e42f8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/attribute_sorter.rb @@ -0,0 +1,21 @@ +module Temple + module HTML + # This filter sorts html attributes. + # @api public + class AttributeSorter < Filter + define_options sort_attrs: true + + def call(exp) + options[:sort_attrs] ? super : exp + end + + def on_html_attrs(*attrs) + n = 0 # Use n to make sort stable. This is important because the merger could be executed afterwards. + [:html, :attrs, *attrs.sort_by do |attr| + raise(InvalidExpression, 'Attribute is not a html attr') if attr[0] != :html || attr[1] != :attr + [attr[2].to_s, n += 1] + end] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/dispatcher.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/dispatcher.rb new file mode 100644 index 0000000..9afcab9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/dispatcher.rb @@ -0,0 +1,31 @@ +module Temple + module HTML + # @api private + module Dispatcher + def on_html_attrs(*attrs) + [:html, :attrs, *attrs.map {|a| compile(a) }] + end + + def on_html_attr(name, content) + [:html, :attr, name, compile(content)] + end + + def on_html_comment(content) + [:html, :comment, compile(content)] + end + + def on_html_condcomment(condition, content) + [:html, :condcomment, condition, compile(content)] + end + + def on_html_js(content) + [:html, :js, compile(content)] + end + + def on_html_tag(name, attrs, content = nil) + result = [:html, :tag, name, compile(attrs)] + content ? (result << compile(content)) : result + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/fast.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/fast.rb new file mode 100644 index 0000000..59ddb08 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/fast.rb @@ -0,0 +1,130 @@ +module Temple + module HTML + # @api public + class Fast < Filter + DOCTYPES = { + xml: { + '1.1' => '', + '5' => '', + 'html' => '', + 'strict' => '', + 'frameset' => '', + 'mobile' => '', + 'basic' => '', + 'transitional' => '', + 'svg' => '' + }, + html: { + '5' => '', + 'html' => '', + 'strict' => '', + 'frameset' => '', + 'transitional' => '' + } + } + DOCTYPES[:xhtml] = DOCTYPES[:xml] + DOCTYPES.freeze + + # See http://www.w3.org/html/wg/drafts/html/master/single-page.html#void-elements + HTML_VOID_ELEMENTS = %w[area base br col embed hr img input keygen link menuitem meta param source track wbr] + + define_options format: :xhtml, + attr_quote: '"', + autoclose: HTML_VOID_ELEMENTS, + js_wrapper: nil + + def initialize(opts = {}) + super + @format = options[:format] + unless [:xhtml, :html, :xml].include?(@format) + if @format == :html4 || @format == :html5 + warn "Format #{@format.inspect} is deprecated, use :html" + @format = :html + else + raise ArgumentError, "Invalid format #{@format.inspect}" + end + end + wrapper = options[:js_wrapper] + wrapper = @format == :xml || @format == :xhtml ? :cdata : :comment if wrapper == :guess + @js_wrapper = + case wrapper + when :comment + [ "" ] + when :cdata + [ "\n//\n" ] + when :both + [ "" ] + when nil + when Array + wrapper + else + raise ArgumentError, "Invalid JavaScript wrapper #{wrapper.inspect}" + end + end + + def on_html_doctype(type) + type = type.to_s.downcase + + if type =~ /^xml(\s+(.+))?$/ + raise(FilterError, 'Invalid xml directive in html mode') if @format == :html + w = options[:attr_quote] + str = "" + else + str = DOCTYPES[@format][type] || raise(FilterError, "Invalid doctype #{type}") + end + + [:static, str] + end + + def on_html_comment(content) + [:multi, + [:static, '']] + end + + def on_html_condcomment(condition, content) + on_html_comment [:multi, + [:static, "[#{condition}]>"], + content, + [:static, ''] + result << compile(content) if content + result << [:static, ""] if !closed + result + end + + def on_html_attrs(*attrs) + [:multi, *attrs.map {|attr| compile(attr) }] + end + + def on_html_attr(name, value) + if @format == :html && empty_exp?(value) + [:static, " #{name}"] + else + [:multi, + [:static, " #{name}=#{options[:attr_quote]}"], + compile(value), + [:static, options[:attr_quote]]] + end + end + + def on_html_js(content) + if @js_wrapper + [:multi, + [:static, @js_wrapper.first], + compile(content), + [:static, @js_wrapper.last]] + else + compile(content) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/filter.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/filter.rb new file mode 100644 index 0000000..6175a87 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/filter.rb @@ -0,0 +1,21 @@ +module Temple + module HTML + # @api public + class Filter < Temple::Filter + include Dispatcher + + def contains_nonempty_static?(exp) + case exp.first + when :multi + exp[1..-1].any? {|e| contains_nonempty_static?(e) } + when :escape + contains_nonempty_static?(exp.last) + when :static + !exp.last.empty? + else + false + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/pretty.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/pretty.rb new file mode 100644 index 0000000..fb99684 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/pretty.rb @@ -0,0 +1,103 @@ +module Temple + module HTML + # @api public + class Pretty < Fast + define_options indent: ' ', + pretty: true, + indent_tags: %w(article aside audio base body datalist dd div dl dt + fieldset figure footer form head h1 h2 h3 h4 h5 h6 + header hgroup hr html li link meta nav ol option p + rp rt ruby section script style table tbody td tfoot + th thead tr ul video doctype).freeze, + pre_tags: %w(code pre textarea).freeze + + def initialize(opts = {}) + super + @indent_next = nil + @indent = 0 + @pretty = options[:pretty] + @pre_tags = @format != :xml && Regexp.union(options[:pre_tags].map {|t| "<#{t}" }) + end + + def call(exp) + @pretty ? [:multi, preamble, compile(exp)] : super + end + + def on_static(content) + return [:static, content] unless @pretty + unless @pre_tags && @pre_tags =~ content + content = content.sub(/\A\s*\n?/, "\n".freeze) if @indent_next + content = content.gsub("\n".freeze, indent) + end + @indent_next = false + [:static, content] + end + + def on_dynamic(code) + return [:dynamic, code] unless @pretty + indent_next, @indent_next = @indent_next, false + [:dynamic, "::Temple::Utils.indent_dynamic((#{code}), #{indent_next.inspect}, #{indent.inspect}#{@pre_tags ? ', ' + @pre_tags_name : ''})"] + end + + def on_html_doctype(type) + return super unless @pretty + [:multi, [:static, tag_indent('doctype')], super] + end + + def on_html_comment(content) + return super unless @pretty + result = [:multi, [:static, tag_indent('comment')], super] + @indent_next = false + result + end + + def on_html_tag(name, attrs, content = nil) + return super unless @pretty + + name = name.to_s + closed = !content || (empty_exp?(content) && options[:autoclose].include?(name)) + + @pretty = false + result = [:multi, [:static, "#{tag_indent(name)}<#{name}"], compile(attrs)] + result << [:static, (closed && @format != :html ? ' /' : '') + '>'] + + @pretty = !@pre_tags || !options[:pre_tags].include?(name) + if content + @indent += 1 + result << compile(content) + @indent -= 1 + end + unless closed + indent = tag_indent(name) + result << [:static, "#{content && !empty_exp?(content) ? indent : ''}"] + end + @pretty = true + result + end + + protected + + def preamble + return [:multi] unless @pre_tags + @pre_tags_name = unique_name + [:code, "#{@pre_tags_name} = /#{@pre_tags.source}/"] + end + + def indent + "\n" + (options[:indent] || '') * @indent + end + + # Return indentation before tag + def tag_indent(name) + if @format == :xml + flag = @indent_next != nil + @indent_next = true + else + flag = @indent_next != nil && (@indent_next || options[:indent_tags].include?(name)) + @indent_next = options[:indent_tags].include?(name) + end + flag ? indent : '' + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/safe.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/safe.rb new file mode 100644 index 0000000..7280434 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/html/safe.rb @@ -0,0 +1,23 @@ +module Temple + module HTML + class SafeString < String + def html_safe?; true end + def html_safe; self end + def to_s; self end + end + end +end + +class Object + def html_safe?; false end +end + +class Numeric + def html_safe?; true end +end + +class String + def html_safe + Temple::HTML::SafeString.new(self) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/map.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/map.rb new file mode 100644 index 0000000..2b4e9d0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/map.rb @@ -0,0 +1,105 @@ +module Temple + # Immutable map class which supports map merging + # @api public + class ImmutableMap + include Enumerable + + def initialize(*map) + @map = map.compact + end + + def include?(key) + @map.any? {|h| h.include?(key) } + end + + def [](key) + @map.each {|h| return h[key] if h.include?(key) } + nil + end + + def each + keys.each {|k| yield(k, self[k]) } + end + + def keys + @map.inject([]) {|keys, h| keys.concat(h.keys) }.uniq + end + + def values + keys.map {|k| self[k] } + end + + def to_hash + result = {} + each {|k, v| result[k] = v } + result + end + end + + # Mutable map class which supports map merging + # @api public + class MutableMap < ImmutableMap + def initialize(*map) + super({}, *map) + end + + def []=(key, value) + @map.first[key] = value + end + + def update(map) + @map.first.update(map) + end + end + + class OptionMap < MutableMap + def initialize(*map, &block) + super(*map) + @handler = block + @valid = {} + @deprecated = {} + end + + def []=(key, value) + validate_key!(key) + super + end + + def update(map) + validate_map!(map) + super + end + + def valid_keys + (keys + @valid.keys + + @map.map {|h| h.valid_keys if h.respond_to?(:valid_keys) }.compact.flatten).uniq + end + + def add_valid_keys(*keys) + keys.flatten.each { |key| @valid[key] = true } + end + + def add_deprecated_keys(*keys) + keys.flatten.each { |key| @valid[key] = @deprecated[key] = true } + end + + def validate_map!(map) + map.to_hash.keys.each {|key| validate_key!(key) } + end + + def validate_key!(key) + @handler.call(self, key, :deprecated) if deprecated_key?(key) + @handler.call(self, key, :invalid) unless valid_key?(key) + end + + def deprecated_key?(key) + @deprecated.include?(key) || + @map.any? {|h| h.deprecated_key?(key) if h.respond_to?(:deprecated_key?) } + end + + def valid_key?(key) + include?(key) || @valid.include?(key) || + @map.any? {|h| h.valid_key?(key) if h.respond_to?(:valid_key?) } + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/dispatcher.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/dispatcher.rb new file mode 100644 index 0000000..f050542 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/dispatcher.rb @@ -0,0 +1,161 @@ +module Temple + module Mixins + # @api private + module CoreDispatcher + def on_multi(*exps) + multi = [:multi] + exps.each {|exp| multi << compile(exp) } + multi + end + + def on_capture(name, exp) + [:capture, name, compile(exp)] + end + end + + # @api private + module EscapeDispatcher + def on_escape(flag, exp) + [:escape, flag, compile(exp)] + end + end + + # @api private + module ControlFlowDispatcher + def on_if(condition, *cases) + [:if, condition, *cases.compact.map {|e| compile(e) }] + end + + def on_case(arg, *cases) + [:case, arg, *cases.map {|condition, exp| [condition, compile(exp)] }] + end + + def on_block(code, content) + [:block, code, compile(content)] + end + + def on_cond(*cases) + [:cond, *cases.map {|condition, exp| [condition, compile(exp)] }] + end + end + + # @api private + module CompiledDispatcher + def call(exp) + compile(exp) + end + + def compile(exp) + dispatcher(exp) + end + + private + + def dispatcher(exp) + replace_dispatcher(exp) + end + + def replace_dispatcher(exp) + tree = DispatchNode.new + dispatched_methods.each do |method| + method.split('_'.freeze)[1..-1].inject(tree) {|node, type| node[type.to_sym] }.method = method + end + self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def dispatcher(exp) + return replace_dispatcher(exp) if self.class != #{self.class} + #{tree.compile.gsub("\n", "\n ")} + end + RUBY + dispatcher(exp) + end + + def dispatched_methods + re = /^on(_[a-zA-Z0-9]+)*$/ + self.methods.map(&:to_s).select(&re.method(:=~)) + end + + # @api private + class DispatchNode < Hash + attr_accessor :method + + def initialize + super { |hsh,key| hsh[key] = DispatchNode.new } + @method = nil + end + + def compile(level = 0, call_parent = nil) + call_method = method ? (level == 0 ? "#{method}(*exp)" : + "#{method}(*exp[#{level}..-1])") : call_parent + if empty? + raise 'Invalid dispatcher node' unless method + call_method + else + code = String.new + code << "case(exp[#{level}])\n" + each do |key, child| + code << "when #{key.inspect}\n " << + child.compile(level + 1, call_method).gsub("\n".freeze, "\n ".freeze) << "\n".freeze + end + code << "else\n " << (call_method || 'exp') << "\nend" + end + end + end + end + + # @api public + # + # Implements a compatible call-method + # based on the including classe's methods. + # + # It uses every method starting with + # "on" and uses the rest of the method + # name as prefix of the expression it + # will receive. So, if a dispatcher + # has a method named "on_x", this method + # will be called with arg0,..,argN + # whenever an expression like [:x, arg0,..,argN ] + # is encountered. + # + # This works with longer prefixes, too. + # For example a method named "on_y_z" + # will be called whenever an expression + # like [:y, :z, .. ] is found. Furthermore, + # if additionally a method named "on_y" + # is present, it will be called when an + # expression starts with :y but then does + # not contain with :z. This way a + # dispatcher can implement namespaces. + # + # @note + # Processing does not reach into unknown + # expression types by default. + # + # @example + # class MyAwesomeDispatch + # include Temple::Mixins::Dispatcher + # def on_awesome(thing) # keep awesome things + # return [:awesome, thing] + # end + # def on_boring(thing) # make boring things awesome + # return [:awesome, thing+" with bacon"] + # end + # def on(type,*args) # unknown stuff is boring too + # return [:awesome, 'just bacon'] + # end + # end + # filter = MyAwesomeDispatch.new + # # Boring things are converted: + # filter.call([:boring, 'egg']) #=> [:awesome, 'egg with bacon'] + # # Unknown things too: + # filter.call([:foo]) #=> [:awesome, 'just bacon'] + # # Known but not boring things won't be touched: + # filter.call([:awesome, 'chuck norris']) #=>[:awesome, 'chuck norris'] + # + module Dispatcher + include CompiledDispatcher + include CoreDispatcher + include EscapeDispatcher + include ControlFlowDispatcher + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/engine_dsl.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/engine_dsl.rb new file mode 100644 index 0000000..4657840 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/engine_dsl.rb @@ -0,0 +1,145 @@ +module Temple + module Mixins + # @api private + module EngineDSL + def chain_modified! + end + + def append(*args, &block) + chain << chain_element(args, block) + chain_modified! + end + + def prepend(*args, &block) + chain.unshift(chain_element(args, block)) + chain_modified! + end + + def remove(name) + name = chain_name(name) + raise "#{name} not found" unless chain.reject! {|i| name === i.first } + chain_modified! + end + + alias use append + + def before(name, *args, &block) + name = chain_name(name) + e = chain_element(args, block) + chain.map! {|f| name === f.first ? [e, f] : [f] }.flatten!(1) + raise "#{name} not found" unless chain.include?(e) + chain_modified! + end + + def after(name, *args, &block) + name = chain_name(name) + e = chain_element(args, block) + chain.map! {|f| name === f.first ? [f, e] : [f] }.flatten!(1) + raise "#{name} not found" unless chain.include?(e) + chain_modified! + end + + def replace(name, *args, &block) + name = chain_name(name) + e = chain_element(args, block) + chain.map! {|f| name === f.first ? e : f } + raise "#{name} not found" unless chain.include?(e) + chain_modified! + end + + # Shortcuts to access namespaces + { filter: Temple::Filters, + generator: Temple::Generators, + html: Temple::HTML }.each do |method, mod| + define_method(method) do |name, *options| + use(name, mod.const_get(name), *options) + end + end + + private + + def chain_name(name) + case name + when Class + name.name.to_sym + when Symbol, String + name.to_sym + when Regexp + name + else + raise(ArgumentError, 'Name argument must be Class, Symbol, String or Regexp') + end + end + + def chain_class_constructor(filter, local_options) + define_options(filter.options.valid_keys) if respond_to?(:define_options) && filter.respond_to?(:options) + proc do |engine| + opts = {}.update(engine.options) + opts.delete_if {|k,v| !filter.options.valid_key?(k) } if filter.respond_to?(:options) + opts.update(local_options) if local_options + filter.new(opts) + end + end + + def chain_proc_constructor(name, filter) + raise(ArgumentError, 'Proc or blocks must have arity 0 or 1') if filter.arity > 1 + method_name = "FILTER #{name}" + c = Class === self ? self : singleton_class + filter = c.class_eval { define_method(method_name, &filter); instance_method(method_name) } + proc do |engine| + if filter.arity == 1 + # the proc takes one argument, e.g. use(:Filter) {|exp| exp } + filter.bind(engine) + else + f = filter.bind(engine).call + if f.respond_to? :call + # the proc returns a callable object, e.g. use(:Filter) { Filter.new } + f + else + raise(ArgumentError, 'Proc or blocks must return a Callable or a Class') unless f.respond_to? :new + # the proc returns a class, e.g. use(:Filter) { Filter } + f.new(f.respond_to?(:options) ? engine.options.to_hash.select {|k,v| f.options.valid_key?(k) } : engine.options) + end + end + end + end + + def chain_element(args, block) + name = args.shift + if Class === name + filter = name + name = filter.name.to_sym + else + raise(ArgumentError, 'Name argument must be Class or Symbol') unless Symbol === name + end + + if block + raise(ArgumentError, 'Class and block argument are not allowed at the same time') if filter + filter = block + end + + filter ||= args.shift + + case filter + when Proc + # Proc or block argument + # The proc is converted to a method of the engine class. + # The proc can then access the option hash of the engine. + raise(ArgumentError, 'Too many arguments') unless args.empty? + [name, chain_proc_constructor(name, filter)] + when Class + # Class argument (e.g Filter class) + # The options are passed to the classes constructor. + raise(ArgumentError, 'Too many arguments') if args.size > 1 + [name, chain_class_constructor(filter, args.first)] + else + # Other callable argument (e.g. Object of class which implements #call or Method) + # The callable has no access to the option hash of the engine. + raise(ArgumentError, 'Too many arguments') unless args.empty? + raise(ArgumentError, 'Class or callable argument is required') unless filter.respond_to?(:call) + [name, proc { filter }] + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/grammar_dsl.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/grammar_dsl.rb new file mode 100644 index 0000000..0f154f5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/grammar_dsl.rb @@ -0,0 +1,170 @@ +module Temple + module Mixins + # @api private + module GrammarDSL + class Rule + def initialize(grammar) + @grammar = grammar + end + + def match?(exp) + match(exp, []) + end + alias === match? + alias =~ match? + + def |(rule) + Or.new(@grammar, self, rule) + end + + def copy_to(grammar) + copy = dup.instance_eval { @grammar = grammar; self } + copy.after_copy(self) if copy.respond_to?(:after_copy) + copy + end + end + + class Or < Rule + def initialize(grammar, *children) + super(grammar) + @children = children.map {|rule| @grammar.Rule(rule) } + end + + def <<(rule) + @children << @grammar.Rule(rule) + self + end + + alias | << + + def match(exp, unmatched) + tmp = [] + @children.any? {|rule| rule.match(exp, tmp) } || (unmatched.concat(tmp) && false) + end + + def after_copy(source) + @children = @children.map {|child| child.copy_to(@grammar) } + end + end + + class Root < Or + def initialize(grammar, name) + super(grammar) + @name = name.to_sym + end + + def match(exp, unmatched) + success = super + unmatched << [@name, exp] unless success + success + end + + def validate!(exp) + unmatched = [] + unless match(exp, unmatched) + require 'pp' + entry = unmatched.first + unmatched.reverse_each do |u| + entry = u if u.flatten.size < entry.flatten.size + end + raise(InvalidExpression, PP.pp(entry.last, "#{@grammar}::#{entry.first} did not match\n")) + end + end + + def copy_to(grammar) + grammar.const_defined?(@name) ? grammar.const_get(@name) : super + end + + def after_copy(source) + @grammar.const_set(@name, self) + super + end + end + + class Element < Or + def initialize(grammar, rule) + super(grammar) + @rule = grammar.Rule(rule) + end + + def match(exp, unmatched) + return false unless Array === exp && !exp.empty? + head, *tail = exp + @rule.match(head, unmatched) && super(tail, unmatched) + end + + def after_copy(source) + @children = @children.map do |child| + child == source ? self : child.copy_to(@grammar) + end + @rule = @rule.copy_to(@grammar) + end + end + + class Value < Rule + def initialize(grammar, value) + super(grammar) + @value = value + end + + def match(exp, unmatched) + @value === exp + end + end + + def extended(mod) + mod.extend GrammarDSL + constants.each do |name| + const_get(name).copy_to(mod) if Rule === const_get(name) + end + end + + def match?(exp) + const_get(:Expression).match?(exp) + end + alias === match? + alias =~ match? + + def validate!(exp) + const_get(:Expression).validate!(exp) + end + + def Value(value) + Value.new(self, value) + end + + def Rule(rule) + case rule + when Rule + rule + when Symbol, Class, true, false, nil + Value(rule) + when Array + start = Or.new(self) + curr = [start] + rule.each do |elem| + if elem =~ /^(.*)(\*|\?|\+)$/ + elem = Element.new(self, const_get($1)) + curr.each {|c| c << elem } + elem << elem if $2 != '?' + curr = $2 == '+' ? [elem] : (curr << elem) + else + elem = Element.new(self, elem) + curr.each {|c| c << elem } + curr = [elem] + end + end + elem = Value([]) + curr.each {|c| c << elem } + start + else + raise ArgumentError, "Invalid grammar rule '#{rule.inspect}'" + end + end + + def const_missing(name) + const_set(name, Root.new(self, name)) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/options.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/options.rb new file mode 100644 index 0000000..e52a0cf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/options.rb @@ -0,0 +1,87 @@ +module Temple + module Mixins + # @api public + module ClassOptions + def set_default_options(opts) + warn 'set_default_options has been deprecated, use set_options' + set_options(opts) + end + + def default_options + warn 'default_options has been deprecated, use options' + options + end + + def set_options(opts) + options.update(opts) + end + + def options + @options ||= OptionMap.new(superclass.respond_to?(:options) ? + superclass.options : nil) do |hash, key, what| + warn "#{self}: Option #{key.inspect} is #{what}" unless @option_validator_disabled + end + end + + def define_options(*opts) + if opts.last.respond_to?(:to_hash) + hash = opts.pop.to_hash + options.add_valid_keys(hash.keys) + options.update(hash) + end + options.add_valid_keys(opts) + end + + def define_deprecated_options(*opts) + if opts.last.respond_to?(:to_hash) + hash = opts.pop.to_hash + options.add_deprecated_keys(hash.keys) + options.update(hash) + end + options.add_deprecated_keys(opts) + end + + def disable_option_validator! + @option_validator_disabled = true + end + end + + module ThreadOptions + def with_options(options) + old_options = thread_options + Thread.current[thread_options_key] = ImmutableMap.new(options, thread_options) + yield + ensure + Thread.current[thread_options_key] = old_options + end + + def thread_options + Thread.current[thread_options_key] + end + + protected + + def thread_options_key + @thread_options_key ||= "#{self.name}-thread-options".to_sym + end + end + + # @api public + module Options + def self.included(base) + base.class_eval do + extend ClassOptions + extend ThreadOptions + end + end + + attr_reader :options + + def initialize(opts = {}) + self.class.options.validate_map!(opts) + self.class.options.validate_map!(self.class.thread_options) if self.class.thread_options + @options = ImmutableMap.new({}.update(self.class.options).update(self.class.thread_options || {}).update(opts)) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/template.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/template.rb new file mode 100644 index 0000000..29edb0c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/mixins/template.rb @@ -0,0 +1,28 @@ +module Temple + module Mixins + # @api private + module Template + include ClassOptions + + def compile(code, options) + engine = options.delete(:engine) + raise 'No engine configured' unless engine + engine.new(options).call(code) + end + + def register_as(*names) + raise NotImplementedError + end + + def create(engine, options) + register_as = options.delete(:register_as) + template = Class.new(self) + template.disable_option_validator! + template.options[:engine] = engine + template.options.update(options) + template.register_as(*register_as) if register_as + template + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/parser.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/parser.rb new file mode 100644 index 0000000..c78b5af --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/parser.rb @@ -0,0 +1,8 @@ +module Temple + # Temple base parser + # @api public + class Parser + include Utils + include Mixins::Options + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/static_analyzer.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/static_analyzer.rb new file mode 100644 index 0000000..6efe4af --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/static_analyzer.rb @@ -0,0 +1,77 @@ +begin + require 'ripper' +rescue LoadError +end + +module Temple + module StaticAnalyzer + STATIC_TOKENS = [ + :on_tstring_beg, :on_tstring_end, :on_tstring_content, + :on_embexpr_beg, :on_embexpr_end, + :on_lbracket, :on_rbracket, + :on_qwords_beg, :on_words_sep, :on_qwords_sep, + :on_lparen, :on_rparen, + :on_lbrace, :on_rbrace, :on_label, + :on_int, :on_float, :on_imaginary, + :on_comma, :on_sp, :on_ignored_nl, + ].freeze + + DYNAMIC_TOKENS = [ + :on_ident, :on_period, + ].freeze + + STATIC_KEYWORDS = [ + 'true', 'false', 'nil', + ].freeze + + STATIC_OPERATORS = [ + '=>', + ].freeze + + class << self + def available? + defined?(Ripper) && Ripper.respond_to?(:lex) + end + + def static?(code) + return false if code.nil? || code.strip.empty? + return false if syntax_error?(code) + + Ripper.lex(code).each do |_, token, str| + case token + when *STATIC_TOKENS + # noop + when :on_kw + return false unless STATIC_KEYWORDS.include?(str) + when :on_op + return false unless STATIC_OPERATORS.include?(str) + when *DYNAMIC_TOKENS + return false + else + return false + end + end + true + end + + def syntax_error?(code) + SyntaxChecker.new(code).parse + false + rescue SyntaxChecker::ParseError + true + end + end + + if defined?(Ripper) + class SyntaxChecker < Ripper + class ParseError < StandardError; end + + private + + def on_parse_error(*) + raise ParseError + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/templates.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/templates.rb new file mode 100644 index 0000000..82959c4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/templates.rb @@ -0,0 +1,11 @@ +module Temple + # @api public + module Templates + autoload :Tilt, 'temple/templates/tilt' + autoload :Rails, 'temple/templates/rails' + + def self.method_missing(name, engine, options = {}) + const_get(name).create(engine, options) + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/templates/rails.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/templates/rails.rb new file mode 100644 index 0000000..ca27351 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/templates/rails.rb @@ -0,0 +1,26 @@ +module Temple + module Templates + class Rails + extend Mixins::Template + + def call(template, source = nil) + opts = {}.update(self.class.options).update(file: template.identifier) + self.class.compile((source || template.source), opts) + end + + def supports_streaming? + self.class.options[:streaming] + end + + def self.register_as(*names) + raise 'Rails is not loaded - Temple::Templates::Rails cannot be used' unless defined?(::ActionView) + if ::ActiveSupport::VERSION::MAJOR < 3 || ::ActiveSupport::VERSION::MAJOR == 3 && ::ActiveSupport::VERSION::MINOR < 1 + raise "Temple supports only Rails 3.1 and greater, your Rails version is #{::ActiveSupport::VERSION::STRING}" + end + names.each do |name| + ::ActionView::Template.register_template_handler name.to_sym, new + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/templates/tilt.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/templates/tilt.rb new file mode 100644 index 0000000..f8d3d52 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/templates/tilt.rb @@ -0,0 +1,46 @@ +require 'tilt' + +module Temple + module Templates + class Tilt < ::Tilt::Template + extend Mixins::Template + + define_options mime_type: 'text/html' + + def self.default_mime_type + options[:mime_type] + end + + def self.default_mime_type=(mime_type) + options[:mime_type] = mime_type + end + + # Prepare Temple template + # + # Called immediately after template data is loaded. + # + # @return [void] + def prepare + opts = {}.update(self.class.options).update(options).update(file: eval_file) + opts.delete(:mime_type) + if opts.include?(:outvar) + opts[:buffer] = opts.delete(:outvar) + opts[:save_buffer] = true + end + @src = self.class.compile(data, opts) + end + + # A string containing the (Ruby) source code for the template. + # + # @param [Hash] locals Local variables + # @return [String] Compiled template ruby code + def precompiled_template(locals = {}) + @src + end + + def self.register_as(*names) + ::Tilt.register(self, *names.map(&:to_s)) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/utils.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/utils.rb new file mode 100644 index 0000000..9dede7f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/utils.rb @@ -0,0 +1,101 @@ +begin + require 'escape_utils' +rescue LoadError + begin + require 'cgi/escape' + rescue LoadError + end +end + +module Temple + # @api public + module Utils + extend self + + # Returns an escaped copy of `html`. + # Strings which are declared as html_safe are not escaped. + # + # @param html [String] The string to escape + # @return [String] The escaped string + def escape_html_safe(html) + html.html_safe? ? html : escape_html(html) + end + + if defined?(EscapeUtils) + # Returns an escaped copy of `html`. + # + # @param html [String] The string to escape + # @return [String] The escaped string + def escape_html(html) + EscapeUtils.escape_html(html.to_s, false) + end + elsif defined?(CGI.escapeHTML) + # Returns an escaped copy of `html`. + # + # @param html [String] The string to escape + # @return [String] The escaped string + def escape_html(html) + CGI.escapeHTML(html.to_s) + end + else + # Used by escape_html + # @api private + ESCAPE_HTML = { + '&' => '&', + '"' => '"', + '\'' => ''', + '<' => '<', + '>' => '>' + }.freeze + + ESCAPE_HTML_PATTERN = Regexp.union(*ESCAPE_HTML.keys) + + # Returns an escaped copy of `html`. + # + # @param html [String] The string to escape + # @return [String] The escaped string + def escape_html(html) + html.to_s.gsub(ESCAPE_HTML_PATTERN, ESCAPE_HTML) + end + end + + # Generate unique variable name + # + # @param prefix [String] Variable name prefix + # @return [String] Variable name + def unique_name(prefix = nil) + @unique_name ||= 0 + prefix ||= (@unique_prefix ||= self.class.name.gsub('::'.freeze, '_'.freeze).downcase) + "_#{prefix}#{@unique_name += 1}" + end + + # Check if expression is empty + # + # @param exp [Array] Temple expression + # @return true if expression is empty + def empty_exp?(exp) + case exp[0] + when :multi + exp[1..-1].all? {|e| empty_exp?(e) } + when :newline + true + else + false + end + end + + def indent_dynamic(text, indent_next, indent, pre_tags = nil) + text = text.to_s + safe = text.respond_to?(:html_safe?) && text.html_safe? + return text if pre_tags && text =~ pre_tags + + level = text.scan(/^\s*/).map(&:size).min + text = text.gsub(/(?!\A)^\s{#{level}}/, '') if level > 0 + + text = text.sub(/\A\s*\n?/, "\n".freeze) if indent_next + text = text.gsub("\n".freeze, indent) + + safe ? text.html_safe : text + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/version.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/version.rb new file mode 100644 index 0000000..7d26798 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/lib/temple/version.rb @@ -0,0 +1,3 @@ +module Temple + VERSION = '0.8.2' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/temple.gemspec b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/temple.gemspec new file mode 100644 index 0000000..8a84aee --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/temple.gemspec @@ -0,0 +1,29 @@ +# -*- encoding: utf-8 -*- +require File.dirname(__FILE__) + '/lib/temple/version' +require 'date' + +Gem::Specification.new do |s| + s.name = 'temple' + s.version = Temple::VERSION + s.date = Date.today.to_s + + s.authors = ['Magnus Holm', 'Daniel Mendler'] + s.email = ['judofyr@gmail.com', 'mail@daniel-mendler.de'] + s.homepage = 'https://github.com/judofyr/temple' + s.summary = 'Template compilation framework in Ruby' + + s.require_paths = %w(lib) + s.files = `git ls-files`.split("\n") + s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") + s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } + s.license = 'MIT' + + s.required_ruby_version = '>=1.9.2' + + # Tilt is only development dependency because most parts of Temple + # can be used without it. + s.add_development_dependency('tilt') + s.add_development_dependency('bacon') + s.add_development_dependency('rake') + s.add_development_dependency('erubis') +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_code_merger.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_code_merger.rb new file mode 100644 index 0000000..31f723c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_code_merger.rb @@ -0,0 +1,38 @@ +require 'helper' + +describe Temple::Filters::CodeMerger do + before do + @filter = Temple::Filters::CodeMerger.new + end + + it 'should merge serveral codes' do + @filter.call([:multi, + [:code, "a"], + [:code, "b"], + [:code, "c"] + ]).should.equal [:code, "a; b; c"] + end + + it 'should merge serveral codes around static' do + @filter.call([:multi, + [:code, "a"], + [:code, "b"], + [:static, "123"], + [:code, "a"], + [:code, "b"] + ]).should.equal [:multi, + [:code, "a; b"], + [:static, "123"], + [:code, "a; b"] + ] + end + + it 'should merge serveral codes with newlines' do + @filter.call([:multi, + [:code, "a"], + [:code, "b"], + [:newline], + [:code, "c"] + ]).should.equal [:code, "a; b\nc"] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_control_flow.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_control_flow.rb new file mode 100644 index 0000000..55f4ed9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_control_flow.rb @@ -0,0 +1,90 @@ +require 'helper' + +describe Temple::Filters::ControlFlow do + before do + @filter = Temple::Filters::ControlFlow.new + end + + it 'should process blocks' do + @filter.call([:block, 'loop do', + [:static, 'Hello'] + ]).should.equal [:multi, + [:code, 'loop do'], + [:static, 'Hello'], + [:code, 'end']] + end + + it 'should process if' do + @filter.call([:if, 'condition', + [:static, 'Hello'] + ]).should.equal [:multi, + [:code, 'if condition'], + [:static, 'Hello'], + [:code, 'end'] + ] + end + + it 'should process if with else' do + @filter.call([:if, 'condition', + [:static, 'True'], + [:static, 'False'] + ]).should.equal [:multi, + [:code, 'if condition'], + [:static, 'True'], + [:code, 'else'], + [:static, 'False'], + [:code, 'end'] + ] + end + + it 'should create elsif' do + @filter.call([:if, 'condition1', + [:static, '1'], + [:if, 'condition2', + [:static, '2'], + [:static, '3']] + ]).should.equal [:multi, + [:code, 'if condition1'], + [:static, '1'], + [:code, 'elsif condition2'], + [:static, '2'], + [:code, 'else'], + [:static, '3'], + [:code, 'end'] + ] + end + + it 'should process cond' do + @filter.call([:cond, + ['cond1', [:exp1]], + ['cond2', [:exp2]], + [:else, [:exp3]], + ]).should.equal [:multi, + [:code, 'case'], + [:code, 'when cond1'], + [:exp1], + [:code, 'when cond2'], + [:exp2], + [:code, 'else'], + [:exp3], + [:code, 'end'] + ] + end + + it 'should process case' do + @filter.call([:case, 'var', + ['Array', [:exp1]], + ['String', [:exp2]], + [:else, [:exp3]], + ]).should.equal [:multi, + [:code, 'case (var)'], + [:code, 'when Array'], + [:exp1], + [:code, 'when String'], + [:exp2], + [:code, 'else'], + [:exp3], + [:code, 'end'] + ] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_dynamic_inliner.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_dynamic_inliner.rb new file mode 100644 index 0000000..af2167e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_dynamic_inliner.rb @@ -0,0 +1,95 @@ +require 'helper' + +describe Temple::Filters::DynamicInliner do + before do + @filter = Temple::Filters::DynamicInliner.new + end + + it 'should compile several statics into dynamic' do + @filter.call([:multi, + [:static, "Hello "], + [:static, "World\n "], + [:static, "Have a nice day"] + ]).should.equal [:dynamic, '"Hello World\n Have a nice day"'] + end + + it 'should compile several dynamics into dynamic' do + @filter.call([:multi, + [:dynamic, "@hello"], + [:dynamic, "@world"], + [:dynamic, "@yeah"] + ]).should.equal [:dynamic, '"#{@hello}#{@world}#{@yeah}"'] + end + + it 'should compile static and dynamic into dynamic' do + @filter.call([:multi, + [:static, "Hello"], + [:dynamic, "@world"], + [:dynamic, "@yeah"], + [:static, "Nice"] + ]).should.equal [:dynamic, '"Hello#{@world}#{@yeah}Nice"'] + end + + it 'should merge statics and dynamics around a code' do + exp = @filter.call([:multi, + [:static, "Hello "], + [:dynamic, "@world"], + [:code, "Oh yeah"], + [:dynamic, "@yeah"], + [:static, "Once more"] + ]).should.equal [:multi, + [:dynamic, '"Hello #{@world}"'], + [:code, "Oh yeah"], + [:dynamic, '"#{@yeah}Once more"'] + ] + end + + it 'should keep codes intact' do + @filter.call([:multi, [:code, 'foo']]).should.equal [:code, 'foo'] + end + + it 'should keep single statics intact' do + @filter.call([:multi, [:static, 'foo']]).should.equal [:static, 'foo'] + end + + it 'should keep single dynamic intact' do + @filter.call([:multi, [:dynamic, 'foo']]).should.equal [:dynamic, 'foo'] + end + + it 'should inline inside multi' do + @filter.call([:multi, + [:static, "Hello "], + [:dynamic, "@world"], + [:multi, + [:static, "Hello "], + [:dynamic, "@world"]], + [:static, "Hello "], + [:dynamic, "@world"] + ]).should.equal [:multi, + [:dynamic, '"Hello #{@world}"'], + [:dynamic, '"Hello #{@world}"'], + [:dynamic, '"Hello #{@world}"'] + ] + end + + it 'should merge across newlines' do + exp = @filter.call([:multi, + [:static, "Hello \n"], + [:newline], + [:dynamic, "@world"], + [:newline] + ]).should.equal [:dynamic, ['"Hello \n"', '"#{@world}"', '""'].join("\\\n")] + end + + it 'should compile static followed by newline' do + @filter.call([:multi, + [:static, "Hello \n"], + [:newline], + [:code, "world"] + ]).should.equal [:multi, + [:static, "Hello \n"], + [:newline], + [:code, "world"] + ] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_eraser.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_eraser.rb new file mode 100644 index 0000000..e655b44 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_eraser.rb @@ -0,0 +1,55 @@ +require 'helper' + +describe Temple::Filters::Eraser do + it 'should respect keep' do + eraser = Temple::Filters::Eraser.new(keep: [:a]) + eraser.call([:multi, + [:a], + [:b], + [:c] + ]).should.equal [:multi, + [:a], + [:multi], + [:multi] + ] + end + + it 'should respect erase' do + eraser = Temple::Filters::Eraser.new(erase: [:a]) + eraser.call([:multi, + [:a], + [:b], + [:c] + ]).should.equal [:multi, + [:multi], + [:b], + [:c] + ] + end + + it 'should choose erase over keep' do + eraser = Temple::Filters::Eraser.new(keep: [:a, :b], erase: [:a]) + eraser.call([:multi, + [:a], + [:b], + [:c] + ]).should.equal [:multi, + [:multi], + [:b], + [:multi] + ] + end + + it 'should erase nested types' do + eraser = Temple::Filters::Eraser.new(erase: [[:a, :b]]) + eraser.call([:multi, + [:a, :a], + [:a, :b], + [:b] + ]).should.equal [:multi, + [:a, :a], + [:multi], + [:b] + ] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_escapable.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_escapable.rb new file mode 100644 index 0000000..cdb422e --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_escapable.rb @@ -0,0 +1,49 @@ +require 'helper' + +describe Temple::Filters::Escapable do + before do + @filter = Temple::Filters::Escapable.new + end + + it 'should handle escape expressions' do + @filter.call([:escape, true, + [:multi, + [:static, "a < b"], + [:dynamic, "ruby_method"]] + ]).should.equal [:multi, + [:static, "a < b"], + [:dynamic, "::Temple::Utils.escape_html((ruby_method))"], + ] + end + + it 'should keep codes intact' do + exp = [:multi, [:code, 'foo']] + @filter.call(exp).should.equal exp + end + + it 'should keep statics intact' do + exp = [:multi, [:static, '<']] + @filter.call(exp).should.equal exp + end + + it 'should keep dynamic intact' do + exp = [:multi, [:dynamic, 'foo']] + @filter.call(exp).should.equal exp + end + + it 'should have use_html_safe option' do + with_html_safe do + filter = Temple::Filters::Escapable.new(use_html_safe: true) + filter.call([:escape, true, + [:static, Temple::HTML::SafeString.new("a < b")] + ]).should.equal [:static, "a < b"] + end + end + + it 'should support censoring' do + filter = Temple::Filters::Escapable.new(escape_code: '(%s).gsub("Temple sucks", "Temple rocks")') + filter.call([:escape, true, + [:static, "~~ Temple sucks ~~"] + ]).should.equal [:static, "~~ Temple rocks ~~"] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_multi_flattener.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_multi_flattener.rb new file mode 100644 index 0000000..af40f86 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_multi_flattener.rb @@ -0,0 +1,33 @@ +require 'helper' + +describe Temple::Filters::MultiFlattener do + before do + @filter = Temple::Filters::MultiFlattener.new + end + + it 'should flatten nested multi expressions' do + @filter.call([:multi, + [:static, "a"], + [:multi, + [:dynamic, "aa"], + [:multi, + [:static, "aaa"], + [:static, "aab"], + ], + [:dynamic, "ab"], + ], + [:static, "b"], + ]).should.equal [:multi, + [:static, "a"], + [:dynamic, "aa"], + [:static, "aaa"], + [:static, "aab"], + [:dynamic, "ab"], + [:static, "b"], + ] + end + + it 'should return first element' do + @filter.call([:multi, [:code, 'foo']]).should.equal [:code, 'foo'] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_static_analyzer.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_static_analyzer.rb new file mode 100644 index 0000000..820fdb1 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_static_analyzer.rb @@ -0,0 +1,37 @@ +require 'helper' + +describe Temple::Filters::StaticAnalyzer do + before do + @filter = Temple::Filters::StaticAnalyzer.new + @generator = Temple::Generator.new + end + + if Temple::StaticAnalyzer.available? + it 'should convert :dynamic to :static if code is static' do + @filter.call([:dynamic, '"#{"hello"}#{100}"'] + ).should.equal [:static, 'hello100'] + end + + it 'should not convert :dynamic if code is dynamic' do + exp = [:dynamic, '"#{hello}#{100}"'] + @filter.call(exp).should.equal(exp) + end + + it 'should not change number of newlines in generated code' do + exp = [:dynamic, "[100,\n200,\n]"] + @filter.call(exp).should.equal([:multi, [:static, '[100, 200]'], [:newline], [:newline]]) + + @generator.call(@filter.call(exp)).count("\n"). + should.equal(@generator.call(exp).count("\n")) + end + else + it 'should do nothing' do + [ + [:dynamic, '"#{"hello"}#{100}"'], + [:dynamic, '"#{hello}#{100}"'], + ].each do |exp| + @filter.call(exp).should.equal(exp) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_static_merger.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_static_merger.rb new file mode 100644 index 0000000..e2ff11c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_static_merger.rb @@ -0,0 +1,41 @@ +require 'helper' + +describe Temple::Filters::StaticMerger do + before do + @filter = Temple::Filters::StaticMerger.new + end + + it 'should merge serveral statics' do + @filter.call([:multi, + [:static, "Hello "], + [:static, "World, "], + [:static, "Good night"] + ]).should.equal [:static, "Hello World, Good night"] + end + + it 'should merge serveral statics around code' do + @filter.call([:multi, + [:static, "Hello "], + [:static, "World!"], + [:code, "123"], + [:static, "Good night, "], + [:static, "everybody"] + ]).should.equal [:multi, + [:static, "Hello World!"], + [:code, "123"], + [:static, "Good night, everybody"] + ] + end + + it 'should merge serveral statics across newlines' do + @filter.call([:multi, + [:static, "Hello "], + [:static, "World, "], + [:newline], + [:static, "Good night"] + ]).should.equal [:multi, + [:static, "Hello World, Good night"], + [:newline] + ] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_string_splitter.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_string_splitter.rb new file mode 100644 index 0000000..bbf3194 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/filters/test_string_splitter.rb @@ -0,0 +1,25 @@ +require 'helper' +begin + require 'ripper' +rescue LoadError +end + +if defined?(Ripper) && RUBY_VERSION >= "2.0.0" + describe Temple::Filters::StringSplitter do + before do + @filter = Temple::Filters::StringSplitter.new + end + + it 'should split :dynamic with string literal' do + @filter.call([:dynamic, '"static#{dynamic}"'] + ).should.equal [:multi, [:static, 'static'], [:dynamic, 'dynamic']] + end + + describe '.compile' do + it 'should raise CompileError for non-string literals' do + lambda { Temple::Filters::StringSplitter.compile('1') }. + should.raise(Temple::FilterError) + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/helper.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/helper.rb new file mode 100644 index 0000000..608c54d --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/helper.rb @@ -0,0 +1,30 @@ +require 'bacon' +require 'temple' + +module TestHelper + def with_html_safe + require 'temple/html/safe' + String.send(:define_method, :html_safe?) { false } + String.send(:define_method, :html_safe) { Temple::HTML::SafeString.new(self) } + yield + ensure + String.send(:undef_method, :html_safe?) if String.method_defined?(:html_safe?) + String.send(:undef_method, :html_safe) if String.method_defined?(:html_safe) + end + + def grammar_validate(grammar, exp, message) + lambda { grammar.validate!(exp) }.should.raise(Temple::InvalidExpression).message.should.equal message + end + + def erb(src, options = {}) + Temple::ERB::Template.new(options) { src }.render + end + + def erubis(src, options = {}) + Tilt::ErubisTemplate.new(options) { src }.render + end +end + +class Bacon::Context + include TestHelper +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_attribute_merger.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_attribute_merger.rb new file mode 100644 index 0000000..b640ff3 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_attribute_merger.rb @@ -0,0 +1,76 @@ +require 'helper' + +describe Temple::HTML::AttributeMerger do + before do + @merger = Temple::HTML::AttributeMerger.new + end + + it 'should pass static attributes through' do + @merger.call([:html, :tag, + 'div', + [:html, :attrs, [:html, :attr, 'class', [:static, 'b']]], + [:content] + ]).should.equal [:html, :tag, "div", + [:html, :attrs, + [:html, :attr, "class", [:static, "b"]]], + [:content]] + end + + it 'should preserve the order of html attributes' do + @merger.call([:html, :tag, + 'meta', + [:html, :attrs, [:html, :attr, 'c', [:static, '1']], + [:html, :attr, 'd', [:static, '2']], + [:html, :attr, 'a', [:static, '3']], + [:html, :attr, 'b', [:static, '4']]] + ]).should.equal [:html, :tag, 'meta', + [:html, :attrs, + [:html, :attr, 'c', [:static, '1']], + [:html, :attr, 'd', [:static, '2']], + [:html, :attr, 'a', [:static, '3']], + [:html, :attr, 'b', [:static, '4']]]] + + # Use case: + @merger.call([:html, :tag, + 'meta', + [:html, :attrs, [:html, :attr, 'http-equiv', [:static, 'Content-Type']], + [:html, :attr, 'content', [:static, '']]] + ]).should.equal [:html, :tag, 'meta', + [:html, :attrs, + [:html, :attr, 'http-equiv', [:static, 'Content-Type']], + [:html, :attr, 'content', [:static, '']]]] + end + + it 'should merge ids' do + @merger.call([:html, :tag, + 'div', + [:html, :attrs, [:html, :attr, 'id', [:dynamic, 'a']], [:html, :attr, 'id', [:dynamic, 'b']]], + [:content] + ]).should.equal [:html, :tag, "div", + [:html, :attrs, + [:html, :attr, "id", + [:multi, + [:code, "_temple_html_attributemerger1 = []"], + [:capture, "_temple_html_attributemerger1[0]", [:dynamic, "a"]], + [:capture, "_temple_html_attributemerger1[1]", [:dynamic, "b"]], + [:dynamic, "_temple_html_attributemerger1.reject(&:empty?).join(\"_\")"]]]], + [:content]] + end + + it 'should merge classes' do + @merger.call([:html, :tag, + 'div', + [:html, :attrs, [:html, :attr, 'class', [:static, 'a']], [:html, :attr, 'class', [:dynamic, 'b']]], + [:content] + ]).should.equal [:html, :tag, "div", + [:html, :attrs, + [:html, :attr, "class", + [:multi, + [:code, "_temple_html_attributemerger1 = []"], + [:capture, "_temple_html_attributemerger1[0]", [:static, "a"]], + [:capture, "_temple_html_attributemerger1[1]", [:dynamic, "b"]], + [:dynamic, "_temple_html_attributemerger1.reject(&:empty?).join(\" \")"]]]], + [:content]] + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_attribute_remover.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_attribute_remover.rb new file mode 100644 index 0000000..9ad0ffa --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_attribute_remover.rb @@ -0,0 +1,43 @@ +require 'helper' + +describe Temple::HTML::AttributeRemover do + before do + @remover = Temple::HTML::AttributeRemover.new + end + + it 'should pass static attributes through' do + @remover.call([:html, :tag, + 'div', + [:html, :attrs, [:html, :attr, 'class', [:static, 'b']]], + [:content] + ]).should.equal [:html, :tag, "div", + [:multi, + [:html, :attr, "class", [:static, "b"]]], + [:content]] + end + + it 'should check for empty dynamic attribute if it is included in :remove_empty_attrs' do + @remover.call([:html, :tag, + 'div', + [:html, :attrs, [:html, :attr, 'class', [:dynamic, 'b']]], + [:content] + ]).should.equal [:html, :tag, "div", + [:multi, + [:multi, + [:capture, "_temple_html_attributeremover1", [:dynamic, "b"]], + [:if, "!_temple_html_attributeremover1.empty?", + [:html, :attr, "class", [:dynamic, "_temple_html_attributeremover1"]]]]], + [:content]] + end + + it 'should not check for empty dynamic attribute if it is not included in :remove_empty_attrs' do + @remover.call([:html, :tag, + 'div', + [:html, :attrs, [:html, :attr, 'name', [:dynamic, 'b']]], + [:content] + ]).should.equal [:html, :tag, "div", + [:multi, + [:html, :attr, "name", [:dynamic, "b"]]], + [:content]] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_attribute_sorter.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_attribute_sorter.rb new file mode 100644 index 0000000..85644bf --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_attribute_sorter.rb @@ -0,0 +1,48 @@ +require 'helper' + +describe Temple::HTML::AttributeSorter do + before do + @ordered = Temple::HTML::AttributeSorter.new + @unordered = Temple::HTML::AttributeSorter.new sort_attrs: false + end + + it 'should sort html attributes by name by default, when :sort_attrs is true' do + @ordered.call([:html, :tag, + 'meta', + [:html, :attrs, [:html, :attr, 'c', [:static, '1']], + [:html, :attr, 'd', [:static, '2']], + [:html, :attr, 'a', [:static, '3']], + [:html, :attr, 'b', [:static, '4']]] + ]).should.equal [:html, :tag, 'meta', + [:html, :attrs, + [:html, :attr, 'a', [:static, '3']], + [:html, :attr, 'b', [:static, '4']], + [:html, :attr, 'c', [:static, '1']], + [:html, :attr, 'd', [:static, '2']]]] + end + + it 'should preserve the order of html attributes when :sort_attrs is false' do + @unordered.call([:html, :tag, + 'meta', + [:html, :attrs, [:html, :attr, 'c', [:static, '1']], + [:html, :attr, 'd', [:static, '2']], + [:html, :attr, 'a', [:static, '3']], + [:html, :attr, 'b', [:static, '4']]] + ]).should.equal [:html, :tag, 'meta', + [:html, :attrs, + [:html, :attr, 'c', [:static, '1']], + [:html, :attr, 'd', [:static, '2']], + [:html, :attr, 'a', [:static, '3']], + [:html, :attr, 'b', [:static, '4']]]] + + # Use case: + @unordered.call([:html, :tag, + 'meta', + [:html, :attrs, [:html, :attr, 'http-equiv', [:static, 'Content-Type']], + [:html, :attr, 'content', [:static, '']]] + ]).should.equal [:html, :tag, 'meta', + [:html, :attrs, + [:html, :attr, 'http-equiv', [:static, 'Content-Type']], + [:html, :attr, 'content', [:static, '']]]] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_fast.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_fast.rb new file mode 100644 index 0000000..803857b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_fast.rb @@ -0,0 +1,97 @@ +require 'helper' + +describe Temple::HTML::Fast do + before do + @html = Temple::HTML::Fast.new + end + + it 'should compile html doctype' do + @html.call([:multi, [:html, :doctype, '5']]).should.equal [:multi, [:static, '']] + @html.call([:multi, [:html, :doctype, 'html']]).should.equal [:multi, [:static, '']] + @html.call([:multi, [:html, :doctype, '1.1']]).should.equal [:multi, + [:static, '']] + end + + it 'should compile xml encoding' do + @html.call([:html, :doctype, 'xml latin1']).should.equal [:static, ""] + end + + it 'should compile html comment' do + @html.call([:html, :comment, [:static, 'test']]).should.equal [:multi, [:static, ""]] + end + + it 'should compile js wrapped in comments' do + Temple::HTML::Fast.new(js_wrapper: nil).call([:html, :js, [:static, 'test']]).should.equal [:static, "test"] + Temple::HTML::Fast.new(js_wrapper: :comment).call([:html, :js, [:static, 'test']]).should.equal [:multi, [:static, ""]] + Temple::HTML::Fast.new(js_wrapper: :cdata).call([:html, :js, [:static, 'test']]).should.equal [:multi, [:static, "\n//\n"]] + Temple::HTML::Fast.new(js_wrapper: :both).call([:html, :js, [:static, 'test']]).should.equal [:multi, [:static, ""]] + end + + it 'should guess default js comment' do + Temple::HTML::Fast.new(js_wrapper: :guess, format: :xhtml).call([:html, :js, [:static, 'test']]).should.equal [:multi, [:static, "\n//\n"]] + Temple::HTML::Fast.new(js_wrapper: :guess, format: :html).call([:html, :js, [:static, 'test']]).should.equal [:multi, [:static, ""]] + end + + it 'should compile autoclosed html tag' do + @html.call([:html, :tag, + 'img', [:attrs], + [:multi, [:newline]] + ]).should.equal [:multi, + [:static, ""], + [:multi, [:newline]]] + end + + it 'should compile explicitly closed html tag' do + @html.call([:html, :tag, + 'closed', [:attrs] + ]).should.equal [:multi, + [:static, ""]] + end + + it 'should compile html with content' do + @html.call([:html, :tag, + 'div', [:attrs], [:content] + ]).should.equal [:multi, + [:static, ""], + [:content], + [:static, "
    "]] + end + + it 'should compile html with attrs' do + @html.call([:html, :tag, + 'div', + [:html, :attrs, + [:html, :attr, 'id', [:static, 'test']], + [:html, :attr, 'class', [:dynamic, 'block']]], + [:content] + ]).should.equal [:multi, + [:static, ""], + [:content], + [:static, "
    "]] + end + + it 'should keep codes intact' do + exp = [:multi, [:code, 'foo']] + @html.call(exp).should.equal exp + end + + it 'should keep statics intact' do + exp = [:multi, [:static, '<']] + @html.call(exp).should.equal exp + end + + it 'should keep dynamic intact' do + exp = [:multi, [:dynamic, 'foo']] + @html.call(exp).should.equal exp + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_pretty.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_pretty.rb new file mode 100644 index 0000000..dbe10f8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/html/test_pretty.rb @@ -0,0 +1,55 @@ +require 'helper' + +describe Temple::HTML::Pretty do + before do + @html = Temple::HTML::Pretty.new + end + + it 'should indent nested tags' do + @html.call([:html, :tag, 'div', [:multi], + [:html, :tag, 'p', [:multi], [:multi, [:static, 'text'], [:dynamic, 'code']]] + ]).should.equal [:multi, + [:code, "_temple_html_pretty1 = /"], + [:multi, + [:static, "\n "], + [:multi, + [:static, "\n text"], + [:dynamic, "::Temple::Utils.indent_dynamic((code), false, \"\\n \", _temple_html_pretty1)"]], + [:static, "\n

    "]], + [:static, "\n
    "]]] + end + + it 'should not indent preformatted tags' do + @html.call([:html, :tag, 'pre', [:multi], + [:html, :tag, 'p', [:multi], [:static, 'text']] + ]).should.equal [:multi, + [:code, "_temple_html_pretty1 = /"], + [:multi, + [:static, ""], + [:static, "text"], + [:static, "

    "]], + [:static, ""]]] + end + + it 'should not escape html_safe strings' do + with_html_safe do + @html.call( + [:dynamic, '"text<".html_safe'] + ).should.equal [:multi, + [:code, "_temple_html_pretty1 = / +* <%= n %> +<% end %> +} + + erb(src).should.equal erubis(src) + end + + it 'should recognize comments' do + src = %q{ +hello + <%# comment -- ignored -- useful in testing %> +world} + + erb(src).should.equal erubis(src) + end + + it 'should recognize <%% and %%>' do + src = %q{ +<%% +<% if true %> + %%> +<% end %> +} + + erb(src).should.equal "\n<%\n %>\n" + end + + it 'should escape automatically' do + src = '<%= "<" %>' + ans = '<' + erb(src).should.equal ans + end + + it 'should support == to disable automatic escape' do + src = '<%== "<" %>' + ans = '<' + erb(src).should.equal ans + end + + it 'should support trim mode' do + src = %q{ +%% hi += hello +<% 3.times do |n| %> +* <%= n %> +<% end %> +} + + erb(src, trim: true).should.equal erubis(src, trim: true) + erb(src, trim: false).should.equal erubis(src, trim: false) + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_filter.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_filter.rb new file mode 100644 index 0000000..b47e070 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_filter.rb @@ -0,0 +1,29 @@ +require 'helper' + +class SimpleFilter < Temple::Filter + define_options :key + + def on_test(arg) + [:on_test, arg] + end +end + +describe Temple::Filter do + it 'should support options' do + Temple::Filter.should.respond_to :default_options + Temple::Filter.should.respond_to :set_default_options + Temple::Filter.should.respond_to :define_options + Temple::Filter.new.options.should.be.instance_of Temple::ImmutableMap + SimpleFilter.new(key: 3).options[:key].should.equal 3 + end + + it 'should implement call' do + Temple::Filter.new.call([:exp]).should.equal [:exp] + end + + it 'should process expressions' do + filter = SimpleFilter.new + filter.call([:unhandled]).should.equal [:unhandled] + filter.call([:test, 42]).should.equal [:on_test, 42] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_generator.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_generator.rb new file mode 100644 index 0000000..fd7f78f --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_generator.rb @@ -0,0 +1,158 @@ +require 'helper' + +class SimpleGenerator < Temple::Generator + def preamble + "#{buffer} = BUFFER" + end + + def postamble + buffer + end + + def on_static(s) + concat "S:#{s}" + end + + def on_dynamic(s) + concat "D:#{s}" + end + + def on_code(s) + "C:#{s}" + end +end + +describe Temple::Generator do + it 'should compile simple expressions' do + gen = SimpleGenerator.new + + gen.call([:static, 'test']).should.equal '_buf = BUFFER; _buf << (S:test); _buf' + gen.call([:dynamic, 'test']).should.equal '_buf = BUFFER; _buf << (D:test); _buf' + gen.call([:code, 'test']).should.equal '_buf = BUFFER; C:test; _buf' + end + + it 'should compile multi expression' do + gen = SimpleGenerator.new(buffer: "VAR") + gen.call([:multi, + [:static, "static"], + [:dynamic, "dynamic"], + [:code, "code"] + ]).should.equal 'VAR = BUFFER; VAR << (S:static); VAR << (D:dynamic); C:code; VAR' + end + + it 'should compile capture' do + gen = SimpleGenerator.new(buffer: "VAR", capture_generator: SimpleGenerator) + gen.call([:capture, "foo", + [:static, "test"] + ]).should.equal 'VAR = BUFFER; foo = BUFFER; foo << (S:test); foo; VAR' + end + + it 'should compile capture with multi' do + gen = SimpleGenerator.new(buffer: "VAR", capture_generator: SimpleGenerator) + gen.call([:multi, + [:static, "before"], + + [:capture, "foo", [:multi, + [:static, "static"], + [:dynamic, "dynamic"], + [:code, "code"]]], + + [:static, "after"] + ]).should.equal 'VAR = BUFFER; VAR << (S:before); foo = BUFFER; foo << (S:static); ' + + 'foo << (D:dynamic); C:code; foo; VAR << (S:after); VAR' + end + + it 'should compile newlines' do + gen = SimpleGenerator.new(buffer: "VAR") + gen.call([:multi, + [:static, "static"], + [:newline], + [:dynamic, "dynamic"], + [:newline], + [:code, "code"] + ]).should.equal "VAR = BUFFER; VAR << (S:static); \n; " + + "VAR << (D:dynamic); \n; C:code; VAR" + end +end + +describe Temple::Generators::Array do + it 'should compile simple expressions' do + gen = Temple::Generators::Array.new(freeze_static: false) + gen.call([:static, 'test']).should.equal '_buf = []; _buf << ("test"); _buf' + gen.call([:dynamic, 'test']).should.equal '_buf = []; _buf << (test); _buf' + gen.call([:code, 'test']).should.equal '_buf = []; test; _buf' + + gen.call([:multi, [:static, 'a'], [:static, 'b']]).should.equal '_buf = []; _buf << ("a"); _buf << ("b"); _buf' + gen.call([:multi, [:static, 'a'], [:dynamic, 'b']]).should.equal '_buf = []; _buf << ("a"); _buf << (b); _buf' + end + + it 'should freeze static' do + gen = Temple::Generators::Array.new(freeze_static: true) + gen.call([:static, 'test']).should.equal '_buf = []; _buf << ("test".freeze); _buf' + end +end + +describe Temple::Generators::ArrayBuffer do + it 'should compile simple expressions' do + gen = Temple::Generators::ArrayBuffer.new(freeze_static: false) + gen.call([:static, 'test']).should.equal '_buf = "test"' + gen.call([:dynamic, 'test']).should.equal '_buf = (test).to_s' + gen.call([:code, 'test']).should.equal '_buf = []; test; _buf = _buf.join("")' + + gen.call([:multi, [:static, 'a'], [:static, 'b']]).should.equal '_buf = []; _buf << ("a"); _buf << ("b"); _buf = _buf.join("")' + gen.call([:multi, [:static, 'a'], [:dynamic, 'b']]).should.equal '_buf = []; _buf << ("a"); _buf << (b); _buf = _buf.join("")' + end + + it 'should freeze static' do + gen = Temple::Generators::ArrayBuffer.new(freeze_static: true) + gen.call([:static, 'test']).should.equal '_buf = "test"' + gen.call([:multi, [:dynamic, '1'], [:static, 'test']]).should.equal '_buf = []; _buf << (1); _buf << ("test".freeze); _buf = _buf.join("".freeze)' + end +end + +describe Temple::Generators::StringBuffer do + it 'should compile simple expressions' do + gen = Temple::Generators::StringBuffer.new(freeze_static: false) + gen.call([:static, 'test']).should.equal '_buf = "test"' + gen.call([:dynamic, 'test']).should.equal '_buf = (test).to_s' + gen.call([:code, 'test']).should.equal '_buf = \'\'; test; _buf' + + gen.call([:multi, [:static, 'a'], [:static, 'b']]).should.equal '_buf = \'\'; _buf << ("a"); _buf << ("b"); _buf' + gen.call([:multi, [:static, 'a'], [:dynamic, 'b']]).should.equal '_buf = \'\'; _buf << ("a"); _buf << ((b).to_s); _buf' + end + + it 'should freeze static' do + gen = Temple::Generators::StringBuffer.new(freeze_static: true) + gen.call([:static, 'test']).should.equal '_buf = "test"' + gen.call([:multi, [:dynamic, '1'], [:static, 'test']]).should.equal '_buf = \'\'; _buf << ((1).to_s); _buf << ("test".freeze); _buf' + end +end + +describe Temple::Generators::ERB do + it 'should compile simple expressions' do + gen = Temple::Generators::ERB.new + gen.call([:static, 'test']).should.equal 'test' + gen.call([:dynamic, 'test']).should.equal '<%= test %>' + gen.call([:code, 'test']).should.equal '<% test %>' + + gen.call([:multi, [:static, 'a'], [:static, 'b']]).should.equal 'ab' + gen.call([:multi, [:static, 'a'], [:dynamic, 'b']]).should.equal 'a<%= b %>' + end +end + +describe Temple::Generators::RailsOutputBuffer do + it 'should compile simple expressions' do + gen = Temple::Generators::RailsOutputBuffer.new(freeze_static: false) + gen.call([:static, 'test']).should.equal '@output_buffer = ActiveSupport::SafeBuffer.new; ' + + '@output_buffer.safe_concat(("test")); @output_buffer' + gen.call([:dynamic, 'test']).should.equal '@output_buffer = ActiveSupport::SafeBuffer.new; ' + + '@output_buffer.safe_concat(((test).to_s)); @output_buffer' + gen.call([:code, 'test']).should.equal '@output_buffer = ActiveSupport::SafeBuffer.new; ' + + 'test; @output_buffer' + end + + it 'should freeze static' do + gen = Temple::Generators::RailsOutputBuffer.new(freeze_static: true) + gen.call([:static, 'test']).should.equal '@output_buffer = ActiveSupport::SafeBuffer.new; @output_buffer.safe_concat(("test".freeze)); @output_buffer' + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_grammar.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_grammar.rb new file mode 100644 index 0000000..e9b7572 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_grammar.rb @@ -0,0 +1,47 @@ +require 'helper' + +describe Temple::Grammar do + it 'should match core expressions' do + Temple::Grammar.should.match [:multi] + Temple::Grammar.should.match [:multi, [:multi]] + Temple::Grammar.should.match [:static, 'Text'] + Temple::Grammar.should.match [:dynamic, 'Text'] + Temple::Grammar.should.match [:code, 'Text'] + Temple::Grammar.should.match [:capture, 'Text', [:multi]] + Temple::Grammar.should.match [:newline] + end + + it 'should not match invalid core expressions' do + Temple::Grammar.should.not.match [:multi, 'String'] + Temple::Grammar.should.not.match [:static] + Temple::Grammar.should.not.match [:dynamic, 1] + Temple::Grammar.should.not.match [:code, :sym] + Temple::Grammar.should.not.match [:capture, [:multi]] + Temple::Grammar.should.not.match [:newline, [:multi]] + end + + it 'should match control flow expressions' do + Temple::Grammar.should.match [:if, 'Condition', [:multi]] + Temple::Grammar.should.match [:if, 'Condition', [:multi], [:multi]] + Temple::Grammar.should.match [:block, 'Loop', [:multi]] + Temple::Grammar.should.match [:case, 'Arg', ['Cond1', [:multi]], ['Cond1', [:multi]], [:else, [:multi]]] + Temple::Grammar.should.not.match [:case, 'Arg', [:sym, [:multi]]] + Temple::Grammar.should.match [:cond, ['Cond1', [:multi]], ['Cond2', [:multi]], [:else, [:multi]]] + Temple::Grammar.should.not.match [:cond, [:sym, [:multi]]] + end + + it 'should match escape expression' do + Temple::Grammar.should.match [:escape, true, [:multi]] + Temple::Grammar.should.match [:escape, false, [:multi]] + end + + it 'should match html expressions' do + Temple::Grammar.should.match [:html, :doctype, 'Doctype'] + Temple::Grammar.should.match [:html, :comment, [:multi]] + Temple::Grammar.should.match [:html, :tag, 'Tag', [:multi]] + Temple::Grammar.should.match [:html, :tag, 'Tag', [:multi], [:multi]] + Temple::Grammar.should.match [:html, :tag, 'Tag', [:multi], [:static, 'Text']] + Temple::Grammar.should.match [:html, :tag, 'Tag', [:html, :attrs, [:html, :attr, 'id', + [:static, 'val']]], [:static, 'Text']] + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_map.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_map.rb new file mode 100644 index 0000000..c254ded --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_map.rb @@ -0,0 +1,39 @@ +require 'helper' + +describe Temple::ImmutableMap do + it 'has read accessor' do + hash = Temple::ImmutableMap.new({a: 1},{b: 2, a: 3}) + hash[:a].should.equal 1 + hash[:b].should.equal 2 + end + + it 'has include?' do + hash = Temple::ImmutableMap.new({a: 1},{b: 2, a: 3}) + hash.should.include :a + hash.should.include :b + hash.should.not.include :c + end + + it 'has values' do + Temple::ImmutableMap.new({a: 1},{b: 2, a: 3}).values.sort.should.equal [1,2] + end + + it 'has keys' do + Temple::ImmutableMap.new({a: 1},{b: 2, a: 3}).keys.should.equal [:a,:b] + end + + it 'has to_a' do + Temple::ImmutableMap.new({a: 1},{b: 2, a: 3}).to_a.should.equal [[:a, 1], [:b, 2]] + end +end + +describe Temple::MutableMap do + it 'has write accessor' do + parent = {a: 1} + hash = Temple::MutableMap.new(parent) + hash[:a].should.equal 1 + hash[:a] = 2 + hash[:a].should.equal 2 + parent[:a].should.equal 1 + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_static_analyzer.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_static_analyzer.rb new file mode 100644 index 0000000..1d2b4e8 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_static_analyzer.rb @@ -0,0 +1,39 @@ +require 'helper' + +describe Temple::StaticAnalyzer do + describe '.available?' do + it 'should return true if its dependency is available' do + Temple::StaticAnalyzer.available?.should.equal(defined?(Ripper) && Ripper.respond_to?(:lex)) + end + end + + if Temple::StaticAnalyzer.available? + describe '.static?' do + it 'should return true if given Ruby expression is static' do + ['true', 'false', '"hello world"', "[1, { 2 => 3 }]", "[\n1,\n]"].each do |exp| + Temple::StaticAnalyzer.static?(exp).should.equal(true) + end + end + + it 'should return false if given Ruby expression is dynamic' do + ['1 + 2', 'variable', 'method_call(a)', 'CONSTANT'].each do |exp| + Temple::StaticAnalyzer.static?(exp).should.equal(false) + end + end + end + + describe '.syntax_error?' do + it 'should return false if given Ruby expression is valid' do + ['Foo.bar.baz { |c| c.d! }', '{ foo: bar }'].each do |exp| + Temple::StaticAnalyzer.syntax_error?(exp).should.equal(false) + end + end + + it 'should return true if given Ruby expression is invalid' do + ['Foo.bar.baz { |c| c.d! ', ' foo: bar '].each do |exp| + Temple::StaticAnalyzer.syntax_error?(exp).should.equal(true) + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_utils.rb b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_utils.rb new file mode 100644 index 0000000..8265d65 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/temple-0.8.2/test/test_utils.rb @@ -0,0 +1,39 @@ +require 'helper' + +class UniqueTest + include Temple::Utils +end + +describe Temple::Utils do + it 'has empty_exp?' do + Temple::Utils.empty_exp?([:multi]).should.be.true + Temple::Utils.empty_exp?([:multi, [:multi]]).should.be.true + Temple::Utils.empty_exp?([:multi, [:multi, [:newline]], [:newline]]).should.be.true + Temple::Utils.empty_exp?([:multi]).should.be.true + Temple::Utils.empty_exp?([:multi, [:multi, [:static, 'text']]]).should.be.false + Temple::Utils.empty_exp?([:multi, [:newline], [:multi, [:dynamic, 'text']]]).should.be.false + end + + it 'has unique_name' do + u = UniqueTest.new + u.unique_name.should.equal '_uniquetest1' + u.unique_name.should.equal '_uniquetest2' + UniqueTest.new.unique_name.should.equal '_uniquetest1' + end + + it 'has escape_html' do + Temple::Utils.escape_html('<').should.equal '<' + end + + it 'should escape unsafe html strings' do + with_html_safe do + Temple::Utils.escape_html_safe('<').should.equal '<' + end + end + + it 'should not escape safe html strings' do + with_html_safe do + Temple::Utils.escape_html_safe('<'.html_safe).should.equal '<' + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/COPYING b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/COPYING new file mode 100644 index 0000000..7ef2588 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/COPYING @@ -0,0 +1,18 @@ +Copyright (c) 2010-2016 Ryan Tomayko + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/bin/tilt b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/bin/tilt new file mode 100755 index 0000000..97d6366 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/bin/tilt @@ -0,0 +1,122 @@ +#!/usr/bin/env ruby +require 'ostruct' +require 'optparse' +require 'tilt' + +usage = < +Process template and write output to stdout. With no or +when is '-', read template from stdin and use the --type option +to determine the template's type. + +Options + -l, --list List template engines + file patterns and exit + -t, --type= Use this template engine; required if no + -y, --layout= Use as a layout template + + -D= Define variable as + -d, --define-file= Load YAML from and use for variables + --vars= Evaluate to Hash and use for variables + + -h, --help Show this help message + +Convert markdown to HTML: + $ tilt foo.markdown > foo.html + +Process ERB template: + $ echo "Answer: <%= 2 + 2 %>" | tilt -t erb + Answer: 4 + +Define variables: + $ echo "Answer: <%= 2 + n %>" | tilt -t erb --vars="{:n=>40}" + Answer: 42 + $ echo "Answer: <%= 2 + n.to_i %>" | tilt -t erb -Dn=40 + Answer: 42 +USAGE + +script_name = File.basename($0) +pattern = nil +layout = nil +locals = {} + +ARGV.options do |o| + o.program_name = script_name + + # list all available template engines + o.on("-l", "--list") do + groups = {} + Tilt.lazy_map.each do |pattern,engines| + engines.each do |engine| + key = engine[0].split('::').last.sub(/Template$/, '') + (groups[key] ||= []) << pattern + end + end + groups.sort { |(k1,v1),(k2,v2)| k1 <=> k2 }.each do |engine,files| + printf "%-15s %s\n", engine, files.sort.join(', ') + end + exit + end + + # the template type / pattern + o.on("-t", "--type=PATTERN", String) do |val| + abort "unknown template type: #{val}" if Tilt[val].nil? + pattern = val + end + + # pass template output into the specified layout template + o.on("-y", "--layout=FILE", String) do |file| + paths = [file, "~/.tilt/#{file}", "/etc/tilt/#{file}"] + layout = paths. + map { |p| File.expand_path(p) }. + find { |p| File.exist?(p) } + abort "no such layout: #{file}" if layout.nil? + end + + # define a local variable + o.on("-D", "--define=PAIR", String) do |pair| + key, value = pair.split(/[=:]/, 2) + locals[key.to_sym] = value + end + + # define local variables from YAML or JSON + o.on("-d", "--define-file=FILE", String) do |file| + require 'yaml' + abort "no such define file: #{file}" unless File.exist? file + hash = File.open(file, 'r:bom|utf-8') { |f| YAML.load f, file } + abort "vars must be a Hash, not #{hash.inspect}" if !hash.is_a?(Hash) + hash.each { |key, value| locals[key.to_sym] = value } + end + + # define local variables using a Ruby hash + o.on("--vars=RUBY") do |ruby| + hash = eval(ruby) + abort "vars must be a Hash, not #{hash.inspect}" if !hash.is_a?(Hash) + hash.each { |key, value| locals[key.to_sym] = value } + end + + o.on_tail("-h", "--help") { puts usage; exit } + + o.parse! +end + +file = ARGV.first || '-' +pattern = file if pattern.nil? +abort "template type not given. see: #{$0} --help" if ['-', ''].include?(pattern) + +engine = Tilt[pattern] +abort "template engine not found for: #{pattern}" if engine.nil? + +template = + engine.new(file) { + if file == '-' + $stdin.read + else + File.read(file) + end + } +output = template.render(self, locals) + +# process layout +output = Tilt.new(layout).render(self, locals) { output } if layout + +$stdout.write(output) diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt.rb new file mode 100644 index 0000000..35d93f0 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt.rb @@ -0,0 +1,166 @@ +require 'tilt/mapping' +require 'tilt/template' + +# Namespace for Tilt. This module is not intended to be included anywhere. +module Tilt + # Current version. + VERSION = '2.0.10' + + @default_mapping = Mapping.new + + # @return [Tilt::Mapping] the main mapping object + def self.default_mapping + @default_mapping + end + + # @private + def self.lazy_map + default_mapping.lazy_map + end + + # @see Tilt::Mapping#register + def self.register(template_class, *extensions) + default_mapping.register(template_class, *extensions) + end + + # @see Tilt::Mapping#register_lazy + def self.register_lazy(class_name, file, *extensions) + default_mapping.register_lazy(class_name, file, *extensions) + end + + # @deprecated Use {register} instead. + def self.prefer(template_class, *extensions) + register(template_class, *extensions) + end + + # @see Tilt::Mapping#registered? + def self.registered?(ext) + default_mapping.registered?(ext) + end + + # @see Tilt::Mapping#new + def self.new(file, line=nil, options={}, &block) + default_mapping.new(file, line, options, &block) + end + + # @see Tilt::Mapping#[] + def self.[](file) + default_mapping[file] + end + + # @see Tilt::Mapping#template_for + def self.template_for(file) + default_mapping.template_for(file) + end + + # @see Tilt::Mapping#templates_for + def self.templates_for(file) + default_mapping.templates_for(file) + end + + # @return the template object that is currently rendering. + # + # @example + # tmpl = Tilt['index.erb'].new { '<%= Tilt.current_template %>' } + # tmpl.render == tmpl.to_s + # + # @note This is currently an experimental feature and might return nil + # in the future. + def self.current_template + Thread.current[:tilt_current_template] + end + + # Extremely simple template cache implementation. Calling applications + # create a Tilt::Cache instance and use #fetch with any set of hashable + # arguments (such as those to Tilt.new): + # + # cache = Tilt::Cache.new + # cache.fetch(path, line, options) { Tilt.new(path, line, options) } + # + # Subsequent invocations return the already loaded template object. + # + # @note + # Tilt::Cache is a thin wrapper around Hash. It has the following + # limitations: + # * Not thread-safe. + # * Size is unbounded. + # * Keys are not copied defensively, and should not be modified after + # being passed to #fetch. More specifically, the values returned by + # key#hash and key#eql? should not change. + # If this is too limiting for you, use a different cache implementation. + class Cache + def initialize + @cache = {} + end + + # Caches a value for key, or returns the previously cached value. + # If a value has been previously cached for key then it is + # returned. Otherwise, block is yielded to and its return value + # which may be nil, is cached under key and returned. + # @yield + # @yieldreturn the value to cache for key + def fetch(*key) + @cache.fetch(key) do + @cache[key] = yield + end + end + + # Clears the cache. + def clear + @cache = {} + end + end + + + # Template Implementations ================================================ + + # ERB + register_lazy :ERBTemplate, 'tilt/erb', 'erb', 'rhtml' + register_lazy :ErubisTemplate, 'tilt/erubis', 'erb', 'rhtml', 'erubis' + register_lazy :ErubiTemplate, 'tilt/erubi', 'erb', 'rhtml', 'erubi' + + # Markdown + register_lazy :BlueClothTemplate, 'tilt/bluecloth', 'markdown', 'mkd', 'md' + register_lazy :MarukuTemplate, 'tilt/maruku', 'markdown', 'mkd', 'md' + register_lazy :KramdownTemplate, 'tilt/kramdown', 'markdown', 'mkd', 'md' + register_lazy :RDiscountTemplate, 'tilt/rdiscount', 'markdown', 'mkd', 'md' + register_lazy :RedcarpetTemplate, 'tilt/redcarpet', 'markdown', 'mkd', 'md' + register_lazy :CommonMarkerTemplate, 'tilt/commonmarker', 'markdown', 'mkd', 'md' + register_lazy :PandocTemplate, 'tilt/pandoc', 'markdown', 'mkd', 'md' + + # Rest (sorted by name) + register_lazy :AsciidoctorTemplate, 'tilt/asciidoc', 'ad', 'adoc', 'asciidoc' + register_lazy :BabelTemplate, 'tilt/babel', 'es6', 'babel', 'jsx' + register_lazy :BuilderTemplate, 'tilt/builder', 'builder' + register_lazy :CSVTemplate, 'tilt/csv', 'rcsv' + register_lazy :CoffeeScriptTemplate, 'tilt/coffee', 'coffee' + register_lazy :CoffeeScriptLiterateTemplate, 'tilt/coffee', 'litcoffee' + register_lazy :CreoleTemplate, 'tilt/creole', 'wiki', 'creole' + register_lazy :EtanniTemplate, 'tilt/etanni', 'etn', 'etanni' + register_lazy :HamlTemplate, 'tilt/haml', 'haml' + register_lazy :LessTemplate, 'tilt/less', 'less' + register_lazy :LiquidTemplate, 'tilt/liquid', 'liquid' + register_lazy :LiveScriptTemplate, 'tilt/livescript','ls' + register_lazy :MarkabyTemplate, 'tilt/markaby', 'mab' + register_lazy :NokogiriTemplate, 'tilt/nokogiri', 'nokogiri' + register_lazy :PlainTemplate, 'tilt/plain', 'html' + register_lazy :PrawnTemplate, 'tilt/prawn', 'prawn' + register_lazy :RDocTemplate, 'tilt/rdoc', 'rdoc' + register_lazy :RadiusTemplate, 'tilt/radius', 'radius' + register_lazy :RedClothTemplate, 'tilt/redcloth', 'textile' + register_lazy :RstPandocTemplate, 'tilt/rst-pandoc', 'rst' + register_lazy :SassTemplate, 'tilt/sass', 'sass' + register_lazy :ScssTemplate, 'tilt/sass', 'scss' + register_lazy :SigilTemplate, 'tilt/sigil', 'sigil' + register_lazy :StringTemplate, 'tilt/string', 'str' + register_lazy :TypeScriptTemplate, 'tilt/typescript', 'ts', 'tsx' + register_lazy :WikiClothTemplate, 'tilt/wikicloth', 'wiki', 'mediawiki', 'mw' + register_lazy :YajlTemplate, 'tilt/yajl', 'yajl' + + # External template engines + register_lazy 'Slim::Template', 'slim', 'slim' + register_lazy 'Tilt::HandlebarsTemplate', 'tilt/handlebars', 'handlebars', 'hbs' + register_lazy 'Tilt::OrgTemplate', 'org-ruby', 'org' + register_lazy 'Opal::Processor', 'opal', 'opal', 'rb' + register_lazy 'Tilt::JbuilderTemplate', 'tilt/jbuilder', 'jbuilder' +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/asciidoc.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/asciidoc.rb new file mode 100644 index 0000000..fb1ccc4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/asciidoc.rb @@ -0,0 +1,27 @@ +require 'tilt/template' +require 'asciidoctor' + +# AsciiDoc see: http://asciidoc.org/ +module Tilt + # Asciidoctor implementation for AsciiDoc see: + # http://asciidoctor.github.com/ + # + # Asciidoctor is an open source, pure-Ruby processor for + # converting AsciiDoc documents or strings into HTML 5, + # DocBook 4.5 and other formats. + class AsciidoctorTemplate < Template + self.default_mime_type = 'text/html' + + def prepare + options[:header_footer] = false if options[:header_footer].nil? + end + + def evaluate(scope, locals, &block) + @output ||= Asciidoctor.render(data, options, &block) + end + + def allows_script? + false + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/babel.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/babel.rb new file mode 100644 index 0000000..a498ec9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/babel.rb @@ -0,0 +1,16 @@ +require 'tilt/template' +require 'babel/transpiler' + +module Tilt + class BabelTemplate < Template + self.default_mime_type = 'application/javascript' + + def prepare + options[:filename] ||= file + end + + def evaluate(scope, locals, &block) + @output ||= Babel::Transpiler.transform(data)["code"] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/bluecloth.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/bluecloth.rb new file mode 100644 index 0000000..7ed59c7 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/bluecloth.rb @@ -0,0 +1,24 @@ +require 'tilt/template' +require 'bluecloth' + +module Tilt + # BlueCloth Markdown implementation. See: + # http://deveiate.org/projects/BlueCloth/ + class BlueClothTemplate < Template + self.default_mime_type = 'text/html' + + def prepare + @engine = BlueCloth.new(data, options) + @output = nil + end + + def evaluate(scope, locals, &block) + @output ||= @engine.to_html + end + + def allows_script? + false + end + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/builder.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/builder.rb new file mode 100644 index 0000000..adde14b --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/builder.rb @@ -0,0 +1,37 @@ +require 'tilt/template' +require 'builder' + +module Tilt + # Builder template implementation. See: + # http://builder.rubyforge.org/ + class BuilderTemplate < Template + self.default_mime_type = 'text/xml' + + def prepare + options[:indent] ||= 2 + end + + def evaluate(scope, locals, &block) + xml = (locals[:xml] || ::Builder::XmlMarkup.new(options)) + + if data.respond_to?(:to_str) + if !locals[:xml] + locals = locals.merge(:xml => xml) + end + return super(scope, locals, &block) + end + + data.call(xml) + xml.target! + end + + def precompiled_postamble(locals) + "xml.target!" + end + + def precompiled_template(locals) + data.to_str + end + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/coffee.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/coffee.rb new file mode 100644 index 0000000..08feb50 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/coffee.rb @@ -0,0 +1,58 @@ +require 'tilt/template' +require 'coffee_script' + +module Tilt + # CoffeeScript template implementation. See: + # http://coffeescript.org/ + # + # CoffeeScript templates do not support object scopes, locals, or yield. + class CoffeeScriptTemplate < Template + self.default_mime_type = 'application/javascript' + + @@default_bare = false + + def self.default_bare + @@default_bare + end + + def self.default_bare=(value) + @@default_bare = value + end + + # DEPRECATED + def self.default_no_wrap + @@default_bare + end + + # DEPRECATED + def self.default_no_wrap=(value) + @@default_bare = value + end + + def self.literate? + false + end + + def prepare + if !options.key?(:bare) and !options.key?(:no_wrap) + options[:bare] = self.class.default_bare + end + options[:literate] ||= self.class.literate? + end + + def evaluate(scope, locals, &block) + @output ||= CoffeeScript.compile(data, options) + end + + def allows_script? + false + end + end + + class CoffeeScriptLiterateTemplate < CoffeeScriptTemplate + def self.literate? + true + end + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/commonmarker.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/commonmarker.rb new file mode 100644 index 0000000..dd331e4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/commonmarker.rb @@ -0,0 +1,78 @@ +require 'tilt/template' +require 'commonmarker' + +module Tilt + class CommonMarkerTemplate < Template + self.default_mime_type = 'text/html' + + OPTION_ALIAS = { + :smartypants => :SMART + } + PARSE_OPTIONS = [ + :SMART, + :smartypants, + ].freeze + RENDER_OPTIONS = [ + :GITHUB_PRE_LANG, + :HARDBREAKS, + :NOBREAKS, + :SAFE, + :SOURCEPOS, + ].freeze + EXTENSIONS = [ + :autolink, + :strikethrough, + :table, + :tagfilter, + ].freeze + + def extensions + EXTENSIONS.select do |extension| + options[extension] + end + end + + def parse_options + raw_options = PARSE_OPTIONS.select do |option| + options[option] + end + actual_options = raw_options.map do |option| + OPTION_ALIAS[option] || option + end + + if actual_options.any? + actual_options + else + :DEFAULT + end + end + + def render_options + raw_options = RENDER_OPTIONS.select do |option| + options[option] + end + actual_options = raw_options.map do |option| + OPTION_ALIAS[option] || option + end + if actual_options.any? + actual_options + else + :DEFAULT + end + end + + def prepare + @engine = nil + @output = nil + end + + def evaluate(scope, locals, &block) + doc = CommonMarker.render_doc(data, parse_options, extensions) + doc.to_html(render_options, extensions) + end + + def allows_script? + false + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/creole.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/creole.rb new file mode 100644 index 0000000..04cff16 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/creole.rb @@ -0,0 +1,25 @@ +require 'tilt/template' +require 'creole' + +module Tilt + # Creole implementation. See: + # http://www.wikicreole.org/ + class CreoleTemplate < Template + def prepare + opts = {} + [:allowed_schemes, :extensions, :no_escape].each do |k| + opts[k] = options[k] if options[k] + end + @engine = Creole::Parser.new(data, opts) + @output = nil + end + + def evaluate(scope, locals, &block) + @output ||= @engine.to_html + end + + def allows_script? + false + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/csv.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/csv.rb new file mode 100644 index 0000000..fd0e602 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/csv.rb @@ -0,0 +1,65 @@ +require 'tilt/template' + +if RUBY_VERSION >= '1.9.0' + require 'csv' +else + require 'fastercsv' +end + +module Tilt + + # CSV Template implementation. See: + # http://ruby-doc.org/stdlib/libdoc/csv/rdoc/CSV.html + # + # == Example + # + # # Example of csv template + # tpl = <<-EOS + # # header + # csv << ['NAME', 'ID'] + # + # # data rows + # @people.each do |person| + # csv << [person[:name], person[:id]] + # end + # EOS + # + # @people = [ + # {:name => "Joshua Peek", :id => 1}, + # {:name => "Ryan Tomayko", :id => 2}, + # {:name => "Simone Carletti", :id => 3} + # ] + # + # template = Tilt::CSVTemplate.new { tpl } + # template.render(self) + # + class CSVTemplate < Template + self.default_mime_type = 'text/csv' + + def self.engine + if RUBY_VERSION >= '1.9.0' && defined? ::CSV + ::CSV + elsif defined? ::FasterCSV + ::FasterCSV + end + end + + def prepare + @outvar = options.delete(:outvar) || '_csvout' + end + + def precompiled_template(locals) + <<-RUBY + #{@outvar} = #{self.class.engine}.generate(#{options}) do |csv| + #{data} + end + RUBY + end + + def precompiled(locals) + source, offset = super + [source, offset + 1] + end + + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/dummy.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/dummy.rb new file mode 100644 index 0000000..437a1d9 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/dummy.rb @@ -0,0 +1,3 @@ +# Used for detecting autoloading bug in JRuby +class Tilt::Dummy; end + diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/erb.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/erb.rb new file mode 100644 index 0000000..cbf4e0c --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/erb.rb @@ -0,0 +1,63 @@ +require 'tilt/template' +require 'erb' + +module Tilt + # ERB template implementation. See: + # http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html + class ERBTemplate < Template + @@default_output_variable = '_erbout' + + SUPPORTS_KVARGS = ::ERB.instance_method(:initialize).parameters.assoc(:key) rescue false + + def self.default_output_variable + @@default_output_variable + end + + def self.default_output_variable=(name) + warn "#{self}.default_output_variable= has been replaced with the :outvar-option" + @@default_output_variable = name + end + + def prepare + @outvar = options[:outvar] || self.class.default_output_variable + options[:trim] = '<>' if !(options[:trim] == false) && (options[:trim].nil? || options[:trim] == true) + @engine = if SUPPORTS_KVARGS + ::ERB.new(data, trim_mode: options[:trim], eoutvar: @outvar) + else + ::ERB.new(data, options[:safe], options[:trim], @outvar) + end + end + + def precompiled_template(locals) + source = @engine.src + source + end + + def precompiled_preamble(locals) + <<-RUBY + begin + __original_outvar = #{@outvar} if defined?(#{@outvar}) + #{super} + RUBY + end + + def precompiled_postamble(locals) + <<-RUBY + #{super} + ensure + #{@outvar} = __original_outvar + end + RUBY + end + + # ERB generates a line to specify the character coding of the generated + # source in 1.9. Account for this in the line offset. + if RUBY_VERSION >= '1.9.0' + def precompiled(locals) + source, offset = super + [source, offset + 1] + end + end + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/erubi.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/erubi.rb new file mode 100644 index 0000000..ea146e4 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/erubi.rb @@ -0,0 +1,32 @@ +require 'tilt/template' +require 'erubi' + +module Tilt + # Erubi (a simplified version of Erubis) template implementation. + # See https://github.com/jeremyevans/erubi + # + # ErubiTemplate supports the following additional options, in addition + # to the options supported by the Erubi engine: + # + # :engine_class :: allows you to specify a custom engine class to use + # instead of the default (which is ::Erubi::Engine). + class ErubiTemplate < Template + def prepare + @options.merge!(:preamble => false, :postamble => false, :ensure=>true) + + engine_class = @options[:engine_class] || Erubi::Engine + + @engine = engine_class.new(data, @options) + @outvar = @engine.bufvar + + # Remove dup after tilt supports frozen source. + @src = @engine.src.dup + + @engine + end + + def precompiled_template(locals) + @src + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/erubis.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/erubis.rb new file mode 100644 index 0000000..0f18078 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/erubis.rb @@ -0,0 +1,43 @@ +require 'tilt/erb' +require 'erubis' + +module Tilt + # Erubis template implementation. See: + # http://www.kuwata-lab.com/erubis/ + # + # ErubisTemplate supports the following additional options, which are not + # passed down to the Erubis engine: + # + # :engine_class allows you to specify a custom engine class to use + # instead of the default (which is ::Erubis::Eruby). + # + # :escape_html when true, ::Erubis::EscapedEruby will be used as + # the engine class instead of the default. All content + # within <%= %> blocks will be automatically html escaped. + class ErubisTemplate < ERBTemplate + def prepare + @outvar = options.delete(:outvar) || self.class.default_output_variable + @options.merge!(:preamble => false, :postamble => false, :bufvar => @outvar) + engine_class = options.delete(:engine_class) + engine_class = ::Erubis::EscapedEruby if options.delete(:escape_html) + @engine = (engine_class || ::Erubis::Eruby).new(data, options) + end + + def precompiled_preamble(locals) + [super, "#{@outvar} = _buf = String.new"].join("\n") + end + + def precompiled_postamble(locals) + [@outvar, super].join("\n") + end + + # Erubis doesn't have ERB's line-off-by-one under 1.9 problem. + # Override and adjust back. + if RUBY_VERSION >= '1.9.0' + def precompiled(locals) + source, offset = super + [source, offset - 1] + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/etanni.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/etanni.rb new file mode 100644 index 0000000..e598ced --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/etanni.rb @@ -0,0 +1,27 @@ +require 'tilt/template' + +module Tilt + class EtanniTemplate < Template + def prepare + separator = data.hash.abs + chomp = "<<#{separator}.chomp!" + start = "\n_out_ << #{chomp}\n" + stop = "\n#{separator}\n" + replacement = "#{stop}\\1#{start}" + + temp = data.strip + temp.gsub!(/<\?r\s+(.*?)\s+\?>/m, replacement) + + @code = "_out_ = [<<#{separator}.chomp!]\n#{temp}#{stop}_out_.join" + end + + def precompiled_template(locals) + @code + end + + def precompiled(locals) + source, offset = super + [source, offset + 1] + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/haml.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/haml.rb new file mode 100644 index 0000000..fc7f205 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/haml.rb @@ -0,0 +1,86 @@ +require 'tilt/template' +require 'haml' + +module Tilt + # Haml template implementation. See: + # http://haml.hamptoncatlin.com/ + class HamlTemplate < Template + self.default_mime_type = 'text/html' + + # `Gem::Version.correct?` may return false because of Haml::VERSION #=> "3.1.8 (Separated Sally)". After Haml 4, it's always correct. + if Gem::Version.correct?(Haml::VERSION) && Gem::Version.new(Haml::VERSION) >= Gem::Version.new('5.0.0.beta.2') + def prepare + options = {}.update(@options).update(filename: eval_file, line: line) + if options.include?(:outvar) + options[:buffer] = options.delete(:outvar) + options[:save_buffer] = true + end + @engine = ::Haml::TempleEngine.new(options) + @engine.compile(data) + end + + def evaluate(scope, locals, &block) + raise ArgumentError, 'invalid scope: must not be frozen' if scope.frozen? + super + end + + def precompiled_template(locals) + @engine.precompiled_with_ambles( + [], + after_preamble: <<-RUBY + __in_erb_template = true + _haml_locals = locals + RUBY + ) + end + else # Following definitions are for Haml <= 4 and deprecated. + def prepare + options = @options.merge(:filename => eval_file, :line => line) + @engine = ::Haml::Engine.new(data, options) + end + + def evaluate(scope, locals, &block) + raise ArgumentError, 'invalid scope: must not be frozen' if scope.frozen? + + if @engine.respond_to?(:precompiled_method_return_value, true) + super + else + @engine.render(scope, locals, &block) + end + end + + # Precompiled Haml source. Taken from the precompiled_with_ambles + # method in Haml::Precompiler: + # http://github.com/nex3/haml/blob/master/lib/haml/precompiler.rb#L111-126 + def precompiled_template(locals) + @engine.precompiled + end + + def precompiled_preamble(locals) + local_assigns = super + @engine.instance_eval do + <<-RUBY + begin + extend Haml::Helpers + _hamlout = @haml_buffer = Haml::Buffer.new(haml_buffer, #{options_for_buffer.inspect}) + _erbout = _hamlout.buffer + __in_erb_template = true + _haml_locals = locals + #{local_assigns} + RUBY + end + end + + def precompiled_postamble(locals) + @engine.instance_eval do + <<-RUBY + #{precompiled_method_return_value} + ensure + @haml_buffer = @haml_buffer.upper if haml_buffer + end + RUBY + end + end + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/kramdown.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/kramdown.rb new file mode 100644 index 0000000..c69a073 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/kramdown.rb @@ -0,0 +1,25 @@ +require 'tilt/template' +require 'kramdown' + +module Tilt + # Kramdown Markdown implementation. See: + # http://kramdown.rubyforge.org/ + class KramdownTemplate < Template + DUMB_QUOTES = [39, 39, 34, 34] + + def prepare + options[:smart_quotes] = DUMB_QUOTES unless options[:smartypants] + @engine = Kramdown::Document.new(data, options) + @output = nil + end + + def evaluate(scope, locals, &block) + @output ||= @engine.to_html + end + + def allows_script? + false + end + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/less.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/less.rb new file mode 100644 index 0000000..81318a6 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/less.rb @@ -0,0 +1,30 @@ +require 'tilt/template' +require 'less' + +module Tilt + # Lessscss template implementation. See: + # http://lesscss.org/ + # + # Less templates do not support object scopes, locals, or yield. + class LessTemplate < Template + self.default_mime_type = 'text/css' + + def prepare + if ::Less.const_defined? :Engine + @engine = ::Less::Engine.new(data) + else + parser = ::Less::Parser.new(options.merge :filename => eval_file, :line => line) + @engine = parser.parse(data) + end + end + + def evaluate(scope, locals, &block) + @output ||= @engine.to_css(options) + end + + def allows_script? + false + end + end +end + diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/liquid.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/liquid.rb new file mode 100644 index 0000000..f2b47b5 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/liquid.rb @@ -0,0 +1,44 @@ +require 'tilt/template' +require 'liquid' + +module Tilt + # Liquid template implementation. See: + # http://liquidmarkup.org/ + # + # Liquid is designed to be a *safe* template system and threfore + # does not provide direct access to execuatable scopes. In order to + # support a +scope+, the +scope+ must be able to represent itself + # as a hash by responding to #to_h. If the +scope+ does not respond + # to #to_h it will be ignored. + # + # LiquidTemplate does not support yield blocks. + # + # It's suggested that your program require 'liquid' at load + # time when using this template engine. + class LiquidTemplate < Template + def prepare + @engine = ::Liquid::Template.parse(data, liquid_options) + end + + def evaluate(scope, locals, &block) + locals = locals.inject({}){ |h,(k,v)| h[k.to_s] = v ; h } + if scope.respond_to?(:to_h) + scope = scope.to_h.inject({}){ |h,(k,v)| h[k.to_s] = v ; h } + locals = scope.merge(locals) + end + locals['yield'] = block.nil? ? '' : yield + locals['content'] = locals['yield'] + @engine.render(locals) + end + + def allows_script? + false + end + + private + + def liquid_options + { line_numbers: true }.merge options + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/livescript.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/livescript.rb new file mode 100644 index 0000000..6c3cabd --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/livescript.rb @@ -0,0 +1,23 @@ +require 'tilt/template' +require 'livescript' + +module Tilt + # LiveScript template implementation. See: + # http://livescript.net/ + # + # LiveScript templates do not support object scopes, locals, or yield. + class LiveScriptTemplate < Template + self.default_mime_type = 'application/javascript' + + def prepare + end + + def evaluate(scope, locals, &block) + @output ||= LiveScript.compile(data, options) + end + + def allows_script? + false + end + end +end diff --git a/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/mapping.rb b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/mapping.rb new file mode 100644 index 0000000..de78cd2 --- /dev/null +++ b/vendor/bundle/ruby/3.0.0/gems/tilt-2.0.10/lib/tilt/mapping.rb @@ -0,0 +1,293 @@ +require 'monitor' + +module Tilt + # Tilt::Mapping associates file extensions with template implementations. + # + # mapping = Tilt::Mapping.new + # mapping.register(Tilt::RDocTemplate, 'rdoc') + # mapping['index.rdoc'] # => Tilt::RDocTemplate + # mapping.new('index.rdoc').render + # + # You can use {#register} to register a template class by file + # extension, {#registered?} to see if a file extension is mapped, + # {#[]} to lookup template classes, and {#new} to instantiate template + # objects. + # + # Mapping also supports *lazy* template implementations. Note that regularly + # registered template implementations *always* have preference over lazily + # registered template implementations. You should use {#register} if you + # depend on a specific template implementation and {#register_lazy} if there + # are multiple alternatives. + # + # mapping = Tilt::Mapping.new + # mapping.register_lazy('RDiscount::Template', 'rdiscount/template', 'md') + # mapping['index.md'] + # # => RDiscount::Template + # + # {#register_lazy} takes a class name, a filename, and a list of file + # extensions. When you try to lookup a template name that matches the + # file extension, Tilt will automatically try to require the filename and + # constantize the class name. + # + # Unlike {#register}, there can be multiple template implementations + # registered lazily to the same file extension. Tilt will attempt to load the + # template implementations in order (registered *last* would be tried first), + # returning the first which doesn't raise LoadError. + # + # If all of the registered template implementations fails, Tilt will raise + # the exception of the first, since that was the most preferred one. + # + # mapping = Tilt::Mapping.new + # mapping.register_lazy('Bluecloth::Template', 'bluecloth/template', 'md') + # mapping.register_lazy('RDiscount::Template', 'rdiscount/template', 'md') + # mapping['index.md'] + # # => RDiscount::Template + # + # In the previous example we say that RDiscount has a *higher priority* than + # BlueCloth. Tilt will first try to `require "rdiscount/template"`, falling + # back to `require "bluecloth/template"`. If none of these are successful, + # the first error will be raised. + class Mapping + # @private + attr_reader :lazy_map, :template_map + + def initialize + @template_map = Hash.new + @lazy_map = Hash.new { |h, k| h[k] = [] } + end + + # @private + def initialize_copy(other) + @template_map = other.template_map.dup + @lazy_map = other.lazy_map.dup + end + + # Registers a lazy template implementation by file extension. You + # can have multiple lazy template implementations defined on the + # same file extension, in which case the template implementation + # defined *last* will be attempted loaded *first*. + # + # @param class_name [String] Class name of a template class. + # @param file [String] Filename where the template class is defined. + # @param extensions [Array] List of extensions. + # @return [void] + # + # @example + # mapping.register_lazy 'MyEngine::Template', 'my_engine/template', 'mt' + # + # defined?(MyEngine::Template) # => false + # mapping['index.mt'] # => MyEngine::Template + # defined?(MyEngine::Template) # => true + def register_lazy(class_name, file, *extensions) + # Internal API + if class_name.is_a?(Symbol) + Tilt.autoload class_name, file + class_name = "Tilt::#{class_name}" + end + + extensions.each do |ext| + @lazy_map[ext].unshift([class_name, file]) + end + end + + # Registers a template implementation by file extension. There can only be + # one template implementation per file extension, and this method will + # override any existing mapping. + # + # @param template_class + # @param extensions [Array] List of extensions. + # @return [void] + # + # @example + # mapping.register MyEngine::Template, 'mt' + # mapping['index.mt'] # => MyEngine::Template + def register(template_class, *extensions) + if template_class.respond_to?(:to_str) + # Support register(ext, template_class) too + extensions, template_class = [template_class], extensions[0] + end + + extensions.each do |ext| + @template_map[ext.to_s] = template_class + end + end + + # Checks if a file extension is registered (either eagerly or + # lazily) in this mapping. + # + # @param ext [String] File extension. + # + # @example + # mapping.registered?('erb') # => true + # mapping.registered?('nope') # => false + def registered?(ext) + @template_map.has_key?(ext.downcase) or lazy?(ext) + end + + # Instantiates a new template class based on the file. + # + # @raise [RuntimeError] if there is no template class registered for the + # file name. + # + # @example + # mapping.new('index.mt') # => instance of MyEngine::Template + # + # @see Tilt::Template.new + def new(file, line=nil, options={}, &block) + if template_class = self[file] + template_class.new(file, line, options, &block) + else + fail "No template engine registered for #{File.basename(file)}" + end + end + + # Looks up a template class based on file name and/or extension. + # + # @example + # mapping['views/hello.erb'] # => Tilt::ERBTemplate + # mapping['hello.erb'] # => Tilt::ERBTemplate + # mapping['erb'] # => Tilt::ERBTemplate + # + # @return [template class] + def [](file) + _, ext = split(file) + ext && lookup(ext) + end + + alias template_for [] + + # Looks up a list of template classes based on file name. If the file name + # has multiple extensions, it will return all template classes matching the + # extensions from the end. + # + # @example + # mapping.templates_for('views/index.haml.erb') + # # => [Tilt::ERBTemplate, Tilt::HamlTemplate] + # + # @return [Array